diff --git a/package.json b/package.json index dfad6ad3..0d6c4c32 100644 --- a/package.json +++ b/package.json @@ -83,9 +83,9 @@ } ], "build": { - "electronVersion": "15.3.1", + "electronVersion": "15.3.3", "electronDownload": { - "version": "15.3.1-wvvmp", + "version": "15.3.3-wvvmp", "mirror": "https://github.com/castlabs/electron-releases/releases/download/v" }, "appId": "cider", diff --git a/resources/cider-ui-tests/apple-hls.js b/resources/cider-ui-tests/apple-hls.js new file mode 100644 index 00000000..abb18dab --- /dev/null +++ b/resources/cider-ui-tests/apple-hls.js @@ -0,0 +1,31028 @@ +/*! For license information please see hls.js.LICENSE.txt */ +!function Ky(Hy) { + const jy = this; + var e, t; + e = this, + t = function() { + "use strict"; + var P, e = e=>e && e.Math === Math && e, d = e("object" == typeof globalThis && globalThis) || e("object" == typeof window && window) || e("object" == typeof jy && jy) || e("object" == typeof global && global) || Function("return this")(); + class l { + constructor() { + this.keySize = null, + this.ksRows = null, + this.keySchedule = null, + this.invKeySchedule = null, + 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.initTable() + } + uint8ArrayToUint32Array_(e) { + const t = new DataView(e) + , i = Math.floor(t.byteLength / 4) + , r = new Uint32Array(i); + for (let e = 0; e < i; e++) + r[e] = t.getUint32(4 * e); + return r + } + initTable() { + const e = this["sBox"] + , t = this["invSBox"] + , i = this["subMix"] + , r = i[0] + , n = i[1] + , s = i[2] + , a = i[3] + , o = this["invSubMix"] + , d = o[0] + , l = o[1] + , u = o[2] + , c = o[3] + , h = new Uint32Array(256); + let p = 0 + , f = 0 + , m = 0; + for (m = 0; m < 256; m++) + h[m] = m < 128 ? m << 1 : m << 1 ^ 283; + for (m = 0; m < 256; m++) { + var g = (g = f ^ f << 1 ^ f << 2 ^ f << 3 ^ f << 4) >>> 8 ^ 255 & g ^ 99; + e[p] = g, + t[g] = p; + const o = h[p] + , m = h[o] + , v = h[m]; + var y = 257 * h[g] ^ 16843008 * g; + r[p] = y << 24 | y >>> 8, + n[p] = y << 16 | y >>> 16, + s[p] = y << 8 | y >>> 24, + a[p] = y, + y = 16843009 * v ^ 65537 * m ^ 257 * o ^ 16843008 * p, + d[g] = y << 24 | y >>> 8, + l[g] = y << 16 | y >>> 16, + u[g] = y << 8 | y >>> 24, + c[g] = y, + p ? (p = o ^ h[h[h[v ^ o]]], + f ^= h[h[f]]) : p = f = 1 + } + } + expandKey(e) { + var n = this.uint8ArrayToUint32Array_(e); + let t = !0 + , i = 0; + for (; i < n.length && t; ) + t = n[i] === this.key[i], + i++; + if (!t) { + this.key = n; + var s = this.keySize = n.length; + if (4 !== s && 6 !== s && 8 !== s) + throw new Error("Invalid aes key size=" + s); + var a = this.ksRows = 4 * (s + 6 + 1); + let e, t; + const o = this.keySchedule = new Uint32Array(a) + , d = this.invKeySchedule = new Uint32Array(a) + , l = this.sBox + , u = this["rcon"] + , c = this["invSubMix"] + , h = c[0] + , p = c[1] + , f = c[2] + , m = c[3]; + let i, r; + for (e = 0; e < a; e++) + e < s ? i = o[e] = n[e] : (r = i, + e % s == 0 ? (r = r << 8 | r >>> 24, + r = l[r >>> 24] << 24 | l[r >>> 16 & 255] << 16 | l[r >>> 8 & 255] << 8 | l[255 & r], + r ^= u[e / s | 0] << 24) : 6 < s && e % s == 4 && (r = l[r >>> 24] << 24 | l[r >>> 16 & 255] << 16 | l[r >>> 8 & 255] << 8 | l[255 & r]), + o[e] = i = (o[e - s] ^ r) >>> 0); + for (t = 0; t < a; t++) + e = a - t, + r = 3 & t ? o[e] : o[e - 4], + d[t] = t < 4 || e <= 4 ? r : h[l[r >>> 24]] ^ p[l[r >>> 16 & 255]] ^ f[l[r >>> 8 & 255]] ^ m[l[255 & r]], + d[t] = d[t] >>> 0 + } + } + networkToHostOrderSwap(e) { + return e << 24 | (65280 & e) << 8 | (16711680 & e) >> 8 | e >>> 24 + } + decrypt(e, t, i) { + var r = this.keySize + 6 + , n = this["invKeySchedule"] + , s = this.invSBox + , a = this["invSubMix"] + , o = a[0] + , d = a[1] + , l = a[2] + , u = a[3] + , i = this.uint8ArrayToUint32Array_(i); + let c = i[0] + , h = i[1] + , p = i[2] + , f = i[3]; + const m = new Int32Array(e) + , g = new Int32Array(m.length); + let y, v, S, b, T, E, I, w, A, O, k, C, D, M; + const P = this.networkToHostOrderSwap; + for (; t < m.length; ) { + for (A = P(m[t]), + O = P(m[t + 1]), + k = P(m[t + 2]), + C = P(m[t + 3]), + T = A ^ n[0], + E = C ^ n[1], + I = k ^ n[2], + w = O ^ n[3], + D = 4, + M = 1; M < r; M++) + y = o[T >>> 24] ^ d[E >> 16 & 255] ^ l[I >> 8 & 255] ^ u[255 & w] ^ n[D], + v = o[E >>> 24] ^ d[I >> 16 & 255] ^ l[w >> 8 & 255] ^ u[255 & T] ^ n[D + 1], + S = o[I >>> 24] ^ d[w >> 16 & 255] ^ l[T >> 8 & 255] ^ u[255 & E] ^ n[D + 2], + b = o[w >>> 24] ^ d[T >> 16 & 255] ^ l[E >> 8 & 255] ^ u[255 & I] ^ n[D + 3], + T = y, + E = v, + I = S, + w = b, + D += 4; + y = s[T >>> 24] << 24 ^ s[E >> 16 & 255] << 16 ^ s[I >> 8 & 255] << 8 ^ s[255 & w] ^ n[D], + v = s[E >>> 24] << 24 ^ s[I >> 16 & 255] << 16 ^ s[w >> 8 & 255] << 8 ^ s[255 & T] ^ n[D + 1], + S = s[I >>> 24] << 24 ^ s[w >> 16 & 255] << 16 ^ s[T >> 8 & 255] << 8 ^ s[255 & E] ^ n[D + 2], + b = s[w >>> 24] << 24 ^ s[T >> 16 & 255] << 16 ^ s[E >> 8 & 255] << 8 ^ s[255 & I] ^ n[D + 3], + D += 3, + g[t] = P(y ^ c), + g[t + 1] = P(b ^ h), + g[t + 2] = P(S ^ p), + g[t + 3] = P(v ^ f), + c = A, + h = O, + p = k, + f = C, + t += 4 + } + return g.buffer + } + destroy() { + this.key = void 0, + this.keySize = void 0, + this.ksRows = void 0, + this.sBox = void 0, + this.invSBox = void 0, + this.subMix = void 0, + this.invSubMix = void 0, + this.keySchedule = void 0, + this.invKeySchedule = void 0, + this.rcon = void 0 + } + } + class i { + constructor(e, t) { + this.rpc = e, + this.logger = t, + this.decrypt = (r,n,s,a,o)=>t=>{ + const i = d.crypto; + if (null != o && o.useJSCrypto || null == i || !i.subtle) { + const s = new l; + var e; + s.expandKey(r); + const i = s.decrypt(a, 0, n); + e = o.plainTextLength ? i.slice(0, o.plainTextLength) : function(e) { + var t = new Uint8Array(e) + , i = t[e.byteLength - 1] + , r = e.byteLength - 1; + let n = 0; + if (1 <= i && i <= 16) + for (let e = r; e > r - i && t[e] === i; e--) + n++; + return e = n === i ? e.slice(0, r - i + 1) : e + }(i), + t(e, void 0, [e]) + } else + i.subtle.importKey("raw", r, s, !1, ["decrypt"]).then(e=>i.subtle.decrypt({ + name: s, + iv: n + }, e, a)).then(e=>{ + t(e, void 0, [e]) + } + ).catch(e=>t(void 0, e)) + } + , + e.register("decrypt", this.decrypt) + } + } + (gr = P = P || {}).MEDIA_ATTACHING = "hlsMediaAttaching", + gr.MEDIA_ATTACHED = "hlsMediaAttached", + gr.MEDIA_DETACHING = "hlsMediaDetaching", + gr.MEDIA_DETACHED = "hlsMediaDetached", + gr.BUFFER_CREATED = "hlsBufferCreated", + gr.BUFFER_APPENDING = "hlsBufferAppending", + gr.BUFFER_APPENDED = "hlsBufferAppended", + gr.BUFFER_FLUSHED = "hlsBufferFlushed", + gr.MANIFEST_LOADING = "hlsManifestLoading", + gr.MANIFEST_LOADED = "hlsManifestLoaded", + gr.MANIFEST_PARSED = "hlsManifestParsed", + gr.LEVEL_SWITCHING = "hlsLevelSwitching", + gr.LEVEL_SWITCHED = "hlsLevelSwitched", + gr.LEVEL_LOADING = "hlsLevelLoading", + gr.LEVEL_LOADED = "hlsLevelLoaded", + gr.LEVEL_UPDATED = "hlsLevelUpdated", + gr.LEVELS_CHANGED = "hlsLevelsChanged", + gr.AUDIO_TRACKS_UPDATED = "hlsAudioTracksUpdated", + gr.AUDIO_TRACK_SWITCH = "hlsAudioTrackSwitch", + gr.AUDIO_TRACK_SWITCHED = "hlsAudioTrackSwitched", + gr.AUDIO_TRACK_LOADED = "hlsAudioTrackLoaded", + gr.SUBTITLE_TRACKS_UPDATED = "hlsSubtitleTracksUpdated", + gr.SUBTITLE_TRACKS_CREATED = "hlsSubtitleTracksCreated", + gr.SUBTITLE_TRACK_SWITCH = "hlsSubtitleTrackSwitch", + gr.INLINE_STYLES_PARSED = "hlsInlineStylesParsed", + gr.SESSION_DATA_COMPLETE = "hlsSessionDataComplete", + gr.FRAG_LOADING = "hlsFragLoading", + gr.FRAG_LOADED = "hlsFragLoaded", + gr.FRAG_BUFFERED = "hlsFragBuffered", + gr.FRAG_CHANGED = "hlsFragChanged", + gr.INTERNAL_ERROR = "hlsInternalError", + gr.ERROR = "hlsError", + gr.DESTROYING = "hlsDestroying", + gr.KEY_REQUEST_STARTED = "hlsKeyRequestStarted", + gr.LICENSE_CHALLENGE_CREATED = "hlsLicenseChallengeCreated", + gr.LICENSE_RELEASED = "hlsLicenseReleased", + gr.KEY_LOADED = "hlsKeyLoaded", + gr.UNRESOLVED_URI_LOADING = "hlsUnresolvedUriLoading", + gr.DESIRED_RATE_CHANGED = "hlsDesiredRateChanged", + gr.PLAYER_STATE_CHANGE = "hlsPlayerStateChange", + gr.SEEKING = "hlsSeeking", + gr.SEEKED = "hlsSeeked", + gr.STALLED = "hlsStalled", + gr.RESUME_FROM_STALL = "hlsResumeFromStall", + gr.READY_FOR_NEXT_ITEM = "hlsReadyForNextItem", + gr.ITEM_TRANSITIONED = "hlsItemTransitioned", + gr.ITEM_EVICTED = "hlsItemEvicted", + gr.DATERANGE_UPDATED = "hlsDaterangeUpdated"; + var v, x = P; + (dd = v = v || {}).FRAG_PARSING_INIT_SEGMENT = "hlsFragParsingInitSegment", + dd.FRAG_PARSING_DATA = "hlsFragParsingData", + dd.FRAG_PARSED = "hlsFragParsed", + dd.INIT_PTS_FOUND = "hlsInitPtsFound"; + class p extends Error { + constructor(e, t, i, r, n) { + super(r), + this.type = e, + this.details = t, + this.fatal = i, + this.reason = r, + this.response = n, + this.handled = !1 + } + } + class R extends p { + constructor(e, t, i, r, n) { + super(e, t, i, r, n), + this.response = n + } + } + const $ = { + PlaylistNotReceived: { + code: -12884, + text: "Playlist not received" + }, + CryptResponseReceivedSlowly: { + code: -16833, + text: "Crypt key received slowly" + }, + LivePlaylistUpdateError: { + code: -12888, + text: "Live playlist not updated" + }, + NoResponseFromMediaRequest: { + code: -12889, + text: "No response for fragment" + }, + IncompatibleAsset: { + code: -12927, + text: "IncompatibleAsset" + }, + CorruptStream: { + code: -16041, + text: "Corrupt fragment" + }, + InternalError: { + code: -12645, + text: "InternalException" + }, + CantSwitchInTime: { + code: -12644, + text: "CantSwitchInTime" + }, + VideoDecoderBadDataErr: { + code: -12909, + text: "Buffer error" + }, + InsufficientDataAvailable: { + code: -12928, + text: "Incomplete data" + }, + AllocationFailed: { + code: -12862, + text: "AllocationFailed" + }, + PlaylistErrorMissingEXTM3U: { + code: -12269, + text: "Response doesnt have #EXTM3U tag" + }, + PlaylistErrorInvalidEntry: { + code: -12264, + text: "Invalid entry" + }, + PlaylistErrorBadTargetDuration: { + code: -12271, + text: "Invalid targetduration" + }, + NoValidAlternates: { + code: -12925, + text: "No valid alternates" + }, + FormatError: { + code: -12642, + text: "Incorrect playlist format" + }, + UnsupportedKeySystemError: { + code: -6e4, + text: "Unsupported Key System" + }, + EmptyLoadSourceError: { + code: -60001, + text: "Empty loadSource url" + }, + UndefinedItemIdError: { + code: -60002, + text: "Undefined itemId" + }, + ManifestParseError: { + code: -60003, + text: "Manifest parse error" + }, + DemuxWorkerError: { + code: -60004, + text: "Demux worker error" + }, + DecryptWorkerError: { + code: -60005, + text: "Decrypt worker error" + }, + OutOfRangeSeekError: { + code: -60006, + text: "Seeked out of playable range" + }, + ExceptionInKeyLoadError: { + code: -60007, + text: "Exception in Key load" + }, + FragmentAbortError: { + code: -60008, + text: "Fragment abort error" + }, + ManifestTimeoutError: { + code: -60009, + text: "Manifest Timeout Error" + }, + PlaylistTimeoutError: { + code: -60010, + text: "Playlist Timeout Error" + }, + FragmentTimeoutError: { + code: -60011, + text: "Fragment Timeout Error" + }, + IncompleteSessionData: { + code: -60012, + text: "Session data not complete after loading all items" + }, + SessionDataLoadTimeout: { + code: -60013, + text: "Session data load timeout" + }, + FailedDemuxerSanityCheck: { + code: -60014, + text: "Failed demuxer sanity check" + }, + InvalidADTSSamplingIndex: { + code: -60015, + text: "Invalid ADTS sampling index" + }, + DemuxerNotFound: { + code: -60016, + text: "No demux matching with content found" + }, + InvalidAC3Magic: { + code: -60029, + text: "Invalid ac-3 magic" + }, + InvalidInitTimestamp: { + code: -60017, + text: "Invalid initPTS or initDTS" + }, + NoAVSamplesFound: { + code: -60018, + text: "no audio/video samples found" + }, + NoTSSyncByteFound: { + code: -60019, + text: "TS packet did not start with 0x47" + }, + PESDidNotStartWithADTS: { + code: -60020, + text: "AAC PES did not start with ADTS header" + }, + NoADTSHeaderInPES: { + code: -60021, + text: "No ADTS header found in AAC PES" + }, + InvalidDolbyAudioMagic: { + code: -60022, + text: "Invalid dolby audio magic" + }, + FailedToAllocateVideoMdat: { + code: -60023, + text: "Fail allocating video mdat" + }, + FailedToAllocateAudioMdat: { + code: -60024, + text: "Fail allocating audio mdat" + }, + InsufficientEC3Data: { + code: -60025, + text: "Error parsing ec-3, not enough data" + }, + InvalidEC3Magic: { + code: -60026, + text: "Invalid ec-3 magic" + }, + ReservedStreamType: { + code: -60027, + text: "Reserved stream type" + }, + InsufficientAC3Data: { + code: -60028, + text: "error parsing ac-3, not enough data" + }, + InvalidAC3SamplingRateCode: { + code: -60030, + text: "Invalid ac-3 samplingRateCode" + }, + PlaylistErrorInvalidEXTXDEFINE: { + code: -61e3, + text: "Encountered undefined/not imported EXT-X-DEFINE property" + }, + PlaylistErrorMissingImportReference: { + code: -61001, + text: "IMPORT references variable not in master playlist and/or NAME" + }, + PlaylistErrorInvalidSERVERURI: { + code: -61002, + text: "Encountered undefined/invalid SERVER-URI attribute for EXT-X-CONTENT-STEERING tag" + }, + PlaylistErrorInvalidPATHWAYID: { + code: -61003, + text: "Encountered invalid PATHWAY-ID attribute for EXT-X-CONTENT-STEERING tag" + }, + PlaylistErrorInvalidSCORE: { + code: -61004, + text: "Encountered negative/non-number SCORE property" + }, + KeySystemFailedToUpdateSession: { + code: -62e3, + text: "KeySystem: Promise Rejected while updating session" + }, + KeySystemFailedToGenerateLicenseRenewal: { + code: -62001, + text: "KeySystem: Failed to generate license renewal" + }, + KeySystemFailedToGenerateLicenseRequest: { + code: -62002, + text: "KeySystem: Failed to generate license request" + }, + KeySystemAbort: { + code: -62003, + text: "KeySystem: Aborted" + }, + KeySystemUnexpectedStateTransition: { + code: -62004, + text: "KeySystem: Unexpected state transition" + }, + KeySystemUnexpectedState: { + code: -62005, + text: "KeySystem: Unexpected state" + }, + KeySystemCDMUnknownError: { + code: -62006, + text: "KeySystem: Unknown error from CDM" + }, + KeySystemRequestTimedOut: { + code: -62007, + text: "Key request timed out" + }, + KeySystemUnexpectedMETHOD: { + code: -62008, + text: "Unexpected METHOD attribute" + }, + KeySystemUnmatchedString: { + code: -62009, + text: "KeySystem: string does not match" + }, + KeySystemInternalError: { + code: -62010, + text: "KeySystem: internal-error" + }, + KeySystemOutputRestricted: { + code: -62011, + text: "KeySystem: output-restricted" + }, + KeySystemSetupError: { + code: -62012, + text: "KeySystem: setup error" + }, + KeySystemFailedToInitialize: { + code: -62013, + text: "KeySystem: could not initialize" + }, + KeySystemFailedToCreateSession: { + code: -62014, + text: "KeySystem: could not create session" + }, + KeySystemUndefinedNavigator: { + code: -62015, + text: "KeySystem: navigator undefined" + }, + KeySystemNoKeySystemsToTry: { + code: -62016, + text: "KeySystem: no key systems to try" + }, + KeySystemNoConstructor: { + code: -62017, + text: "KeySystem: No constructor" + }, + KeySystemNoKeySystemAccess: { + code: -62018, + text: "KeySystem: No KeySystemAccess" + }, + KeySystemCertificateLoadError: { + code: -62019, + text: "KeySystem: Certificate Load Error" + } + } + , o = "networkError" + , L = "mediaError" + , s = "otherError" + , _ = "manifestParsingError" + , f = "manifestIncompatibleCodecsError" + , N = "levelLoadError" + , n = "bufferAppendError" + , r = "internalException"; + class V extends p { + constructor(e, t, i) { + super(s, r, e, t, i) + } + } + class D extends p { + constructor(e, t, i) { + super(L, "fragParsingError", e, t, i) + } + } + class F extends p { + constructor(e, t, i, r) { + super("muxError", "remuxAllocError", e, t, i), + this.bytes = r + } + } + function S(e) { + return e.baseTime / e.timescale + } + function B(e, t) { + return { + baseTime: Math.floor(e * t), + timescale: t + } + } + function g(e, t) { + return S(e) < S(t) ? e : t + } + function y(e, t) { + return S(e) > S(t) ? e : t + } + function b(e, t) { + return S(e) - S(t) + } + var t = void 0 !== d.Buffer ? require("events").EventEmitter : class { + constructor() { + this.eventMap = {} + } + _on(e, t, i=!1) { + return null == this.eventMap[e] && (this.eventMap[e] = []), + i ? this.eventMap[e].splice(0, 0, t) : this.eventMap[e].push(t), + this + } + _off(e, t) { + return null != this.eventMap[e] && (this.eventMap[e] = this.eventMap[e].filter(e=>e.listener !== t.listener), + 0 === this.eventMap[e].length && delete this.eventMap[e]), + this + } + on(e, t) { + return this._on(e, { + listener: t, + once: !1 + }) + } + off(e, t) { + return this._off(e, { + listener: t + }) + } + addListener(e, t) { + return this.on(e, t) + } + once(e, t) { + return this._on(e, { + listener: t, + once: !0 + }) + } + removeListener(e, t) { + return this.off(e, t) + } + removeAllListeners(e) { + return delete this.eventMap[e], + this + } + setMaxListeners(e) { + return this + } + getMaxListeners() { + return 1 / 0 + } + listeners(e) { + return null == this.eventMap[e] ? [] : this.eventMap[e].map(e=>e.listener) + } + rawListeners(e) { + return this.listeners(e) + } + emit(e, ...t) { + if (null == this.eventMap[e]) + return !1; + let i = !1; + for (const r of this.eventMap[e]) { + try { + r.listener.apply(this, t) + } catch (e) {} + i = !0 + } + return i + } + listenerCount(e) { + return null == this.eventMap[e] ? 0 : this.eventMap[e].length + } + prependListener(e, t) { + return this._on(e, { + listener: t, + once: !1 + }, !0) + } + prependOnceListener(e, t) { + return this._on(e, { + listener: t, + once: !0 + }, !0) + } + eventNames() { + return Object.keys(this.eventMap) + } + } + ; + class a extends t { + trigger(e, t) { + this.emit(e, t) + } + } + function E(e, t, i, r, n) { + let s, a, o, d; + const l = navigator.userAgent.toLowerCase() + , u = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350]; + s = 1 + ((192 & t[i + 2]) >>> 6); + var c = (60 & t[i + 2]) >>> 2; + if (!(u.length - 1 < c)) + return o = (1 & t[i + 2]) << 2, + o |= (192 & t[i + 3]) >>> 6, + /firefox/i.test(l) ? 6 <= c ? (s = 5, + d = new Array(4), + a = c - 3) : (s = 2, + d = new Array(2)) : -1 !== l.indexOf("android") ? (s = 2, + d = new Array(2)) : (s = 5, + d = new Array(4), + a = r && (-1 !== r.indexOf("mp4a.40.29") || -1 !== r.indexOf("mp4a.40.5")) || !r && 6 <= c ? c - 3 : ((r && -1 !== r.indexOf("mp4a.40.2") || !r && 1 == o) && (s = 2, + d = new Array(2)), + c)), + d[0] = s << 3, + d[0] |= (14 & c) >> 1, + d[1] |= (1 & c) << 7, + d[1] |= o << 3, + 5 === s && (d[1] |= (14 & a) >> 1, + d[2] = (1 & a) << 7, + d[2] |= 8, + d[3] = 0), + { + esdsConfig: d, + samplerate: u[c], + channelCount: o, + segmentCodec: "aac", + codec: "mp4a.40." + s + }; + { + const t = new D(!0,`invalid ADTS sampling index:${c}`,$.InvalidADTSSamplingIndex); + e.trigger(x.INTERNAL_ERROR, t) + } + } + class u { + constructor(e, t, i, r, n) { + this.observer = e, + this.remuxer = t, + this.config = i, + this.typeSupported = r, + this.logger = n + } + static probe(e, t) { + throw new Error("Method not implemented") + } + resetTimeStamp(e) {} + resetInitSegment(e, t, i, r) {} + destroy() {} + } + class c extends u { + constructor(e, t, i, r, n) { + super(e, t, i, r, n), + this.observer = e, + this.remuxer = t, + this.config = i, + this.typeSupported = r, + this.logger = n, + this.esRemuxer = t + } + } + class h { + constructor(e, t, i) { + this.observer = e, + this.config = t, + this.logger = i + } + resetInitSegment() {} + resetTimeStamp(e) {} + destroy() {} + } + let m, I; + var w = { + strToUtf8array: e=>(m = m || new TextEncoder, + m.encode(e)), + utf8arrayToStr: e=>(I = I || new TextDecoder("utf-8"), + I.decode(e)) + } + , A = { + strToUtf8array(e) { + e = d.Buffer.from(e, "utf-8"); + return new Uint8Array(e.buffer,e.byteOffset,e.byteLength) + }, + utf8arrayToStr: e=>d.Buffer.from(e).toString("utf-8") + }; + let O = { + strToUtf8array(e) { + const t = unescape(encodeURIComponent(e)) + , i = new Uint8Array(t.length); + for (let e = 0; e < t.length; e++) + i[e] = t.charCodeAt(e); + return i + }, + utf8arrayToStr: e=>String.fromCharCode.apply(null, Array.from(e)) + }; + "undefined" != typeof TextEncoder && "undefined" != typeof TextDecoder ? O = w : "function" == typeof (null === (pd = d.Buffer) || void 0 === pd ? void 0 : pd.from) && (O = A); + const k = { + name: "ID3" + }; + class C { + constructor(e, t) { + this.logger = t, + this._hasTimeStamp = !1, + this._audioType = null, + this._length = 0, + this._frames = []; + let i, r, n, s, a = 0; + for (; ; ) + if (n = C.readUTF(e, a, 3), + a += 3, + "ID3" === n) { + this._minor = e[a++], + this._revision = e[a++]; + const t = e[a++]; + if (128 & t && (this._unsynchronized = !0, + this.logger.error(k, "id3 tag is unsynchronized")), + 64 & t && (this._hasExtendedHeader = !0, + this.logger.warn(k, "id3 tag has extended header")), + i = C.readSynchSafeUint32(e.subarray(a, a + 4)), + a += 4, + r = a + i, + this._hasExtendedHeader) { + const t = C.readSynchSafeUint32(e.subarray(a, a + 4)); + this.logger.warn(k, `id3 tag has ${t}-byte extended header. usually 6 or 10 bytes`), + a += t + } + 2 < this.minor ? this._parseID3Frames(e, a, r) : this.logger.error(k, "[id3] doesn't support older than v2.3 tags"), + a = r + } else { + if ("3DI" !== n) + return a -= 3, + void ((s = a) && (this.hasTimeStamp || this.logger.warn(k, "ID3 tag found, but no timestamp"), + this._length = s, + this._payload = e.slice(0, s))); + a += 7 + } + } + static isHeader(e, t) { + return 73 === e[t] && 68 === e[t + 1] && 51 === e[t + 2] && e[t + 3] < 255 && e[t + 4] < 255 && e[t + 6] < 128 && e[t + 7] < 128 && e[t + 8] < 128 && e[t + 9] < 128 + } + static readSynchSafeUint32(e) { + return 2097152 * (127 & e[0]) + 16384 * (127 & e[1]) + 128 * (127 & e[2]) + (127 & e[3]) + } + static readUTF(e, t, i) { + let r = "" + , n = t; + for (var s = t + i; r += String.fromCharCode(e[n++]), + n < s; ) + ; + return r + } + isID3Frame(e, t) { + return e[t + 4] < 128 && e[t + 5] < 128 && e[t + 6] < 128 && e[t + 7] < 128 + } + decodeID3Frame(e) { + return "TXXX" === e.type ? this.decodeTxxxFrame(e) : "WXXX" === e.type ? this.decodeWxxxFrame(e) : "PRIV" === e.type ? this.decodePrivFrame(e) : "T" === e.type[0] ? this.decodeTextFrame(e) : { + key: e.type, + data: e.data + } + } + decodeTxxxFrame(e) { + if (!(e.size < 2) && 3 === e.data[0]) { + var t = 1 + , i = this.id3utf8ArrayToStr(e.data.subarray(1)); + return t += i.length + 1, + { + key: "TXXX", + description: i, + data: this.id3utf8ArrayToStr(e.data.subarray(t)) + } + } + } + decodeWxxxFrame(e) { + if (!(e.size < 2) && 3 === e.data[0]) { + var t = 1 + , i = this.id3utf8ArrayToStr(e.data.subarray(1)); + return t += i.length + 1, + { + key: "WXXX", + description: i, + data: O.utf8arrayToStr(e.data.subarray(t)) + } + } + } + decodeTextFrame(e) { + if (!(e.size < 2) && 3 === e.data[0]) { + var t = e.data.subarray(1); + return { + key: e.type, + data: this.id3utf8ArrayToStr(t) + } + } + } + decodePrivFrame(e) { + if (!(e.size < 2)) { + var t = this.id3utf8ArrayToStr(e.data); + return { + key: "PRIV", + info: t, + data: e.data.slice(t.length + 1) + } + } + } + _extractID3Frame(e, t, i, r, n) { + var s = r + i; + let a; + return s <= n ? a = { + type: t, + data: e.slice(r, s) + } : this.logger.error(k, `id3 frame ${t} size ${i} exceeded ${n}`), + a + } + _parseID3Frames(e, t, i) { + let r, n, s, a; + for (; t + 8 <= i; ) { + if (!this.isID3Frame(e, t)) + return void this.logger.error(k, `[id3] illegal id3 frame @ offset ${t}. skip this id3 tag`); + if (r = C.readUTF(e, t, 4), + t += 4, + "" === r) + return; + if (0 === (n = C.readSynchSafeUint32(e.subarray(t, t + 4)))) + return; + t += 4, + e[t++], + e[t++], + s = t; + var o = this._extractID3Frame(e, r, n, s, i); + if (o) { + const e = this.decodeID3Frame(o); + this._frames.push(e) + } + if ("PRIV" === r) + if (53 === n && "com.apple.streaming.transportStreamTimestamp" === C.readUTF(e, t, 44)) { + t += 44, + t += 4; + const i = 1 & e[t++]; + this._hasTimeStamp = !0, + a = ((e[t++] << 23) + (e[t++] << 15) + (e[t++] << 7) + e[t++]) / 45, + i && (a += 47721858.84), + a = Math.round(a), + this._timeStamp = a + } else + 45 <= n && "com.apple.streaming.audioDescription" === C.readUTF(e, t, 36) ? (t += 37, + this._audioType = C.readUTF(e, t, 4), + t += 4, + t += n - 41) : t += n; + else + t += n + } + } + id3utf8ArrayToStr(e) { + let t, i, r = "", n = 0; + const s = e.length; + for (; n < s; ) { + const s = e[n++]; + switch (s >> 4) { + case 0: + return r; + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + r += String.fromCharCode(s); + break; + case 12: + case 13: + t = e[n++], + r += String.fromCharCode((31 & s) << 6 | 63 & t); + break; + case 14: + t = e[n++], + i = e[n++], + r += String.fromCharCode((15 & s) << 12 | (63 & t) << 6 | (63 & i) << 0) + } + } + } + get hasTimeStamp() { + return this._hasTimeStamp + } + get timeStamp() { + return this._timeStamp + } + get audioType() { + return this._audioType + } + get length() { + return this._length + } + get payload() { + return this._payload + } + get frames() { + return this._frames + } + get minor() { + return this._minor + } + get revision() { + return this._revision + } + } + var M = C; + const U = { + name: "AACDemuxer" + }; + class K extends c { + resetInitSegment(e, t) { + this.audioConfig = void 0, + this.audioTrack = void 0, + this.duration = t + } + static probe(e, t) { + let i, r; + for (i = new M(e,t).length, + r = Math.min(e.length - 1, i + 100); i < r; i++) + if (255 === e[i] && 240 == (246 & e[i + 1])) + return !0; + return !1 + } + append(e, t, i, r, n) { + var s = new M(e,this.logger) + , a = s.hasTimeStamp ? 90 * s.timeStamp : 9e4 * t; + let o, d, l, u, c, h, p, f, m, g; + for (s.length && (g = s.payload, + s.frames.length && (m = s.frames), + f = { + id3Samples: [{ + pts: a, + dts: a, + data: g, + frames: m + }], + inputTimescale: 9e4 + }), + l = s.length, + h = e.length; l < h - 1 && (255 !== e[l] || 240 != (246 & e[l + 1])); l++) + ; + if (!this.audioConfig && (this.audioConfig = E(this.observer, e, l, void 0, this.logger), + !this.audioConfig)) + throw "failed to parse adts config"; + if (!this.audioTrack) { + const e = { + id: 258, + inputTimescale: 9e4, + timescale: NaN, + duration: this.duration, + encrypted: !1, + keyTagInfo: n + } + , t = { + len: 0, + sequenceNumber: 0, + esSamples: [] + }; + this.audioTrack = { + info: e, + parsingData: t, + type: "audio", + config: this.audioConfig + } + } + "zaac" !== s.audioType && "zach" !== s.audioType && "zacp" !== s.audioType || (this.audioTrack.info.encrypted = !0), + d = 0; + for (var y = 9216e4 / this.audioConfig.samplerate; l + 5 < h && (u = 1 & e[l + 1] ? 7 : 9, + o = (3 & e[l + 3]) << 11 | e[l + 4] << 3 | (224 & e[l + 5]) >>> 5, + o -= u, + 0 < o && l + u + o <= h); ) + for (c = a + d * y, + p = { + unit: e.subarray(l + u, l + u + o), + pts: c, + dts: c, + keyTagInfo: n + }, + this.audioTrack.parsingData.esSamples.push(p), + this.audioTrack.parsingData.len += o, + l += o + u, + d++; l < h - 1; l++) { + if (M.isHeader(e, l)) { + const t = new M(e.subarray(l),this.logger); + if (0 < t.length) { + l += t.length; + const e = t.hasTimeStamp ? 90 * t.timeStamp : a; + f.id3Samples.push({ + pts: e, + dts: e, + data: t.payload, + frames: t.frames + }) + } else + this.logger.error(U, `[id3] invalid length ${h}`) + } + if (255 === e[l] && 240 == (246 & e[l + 1])) + break + } + this.esRemuxer.remuxEsTracks(this.audioTrack, void 0, f, void 0, t, i, r, n) + } + } + class H { + bsReadAndUpdate(e, t, i) { + e = this.readBits(e, t, i); + return this.updateOffset(t, i), + e + } + bsWriteAndUpdate(e, t, i, r) { + r = this.writeBits(e, t, i, r); + return this.updateOffset(t, i), + r + } + bsSkip(e, t) { + this.updateOffset(e, t) + } + readBits(i, r, n) { + if (i && r) { + let t = r.byteOffset; + const s = r["usedBits"]; + if (!(8 <= s || 32 < s + n)) { + let e; + const a = new Uint32Array(1) + , o = new Uint32Array(1) + , d = new Uint8Array(1); + if (!(8 <= s || 32 < n)) { + if (s) { + const r = 8 - s + , a = n < r ? r - n : 0; + o[0] = 4278190080 >>> 32 - r, + e = (i[t] & o[0]) >>> a, + t += 1, + n -= r + } + for (; 0 < n; ) { + d[0] = i[t]; + const r = Math.min(n, 8) + , s = 8 - r; + o[0] = 4278190080 >>> 24 + s << s, + a[0] = (d[0] & o[0]) >> s, + e = e ? e << r | a[0] : a[0], + t += 1, + n -= r + } + return e + } + } + } + } + writeBits(t, i, r, n) { + if (t && i) { + let e = i.byteOffset; + var i = i["usedBits"]; + if (!(8 <= i || 32 < i + r)) { + const s = new Uint32Array(1) + , a = new Uint32Array(1) + , o = new Uint32Array(1) + , d = new Uint8Array(1); + for (s[0] = n, + i && (a[0] = s[0] << 32 - r, + o[0] = 4278190080, + d[0] = (a[0] & o[0]) >>> 24 + i, + t[e] &= ~(o[0] >>> 24 + i), + t[e] |= d[0], + e += 1, + r -= 8 - i); 0 < r; ) { + a[0] = s[0] << 32 - r, + o[0] = 4278190080, + d[0] = (a[0] & o[0]) >>> 24; + const l = r < 0 ? 8 - r : 0; + t[e] &= ~(o[0] >>> 24 >>> l << l), + t[e] |= d[0], + r -= 8, + e += 1 + } + return 0 + } + } + } + updateOffset(e, t) { + var i, r; + !e || !t || 32 < e.usedBits + t || (i = e.usedBits % 8, + r = Math.floor((i + t) / 8), + t = (i + t) % 8, + e.byteOffset += r, + e.usedBits = t) + } + } + function j(e, t) { + return 1536 / e.samplerate * t + } + function q(e, t, i, r) { + let n; + if (i + 8 > t.length) + return n = new D(!0,"error parsing ac-3, not enough data",$.InsufficientAC3Data), + void e.trigger(x.INTERNAL_ERROR, n); + if (11 !== t[i] || 119 !== t[i + 1]) + return n = new D(!0,"invalid ac-3 magic",$.InvalidAC3Magic), + void e.trigger(x.INTERNAL_ERROR, n); + var s = t[i + 4] >> 6; + if (3 <= s) + return n = new D(!0,`invalid ac-3 samplingRateCode:${s}`,$.InvalidAC3SamplingRateCode), + void e.trigger(x.INTERNAL_ERROR, n); + var a = 63 & t[i + 4] + , o = t[i + 6] >> 5; + let d = 0; + 2 == o ? d += 2 : (1 & o && 1 != o && (d += 2), + 4 & o && (d += 2)); + var l = (t[i + 6] << 8 | t[i + 7]) >> 12 - d & 1 + , u = [2, 1, 2, 3, 3, 4, 4, 5][o] + l + , e = t[i + 5] >> 3 + , i = 7 & t[i + 5]; + return { + samplerate: G[s], + channelCount: u, + segmentCodec: "ac3", + codec: "ac-3", + extraData: s << 22 | e << 17 | i << 14 | o << 11 | l << 10 | a >> 1 << 5 + } + } + function Q(e, t, i) { + let r; + if (i + 8 > t.length) + return r = new D(!0,"error parsing ac-3, not enough data",$.InsufficientAC3Data), + void e.trigger(x.INTERNAL_ERROR, r); + if (11 !== t[i] || 119 !== t[i + 1]) + return r = new D(!0,"invalid ac-3 magic",$.InvalidAC3Magic), + void e.trigger(x.INTERNAL_ERROR, r); + var n = t[i + 4] >> 6; + return 3 <= n ? (r = new D(!0,`invalid ac-3 samplingRateCode:${n}`,$.InvalidAC3SamplingRateCode), + void e.trigger(x.INTERNAL_ERROR, r)) : (i = 63 & t[i + 4], + 2 * W[3 * i + n]) + } + const G = [48e3, 44100, 32e3] + , W = [64, 69, 96, 64, 70, 96, 80, 87, 120, 80, 88, 120, 96, 104, 144, 96, 105, 144, 112, 121, 168, 112, 122, 168, 128, 139, 192, 128, 140, 192, 160, 174, 240, 160, 175, 240, 192, 208, 288, 192, 209, 288, 224, 243, 336, 224, 244, 336, 256, 278, 384, 256, 279, 384, 320, 348, 480, 320, 349, 480, 384, 417, 576, 384, 418, 576, 448, 487, 672, 448, 488, 672, 512, 557, 768, 512, 558, 768, 640, 696, 960, 640, 697, 960, 768, 835, 1152, 768, 836, 1152, 896, 975, 1344, 896, 976, 1344, 1024, 1114, 1536, 1024, 1115, 1536, 1152, 1253, 1728, 1152, 1254, 1728, 1280, 1393, 1920, 1280, 1394, 1920]; + class z extends c { + resetInitSegment(e, t) { + this.audioConfig = void 0, + this.audioTrack = void 0, + this.duration = t + } + static probe(e, t) { + var i = new M(e,t) + , t = i.length; + return !!(i.hasTimeStamp && 11 === e[t] && 119 === e[t + 1] && (new H).bsReadAndUpdate(e, { + byteOffset: t + 5, + usedBits: 0 + }, 5) < 16) + } + append(e, t, i, r, n) { + var s = new M(e,this.logger) + , a = 90 * s.timeStamp + , o = e.byteLength; + let d = 0 + , l = s.length; + if (this.audioConfig || (this.audioConfig = q(this.observer, e, l, this.logger)), + !this.audioConfig) + throw "failed to parse ac3 config"; + if (!this.audioTrack) { + const e = { + id: 258, + inputTimescale: 9e4, + timescale: NaN, + duration: this.duration, + encrypted: !1, + keyTagInfo: n + } + , t = { + len: 0, + sequenceNumber: 0, + esSamples: [] + }; + this.audioTrack = { + info: e, + parsingData: t, + type: "audio", + config: this.audioConfig + } + } + var u = j(this.audioConfig, this.audioTrack.info.inputTimescale); + for ("zac3" === s.audioType && (this.audioTrack.info.encrypted = !0); l < o; ) { + if (M.isHeader(e, l) && (l += new M(e.subarray(l),this.logger).length), + 11 !== e[l] || 119 !== e[l + 1]) { + const e = new D(!0,"invalid ac-3 magic",$.InvalidAC3Magic); + return void this.observer.trigger(x.INTERNAL_ERROR, e) + } + const t = Q(this.observer, e, l) + , i = a + d * u + , r = { + unit: e.subarray(l, l + t), + pts: i, + dts: i, + keyTagInfo: n + }; + this.audioTrack.parsingData.esSamples.push(r), + this.audioTrack.parsingData.len += t, + l += t, + d++ + } + this.esRemuxer.remuxEsTracks(this.audioTrack, void 0, { + id3Samples: [{ + pts: a, + dts: a, + data: s.payload, + frames: s.frames + }], + inputTimescale: this.audioTrack.info.inputTimescale + }, void 0, t, i, r, n) + } + } + var X = function(t, i, r, n) { + const s = new H; + let a, o = !1, d = 0; + for (; r < i.length; ) { + if (r + 8 > i.length) + return a = new D(!0,"error parsing ec-3, not enough data",$.InsufficientEC3Data), + void t.trigger(x.INTERNAL_ERROR, a); + let e = 0; + if (M.isHeader(i, r) && (e = new M(i.subarray(r),n).length || 0, + r += e), + 11 !== i[r] || 119 !== i[r + 1]) + return a = new D(!0,"invalid ec-3 magic",$.InvalidEC3Magic), + void t.trigger(x.INTERNAL_ERROR, a); + var l = { + byteOffset: r + 2, + usedBits: 0 + } + , u = s.bsReadAndUpdate(i, l, 2) + , c = s.bsReadAndUpdate(i, l, 3); + if (0 === u || 2 === u) + if (!0 === o) { + if (0 === c) + break + } else + o = !0; + else if (1 !== u) + return a = new D(!0,"reserved stream type",$.ReservedStreamType), + void t.trigger(x.INTERNAL_ERROR, a); + l = 2 * (s.bsReadAndUpdate(i, l, 11) + 1); + r += l, + d += l + (e || 0) + } + return d + } + , Y = function(t, i, r, n) { + const s = { + frmsiz: 0, + fscod: 0, + numblkscod: 0, + acmod: 0, + lfeon: 0, + bsid: 0, + strmtyp: 0, + substreamid: 0, + chanmape: 0, + chanmap: 0, + mixdef: 0, + mixdeflen: 0, + bsmod: 0 + } + , a = { + fscod: 0, + acmod: 0, + lfeon: 0, + bsid: 0, + bsmod: 0, + chan_loc: 0, + data_rate: 0, + num_ind_sub: 0, + num_dep_sub: [], + complexity_index_type_a: 0 + } + , o = new H; + let d, l = !1, u = 0; + for (; r < i.length; ) { + if (r + 8 > i.length) + return d = new D(!0,"error parsing ec-3, not enough data",$.InsufficientEC3Data), + void t.trigger(x.INTERNAL_ERROR, d); + let e = 0; + if (M.isHeader(i, r) && (e = new M(i.subarray(r),n).length || 0, + r += e), + 11 !== i[r] || 119 !== i[r + 1]) + return d = new D(!0,"invalid ec-3 magic",$.InvalidEC3Magic), + void t.trigger(x.INTERNAL_ERROR, d); + const h = { + byteOffset: r + 2, + usedBits: 0 + }; + if (s.strmtyp = o.bsReadAndUpdate(i, h, 2), + s.substreamid = o.bsReadAndUpdate(i, h, 3), + 0 === s.strmtyp || 2 === s.strmtyp) { + if (!0 === l) { + if (0 === s.substreamid) + break + } else + l = !0; + a.num_ind_sub++, + a.num_dep_sub.push(0) + } else { + if (1 !== s.strmtyp) + return d = new D(!0,"reserved stream type",$.ReservedStreamType), + void t.trigger(x.INTERNAL_ERROR, d); + a.num_dep_sub[a.num_ind_sub - 1]++ + } + if (s.frmsiz = o.bsReadAndUpdate(i, h, 11), + s.fscod = o.bsReadAndUpdate(i, h, 2), + 3 === s.fscod ? (o.bsSkip(h, 2), + s.numblkscod = 3) : s.numblkscod = o.bsReadAndUpdate(i, h, 2), + s.acmod = o.bsReadAndUpdate(i, h, 3), + s.lfeon = o.bsReadAndUpdate(i, h, 1), + s.bsid = o.bsReadAndUpdate(i, h, 5), + o.bsSkip(h, 5), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 8), + 0 === s.acmod && (o.bsSkip(h, 5), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 8)), + 1 === s.strmtyp && (s.chanmape = o.bsReadAndUpdate(i, h, 1), + s.chanmape && (s.chanmap = o.bsReadAndUpdate(i, h, 16))), + o.bsReadAndUpdate(i, h, 1) && (2 < s.acmod && o.bsSkip(h, 2), + 1 & s.acmod && 2 < s.acmod && o.bsSkip(h, 6), + 4 & s.acmod && o.bsSkip(h, 6), + s.lfeon && o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 5), + 0 === s.strmtyp)) { + if (o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 6), + 0 === s.acmod && o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 6), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 6), + s.mixdef = o.bsReadAndUpdate(i, h, 2), + 1 === s.mixdef) + o.bsSkip(h, 5); + else if (2 === s.mixdef) + o.bsSkip(h, 12); + else if (3 === s.mixdef) { + s.mixdeflen = o.bsReadAndUpdate(i, h, 5), + o.bsReadAndUpdate(i, h, 1) && (o.bsSkip(h, 5), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), + o.bsReadAndUpdate(i, h, 1) && (o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 4))), + o.bsReadAndUpdate(i, h, 1) && (o.bsSkip(h, 5), + o.bsReadAndUpdate(i, h, 1) && (o.bsSkip(h, 7), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 8))); + const t = s.mixdeflen + 2 + (h.usedBits ? 1 : 0); + h.byteOffset += t + } + if (s.acmod < 2 && (o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 14), + 0 === s.acmod && o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 14)), + o.bsReadAndUpdate(i, h, 1)) + if (0 === s.numblkscod) + o.bsSkip(h, 5); + else + for (let e = 0; e < s.numblkscod; e++) + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 5) + } + if (s.bsmod = 0, + o.bsReadAndUpdate(i, h, 1) && (s.bsmod = o.bsReadAndUpdate(i, h, 3), + o.bsSkip(h, 2), + 2 === s.acmod && o.bsSkip(h, 4), + 6 <= s.acmod && o.bsSkip(h, 2), + o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 8), + 0 === s.acmod && o.bsReadAndUpdate(i, h, 1) && o.bsSkip(h, 8), + s.fscod < 3 && o.bsSkip(h, 1)), + 0 === s.strmtyp && 3 !== s.numblkscod && o.bsSkip(h, 1), + 2 !== s.strmtyp || (3 === s.numblkscod ? 1 : o.bsReadAndUpdate(i, h, 1)) && o.bsReadAndUpdate(i, h, 6), + o.bsReadAndUpdate(i, h, 1)) { + const t = o.bsReadAndUpdate(i, h, 6); + if (0 === s.strmtyp && 0 === s.substreamid && 1 === t) { + const t = o.bsReadAndUpdate(i, h, 7) + , r = o.bsReadAndUpdate(i, h, 1) + , n = o.bsReadAndUpdate(i, h, 8); + 0 === t && 1 === r && 1 <= n && n <= 16 && (a.complexity_index_type_a = n) + } + } + if (s.chanmape) + a.chan_loc |= s.chanmap; + else { + const t = [40960, 16384, 40960, 57344, 41472, 57856, 47104, 63488]; + a.chan_loc |= t[s.acmod] + } + 0 === s.strmtyp && (a.fscod = s.fscod, + a.bsid = s.bsid, + a.bsmod = s.bsmod, + a.acmod = s.acmod, + a.lfeon = s.lfeon), + a.chan_loc |= s.lfeon ? 1 : 0; + const p = 2 * (s.frmsiz + 1); + r += p, + u += p + (e || 0) + } + let c = 0; + for (let e = 0; e < 16; e++) + a.chan_loc & 1 << e && c++; + a.lfeon && c++; + let h = 10 + 3 * a.num_ind_sub; + const p = [48e3, 44100, 32e3][a.fscod]; + a.data_rate = p / 1536 * u * 8, + h = 10 + 3 * a.num_ind_sub; + for (let e = 0; e < a.num_ind_sub; e++) + 0 < a.num_dep_sub[e] && h++; + 0 < a.complexity_index_type_a && (h += 2); + var f = new Uint8Array(h) + , m = { + byteOffset: 0, + usedBits: 0 + }; + o.bsWriteAndUpdate(f, m, 32, h), + o.bsWriteAndUpdate(f, m, 32, 1684366131), + o.bsWriteAndUpdate(f, m, 13, a.data_rate), + o.bsWriteAndUpdate(f, m, 3, a.num_ind_sub); + for (let e = 0; e < a.num_ind_sub; e++) + o.bsWriteAndUpdate(f, m, 2, a.fscod), + o.bsWriteAndUpdate(f, m, 5, a.bsid), + o.bsWriteAndUpdate(f, m, 1, 0), + o.bsWriteAndUpdate(f, m, 1, 0 === e ? 0 : 1), + o.bsWriteAndUpdate(f, m, 3, a.bsmod), + o.bsWriteAndUpdate(f, m, 3, a.acmod), + o.bsWriteAndUpdate(f, m, 1, a.lfeon), + o.bsWriteAndUpdate(f, m, 3, 0), + o.bsWriteAndUpdate(f, m, 4, a.num_dep_sub[e]), + 0 < a.num_dep_sub[e] ? o.bsWriteAndUpdate(f, m, 9, a.chan_loc) : o.bsWriteAndUpdate(f, m, 1, 0); + return 0 < a.complexity_index_type_a && (o.bsWriteAndUpdate(f, m, 7, 0), + o.bsWriteAndUpdate(f, m, 1, 1), + o.bsWriteAndUpdate(f, m, 8, a.complexity_index_type_a)), + { + samplerate: p, + channelCount: c, + segmentCodec: "ec3", + codec: "ec-3", + extraDataBytes: f + } + }; + class J extends c { + resetInitSegment(e, t) { + this.audioConfig = void 0, + this.audioTrack = void 0, + this.duration = t + } + static probe(e, t) { + var i = new M(e,t) + , t = i.length; + return !(!i.hasTimeStamp || 11 !== e[t] || 119 !== e[t + 1] || 16 !== (new H).bsReadAndUpdate(e, { + byteOffset: t + 5, + usedBits: 0 + }, 5)) + } + append(e, t, i, r, n) { + var s = new M(e,this.logger) + , a = 90 * s.timeStamp + , o = e.length; + let d = 0 + , l = s.length; + if (this.audioConfig || (this.audioConfig = Y(this.observer, e, l, this.logger)), + !this.audioConfig) + throw "failed to parse ec-3 config"; + if (!this.audioTrack) { + const e = { + id: 258, + inputTimescale: 9e4, + timescale: NaN, + duration: this.duration, + encrypted: !1, + keyTagInfo: n + } + , t = { + len: 0, + sequenceNumber: 0, + esSamples: [] + }; + this.audioTrack = { + info: e, + parsingData: t, + type: "audio", + config: this.audioConfig + } + } + var u = j(this.audioConfig, this.audioTrack.info.inputTimescale); + for ("zec3" === s.audioType && (this.audioTrack.info.encrypted = !0); l < o; ) { + const t = X(this.observer, e, l, this.logger) + , i = a + d * u + , r = { + unit: e.subarray(l, l + t), + pts: i, + dts: i, + keyTagInfo: n + }; + this.audioTrack.parsingData.esSamples.push(r), + this.audioTrack.parsingData.len += t, + l += t, + d++ + } + this.esRemuxer.remuxEsTracks(this.audioTrack, void 0, { + id3Samples: [{ + pts: a, + dts: a, + data: s.payload, + frames: s.frames + }], + inputTimescale: this.audioTrack.info.inputTimescale + }, void 0, t, i, r, n) + } + } + const Z = { + BitratesMap: [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], + SamplingRateMap: [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3], + SamplesCoefficients: [[0, 72, 144, 12], [0, 0, 0, 0], [0, 72, 144, 12], [0, 144, 144, 12]], + BytesInSlot: [0, 1, 1, 4], + onFrame: function(e, t, i, r, n, s, a) { + r = a + s * (10368e4 / r); + e.esSamples.push({ + unit: t, + pts: r, + dts: r + }), + e.len += t.length + }, + onNoise: function(e, t) { + t.warn("mpeg audio has noise: " + e.length + " bytes") + }, + parseFrames: function(e, t, i, r, n, s, a) { + if (r < i + 2) + return -1; + if (255 === t[i] || 224 == (224 & t[i + 1])) { + if (r < i + 24) + return -1; + const a = t[i + 1] >> 3 & 3 + , c = t[i + 1] >> 1 & 3 + , h = t[i + 2] >> 4 & 15 + , p = t[i + 2] >> 2 & 3 + , f = !!(2 & t[i + 2]); + if (1 != a && 0 != h && 15 != h && 3 != p) { + var o = 1e3 * [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][14 * (3 == a ? 3 - c : 3 == c ? 3 : 4) + h - 1] + , d = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3][3 * (3 == a ? 0 : 2 == a ? 1 : 2) + p] + , l = f ? 1 : 0 + , u = t[i + 3] >> 6 == 3 ? 1 : 2 + , l = 3 == c ? (3 == a ? 12 : 6) * o / d + l << 2 : (3 == a ? 144 : 72) * o / d + l | 0; + return r < i + l ? -1 : (Z.onFrame(e, t.subarray(i, i + l), o, d, u, n, s), + l) + } + } + let c = i + 2; + for (; c < r; ) { + if (255 === t[c - 1] && 224 == (224 & t[c])) + return Z.onNoise(t.subarray(i, c - 1), a), + c - i - 1; + c++ + } + return -1 + }, + parse: function(e, t, i, r, n) { + var s = t.length; + let a, o = 0; + for (; i < s && 0 < (a = Z.parseFrames(e, t, i, s, o++, r, n)); ) + i += a + }, + getAudioConfig: function(e, t) { + var i = e[t + 1] >> 3 & 3 + , r = e[t + 1] >> 1 & 3 + , n = e[t + 2] >> 4 & 15 + , s = e[t + 2] >> 2 & 3 + , a = e[t + 2] >> 1 & 1; + if (1 != i && 0 != n && 15 != n && 3 != s) { + var o = 3 == i ? 3 - r : 3 == r ? 3 : 4 + , o = 1e3 * Z.BitratesMap[14 * o + n - 1] + , n = 3 == i ? 0 : 2 == i ? 1 : 2 + , s = Z.SamplingRateMap[3 * n + s] + , t = e[t + 3] >> 6 == 3 ? 1 : 2 + , i = Z.SamplesCoefficients[i][r] + , r = Z.BytesInSlot[r]; + return { + segmentCodec: "mp3", + codec: "mp3", + samplerate: s, + channelCount: t, + frameLength: parseInt(i * o / s + a, 10) * r + } + } + }, + isHeaderPattern: function(e, t) { + return 255 === e[t] && 224 == (224 & e[t + 1]) && 0 != (6 & e[t + 1]) + }, + probe: function(t, i) { + if (i + 1 < t.length && Z.isHeaderPattern(t, i)) { + var r = Z.getAudioConfig(t, i); + let e = 4; + r && r.frameLength && (e = r.frameLength); + i = i + e; + if (i === t.length || i + 1 < t.length && Z.isHeaderPattern(t, i)) + return !0 + } + return !1 + } + }; + var ee = Z; + const te = { + name: "MP3Demuxer" + }; + class ie extends c { + resetInitSegment(e, t) { + this.audioConfig = void 0, + this.audioTrack = void 0, + this.duration = t + } + static probe(e, t) { + var i = new M(e,t); + let r, n; + if (i.hasTimeStamp) + for (r = i.length, + n = Math.min(e.length - 1, r + 100); r < n; r++) + if (ee.probe(e, r)) + return t.warn(te, "MPEG Audio sync word found !"), + !0; + return !1 + } + append(e, t, i, r, n) { + var s = new M(e,this.logger) + , a = 90 * s.timeStamp; + if (this.audioConfig || (this.audioConfig = ee.getAudioConfig(e, s.length)), + !this.audioConfig) + throw "unable to parse mp3 header"; + if (!this.audioTrack) { + const e = { + id: 258, + inputTimescale: 9e4, + timescale: NaN, + duration: this.duration, + encrypted: !1, + keyTagInfo: n + } + , t = { + len: 0, + sequenceNumber: 0, + esSamples: [] + }; + this.audioTrack = { + info: e, + parsingData: t, + type: "audio", + config: this.audioConfig + } + } + ee.parse(this.audioTrack.parsingData, e, s.length, a, this.logger), + this.esRemuxer.remuxEsTracks(this.audioTrack, void 0, { + id3Samples: [{ + pts: a, + dts: a, + data: s.payload, + frames: s.frames + }], + inputTimescale: 9e4 + }, void 0, t, i, r) + } + } + function re(e, t) { + if ("mp4a.40.2" === e) { + if (1 === t) + return new Uint8Array([0, 200, 0, 128, 35, 128]); + if (2 === t) + return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]); + if (3 === t) + return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]); + if (4 === t) + return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]); + if (5 === t) + 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 (6 === t) + 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 (1 === t) + 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 (2 === t) + 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 (3 === t) + 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 + } + function ne(e) { + return "number" == typeof e && isFinite(e) + } + function se(e, i=3) { + return JSON.stringify(e, (e,t)=>!isNaN(t) && null != t && t.toFixed ? Number(null == t ? void 0 : t.toFixed(i)) : t) + } + let ae = !0; + function oe(e) { + return ae ? "" : e + } + function de(e) { + if (!e) + return e; + if ("object" != typeof e) + return e; + { + if (Array.isArray(e)) + return e.map(de); + const r = {}; + for (var [t,i] of Object.entries(e)) + r[t] = de(i); + return r + } + } + function le(e) { + const t = [...e]; + for (let e = 0; e < t.length; e++) + t[e] = Object.assign({}, t[e]), + t[e].url = oe(t[e].url), + t[e].attrs && (t[e].attrs = Object.assign({}, t[e].attrs), + t[e].attrs.URI = oe(t[e].attrs.URI)); + return t + } + function ue(e) { + const t = [...e]; + for (let e = 0; e < t.length; e++) + t[e] = Object.assign({}, t[e]), + t[e].url = oe(t[e].url); + return t + } + const ce = Math.pow(2, 32) - 1; + class he { + static init() { + let e; + for (e in he.types = { + avc1: [], + avcC: [], + btrt: [], + dinf: [], + dref: [], + esds: [], + free: [], + ftyp: [], + hdlr: [], + mdat: [], + mdhd: [], + mdia: [], + mfhd: [], + minf: [], + moof: [], + moov: [], + mp4a: [], + ".mp3": [], + dac3: [], + "ac-3": [], + dec3: [], + "ec-3": [], + mvex: [], + mvhd: [], + pasp: [], + sdtp: [], + stbl: [], + stco: [], + stsc: [], + stsd: [], + stsz: [], + stts: [], + tfdt: [], + tfhd: [], + traf: [], + trak: [], + trun: [], + trex: [], + tkhd: [], + vmhd: [], + smhd: [], + uuid: [], + encv: [], + enca: [], + frma: [], + schm: [], + schi: [], + senc: [], + saio: [], + saiz: [], + sinf: [], + tenc: [], + sbgp: [], + seig: [], + sgpd: [], + pssh: [] + }, + he.types) + he.types.hasOwnProperty(e) && (he.types[e] = [e.charCodeAt(0), e.charCodeAt(1), e.charCodeAt(2), e.charCodeAt(3)]); + var t = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 118, 105, 100, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 86, 105, 100, 101, 111, 72, 97, 110, 100, 108, 101, 114, 0]) + , i = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 115, 111, 117, 110, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 111, 117, 110, 100, 72, 97, 110, 100, 108, 101, 114, 0]); + he.HDLR_TYPES = { + video: t, + audio: i + }; + var r = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 12, 117, 114, 108, 32, 0, 0, 0, 1]) + , n = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]); + he.STTS = he.STSC = he.STCO = n, + he.STSZ = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), + he.VMHD = new Uint8Array([0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]), + he.SMHD = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]), + he.STSD = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1]); + t = new Uint8Array([105, 115, 111, 109]), + i = new Uint8Array([97, 118, 99, 49]), + n = new Uint8Array([0, 0, 0, 1]); + he.FTYP = he.box(he.types.ftyp, t, n, t, i), + he.DINF = he.box(he.types.dinf, he.box(he.types.dref, r)) + } + static set16(e, t, i) { + return t[i] = e >> 8 & 255, + t[i + 1] = 255 & e, + i + 2 + } + static set32(e, t, i) { + return t[i] = e >> 24 & 255, + t[i + 1] = e >> 16 & 255, + t[i + 2] = e >> 8 & 255, + t[i + 3] = 255 & e, + i + 4 + } + static box(e) { + var t = Array.prototype.slice.call(arguments, 1); + let i = 8 + , r = t.length; + for (var n = r; r--; ) + i += t[r].byteLength; + const s = new Uint8Array(i); + for (s[0] = i >> 24 & 255, + s[1] = i >> 16 & 255, + s[2] = i >> 8 & 255, + s[3] = 255 & i, + s.set(e, 4), + r = 0, + i = 8; r < n; r++) + s.set(t[r], i), + i += t[r].byteLength; + return s + } + static hdlr(e) { + return he.box(he.types.hdlr, he.HDLR_TYPES[e]) + } + static mdat(e) { + return he.box(he.types.mdat, e) + } + static mdhd(e, t) { + t *= e; + var i = Math.floor(t / (1 + ce)) + , t = Math.floor(t % (1 + ce)); + return he.box(he.types.mdhd, new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, e >> 24 & 255, e >> 16 & 255, e >> 8 & 255, 255 & e, i >> 24, i >> 16 & 255, i >> 8 & 255, 255 & i, t >> 24, t >> 16 & 255, t >> 8 & 255, 255 & t, 85, 196, 0, 0])) + } + static mdia(e) { + var t = he.mdhd(e.info.timescale, e.info.duration) + , i = he.hdlr(e.type) + , e = he.minf(e); + return he.box(he.types.mdia, t, i, e) + } + static mfhd(e) { + return he.box(he.types.mfhd, new Uint8Array([0, 0, 0, 0, e >> 24, e >> 16 & 255, e >> 8 & 255, 255 & e])) + } + static minf(e) { + return "audio" === e.type ? he.box(he.types.minf, he.box(he.types.smhd, he.SMHD), he.DINF, he.stbl(e)) : he.box(he.types.minf, he.box(he.types.vmhd, he.VMHD), he.DINF, he.stbl(e)) + } + static moof(e, t) { + he.types || he.init(); + e = he.traf(t, e); + return he.box(he.types.moof, he.mfhd(t.sequenceNumber), e) + } + static moov(e) { + let t = e.length; + const i = []; + for (; t--; ) + i[t] = he.trak(e[t]); + return he.box.apply(null, [he.types.moov, he.mvhd(e[0].info.timescale, e[0].info.duration)].concat(i).concat(he.mvex(e))) + } + static mvex(e) { + let t = e.length; + const i = []; + for (; t--; ) + i[t] = he.trex(e[t]); + return he.box(he.types.mvex, ...i) + } + static mvhd(e, t) { + t *= e; + var i = Math.floor(t / (1 + ce)) + , t = Math.floor(t % (1 + ce)) + , t = 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, 255 & e, i >> 24, i >> 16 & 255, i >> 8 & 255, 255 & i, t >> 24, 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]); + return he.box(he.types.mvhd, t) + } + static sdtp(e) { + const t = e.samples || [] + , i = new Uint8Array(4 + t.length); + let r, n; + for (n = 0; n < t.length; n++) + r = t[n].flags, + i[n + 4] = r.dependsOn << 4 | r.isDependedOn << 2 | r.hasRedundancy; + return he.box(he.types.sdtp, i) + } + static stbl(e) { + var t = he.stsd(e) + , i = he.box(he.types.stts, he.STTS) + , r = he.box(he.types.stsc, he.STSC) + , n = he.box(he.types.stsz, he.STSZ) + , e = he.box(he.types.stco, he.STCO); + return he.box(he.types.stbl, t, i, r, n, e) + } + static avc1(e) { + let t, i, r, n = [], s = []; + var a = e.info.encrypted ? he.types.encv : he.types.avc1; + for (t = 0; t < e.config.sps.length; t++) + i = e.config.sps[t], + r = i.byteLength, + n.push(r >>> 8 & 255), + n.push(255 & r), + n = n.concat(Array.prototype.slice.call(i)); + for (t = 0; t < e.config.pps.length; t++) + i = e.config.pps[t], + r = i.byteLength, + s.push(r >>> 8 & 255), + s.push(255 & r), + s = s.concat(Array.prototype.slice.call(i)); + var o = he.box(he.types.avcC, new Uint8Array([1, n[3], n[4], n[5], 255, 224 | e.config.sps.length].concat(n).concat([e.config.pps.length]).concat(s))) + , d = e.config.width + , l = e.config.height + , u = e.config.pixelRatio[0] + , c = e.config.pixelRatio[1] + , h = e.info.encrypted && e.info.keyTagInfo ? he.sinf(e.info.keyTagInfo, e.type, he.types.avc1) : new Uint8Array; + return he.box(a, 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, d >> 8 & 255, 255 & d, l >> 8 & 255, 255 & l, 0, 72, 0, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 1, 18, 100, 97, 105, 108, 121, 109, 111, 116, 105, 111, 110, 47, 104, 108, 115, 46, 106, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 17, 17]), o, h, he.box(he.types.btrt, new Uint8Array([0, 28, 156, 128, 0, 45, 198, 192, 0, 45, 198, 192])), he.box(he.types.pasp, new Uint8Array([u >> 24, u >> 16 & 255, u >> 8 & 255, 255 & u, c >> 24, c >> 16 & 255, c >> 8 & 255, 255 & c]))) + } + static esds(e) { + var t = e.esdsConfig.length; + return new Uint8Array([0, 0, 0, 0, 3, 23 + t, 0, 1, 0, 4, 15 + t, 64, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5].concat([t]).concat(e.esdsConfig).concat([6, 1, 2])) + } + static audioStsd(e) { + var t = e.samplerate; + return new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, e.channelCount, 0, 16, 0, 0, 0, 0, t >> 8 & 255, 255 & t, 0, 0]) + } + static dac3(e) { + e = e.extraData; + return new Uint8Array([e >> 16 & 255, e >> 8 & 255, 255 & e]) + } + static dec3(e) { + return e.extraDataBytes + } + static mp4a(e, t) { + let i = he.types.mp4a + , r = null; + r = e.encrypted && e.keyTagInfo ? (i = he.types.enca, + he.sinf(e.keyTagInfo, "audio", he.types.mp4a)) : new Uint8Array; + e = he.audioStsd(t), + t = he.box(he.types.esds, he.esds(t)); + return he.box(i, e, t, r) + } + static mp3(e) { + return he.box(he.types[".mp3"], he.audioStsd(e)) + } + static ac3(e, t) { + let i = he.types["ac-3"] + , r = null; + return r = e.encrypted && e.keyTagInfo ? (i = he.types.enca, + he.sinf(e.keyTagInfo, "audio", he.types["ac-3"])) : new Uint8Array, + he.box(i, he.audioStsd(t), he.box(he.types.dac3, he.dac3(t)), r) + } + static ec3(e, t) { + let i = he.types["ec-3"] + , r = null; + return r = e.encrypted && e.keyTagInfo ? (i = he.types.enca, + he.sinf(e.keyTagInfo, "audio", he.types["ec-3"])) : new Uint8Array, + he.box(i, he.audioStsd(t), he.box(he.types.dec3, he.dec3(t)), r) + } + static stsd(e) { + if ("audio" !== e.type) + return he.box(he.types.stsd, he.STSD, he.avc1(e)); + if ("mp3" === e.config.segmentCodec && "mp3" === e.config.codec) + return he.box(he.types.stsd, he.STSD, he.mp3(e.config)); + if ("ac3" === e.config.segmentCodec) + return he.box(he.types.stsd, he.STSD, he.ac3(e.info, e.config)); + if ("ec3" === e.config.segmentCodec) + return he.box(he.types.stsd, he.STSD, he.ec3(e.info, e.config)); + if ("aac" === e.config.segmentCodec) + return he.box(he.types.stsd, he.STSD, he.mp4a(e.info, e.config)); + throw `unknown segmentCodec ${e.config.segmentCodec}` + } + static tkhd(e) { + var t = e.info.id + , i = e.info.duration * e.info.timescale + , r = Math.floor(i / (1 + ce)) + , i = Math.floor(i % (1 + ce)); + let n = 0 + , s = 0; + return "video" === e.type && (n = e.config.width, + s = e.config.height), + he.box(he.types.tkhd, new Uint8Array([1, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, t >> 24 & 255, t >> 16 & 255, t >> 8 & 255, 255 & t, 0, 0, 0, 0, r >> 24, r >> 16 & 255, r >> 8 & 255, 255 & r, i >> 24, i >> 16 & 255, i >> 8 & 255, 255 & i, 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, n >> 8 & 255, 255 & n, 0, 0, s >> 8 & 255, 255 & s, 0, 0])) + } + static traf(e, t) { + var i = he.senc(e) + , r = he.sdtp(e) + , n = i.boxData + , s = n.length ? he.saio(76) : new Uint8Array + , a = n.length ? he.saiz(i.defaultSampleInfoSize, i.sampleInfoSizes) : new Uint8Array + , o = he.sbgp(e) + , d = he.sgpd(e) + , l = e.id + , i = Math.floor(t / (1 + ce)) + , t = Math.floor(t % (1 + ce)); + return he.box(he.types.traf, he.box(he.types.tfhd, new Uint8Array([0, 2, 0, 0, l >> 24, l >> 16 & 255, l >> 8 & 255, 255 & l])), he.box(he.types.tfdt, new Uint8Array([1, 0, 0, 0, i >> 24, i >> 16 & 255, i >> 8 & 255, 255 & i, t >> 24, t >> 16 & 255, t >> 8 & 255, 255 & t])), n, s, a, o, d, he.trun(e, r.length + n.length + o.length + d.length + s.length + a.length + 16 + 20 + 8 + 16 + 8 + 8), r) + } + static trak(e) { + if ("trakData"in e) + return e.trakData; + e.info.duration = e.info.duration || 4294967295; + var t = he.types.trak + , i = he.tkhd(e) + , e = he.mdia(e); + return he.box(t, i, e) + } + static trex(e) { + e = e.info.id; + return he.box(he.types.trex, new Uint8Array([0, 0, 0, 0, e >> 24, e >> 16 & 255, e >> 8 & 255, 255 & e, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1])) + } + static trun(e, t) { + const i = e.samples || [] + , r = i.length + , n = 12 + 16 * r + , s = new Uint8Array(n); + let a, o, d, l, u, c; + for (t += 8 + n, + s.set([0, 0, 15, 1, r >>> 24 & 255, r >>> 16 & 255, r >>> 8 & 255, 255 & r, t >>> 24 & 255, t >>> 16 & 255, t >>> 8 & 255, 255 & t], 0), + a = 0; a < r; a++) + d = (o = i[a]).duration, + l = o.size, + u = o.flags, + c = o.cts, + s.set([d >>> 24 & 255, d >>> 16 & 255, d >>> 8 & 255, 255 & d, l >>> 24 & 255, l >>> 16 & 255, l >>> 8 & 255, 255 & l, u.isLeading << 2 | u.dependsOn, u.isDependedOn << 6 | u.hasRedundancy << 4 | u.paddingValue << 1 | u.isNonSync, 61440 & u.degradPrio, 15 & u.degradPrio, c >>> 24 & 255, c >>> 16 & 255, c >>> 8 & 255, 255 & c], 12 + 16 * a); + return he.box(he.types.trun, s) + } + static initSegment(e) { + he.types || he.init(); + const t = he.moov(e) + , i = new Uint8Array(he.FTYP.byteLength + t.byteLength); + return i.set(he.FTYP), + i.set(t, he.FTYP.byteLength), + i + } + static saio(e) { + e = e + 4 + 4; + return he.box(he.types.saio, new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, e >> 24 & 255, e >> 16 & 255, e >> 8 & 255, 255 & e])) + } + static saiz(e, t) { + ne(e) || (e = 0); + var i = t.length + , t = 0 === e ? new Uint8Array(t) : new Uint8Array; + return he.box(he.types.saiz, new Uint8Array([0, 0, 0, 0, e, i >> 24 & 255, i >> 16 & 255, i >> 8 & 255, 255 & i]), t) + } + static senc(e) { + const t = e.samples || [] + , i = t.length; + let r = 0 + , n = NaN + , s = !0; + const a = []; + if (!e.encrypted || i <= 0) + return { + boxData: new Uint8Array, + sampleInfoSizes: a, + defaultSampleInfoSize: 0 + }; + e = e.defaultPerSampleIVSize || 0; + for (const l of t) + l.subsamples && (r += l.subsamples.length); + if (r <= 0) + return { + boxData: new Uint8Array, + sampleInfoSizes: a, + defaultSampleInfoSize: 0 + }; + const o = new Uint8Array(2 * i + i * e + 6 * r + 4); + let d = this.set32(i, o, 0); + for (const l of t) { + const t = l.subsamples || []; + let e = 2; + l.iv && (o.set(l.iv, d), + d += l.iv.byteLength, + e += l.iv.byteLength), + d = this.set16(t.length, o, d); + for (const l of t) + d = this.set16(l[0], o, d), + d = this.set32(l[1], o, d), + e += 6; + a.push(e), + ne(n) || (n = e), + s = s && n === e, + n = e + } + return { + boxData: he.box(he.types.senc, new Uint8Array([0, 0, 0, 2]), o), + defaultSampleInfoSize: s ? n : 0, + sampleInfoSizes: a + } + } + static sinf(e, t, i) { + return he.box(he.types.sinf, he.frma(i), he.schm(), he.schi(e, t)) + } + static frma(e) { + return he.box(he.types.frma, new Uint8Array(e)) + } + static schm() { + return he.box(he.types.schm, new Uint8Array([0, 0, 0, 0, 99, 98, 99, 115, 0, 1, 0, 0])) + } + static schi(e, t) { + return he.box(he.types.schi, he.tenc(e, t)) + } + static tenc(e, t) { + let i = 0; + "video" === t && (i = 25); + const r = new Uint8Array(17); + if (r[0] = 16, + e.iv && 16 === e.iv.byteLength && r.set(e.iv, 1), + !e.keyId) + throw "tenc: no key id found in decryptdata"; + return he.box(he.types.tenc, new Uint8Array([1, 0, 0, 0, 0, i, 1, 0]), e.keyId, r) + } + static sbgp(e) { + if (!e.encrypted || 0 === e.samples.length || !e.samples[0].keyTagInfo) + return new Uint8Array; + e = e.samples.length; + return he.box(he.types.sbgp, new Uint8Array([0, 0, 0, 0]), new Uint8Array(he.types.seig), new Uint8Array([0, 0, 0, 1, e >> 24 & 255, e >> 16 & 255, e >> 8 & 255, 255 & e, 0, 1, 0, 1])) + } + static sgpd(e) { + if (!e.encrypted || 0 === e.samples.length || !e.samples[0].keyTagInfo) + return new Uint8Array; + var t = e.samples[0].keyTagInfo; + let i = 0; + "video" === e.type && (i = 25); + const r = new Uint8Array(17); + if (r[0] = 16, + t.iv && r.set(t.iv, 1), + !t.keyId) + throw "sgpd: no keyid in decryptdata"; + return he.box(he.types.sgpd, new Uint8Array([1, 0, 0, 0]), new Uint8Array(he.types.seig), new Uint8Array([0, 0, 0, 37, 0, 0, 0, 1]), new Uint8Array([0, i, 1, 0]), t.keyId, r) + } + static pssh(e, t, i) { + if (he.types || he.init(), + !e) + throw new TypeError("Bad system id"); + if (16 !== e.byteLength) + throw new RangeError("Invalid system id"); + let r, n, s; + if (t) { + r = 1, + n = new Uint8Array(16 * t.length); + for (let e = 0; e < t.length; e++) { + const i = t[e]; + if (16 !== i.byteLength) + throw new RangeError("Invalid key"); + n.set(i, 16 * e) + } + } else + r = 0, + n = new Uint8Array; + 0 < r ? (s = new Uint8Array(4), + 0 < t.length && new DataView(s.buffer).setUint32(0, t.length, !1)) : s = new Uint8Array; + var a = new Uint8Array(4); + return i && 0 < i.byteLength && new DataView(a.buffer).setUint32(0, i.byteLength, !1), + he.box(he.types.pssh, new Uint8Array([r, 0, 0, 0]), e, s, n, a, i || new Uint8Array) + } + } + var pe, fe, me = he; + (yi = pe = pe || {})[yi.SDR = 0] = "SDR", + yi[yi.HDR = 1] = "HDR", + yi[yi.HDR10 = 2] = "HDR10", + yi[yi.DolbyVision = 3] = "DolbyVision", + yi[yi.HLG = 4] = "HLG", + (Si = fe = fe || {})[Si.H264 = 16] = "H264", + Si[Si.HEVC = 64] = "HEVC", + Si[Si.VP09 = 65] = "VP09"; + const ge = new Set(["ac-3", "mp4a.a5", "mp4a.A5"]) + , ye = new Set(["ec-3", "mp4a.a6", "mp4a.A6"]) + , ve = { + aac: 1024, + mp3: 1024, + ac3: 1536, + ec3: 1536 + } + , Se = { + isAC3: e=>Boolean(e && ge.has(e)), + isEC3: e=>Boolean(e && ye.has(e)), + isDolbyAtmos(e, t) { + const i = t.split("/"); + return Boolean(Se.isEC3(e) && 1 < i.length && i[1].split(",").find(e=>"JOC" === e)) + }, + isAAC(e) { + return Boolean(e && ("aac" === e || null !== (e = e.match(/^mp4a\.40\.(.*)/)) && "34" !== e[1])) + }, + isMP3(e) { + return Boolean(e && ("mp3" === e || null !== (e = e.match(/^mp4a\.40\.(.*)/)) && "34" === e[1])) + }, + isAVC: e=>Boolean(e && e.match(/^avc[13]\.(.*)/)), + isXHEAAC: function(e) { + return Boolean("mp4a.40.42" === e) + }, + isALAC: function(e) { + return Boolean("alac" === e) + }, + isFLAC: function(e) { + return Boolean("fLaC" === e) + }, + isHEVC: e=>Boolean(e && e.match(/^(hev|hvc)1\..*/)), + isDolby: e=>Boolean(e && e.match(/^dv(h1|he|a1|av)\..*/)), + isVP09: e=>Boolean(e && e.match(/^vp09\..*/)), + isCompatibleCodecString(e, t) { + const i = e.split(",") + , r = t.split(",") + , n = i.filter(e=>Se.isVideoCodec(e)) + , s = r.filter(e=>Se.isVideoCodec(e)) + , a = i.filter(e=>Se.isAudioCodec(e)) + , o = r.filter(e=>Se.isAudioCodec(e)) + , d = 0 === n.length && 0 === s.length || n.length === s.length && Se.isCompatibleVideoCodec(n[0], s[0]) + , l = 0 === a.length && 0 === o.length || a.length === o.length && Se.isCompatibleAudioCodec(a[0], o[0]); + return d && l + }, + isVideoCodec: e=>Se.isAVC(e) || Se.isDolby(e) || Se.isHEVC(e), + isAudioCodec: e=>Se.isAC3(e) || Se.isEC3(e) || Se.isAAC(e) || Se.isMP3(e), + isCompatibleVideoCodec: (e,t)=>Boolean(e && t && (e === t || Se.isDolby(e) && Se.isDolby(t) || Se.isHEVC(e) && Se.isHEVC(t) || Se.isAVC(e) && Se.isAVC(t))), + isCompatibleAudioCodec: (e,t)=>Boolean(e && t && (e === t || Se.isAAC(e) && Se.isAAC(t) || Se.isAC3(e) && Se.isAC3(t) || Se.isEC3(e) && Se.isEC3(t) || Se.isMP3(e) && Se.isMP3(t))), + getSegmentCodec(e) { + let t; + if (Se.isAAC(e)) + t = "aac"; + else if (Se.isAC3(e)) + t = "ac3"; + else if (Se.isEC3(e)) + t = "ec3"; + else { + if ("mp3" !== e) + throw new Error(`invalid audio config, codec ${e}`); + t = "mp3" + } + return t + }, + getChannelCount(e) { + if (!e) + return 0; + e = e.split("/"), + e = parseInt(e[0]); + return ne(e) ? e : 0 + }, + avc1toavcoti(e) { + var t; + const i = e.split("."); + let r; + return 2 < i.length ? (r = i.shift() + ".", + r += parseInt(null !== (t = i.shift()) && void 0 !== t ? t : "").toString(16), + r += ("000" + parseInt(null !== (t = i.shift()) && void 0 !== t ? t : "").toString(16)).substr(-4)) : r = e, + r + }, + getDynamicRangeType(e, t) { + let i = pe.SDR; + return "PQ" === e && Se.isDolby(t) ? i = pe.DolbyVision : "PQ" === e && (Se.isHEVC(t) || Se.isVP09(t)) ? i = pe.HDR10 : "HLG" !== e || -1 === t.indexOf("hvc1") && !Se.isVP09(t) || (i = pe.HLG), + i + }, + getCompressionType(e) { + let t = fe.H264; + return Se.isHEVC(e) || Se.isDolby(e) ? t = fe.HEVC : Se.isVP09(e) && (t = fe.VP09), + t + }, + isHigherCodecByFamily(e, t) { + if (!e) + return !0; + const i = e.split(".") + , r = t.split("."); + if (i[0] !== r[0]) + throw new Error(`mismatch in codec family current/new: ${i[0]}/${r[0]}`); + switch (i[0]) { + case "avc1": + case "avc3": + return r[1] > i[1]; + case "vp09": + return e < t; + case "hvc1": + case "hev1": + var n = "H" === i[3].substring(0, 1) ? 1 : 0 + , s = i[3].substring(1) + , a = "H" === r[3].substring(0, 1) ? 1 : 0 + , o = r[3].substring(1); + return r[1] > i[1] || r[2] > i[2] || n < a || s < o; + case "dvh1": + return r[1] > i[1] || r[2] > i[2] + } + } + }; + class be { + static getTrack(e, t, i, r, n) { + let s; + switch (Se.getSegmentCodec(i)) { + case "aac": + var a; + (a = E(e, 1 === r ? new Uint8Array([255, 241, 92, 64, 1, 127, 252]) : new Uint8Array([255, 241, 92, 128, 1, 191, 252]), 0, i)) && (s = { + type: "audio", + info: { + id: t, + timescale: a.samplerate, + duration: 0, + encrypted: !1, + keyTagInfo: void 0 + }, + config: a + }); + break; + case "ac3": + case "ec3": + { + const i = q(e, new Uint8Array([11, 119, 69, 17, 128, 64, 47, 132]), 0); + i && (s = { + type: "audio", + info: { + id: t, + timescale: i.samplerate, + duration: 0, + encrypted: !1, + keyTagInfo: void 0 + }, + config: i + }) + } + } + return s + } + static getSample(e, t) { + let i; + switch (e) { + case "mp4a.40.2": + case "mp4a.40.5": + i = 1 === t ? new Uint8Array([0, 208, 0, 7]) : new Uint8Array([33, 0, 3, 64, 104, 28]); + break; + case "ac-3": + case "ec-3": + i = new Uint8Array([11, 119, 69, 17, 128, 64, 47, 132, 41, 3, 253, 214, 124, 253, 243, 215, 233, 95, 185, 123, 78, 20, 40, 106, 97, 190, 74, 253, 43, 218, 208, 140, 191, 176, 144, 120, 214, 181, 44, 124, 129, 251, 91, 109, 187, 109, 198, 225, 43, 172, 116, 140, 176, 123, 38, 144, 211, 247, 225, 64, 29, 53, 175, 96, 16, 57, 121, 87, 78, 203, 81, 37, 7, 72, 228, 132, 37, 169, 38, 231, 97, 229, 247, 194, 208, 8, 12, 83, 74, 139, 137, 17, 22, 26, 221, 203, 107, 113, 94, 93, 75, 33, 208, 247, 146, 105, 39, 143, 6, 36, 1, 227, 108, 70, 11, 180, 152, 218, 182, 218, 209, 59, 85, 104, 201, 70, 37, 82, 219, 68, 55, 225, 144, 99, 149, 0, 119, 26, 14, 69, 164, 241, 204, 222, 81, 177, 142, 80, 20, 100, 97, 143, 101, 221, 140, 113, 31, 208, 124, 25, 64, 29, 49, 77, 140, 30, 155, 74, 214, 204, 138, 229, 109, 172, 95, 130, 70, 230, 134, 88, 59, 179, 212, 155, 232, 0, 0, 0, 0, 0, 173, 234]) + } + return i + } + static getSegment(e, i, r, n) { + if (e) { + var s = e.info["timescale"] + , a = e.config["segmentCodec"] + , o = be.getSample(e.config.codec, e.config.channelCount); + if (o) { + const d = [] + , l = { + id: e.info.id, + sequenceNumber: i, + type: "audio", + encrypted: !1, + samples: d, + defaultPerSampleIVSize: 0 + } + , u = ve[a] + , c = Math.ceil(n * s / u) + , h = { + baseTime: Math.round(c * u + r), + timescale: s + }; + let t = 0; + const p = c * o.byteLength + 8 + , f = new Uint8Array(p); + f[0] = p >> 24 & 255, + f[1] = p >> 16 & 255, + f[2] = p >> 8 & 255, + f[3] = 255 & p, + me.types || me.init(), + f.set(me.types.mdat, 4), + t += 8; + for (let e = 0; e < c; e++) + d.push({ + duration: u, + size: o.byteLength, + cts: 0, + flags: { + isLeading: 0, + isDependedOn: 0, + hasRedundancy: 0, + degradPrio: 0, + dependsOn: 1, + isNonSync: 0, + paddingValue: 0 + } + }), + f.set(o, t), + t += o.byteLength; + const m = me.moof(r, l) + , g = new Uint8Array(m.byteLength + f.byteLength); + return g.set(m), + g.set(f, m.byteLength), + { + silentFragData: g, + endTs: h + } + } + } + } + } + class Te extends h { + constructor(e, t, i, r, n) { + super(e, t, n), + this.typeSupported = i, + this.isVideoContiguous = !1, + this.logger = n.child({ + name: "EsRemuxer" + }); + const s = navigator.userAgent; + this.isSafari = r && -1 < r.indexOf("Apple") && s && !s.match("CriOS") + } + resetTimeStamp(e) { + this._initPTS = this._initDTS = e + } + resetInitSegment() { + this.currentInitTrack = void 0, + this._silentAudioTrack = void 0 + } + remuxEsTracks(r, n, s, a, o, d, l, u, c, h) { + let p; + d || (this.isVideoContiguous = !1); + c = void 0 === c ? o : c; + if (!this.currentInitTrack) { + if (r && r.config.codec && (this._audioTrackInfo = { + id: r.info.id, + codec: r.config.codec, + channelCount: r.config.channelCount + }), + n && h && this._audioTrackInfo) { + const r = be.getTrack(this.observer, this._audioTrackInfo.id, this._audioTrackInfo.codec, this._audioTrackInfo.channelCount, this.logger); + if (r) { + this._silentAudioTrack = Object.assign(Object.assign({}, r), { + info: Object.assign(Object.assign({}, r.info), { + inputTimescale: 9e4 + }), + parsingData: { + len: 0, + sequenceNumber: 0, + esSamples: [] + } + }); + const s = this._initPTS + Math.round(c * this._silentAudioTrack.info.timescale); + p = be.getSegment(this._silentAudioTrack, n.parsingData.sequenceNumber, s, h), + n.parsingData.sequenceNumber++ + } + } else + this._silentAudioTrack = void 0; + this.updateInitPTSDTS(n, r, o), + this.generateIS(this._silentAudioTrack || r, n) + } + if (this.currentInitTrack) { + const f = n && n.parsingData.esSamples.length + , m = this.isVideoContiguous; + let t, i, e; + if (n && h && this._silentAudioTrack && !p) { + const r = this._initPTS + Math.round((c + this.config.audioPrimingDelay) * this._silentAudioTrack.info.timescale); + p = be.getSegment(this._silentAudioTrack, n.parsingData.sequenceNumber, r, h) + } + if (r && r.parsingData.esSamples.length) { + if (ne(r.info.timescale) || (this.logger.warn("regenerate InitSegment as audio detected"), + this.updateInitPTSDTS(n, r, o), + this.generateIS(r, n)), + t = this.remuxAudio(r, c, d, l, u), + f) { + let e; + t && (e = S(t.endPTS) - S(t.startPTS)), + ne(n.info.timescale) || (this.logger.warn("regenerate InitSegment as video detected"), + this.updateInitPTSDTS(n, r, o), + this.generateIS(r, n)), + i = this.remuxVideo(n, c, m, e, h) + } + } else + f && (i = this.remuxVideo(n, c, m, void 0, h)), + i && r && r.config.codec && (t = this.remuxEmptyAudio(r, c, d, l, i, u)); + p ? e = { + data1: i.data1, + data2: p.silentFragData, + startDTS: i.startDTS, + startPTS: i.startPTS, + endDTS: y(i.endDTS, p.endTs), + endPTS: y(i.endPTS, p.endTs), + type: "audiovideo", + track: this.currentInitTrack + } : i && t ? e = { + data1: i.data1, + data2: t.data1, + startDTS: g(i.startDTS, t.startDTS), + startPTS: g(i.startPTS, t.startPTS), + endDTS: y(i.endDTS, t.endDTS), + endPTS: y(i.endPTS, t.endPTS), + type: "audiovideo", + track: this.currentInitTrack, + dropped: i.dropped, + framesWithoutIDR: i.framesWithoutIDR, + firstKeyframePts: i.firstKeyframePts + } : i ? e = { + data1: i.data1, + startDTS: i.startDTS, + startPTS: i.startPTS, + endDTS: i.endDTS, + endPTS: i.endPTS, + type: "video", + track: this.currentInitTrack, + dropped: i.dropped, + framesWithoutIDR: i.framesWithoutIDR, + firstKeyframePts: i.firstKeyframePts + } : t ? e = { + data1: t.data1, + startDTS: t.startDTS, + startPTS: t.startPTS, + endDTS: t.endDTS, + endPTS: t.endPTS, + type: "audio", + track: this.currentInitTrack + } : this.logger.error("Missing video and audio data"), + a && a.captionSamples.length && this.remuxText(a, e), + null !== (a = null == s ? void 0 : s.id3Samples) && void 0 !== a && a.length && this.remuxID3(s, e), + this.observer.trigger(v.FRAG_PARSING_DATA, e) + } else + this.logger.error("failed to generate IS"); + this.observer.trigger(v.FRAG_PARSED) + } + updateInitPTSDTS(e, t, i) { + let r = 1 / 0 + , n = 1 / 0; + var s = e ? e.parsingData.esSamples : [] + , a = t ? t.parsingData.esSamples : []; + if (!ne(this._initPTS)) { + if (t && a.length && (r = n = a[0].pts - t.info.inputTimescale * i), + e && s.length) { + const t = e.info.inputTimescale; + e.info.timescale = t, + r = Math.min(r, s.reduce((e,t)=>{ + var i = t.pts - e; + return i < -4294967296 ? Ee(e, t.pts) : 0 < i ? e : t.pts + } + , s[0].pts) - t * i), + n = Math.min(n, s[0].dts - t * i), + this.observer.trigger(v.INIT_PTS_FOUND, { + initPTS: B(r, t) + }) + } + if (ne(r) && ne(n)) + this._initPTS = r, + this._initDTS = n; + else { + const e = new D(!1,"invalid initPTS or initDTS",$.InvalidInitTimestamp); + this.observer.trigger(x.INTERNAL_ERROR, e) + } + } + } + generateIS(e, t) { + const i = t ? t.parsingData.esSamples : [] + , r = this.typeSupported; + let n, s = "audio/mp4"; + if (e && t && i.length) { + const i = t.info.inputTimescale; + t.info.timescale = i, + e.info.timescale = e.config.samplerate; + const r = he.initSegment([t, e]); + n = { + type: "audiovideo", + container: "video/mp4", + codec: `${t.config.codec},${e.config.codec}`, + initSegment: r + } + } else if (e) { + "mp3" === (e.info.timescale = e.config.samplerate, + e.config.segmentCodec) && (r.mpeg ? (s = "audio/mpeg", + e.config.codec = "") : r.mp3 && (e.config.codec = "mp3")); + const t = "mp3" === e.config.segmentCodec && r.mpeg ? new Uint8Array : he.initSegment([e]); + n = { + type: "audio", + container: s, + codec: e.config.codec, + initSegment: t + } + } else if (t && i.length) { + const e = t.info.inputTimescale; + t.info.timescale = e; + const i = he.initSegment([t]); + n = { + type: "video", + container: "video/mp4", + codec: t.config.codec, + initSegment: i + } + } + if (n) { + this.currentInitTrack = n; + const e = { + track: n + }; + this.observer.trigger(v.FRAG_PARSING_INIT_SEGMENT, e) + } else { + const e = new D(!1,"no audio/video samples found",$.NoAVSamplesFound); + this.observer.trigger(x.INTERNAL_ERROR, e) + } + } + remuxVideo(n, e, s, a, o) { + let d, l, u, c, h, t, p = 8, i = n.parsingData.dropped; + const r = !s && this.config.forceKeyFrameOnDiscontinuity + , f = n.parsingData.esSamples + , m = n.info.inputTimescale + , g = [] + , y = n.info.encrypted; + let v, S; + v = s ? this.nextAvcDts : Ee(f[0].dts, f[0].pts), + f.forEach(function(e) { + e.pts = Ee(e.pts, v), + e.dts = Ee(e.dts, v) + }), + f.sort(function(e, t) { + var i = e.dts - t.dts + , r = e.pts - t.pts; + return i || r || e.id - t.id + }); + var b = f.findIndex(e=>e.key); + f[b] && (S = f[b].pts), + r && (0 < b ? (this.logger.warn(`Dropped ${b} out of ${f.length} video samples due to a missing keyframe`), + f.splice(0, b), + i += b) : -1 === b && (this.logger.warn(`No keyframe found out of ${f.length} video samples`), + i += f.length)); + var T = f[0] + , E = f[f.length - 1] + , I = f.reduce((e,t)=>Math.max(Math.min(e, t.pts - t.dts), -18e3), 0); + if (I < 0) { + this.logger.warn(`PTS < DTS detected in video samples, shifting DTS by ${Math.round(I / 90)} ms to overcome this issue`); + for (let e = 0; e < f.length; e++) + f[e].dts += I + } + var w = this.isSafari; + if (d = Math.round((E.dts - T.dts) / (f.length - 1)), + c = Math.max(T.dts, 0), + u = Math.max(T.pts, 0), + ne(o) && (c = e * m, + u = e * m), + s) { + const n = c - v + , M = n > d + , s = n < -1; + (M || s) && (M ? this.logger.warn(`AVC: ${n}/90000 hole between fragments detected`) : this.logger.warn(`AVC: ${n}/90000 overlapping between fragments detected`)) + } + let A = 0 + , O = 0; + var k = f.length; + for (let e = 0; e < k; e++) { + const M = f[e] + , s = M.units + , a = s.length; + let t = 0; + for (let e = 0; e < a; e++) + t += s[e].data.length; + O += t, + A += a, + M.length = t, + M.dts = w ? c + e * d : Math.max(M.dts, c), + M.pts = Math.max(M.pts, M.dts) + } + t = Math.max(E.dts, 0), + h = Math.max(E.pts, 0, t), + ne(o) && (t = e * m, + h = e * m); + e = O + 4 * A + 8; + try { + l = new Uint8Array(e) + } catch (n) { + const M = new F(!1,`fail allocating video mdat ${e}`,$.FailedToAllocateVideoMdat,e); + return void this.observer.trigger(x.INTERNAL_ERROR, M) + } + const C = new DataView(l.buffer); + C.setUint32(0, e), + l.set(he.types.mdat, 4); + for (let t = 0; t < k; t++) { + const M = f[t] + , s = M.units; + let e, i = 0; + const h = []; + let r = 0; + for (let e = 0, t = s.length; e < t; e++) { + const M = s[e] + , a = M.data + , o = M.data.byteLength; + if (C.setUint32(p, o), + p += 4, + l.set(a, p), + p += o, + i += 4 + o, + y) + if (o <= 48 || 1 !== M.type && 5 !== M.type) + r += 4 + o; + else { + let e = o - 32; + e % 16 == 0 && (e -= 16), + h.push([r + 36, e]), + r = o - 32 - e + } + } + if (0 < r && h.push([r, 0]), + w) + e = Math.max(0, d * Math.round((M.pts - M.dts) / d)); + else { + if (t < k - 1) + d = f[t + 1].dts - M.dts; + else { + const s = this.config + , o = M.dts - f[0 < t ? t - 1 : t].dts; + if (s.stretchShortVideoTrack) { + const n = s.maxBufferHole + , l = s.maxSeekHole + , c = Math.floor(Math.min(n, l) * m) + , x = (a ? u + a * m : this.nextAudioPts) - M.pts; + x > c ? (d = x - o, + d < 0 && (d = o)) : d = o + } else + d = o + } + e = Math.round(M.pts - M.dts) + } + ne(o) && (e = 0, + d = o * m), + g.push({ + size: i, + duration: d, + cts: e, + flags: { + isLeading: 0, + isDependedOn: 0, + hasRedundancy: 0, + degradPrio: 0, + dependsOn: M.key ? 2 : 1, + isNonSync: M.key ? 0 : 1, + paddingValue: 0 + }, + keyTagInfo: M.keyTagInfo, + subsamples: h + }) + } + if (this.nextAvcDts = t + d, + this.isVideoContiguous = !0, + g.length && -1 < navigator.userAgent.toLowerCase().indexOf("chrome")) { + const n = g[0].flags; + n.dependsOn = 2, + n.isNonSync = 0 + } + e = { + sequenceNumber: n.parsingData.sequenceNumber++, + id: n.info.id, + type: n.type, + encrypted: n.info.encrypted, + samples: g, + defaultPerSampleIVSize: 0 + }, + e = he.moof(c + this.config.audioPrimingDelay * m, e); + n.parsingData.esSamples = []; + const D = new Uint8Array(e.byteLength + l.byteLength); + return D.set(e), + D.set(l, e.byteLength), + { + data1: D, + startPTS: B(u / m, m), + endPTS: B((h + d) / m, m), + startDTS: B(c / m, m), + endDTS: B(this.nextAvcDts / m, m), + type: "video", + dropped: i, + framesWithoutIDR: b, + firstKeyframePts: B(S / m, m) + } + } + remuxAudio(r, i, n, e, s) { + const a = r.info.inputTimescale + , o = a / r.info.timescale + , d = ("aac" === r.config.segmentCodec ? 1024 : "mp3" === r.config.segmentCodec ? 1152 : 1536) * o + , l = "mp3" === r.config.segmentCodec && this.typeSupported.mpeg + , u = [] + , c = r.info.encrypted + , t = this._initPTS + i * a; + let h, p, f, m, g, y, v, S, b, T, E, I, w, A, O = l ? 0 : 8; + const k = new H + , C = r.parsingData.esSamples; + if (A = this.nextAudioPts, + (n = n || C.length && A && (e && Math.abs(t - A) < 9e3 || Math.abs(Ee(C[0].pts - A, t)) < 20 * d)) || (A = Ee(C[0].pts, this._initPTS)), + C.forEach(function(e) { + e.pts = e.dts = Ee(e.pts, A) + }), + e && "aac" === r.config.segmentCodec) + for (let t = 0, i = A; t < C.length; ) { + const M = C[t]; + T = M.pts; + const o = T - i + , l = Math.abs(1e3 * o / a); + if (o <= -d) + this.logger.warn(`Dropping 1 audio frame @ ${(i / a).toFixed(3)}s due to ${l} ms overlap.`), + C.splice(t, 1), + r.parsingData.len -= M.unit.length; + else if (o >= d && l < 1e4 && i) { + const l = Math.round(o / d); + this.logger.warn(`Injecting ${l} audio frame @ ${(i / a).toFixed(3)}s due to ${Math.round(1e3 * o / a)} ms gap.`); + for (let e = 0; e < l; e++) + w = Math.max(i, 0), + I = re(r.config.codec, r.config.channelCount), + I || (this.logger.warn("Unable to get silent frame for given audio codec; duplicating last frame instead."), + I = M.unit.subarray(0)), + C.splice(t, 0, { + unit: I, + pts: w, + dts: w, + keyTagInfo: s + }), + r.parsingData.len += I.length, + i += d, + t += 1; + M.pts = M.dts = i, + i += d, + t += 1 + } else + i += d, + M.pts = M.dts = 0 === t ? A : C[t - 1].pts + d, + t += 1 + } + for (let e = 0, t = C.length; e < t; e++) { + if (p = C[e], + m = p.unit, + T = p.pts, + E = p.dts, + void 0 !== b) + f.duration = Math.round((E - b) / o); + else { + const i = Math.round(1e3 * (T - A) / a); + let t = 0; + if (n && "aac" === r.config.segmentCodec && i) { + if (0 < i && i < 1e4) + t = Math.round((T - A) / d), + 0 < t && (I = re(r.config.codec, r.config.channelCount), + I = I || m.subarray(0), + r.parsingData.len += t * I.length); + else if (i < -12) { + r.parsingData.len -= m.byteLength; + continue + } + T = E = A + } + if (v = Math.max(0, T), + S = Math.max(0, E), + !(0 < r.parsingData.len)) + return; + { + const i = l ? r.parsingData.len : r.parsingData.len + 8; + try { + g = new Uint8Array(i) + } catch (r) { + const n = new F(!1,`fail allocating audio mdat ${i}`,$.FailedToAllocateAudioMdat,i); + return void this.observer.trigger(x.INTERNAL_ERROR, n) + } + l || (h = new DataView(g.buffer), + h.setUint32(0, i), + g.set(he.types.mdat, 4)) + } + for (let e = 0; e < t; e++) + w = T - (t - e) * d, + I = re(r.config.codec, r.config.channelCount), + I || (this.logger.warn("Unable to get silent frame for given audio codec; duplicating this frame instead."), + I = m.subarray(0)), + g.set(I, O), + O += I.byteLength, + f = { + size: I.byteLength, + cts: 0, + duration: 1024, + flags: { + isLeading: 0, + isDependedOn: 0, + hasRedundancy: 0, + degradPrio: 0, + dependsOn: 1, + paddingValue: 0, + isNonSync: 0 + }, + keyTagInfo: p.keyTagInfo, + subsamples: c ? [[I.byteLength, 0]] : [] + }, + u.push(f) + } + g.set(m, O); + const M = m.byteLength; + O += M; + const s = []; + if (c) + if ("ec3" === r.config.segmentCodec) { + let e = 0; + for (; e < m.byteLength; ) { + const i = 2 * (k.bsReadAndUpdate(m, { + byteOffset: e + 2, + usedBits: 5 + }, 11) + 1); + e += i; + const n = Math.min(i, 16); + s.push([n, i - n]) + } + } else { + const r = Math.min(M, 16); + s.push([r, M - r]) + } + f = { + size: M, + cts: 0, + duration: 0, + flags: { + isLeading: 0, + isDependedOn: 0, + hasRedundancy: 0, + degradPrio: 0, + dependsOn: 1, + paddingValue: 0, + isNonSync: 0 + }, + keyTagInfo: p.keyTagInfo, + subsamples: s + }, + u.push(f), + b = E + } + let D = 0; + e = u.length; + if (2 <= e && (D = u[e - 2].duration, + f.duration = D), + e) { + if (this.nextAudioPts = T + o * D, + r.parsingData.len = 0, + l) + y = new Uint8Array; + else { + const i = { + sequenceNumber: r.parsingData.sequenceNumber++, + id: r.info.id, + type: r.type, + encrypted: r.info.encrypted, + samples: u, + defaultPerSampleIVSize: 0 + }; + y = he.moof((S + this.config.audioPrimingDelay * a) / o, i) + } + const i = new Uint8Array(y.byteLength + g.byteLength); + return i.set(y), + i.set(g, y.byteLength), + r.parsingData.esSamples = [], + { + data1: i, + startPTS: B(v / a, a), + endPTS: B(this.nextAudioPts / a, a), + startDTS: B(S / a, a), + endDTS: B((E + o * D) / a, a), + type: "audio" + } + } + return null + } + remuxEmptyAudio(t, e, i, r, n, s) { + var a = t.info.inputTimescale + , o = a / (t.config.samplerate || a) + , d = this.nextAudioPts + , l = (void 0 !== d ? d : S(n.startDTS) * a) + this._initDTS + , a = S(n.endDTS) * a + this._initDTS + , u = 1024 * o + , c = Math.ceil((a - l) / u) + , h = re(t.config.codec, t.config.channelCount); + if (this.logger.warn("remux empty Audio"), + !h) + return this.logger.error("Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!"), + null; + const p = []; + for (let e = 0; e < c; e++) { + const i = l + e * u; + p.push({ + unit: h, + pts: i, + dts: i, + keyTagInfo: s + }), + t.parsingData.len += h.length + } + return t.parsingData.esSamples = p, + this.remuxAudio(t, e, i, r, s) + } + remuxID3(t, e) { + var i = t.id3Samples.length; + let r; + var n = t.inputTimescale; + if (i) { + for (let e = 0; e < i; e++) + r = t.id3Samples[e], + r.pts = r.pts / n, + r.dts = r.dts / n; + e.id3Samples = t.id3Samples + } + t.id3Samples = [] + } + remuxText(t, e) { + t.captionSamples.sort(function(e, t) { + return e.pts - t.pts + }); + var i = t.captionSamples.length; + let r; + var n = t.inputTimescale; + if (i) { + for (let e = 0; e < i; e++) + r = t.captionSamples[e], + r.pts = r.pts / n; + e.captionData || (e.captionData = {}), + e.captionData.ts = t.captionSamples + } + t.captionSamples = [] + } + } + function Ee(e, t) { + var i; + if (void 0 === t) + return e; + for (i = t < e ? -8589934592 : 8589934592; 4294967296 < Math.abs(e - t); ) + e += i; + return e + } + e = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : void 0 !== jy ? jy : {}; + function Ie(e) { + try { + return JSON.stringify(e) + } catch (e) { + return '"[Circular]"' + } + } + function we(e, t, i) { + var r = i && i.stringify || Ie; + if ("object" == typeof e && null !== e) { + var n = t.length + 1; + if (1 === n) + return e; + var s = new Array(n); + s[0] = r(e); + for (var a = 1; a < n; a++) + s[a] = r(t[a]); + return s.join(" ") + } + if ("string" != typeof e) + return e; + var o = t.length; + if (0 === o) + return e; + for (var d = "", l = 0, u = -1, c = e && e.length || 0, h = 0; h < c; ) { + if (37 === e.charCodeAt(h) && h + 1 < c) { + switch (u = -1 < u ? u : 0, + e.charCodeAt(h + 1)) { + case 100: + if (o <= l) + break; + if (u < h && (d += e.slice(u, h)), + null == t[l]) + break; + d += Number(t[l]), + u = h += 2; + break; + case 79: + case 111: + case 106: + if (o <= l) + break; + if (u < h && (d += e.slice(u, h)), + void 0 === t[l]) + break; + var p = typeof t[l]; + if ("string" == p) { + d += "'" + t[l] + "'", + u = h + 2, + h++; + break + } + if ("function" == p) { + d += t[l].name || "", + u = h + 2, + h++; + break + } + d += r(t[l]), + u = h + 2, + h++; + break; + case 115: + if (o <= l) + break; + u < h && (d += e.slice(u, h)), + d += String(t[l]), + u = h + 2, + h++; + break; + case 37: + u < h && (d += e.slice(u, h)), + d += "%", + u = h + 2, + h++ + } + ++l + } + ++h + } + return -1 === u ? e : (u < c && (d += e.slice(u)), + d) + } + var Ae = Ce; + const Oe = function() { + function t(e) { + return void 0 !== e && e + } + try { + return "undefined" != typeof globalThis || Object.defineProperty(Object.prototype, "globalThis", { + get: function() { + return delete Object.prototype.globalThis, + this.globalThis = this + }, + configurable: !0 + }), + globalThis + } catch (e) { + return t(jy) || t(window) || t(this) || {} + } + }().console || {} + , ke = { + mapHttpRequest: Re, + mapHttpResponse: Re, + wrapRequestSerializer: Le, + wrapResponseSerializer: Le, + wrapErrorSerializer: Le, + req: Re, + res: Re, + err: function(e) { + const t = { + type: e.constructor.name, + msg: e.message, + stack: e.stack + }; + for (const i in e) + void 0 === t[i] && (t[i] = e[i]); + return t + } + }; + function Ce(s) { + (s = s || {}).browser = s.browser || {}; + const a = s.browser.transmit; + if (a && "function" != typeof a.send) + throw Error("pino: transmit option must have a send function"); + const e = s.browser.write || Oe; + s.browser.write && (s.browser.asObject = !0); + const o = s.serializers || {} + , d = (t = s.browser.serialize, + i = o, + Array.isArray(t) ? t.filter(function(e) { + return "!stdSerializers.err" !== e + }) : !0 === t && Object.keys(i)); + var t, i; + let r = s.browser.serialize; + Array.isArray(s.browser.serialize) && -1 < s.browser.serialize.indexOf("!stdSerializers.err") && (r = !1), + "function" == typeof e && (e.error = e.fatal = e.warn = e.info = e.debug = e.trace = e), + !1 === s.enabled && (s.level = "silent"); + const n = s.level || "info" + , l = Object.create(e); + l.log || (l.log = _e), + Object.defineProperty(l, "levelVal", { + get: function() { + return "silent" === this.level ? 1 / 0 : this.levels.values[this.level] + } + }), + Object.defineProperty(l, "level", { + get: function() { + return this._level + }, + set: function(e) { + if ("silent" !== e && !this.levels.values[e]) + throw Error("unknown level " + e); + this._level = e, + De(u, l, "error", "log"), + De(u, l, "fatal", "error"), + De(u, l, "warn", "error"), + De(u, l, "info", "log"), + De(u, l, "debug", "log"), + De(u, l, "trace", "log") + } + }); + const u = { + transmit: a, + serialize: d, + asObject: s.browser.asObject, + levels: ["error", "fatal", "warn", "info", "debug", "trace"], + timestamp: "function" == typeof (i = s).timestamp ? i.timestamp : !1 === i.timestamp ? Ne : Fe + }; + return l.levels = Ce.levels, + l.level = n, + l.setMaxListeners = l.getMaxListeners = l.emit = l.addListener = l.on = l.prependListener = l.once = l.prependOnceListener = l.removeListener = l.removeAllListeners = l.listeners = l.listenerCount = l.eventNames = l.write = l.flush = _e, + l.serializers = o, + l._serialize = d, + l._stdErrSerialize = r, + l.child = function(t) { + if (!t) + throw new Error("missing bindings for child Pino"); + var i, r, e = t.serializers; + function n(e) { + this._childLevel = 1 + (0 | e._childLevel), + this.error = Pe(e, t, "error"), + this.fatal = Pe(e, t, "fatal"), + this.warn = Pe(e, t, "warn"), + this.info = Pe(e, t, "info"), + this.debug = Pe(e, t, "debug"), + this.trace = Pe(e, t, "trace"), + i && (this.serializers = i, + this._serialize = r), + a && (this._logEvent = xe([].concat(e._logEvent.bindings, t))) + } + return d && e && (i = Object.assign({}, o, e), + r = !0 === s.browser.serialize ? Object.keys(i) : d, + delete t.serializers, + Me([t], r, i, this._stdErrSerialize)), + n.prototype = this, + new n(this) + } + , + a && (l._logEvent = xe()), + l + } + function De(e, t, i, r) { + var n, s, a, o, d = Object.getPrototypeOf(t); + t[i] = !(t.levelVal > t.levels.values[i]) && (d[i] || Oe[i] || Oe[r]) || _e, + s = t, + a = i, + !(n = e).transmit && s[a] === _e || (s[a] = (o = s[a], + function() { + const e = n.timestamp() + , t = new Array(arguments.length) + , i = Object.getPrototypeOf && Object.getPrototypeOf(this) === Oe ? Oe : this; + for (var r = 0; r < t.length; r++) + t[r] = arguments[r]; + if (n.serialize && !n.asObject && Me(t, this._serialize, this.serializers, this._stdErrSerialize), + n.asObject ? o.call(i, function(e, t, i, r) { + e._serialize && Me(i, e._serialize, e.serializers, e._stdErrSerialize); + const n = i.slice(); + let s = n[0]; + const a = {}; + r && (a.time = r), + a.level = Ce.levels.values[t]; + let o = 1 + (0 | e._childLevel); + if (o < 1 && (o = 1), + null !== s && "object" == typeof s) { + for (; o-- && "object" == typeof n[0]; ) + Object.assign(a, n.shift()); + s = n.length ? we(n.shift(), n) : void 0 + } else + "string" == typeof s && (s = we(n.shift(), n)); + return void 0 !== s && (a.msg = s), + a + }(this, a, t, e)) : o.apply(i, t), + n.transmit) { + const o = n.transmit.level || s.level + , i = Ce.levels.values[o] + , r = Ce.levels.values[a]; + r < i || function(e, t, i) { + const r = t.send + , n = t.ts + , s = t.methodLevel + , a = t.methodValue + , o = t.val + , d = e._logEvent.bindings; + Me(i, e._serialize || Object.keys(e.serializers), e.serializers, void 0 === e._stdErrSerialize || e._stdErrSerialize), + e._logEvent.ts = n, + e._logEvent.messages = i.filter(function(e) { + return -1 === d.indexOf(e) + }), + e._logEvent.level.label = s, + e._logEvent.level.value = a, + r(s, e._logEvent, o), + e._logEvent = xe(d) + }(this, { + ts: e, + methodLevel: a, + methodValue: r, + transmitLevel: o, + transmitValue: Ce.levels.values[n.transmit.level || s.level], + send: n.transmit.send, + val: s.levelVal + }, t) + } + } + )) + } + function Me(e, t, i, r) { + for (const n in e) + if (r && e[n]instanceof Error) + e[n] = Ce.stdSerializers.err(e[n]); + else if ("object" == typeof e[n] && !Array.isArray(e[n])) + for (const r in e[n]) + t && -1 < t.indexOf(r) && r in i && (e[n][r] = i[r](e[n][r])) + } + function Pe(i, r, n) { + return function() { + try{const e = new Array(1 + arguments.length); + e[0] = r; + for (var t = 1; t < e.length; t++) + e[t] = arguments[t - 1]; + return i[n].apply(this, e) } catch(e){} + } + } + function xe(e) { + return { + ts: 0, + messages: [], + bindings: e || [], + level: { + label: "", + value: 0 + } + } + } + function Re() { + return {} + } + function Le(e) { + return e + } + function _e() {} + function Ne() { + return !1 + } + function Fe() { + return Date.now() + } + let Be; + function Ue(e={}) { + return Object.assign(Object.assign({}, e), { + customLevels: Object.assign(Object.assign({}, e.customLevels || {}), { + qe: 35 + }) + }) + } + Ce.levels = { + values: { + fatal: 60, + error: 50, + warn: 40, + info: 30, + debug: 20, + trace: 10 + }, + labels: { + 10: "trace", + 20: "debug", + 30: "info", + 40: "warn", + 50: "error", + 60: "fatal" + } + }, + Ce.stdSerializers = ke, + Ce.stdTimeFunctions = Object.assign({}, { + nullTime: Ne, + epochTime: Fe, + unixTime: function() { + return Math.round(Date.now() / 1e3) + }, + isoTime: function() { + return new Date(Date.now()).toISOString() + } + }); + const $e = ()=>{} + ; + function Ve(e, t) { + const i = (e = t in e ? e : console)[t] || e.log; + return i ? i.bind(e) : $e + } + function Ke(r, n, e) { + var {time: s, sessionId: t, critical: i, name: a, msg: o} = e; + let d = ""; + if ("data"in e) + try { + const r = [] + , n = []; + d = JSON.stringify(e.data, (e,t)=>{ + if ("object" == typeof t && null !== t) { + var i = n.indexOf(t); + if (-1 !== i) + return `[Circular object reference: '${r[i]}']`; + r.push(e), + n.push(t) + } + return t + } + ) + } catch (r) { + d = `Log serialization error: "${r}"` + } + r(`${function() { + const e = new Date(s) + , t = e.getTimezoneOffset() + , i = He(Math.floor(Math.abs(t) / 60)) + , r = He(Math.abs(t) % 60); + let n = t <= 0 ? "UTC+" + i : "UTC-" + i; + return n = r ? n + ":" + r : n, + e.getFullYear() + "-" + He(e.getMonth() + 1) + "-" + He(e.getDate()) + " " + He(e.getHours()) + ":" + He(e.getMinutes()) + ":" + He(e.getSeconds()) + "." + (e.getMilliseconds() / 1e3).toFixed(3).slice(2, 5) + " " + n + }()}| [SessionID: ${t}] | [${n}] >${i ? " [QE Critical]" : ""} [${a}] ${o || ""} ${d}`) + } + function He(e) { + return e < 10 ? "0" + e : e.toString() + } + function je(e, t=1 / 0) { + if (!e) + return ""; + const i = new Uint8Array(e); + let r, n = ""; + for (r = 0; r < i.length && r < t; r++) { + let e = i[r].toString(16); + e.length < 2 && (e = "0" + e), + n += e + } + return n + } + const qe = ()=>(Be || (Be = Ae(Ue()).child({ + name: "hls" + }), + Be.qe = e=>Be.info(e), + Be.warn("getLogger called without hls object instantiated, returning a logger that is not configured")), + Be) + , Qe = { + bin2str: e=>String.fromCharCode.apply(null, Array.from(e)), + readUint16(e, t) { + t = e[t] << 8 | e[t + 1]; + return t < 0 ? 65536 + t : t + }, + readSint32: (e,t)=>e[t] << 24 | e[t + 1] << 16 | e[t + 2] << 8 | e[t + 3], + readUint32(e, t) { + t = Qe.readSint32(e, t); + return t < 0 ? 4294967296 + t : t + }, + writeUint32(e, t, i) { + e[t] = i >> 24, + e[t + 1] = i >> 16 & 255, + e[t + 2] = i >> 8 & 255, + e[t + 3] = 255 & i + }, + readUint64(e, t) { + var i = Qe.readUint32(e, t); + return i *= Math.pow(2, 32), + i += Qe.readUint32(e, t + 4) + }, + writeUint64(e, t, i) { + var r = Math.pow(2, 32) - 1 + , n = Math.floor(i / (1 + r)) + , r = Math.floor(i % (1 + r)); + Qe.writeUint32(e, t, n), + Qe.writeUint32(e, t + 4, r) + }, + findBox(e, t) { + let i, r, n, s, a, o = []; + if (!t.length) + return []; + for (i = 0; i < e.byteLength; ) + r = Qe.readUint32(e, i), + n = Qe.bin2str(e.subarray(i + 4, i + 8)), + s = 1 < r ? i + r : e.byteLength, + n === t[0] && (1 === t.length ? o.push(e.subarray(i + 8, s)) : (a = Qe.findBox(e.subarray(i + 8, s), t.slice(1))).length && (o = o.concat(a))), + i = s; + return o + }, + findBoxWithOffset(e, t, i, r) { + let n, s, a, o, d, l = []; + if (!i.length) + return []; + for (n = 0; n < e.byteLength; ) + s = Qe.readUint32(e, n), + a = Qe.bin2str(e.subarray(n + 4, n + 8)), + o = 1 < s ? n + s : e.byteLength, + a === i[0] && (r && r.push({ + offset: n + t, + type: a, + size: s + }), + 1 === i.length ? l.push({ + offset: n + t, + type: a, + data: e.subarray(n + 8, o), + boxSize: s, + walkedPath: r ? r.slice(0) : void 0 + }) : (d = Qe.findBoxWithOffset(e.subarray(n + 8, o), n + t + 8, i.slice(1), r ? r.slice(0) : void 0)).length && (l = l.concat(d), + r = r ? r.slice(0, -1) : void 0)), + n = o; + return l + } + } + , Ge = { + name: "MP4EncryptionRemuxer" + }; + class We extends h { + constructor(e, t, i, r, n) { + super(e, t, n) + } + static _isCommonEncryptionInternal(e) { + return Boolean(e && !("NONE" === e || "AES-128" === e)) + } + static remuxInitSegment(c, h, p, f) { + if (!p) + return c; + let e = c; + if (We._isCommonEncryptionInternal(p.method)) { + const m = p.keyId; + let u = !1; + const g = []; + if (Qe.findBoxWithOffset(c, 0, ["moov", "trak"]).forEach(t=>{ + const o = t.data; + let d, i = 0; + const l = Qe.findBoxWithOffset(o, 0, ["mdia", "minf", "stbl", "stsd"], [])[0] + , e = l.data.subarray(8); + let r = !0 + , n = Qe.findBoxWithOffset(e, l.offset + 16, ["enca"]); + 0 === n.length && (r = !1, + n = Qe.findBoxWithOffset(e, l.offset + 16, ["encv"])), + n.forEach(s=>{ + let e = null + , a = null; + i = r ? (e = s.data.subarray(28), + d = "audio", + l.offset + 16 + 8 + 28) : (e = s.data.subarray(78), + d = "video", + l.offset + 16 + 8 + 78), + e && Qe.findBoxWithOffset(e, i, ["sinf"]).forEach(e=>{ + const t = e.data + , i = Qe.findBox(t, ["frma"])[0] + , r = Qe.findBox(t, ["schm"])[0]; + if (i) + if (r) { + var n = Qe.bin2str(r.subarray(4, 8)); + if ("aac " === Qe.bin2str(i.subarray(0, 4)) && (me.types || me.init(), + i.set(me.types.mp4a, 0)), + "cbcs" === n || "cenc" === n) { + f && f.push(t); + const e = Qe.findBox(t, ["schi", "tenc"])[0]; + if (e) { + const h = 8; + e.subarray(8, 24), + e.set(m, 8); + const f = e[6] + , t = e[7]; + if (1 === f && 0 === t) { + const h = e[24]; + 0 < h && p.iv && h === p.iv.length && e.set(p.iv, 25) + } + } + } else if ("cbc2" === n) { + u = !0, + me.types || me.init(); + const h = Qe.findBoxWithOffset(t, 0, ["frma"])[0] + , f = me.box(me.types.schi, me.tenc(p, d)) + , m = me.box(me.types.sinf, t.subarray(h.offset, h.boxSize), me.schm(), f); + a = me.box(me.types.trak, o.subarray(0, e.offset), m, o.subarray(e.offset + e.boxSize)); + const i = a.subarray(8) + , r = m.byteLength - e.boxSize; + l.walkedPath && (l.walkedPath.push({ + type: "stsd", + offset: s.offset, + size: s.boxSize + }), + l.walkedPath.forEach(e=>{ + Qe.writeUint32(i, e.offset, e.size + r) + } + )) + } + } else + h.error(Ge, "missing schm box"); + else + h.error(Ge, "missing frma box") + } + ), + a = a || c.subarray(t.offset, t.offset + t.boxSize), + g.push(a) + } + ); + var s = Qe.findBoxWithOffset(o, 0, ["edts"])[0]; + s && (me.types || me.init(), + o.set(me.types.free, s.offset + 4)) + } + ), + u) { + const p = We.remuxCbc2InitSegment(c, g, h); + e = p || c + } + } + return e + } + static remuxCbc2InitSegment(i, r, n) { + const s = Qe.findBoxWithOffset(i, 0, ["ftyp"])[0]; + if (s) { + const a = Qe.findBoxWithOffset(i, s.boxSize, ["moov"])[0]; + let e = [] + , t = 0; + for (; t < a.data.byteLength; ) { + const i = Qe.readUint32(a.data, t) + , n = Qe.bin2str(a.data.subarray(t + 4, t + 8)) + , s = 1 < i ? t + i : a.data.byteLength; + "trak" === n ? r && (e = e.concat(r), + r = void 0) : e.push(a.data.subarray(t, s)), + t = s + } + const o = me.box(me.types.moov, ...e) + , d = new Uint8Array(s.boxSize + o.byteLength); + return d.set(i.subarray(0, s.boxSize)), + d.set(o, s.boxSize), + d + } + n.error(Ge, "no ftyp found") + } + static remuxOverflowSegment(i, e) { + me.types || me.init(); + const t = Qe.findBoxWithOffset(i, 0, ["moof", "traf", "tfdt"], []); + let r, n = i.byteLength; + if (t.forEach(e=>{ + 0 === e.data[0] && (n += 4) + } + ), + n > i.byteLength) { + r = new Uint8Array(n); + let e = 0 + , t = 0; + for (; t < i.byteLength; ) { + const n = Qe.readUint32(i, t) + , s = Qe.bin2str(i.subarray(t + 4, t + 8)) + , a = 1 < n ? t + n : i.byteLength; + if ("moof" === s) { + const n = We.remuxOverflowMoof(i.subarray(t + 8, a)); + r.set(n, e), + e += n.byteLength + } else + r.set(i.subarray(t, a), e), + e += n; + t = a + } + } else + e.warn(Ge, "no increase in size"); + return r || i + } + static remuxOverflowMoof(e) { + let t = 0; + const i = []; + for (; t < e.byteLength; ) { + const r = Qe.readUint32(e, t); + if ("traf" === Qe.bin2str(e.subarray(t + 4, t + 8))) { + const s = We.remuxOverflowTraf(e.subarray(t + 8, t + r)); + i.push(s) + } else + i.push(e.subarray(t, t + r)); + t = 1 < r ? t + r : e.byteLength + } + const r = me.box(me.types.moof, ...i) + , s = r.byteLength - e.byteLength - 8; + return Qe.findBoxWithOffset(r, 0, ["moof", "traf", "trun"], []).forEach(e=>{ + var t; + 0 != (1 & e.data[3]) && (t = Qe.readUint32(e.data, 8), + Qe.writeUint32(e.data, 8, t + s)) + } + ), + Qe.findBoxWithOffset(r, 0, ["moof", "traf", "saio"], []).forEach(t=>{ + const i = 1 & t.data[0]; + let r = 4; + 1 & t.data[3] && (r += 8); + var n = Qe.readUint32(t.data, r); + if (r += 4, + i) + for (let e = 0; e < n; e++) { + const i = Qe.readUint64(t.data, r); + Qe.writeUint64(t.data, r, i + s), + r += 8 + } + else + for (let e = 0; e < n; e++) { + const i = Qe.readUint32(t.data, r); + Qe.writeUint32(t.data, r, i + s), + r += 4 + } + } + ), + r + } + static remuxOverflowTraf(e) { + let t = 0; + const i = []; + for (; t < e.byteLength; ) { + var r, n = Qe.readUint32(e, t); + "tfdt" === Qe.bin2str(e.subarray(t + 4, t + 8)) && 0 === e[t + 8] ? (r = Qe.readUint32(e, t + 12), + r = me.box(me.types.tfdt, new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0, r >> 24, r >> 16 & 255, r >> 8 & 255, 255 & r])), + i.push(r)) : i.push(e.subarray(t, t + n)), + t = 1 < n ? t + n : e.byteLength + } + return me.box(me.types.traf, ...i) + } + remuxText(e, t) { + e.captionSamples.sort(function(e, t) { + return e.pts - t.pts + }), + e.captionSamples.length && (t.captionData || (t.captionData = {}), + t.captionData.mp4 = e.captionSamples), + e.captionSamples = [] + } + remuxIFrame(e, t, i, r, n) { + if (!t.samples || !t.samples.length || !t.samples[0].data) + return null; + let s; + const a = me.moof(e * t.timescale, t) + , o = new Uint8Array(a.byteLength + t.samples[0].data.byteLength + 8); + o.set(a), + Qe.writeUint32(o, a.byteLength, t.samples[0].data.byteLength + 8), + o.set(me.types.mdat, a.byteLength + 4), + o.set(t.samples[0].data, a.byteLength + 8), + t.sequenceNumber++; + var d = t.timescale + , l = B(e + r, d) + , d = B(e, d); + let u, c; + u = i ? (s = "audiovideo", + i.sequenceNumber = t.sequenceNumber, + t.sequenceNumber++, + c = be.getSegment(i, i.sequenceNumber, e * i.info.timescale, r), + y(c.endTs, l)) : (s = "video", + l); + n = { + data1: o, + data2: null == c ? void 0 : c.silentFragData, + startPTS: d, + startDTS: d, + endPTS: u, + endDTS: u, + type: s, + dropped: 0, + track: n + }; + this.observer.trigger(v.FRAG_PARSING_DATA, n), + this.observer.trigger(v.FRAG_PARSED) + } + remuxRawData(e, t, i, r, n, s, a, o, d) { + let l; + t && r ? l = "audiovideo" : t ? l = "audio" : r && (l = "video"); + const u = Math.max(i, e) + , c = { + data1: o, + track: d, + startPTS: B(s, a), + startDTS: B(s, a), + endPTS: void 0, + endDTS: void 0, + type: l, + dropped: 0 + }; + return u && (c.endPTS = B(s + u, a), + c.endDTS = B(s + u, a)), + n && n.captionSamples.length && this.remuxText(n, c), + this.observer.trigger(v.FRAG_PARSING_DATA, c), + this.observer.trigger(v.FRAG_PARSED), + c + } + remuxEmsg(e, t, i, r, n, s, a) { + let o = ""; + e && (o += "audio"), + t && (o += "video"); + n = B(r, n), + a = { + data1: s, + startPTS: n, + startDTS: n, + endPTS: void 0, + endDTS: void 0, + type: o, + dropped: 0, + track: a + }; + return i && 0 < i.id3Samples.length && this.remuxID3(i, a), + this.observer.trigger(v.FRAG_PARSING_DATA, a), + this.observer.trigger(v.FRAG_PARSED), + a + } + remuxID3(t, e) { + let i; + var r = t.id3Samples.length; + if (r) { + for (let e = 0; e < r; e++) + i = t.id3Samples[e], + i.pts = i.pts - 10, + i.dts = i.dts - 10; + e.id3Samples = [...t.id3Samples] + } + t.id3Samples = [] + } + } + const ze = Math.pow(2, 32) - 1 + , Xe = Math.pow(2, 20) - 1 + , Ye = { + name: "MP4Demuxer" + }; + class Je extends u { + constructor(e, t, i, r, n) { + super(e, t, i, {}, n), + this.mp4Remuxer = t, + this.audioPrimingDelay = i.audioPrimingDelay + } + resetTimeStamp(e) { + ne(e) ? this.initData.audio && !this.initData.video ? this.initPtsTs = { + baseTime: Math.round(e * this.initData.audio.timescale / 9e4), + timescale: this.initData.audio.timescale + } : this.initPtsTs = { + baseTime: e, + timescale: 9e4 + } : this.initPtsTs = void 0 + } + static isHEVCFlavor(e) { + if (!e) + return !1; + var t = e.indexOf(".") + , t = t < 0 ? e : e.substring(0, t); + return "hvc1" === t || "hev1" === t || "chvc" === t || "qhvc" === t || "qhev" === t || "muxa" === t || "dvh1" === t || "dvhe" === t || "cdh1" === t || "qdh1" === t || "qdhe" === t + } + resetInitSegment(t, i, r) { + if (this._silentAudioTrack = void 0, + t && t.byteLength) { + var n = We.remuxInitSegment(t, this.logger, r) + , s = this.initData = Je.parseInitSegment(n); + let e; + s.foundLargeTimescale && this.logger.warn(Ye, "large timescale found, will check for 32 bit tfdts"); + var a = s.audioCodec + , r = s.videoCodec; + if (s.audio && s.video ? e = { + type: "audiovideo", + container: "video/mp4", + codec: a + "," + r, + initSegment: n + } : (s.audio && a && (e = { + type: "audio", + container: "audio/mp4", + codec: a, + initSegment: n + }), + s.video && r && (e = { + type: "video", + container: "video/mp4", + codec: r, + initSegment: n + })), + s.video) { + const o = s.video + , d = t.subarray(o.trakOffset, o.trakOffset + o.trakSize); + this._videoTrack = Object.assign(Object.assign({}, o), { + info: { + id: o.id, + timescale: o.timescale, + duration: i + }, + trakData: d, + sequenceNumber: 0, + samples: [] + }), + this.trySEICaptions = !Se.isVP09(r), + this._captionTrack = Object.assign(Object.assign({}, s.caption), { + sequenceNumber: 0, + captionSamples: [] + }) + } + s.audio && a && (this._audioTrack = Object.assign({}, s.audio)), + s.caption && (this.trySEICaptions = !1, + this._captionTrack = Object.assign(Object.assign({}, s.caption), { + sequenceNumber: 0, + captionSamples: [] + })), + this.remuxedInitDataTrack = e; + s = { + track: e + }; + this.observer.trigger(v.FRAG_PARSING_INIT_SEGMENT, s) + } + } + static probe(e, t) { + return 0 < Qe.findBox(e.subarray(0, Math.min(e.length, 512e3)), ["moof"]).length + } + static parseHvcC(e) { + let t; + var i, r; + return e ? 1 === (i = e[0]) ? (r = e[1], + t = { + profileSpace: r >> 6, + tierFlag: (32 & r) >> 5 ? "H" : "L", + profileIDC: 31 & r, + profileCompat: Qe.readUint32(e, 2), + constraintIndicator: e.subarray(6, 12), + levelIDC: e[12] + }) : qe().warn(Ye, `Unhandled version ${i} in hvcC box`) : qe().warn(Ye, "No hvcC box"), + t + } + static hvcCToCodecString(t, i) { + const r = t + "." + (i.profileSpace ? String.fromCharCode(i.profileSpace + "A" - 1) : "") + i.profileIDC + "." + i.profileCompat.toString(16).toUpperCase() + "." + i.tierFlag + i.levelIDC; + let n = ""; + for (let e = i.constraintIndicator.length - 1; 0 <= e; --e) { + const r = i.constraintIndicator[e]; + if (0 !== r || "" !== n) { + const t = r.toString(16).toUpperCase(); + n = "." + ("" === n ? t : t + n) + } + } + return r + n + } + static parseDvcC(e) { + let t; + return e ? t = { + versionMajor: e[0], + versionMinor: e[1], + profile: e[2] >> 1 & 127, + level: e[2] << 5 & 32 | e[3] >> 3 & 31 + } : qe().warn(Ye, "No dvcC box"), + t + } + static dvcCToCodecString(e, t) { + return e + "." + (t.profile < 10 ? "0" + t.profile : t.profile) + "." + (t.level < 10 ? "0" + t.level : t.level) + } + static parseVpcC(e) { + let t; + return e ? t = { + profile: e[4], + level: e[5], + bitDepth: e[6] >> 4 & 15 + } : qe().warn(Ye, "No vpcC box"), + t + } + static vpcCToCodecString(e, t) { + return e + "." + (t.profile < 10 ? "0" + t.profile : t.profile) + "." + (t.level < 10 ? "0" + t.level : t.level) + "." + t.bitDepth + } + static parseInitSegment(e) { + const c = { + foundLargeTimescale: !1, + tracksById: {} + }; + return Qe.findBoxWithOffset(e, 0, ["moov", "trak"]).forEach(t=>{ + const i = t.data + , r = Qe.findBox(i, ["tkhd"])[0]; + if (r) { + var n = 0 === (a = r[0]) ? 12 : 20 + , s = Qe.readUint32(r, n) + , e = Qe.findBox(i, ["mdia", "mdhd"])[0]; + if (e) { + var a, o = 0 === (a = e[0]) ? 12 : 20, n = Qe.readUint32(e, o); + o += 4, + 1e6 <= n && (c.foundLargeTimescale = !0); + const d = 0 === a ? Qe.readUint32(e, o) : 0 + , l = Qe.findBox(i, ["mdia", "hdlr"])[0]; + if (l) { + const r = Qe.bin2str(l.subarray(8, 12)) + , u = { + soun: "audio", + vide: "video", + clcp: "caption" + }[r] || r; + if (u) { + const r = Qe.findBox(i, ["mdia", "minf", "stbl", "stsd"]); + if (r.length) { + const i = r[0]; + Qe.bin2str(i.subarray(12, 16)); + o = Je.parseStsd(i); + let e; + if ("caption" === u) { + const t = Object.assign({ + id: s, + type: u, + timescale: n, + duration: d, + isTimingTrack: !1, + sequenceNumber: 0, + captionSamples: [] + }, o); + c.caption = t, + e = t + } else { + const i = Object.assign({ + id: s, + type: u, + timescale: n, + duration: d, + isTimingTrack: !0, + trakOffset: t.offset, + trakSize: t.boxSize, + sequenceNumber: 0, + samples: [], + fragmentDuration: 0 + }, o); + "video" === u ? (c.video = i, + c.videoCodec = i.codec) : (c.audio = i, + c.audioCodec = i.codec), + e = i + } + c.tracksById[s] = e + } + } + } + } + } + } + ), + Qe.findBoxWithOffset(e, 0, ["moov", "mvex", "trex"]).forEach(e=>{ + var t = e.data + , e = Qe.readUint32(t, 4) + , t = Qe.readUint32(t, 16); + c.tracksById[e].defaultSampleSize = t + } + ), + c + } + static parseStsd(e) { + let r, t; + const i = e.subarray(8); + let n = Qe.bin2str(i.subarray(4, 8)) + , s = null + , a = null; + "enca" === n ? (s = Qe.findBox(i, ["enca"])[0], + a = s.subarray(28)) : "encv" === n && (s = Qe.findBox(i, ["encv"])[0], + a = s.subarray(78)); + e = !!a; + r = 0, + a && Qe.findBox(a, ["sinf"]).forEach(e=>{ + const t = Qe.findBox(e, ["schm"])[0]; + if (t) { + var i = Qe.bin2str(t.subarray(4, 8)); + if ("cbcs" === i || "cenc" === i) { + const t = Qe.findBox(e, ["frma"])[0]; + t && (n = Qe.bin2str(t)); + e = Qe.findBox(e, ["schi", "tenc"])[0]; + e && (r = e[7]) + } + } + } + ); + let o; + var d = i.subarray(86); + switch (n) { + case "mp4a": + t = "mp4a.40.5"; + break; + case "ac-3": + case "ec-3": + case "alac": + case "fLaC": + t = n; + break; + case "avc1": + case "avc3": + t = n + ".640028"; + break; + case "hvc1": + case "hev1": + const l = Qe.findBox(d, ["hvcC"])[0]; + o = Je.parseHvcC(l), + t = o ? Je.hvcCToCodecString(n, o) : n + ".2.4.H150.B0"; + break; + case "dvh1": + case "dvhe": + const r = Qe.findBox(d, ["dvcC"])[0]; + o = Je.parseDvcC(r), + t = o ? Je.dvcCToCodecString(n, o) : n + ".05.01"; + break; + case "c608": + t = n; + break; + case "vp09": + const i = Qe.findBox(d, ["vpcC"])[0]; + o = Je.parseVpcC(i), + t = Je.vpcCToCodecString(n, o); + break; + default: + t = n + } + return { + codec: t, + encrypted: e, + defaultPerSampleIVSize: r + } + } + static has32BitTfdts(e) { + const t = Qe.findBox(e, ["moof", "traf", "tfdt"]); + let i = !1; + return t.forEach(e=>{ + 0 === e[0] && (i = !0) + } + ), + i + } + static getStartDtsTs(r, e) { + const t = Qe.findBox(e, ["moof", "traf"]); + let n, s = Number.MAX_SAFE_INTEGER; + return t.map(function(i) { + return Qe.findBox(i, ["tfhd"]).forEach(e=>{ + var t = Qe.readUint32(e, 4) + , e = r.tracksById[t]; + if (e) { + if (!e.isTimingTrack) + return 1 / 0; + t = e.timescale || 9e4, + e = Qe.findBox(i, ["tfdt"]).map(function(e) { + let t; + var i = e[0]; + return t = Qe.readUint32(e, 4), + 1 === i && (t > Xe && qe().warn(Ye, `Value larger than can be represented by float for upper 32 bits ${t}`), + t *= Math.pow(2, 32), + t += Qe.readUint32(e, 8)), + t + }), + e = 0 < e.length ? e[0] : 1 / 0; + isFinite(e) && e / t < s && (s = e / t, + n = { + baseTime: e, + timescale: t + }) + } + } + ) + }), + n + } + static offsetStartDTS(r, e, d, n) { + Qe.findBox(e, ["moof", "traf"]).map(function(i) { + return Qe.findBox(i, ["tfhd"]).map(function(e) { + const t = Qe.readUint32(e, 4) + , s = r.tracksById[t]; + if (s) { + const a = s.timescale || 9e4 + , o = "caption" === s.type ? 0 : n; + Qe.findBox(i, ["tfdt"]).map(function(t) { + const i = t[0] + , r = s.type; + if (0 === i) { + let e = Qe.readUint32(t, 4) - Math.round(d.baseTime * a / d.timescale); + "video" === r && e < 0 && (qe().warn(Ye, `video tdft would have gone negative by ${e / a} seconds`), + e = 0), + e += Math.round(o * a), + e = Math.max(e, 0), + Qe.writeUint32(t, 4, e) + } else { + const i = Qe.readUint32(t, 4); + i > Xe && qe().error(Ye, `baseMediaDecodeTime larger than can be represented by float for upper 32 bits ${i}`); + let e = i; + e *= Math.pow(2, 32), + e += Qe.readUint32(t, 8), + e -= Math.round(d.baseTime * a / d.timescale), + "video" === r && e < 0 && (qe().warn(Ye, `video tdft would have gone negative by ${e / a} seconds`), + e = 0), + e += Math.round(o * a), + e = Math.max(e, 0); + const n = Math.floor(e / (1 + ze)) + , s = Math.floor(e % (1 + ze)); + Qe.writeUint32(t, 4, n), + Qe.writeUint32(t, 8, s) + } + }) + } + }) + }) + } + static writeStartDTS(i, e, s) { + Qe.findBox(e, ["moof", "traf"]).map(function(t) { + return Qe.findBox(t, ["tfhd"]).map(function(e) { + e = Qe.readUint32(e, 4), + e = i.tracksById[e]; + if (e) { + const r = e.timescale || 9e4 + , n = Math.round(s * r) / r; + .01 < Math.abs(n - s) && qe().warn(Ye, `[iframes] large rounding error when adjusting timestamps, startDTS: ${s}, roundedStartDTS: ${n}`), + Qe.findBox(t, ["tfdt"]).map(function(e) { + var t, i; + 0 === e[0] ? Qe.writeUint32(e, 4, n * r) : (i = n * r, + i = Math.max(i, 0), + t = Math.floor(i / (1 + ze)), + i = Math.floor(i % (1 + ze)), + Qe.writeUint32(e, 4, t), + Qe.writeUint32(e, 8, i)) + }) + } + }) + }) + } + static parseSAIO(e) { + let t = 0 + , i = 0; + var r = e[0]; + i += 4, + 0 != (1 & Qe.readUint32(e, 0)) && (i += 8); + var n = 16777215 & Qe.readUint32(e, i); + return 1 == n ? (i += 4, + t = Qe.readUint32(e, i), + 1 === r && (i += 4, + t *= Math.pow(2, 32), + t += Qe.readUint32(e, i))) : qe().error(Ye, `saio entry count error, count is: ${n}`), + t + } + static parseSAIZ(e) { + let t = 0 + , i = 0; + return i += 4, + 0 != (1 & Qe.readUint32(e, 0)) && (i += 8), + t = e[i], + i++, + i += 4, + 0 === t && (t = e[i]), + t + } + static parseSubsample(e, t) { + const i = { + subsamples: [] + }; + let r = 0; + for (e && (i.iv = t.subarray(0, e), + r += e), + r += 2; r + 6 <= t.byteLength; ) { + const e = Qe.readUint16(t, r); + r += 2; + var n = Qe.readUint32(t, r); + r += 4, + i.subsamples.push([e, n]) + } + return i + } + static isSEIMessage(e, t) { + return e ? 39 === t || 40 === t : 6 === t + } + static parseCLCPSample(e, t, i) { + let r = 0; + const n = []; + let s = 0; + for (; r < i; ) { + var a = t + r + , o = Qe.readUint32(e, a); + a += 4; + var d = Qe.bin2str(e.subarray(a, a + 4)); + if (a += 4, + "cdat" !== d) + break; + { + const t = o - 8 + , l = e.subarray(a, a + t); + s += t, + n.push(l), + r += o + } + } + return { + cdatList: n, + cdatTotalSize: s + } + } + static parseSamples(e, S, b, T, E, I) { + const w = b.timescale + , l = b.id; + let A, O = e, k = 0, C = !1; + Qe.findBoxWithOffset(S, 0, ["moof"]).map(function(e) { + const t = e.data + , v = e.offset; + Qe.findBox(t, ["traf"]).map(function(d) { + var e = Qe.findBox(d, ["tfdt"]).map(function(e) { + let t; + var i = e[0]; + return t = Qe.readUint32(e, 4), + 1 === i && (t *= Math.pow(2, 32), + t += Qe.readUint32(e, 8)), + t / w + })[0]; + return void 0 !== e && (O = e), + Qe.findBox(d, ["tfhd"]).map(function(e) { + var t = Qe.readUint32(e, 4) + , i = 16777215 & Qe.readUint32(e, 0) + , r = 0 != (1 & i) + , n = 0 != (2 & i) + , s = 0 != (8 & i); + let g = 0; + var a = 0 != (16 & i); + let y = 0; + i = 0 != (32 & i); + let o = 8; + if (ne(b.defaultSampleSize) && (y = b.defaultSampleSize), + t === l) { + if (r && (Qe.readUint32(e, o), + o += 4, + Qe.readUint32(e, o), + o += 4), + n && (Qe.readUint32(e, o), + o += 4), + s && (g = Qe.readUint32(e, o), + o += 4), + a && (y = Qe.readUint32(e, o), + o += 4), + i && (Qe.readUint32(e, o), + o += 4), + "video" === b.type) { + let t = 0 + , i = 0; + Qe.findBox(d, ["saio"]).map(function(e) { + t = Je.parseSAIO(e) + }), + Qe.findBox(d, ["saiz"]).map(function(e) { + i = Je.parseSAIZ(e) + }), + t && i && (A = Je.parseSubsample(b.defaultPerSampleIVSize, S.subarray(t, t + i))), + C = Je.isHEVCFlavor(b.codec) + } + Qe.findBox(d, ["trun"]).map(function(i) { + var t = i[0] + , e = 16777215 & Qe.readUint32(i, 0) + , r = 0 != (1 & e); + let n = 0; + var s = 0 != (4 & e) + , a = 0 != (256 & e); + let o = 0; + var d = 0 != (512 & e); + let l = 0; + var u = 0 != (1024 & e) + , c = 0 != (2048 & e); + let h = 0; + var p = Qe.readUint32(i, 4); + let f = 8; + r && (n = Qe.readUint32(i, f), + f += 4), + s && (f += 4); + let m = n + v; + for (let e = 0; e < p && (I < 0 || k < I); e++) { + if (a ? (o = Qe.readUint32(i, f), + f += 4) : o = g, + d ? (l = Qe.readUint32(i, f), + f += 4) : l = y, + u && (f += 4), + c && (h = 0 === t ? Qe.readUint32(i, f) : Qe.readSint32(i, f), + f += 4), + "video" === b.type) { + if (ne(T)) + b.samples.push({ + data: S.subarray(m, m + l), + size: l, + duration: T * w, + cts: 0, + flags: { + isLeading: 0, + isDependedOn: 0, + hasRedundancy: 0, + degradPrio: 0, + dependsOn: 2, + isNonSync: 0, + paddingValue: 0 + }, + subsamples: A ? A.subsamples : [], + iv: A ? A.iv : void 0 + }); + else if (b.fragmentDuration += o, + E) { + let e = 0; + for (; e < l; ) { + const T = Qe.readUint32(S, m); + m += 4; + const E = 31 & S[m]; + if (b.seiSamples || (b.seiSamples = []), + Je.isSEIMessage(C, E)) { + const i = S.subarray(m, m + T); + b.seiSamples.push({ + pts: O + h / w, + type: E, + data: i, + sampleOffset: m, + naluSize: T + }) + } + m += T, + e += T + 4 + } + } + } else if ("audio" === b.type) + b.fragmentDuration += o; + else if ("caption" === b.type) { + const {cdatList: i, cdatTotalSize: T} = Je.parseCLCPSample(S, m, l); + if (m += l, + i.length) { + let t; + if (1 === i.length) + t = new Uint8Array(i[0]); + else if (1 < i.length) { + let e = 0; + t = new Uint8Array(T); + for (const T of i) + t.set(T, e), + e += T.length + } + b.captionSamples.push({ + type: 3, + pts: O, + bytes: t + }) + } + } + k++, + O += o / w + } + }) + } + }) + }) + }) + } + static parseEmsg(e) { + let t, i, r, n, s, a = "", o = "", d = 0; + if (0 === e[0]) { + for (; "\0" !== Qe.bin2str(e.subarray(d, d + 1)); ) + a += Qe.bin2str(e.subarray(d, d + 1)), + d += 1; + for (a += Qe.bin2str(e.subarray(d, d + 1)), + d += 1; "\0" !== Qe.bin2str(e.subarray(d, d + 1)); ) + o += Qe.bin2str(e.subarray(d, d + 1)), + d += 1; + o += Qe.bin2str(e.subarray(d, d + 1)), + d += 1, + t = Qe.readUint32(e, 12), + i = Qe.readUint32(e, 16), + n = Qe.readUint32(e, 20), + s = Qe.readUint32(e, 24), + d = 28 + } else { + d += 4, + t = Qe.readUint32(e, d), + d += 4; + const i = Qe.readUint32(e, d); + d += 4; + var l = Qe.readUint32(e, d); + for (d += 4, + r = Math.pow(2, 32) * i + l, + Number.isSafeInteger(r) || (r = Number.MAX_SAFE_INTEGER, + qe().warn(Ye, "Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")), + n = Qe.readUint32(e, d), + d += 4, + s = Qe.readUint32(e, d), + d += 4; "\0" !== Qe.bin2str(e.subarray(d, d + 1)); ) + a += Qe.bin2str(e.subarray(d, d + 1)), + d += 1; + for (a += Qe.bin2str(e.subarray(d, d + 1)), + d += 1; "\0" !== Qe.bin2str(e.subarray(d, d + 1)); ) + o += Qe.bin2str(e.subarray(d, d + 1)), + d += 1; + o += Qe.bin2str(e.subarray(d, d + 1)), + d += 1 + } + return { + schemeIdUri: a, + value: o, + timeScale: t, + presentationTime: r, + presentationTimeDelta: i, + eventDuration: n, + id: s, + payload: e.subarray(d, e.byteLength) + } + } + static extractID3PayloadCreateID3Track(e, t, i, r) { + const n = new M(e.payload,r) + , s = new Uint8Array(e.payload) + , a = s.byteLength; + let o = 0 + , d = 0; + var l = ne(e.presentationTime) ? e.presentationTime / e.timeScale : t + e.presentationTimeDelta / e.timeScale; + if (ne(l)) { + const c = e.eventDuration + , h = s.subarray(0, 10) + , p = Qe.bin2str(h.subarray(d, d + 3)); + d += 3, + "ID3" !== p && qe().error(Ye, "No ID3 tag found when extracting ID3 payload"), + d += 2; + var t = s.subarray(d, d + 1) + , e = 64 & t[0] + , u = 16 & t[0]; + if (d += 1, + M.readSynchSafeUint32(s.subarray(d, d + 4)), + d += 4, + e) { + const f = M.readSynchSafeUint32(s.subarray(d, d + 4)); + d += 4, + d += f + } + for (; d + 2 < a; ) { + Qe.bin2str(s.subarray(d, d + 4)), + d += 4; + const m = M.readSynchSafeUint32(s.subarray(d, d + 4)); + d += 4; + const r = l + o * c + , a = { + data: s, + pts: r, + dts: r, + keyTagInfo: void 0, + frames: n.frames + }; + i.id3Samples.push(a), + d += m, + o++, + u && ("DI3" !== Qe.bin2str(s.subarray(d, d + 3)) && qe().error(Ye, "End should be DI3 if footer present in extracting ID3 payload"), + d += 3, + d += 7) + } + d + 2 === a && 0 !== Qe.readUint16(s, d) && qe().warn(Ye, "Padding should be 0 when extracting ID3 payload") + } else + qe().error(Ye, "No pts found in emsg info when extracting ID3 payload") + } + append(e, t, i, r, n, s, a) { + let o = this.initData + , d = 0 + , l = 0 + , u = !1 + , c = !1; + void 0 === o && (this.resetInitSegment(e, 0), + o = this.initData); + let h, p = this.initPtsTs; + p || (h = Je.getStartDtsTs(o, e), + this.initPtsTs = p = { + baseTime: h.baseTime - Math.round(t * h.timescale), + timescale: h.timescale + }, + this.observer.trigger(v.INIT_PTS_FOUND, { + initPTS: p + })), + o.foundLargeTimescale && Je.has32BitTfdts(e) && !a && (e = We.remuxOverflowSegment(e, this.logger)), + h = Je.getStartDtsTs(o, e); + const f = Qe.findBox(e, ["emsg"]); + if (o.video && o.video.encrypted && (Qe.findBox(e, ["moof", "traf"]).find(function(e) { + return Boolean(Qe.findBox(e, ["senc"])[0] || Qe.findBox(e, ["saiz"])[0] && Qe.findBox(e, ["saio"])[0]) + }) || this.logger.warn(Ye, `Missing subsample information for encrypted content codec=${o.videoCodec}`)), + a) { + const t = this._videoTrack.timescale; + a = Math.ceil(a * t) / t; + const i = (h.baseTime + this.audioPrimingDelay * h.timescale) / h.timescale; + if (this._videoTrack && this._audioTrack && !this._silentAudioTrack) { + const e = be.getTrack(this.observer, this._audioTrack.id, this._audioTrack.codec, 2, this.logger); + if (!e) + throw `unable to create silent audio track for codec ${this._audioTrack.codec}`; + this._silentAudioTrack = Object.assign(Object.assign({}, e), { + sequenceNumber: 0 + }); + const t = me.initSegment([this._videoTrack, this._silentAudioTrack]); + this.remuxedInitDataTrack = { + type: "audiovideo", + container: "video/mp4", + codec: this._silentAudioTrack.config.codec + "," + this._videoTrack.codec, + initSegment: t + }; + const i = { + track: this.remuxedInitDataTrack + }; + this.observer.trigger(v.FRAG_PARSING_INIT_SEGMENT, i) + } + Je.parseSamples(i, e, this._videoTrack, a, !1, 1), + this.mp4Remuxer.remuxIFrame(i, this._videoTrack, this._silentAudioTrack, a, this.remuxedInitDataTrack), + this._videoTrack.samples = [] + } else if (f && 0 < f.length) { + var m = (h.baseTime - this.audioPrimingDelay * h.timescale) / h.timescale + , m = Math.max(0, m); + const r = f.map(e=>{ + e = Je.parseEmsg(e); + return "https://aomedia.org/emsg/ID3\0" !== e.schemeIdUri || this._id3Track || (this._id3Track = { + id3Samples: [], + inputTimescale: 9e4 + }), + e + } + ); + this._id3Track && r.map(e=>{ + Je.extractID3PayloadCreateID3Track(e, t, this._id3Track, this.logger) + } + ), + this.mp4Remuxer.remuxEmsg(!!o.audio, !!o.video, this._id3Track, m, h.timescale, e, this.remuxedInitDataTrack), + this._id3Track && (this._id3Track.id3Samples = []) + } else { + m = (h.baseTime - this.audioPrimingDelay * h.timescale) / h.timescale, + m = Math.max(0, m); + this._videoTrack && (Je.parseSamples(m, e, this._videoTrack, void 0, this.trySEICaptions, -1), + d = this._videoTrack.fragmentDuration / this._videoTrack.timescale, + u = !0, + this._videoTrack.fragmentDuration = 0, + this.trySEICaptions ? (Je.extractSEICaptionsFromNALu(this._videoTrack.seiSamples, this._captionTrack), + this._videoTrack.seiSamples = []) : this._captionTrack && Je.parseSamples(m, e, this._captionTrack, void 0, !1, Number.MAX_SAFE_INTEGER)), + this._audioTrack && (Je.parseSamples(m, e, this._audioTrack, void 0, !1, -1), + l = this._audioTrack.fragmentDuration / this._audioTrack.timescale, + c = !0, + this._audioTrack.fragmentDuration = 0), + this.mp4Remuxer.remuxRawData(l, c, d, u, this._captionTrack, m, h.timescale, e, this.remuxedInitDataTrack) + } + } + static extractSEICaptionsFromNALu(a, o) { + if (a) { + for (let s = 0; s < a.length; ++s) { + var d = a[s] + , l = d.pts; + let t = 0; + t++; + let e = 0 + , i = 0 + , r = !1 + , n = 0; + for (; !r && t < d.data.length; ) { + for (e = 0; !(t >= d.data.length) && (n = d.data[t++], + e += n, + 255 === n); ) + ; + for (i = 0; !(t >= d.data.length) && (n = d.data[t++], + i += n, + 255 === n); ) + ; + const a = d.data.length - t; + if (4 === e && t < d.data.length) { + if (r = !0, + 181 === d.data[t++]) { + const a = Qe.readUint16(d.data, t); + if (t += 2, + 49 === a) { + const a = Qe.readUint32(d.data, t); + if (t += 4, + 1195456820 === a && 3 === d.data[t++]) { + const a = d.data[t++]; + t++; + const u = 31 & a + , c = []; + if (64 & a) + for (let e = 0; e < u; e++) { + const a = d.data[t++]; + if (a === (252 & a)) { + const o = 3 & a; + if (0 == o || 1 == o) { + const a = d.data[t++] + , o = d.data[t++]; + c.push(a), + c.push(o) + } + } else + t += 2 + } + 0 < c.length && o.captionSamples.push({ + type: 3, + pts: l, + bytes: c + }) + } + } + } + } else if (i < a) + t += i; + else if (i > a) + break + } + } + return o + } + } + } + const Ze = { + name: "ExpGolomb" + }; + class et { + constructor(e, t) { + this.data = e, + this.logger = t, + this._bytesAvailable = e.byteLength, + this.word = 0, + this.bitsAvailable = 0 + } + get bytesAvailable() { + return this._bytesAvailable + } + loadWord() { + const e = this.data + , t = this._bytesAvailable + , i = e.byteLength - t + , r = new Uint8Array(4) + , n = Math.min(4, t); + if (0 === n) + throw new Error("no bytes available"); + r.set(e.subarray(i, i + n)), + this.word = new DataView(r.buffer).getUint32(0), + this.bitsAvailable = 8 * n, + this._bytesAvailable -= n + } + skipBits(e) { + var t; + this.bitsAvailable > e || (t = (e -= this.bitsAvailable) >> 3, + e -= t >> 3, + this._bytesAvailable -= t, + this.loadWord()), + this.word <<= e, + this.bitsAvailable -= e + } + readBits(e) { + let t = Math.min(this.bitsAvailable, e); + var i = this.word >>> 32 - t; + return 32 < e && this.logger.error(Ze, "Cannot read more than 32 bits at a time"), + this.bitsAvailable -= t, + 0 < this.bitsAvailable ? this.word <<= t : 0 < this._bytesAvailable && this.loadWord(), + t = e - t, + 0 < t && this.bitsAvailable ? i << t | this.readBits(t) : i + } + skipLZ() { + let e; + for (e = 0; e < this.bitsAvailable; ++e) + if (0 != (this.word & 2147483648 >>> e)) + 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() { + var e = this.skipLZ(); + return this.readBits(e + 1) - 1 + } + readEG() { + var e = this.readUEG(); + return 1 & e ? 1 + e >>> 1 : -1 * (e >>> 1) + } + readBoolean() { + return 1 === this.readBits(1) + } + readUByte() { + return this.readBits(8) + } + readUShort() { + return this.readBits(16) + } + readUInt() { + return this.readBits(32) + } + skipScalingList(e) { + let t, i, r = 8, n = 8; + for (t = 0; t < e; t++) + 0 !== n && (i = this.readEG(), + n = (r + i + 256) % 256), + r = 0 === n ? r : n + } + readSPS() { + let e, t, i, r = 0, n = 0, s = 0, a = 0; + const o = this.readUByte.bind(this) + , d = this.readBits.bind(this) + , l = this.readUEG.bind(this) + , u = this.readBoolean.bind(this) + , c = this.skipBits.bind(this) + , h = this.skipEG.bind(this) + , p = this.skipUEG.bind(this) + , f = this.skipScalingList.bind(this); + o(); + var m = o(); + if (d(5), + c(3), + o(), + p(), + 100 === m || 110 === m || 122 === m || 244 === m || 44 === m || 83 === m || 86 === m || 118 === m || 128 === m) { + const e = l(); + if (3 === e && c(1), + p(), + p(), + c(1), + u()) + for (t = 3 !== e ? 8 : 12, + i = 0; i < t; i++) + u() && f(i < 6 ? 16 : 64) + } + p(); + var g = l(); + if (0 === g) + l(); + else if (1 === g) + for (c(1), + h(), + h(), + e = l(), + i = 0; i < e; i++) + h(); + p(), + c(1); + var y = l() + , m = l() + , g = d(1); + 0 === g && c(1), + c(1), + u() && (r = l(), + n = l(), + s = l(), + a = l()); + let v = [1, 1]; + if (u() && u()) + switch (o()) { + case 1: + v = [1, 1]; + break; + case 2: + v = [12, 11]; + break; + case 3: + v = [10, 11]; + break; + case 4: + v = [16, 11]; + break; + case 5: + v = [40, 33]; + break; + case 6: + v = [24, 11]; + break; + case 7: + v = [20, 11]; + break; + case 8: + v = [32, 11]; + break; + case 9: + v = [80, 33]; + break; + case 10: + v = [18, 11]; + break; + case 11: + v = [15, 11]; + break; + case 12: + v = [64, 33]; + break; + case 13: + v = [160, 99]; + break; + case 14: + v = [4, 3]; + break; + case 15: + v = [3, 2]; + break; + case 16: + v = [2, 1]; + break; + case 255: + v = [o() << 8 | o(), o() << 8 | o()] + } + return { + width: Math.ceil(16 * (y + 1) - 2 * r - 2 * n), + height: (2 - g) * (m + 1) * 16 - (g ? 2 : 4) * (s + a), + pixelRatio: v + } + } + readSliceType() { + return this.readUByte(), + this.readUEG(), + this.readUEG() + } + } + const tt = { + name: "TS Demuxer" + }; + var it, rt = class extends c { + constructor(e, t, i, r, n) { + super(e, t, i, r, n) + } + static probe(e, t) { + return 564 <= e.length && 71 === e[0] && 71 === e[188] && 71 === e[376] + } + resetInitSegment(e, t, i) { + this.pmtParsed = !1; + var r = { + id: this._pmtId = -1, + inputTimescale: 9e4, + timescale: NaN, + duration: 0, + encrypted: i && i.isEncrypted, + keyTagInfo: i + } + , i = { + len: 0, + sequenceNumber: 0 + }; + this._avcContext = { + info: Object.assign({}, r), + parsingData: Object.assign(Object.assign({}, i), { + esSamples: new Array, + dropped: 0 + }), + config: {}, + container: "video/mp2t", + type: "video" + }, + this._audioContext = { + info: Object.assign({}, r), + parsingData: Object.assign(Object.assign({}, i), { + esSamples: new Array + }), + container: "video/mp2t", + type: "audio" + }, + this._id3Track = { + id: -1, + inputTimescale: 9e4, + id3Samples: [] + }, + this._txtTrack = { + inputTimescale: 9e4, + captionSamples: [] + }, + this._duration = t, + this._initSegment = e + } + append(e, t, i, r, n, s, a) { + let o, d, l, u, c, h = !1; + this.contiguous = i; + const p = this._avcContext + , f = this._audioContext + , m = this._id3Track; + let g = this.pmtParsed + , y = p.info.id + , v = f.info.id + , S = m.id + , b = this._pmtId + , T = p.pesData + , E = f.pesData + , I = m.pesData; + if (this.iframeMode = void 0 !== a, + this._initSegment && 0 < this._initSegment.byteLength) { + const t = new Uint8Array(this._initSegment.byteLength + e.byteLength); + t.set(this._initSegment), + t.set(e, this._initSegment.byteLength), + this._initSegment = void 0, + 71 === t[0] && (e = t) + } + let w, A, O = e.length; + for (O -= O % 188, + o = 0; o < O; o += 188) { + if (71 !== e[o]) { + const e = new D(!1,"TS packet did not start with 0x47",$.NoTSSyncByteFound); + return void this.observer.trigger(x.INTERNAL_ERROR, e) + } + if (d = !!(64 & e[o + 1]), + l = ((31 & e[o + 1]) << 8) + e[o + 2], + 1 < (48 & e[o + 3]) >> 4) { + if (u = o + 5 + e[o + 4], + u === o + 188) + continue + } else + u = o + 4; + switch (l) { + case y: + d && (T && (c = this._parsePES(T)) && this._parseAVCPES(c, !1), + T = { + data: [], + size: 0, + keyTagInfo: n + }), + T && (T.data.push(e.subarray(u, o + 188)), + T.size += o + 188 - u); + break; + case v: + if (d && !this.iframeMode) { + if (E && (c = this._parsePES(E))) + switch (f.segmentCodec) { + case "aac": + this._parseAACPES(c); + break; + case "mp3": + this._parseMPEGPES(c); + break; + case "ac3": + case "ec3": + this._parseDolbyPES(c) + } + E = { + data: [], + size: 0, + keyTagInfo: n + } + } + E && (E.data.push(e.subarray(u, o + 188)), + E.size += o + 188 - u); + break; + case S: + d && (I && (c = this._parsePES(I)) && m.id3Samples.push(c), + I = { + data: [], + size: 0 + }), + I && (I.data.push(e.subarray(u, o + 188)), + I.size += o + 188 - u); + break; + case 0: + d && (u += e[u] + 1), + b = this._pmtId = this._parsePAT(e, u); + break; + case b: + d && (u += e[u] + 1); + const t = this._parsePMT(e, u, this.typeSupported); + y = t.avcId, + 0 < y && (p.info.id = y, + p.info.encrypted = t.videoEncrypted), + v = t.audioId, + 0 < v && (f.info.id = v, + f.segmentCodec = t.audioSegmentCodec, + f.info.encrypted = t.audioEncrypted), + S = t.id3Id, + 0 < S && (m.id = S), + h && !g && (h = !1, + o = -188), + g = this.pmtParsed = !0; + break; + case 17: + case 8191: + break; + default: + h = !0 + } + } + if (T && (c = this._parsePES(T)) ? (this._parseAVCPES(c, !0), + p.pesData = void 0) : p.pesData = T, + E && (c = this._parsePES(E))) { + switch (f.segmentCodec) { + case "aac": + this._parseAACPES(c); + break; + case "mp3": + this._parseMPEGPES(c); + break; + case "ac3": + case "ec3": + this._parseDolbyPES(c) + } + f.pesData = void 0 + } else + E && E.size && this.logger.warn(tt, "last AAC PES packet truncated,might overlap between fragments"), + f.pesData = E; + I && (c = this._parsePES(I)) ? (m.id3Samples.push(c), + m.pesData = void 0) : m.pesData = I, + f.config && f.segmentCodec && (w = { + type: "audio", + info: f.info, + config: f.config, + parsingData: f.parsingData + }); + var k, C = p.config; + "string" == typeof (k = C).codec && Array.isArray(k.sps) && Array.isArray(k.pps) && "number" == typeof k.width && "number" == typeof k.height && Array.isArray(k.pixelRatio) && (A = { + type: "video", + info: p.info, + config: C, + parsingData: p.parsingData + }), + this.esRemuxer.remuxEsTracks(w, A, m, this._txtTrack, t, i, r, n, s, a) + } + destroy() { + this._duration = 0 + } + _parsePAT(e, t) { + return (31 & e[t + 10]) << 8 | e[t + 11] + } + _parsePMT(e, t, i) { + var r; + const n = { + audioId: -1, + avcId: -1, + id3Id: -1, + audioEncrypted: !1, + videoEncrypted: !1 + } + , s = t + 3 + ((15 & e[t + 1]) << 8 | e[t + 2]) - 4; + for (t += 12 + ((15 & e[t + 10]) << 8 | e[t + 11]); t < s; ) { + switch (r = (31 & e[t + 1]) << 8 | e[t + 2], + e[t]) { + case 207: + n.audioEncrypted = !0; + case 15: + -1 === n.audioId && (n.audioId = r, + n.audioSegmentCodec = "aac"); + break; + case 21: + -1 === n.id3Id && (n.id3Id = r); + break; + case 219: + n.videoEncrypted = !0; + case 27: + -1 === n.avcId && (n.avcId = r); + break; + case 3: + case 4: + !0 !== i.mpeg && !0 !== i.mp3 ? this.logger.warn(tt, "MPEG audio found, not supported in this browser for now") : -1 === n.audioId && (n.audioId = r, + n.audioSegmentCodec = "mp3"); + break; + case 193: + n.audioEncrypted = !0; + case 129: + !0 !== i.ac3 ? this.logger.warn(tt, "AC-3 audio found, not supported in this browser for now") : -1 === n.audioId && (n.audioId = r, + n.audioSegmentCodec = "ac3"); + break; + case 194: + n.audioEncrypted = !0; + case 135: + !0 !== i.ec3 ? this.logger.warn(tt, "EC-3 audio found, not supported in this browser for now") : -1 === n.audioId && (n.audioId = r, + n.audioSegmentCodec = "ec3"); + break; + case 36: + this.logger.warn(tt, "HEVC stream type found, not supported for now"); + break; + default: + this.logger.warn(tt, "unkown stream type:" + e[t]) + } + t += 5 + ((15 & e[t + 3]) << 8 | e[t + 4]) + } + return n + } + _parsePES(e) { + let i, t, r, n, s, a, o = 0; + const d = e.data + , l = e.keyTagInfo; + let u = NaN + , c = NaN; + if (e && 0 !== e.size) { + for (; d[0].length < 19 && 1 < d.length; ) { + const e = new Uint8Array(d[0].length + d[1].length); + e.set(d[0]), + e.set(d[1], d[0].length), + d[0] = e, + d.splice(1, 1) + } + if (i = d[0], + 1 === (i[0] << 16) + (i[1] << 8) + i[2] && (r = (i[4] << 8) + i[5], + !(r && r > e.size - 6))) { + 192 & (t = i[7]) && (u = 536870912 * (14 & i[9]) + 4194304 * (255 & i[10]) + 16384 * (254 & i[11]) + 128 * (255 & i[12]) + (254 & i[13]) / 2, + 64 & t ? (c = 536870912 * (14 & i[14]) + 4194304 * (255 & i[15]) + 16384 * (254 & i[16]) + 128 * (255 & i[17]) + (254 & i[18]) / 2, + 54e5 < u - c && (this.logger.warn(tt, `${Math.round((u - c) / 9e4)}s delta between PTS and DTS, align them`), + u = c)) : c = u), + n = i[8], + a = n + 9, + e.size -= a, + s = new Uint8Array(e.size); + for (let t = 0, e = d.length; t < e; t++) { + i = d[t]; + let e = i.byteLength; + if (a) { + if (a > e) { + a -= e; + continue + } + i = i.subarray(a), + e -= a, + a = 0 + } + s.set(i, o), + o += e + } + return r && (r -= n + 3), + { + data: s, + pts: u, + dts: c, + len: r, + keyTagInfo: l + } + } + } + } + pushAccesUnit(e, t) { + const i = e.avcSample; + if (i && i.units.length && i.frame) { + const r = e.parsingData.esSamples + , n = r.length; + (!0 === i.key || e.config.sps && (n || this.contiguous)) && (i.id = n, + i.keyTagInfo = t, + e.info.encrypted) && i.units.forEach(e=>{ + if (48 < e.data.byteLength) + switch (e.type) { + case 1: + case 5: + e.data = this.discardEPB(e.data) + } + } + ), + n || isFinite(i.pts) ? r.push(i) : e.parsingData.dropped++ + } + } + _parseAVCPES(o, e) { + if (!o.data) + throw "invalid pes data"; + const d = this._avcContext + , t = this._parseAVCNALu(o.data); + let l, u, c, h = d.avcSample; + const p = o.keyTagInfo; + o.data = void 0, + t.forEach(n=>{ + switch (n.type) { + case 1: + if (h && !this.iframeMode) { + u = !0, + h.frame = !0; + const o = n.data; + if (4 < o.length) { + const n = new et(o,this.logger).readSliceType(); + 2 !== n && 4 !== n && 7 !== n && 9 !== n || (h.key = !0) + } + } + break; + case 5: + u = !0, + h && (h = h || (d.avcSample = this._createAVCSample(!0, o.pts, o.dts, "")), + h.key = !0, + h.frame = !0); + break; + case 6: + u = !0, + l = new et(this.discardEPB(n.data),this.logger), + l.readUByte(); + let e = 0 + , t = 0 + , i = !1 + , r = 0; + for (; !i && 1 < l.bytesAvailable; ) { + for (e = 0; r = l.readUByte(), + e += r, + 255 === r; ) + ; + for (t = 0; r = l.readUByte(), + t += r, + 255 === r; ) + ; + if (4 === e && 0 !== l.bytesAvailable) { + if (i = !0, + 181 === l.readUByte() && 49 === l.readUShort() && 1195456820 === l.readUInt() && 3 === l.readUByte()) { + const n = l.readUByte() + , d = 31 & n + , s = [n, l.readUByte()]; + for (c = 0; c < d; c++) + s.push(l.readUByte()), + s.push(l.readUByte()), + s.push(l.readUByte()); + this._insertSampleInOrder(this._txtTrack.captionSamples, { + type: 3, + pts: o.pts, + bytes: s + }) + } + } else if (t < l.bytesAvailable) + for (c = 0; c < t; c++) + l.readUByte() + } + break; + case 7: + if (u = !0, + !d.config.sps) { + l = new et(n.data,this.logger); + const o = l.readSPS(); + d.config.width = o.width, + d.config.height = o.height, + d.config.pixelRatio = o.pixelRatio, + d.config.sps = [n.data], + d.info.duration = this._duration; + const a = n.data.subarray(1, 4); + let t = "avc1."; + for (c = 0; c < 3; c++) { + let e = a[c].toString(16); + e.length < 2 && (e = "0" + e), + t += e + } + d.config.codec = t + } + break; + case 8: + u = !0, + d.config.pps || (d.config.pps = [n.data]); + break; + case 9: + u = !1, + h && this.pushAccesUnit(d, p), + h = d.avcSample = this._createAVCSample(!1, o.pts, o.dts, ""); + break; + case 12: + u = !1; + break; + default: + u = !1, + h && (h.debug += "unknown NAL " + n.type + " ") + } + h && u && h.units.push(n) + } + ), + e && h && (this.pushAccesUnit(d, p), + d.avcSample = void 0) + } + _createAVCSample(e, t, i, r) { + return { + id: NaN, + key: e, + pts: t, + dts: i, + units: new Array, + debug: r + } + } + _insertSampleInOrder(t, i) { + var r = t.length; + if (0 < r) { + if (i.pts >= t[r - 1].pts) + t.push(i); + else + for (let e = r - 1; 0 <= e; e--) + if (i.pts < t[e].pts) { + t.splice(e, 0, i); + break + } + } else + t.push(i) + } + _getLastNalUnit() { + const e = this._avcContext; + let t, i = e.avcSample; + if (!i || 0 === i.units.length) { + const t = e.parsingData.esSamples; + i = t[t.length - 1] + } + if (i) { + const e = i.units; + t = e[e.length - 1] + } + return t + } + _parseAVCNALu(e) { + const t = e.byteLength; + let i, r, n = 0; + const s = this._avcContext; + let a = s.naluState || 0; + const o = a + , d = []; + let l, u, c, h = -1; + for (-1 === a && (h = 0, + c = 31 & e[0], + a = 0, + n = 1); n < t; ) + if (i = e[n++], + a) + if (1 !== a) + if (i) + if (1 === i) { + if (0 <= h) + l = { + data: e.subarray(h, n - a - 1), + type: c + }, + d.push(l); + else { + const t = this._getLastNalUnit(); + if (t && (o && n <= 4 - o && t.state && (t.data = t.data.subarray(0, t.data.byteLength - o)), + r = n - a - 1, + 0 < r)) { + const i = new Uint8Array(t.data.byteLength + r); + i.set(t.data, 0), + i.set(e.subarray(0, r), t.data.byteLength), + t.data = i + } + } + a = n < t ? (u = 31 & e[n], + h = n, + c = u, + 0) : -1 + } else + a = 0; + else + a = 3; + else + a = i ? 0 : 2; + else + a = i ? 0 : 1; + if (0 <= h && 0 <= a && (l = { + data: e.subarray(h, t), + type: c, + state: a + }, + d.push(l)), + 0 === d.length) { + const t = this._getLastNalUnit(); + if (t) { + const i = new Uint8Array(t.data.byteLength + e.byteLength); + i.set(t.data, 0), + i.set(e, t.data.byteLength), + t.data = i + } + } + return s.naluState = a, + d + } + discardEPB(e) { + const t = e.byteLength + , i = []; + let r = 1; + for (; r < t - 2; ) + 0 === e[r] && 0 === e[r + 1] && 3 === e[r + 2] ? (i.push(r + 2), + r += 2) : r++; + if (0 === i.length) + return e; + const n = t - i.length + , s = new Uint8Array(n); + let a = 0; + for (r = 0; r < n; a++, + r++) + a === i[0] && (a++, + i.shift()), + s[r] = e[a]; + return s + } + _parseAACPES(e) { + const t = this._audioContext + , i = t.audioLastPTS + , r = e.keyTagInfo; + let n, s, a, o, d, l, u, c = e.data, h = e.pts, p = t.audioOverFlow; + if (p) { + const e = new Uint8Array(p.byteLength + c.byteLength); + e.set(p, 0), + e.set(c, p.byteLength), + c = e + } + for (a = 0, + l = c.length; a < l - 1 && (255 !== c[a] || 240 != (240 & c[a + 1])); a++) + ; + if (a) { + let e, t, i; + i = a < l - 1 ? (e = `AAC PES did not start with ADTS header,offset:${a}`, + t = !1, + $.PESDidNotStartWithADTS) : (e = "no ADTS header found in AAC PES", + t = !0, + $.NoADTSHeaderInPES), + this.logger.warn(tt, `parsing error:${e}`); + const r = new D(t,e,i); + if (this.observer.trigger(x.INTERNAL_ERROR, r), + t) + return + } + if (!t.config) { + const e = E(this.observer, c, a, void 0, this.logger); + if (!e) + throw "unable to parse adts header"; + t.config = e + } + s = 0; + var f = 9216e4 / t.config.samplerate; + if (p && i) { + const e = i + f; + 1 < Math.abs(e - h) && (h = e) + } + for (; a + 5 < l && (o = 1 & c[a + 1] ? 7 : 9, + n = (3 & c[a + 3]) << 11 | c[a + 4] << 3 | (224 & c[a + 5]) >>> 5, + n -= o, + 0 < n && a + o + n <= l); ) + for (d = h + s * f, + u = { + unit: c.subarray(a + o, a + o + n), + pts: d, + dts: d, + keyTagInfo: r + }, + t.parsingData.esSamples.push(u), + t.parsingData.len += n, + a += n + o, + s++; a < l - 1 && (255 !== c[a] || 240 != (240 & c[a + 1])); a++) + ; + p = a < l ? c.subarray(a, l) : void 0, + t.audioOverFlow = p, + t.audioLastPTS = d + } + _parseMPEGPES(e) { + "mp3" === this._audioContext.segmentCodec && ee.parse(this._audioContext.parsingData, e.data, 0, e.pts, this.logger) + } + _parseDolbyPES(e) { + const t = this._audioContext; + let i = e.data + , r = e.pts; + var n = e.keyTagInfo; + let s = 0 + , a = 0 + , o = t.audioOverFlow; + e = t.audioLastPTS; + if (!t.config) { + let e; + if ("ac3" === t.segmentCodec ? e = q(this.observer, i, a, this.logger) : "ec3" === t.segmentCodec && (e = Y(this.observer, i, a, this.logger)), + !e) + throw "unable to parse dolby header"; + t.config = e + } + if ("ac3" !== t.config.segmentCodec && "ec3" !== t.config.segmentCodec) + throw "unexpected config type"; + var d = 1536 / t.config.samplerate * t.info.inputTimescale; + if (o) { + const c = new Uint8Array(o.byteLength + i.byteLength); + c.set(o, 0), + c.set(i, o.byteLength), + i = c + } + var l = i.length; + if (o && e) { + const c = e + d; + 1 < Math.abs(c - r) && (r = c) + } + let u = 0; + for (; a + u <= l; ) { + if (11 !== i[a] || 119 !== i[a + 1]) { + const c = new D(!0,"invalid dolby audio magic",$.InvalidDolbyAudioMagic); + return void this.observer.trigger(x.INTERNAL_ERROR, c) + } + "ac3" === t.segmentCodec ? u = Q(this.observer, i, a) : "ec3" === t.segmentCodec && (u = X(this.observer, i, a, this.logger)); + const c = r + s * d; + t.audioLastPTS = c; + const o = { + unit: i.subarray(a, a + u), + pts: c, + dts: c, + keyTagInfo: n + }; + t.parsingData.esSamples.push(o), + t.info.duration = this._duration, + t.parsingData.len += u, + a += u, + s++ + } + o = a < l ? i.subarray(a, l) : void 0, + t.audioOverFlow = o + } + } + ; + class nt extends a { + constructor(e, t, i, r) { + super(), + this.typeSupported = e, + this.config = t, + this.vendor = i, + this.logger = r + } + destroy() { + this.removeAllListeners(); + const e = this.demuxer + , t = this.remuxer; + e && e.destroy(), + t && t.destroy() + } + push(t, i, r, n, s, a, o, d, l, u, c, h) { + if (t) { + let e = this.demuxer; + var p = new Uint8Array(t); + if (!e || (s || a) && !this.probeFn(p, this.logger)) { + const {typeSupported: t, config: i} = this + , r = [{ + demux: Je, + remux: We + }, { + demux: rt, + remux: Te + }, { + demux: J, + remux: Te + }, { + demux: z, + remux: Te + }, { + demux: K, + remux: Te + }, { + demux: ie, + remux: Te + }]; + for (const n of r) { + const r = n.demux["probe"]; + if (r(p, this.logger)) { + this.remuxer = new n.remux(this,i,t,this.vendor,this.logger), + e = new n.demux(this,this.remuxer,i,t,this.logger), + this.probeFn = r; + break + } + } + if (!e) { + const t = new D(!0,"no demux matching with content found",$.DemuxerNotFound); + return void this.trigger(x.INTERNAL_ERROR, t) + } + this.demuxer = e + } + const f = this.remuxer + , m = !this.lastKeyTagInfo || i && "NONE" !== i.method && this.lastKeyTagInfo.uri !== i.uri; + if (this.lastKeyTagInfo = i, + (s || a || m) && (e.resetInitSegment(new Uint8Array(r), d, i, s), + f.resetInitSegment()), + s) { + const t = u ? S(u) : void 0; + e.resetTimeStamp(t), + f.resetTimeStamp(t) + } + e.append(p, n, o, l, i, c, h) + } + } + } + function st() { + let e = `${Date.now()}-${Math.random()}`; + return "undefined" != typeof performance && "function" == typeof performance.now && (e += `-${performance.now()}`), + e + } + class at { + constructor(e, t) { + this.rpc = e, + this.logger = t, + this.init = (t,n,s)=>e=>{ + const i = st() + , r = this.demuxers[i] = new nt(t,n,s,this.logger); + [v.INIT_PTS_FOUND, v.FRAG_PARSING_INIT_SEGMENT, v.FRAG_PARSING_DATA, v.FRAG_PARSED, x.INTERNAL_ERROR].forEach(t=>{ + r.on(t, e=>this.rpc.invoke("demuxer.event", [i, t, e])(()=>{} + )) + } + ), + e(i) + } + , + this.push = (i,r,n,s,a,o,d,l,u,c,h,p,f)=>e=>{ + const t = this.demuxers[i]; + t ? (t.push(r, n, s, a, o, d, l, u, c, h, p, f), + e()) : e(void 0, `Demuxer with id "${i}" does not exist on push`) + } + , + this.destroy = i=>e=>{ + const t = this.demuxers[i]; + t ? (t.destroy(), + delete this.demuxers[i], + e()) : this.logger.error(`Demuxer with id "${i}" does not exist on destroy`) + } + , + this.demuxers = {}, + e.register("demuxer.init", this.init), + e.register("demuxer.push", this.push), + e.register("demuxer.destroy", this.destroy) + } + } + class ot { + constructor(e) { + this.worker = e, + this.handlers = {}, + this.deferers = {}, + this._messageHandler = e=>{ + var {type: t, id: i, command: r, args: n, result: e, error: s} = e.data; + if (t === it.Invoke) + try { + if (null == this.handlers[r]) + throw new Error(`command ${r} not found`); + this.handlers[r](...n)(this._respond.bind(this, i, r)) + } catch (s) { + this._respond(i, r, null, new Error(`command ${r} not found`)) + } + else + t === it.Result && null != this.deferers[i] && (this.deferers[i](e, s), + delete this.deferers[i]) + } + , + e.addEventListener("message", this._messageHandler) + } + register(e, t) { + if (null != this.handlers[e]) + return !1; + this.handlers[e] = t + } + unregister(e) { + if (null != this.handlers[e]) + return !1; + delete this.handlers[e] + } + invoke(i, r, n) { + return (e=ot._fallbackCallback)=>{ + var t = st(); + this.deferers[t] = e; + t = { + type: it.Invoke, + id: t, + command: i, + args: r + }; + this._send(t, n) + } + } + teardown() { + this.worker.removeEventListener("message", this._messageHandler) + } + _respond(e, t, i, r, n) { + r instanceof Error && (r = `[${r.name}] ${r.message}\n${r.stack}`); + r = { + type: it.Result, + id: e, + command: t, + result: i, + error: r + }; + this._send(r, n) + } + _send(e, t=[]) { + this.worker.postMessage(e, t.map(e=>ArrayBuffer.isView(e) ? e.buffer : e).filter(e=>void 0 !== e)) + } + } + ot._fallbackCallback = (e,t)=>{ + if (null != t) + throw t + } + , + (gr = it = it || {})[gr.Invoke = 0] = "Invoke", + gr[gr.Result = 1] = "Result", + ArrayBuffer.isView || (ArrayBuffer.isView = function(e) { + return null !== e && "object" == typeof e && e.buffer instanceof ArrayBuffer + } + ), + void 0 !== Hy && Hy && (Br = new ot(d), + mu = (r=>{ + const t = (i=[])=>{ + const e = Object.fromEntries(["fatal", "error", "warn", "info", "debug", "trace", "qe"].map(e=>{ + return [e, (t = e, + (...e)=>{ + r.invoke("logger.log", [i, t, ...e])((e,t)=>{ + if (null != t) + throw t + } + ) + } + )]; + var t + } + )); + return e.child = e=>t([...i, e]), + e + } + ; + return t() + } + )(Br), + new i(Br,mu), + new at(Br,mu)); + var dt = function(e, t) { + return (dt = Object.setPrototypeOf || { + __proto__: [] + }instanceof Array && function(e, t) { + e.__proto__ = t + } + || function(e, t) { + for (var i in t) + Object.prototype.hasOwnProperty.call(t, i) && (e[i] = t[i]) + } + )(e, t) + }; + function lt(e, t) { + if ("function" != typeof t && null !== t) + throw new TypeError("Class extends value " + String(t) + " is not a constructor or null"); + function i() { + this.constructor = e + } + dt(e, t), + e.prototype = null === t ? Object.create(t) : (i.prototype = t.prototype, + new i) + } + var ut = function() { + return (ut = Object.assign || function(e) { + for (var t, i = 1, r = arguments.length; i < r; i++) + for (var n in t = arguments[i]) + Object.prototype.hasOwnProperty.call(t, n) && (e[n] = t[n]); + return e + } + ).apply(this, arguments) + }; + function ct(e, t, i, r) { + var n, s = arguments.length, a = s < 3 ? t : null === r ? r = Object.getOwnPropertyDescriptor(t, i) : r; + if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) + a = Reflect.decorate(e, t, i, r); + else + for (var o = e.length - 1; 0 <= o; o--) + (n = e[o]) && (a = (s < 3 ? n(a) : 3 < s ? n(t, i, a) : n(t, i)) || a); + return 3 < s && a && Object.defineProperty(t, i, a), + a + } + function ht(e, t) { + if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) + return Reflect.metadata(e, t) + } + function pt(e) { + var t = "function" == typeof Symbol && Symbol.iterator + , i = t && e[t] + , r = 0; + if (i) + return i.call(e); + if (e && "number" == typeof e.length) + return { + next: function() { + return { + value: (e = e && r >= e.length ? void 0 : e) && e[r++], + done: !e + } + } + }; + throw new TypeError(t ? "Object is not iterable." : "Symbol.iterator is not defined.") + } + function ft(e, t) { + var i = "function" == typeof Symbol && e[Symbol.iterator]; + if (!i) + return e; + var r, n, s = i.call(e), a = []; + try { + for (; (void 0 === t || 0 < t--) && !(r = s.next()).done; ) + a.push(r.value) + } catch (e) { + n = { + error: e + } + } finally { + try { + r && !r.done && (i = s.return) && i.call(s) + } finally { + if (n) + throw n.error + } + } + return a + } + function mt() { + for (var e = [], t = 0; t < arguments.length; t++) + e = e.concat(ft(arguments[t])); + return e + } + function gt(e) { + return "function" == typeof e + } + var yt = !1 + , vt = { + Promise: void 0, + set useDeprecatedSynchronousErrorHandling(e) { + yt = e + }, + get useDeprecatedSynchronousErrorHandling() { + return yt + } + }; + function St(e) { + setTimeout(function() { + throw e + }, 0) + } + var bt = { + closed: !0, + next: function(e) {}, + error: function(e) { + if (vt.useDeprecatedSynchronousErrorHandling) + throw e; + St(e) + }, + complete: function() {} + } + , Tt = Array.isArray || function(e) { + return e && "number" == typeof e.length + } + ; + function Et(e) { + return null !== e && "object" == typeof e + } + var It = (Ot.prototype = Object.create(Error.prototype), + Ot) + , wt = (At.prototype.unsubscribe = function() { + var t; + if (!this.closed) { + var e = this._parentOrParents + , i = this._ctorUnsubscribe + , r = this._unsubscribe + , n = this._subscriptions; + if (this.closed = !0, + this._parentOrParents = null, + this._subscriptions = null, + e instanceof At) + e.remove(this); + else if (null !== e) + for (var s = 0; s < e.length; ++s) + e[s].remove(this); + if (gt(r)) { + i && (this._unsubscribe = void 0); + try { + r.call(this) + } catch (e) { + t = e instanceof It ? kt(e.errors) : [e] + } + } + if (Tt(n)) + for (var s = -1, a = n.length; ++s < a; ) { + var o = n[s]; + if (Et(o)) + try { + o.unsubscribe() + } catch (e) { + t = t || [], + e instanceof It ? t = t.concat(kt(e.errors)) : t.push(e) + } + } + if (t) + throw new It(t) + } + } + , + At.prototype.add = function(e) { + var t, i = e; + if (!e) + return At.EMPTY; + switch (typeof e) { + case "function": + i = new At(e); + case "object": + if (i === this || i.closed || "function" != typeof i.unsubscribe) + return i; + if (this.closed) + return i.unsubscribe(), + i; + i instanceof At || (t = i, + (i = new At)._subscriptions = [t]); + break; + default: + throw new Error("unrecognized teardown " + e + " added to Subscription.") + } + var r = i._parentOrParents; + if (null === r) + i._parentOrParents = this; + else if (r instanceof At) { + if (r === this) + return i; + i._parentOrParents = [r, this] + } else { + if (-1 !== r.indexOf(this)) + return i; + r.push(this) + } + r = this._subscriptions; + return null === r ? this._subscriptions = [i] : r.push(i), + i + } + , + At.prototype.remove = function(e) { + var t = this._subscriptions; + !t || -1 !== (e = t.indexOf(e)) && t.splice(e, 1) + } + , + At.EMPTY = ((dd = new At).closed = !0, + dd), + At); + function At(e) { + this.closed = !1, + this._parentOrParents = null, + this._subscriptions = null, + e && (this._ctorUnsubscribe = !0, + this._unsubscribe = e) + } + function Ot(e) { + return Error.call(this), + this.message = e ? e.length + " errors occurred during unsubscription:\n" + e.map(function(e, t) { + return t + 1 + ") " + e.toString() + }).join("\n ") : "", + this.name = "UnsubscriptionError", + this.errors = e, + this + } + function kt(e) { + return e.reduce(function(e, t) { + return e.concat(t instanceof It ? t.errors : t) + }, []) + } + var Ct, Dt, Mt = "function" == typeof Symbol ? Symbol("rxSubscriber") : "@@rxSubscriber_" + Math.random(), Pt = (lt(Lt, Dt = wt), + Lt.prototype[Mt] = function() { + return this + } + , + Lt.create = function(e, t, i) { + i = new Lt(e,t,i); + return i.syncErrorThrowable = !1, + i + } + , + Lt.prototype.next = function(e) { + this.isStopped || this._next(e) + } + , + Lt.prototype.error = function(e) { + this.isStopped || (this.isStopped = !0, + this._error(e)) + } + , + Lt.prototype.complete = function() { + this.isStopped || (this.isStopped = !0, + this._complete()) + } + , + Lt.prototype.unsubscribe = function() { + this.closed || (this.isStopped = !0, + Dt.prototype.unsubscribe.call(this)) + } + , + Lt.prototype._next = function(e) { + this.destination.next(e) + } + , + Lt.prototype._error = function(e) { + this.destination.error(e), + this.unsubscribe() + } + , + Lt.prototype._complete = function() { + this.destination.complete(), + this.unsubscribe() + } + , + Lt.prototype._unsubscribeAndRecycle = function() { + var e = this._parentOrParents; + return this._parentOrParents = null, + this.unsubscribe(), + this.closed = !1, + this.isStopped = !1, + this._parentOrParents = e, + this + } + , + Lt), xt = (lt(Rt, Ct = Pt), + Rt.prototype.next = function(e) { + var t; + !this.isStopped && this._next && (t = this._parentSubscriber, + vt.useDeprecatedSynchronousErrorHandling && t.syncErrorThrowable ? this.__tryOrSetError(t, this._next, e) && this.unsubscribe() : this.__tryOrUnsub(this._next, e)) + } + , + Rt.prototype.error = function(e) { + if (!this.isStopped) { + var t = this._parentSubscriber + , i = vt.useDeprecatedSynchronousErrorHandling; + if (this._error) + i && t.syncErrorThrowable ? this.__tryOrSetError(t, this._error, e) : this.__tryOrUnsub(this._error, e), + this.unsubscribe(); + else if (t.syncErrorThrowable) + i ? (t.syncErrorValue = e, + t.syncErrorThrown = !0) : St(e), + this.unsubscribe(); + else { + if (this.unsubscribe(), + i) + throw e; + St(e) + } + } + } + , + Rt.prototype.complete = function() { + var e, t, i = this; + this.isStopped || (e = this._parentSubscriber, + this._complete && (t = function() { + return i._complete.call(i._context) + } + , + vt.useDeprecatedSynchronousErrorHandling && e.syncErrorThrowable ? this.__tryOrSetError(e, t) : this.__tryOrUnsub(t)), + this.unsubscribe()) + } + , + Rt.prototype.__tryOrUnsub = function(e, t) { + try { + e.call(this._context, t) + } catch (e) { + if (this.unsubscribe(), + vt.useDeprecatedSynchronousErrorHandling) + throw e; + St(e) + } + } + , + Rt.prototype.__tryOrSetError = function(e, t, i) { + if (!vt.useDeprecatedSynchronousErrorHandling) + throw new Error("bad call"); + try { + t.call(this._context, i) + } catch (t) { + return vt.useDeprecatedSynchronousErrorHandling ? (e.syncErrorValue = t, + e.syncErrorThrown = !0) : St(t), + !0 + } + return !1 + } + , + Rt.prototype._unsubscribe = function() { + var e = this._parentSubscriber; + this._context = null, + this._parentSubscriber = null, + e.unsubscribe() + } + , + Rt); + function Rt(e, t, i, r) { + var n, s = Ct.call(this) || this; + s._parentSubscriber = e; + e = s; + return gt(t) ? n = t : t && (n = t.next, + i = t.error, + r = t.complete, + t !== bt && (gt((e = Object.create(t)).unsubscribe) && s.add(e.unsubscribe.bind(e)), + e.unsubscribe = s.unsubscribe.bind(s))), + s._context = e, + s._next = n, + s._error = i, + s._complete = r, + s + } + function Lt(e, t, i) { + var r = Dt.call(this) || this; + switch (r.syncErrorValue = null, + r.syncErrorThrown = !1, + r.syncErrorThrowable = !1, + r.isStopped = !1, + arguments.length) { + case 0: + r.destination = bt; + break; + case 1: + if (!e) { + r.destination = bt; + break + } + if ("object" == typeof e) { + e instanceof Lt ? (r.syncErrorThrowable = e.syncErrorThrowable, + (r.destination = e).add(r)) : (r.syncErrorThrowable = !0, + r.destination = new xt(r,e)); + break + } + default: + r.syncErrorThrowable = !0, + r.destination = new xt(r,e,t,i) + } + return r + } + var _t = "function" == typeof Symbol && Symbol.observable || "@@observable"; + function Nt(e) { + return e + } + function Ft() { + for (var e = [], t = 0; t < arguments.length; t++) + e[t] = arguments[t]; + return Bt(e) + } + function Bt(t) { + return 0 === t.length ? Nt : 1 === t.length ? t[0] : function(e) { + return t.reduce(function(e, t) { + return t(e) + }, e) + } + } + var Ut = ($t.prototype.lift = function(e) { + var t = new $t; + return t.source = this, + t.operator = e, + t + } + , + $t.prototype.subscribe = function(e, t, i) { + var r = this.operator + , i = function(e, t, i) { + if (e) { + if (e instanceof Pt) + return e; + if (e[Mt]) + return e[Mt]() + } + return e || t || i ? new Pt(e,t,i) : new Pt(bt) + }(e, t, i); + if (r ? i.add(r.call(i, this.source)) : i.add(this.source || vt.useDeprecatedSynchronousErrorHandling && !i.syncErrorThrowable ? this._subscribe(i) : this._trySubscribe(i)), + vt.useDeprecatedSynchronousErrorHandling && i.syncErrorThrowable && (i.syncErrorThrowable = !1, + i.syncErrorThrown)) + throw i.syncErrorValue; + return i + } + , + $t.prototype._trySubscribe = function(t) { + try { + return this._subscribe(t) + } catch (e) { + vt.useDeprecatedSynchronousErrorHandling && (t.syncErrorThrown = !0, + t.syncErrorValue = e), + function(e) { + for (; e; ) { + var t = e + , i = t.closed + , r = t.destination + , t = t.isStopped; + if (i || t) + return; + e = r && r instanceof Pt ? r : null + } + return 1 + }(t) ? t.error(e) : console.warn(e) + } + } + , + $t.prototype.forEach = function(r, e) { + var n = this; + return new (e = Vt(e))(function(e, t) { + var i = n.subscribe(function(e) { + try { + r(e) + } catch (e) { + t(e), + i && i.unsubscribe() + } + }, t, e) + } + ) + } + , + $t.prototype._subscribe = function(e) { + var t = this.source; + return t && t.subscribe(e) + } + , + $t.prototype[_t] = function() { + return this + } + , + $t.prototype.pipe = function() { + for (var e = [], t = 0; t < arguments.length; t++) + e[t] = arguments[t]; + return 0 === e.length ? this : Bt(e)(this) + } + , + $t.prototype.toPromise = function(e) { + var r = this; + return new (e = Vt(e))(function(e, t) { + var i; + r.subscribe(function(e) { + return i = e + }, function(e) { + return t(e) + }, function() { + return e(i) + }) + } + ) + } + , + $t.create = function(e) { + return new $t(e) + } + , + $t); + function $t(e) { + this._isScalar = !1, + e && (this._subscribe = e) + } + function Vt(e) { + if (!(e = e || (vt.Promise || Promise))) + throw new Error("no Promise impl found"); + return e + } + var Kt, Ht, jt, qt, Qt = (ti.prototype = Object.create(Error.prototype), + ti), Gt = (lt(ei, qt = wt), + ei.prototype.unsubscribe = function() { + var e, t; + this.closed || (this.closed = !0, + e = (t = this.subject).observers, + this.subject = null, + !e || 0 === e.length || t.isStopped || t.closed || -1 !== (t = e.indexOf(this.subscriber)) && e.splice(t, 1)) + } + , + ei), Wt = (lt(Zt, jt = Pt), + Zt), zt = (lt(Jt, Ht = Ut), + Jt.prototype[Mt] = function() { + return new Wt(this) + } + , + Jt.prototype.lift = function(e) { + var t = new Xt(this,this); + return t.operator = e, + t + } + , + Jt.prototype.next = function(e) { + if (this.closed) + throw new Qt; + if (!this.isStopped) + for (var t = this.observers, i = t.length, r = t.slice(), n = 0; n < i; n++) + r[n].next(e) + } + , + Jt.prototype.error = function(e) { + if (this.closed) + throw new Qt; + this.hasError = !0, + this.thrownError = e, + this.isStopped = !0; + for (var t = this.observers, i = t.length, r = t.slice(), n = 0; n < i; n++) + r[n].error(e); + this.observers.length = 0 + } + , + Jt.prototype.complete = function() { + if (this.closed) + throw new Qt; + this.isStopped = !0; + for (var e = this.observers, t = e.length, i = e.slice(), r = 0; r < t; r++) + i[r].complete(); + this.observers.length = 0 + } + , + Jt.prototype.unsubscribe = function() { + this.isStopped = !0, + this.closed = !0, + this.observers = null + } + , + Jt.prototype._trySubscribe = function(e) { + if (this.closed) + throw new Qt; + return Ht.prototype._trySubscribe.call(this, e) + } + , + Jt.prototype._subscribe = function(e) { + if (this.closed) + throw new Qt; + return this.hasError ? (e.error(this.thrownError), + wt.EMPTY) : this.isStopped ? (e.complete(), + wt.EMPTY) : (this.observers.push(e), + new Gt(this,e)) + } + , + Jt.prototype.asObservable = function() { + var e = new Ut; + return e.source = this, + e + } + , + Jt.create = function(e, t) { + return new Xt(e,t) + } + , + Jt), Xt = (lt(Yt, Kt = zt), + Yt.prototype.next = function(e) { + var t = this.destination; + t && t.next && t.next(e) + } + , + Yt.prototype.error = function(e) { + var t = this.destination; + t && t.error && this.destination.error(e) + } + , + Yt.prototype.complete = function() { + var e = this.destination; + e && e.complete && this.destination.complete() + } + , + Yt.prototype._subscribe = function(e) { + return this.source ? this.source.subscribe(e) : wt.EMPTY + } + , + Yt); + function Yt(e, t) { + var i = Kt.call(this) || this; + return i.destination = e, + i.source = t, + i + } + function Jt() { + var e = Ht.call(this) || this; + return e.observers = [], + e.closed = !1, + e.isStopped = !1, + e.hasError = !1, + e.thrownError = null, + e + } + function Zt(e) { + var t = jt.call(this, e) || this; + return t.destination = e, + t + } + function ei(e, t) { + var i = qt.call(this) || this; + return i.subject = e, + i.subscriber = t, + i.closed = !1, + i + } + function ti() { + return Error.call(this), + this.message = "object unsubscribed", + this.name = "ObjectUnsubscribedError", + this + } + function ii() { + return function(e) { + return e.lift(new hi(e)) + } + } + var ri, ni, si, ai, oi, di, li, ui, ci, hi = (xi.prototype.call = function(e, t) { + var i = this.connectable; + i._refCount++; + e = new pi(e,i), + t = t.subscribe(e); + return e.closed || (e.connection = i.connect()), + t + } + , + xi), pi = (lt(Pi, ci = Pt), + Pi.prototype._unsubscribe = function() { + var e, t = this.connectable; + t ? (this.connectable = null, + (e = t._refCount) <= 0 ? this.connection = null : (t._refCount = e - 1, + 1 < e ? this.connection = null : (e = this.connection, + t = t._connection, + this.connection = null, + !t || e && t !== e || t.unsubscribe()))) : this.connection = null + } + , + Pi), w = (lt(Mi, ui = Ut), + Mi.prototype._subscribe = function(e) { + return this.getSubject().subscribe(e) + } + , + Mi.prototype.getSubject = function() { + var e = this._subject; + return e && !e.isStopped || (this._subject = this.subjectFactory()), + this._subject + } + , + Mi.prototype.connect = function() { + var e = this._connection; + return e || (this._isComplete = !1, + (e = this._connection = new wt).add(this.source.subscribe(new mi(this.getSubject(),this))), + e.closed && (this._connection = null, + e = wt.EMPTY)), + e + } + , + Mi.prototype.refCount = function() { + return ii()(this) + } + , + Mi), fi = { + operator: { + value: null + }, + _refCount: { + value: 0, + writable: !0 + }, + _subject: { + value: null, + writable: !0 + }, + _connection: { + value: null, + writable: !0 + }, + _subscribe: { + value: (pd = w.prototype)._subscribe + }, + _isComplete: { + value: pd._isComplete, + writable: !0 + }, + getSubject: { + value: pd.getSubject + }, + connect: { + value: pd.connect + }, + refCount: { + value: pd.refCount + } + }, mi = (lt(Di, li = Wt), + Di.prototype._error = function(e) { + this._unsubscribe(), + li.prototype._error.call(this, e) + } + , + Di.prototype._complete = function() { + this.connectable._isComplete = !0, + this._unsubscribe(), + li.prototype._complete.call(this) + } + , + Di.prototype._unsubscribe = function() { + var e, t = this.connectable; + t && (this.connectable = null, + e = t._connection, + t._refCount = 0, + t._subject = null, + t._connection = null, + e && e.unsubscribe()) + } + , + Di), gi = (lt(Ci, di = zt), + Object.defineProperty(Ci.prototype, "value", { + get: function() { + return this.getValue() + }, + enumerable: !0, + configurable: !0 + }), + Ci.prototype._subscribe = function(e) { + var t = di.prototype._subscribe.call(this, e); + return t && !t.closed && e.next(this._value), + t + } + , + Ci.prototype.getValue = function() { + if (this.hasError) + throw this.thrownError; + if (this.closed) + throw new Qt; + return this._value + } + , + Ci.prototype.next = function(e) { + di.prototype.next.call(this, this._value = e) + } + , + Ci), A = (lt(ki, oi = wt), + ki.prototype.schedule = function(e, t) { + return this + } + , + lt(Oi, ai = ki), + Oi.prototype.schedule = function(e, t) { + if (void 0 === t && (t = 0), + this.closed) + return this; + this.state = e; + var i = this.id + , e = this.scheduler; + return null != i && (this.id = this.recycleAsyncId(e, i, t)), + this.pending = !0, + this.delay = t, + this.id = this.id || this.requestAsyncId(e, this.id, t), + this + } + , + Oi.prototype.requestAsyncId = function(e, t, i) { + return void 0 === i && (i = 0), + setInterval(e.flush.bind(e, this), i) + } + , + Oi.prototype.recycleAsyncId = function(e, t, i) { + if (null !== (i = void 0 === i ? 0 : i) && this.delay === i && !1 === this.pending) + return t; + clearInterval(t) + } + , + Oi.prototype.execute = function(e, t) { + if (this.closed) + return new Error("executing a cancelled action"); + this.pending = !1; + t = this._execute(e, t); + if (t) + return t; + !1 === this.pending && null != this.id && (this.id = this.recycleAsyncId(this.scheduler, this.id, null)) + } + , + Oi.prototype._execute = function(e, t) { + var i = !1 + , r = void 0; + try { + this.work(e) + } catch (e) { + i = !0, + r = !!e && e || new Error(e) + } + if (i) + return this.unsubscribe(), + r + } + , + Oi.prototype._unsubscribe = function() { + var e = this.id + , t = this.scheduler + , i = t.actions + , r = i.indexOf(this); + this.work = null, + this.state = null, + this.pending = !1, + this.scheduler = null, + -1 !== r && i.splice(r, 1), + null != e && (this.id = this.recycleAsyncId(t, e, null)), + this.delay = null + } + , + Oi), yi = (lt(Ai, si = A), + Ai.prototype.schedule = function(e, t) { + return 0 < (t = void 0 === t ? 0 : t) ? si.prototype.schedule.call(this, e, t) : (this.delay = t, + this.state = e, + this.scheduler.flush(this), + this) + } + , + Ai.prototype.execute = function(e, t) { + return 0 < t || this.closed ? si.prototype.execute.call(this, e, t) : this._execute(e, t) + } + , + Ai.prototype.requestAsyncId = function(e, t, i) { + return null !== (i = void 0 === i ? 0 : i) && 0 < i || null === i && 0 < this.delay ? si.prototype.requestAsyncId.call(this, e, t, i) : e.flush(this) + } + , + Ai), vi = (wi.prototype.schedule = function(e, t, i) { + return void 0 === t && (t = 0), + new this.SchedulerAction(this,e).schedule(i, t) + } + , + wi.now = function() { + return Date.now() + } + , + wi), Si = (lt(Ii, ni = vi), + Ii.prototype.schedule = function(e, t, i) { + return void 0 === t && (t = 0), + Ii.delegate && Ii.delegate !== this ? Ii.delegate.schedule(e, t, i) : ni.prototype.schedule.call(this, e, t, i) + } + , + Ii.prototype.flush = function(e) { + var t, i = this.actions; + if (this.active) + i.push(e); + else { + this.active = !0; + do { + if (t = e.execute(e.state, e.delay)) + break + } while (e = i.shift()); + if (this.active = !1, + t) { + for (; e = i.shift(); ) + e.unsubscribe(); + throw t + } + } + } + , + Ii), bi = (lt(Ei, ri = Si), + new Ei(yi)), Ti = new Ut(function(e) { + return e.complete() + } + ); + function Ei() { + return null !== ri && ri.apply(this, arguments) || this + } + function Ii(e, t) { + void 0 === t && (t = vi.now); + var i = ni.call(this, e, function() { + return Ii.delegate && Ii.delegate !== i ? Ii.delegate.now() : t() + }) || this; + return i.actions = [], + i.active = !1, + i.scheduled = void 0, + i + } + function wi(e, t) { + void 0 === t && (t = wi.now), + this.SchedulerAction = e, + this.now = t + } + function Ai(e, t) { + var i = si.call(this, e, t) || this; + return i.scheduler = e, + i.work = t, + i + } + function Oi(e, t) { + var i = ai.call(this, e, t) || this; + return i.scheduler = e, + i.work = t, + i.pending = !1, + i + } + function ki(e, t) { + return oi.call(this) || this + } + function Ci(e) { + var t = di.call(this) || this; + return t._value = e, + t + } + function Di(e, t) { + e = li.call(this, e) || this; + return e.connectable = t, + e + } + function Mi(e, t) { + var i = ui.call(this) || this; + return i.source = e, + i.subjectFactory = t, + i._refCount = 0, + i._isComplete = !1, + i + } + function Pi(e, t) { + e = ci.call(this, e) || this; + return e.connectable = t, + e + } + function xi(e) { + this.connectable = e + } + function Ri(e) { + return e ? (t = e, + new Ut(function(e) { + return t.schedule(function() { + return e.complete() + }) + } + )) : Ti; + var t + } + function Li(e) { + return e && "function" == typeof e.schedule + } + var _i = function(r) { + return function(e) { + for (var t = 0, i = r.length; t < i && !e.closed; t++) + e.next(r[t]); + e.complete() + } + }; + function Ni(r, n) { + return new Ut(function(e) { + var t = new wt + , i = 0; + return t.add(n.schedule(function() { + i !== r.length ? (e.next(r[i++]), + e.closed || t.add(this.schedule())) : e.complete() + })), + t + } + ) + } + function Fi(e, t) { + return t ? Ni(e, t) : new Ut(_i(e)) + } + function Bi() { + for (var e = [], t = 0; t < arguments.length; t++) + e[t] = arguments[t]; + var i = e[e.length - 1]; + return Li(i) ? (e.pop(), + Ni(e, i)) : Fi(e) + } + function Ui(t, i) { + return new Ut(i ? function(e) { + return i.schedule($i, 0, { + error: t, + subscriber: e + }) + } + : function(e) { + return e.error(t) + } + ) + } + function $i(e) { + var t = e.error; + e.subscriber.error(t) + } + var Vi = (Ki.prototype.observe = function(e) { + switch (this.kind) { + case "N": + return e.next && e.next(this.value); + case "E": + return e.error && e.error(this.error); + case "C": + return e.complete && e.complete() + } + } + , + Ki.prototype.do = function(e, t, i) { + switch (this.kind) { + case "N": + return e && e(this.value); + case "E": + return t && t(this.error); + case "C": + return i && i() + } + } + , + Ki.prototype.accept = function(e, t, i) { + return e && "function" == typeof e.next ? this.observe(e) : this.do(e, t, i) + } + , + Ki.prototype.toObservable = function() { + switch (this.kind) { + case "N": + return Bi(this.value); + case "E": + return Ui(this.error); + case "C": + return Ri() + } + throw new Error("unexpected notification kind value") + } + , + Ki.createNext = function(e) { + return void 0 !== e ? new Ki("N",e) : Ki.undefinedValueNotification + } + , + Ki.createError = function(e) { + return new Ki("E",void 0,e) + } + , + Ki.createComplete = function() { + return Ki.completeNotification + } + , + Ki.completeNotification = new Ki("C"), + Ki.undefinedValueNotification = new Ki("N",void 0), + Ki); + function Ki(e, t, i) { + this.kind = e, + this.value = t, + this.error = i, + this.hasValue = "N" === e + } + function Hi(t, i) { + return void 0 === i && (i = 0), + function(e) { + return e.lift(new Gi(t,i)) + } + } + var ji, qi, Qi, Gi = (nr.prototype.call = function(e, t) { + return t.subscribe(new Wi(e,this.scheduler,this.delay)) + } + , + nr), Wi = (lt(rr, Qi = Pt), + rr.dispatch = function(e) { + var t = e.notification + , e = e.destination; + t.observe(e), + this.unsubscribe() + } + , + rr.prototype.scheduleMessage = function(e) { + this.destination.add(this.scheduler.schedule(rr.dispatch, this.delay, new zi(e,this.destination))) + } + , + rr.prototype._next = function(e) { + this.scheduleMessage(Vi.createNext(e)) + } + , + rr.prototype._error = function(e) { + this.scheduleMessage(Vi.createError(e)), + this.unsubscribe() + } + , + rr.prototype._complete = function() { + this.scheduleMessage(Vi.createComplete()), + this.unsubscribe() + } + , + rr), zi = function(e, t) { + this.notification = e, + this.destination = t + }, Xi = (lt(ir, qi = zt), + ir.prototype.nextInfiniteTimeWindow = function(e) { + var t; + this.isStopped || ((t = this._events).push(e), + t.length > this._bufferSize && t.shift()), + qi.prototype.next.call(this, e) + } + , + ir.prototype.nextTimeWindow = function(e) { + this.isStopped || (this._events.push(new Yi(this._getNow(),e)), + this._trimBufferThenGetEvents()), + qi.prototype.next.call(this, e) + } + , + ir.prototype._subscribe = function(e) { + var t, i = this._infiniteTimeWindow, r = i ? this._events : this._trimBufferThenGetEvents(), n = this.scheduler, s = r.length; + if (this.closed) + throw new Qt; + if (t = this.isStopped || this.hasError ? wt.EMPTY : (this.observers.push(e), + new Gt(this,e)), + n && e.add(e = new Wi(e,n)), + i) + for (var a = 0; a < s && !e.closed; a++) + e.next(r[a]); + else + for (a = 0; a < s && !e.closed; a++) + e.next(r[a].value); + return this.hasError ? e.error(this.thrownError) : this.isStopped && e.complete(), + t + } + , + ir.prototype._getNow = function() { + return (this.scheduler || bi).now() + } + , + ir.prototype._trimBufferThenGetEvents = function() { + for (var e = this._getNow(), t = this._bufferSize, i = this._windowTime, r = this._events, n = r.length, s = 0; s < n && !(e - r[s].time < i); ) + s++; + return 0 < (s = t < n ? Math.max(s, n - t) : s) && r.splice(0, s), + r + } + , + ir), Yi = function(e, t) { + this.time = e, + this.value = t + }, Ji = (lt(tr, ji = zt), + tr.prototype._subscribe = function(e) { + return this.hasError ? (e.error(this.thrownError), + wt.EMPTY) : this.hasCompleted && this.hasNext ? (e.next(this.value), + e.complete(), + wt.EMPTY) : ji.prototype._subscribe.call(this, e) + } + , + tr.prototype.next = function(e) { + this.hasCompleted || (this.value = e, + this.hasNext = !0) + } + , + tr.prototype.error = function(e) { + this.hasCompleted || ji.prototype.error.call(this, e) + } + , + tr.prototype.complete = function() { + this.hasCompleted = !0, + this.hasNext && ji.prototype.next.call(this, this.value), + ji.prototype.complete.call(this) + } + , + tr), Zi = new Si(A), er = Zi; + function tr() { + var e = null !== ji && ji.apply(this, arguments) || this; + return e.value = null, + e.hasNext = !1, + e.hasCompleted = !1, + e + } + function ir(e, t, i) { + void 0 === e && (e = Number.POSITIVE_INFINITY), + void 0 === t && (t = Number.POSITIVE_INFINITY); + var r = qi.call(this) || this; + return r.scheduler = i, + r._events = [], + r._infiniteTimeWindow = !1, + r._bufferSize = e < 1 ? 1 : e, + r._windowTime = t < 1 ? 1 : t, + t === Number.POSITIVE_INFINITY ? (r._infiniteTimeWindow = !0, + r.next = r.nextInfiniteTimeWindow) : r.next = r.nextTimeWindow, + r + } + function rr(e, t, i) { + void 0 === i && (i = 0); + e = Qi.call(this, e) || this; + return e.scheduler = t, + e.delay = i, + e + } + function nr(e, t) { + void 0 === t && (t = 0), + this.scheduler = e, + this.delay = t + } + function sr() {} + var ar = (lr.prototype = Object.create(Error.prototype), + lr) + , or = (dr.prototype = Object.create(Error.prototype), + dr); + function dr() { + return Error.call(this), + this.message = "Timeout has occurred", + this.name = "TimeoutError", + this + } + function lr() { + return Error.call(this), + this.message = "argument out of range", + this.name = "ArgumentOutOfRangeError", + this + } + function ur(t, i) { + return function(e) { + if ("function" != typeof t) + throw new TypeError("argument is not a function. Are you looking for `mapTo()`?"); + return e.lift(new fr(t,i)) + } + } + var cr, hr, pr, fr = (Tr.prototype.call = function(e, t) { + return t.subscribe(new mr(e,this.project,this.thisArg)) + } + , + Tr), mr = (lt(br, pr = Pt), + br.prototype._next = function(e) { + var t; + try { + t = this.project.call(this.thisArg, e, this.count++) + } catch (e) { + return void this.destination.error(e) + } + this.destination.next(t) + } + , + br), gr = (lt(Sr, hr = Pt), + Sr.prototype.notifyNext = function(e, t, i, r, n) { + this.destination.next(t) + } + , + Sr.prototype.notifyError = function(e, t) { + this.destination.error(e) + } + , + Sr.prototype.notifyComplete = function(e) { + this.destination.complete() + } + , + Sr), yr = (lt(vr, cr = Pt), + vr.prototype._next = function(e) { + this.parent.notifyNext(this.outerValue, e, this.outerIndex, this.index++, this) + } + , + vr.prototype._error = function(e) { + this.parent.notifyError(e, this), + this.unsubscribe() + } + , + vr.prototype._complete = function() { + this.parent.notifyComplete(this), + this.unsubscribe() + } + , + vr); + function vr(e, t, i) { + var r = cr.call(this) || this; + return r.parent = e, + r.outerValue = t, + r.outerIndex = i, + r.index = 0, + r + } + function Sr() { + return null !== hr && hr.apply(this, arguments) || this + } + function br(e, t, i) { + e = pr.call(this, e) || this; + return e.project = t, + e.count = 0, + e.thisArg = i || e, + e + } + function Tr(e, t) { + this.project = e, + this.thisArg = t + } + var Er = "function" == typeof Symbol && Symbol.iterator ? Symbol.iterator : "@@iterator" + , Ir = function(e) { + return e && "number" == typeof e.length && "function" != typeof e + }; + function wr(e) { + return e && "function" != typeof e.subscribe && "function" == typeof e.then + } + var Ar = function(e) { + if (e && "function" == typeof e[_t]) + return n = e, + function(e) { + var t = n[_t](); + if ("function" != typeof t.subscribe) + throw new TypeError("Provided object does not correctly implement Symbol.observable"); + return t.subscribe(e) + } + ; + if (Ir(e)) + return _i(e); + if (wr(e)) + return i = e, + function(t) { + return i.then(function(e) { + t.closed || (t.next(e), + t.complete()) + }, function(e) { + return t.error(e) + }).then(null, St), + t + } + ; + if (e && "function" == typeof e[Er]) + return r = e, + function(t) { + for (var e = r[Er](); ; ) { + var i = void 0; + try { + i = e.next() + } catch (e) { + return t.error(e), + t + } + if (i.done) { + t.complete(); + break + } + if (t.next(i.value), + t.closed) + break + } + return "function" == typeof e.return && t.add(function() { + e.return && e.return() + }), + t + } + ; + var r, i, n, e = Et(e) ? "an invalid object" : "'" + e + "'"; + throw new TypeError("You provided " + e + " where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.") + }; + function Or(e, t, i, r, n) { + if (!(n = void 0 === n ? new yr(e,i,r) : n).closed) + return t instanceof Ut ? t.subscribe(n) : Ar(t)(n) + } + var kr = {}; + function Cr() { + for (var e = [], t = 0; t < arguments.length; t++) + e[t] = arguments[t]; + var i = void 0 + , r = void 0; + return Li(e[e.length - 1]) && (r = e.pop()), + "function" == typeof e[e.length - 1] && (i = e.pop()), + Fi(e = 1 === e.length && Tt(e[0]) ? e[0] : e, r).lift(new Mr(i)) + } + var Dr, Mr = (Rr.prototype.call = function(e, t) { + return t.subscribe(new Pr(e,this.resultSelector)) + } + , + Rr), Pr = (lt(xr, Dr = gr), + xr.prototype._next = function(e) { + this.values.push(kr), + this.observables.push(e) + } + , + xr.prototype._complete = function() { + var e = this.observables + , t = e.length; + if (0 === t) + this.destination.complete(); + else { + this.active = t, + this.toRespond = t; + for (var i = 0; i < t; i++) { + var r = e[i]; + this.add(Or(this, r, void 0, i)) + } + } + } + , + xr.prototype.notifyComplete = function(e) { + 0 == --this.active && this.destination.complete() + } + , + xr.prototype.notifyNext = function(e, t, i) { + var r = this.values + , n = r[i] + , n = this.toRespond ? n === kr ? --this.toRespond : this.toRespond : 0; + r[i] = t, + 0 === n && (this.resultSelector ? this._tryResultSelector(r) : this.destination.next(r.slice())) + } + , + xr.prototype._tryResultSelector = function(e) { + var t; + try { + t = this.resultSelector.apply(this, e) + } catch (e) { + return void this.destination.error(e) + } + this.destination.next(t) + } + , + xr); + function xr(e, t) { + e = Dr.call(this, e) || this; + return e.resultSelector = t, + e.active = 0, + e.values = [], + e.observables = [], + e + } + function Rr(e) { + this.resultSelector = e + } + function Lr(e, t) { + return t ? function(e, t) { + if (null != e) { + if (e && "function" == typeof e[_t]) + return s = e, + a = t, + new Ut(function(t) { + var i = new wt; + return i.add(a.schedule(function() { + var e = s[_t](); + i.add(e.subscribe({ + next: function(e) { + i.add(a.schedule(function() { + return t.next(e) + })) + }, + error: function(e) { + i.add(a.schedule(function() { + return t.error(e) + })) + }, + complete: function() { + i.add(a.schedule(function() { + return t.complete() + })) + } + })) + })), + i + } + ); + if (wr(e)) + return r = e, + n = t, + new Ut(function(t) { + var i = new wt; + return i.add(n.schedule(function() { + return r.then(function(e) { + i.add(n.schedule(function() { + t.next(e), + i.add(n.schedule(function() { + return t.complete() + })) + })) + }, function(e) { + i.add(n.schedule(function() { + return t.error(e) + })) + }) + })), + i + } + ); + if (Ir(e)) + return Ni(e, t); + if (e && "function" == typeof e[Er] || "string" == typeof e) + return function(t, i) { + if (!t) + throw new Error("Iterable cannot be null"); + return new Ut(function(r) { + var n, e = new wt; + return e.add(function() { + n && "function" == typeof n.return && n.return() + }), + e.add(i.schedule(function() { + n = t[Er](), + e.add(i.schedule(function() { + if (!r.closed) { + try { + var e = n.next() + , t = e.value + , i = e.done + } catch (t) { + return void r.error(t) + } + i ? r.complete() : (r.next(t), + this.schedule()) + } + })) + })), + e + } + ) + }(e, t) + } + var r, n, s, a; + throw new TypeError((null !== e && typeof e || e) + " is not observable") + }(e, t) : e instanceof Ut ? e : new Ut(Ar(e)) + } + var _r, Nr, Fr = (lt($r, Nr = Pt), + $r.prototype._next = function(e) { + this.parent.notifyNext(e) + } + , + $r.prototype._error = function(e) { + this.parent.notifyError(e), + this.unsubscribe() + } + , + $r.prototype._complete = function() { + this.parent.notifyComplete(), + this.unsubscribe() + } + , + $r), Br = (lt(Ur, _r = Pt), + Ur.prototype.notifyNext = function(e) { + this.destination.next(e) + } + , + Ur.prototype.notifyError = function(e) { + this.destination.error(e) + } + , + Ur.prototype.notifyComplete = function() { + this.destination.complete() + } + , + Ur); + function Ur() { + return null !== _r && _r.apply(this, arguments) || this + } + function $r(e) { + var t = Nr.call(this) || this; + return t.parent = e, + t + } + function Vr(e, t) { + if (!t.closed) + return e instanceof Ut ? e.subscribe(t) : Ar(e)(t) + } + function Kr(t, n, i) { + return void 0 === i && (i = Number.POSITIVE_INFINITY), + "function" == typeof n ? function(e) { + return e.pipe(Kr(function(i, r) { + return Lr(t(i, r)).pipe(ur(function(e, t) { + return n(i, e, r, t) + })) + }, i)) + } + : ("number" == typeof n && (i = n), + function(e) { + return e.lift(new jr(t,i)) + } + ) + } + var Hr, jr = (Gr.prototype.call = function(e, t) { + return t.subscribe(new qr(e,this.project,this.concurrent)) + } + , + Gr), qr = (lt(Qr, Hr = Br), + Qr.prototype._next = function(e) { + this.active < this.concurrent ? this._tryNext(e) : this.buffer.push(e) + } + , + Qr.prototype._tryNext = function(e) { + var t, i = this.index++; + try { + t = this.project(e, i) + } catch (e) { + return void this.destination.error(e) + } + this.active++, + this._innerSub(t) + } + , + Qr.prototype._innerSub = function(e) { + var t = new Fr(this) + , i = this.destination; + i.add(t); + e = Vr(e, t); + e !== t && i.add(e) + } + , + Qr.prototype._complete = function() { + this.hasCompleted = !0, + 0 === this.active && 0 === this.buffer.length && this.destination.complete(), + this.unsubscribe() + } + , + Qr.prototype.notifyNext = function(e) { + this.destination.next(e) + } + , + Qr.prototype.notifyComplete = function() { + var e = this.buffer; + this.active--, + 0 < e.length ? this._next(e.shift()) : 0 === this.active && this.hasCompleted && this.destination.complete() + } + , + Qr); + function Qr(e, t, i) { + void 0 === i && (i = Number.POSITIVE_INFINITY); + e = Hr.call(this, e) || this; + return e.project = t, + e.concurrent = i, + e.hasCompleted = !1, + e.buffer = [], + e.active = 0, + e.index = 0, + e + } + function Gr(e, t) { + void 0 === t && (t = Number.POSITIVE_INFINITY), + this.project = e, + this.concurrent = t + } + function Wr(e) { + return Kr(Nt, e = void 0 === e ? Number.POSITIVE_INFINITY : e) + } + function zr() { + return Wr(1) + } + function Xr() { + for (var e = [], t = 0; t < arguments.length; t++) + e[t] = arguments[t]; + return zr()(Bi.apply(void 0, e)) + } + function Yr(i) { + return new Ut(function(t) { + var e; + try { + e = i() + } catch (e) { + return void t.error(e) + } + return (e ? Lr(e) : Ri()).subscribe(t) + } + ) + } + function Jr() { + for (var e = [], t = 0; t < arguments.length; t++) + e[t] = arguments[t]; + if (1 === e.length) { + var i = e[0]; + if (Tt(i)) + return Zr(i, null); + if (Et(i) && Object.getPrototypeOf(i) === Object.prototype) { + var r = Object.keys(i); + return Zr(r.map(function(e) { + return i[e] + }), r) + } + } + if ("function" != typeof e[e.length - 1]) + return Zr(e, null); + var n = e.pop(); + return Zr(e = 1 === e.length && Tt(e[0]) ? e[0] : e, null).pipe(ur(function(e) { + return n.apply(void 0, e) + })) + } + function Zr(d, l) { + return new Ut(function(r) { + var n = d.length; + if (0 !== n) + for (var s = new Array(n), a = 0, o = 0, e = 0; e < n; e++) + !function(t) { + var e = Lr(d[t]) + , i = !1; + r.add(e.subscribe({ + next: function(e) { + i || (i = !0, + o++), + s[t] = e + }, + error: function(e) { + return r.error(e) + }, + complete: function() { + ++a !== n && i || (o === n && r.next(l ? l.reduce(function(e, t, i) { + return e[t] = s[i], + e + }, {}) : s), + r.complete()) + } + })) + }(e); + else + r.complete() + } + ) + } + function en(e, i, r, t) { + return gt(r) && (t = r, + r = void 0), + t ? en(e, i, r).pipe(ur(function(e) { + return Tt(e) ? t.apply(void 0, e) : t(e) + })) : new Ut(function(t) { + !function e(t, i, r, n, s) { + var a; + if (function(e) { + return e && "function" == typeof e.addEventListener && "function" == typeof e.removeEventListener + }(t)) { + var o = t; + t.addEventListener(i, r, s), + a = function() { + return o.removeEventListener(i, r, s) + } + } else if (function(e) { + return e && "function" == typeof e.on && "function" == typeof e.off + }(t)) { + var d = t; + t.on(i, r), + a = function() { + return d.off(i, r) + } + } else if (function(e) { + return e && "function" == typeof e.addListener && "function" == typeof e.removeListener + }(t)) { + var l = t; + t.addListener(i, r), + a = function() { + return l.removeListener(i, r) + } + } else { + if (!t || !t.length) + throw new TypeError("Invalid event target"); + for (var u = 0, c = t.length; u < c; u++) + e(t[u], i, r, n, s) + } + n.add(a) + }(e, i, function(e) { + 1 < arguments.length ? t.next(Array.prototype.slice.call(arguments)) : t.next(e) + }, t, r) + } + ) + } + function tn(e, t, i) { + return void 0 === t && (t = Ti), + void 0 === i && (i = Ti), + Yr(function() { + return e() ? t : i + }) + } + function rn(e) { + return !Tt(e) && 0 <= e - parseFloat(e) + 1 + } + function nn() { + for (var e = [], t = 0; t < arguments.length; t++) + e[t] = arguments[t]; + var i = Number.POSITIVE_INFINITY + , r = null + , n = e[e.length - 1]; + return Li(n) ? (r = e.pop(), + 1 < e.length && "number" == typeof e[e.length - 1] && (i = e.pop())) : "number" == typeof n && (i = e.pop()), + null === r && 1 === e.length && e[0]instanceof Ut ? e[0] : Wr(i)(Fi(e, r)) + } + var sn = new Ut(sr); + function an(t, i) { + return function(e) { + return e.lift(new dn(t,i)) + } + } + var on, dn = (cn.prototype.call = function(e, t) { + return t.subscribe(new ln(e,this.predicate,this.thisArg)) + } + , + cn), ln = (lt(un, on = Pt), + un.prototype._next = function(e) { + var t; + try { + t = this.predicate.call(this.thisArg, e, this.count++) + } catch (e) { + return void this.destination.error(e) + } + t && this.destination.next(e) + } + , + un); + function un(e, t, i) { + e = on.call(this, e) || this; + return e.predicate = t, + e.thisArg = i, + e.count = 0, + e + } + function cn(e, t) { + this.predicate = e, + this.thisArg = t + } + function hn() { + for (var e = [], t = 0; t < arguments.length; t++) + e[t] = arguments[t]; + if (1 === e.length) { + if (!Tt(e[0])) + return e[0]; + e = e[0] + } + return Fi(e, void 0).lift(new fn) + } + var pn, fn = (yn.prototype.call = function(e, t) { + return t.subscribe(new mn(e)) + } + , + yn), mn = (lt(gn, pn = gr), + gn.prototype._next = function(e) { + this.observables.push(e) + } + , + gn.prototype._complete = function() { + var e = this.observables + , t = e.length; + if (0 === t) + this.destination.complete(); + else { + for (var i = 0; i < t && !this.hasFirst; i++) { + var r = Or(this, e[i], void 0, i); + this.subscriptions && this.subscriptions.push(r), + this.add(r) + } + this.observables = null + } + } + , + gn.prototype.notifyNext = function(e, t, i) { + if (!this.hasFirst) { + this.hasFirst = !0; + for (var r, n = 0; n < this.subscriptions.length; n++) + n !== i && ((r = this.subscriptions[n]).unsubscribe(), + this.remove(r)); + this.subscriptions = null + } + this.destination.next(t) + } + , + gn); + function gn(e) { + e = pn.call(this, e) || this; + return e.hasFirst = !1, + e.observables = [], + e.subscriptions = [], + e + } + function yn() {} + function vn(i, e, r) { + void 0 === i && (i = 0); + var n = -1; + return rn(e) ? n = Number(e) < 1 ? 1 : Number(e) : Li(e) && (r = e), + Li(r) || (r = er), + new Ut(function(e) { + var t = rn(i) ? i : +i - r.now(); + return r.schedule(Sn, t, { + index: 0, + period: n, + subscriber: e + }) + } + ) + } + function Sn(e) { + var t = e.index + , i = e.period + , r = e.subscriber; + if (r.next(t), + !r.closed) { + if (-1 === i) + return r.complete(); + e.index = t + 1, + this.schedule(e, i) + } + } + function bn() { + for (var e = [], t = 0; t < arguments.length; t++) + e[t] = arguments[t]; + var i = e[e.length - 1]; + return "function" == typeof i && e.pop(), + Fi(e, void 0).lift(new In(i)) + } + var Tn, En, In = (xn.prototype.call = function(e, t) { + return t.subscribe(new wn(e,this.resultSelector)) + } + , + xn), wn = (lt(Pn, En = Pt), + Pn.prototype._next = function(e) { + var t = this.iterators; + Tt(e) ? t.push(new On(e)) : "function" == typeof e[Er] ? t.push(new An(e[Er]())) : t.push(new kn(this.destination,this,e)) + } + , + Pn.prototype._complete = function() { + var e = this.iterators + , t = e.length; + if (this.unsubscribe(), + 0 !== t) { + this.active = t; + for (var i = 0; i < t; i++) { + var r = e[i]; + r.stillUnsubscribed ? this.destination.add(r.subscribe()) : this.active-- + } + } else + this.destination.complete() + } + , + Pn.prototype.notifyInactive = function() { + this.active--, + 0 === this.active && this.destination.complete() + } + , + Pn.prototype.checkIterators = function() { + for (var e = this.iterators, t = e.length, i = this.destination, r = 0; r < t; r++) + if ("function" == typeof (a = e[r]).hasValue && !a.hasValue()) + return; + for (var n = !1, s = [], r = 0; r < t; r++) { + var a, o = (a = e[r]).next(); + if (a.hasCompleted() && (n = !0), + o.done) + return void i.complete(); + s.push(o.value) + } + this.resultSelector ? this._tryresultSelector(s) : i.next(s), + n && i.complete() + } + , + Pn.prototype._tryresultSelector = function(e) { + var t; + try { + t = this.resultSelector.apply(this, e) + } catch (e) { + return void this.destination.error(e) + } + this.destination.next(t) + } + , + Pn), An = (Mn.prototype.hasValue = function() { + return !0 + } + , + Mn.prototype.next = function() { + var e = this.nextResult; + return this.nextResult = this.iterator.next(), + e + } + , + Mn.prototype.hasCompleted = function() { + var e = this.nextResult; + return Boolean(e && e.done) + } + , + Mn), On = (Dn.prototype[Er] = function() { + return this + } + , + Dn.prototype.next = function(e) { + var t = this.index++ + , i = this.array; + return t < this.length ? { + value: i[t], + done: !1 + } : { + value: null, + done: !0 + } + } + , + Dn.prototype.hasValue = function() { + return this.array.length > this.index + } + , + Dn.prototype.hasCompleted = function() { + return this.array.length === this.index + } + , + Dn), kn = (lt(Cn, Tn = Br), + Cn.prototype[Er] = function() { + return this + } + , + Cn.prototype.next = function() { + var e = this.buffer; + return 0 === e.length && this.isComplete ? { + value: null, + done: !0 + } : { + value: e.shift(), + done: !1 + } + } + , + Cn.prototype.hasValue = function() { + return 0 < this.buffer.length + } + , + Cn.prototype.hasCompleted = function() { + return 0 === this.buffer.length && this.isComplete + } + , + Cn.prototype.notifyComplete = function() { + 0 < this.buffer.length ? (this.isComplete = !0, + this.parent.notifyInactive()) : this.destination.complete() + } + , + Cn.prototype.notifyNext = function(e) { + this.buffer.push(e), + this.parent.checkIterators() + } + , + Cn.prototype.subscribe = function() { + return Vr(this.observable, new Fr(this)) + } + , + Cn); + function Cn(e, t, i) { + e = Tn.call(this, e) || this; + return e.parent = t, + e.observable = i, + e.stillUnsubscribed = !0, + e.buffer = [], + e.isComplete = !1, + e + } + function Dn(e) { + this.array = e, + this.index = 0, + this.length = 0, + this.length = e.length + } + function Mn(e) { + this.iterator = e, + this.nextResult = e.next() + } + function Pn(e, t, i) { + e = En.call(this, e) || this; + return e.resultSelector = t, + e.iterators = [], + e.active = 0, + e.resultSelector = "function" == typeof t ? t : void 0, + e + } + function xn(e) { + this.resultSelector = e + } + var Rn, Ln = (Fn.prototype.call = function(e, t) { + return t.subscribe(new _n(e,this.durationSelector)) + } + , + Fn), _n = (lt(Nn, Rn = Br), + Nn.prototype._next = function(e) { + if (this.value = e, + this.hasValue = !0, + !this.throttled) { + var t = void 0; + try { + t = (0, + this.durationSelector)(e) + } catch (e) { + return this.destination.error(e) + } + t = Vr(t, new Fr(this)); + !t || t.closed ? this.clearThrottle() : this.add(this.throttled = t) + } + } + , + Nn.prototype.clearThrottle = function() { + var e = this.value + , t = this.hasValue + , i = this.throttled; + i && (this.remove(i), + this.throttled = void 0, + i.unsubscribe()), + t && (this.value = void 0, + this.hasValue = !1, + this.destination.next(e)) + } + , + Nn.prototype.notifyNext = function() { + this.clearThrottle() + } + , + Nn.prototype.notifyComplete = function() { + this.clearThrottle() + } + , + Nn); + function Nn(e, t) { + e = Rn.call(this, e) || this; + return e.durationSelector = t, + e.hasValue = !1, + e + } + function Fn(e) { + this.durationSelector = e + } + function Bn(e, t) { + return void 0 === t && (t = er), + i = function() { + return vn(e, t) + } + , + function(e) { + return e.lift(new Ln(i)) + } + ; + var i + } + function Un(i) { + return function(e) { + var t = new Vn(i) + , e = e.lift(t); + return t.caught = e + } + } + var $n, Vn = (jn.prototype.call = function(e, t) { + return t.subscribe(new Kn(e,this.selector,this.caught)) + } + , + jn), Kn = (lt(Hn, $n = Br), + Hn.prototype.error = function(e) { + if (!this.isStopped) { + var t = void 0; + try { + t = this.selector(e, this.caught) + } catch (e) { + return void $n.prototype.error.call(this, e) + } + this._unsubscribeAndRecycle(); + var i = new Fr(this); + this.add(i); + t = Vr(t, i); + t !== i && this.add(t) + } + } + , + Hn); + function Hn(e, t, i) { + e = $n.call(this, e) || this; + return e.selector = t, + e.caught = i, + e + } + function jn(e) { + this.selector = e + } + function qn(e, t) { + return Kr(e, t, 1) + } + function Qn(t, i) { + return void 0 === i && (i = er), + function(e) { + return e.lift(new Wn(t,i)) + } + } + var Gn, Wn = (Yn.prototype.call = function(e, t) { + return t.subscribe(new zn(e,this.dueTime,this.scheduler)) + } + , + Yn), zn = (lt(Xn, Gn = Pt), + Xn.prototype._next = function(e) { + this.clearDebounce(), + this.lastValue = e, + this.hasValue = !0, + this.add(this.debouncedSubscription = this.scheduler.schedule(Jn, this.dueTime, this)) + } + , + Xn.prototype._complete = function() { + this.debouncedNext(), + this.destination.complete() + } + , + Xn.prototype.debouncedNext = function() { + var e; + this.clearDebounce(), + this.hasValue && (e = this.lastValue, + this.lastValue = null, + this.hasValue = !1, + this.destination.next(e)) + } + , + Xn.prototype.clearDebounce = function() { + var e = this.debouncedSubscription; + null !== e && (this.remove(e), + e.unsubscribe(), + this.debouncedSubscription = null) + } + , + Xn); + function Xn(e, t, i) { + e = Gn.call(this, e) || this; + return e.dueTime = t, + e.scheduler = i, + e.debouncedSubscription = null, + e.lastValue = null, + e.hasValue = !1, + e + } + function Yn(e, t) { + this.dueTime = e, + this.scheduler = t + } + function Jn(e) { + e.debouncedNext() + } + var Zn, es = (rs.prototype.call = function(e, t) { + return t.subscribe(new ts(e,this.defaultValue)) + } + , + rs), ts = (lt(is, Zn = Pt), + is.prototype._next = function(e) { + this.isEmpty = !1, + this.destination.next(e) + } + , + is.prototype._complete = function() { + this.isEmpty && this.destination.next(this.defaultValue), + this.destination.complete() + } + , + is); + function is(e, t) { + e = Zn.call(this, e) || this; + return e.defaultValue = t, + e.isEmpty = !0, + e + } + function rs(e) { + this.defaultValue = e + } + function ns(e) { + return e instanceof Date && !isNaN(+e) + } + function ss(e, t) { + void 0 === t && (t = er); + var i = ns(e) ? +e - t.now() : Math.abs(e); + return function(e) { + return e.lift(new os(i,t)) + } + } + var as, os = (cs.prototype.call = function(e, t) { + return t.subscribe(new ds(e,this.delay,this.scheduler)) + } + , + cs), ds = (lt(us, as = Pt), + us.dispatch = function(e) { + for (var t, i = e.source, r = i.queue, n = e.scheduler, s = e.destination; 0 < r.length && r[0].time - n.now() <= 0; ) + r.shift().notification.observe(s); + 0 < r.length ? (t = Math.max(0, r[0].time - n.now()), + this.schedule(e, t)) : (this.unsubscribe(), + i.active = !1) + } + , + us.prototype._schedule = function(e) { + this.active = !0, + this.destination.add(e.schedule(us.dispatch, this.delay, { + source: this, + destination: this.destination, + scheduler: e + })) + } + , + us.prototype.scheduleNotification = function(e) { + var t; + !0 !== this.errored && (t = this.scheduler, + e = new ls(t.now() + this.delay,e), + this.queue.push(e), + !1 === this.active && this._schedule(t)) + } + , + us.prototype._next = function(e) { + this.scheduleNotification(Vi.createNext(e)) + } + , + us.prototype._error = function(e) { + this.errored = !0, + this.queue = [], + this.destination.error(e), + this.unsubscribe() + } + , + us.prototype._complete = function() { + this.scheduleNotification(Vi.createComplete()), + this.unsubscribe() + } + , + us), ls = function(e, t) { + this.time = e, + this.notification = t + }; + function us(e, t, i) { + e = as.call(this, e) || this; + return e.delay = t, + e.scheduler = i, + e.queue = [], + e.active = !1, + e.errored = !1, + e + } + function cs(e, t) { + this.delay = e, + this.scheduler = t + } + var hs, ps, fs, ms = (Ts.prototype.call = function(e, t) { + return t.subscribe(new gs(e,this.delayDurationSelector)) + } + , + Ts), gs = (lt(bs, fs = gr), + bs.prototype.notifyNext = function(e, t, i, r, n) { + this.destination.next(e), + this.removeSubscription(n), + this.tryComplete() + } + , + bs.prototype.notifyError = function(e, t) { + this._error(e) + } + , + bs.prototype.notifyComplete = function(e) { + e = this.removeSubscription(e); + e && this.destination.next(e), + this.tryComplete() + } + , + bs.prototype._next = function(e) { + var t = this.index++; + try { + var i = this.delayDurationSelector(e, t); + i && this.tryDelay(i, e) + } catch (e) { + this.destination.error(e) + } + } + , + bs.prototype._complete = function() { + this.completed = !0, + this.tryComplete(), + this.unsubscribe() + } + , + bs.prototype.removeSubscription = function(e) { + e.unsubscribe(); + var t = this.delayNotifierSubscriptions.indexOf(e); + return -1 !== t && this.delayNotifierSubscriptions.splice(t, 1), + e.outerValue + } + , + bs.prototype.tryDelay = function(e, t) { + t = Or(this, e, t); + t && !t.closed && (this.destination.add(t), + this.delayNotifierSubscriptions.push(t)) + } + , + bs.prototype.tryComplete = function() { + this.completed && 0 === this.delayNotifierSubscriptions.length && this.destination.complete() + } + , + bs), ys = (lt(Ss, ps = Ut), + Ss.prototype._subscribe = function(e) { + this.subscriptionDelay.subscribe(new ys(e,this.source)) + } + , + lt(vs, hs = Pt), + vs.prototype._next = function(e) { + this.subscribeToSource() + } + , + vs.prototype._error = function(e) { + this.unsubscribe(), + this.parent.error(e) + } + , + vs.prototype._complete = function() { + this.unsubscribe(), + this.subscribeToSource() + } + , + vs.prototype.subscribeToSource = function() { + this.sourceSubscribed || (this.sourceSubscribed = !0, + this.unsubscribe(), + this.source.subscribe(this.parent)) + } + , + vs); + function vs(e, t) { + var i = hs.call(this) || this; + return i.parent = e, + i.source = t, + i.sourceSubscribed = !1, + i + } + function Ss(e, t) { + var i = ps.call(this) || this; + return i.source = e, + i.subscriptionDelay = t, + i + } + function bs(e, t) { + e = fs.call(this, e) || this; + return e.delayDurationSelector = t, + e.completed = !1, + e.delayNotifierSubscriptions = [], + e.index = 0, + e + } + function Ts(e) { + this.delayDurationSelector = e + } + function Es(t, i) { + return function(e) { + return e.lift(new ws(t,i)) + } + } + var Is, ws = (ks.prototype.call = function(e, t) { + return t.subscribe(new As(e,this.compare,this.keySelector)) + } + , + ks), As = (lt(Os, Is = Pt), + Os.prototype.compare = function(e, t) { + return e === t + } + , + Os.prototype._next = function(e) { + try { + var t = this.keySelector + , i = t ? t(e) : e + } catch (e) { + return this.destination.error(e) + } + t = !1; + if (this.hasKey) + try { + t = (0, + this.compare)(this.key, i) + } catch (e) { + return this.destination.error(e) + } + else + this.hasKey = !0; + t || (this.key = i, + this.destination.next(e)) + } + , + Os); + function Os(e, t, i) { + e = Is.call(this, e) || this; + return e.keySelector = i, + e.hasKey = !1, + "function" == typeof t && (e.compare = t), + e + } + function ks(e, t) { + this.compare = e, + this.keySelector = t + } + function Cs(t) { + return function(e) { + return 0 === t ? Ri() : e.lift(new Ms(t)) + } + } + var Ds, Ms = (Rs.prototype.call = function(e, t) { + return t.subscribe(new Ps(e,this.total)) + } + , + Rs), Ps = (lt(xs, Ds = Pt), + xs.prototype._next = function(e) { + var t = this.total + , i = ++this.count; + i <= t && (this.destination.next(e), + i === t && (this.destination.complete(), + this.unsubscribe())) + } + , + xs); + function xs(e, t) { + e = Ds.call(this, e) || this; + return e.total = t, + e.count = 0, + e + } + function Rs(e) { + if (this.total = e, + this.total < 0) + throw new ar + } + function Ls(t, n) { + return n ? function(e) { + return e.pipe(Ls(function(i, r) { + return Lr(t(i, r)).pipe(ur(function(e, t) { + return n(i, e, r, t) + })) + })) + } + : function(e) { + return e.lift(new Ns(t)) + } + } + var _s, Ns = (Us.prototype.call = function(e, t) { + return t.subscribe(new Fs(e,this.project)) + } + , + Us), Fs = (lt(Bs, _s = Br), + Bs.prototype._next = function(e) { + this.hasSubscription || this.tryNext(e) + } + , + Bs.prototype.tryNext = function(e) { + var t, i = this.index++; + try { + t = this.project(e, i) + } catch (e) { + return void this.destination.error(e) + } + this.hasSubscription = !0, + this._innerSub(t) + } + , + Bs.prototype._innerSub = function(e) { + var t = new Fr(this) + , i = this.destination; + i.add(t); + e = Vr(e, t); + e !== t && i.add(e) + } + , + Bs.prototype._complete = function() { + this.hasCompleted = !0, + this.hasSubscription || this.destination.complete(), + this.unsubscribe() + } + , + Bs.prototype.notifyNext = function(e) { + this.destination.next(e) + } + , + Bs.prototype.notifyError = function(e) { + this.destination.error(e) + } + , + Bs.prototype.notifyComplete = function() { + this.hasSubscription = !1, + this.hasCompleted && this.destination.complete() + } + , + Bs); + function Bs(e, t) { + e = _s.call(this, e) || this; + return e.project = t, + e.hasSubscription = !1, + e.hasCompleted = !1, + e.index = 0, + e + } + function Us(e) { + this.project = e + } + function $s(t) { + return function(e) { + return e.lift(new Ks(t)) + } + } + var Vs, Ks = (qs.prototype.call = function(e, t) { + return t.subscribe(new Hs(e,this.callback)) + } + , + qs), Hs = (lt(js, Vs = Pt), + js); + function js(e, t) { + e = Vs.call(this, e) || this; + return e.add(new wt(t)), + e + } + function qs(e) { + this.callback = e + } + function Qs(t) { + return function(e) { + return 0 === t ? Ri() : e.lift(new Ws(t)) + } + } + var Gs, Ws = (Ys.prototype.call = function(e, t) { + return t.subscribe(new zs(e,this.total)) + } + , + Ys), zs = (lt(Xs, Gs = Pt), + Xs.prototype._next = function(e) { + var t = this.ring + , i = this.total + , r = this.count++; + t.length < i ? t.push(e) : t[r % i] = e + } + , + Xs.prototype._complete = function() { + var e = this.destination + , t = this.count; + if (0 < t) + for (var i = this.count >= this.total ? this.total : this.count, r = this.ring, n = 0; n < i; n++) { + var s = t++ % i; + e.next(r[s]) + } + e.complete() + } + , + Xs); + function Xs(e, t) { + e = Gs.call(this, e) || this; + return e.total = t, + e.ring = new Array, + e.count = 0, + e + } + function Ys(e) { + if (this.total = e, + this.total < 0) + throw new ar + } + function Js(t) { + return function(e) { + return e.lift(new ea(t)) + } + } + var Zs, ea = (ra.prototype.call = function(e, t) { + return t.subscribe(new ta(e,this.value)) + } + , + ra), ta = (lt(ia, Zs = Pt), + ia.prototype._next = function(e) { + this.destination.next(this.value) + } + , + ia); + function ia(e, t) { + e = Zs.call(this, e) || this; + return e.value = t, + e + } + function ra(e) { + this.value = e + } + function na(t, i) { + var r = 2 <= arguments.length ? !0 : !1; + return function(e) { + return e.lift(new aa(t,i,r)) + } + } + var sa, aa = (la.prototype.call = function(e, t) { + return t.subscribe(new oa(e,this.accumulator,this.seed,this.hasSeed)) + } + , + la), oa = (lt(da, sa = Pt), + Object.defineProperty(da.prototype, "seed", { + get: function() { + return this._seed + }, + set: function(e) { + this.hasSeed = !0, + this._seed = e + }, + enumerable: !0, + configurable: !0 + }), + da.prototype._next = function(e) { + if (this.hasSeed) + return this._tryNext(e); + this.seed = e, + this.destination.next(e) + } + , + da.prototype._tryNext = function(e) { + var t, i = this.index++; + try { + t = this.accumulator(this.seed, e, i) + } catch (e) { + this.destination.error(e) + } + this.seed = t, + this.destination.next(t) + } + , + da); + function da(e, t, i, r) { + e = sa.call(this, e) || this; + return e.accumulator = t, + e._seed = i, + e.hasSeed = r, + e.index = 0, + e + } + function la(e, t, i) { + void 0 === i && (i = !1), + this.accumulator = e, + this.seed = t, + this.hasSeed = i + } + ua.prototype.call = function(e, t) { + var i = this.selector + , r = this.subjectFactory() + , e = i(r).subscribe(e); + return e.add(t.subscribe(r)), + e + } + ; + function ua(e, t) { + this.subjectFactory = e, + this.selector = t + } + function ca() { + return function(e) { + return e.lift(new pa) + } + } + var ha, pa = (ga.prototype.call = function(e, t) { + return t.subscribe(new fa(e)) + } + , + ga), fa = (lt(ma, ha = Pt), + ma.prototype._next = function(e) { + var t; + this.hasPrev ? t = [this.prev, e] : this.hasPrev = !0, + this.prev = e, + t && this.destination.next(t) + } + , + ma); + function ma(e) { + e = ha.call(this, e) || this; + return e.hasPrev = !1, + e + } + function ga() {} + function ya(t) { + return function(e) { + return e.lift(new Sa(t,e)) + } + } + var va, Sa = (Ea.prototype.call = function(e, t) { + return t.subscribe(new ba(e,this.notifier,this.source)) + } + , + Ea), ba = (lt(Ta, va = Br), + Ta.prototype.error = function(e) { + if (!this.isStopped) { + var t = this.errors + , i = this.retries + , r = this.retriesSubscription; + if (i) + this.errors = void 0, + this.retriesSubscription = void 0; + else { + t = new zt; + try { + i = (0, + this.notifier)(t) + } catch (e) { + return va.prototype.error.call(this, e) + } + r = Vr(i, new Fr(this)) + } + this._unsubscribeAndRecycle(), + this.errors = t, + this.retries = i, + this.retriesSubscription = r, + t.next(e) + } + } + , + Ta.prototype._unsubscribe = function() { + var e = this.errors + , t = this.retriesSubscription; + e && (e.unsubscribe(), + this.errors = void 0), + t && (t.unsubscribe(), + this.retriesSubscription = void 0), + this.retries = void 0 + } + , + Ta.prototype.notifyNext = function() { + var e = this._unsubscribe; + this._unsubscribe = null, + this._unsubscribeAndRecycle(), + this._unsubscribe = e, + this.source.subscribe(this) + } + , + Ta); + function Ta(e, t, i) { + e = va.call(this, e) || this; + return e.notifier = t, + e.source = i, + e + } + function Ea(e, t) { + this.notifier = e, + this.source = t + } + function Ia() { + return new zt + } + function wa() { + return function(e) { + return ii()((t = e, + i = "function" == typeof (r = Ia) ? r : function() { + return r + } + , + (e = Object.create(t, fi)).source = t, + e.subjectFactory = i, + e)); + var t, i, r + } + } + function Aa(e, t, i) { + var c = e && "object" == typeof e ? e : { + bufferSize: e, + windowTime: t, + refCount: !1, + scheduler: i + }; + return function(e) { + return e.lift((e = c.bufferSize, + n = void 0 === e ? Number.POSITIVE_INFINITY : e, + e = c.windowTime, + s = void 0 === e ? Number.POSITIVE_INFINITY : e, + a = c.refCount, + o = c.scheduler, + d = 0, + u = l = !1, + function(e) { + var t; + d++, + !i || l ? (l = !1, + i = new Xi(n,s,o), + t = i.subscribe(this), + r = e.subscribe({ + next: function(e) { + i.next(e) + }, + error: function(e) { + l = !0, + i.error(e) + }, + complete: function() { + u = !0, + r = void 0, + i.complete() + } + }), + u && (r = void 0)) : t = i.subscribe(this), + this.add(function() { + d--, + t.unsubscribe(), + t = void 0, + r && !u && a && 0 === d && (r.unsubscribe(), + i = r = void 0) + }) + } + )); + var i, r, n, s, a, o, d, l, u + } + } + function Oa(t) { + return function(e) { + return e.lift(new Ca(t)) + } + } + var ka, Ca = (Pa.prototype.call = function(e, t) { + return t.subscribe(new Da(e,this.total)) + } + , + Pa), Da = (lt(Ma, ka = Pt), + Ma.prototype._next = function(e) { + ++this.count > this.total && this.destination.next(e) + } + , + Ma); + function Ma(e, t) { + e = ka.call(this, e) || this; + return e.total = t, + e.count = 0, + e + } + function Pa(e) { + this.total = e + } + function xa() { + for (var t = [], e = 0; e < arguments.length; e++) + t[e] = arguments[e]; + var i = t[t.length - 1]; + return Li(i) ? (t.pop(), + function(e) { + return Xr(t, e, i) + } + ) : function(e) { + return Xr(t, e) + } + } + function Ra(t, n) { + return "function" == typeof n ? function(e) { + return e.pipe(Ra(function(i, r) { + return Lr(t(i, r)).pipe(ur(function(e, t) { + return n(i, e, r, t) + })) + })) + } + : function(e) { + return e.lift(new _a(t)) + } + } + var La, _a = (Ba.prototype.call = function(e, t) { + return t.subscribe(new Na(e,this.project)) + } + , + Ba), Na = (lt(Fa, La = Br), + Fa.prototype._next = function(e) { + var t, i = this.index++; + try { + t = this.project(e, i) + } catch (e) { + return void this.destination.error(e) + } + this._innerSub(t) + } + , + Fa.prototype._innerSub = function(e) { + var t = this.innerSubscription; + t && t.unsubscribe(); + var i = new Fr(this) + , t = this.destination; + t.add(i), + this.innerSubscription = Vr(e, i), + this.innerSubscription !== i && t.add(this.innerSubscription) + } + , + Fa.prototype._complete = function() { + var e = this.innerSubscription; + e && !e.closed || La.prototype._complete.call(this), + this.unsubscribe() + } + , + Fa.prototype._unsubscribe = function() { + this.innerSubscription = void 0 + } + , + Fa.prototype.notifyComplete = function() { + this.innerSubscription = void 0, + this.isStopped && La.prototype._complete.call(this) + } + , + Fa.prototype.notifyNext = function(e) { + this.destination.next(e) + } + , + Fa); + function Fa(e, t) { + e = La.call(this, e) || this; + return e.project = t, + e.index = 0, + e + } + function Ba(e) { + this.project = e + } + function Ua(e, t) { + return t ? Ra(function() { + return e + }, t) : Ra(function() { + return e + }) + } + function $a(t) { + return function(e) { + return e.lift(new Ka(t)) + } + } + var Va, Ka = (qa.prototype.call = function(e, t) { + var i = new Ha(e) + , e = Vr(this.notifier, new Fr(i)); + return e && !i.seenValue ? (i.add(e), + t.subscribe(i)) : i + } + , + qa), Ha = (lt(ja, Va = Br), + ja.prototype.notifyNext = function() { + this.seenValue = !0, + this.complete() + } + , + ja.prototype.notifyComplete = function() {} + , + ja); + function ja(e) { + e = Va.call(this, e) || this; + return e.seenValue = !1, + e + } + function qa(e) { + this.notifier = e + } + function Qa(t, i) { + return void 0 === i && (i = !1), + function(e) { + return e.lift(new Wa(t,i)) + } + } + var Ga, Wa = (Ya.prototype.call = function(e, t) { + return t.subscribe(new za(e,this.predicate,this.inclusive)) + } + , + Ya), za = (lt(Xa, Ga = Pt), + Xa.prototype._next = function(e) { + var t, i = this.destination; + try { + t = this.predicate(e, this.index++) + } catch (e) { + return void i.error(e) + } + this.nextOrComplete(e, t) + } + , + Xa.prototype.nextOrComplete = function(e, t) { + var i = this.destination; + Boolean(t) ? i.next(e) : (this.inclusive && i.next(e), + i.complete()) + } + , + Xa); + function Xa(e, t, i) { + e = Ga.call(this, e) || this; + return e.predicate = t, + e.inclusive = i, + e.index = 0, + e + } + function Ya(e, t) { + this.predicate = e, + this.inclusive = t + } + function Ja(t, i, r) { + return function(e) { + return e.lift(new eo(t,i,r)) + } + } + var Za, eo = (no.prototype.call = function(e, t) { + return t.subscribe(new to(e,this.nextOrObserver,this.error,this.complete)) + } + , + no), to = (lt(ro, Za = Pt), + ro.prototype._next = function(e) { + try { + this._tapNext.call(this._context, e) + } catch (e) { + return void this.destination.error(e) + } + this.destination.next(e) + } + , + ro.prototype._error = function(e) { + try { + this._tapError.call(this._context, e) + } catch (e) { + return void this.destination.error(e) + } + this.destination.error(e) + } + , + ro.prototype._complete = function() { + try { + this._tapComplete.call(this._context) + } catch (e) { + return void this.destination.error(e) + } + return this.destination.complete() + } + , + ro), io = { + leading: !0, + trailing: !1 + }; + function ro(e, t, i, r) { + e = Za.call(this, e) || this; + return e._tapNext = sr, + e._tapError = sr, + e._tapComplete = sr, + e._tapError = i || sr, + e._tapComplete = r || sr, + gt(t) ? (e._context = e)._tapNext = t : t && (e._context = t, + e._tapNext = t.next || sr, + e._tapError = t.error || sr, + e._tapComplete = t.complete || sr), + e + } + function no(e, t, i) { + this.nextOrObserver = e, + this.error = t, + this.complete = i + } + function so(t, i, r) { + return void 0 === i && (i = er), + void 0 === r && (r = io), + function(e) { + return e.lift(new oo(t,i,r.leading,r.trailing)) + } + } + var ao, oo = (co.prototype.call = function(e, t) { + return t.subscribe(new lo(e,this.duration,this.scheduler,this.leading,this.trailing)) + } + , + co), lo = (lt(uo, ao = Pt), + uo.prototype._next = function(e) { + this.throttled ? this.trailing && (this._trailingValue = e, + this._hasTrailingValue = !0) : (this.add(this.throttled = this.scheduler.schedule(ho, this.duration, { + subscriber: this + })), + this.leading ? this.destination.next(e) : this.trailing && (this._trailingValue = e, + this._hasTrailingValue = !0)) + } + , + uo.prototype._complete = function() { + this._hasTrailingValue && this.destination.next(this._trailingValue), + this.destination.complete() + } + , + uo.prototype.clearThrottle = function() { + var e = this.throttled; + e && (this.trailing && this._hasTrailingValue && (this.destination.next(this._trailingValue), + this._trailingValue = null, + this._hasTrailingValue = !1), + e.unsubscribe(), + this.remove(e), + this.throttled = null) + } + , + uo); + function uo(e, t, i, r, n) { + e = ao.call(this, e) || this; + return e.duration = t, + e.scheduler = i, + e.leading = r, + e.trailing = n, + e._hasTrailingValue = !1, + e._trailingValue = null, + e + } + function co(e, t, i, r) { + this.duration = e, + this.scheduler = t, + this.leading = i, + this.trailing = r + } + function ho(e) { + e.subscriber.clearThrottle() + } + var po, fo = (yo.prototype.call = function(e, t) { + return t.subscribe(new mo(e,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler)) + } + , + yo), mo = (lt(go, po = Br), + go.dispatchTimeout = function(e) { + var t = e.withObservable; + e._unsubscribeAndRecycle(), + e.add(Vr(t, new Fr(e))) + } + , + go.prototype.scheduleTimeout = function() { + var e = this.action; + e ? this.action = e.schedule(this, this.waitFor) : this.add(this.action = this.scheduler.schedule(go.dispatchTimeout, this.waitFor, this)) + } + , + go.prototype._next = function(e) { + this.absoluteTimeout || this.scheduleTimeout(), + po.prototype._next.call(this, e) + } + , + go.prototype._unsubscribe = function() { + this.action = void 0, + this.scheduler = null, + this.withObservable = null + } + , + go); + function go(e, t, i, r, n) { + e = po.call(this, e) || this; + return e.absoluteTimeout = t, + e.waitFor = i, + e.withObservable = r, + e.scheduler = n, + e.scheduleTimeout(), + e + } + function yo(e, t, i, r) { + this.waitFor = e, + this.absoluteTimeout = t, + this.withObservable = i, + this.scheduler = r + } + function vo(e, t) { + return void 0 === t && (t = er), + r = e, + n = Ui(new or), + void 0 === (s = t) && (s = er), + function(e) { + var t = ns(r) + , i = t ? +r - s.now() : Math.abs(r); + return e.lift(new fo(i,t,n,s)) + } + ; + var r, n, s + } + function So() { + for (var i = [], e = 0; e < arguments.length; e++) + i[e] = arguments[e]; + return function(e) { + var t; + return "function" == typeof i[i.length - 1] && (t = i.pop()), + e.lift(new Eo(i,t)) + } + } + var bo, To, Eo = (ko.prototype.call = function(e, t) { + return t.subscribe(new Io(e,this.observables,this.project)) + } + , + ko), Io = (lt(Oo, bo = gr), + Oo.prototype.notifyNext = function(e, t, i) { + this.values[i] = t; + t = this.toRespond; + 0 < t.length && (-1 !== (i = t.indexOf(i)) && t.splice(i, 1)) + } + , + Oo.prototype.notifyComplete = function() {} + , + Oo.prototype._next = function(e) { + 0 === this.toRespond.length && (e = [e].concat(this.values), + this.project ? this._tryProject(e) : this.destination.next(e)) + } + , + Oo.prototype._tryProject = function(e) { + var t; + try { + t = this.project.apply(this, e) + } catch (e) { + return void this.destination.error(e) + } + this.destination.next(t) + } + , + Oo), wo = { + type: null, + entityIds: null, + skip: !1 + }, Ao = !1; + function Oo(e, t, i) { + var r = bo.call(this, e) || this; + r.observables = t, + r.project = i, + r.toRespond = []; + var n = t.length; + r.values = new Array(n); + for (var s = 0; s < n; s++) + r.toRespond.push(s); + for (s = 0; s < n; s++) { + var a = t[s]; + r.add(Or(r, a, void 0, s)) + } + return r + } + function ko(e, t) { + this.observables = e, + this.project = t + } + function Co(e, t) { + Do(e, t), + Ao = !0 + } + function Do(e, t) { + !1 === Ao && (wo.type = e, + wo.entityIds = t) + } + function Mo(e, t) { + return e.hasOwnProperty(t) + } + function Po(e) { + return null == e + } + function xo(e) { + return Po(e) ? [] : Array.isArray(e) ? e : [e] + } + (mu = To = To || {}).Set = "Set", + mu.Add = "Add", + mu.Update = "Update", + mu.Remove = "Remove"; + var Ro = "undefined" != typeof window + , Lo = !0; + function _o(e) { + var t = typeof e; + return null != e && ("object" == t || "function" == t) + } + function No(e) { + return Array.isArray(e) + } + function Fo(e) { + return !1 === Po(e) + } + function Bo(e) { + return No(e) && 0 === e.length + } + function Uo(e) { + return "function" == typeof e + } + function $o(e) { + return void 0 === e + } + function Vo(e) { + return e.hasOwnProperty("active") + } + function Ko(e) { + return No(e) + } + function Ho(e) { + var t, i = e.active, r = e.ids, n = e.entities; + return Ko(i) ? (t = r, + (r = (e = i).filter(function(e) { + return -1 < t.indexOf(e) + })).length === e.length ? e : r) : !1 === Mo(n, i) ? null : i + } + function jo(e, t) { + var i, r, n = {}; + try { + for (var s = pt(Object.keys(e)), a = s.next(); !a.done; a = s.next()) { + var o = a.value; + n[o] = t(e[o]) + } + } catch (e) { + i = { + error: e + } + } finally { + try { + a && !a.done && (r = s.return) && r.call(s) + } finally { + if (i) + throw i.error + } + } + return n + } + var qo = { + resettable: !1, + ttl: null, + producerFn: void 0 + }; + function Qo(t) { + Object.freeze(t); + var i = "function" == typeof t + , r = Object.prototype.hasOwnProperty; + return Object.getOwnPropertyNames(t).forEach(function(e) { + !r.call(t, e) || i && ("caller" === e || "callee" === e || "arguments" === e) || null === t[e] || "object" != typeof t[e] && "function" != typeof t[e] || Object.isFrozen(t[e]) || Qo(t[e]) + }), + t + } + var Go, Wo = new zt, zo = new Xi(50,5e3), Xo = new zt; + function Yo(e) { + return null != e && "" + e != "false" + } + function Jo(e) { + return Yo(e) && "Object" === e.constructor.name + } + lt(function(e) { + return Go.call(this, e) || this + }, Go = Error); + var Zo = {} + , ed = {}; + Ro && (window.$$stores = Zo, + window.$$queries = ed); + var td = new zt + , id = new gi(!1) + , rd = { + activeTransactions: 0, + batchTransaction: null + }; + function nd() { + return 0 < rd.activeTransactions + } + function sd(e, t) { + void 0 === t && (t = void 0), + nd() || (rd.batchTransaction = new zt), + rd.activeTransactions++, + id.next(!0); + try { + return e.apply(t) + } finally { + Co("@Transaction"), + 0 == --rd.activeTransactions && (rd.batchTransaction.next(!0), + rd.batchTransaction.complete(), + id.next(!1), + td.next(!0)) + } + } + function ad() { + return function(e, t, i) { + var r = i.value; + return i.value = function() { + for (var e = this, t = [], i = 0; i < arguments.length; i++) + t[i] = arguments[i]; + return sd(function() { + return r.apply(e, t) + }, this) + } + , + i + } + } + function od(t) { + return function(e) { + return e.pipe(Ja(function(e) { + return sd(function() { + return t(e) + }) + })) + } + } + var dd = (ld.prototype.setLoading = function(t) { + (t = void 0 === t ? !1 : t) !== this._value().loading && (Lo && Do("Set Loading"), + this._setState(function(e) { + return ut({}, e, { + loading: t + }) + })) + } + , + ld.prototype.setHasCache = function(e, t) { + var i, r = this; + void 0 === t && (t = { + restartTTL: !1 + }), + e !== this.cache.active.value && this.cache.active.next(e), + t.restartTTL && (i = this.getCacheTTL()) && (null !== this.cache.ttl && clearTimeout(this.cache.ttl), + this.cache.ttl = setTimeout(function() { + return r.setHasCache(!1) + }, i)) + } + , + ld.prototype.getValue = function() { + return this.storeValue + } + , + ld.prototype.setError = function(t) { + t !== this._value().error && (Lo && Do("Set Error"), + this._setState(function(e) { + return ut({}, e, { + error: t + }) + })) + } + , + ld.prototype._select = function(t) { + return this.store.asObservable().pipe(ur(function(e) { + return t(e.state) + }), Es()) + } + , + ld.prototype._value = function() { + return this.storeValue + } + , + ld.prototype._cache = function() { + return this.cache.active + } + , + Object.defineProperty(ld.prototype, "config", { + get: function() { + return this.constructor.akitaConfig || {} + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(ld.prototype, "storeName", { + get: function() { + return this.config.storeName || this.options.storeName || this.options.name + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(ld.prototype, "deepFreeze", { + get: function() { + return this.config.deepFreezeFn || this.options.deepFreezeFn || Qo + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(ld.prototype, "cacheConfig", { + get: function() { + return this.config.cache || this.options.cache + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(ld.prototype, "_producerFn", { + get: function() { + return this.config.producerFn || this.options.producerFn || qo.producerFn + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(ld.prototype, "resettable", { + get: function() { + return (Fo(this.config.resettable) ? this.config : this.options).resettable + }, + enumerable: !0, + configurable: !0 + }), + ld.prototype._setState = function(e, t) { + var i, r = this; + if (void 0 === t && (t = !0), + Uo(e) ? (i = e(this._value()), + this.storeValue = Lo ? this.deepFreeze(i) : i) : this.storeValue = e, + !this.store) + return this.store = new gi({ + state: this.storeValue + }), + void (Lo && this.store.subscribe(function(e) { + var t = e.action; + t && (e = r.storeName, + Xo.next({ + storeName: e, + action: t + })) + })); + nd() ? this.handleTransaction() : this.dispatch(this.storeValue, t) + } + , + ld.prototype.reset = function() { + var e = this; + this.isResettable() ? (Lo && Do("Reset"), + this._setState(function() { + return Object.assign({}, e._initialState) + }), + this.setHasCache(!1)) : Lo && console.warn("You need to enable the reset functionality") + } + , + ld.prototype.update = function(e) { + Lo && Do("Update"); + var t = this._value() + , e = Uo(e) ? Uo(this._producerFn) ? this._producerFn(t, e) : e(t) : e + , e = this.akitaPreUpdate(t, ut({}, t, e)) + , e = Jo(t) ? e : new t.constructor(e); + this._setState(e) + } + , + ld.prototype.updateStoreConfig = function(e) { + this.options = ut({}, this.options, e) + } + , + ld.prototype.akitaPreUpdate = function(e, t) { + return t + } + , + ld.prototype.ngOnDestroy = function() { + this.destroy() + } + , + ld.prototype.destroy = function() { + var e; + Ro && window.hmrEnabled || this !== Zo[this.storeName] || (delete Zo[this.storeName], + e = this.storeName, + Wo.next(e), + this.setHasCache(!1), + this.cache.active.complete(), + this.store.complete()) + } + , + ld.prototype.onInit = function(e) { + var t, i; + (Zo[this.storeName] = this)._setState(function() { + return e + }), + i = this.storeName, + zo.next(i), + this.isResettable() && (this._initialState = e), + Lo && (t = this.storeName, + i = this.constructor.name, + t || console.error("@StoreConfig({ name }) is missing in " + i)) + } + , + ld.prototype.dispatch = function(e, t) { + var i = void 0; + (t = void 0 === t ? !0 : t) && (i = wo, + Ao = !1), + this.store.next({ + state: e, + action: i + }) + } + , + ld.prototype.watchTransaction = function() { + var e = this; + (rd.batchTransaction ? rd.batchTransaction.asObservable() : Bi(!0)).subscribe(function() { + e.inTransaction = !1, + e.dispatch(e._value()) + }) + } + , + ld.prototype.isResettable = function() { + return !1 !== this.resettable && (this.resettable || qo.resettable) + } + , + ld.prototype.handleTransaction = function() { + this.inTransaction || (this.watchTransaction(), + this.inTransaction = !0) + } + , + ld.prototype.getCacheTTL = function() { + return this.cacheConfig && this.cacheConfig.ttl || qo.ttl + } + , + ld); + function ld(e, t) { + this.options = t = void 0 === t ? {} : t, + this.inTransaction = !1, + this.cache = { + active: new gi(!1), + ttl: null + }, + this.onInit(e) + } + var ud, cd, hd, pd = (lt(gd, hd = dd), + Object.defineProperty(gd.prototype, "selectEntityAction$", { + get: function() { + return this.entityActions.asObservable() + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(gd.prototype, "selectEntityIdChanges$", { + get: function() { + return this.entityIdChanges.asObservable() + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(gd.prototype, "idKey", { + get: function() { + return this.config.idKey || this.options.idKey || "id" + }, + enumerable: !0, + configurable: !0 + }), + gd.prototype.set = function(a, o) { + var d, l = this; + void 0 === o && (o = {}), + Po(a) || (Lo && Do("Set Entity"), + d = this.akitaPreAddEntity === gd.prototype.akitaPreAddEntity, + this.setHasCache(!0, { + restartTTL: !0 + }), + this._setState(function(e) { + var t, i, r, n, s, e = (t = { + state: e, + entities: a, + idKey: l.idKey, + preAddEntity: l.akitaPreAddEntity, + isNativePreAdd: d + }, + r = t.state, + n = t.entities, + s = t.idKey, + e = t.preAddEntity, + t = t.isNativePreAdd, + e = No(n) ? (i = (s = function(e, t, i) { + var r, n, s = { + entities: {}, + ids: [] + }; + try { + for (var a = pt(e), o = a.next(); !o.done; o = a.next()) { + var d = i(o.value); + s.entities[d[t]] = d, + s.ids.push(d[t]) + } + } catch (e) { + r = { + error: e + } + } finally { + try { + o && !o.done && (n = a.return) && n.call(a) + } finally { + if (r) + throw r.error + } + } + return s + }(n, s, e)).entities, + s.ids) : n.entities && n.ids ? (i = t ? n.entities : jo(n.entities, e), + n.ids) : (i = t ? n : jo(n, e), + Object.keys(i).map(function(e) { + return isNaN(e) ? e : Number(e) + })), + e = ut({}, r, { + entities: i, + ids: e, + loading: !1 + }), + Vo(r) && (e.active = Ho(e)), + e); + return !1 === $o(o.activeId) && (e.active = o.activeId), + e + }), + this.hasInitialUIState() && this.handleUICreation(), + this.entityActions.next({ + type: To.Set, + ids: this.ids + })) + } + , + gd.prototype.add = function(e, t) { + void 0 === t && (t = { + loading: !1 + }); + var i, e = xo(e); + Bo(e) || (i = function(e) { + var t, i, r = e.state, n = e.entities, s = e.idKey, a = e.options, o = void 0 === a ? {} : a, d = e.preAddEntity, l = {}, u = [], c = !1; + try { + for (var h = pt(n), p = h.next(); !p.done; p = h.next()) { + var f, m, g = p.value; + !1 === Mo(r.entities, g[s]) && (l[m = (f = d(g))[s]] = f, + o.prepend ? u.unshift(m) : u.push(m), + c = !0) + } + } catch (e) { + t = { + error: e + } + } finally { + try { + p && !p.done && (i = h.return) && i.call(h) + } finally { + if (t) + throw t.error + } + } + return c ? { + newState: ut({}, r, { + entities: ut({}, r.entities, l), + ids: o.prepend ? mt(u, r.ids) : mt(r.ids, u) + }), + newIds: u + } : null + }({ + state: this._value(), + preAddEntity: this.akitaPreAddEntity, + entities: e, + idKey: this.idKey, + options: t + })) && (Lo && Do("Add Entity"), + i.newState.loading = t.loading, + this._setState(function() { + return i.newState + }), + this.hasInitialUIState() && this.handleUICreation(!0), + this.entityActions.next({ + type: To.Add, + ids: i.newIds + })) + } + , + gd.prototype.update = function(t, i) { + var r, n, s = this; + $o(i) ? hd.prototype.update.call(this, t) : (n = [], + Bo(n = Uo(t) ? this.ids.filter(function(e) { + return t(s.entities[e]) + }) : Po(t) ? this.ids : xo(t)) || (Lo && Do("Update Entity", n), + this._setState(function(e) { + return function(e) { + var t = e.state + , i = e.ids + , r = e.idKey + , n = e.newStateOrFn + , s = e.preUpdateEntity + , a = e.producerFn + , o = e.onEntityIdChanges + , d = {} + , l = !1; + try { + for (var u = pt(i), c = u.next(); !c.done; c = u.next()) { + var h, p, f, m, g, y, v = c.value; + !1 !== Mo(t.entities, v) && (h = t.entities[v], + p = void 0, + f = (p = Uo(n) ? Uo(a) ? a(h, n) : n(h) : n).hasOwnProperty(r) && p[r] !== h[r], + y = void 0, + m = v, + f && (l = !0, + m = p[r]), + g = ut({}, h, p), + y = Jo(h) ? g : new (Jo(p) ? h : p).constructor(g), + d[m] = s(h, y)) + } + } catch (e) { + T = { + error: e + } + } finally { + try { + c && !c.done && (b = u.return) && b.call(u) + } finally { + if (T) + throw T.error + } + } + var S, b = t.ids, T = t.entities; + return l && (S = ft(i, 1)[0], + T = function(e, t) { + var i = {}; + for (n in e) + Object.prototype.hasOwnProperty.call(e, n) && t.indexOf(n) < 0 && (i[n] = e[n]); + if (null != e && "function" == typeof Object.getOwnPropertySymbols) + for (var r = 0, n = Object.getOwnPropertySymbols(e); r < n.length; r++) + t.indexOf(n[r]) < 0 && Object.prototype.propertyIsEnumerable.call(e, n[r]) && (i[n[r]] = e[n[r]]); + return i + }(t.entities, ["symbol" == typeof S ? S : S + ""]), + b = t.ids.map(function(e) { + return e === S ? m : e + }), + o(S, m)), + ut({}, t, { + entities: ut({}, T, d), + ids: b + }) + }({ + idKey: s.idKey, + ids: n, + preUpdateEntity: s.akitaPreUpdateEntity, + state: e, + newStateOrFn: i, + producerFn: s._producerFn, + onEntityIdChanges: function(e, t) { + r = { + oldId: e, + newId: t + }, + s.entityIdChanges.next(ut({}, r, { + pending: !0 + })) + } + }) + }), + r && this.entityIdChanges.next(ut({}, r, { + pending: !1 + })), + this.entityActions.next({ + type: To.Update, + ids: n + }))) + } + , + gd.prototype.upsert = function(e, i, r, t) { + var n = this; + void 0 === t && (t = {}); + var s = xo(e) + , e = function(t) { + return function(e) { + return Mo(n.entities, e) === t + } + } + , a = Uo(r) ? t.baseClass : r ? r.baseClass : void 0 + , o = Uo(a) + , t = s.filter(e(!0)) + , e = s.filter(e(!1)).map(function(e) { + var t = "function" == typeof i ? i({}) : i + , t = Uo(r) ? r(e, t) : t + , t = ut({}, t, ((t = {})[n.idKey] = e, + t)); + return o ? new a(t) : t + }); + this.update(t, i), + this.add(e), + Lo && Co("Upsert Entity") + } + , + gd.prototype.upsertMany = function(e, t) { + var i, r; + void 0 === t && (t = {}); + var n = [] + , s = [] + , a = {}; + try { + for (var o = pt(e), d = o.next(); !d.done; d = o.next()) { + var l, u, c, h, p, f, m = d.value, g = this.akitaPreCheckEntity(m), y = g[this.idKey]; + Mo(this.entities, y) ? (l = this._value().entities[y], + u = ut({}, this._value().entities[y], g), + c = t.baseClass ? new t.baseClass(u) : u, + f = (h = this.akitaPreUpdateEntity(l, c))[this.idKey], + a[f] = h, + s.push(f)) : (p = t.baseClass ? new t.baseClass(g) : g, + f = (h = this.akitaPreAddEntity(p))[this.idKey], + n.push(f), + a[f] = h) + } + } catch (e) { + i = { + error: e + } + } finally { + try { + d && !d.done && (r = o.return) && r.call(o) + } finally { + if (i) + throw i.error + } + } + Lo && Co("Upsert Many"), + this._setState(function(e) { + return ut({}, e, { + ids: n.length ? mt(e.ids, n) : e.ids, + entities: ut({}, e.entities, a), + loading: !!t.loading + }) + }), + s.length && this.entityActions.next({ + type: To.Update, + ids: s + }), + n.length && this.entityActions.next({ + type: To.Add, + ids: n + }), + n.length && this.hasUIStore() && this.handleUICreation(!0) + } + , + gd.prototype.replace = function(e, t) { + var i, r, n = xo(e); + if (!Bo(n)) { + var s = {}; + try { + for (var a = pt(n), o = a.next(); !o.done; o = a.next()) { + var d = o.value; + t[this.idKey] = d, + s[d] = t + } + } catch (e) { + i = { + error: e + } + } finally { + try { + o && !o.done && (r = a.return) && r.call(a) + } finally { + if (i) + throw i.error + } + } + Lo && Do("Replace Entity", e), + this._setState(function(e) { + return ut({}, e, { + entities: ut({}, e.entities, s) + }) + }) + } + } + , + gd.prototype.move = function(e, t) { + var i = this.ids.slice(); + i.splice(t < 0 ? i.length + t : t, 0, i.splice(e, 1)[0]), + Lo && Do("Move Entity"), + this._setState(function(e) { + return ut({}, e, { + entities: ut({}, e.entities), + ids: i + }) + }) + } + , + gd.prototype.remove = function(t) { + var e, i, r = this; + Bo(this.ids) || (e = Fo(t), + i = [], + Bo(i = Uo(t) ? this.ids.filter(function(e) { + return t(r.entities[e]) + }) : e ? xo(t) : this.ids) || (Lo && Do("Remove Entity", i), + this._setState(function(e) { + return function(e) { + var t, i = e.state, r = e.ids; + if (Po(r)) + return ut({}, i, { + entities: {}, + ids: [], + active: Ko(i.active) ? [] : null + }); + var n = i.entities + , s = {}; + try { + for (var a = pt(i.ids), o = a.next(); !o.done; o = a.next()) { + var d = o.value; + !1 === r.includes(d) && (s[d] = n[d]) + } + } catch (e) { + l = { + error: e + } + } finally { + try { + o && !o.done && (t = a.return) && t.call(a) + } finally { + if (l) + throw l.error + } + } + var l = ut({}, i, { + entities: s, + ids: i.ids.filter(function(e) { + return !1 === r.includes(e) + }) + }); + return Vo(i) && (l.active = Ho(l)), + l + }({ + state: e, + ids: i + }) + }), + e || this.setHasCache(!1), + this.handleUIRemove(i), + this.entityActions.next({ + type: To.Remove, + ids: i + }))) + } + , + gd.prototype.updateActive = function(e) { + var t = xo(this.active); + Lo && Do("Update Active", t), + this.update(t, e) + } + , + gd.prototype.setActive = function(e) { + e = function(e, t, i) { + var r; + if (No(e)) + r = e; + else if (_o(e)) { + if (Po(i)) + return; + e = Object.assign({ + wrap: !0 + }, e); + var n = t.indexOf(i); + if (e.prev) { + var s = 0 === n; + if (s && !e.wrap) + return; + r = s ? t[t.length - 1] : t[n - 1] + } else if (e.next) { + s = t.length === n + 1; + if (s && !e.wrap) + return; + r = s ? t[0] : t[n + 1] + } + } else { + if (e === i) + return; + r = e + } + return r + }(e, this.ids, this.active); + void 0 !== e && (Lo && Do("Set Active", e), + this._setActive(e)) + } + , + gd.prototype.addActive = function(e) { + var t = this + , i = xo(e); + Bo(i) || i.every(function(e) { + return -1 < t.active.indexOf(e) + }) || (Lo && Do("Add Active", e), + this._setState(function(e) { + var t = Array.from(new Set(mt(e.active, i))); + return ut({}, e, { + active: t + }) + })) + } + , + gd.prototype.removeActive = function(e) { + var t = this + , i = xo(e); + Bo(i) || i.some(function(e) { + return -1 < t.active.indexOf(e) + }) && (Lo && Do("Remove Active", e), + this._setState(function(e) { + return ut({}, e, { + active: Array.isArray(e.active) ? e.active.filter(function(e) { + return -1 === i.indexOf(e) + }) : null + }) + })) + } + , + gd.prototype.toggleActive = function(e) { + var i = this + , t = xo(e) + , r = function(t) { + return function(e) { + return i.active.includes(e) === t + } + } + , e = t.filter(r(!0)) + , r = t.filter(r(!1)); + this.removeActive(e), + this.addActive(r), + Lo && Co("Toggle Active") + } + , + gd.prototype.createUIStore = function(e, t) { + var i = { + name: "UI/" + this.storeName, + idKey: this.idKey + }; + return this.ui = new fd(e = void 0 === e ? {} : e,ut({}, i, t = void 0 === t ? {} : t)), + this.ui + } + , + gd.prototype.destroy = function() { + hd.prototype.destroy.call(this), + this.ui instanceof gd && this.ui.destroy(), + this.entityActions.complete() + } + , + gd.prototype.akitaPreUpdateEntity = function(e, t) { + return t + } + , + gd.prototype.akitaPreAddEntity = function(e) { + return e + } + , + gd.prototype.akitaPreCheckEntity = function(e) { + return e + } + , + Object.defineProperty(gd.prototype, "ids", { + get: function() { + return this._value().ids + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(gd.prototype, "entities", { + get: function() { + return this._value().entities + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(gd.prototype, "active", { + get: function() { + return this._value().active + }, + enumerable: !0, + configurable: !0 + }), + gd.prototype._setActive = function(t) { + this._setState(function(e) { + return ut({}, e, { + active: t + }) + }) + } + , + gd.prototype.handleUICreation = function(e) { + var r = this + , t = this.ids + , n = Uo(this.ui._akitaCreateEntityFn) + , i = function(e) { + var t = r.entities[e] + , i = n ? r.ui._akitaCreateEntityFn(t) : r.ui._akitaCreateEntityFn; + return ut(((e = {})[r.idKey] = t[r.idKey], + e), i) + } + , i = ((e = void 0 === e ? !1 : e) ? this.ids.filter(function(e) { + return $o(r.ui.entities[e]) + }) : t).map(i); + e ? this.ui.add(i) : this.ui.set(i) + } + , + gd.prototype.hasInitialUIState = function() { + return this.hasUIStore() && !1 === $o(this.ui._akitaCreateEntityFn) + } + , + gd.prototype.handleUIRemove = function(e) { + this.hasUIStore() && this.ui.remove(e) + } + , + gd.prototype.hasUIStore = function() { + return this.ui instanceof fd + } + , + ct([ad(), ht("design:type", Function), ht("design:paramtypes", [Object, Object, Object, Object]), ht("design:returntype", void 0)], gd.prototype, "upsert", null), + ct([ad(), ht("design:type", Function), ht("design:paramtypes", ["function" == typeof (w = "undefined" != typeof T && T) ? w : Object]), ht("design:returntype", void 0)], gd.prototype, "toggleActive", null), + gd), fd = (lt(md, cd = pd), + md.prototype.setInitialEntityState = function(e) { + this._akitaCreateEntityFn = e + } + , + md); + function md(e, t) { + return cd.call(this, e = void 0 === e ? {} : e, t = void 0 === t ? {} : t) || this + } + function gd(e, t) { + void 0 === t && (t = {}); + e = hd.call(this, ut({}, { + entities: {}, + ids: [], + loading: !0, + error: null + }, e = void 0 === e ? {} : e), t) || this; + return e.options = t, + e.entityActions = new zt, + e.entityIdChanges = new zt, + e + } + function yd() { + return Es(function(e, t) { + return e === t || !1 !== No(e) && !1 !== No(t) && (!(!Bo(e) || !Bo(t)) || !vd(t, e) && !1 === vd(e, t)) + }) + } + function vd(e, t) { + return t.some(function(t) { + return void 0 === e.find(function(e) { + return e === t + }) + }) + } + function Sd(i, e) { + for (var r, n, s, a = [], o = i.ids, d = i.entities, l = e.filterBy, t = e.limitTo, u = e.sortBy, e = e.sortByOrder, c = 0; c < o.length; c++) + !function(t) { + var i = d[o[t]]; + if (!l) + return a.push(i); + xo(l).every(function(e) { + return e(i, t) + }) && a.push(i) + }(c); + u && (s = Uo(u) ? u : (r = u, + void 0 === (n = e) && (n = ud.ASC), + function(e, t) { + if (!e.hasOwnProperty(r) || !t.hasOwnProperty(r)) + return 0; + var i = "string" == typeof e[r] ? e[r].toUpperCase() : e[r] + , e = "string" == typeof t[r] ? t[r].toUpperCase() : t[r] + , t = 0; + return e < i ? t = 1 : i < e && (t = -1), + n == ud.DESC ? -1 * t : t + } + ), + a = a.sort(function(e, t) { + return s(e, t, i) + })); + t = Math.min(t || a.length, a.length); + return t === a.length ? a : a.slice(0, t) + } + function bd(e) { + return "string" == typeof e + } + function Td(t, i) { + return function(e) { + e = e[t]; + if (!$o(e)) + return i ? bd(i) ? e[i] : i(e) : e + } + } + (yi = ud = ud || {}).ASC = "asc", + yi.DESC = "desc"; + Ed.prototype.select = function(t) { + var e, n; + if (Uo(t)) + e = t; + else if (bd(t)) + e = function(e) { + return e[t] + } + ; + else { + if (Array.isArray(t)) + return this.store._select(function(e) { + return e + }).pipe(Es((n = t, + function(t, i) { + var r = Uo(n[0]); + return !1 === n.some(function(e) { + return r ? e(t) !== e(i) : t[e] !== i[e] + }) + } + )), ur(function(i) { + return Uo(t[0]) ? t.map(function(e) { + return e(i) + }) : t.reduce(function(e, t) { + return e[t] = i[t], + e + }, {}) + })); + e = function(e) { + return e + } + } + return this.store._select(e) + } + , + Ed.prototype.selectLoading = function() { + return this.select(function(e) { + return e.loading + }) + } + , + Ed.prototype.selectError = function() { + return this.select(function(e) { + return e.error + }) + } + , + Ed.prototype.getValue = function() { + return this.store._value() + } + , + Ed.prototype.selectHasCache = function() { + return this.store._cache().asObservable() + } + , + Ed.prototype.getHasCache = function() { + return this.store._cache().value + } + , + Object.defineProperty(Ed.prototype, "config", { + get: function() { + return this.constructor.akitaQueryConfig + }, + enumerable: !0, + configurable: !0 + }), + Si = Ed; + function Ed(e) { + this.store = e, + this.__store__ = e, + Lo && (ed[e.storeName] = this) + } + function Id(e) { + return e.pipe(an(function(e) { + return null != e + })) + } + var wd, Ad, Od = (lt(Dd, Ad = Si), + Dd.prototype.selectAll = function(e) { + var t = this; + return void 0 === e && (e = { + asObject: !1 + }), + this.select(function(e) { + return e.entities + }).pipe(ur(function() { + return t.getAll(e) + })) + } + , + Dd.prototype.getAll = function(e) { + return (e = void 0 === e ? { + asObject: !1, + filterBy: void 0, + limitTo: void 0 + } : e).asObject ? function(e, t) { + var r = {} + , n = t.filterBy + , s = t.limitTo + , a = e.ids + , o = e.entities; + if (!n && !s) + return o; + e = !1 === Po(s); + if (n && e) + for (var d = 0, i = 0, l = a.length; i < l && "break" !== function(t) { + if (d === s) + return "break"; + var e = a[t] + , i = o[e]; + xo(n).every(function(e) { + return e(i, t) + }) && (r[e] = i, + d++) + }(i); i++) + ; + else + for (var u = Math.min(s || a.length, a.length), i = 0; i < u; i++) + !function(t) { + var e = a[t] + , i = o[e]; + if (!n) + return r[e] = i; + xo(n).every(function(e) { + return e(i, t) + }) && (r[e] = i) + }(i); + return r + }(this.getValue(), e) : (t = e, + i = this.config || this.options, + t.sortBy = t.sortBy || i && i.sortBy, + t.sortByOrder = t.sortByOrder || i && i.sortByOrder, + Sd(this.getValue(), e)); + var t, i + } + , + Dd.prototype.selectMany = function(e, i) { + return e && e.length ? this.select(function(e) { + return e.entities + }).pipe(ur(function(t) { + return n = function(e) { + return Td(e, i)(t) + } + , + e.reduce(function(e, t, i, r) { + t = n(t); + return void 0 !== t && e.push(t), + e + }, []); + var n + }), yd()) : Bi([]) + } + , + Dd.prototype.selectEntity = function(e, t) { + var i = e; + return Uo(e) && (i = function(e, t) { + var i, r; + try { + for (var n = pt(Object.keys(t)), s = n.next(); !s.done; s = n.next()) { + var a = s.value; + if (!0 === e(t[a])) + return a + } + } catch (e) { + i = { + error: e + } + } finally { + try { + s && !s.done && (r = n.return) && r.call(n) + } finally { + if (i) + throw i.error + } + } + }(e, this.getValue().entities)), + this.select(function(e) { + return e.entities + }).pipe(ur(Td(i, t)), Es()) + } + , + Dd.prototype.getEntity = function(e) { + return this.getValue().entities[e] + } + , + Dd.prototype.selectActiveId = function() { + return this.select(function(e) { + return e.active + }) + } + , + Dd.prototype.getActiveId = function() { + return this.getValue().active + } + , + Dd.prototype.selectActive = function(t) { + var i = this; + return No(this.getActive()) ? this.selectActiveId().pipe(Ra(function(e) { + return i.selectMany(e, t) + })) : this.selectActiveId().pipe(Ra(function(e) { + return i.selectEntity(e, t) + })) + } + , + Dd.prototype.getActive = function() { + var t = this + , e = this.getActiveId(); + return No(e) ? e.map(function(e) { + return t.getValue().entities[e] + }) : Yo(e) ? this.getEntity(e) : void 0 + } + , + Dd.prototype.selectCount = function(e) { + var t = this; + return this.select(function(e) { + return e.entities + }).pipe(ur(function() { + return t.getCount(e) + })) + } + , + Dd.prototype.getCount = function(e) { + return (Uo(e) ? this.getAll().filter(e) : this.getValue().ids).length + } + , + Dd.prototype.selectLast = function(e) { + return this.selectAt(function(e) { + return e[e.length - 1] + }, e) + } + , + Dd.prototype.selectFirst = function(e) { + return this.selectAt(function(e) { + return e[0] + }, e) + } + , + Dd.prototype.selectEntityAction = function(e) { + if (Po(e)) + return this.store.selectEntityAction$; + var t = No(e) ? function(e) { + return e + } + : function(e) { + return e.ids + } + , i = xo(e); + return this.store.selectEntityAction$.pipe(an(function(e) { + e = e.type; + return i.includes(e) + }), ur(function(e) { + return t(e) + })) + } + , + Dd.prototype.hasEntity = function(e) { + var t = this; + return Po(e) ? 0 < this.getValue().ids.length : Uo(e) ? this.getAll().some(e) : No(e) ? e.every(function(e) { + return e in t.getValue().entities + }) : e in this.getValue().entities + } + , + Dd.prototype.hasActive = function(e) { + var t = this.getValue().active + , i = Fo(e); + return Array.isArray(t) ? i ? t.includes(e) : 0 < t.length : i ? t === e : Fo(t) + } + , + Dd.prototype.createUIQuery = function() { + this.ui = new kd(this.__store__.ui) + } + , + Dd.prototype.selectAt = function(e, t) { + var i = this; + return this.select(function(e) { + return e.ids + }).pipe(ur(e), Es(), Ra(function(e) { + return i.selectEntity(e, t) + })) + } + , + Dd), kd = (lt(Cd, wd = Od), + Cd); + function Cd(e) { + return wd.call(this, e) || this + } + function Dd(e, t) { + void 0 === t && (t = {}); + var i = Ad.call(this, e) || this; + return i.options = t, + i.__store__ = e, + i + } + function Md(e, t) { + return 1 === t.split(".").length ? e : t.split(".").slice(1).join(".").split(".").reduce(function(e, t) { + return e && e[t] + }, e) + } + function Pd(e, t, r) { + var i = t.split("."); + if (1 === i.length) + return ut({}, e, r); + e = ut({}, e); + var n = i.length - 2; + return t.split(".").slice(1).reduce(function(e, t, i) { + return e[t] = i !== n ? ut({}, e[t]) : Array.isArray(e[t]) || !_o(e[t]) ? r : ut({}, e[t], r), + e && e[t] + }, e), + e + } + new Xi(1); + var xd, Rd, Ld, _d, A = (Fd.prototype.getQuery = function() { + return this.query + } + , + Fd.prototype.getStore = function() { + return this.getQuery().__store__ + } + , + Fd.prototype.isEntityBased = Yo, + Fd.prototype.selectSource = function(e, t) { + var i = this; + return this.isEntityBased(e) ? this.getQuery().selectEntity(e).pipe(Id) : t ? this.getQuery().select(function(e) { + return Md(e, i.withStoreName(t)) + }) : this.getQuery().select() + } + , + Fd.prototype.getSource = function(e, t) { + if (this.isEntityBased(e)) + return this.getQuery().getEntity(e); + e = this.getQuery().getValue(); + return t ? Md(e, this.withStoreName(t)) : e + } + , + Fd.prototype.withStoreName = function(e) { + return this.storeName + "." + e + } + , + Object.defineProperty(Fd.prototype, "storeName", { + get: function() { + return this.getStore().storeName + }, + enumerable: !0, + configurable: !0 + }), + Fd.prototype.updateStore = function(t, e, i) { + var r = this; + this.isEntityBased(e) ? this.getStore().update(e, t) : i ? this.getStore()._setState(function(e) { + return Pd(e, r.withStoreName(i), t) + }) : this.getStore()._setState(function(e) { + return ut({}, e, t) + }) + } + , + Fd.prototype.onReset = function(i) { + var r = this + , n = this.getStore().reset; + this.getStore().reset = function() { + for (var e = [], t = 0; t < arguments.length; t++) + e[t] = arguments[t]; + setTimeout(function() { + n.apply(r.getStore(), e), + i() + }) + } + } + , + Fd), Nd = { + pagesControls: !1, + range: !1, + startWith: 1, + cacheTimeout: void 0, + clearStoreWithCache: !0 + }; + function Fd(e, t) { + this.query = e + } + function Bd(e, t, i) { + void 0 === i && (i = {}); + var r = xd.call(this, e) || this; + return r.query = e, + r.factoryFnOrPath = t, + r.params = i, + r.params = ut({ + debounceTime: 300, + formKey: "akitaForm", + emitEvent: !1, + arrControlFactory: function(e) { + return r.builder.control(e) + } + }, i), + r.isRootKeys = !1 === Yo(t), + r.isKeyBased = bd(t) || r.isRootKeys, + r + } + function Ud(e, t) { + void 0 === t && (t = {}); + var i = Rd.call(this, e, { + resetFn: function() { + i.initial = !1, + i.destroy({ + clearCache: !0, + currentPage: 1 + }) + } + }) || this; + i.query = e, + i.config = t, + i.metadata = new Map, + i.pages = new Map, + i.pagination = { + currentPage: 1, + perPage: 0, + total: 0, + lastPage: 0, + data: [] + }, + i.initial = !0, + i.isLoading$ = i.query.selectLoading().pipe(ss(0)), + i.config = Object.assign(Nd, t); + e = i.config, + t = e.startWith, + e = e.cacheTimeout; + return i.page = new gi(t), + e && (e instanceof Ut || "function" == typeof e.lift && "function" == typeof e.subscribe) && (i.clearCacheSubscription = e.subscribe(function() { + return i.clearCache() + })), + i + } + lt(Ud, Rd = A), + Object.defineProperty(Ud.prototype, "pageChanges", { + get: function() { + return this.page.asObservable() + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(Ud.prototype, "currentPage", { + get: function() { + return this.pagination.currentPage + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(Ud.prototype, "isFirst", { + get: function() { + return 1 === this.currentPage + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(Ud.prototype, "isLast", { + get: function() { + return this.currentPage === this.pagination.lastPage + }, + enumerable: !0, + configurable: !0 + }), + Ud.prototype.withControls = function() { + return this.config.pagesControls = !0, + this + } + , + Ud.prototype.withRange = function() { + return this.config.range = !0, + this + } + , + Ud.prototype.setLoading = function(e) { + void 0 === e && (e = !0), + this.getStore().setLoading(e) + } + , + Ud.prototype.update = function(e) { + this.pagination = e, + this.addPage(e.data) + } + , + Ud.prototype.addPage = function(e) { + var t = this; + this.pages.set(this.currentPage, { + ids: e.map(function(e) { + return e[t.getStore().idKey] + }) + }), + this.getStore().upsertMany(e) + } + , + Ud.prototype.clearCache = function(e) { + void 0 === e && (e = {}), + this.initial || (Co("@Pagination - Clear Cache"), + !1 !== e.clearStore && (this.config.clearStoreWithCache || e.clearStore) && this.getStore().remove(), + this.pages = new Map, + this.metadata = new Map), + this.initial = !1 + } + , + Ud.prototype.clearPage = function(e) { + this.pages.delete(e) + } + , + Ud.prototype.destroy = function(e) { + var t = void 0 === e ? {} : e + , e = t.clearCache + , t = t.currentPage; + this.clearCacheSubscription && this.clearCacheSubscription.unsubscribe(), + e && this.clearCache(), + $o(t) || this.setPage(t), + this.initial = !0 + } + , + Ud.prototype.isPageActive = function(e) { + return this.currentPage === e + } + , + Ud.prototype.setPage = function(e) { + e === this.currentPage && this.hasPage(e) || this.page.next(this.pagination.currentPage = e) + } + , + Ud.prototype.nextPage = function() { + this.currentPage !== this.pagination.lastPage && this.setPage(this.pagination.currentPage + 1) + } + , + Ud.prototype.prevPage = function() { + 1 < this.pagination.currentPage && this.setPage(this.pagination.currentPage - 1) + } + , + Ud.prototype.setLastPage = function() { + this.setPage(this.pagination.lastPage) + } + , + Ud.prototype.setFirstPage = function() { + this.setPage(1) + } + , + Ud.prototype.hasPage = function(e) { + return this.pages.has(e) + } + , + Ud.prototype.getPage = function(e) { + var t = this + , i = this.pagination.currentPage; + return this.hasPage(i) ? this.selectPage(i) : (this.setLoading(!0), + Lr(e()).pipe(Ra(function(e) { + return i = e.currentPage, + sd(function() { + t.setLoading(!1), + t.update(e) + }), + t.selectPage(i) + }))) + } + , + Ud.prototype.getQuery = function() { + return this.query + } + , + Ud.prototype.refreshCurrentPage = function() { + !1 === Po(this.currentPage) && (this.clearPage(this.currentPage), + this.setPage(this.currentPage)) + } + , + Ud.prototype.getFrom = function() { + return this.isFirst ? 1 : (this.currentPage - 1) * this.pagination.perPage + 1 + } + , + Ud.prototype.getTo = function() { + return this.isLast ? this.pagination.total : this.currentPage * this.pagination.perPage + } + , + Ud.prototype.selectPage = function(n) { + var s = this; + return this.query.selectAll({ + asObject: !0 + }).pipe(Cs(1), ur(function(t) { + var e = ut({}, s.pagination, { + data: s.pages.get(n).ids.map(function(e) { + return t[e] + }) + }) + , i = s.config + , r = i.range + , i = i.pagesControls; + return isNaN(s.pagination.total) && (1 === e.lastPage ? e.total = e.data ? e.data.length : 0 : e.total = e.perPage * e.lastPage, + s.pagination.total = e.total), + r && (e.from = s.getFrom(), + e.to = s.getTo()), + i && (e.pageControls = function(e, t) { + for (var i = Math.ceil(e / t), r = [], n = 0; n < i; n++) + r.push(n + 1); + return r + }(s.pagination.total, s.pagination.perPage)), + e + })) + } + , + ct([(Ld = "@Pagination - New Page", + function(e, t, i) { + var r = i.value; + return i.value = function() { + for (var e = [], t = 0; t < arguments.length; t++) + e[t] = arguments[t]; + return Co(Ld, _d), + r.apply(this, e) + } + , + i + } + ), ht("design:type", Function), ht("design:paramtypes", [Object]), ht("design:returntype", void 0)], Ud.prototype, "update", null), + lt(Bd, xd = A), + Bd.prototype.setForm = function(e, t) { + return this.form = e, + this.builder = t, + this.activate(), + this + } + , + Bd.prototype.reset = function(e) { + var r = this + , e = e || (this.isKeyBased ? this.initialValue : this.factoryFnOrPath()); + this.isKeyBased && Object.keys(this.initialValue).forEach(function(i) { + var e, t = r.initialValue[i]; + Array.isArray(t) && r.builder && (e = r.form.controls[i], + r.cleanArray(e), + t.forEach(function(e, t) { + r.form.get(i).insert(t, r.params.arrControlFactory(e)) + })) + }), + this.form.patchValue(e, { + emitEvent: this.params.emitEvent + }); + var t = this.isKeyBased ? Pd(this.getQuery().getValue(), this.getStore().storeName + "." + this.factoryFnOrPath, e) : ((t = {})[this.params.formKey] = e, + t); + this.updateStore(t) + } + , + Bd.prototype.cleanArray = function(e) { + for (; 0 !== e.length; ) + e.removeAt(0) + } + , + Bd.prototype.resolveInitialValue = function(e, n) { + var s = this; + if (e) + return Object.keys(e).reduce(function(e, i) { + var r, t = n[i]; + return Array.isArray(t) && s.builder && (r = s.params.arrControlFactory, + s.cleanArray(s.form.get(i)), + t.forEach(function(e, t) { + s.form.get(i).insert(t, r(e)) + })), + e[i] = n[i], + e + }, {}) + } + , + Bd.prototype.activate = function() { + var i, e, t, r = this; + this.isKeyBased ? (this.isRootKeys ? this.initialValue = this.resolveInitialValue(this.form.value, this.getQuery().getValue()) : (i = this.getStore().storeName + "." + this.factoryFnOrPath, + e = Md(this.getQuery().getValue(), i), + this.initialValue = this.resolveInitialValue(e, e)), + this.form.patchValue(this.initialValue, { + emitEvent: this.params.emitEvent + })) : (this.getQuery().getValue()[this.params.formKey] || (Co("@PersistNgFormPlugin activate"), + this.updateStore(((t = {})[this.params.formKey] = this.factoryFnOrPath(), + t))), + t = this.getQuery().getValue()[this.params.formKey], + this.form.patchValue(t)), + this.formChanges = this.form.valueChanges.pipe(Qn(this.params.debounceTime)).subscribe(function(t) { + var e; + Co("@PersistForm - Update"), + e = r.isKeyBased ? r.isRootKeys ? function(e) { + return ut({}, e, t) + } + : function(e) { + return Pd(e, i, t) + } + : function() { + var e; + return (e = {})[r.params.formKey] = t, + e + } + , + r.updateStore(e(r.getQuery().getValue())) + }) + } + , + Bd.prototype.destroy = function() { + this.formChanges && this.formChanges.unsubscribe(), + this.form = null, + this.builder = null + } + ; + var $d, Vd, Br = (jd.prototype.getEntity = function(e) { + return this.entities.get(e) + } + , + jd.prototype.hasEntity = function(e) { + return this.entities.has(e) + } + , + jd.prototype.removeEntity = function(e) { + return this.destroy(e), + this.entities.delete(e) + } + , + jd.prototype.createEntity = function(e, t) { + return this.entities.set(e, t) + } + , + jd.prototype.getIds = function() { + return $o(this.entityIds) ? this.query.getValue().ids : xo(this.entityIds) + } + , + jd.prototype.resolvedIds = function(e) { + return $o(e) ? this.getIds() : xo(e) + } + , + jd.prototype.rebase = function(i, r) { + var n = this; + if (void 0 === r && (r = {}), + Yo(i)) + if ($o(this.entityIds)) { + for (var e = 0, t = i.length; e < t; e++) { + var s, a = i[e]; + !1 === this.hasEntity(a) && (Uo(r.beforeAdd) && r.beforeAdd(a), + s = this.instantiatePlugin(a), + this.entities.set(a, s), + Uo(r.afterAdd) && r.afterAdd(s)) + } + this.entities.forEach(function(e, t) { + -1 === i.indexOf(t) && (Uo(r.beforeRemove) && r.beforeRemove(e), + n.removeEntity(t)) + }) + } else + for (var o = xo(this.entityIds), e = 0, t = o.length; e < t; e++) + a = o[e], + -1 < i.indexOf(a) && !1 === this.hasEntity(a) ? (Uo(r.beforeAdd) && r.beforeAdd(a), + s = this.instantiatePlugin(a), + this.entities.set(a, s), + Uo(r.afterAdd) && r.afterAdd(s)) : this.entities.forEach(function(e, t) { + -1 === i.indexOf(t) && !0 === n.hasEntity(t) && (Uo(r.beforeRemove) && r.beforeRemove(e), + n.removeEntity(t)) + }); + else + this.getIds().forEach(function(e) { + n.hasEntity(e) || n.createEntity(e, n.instantiatePlugin(e)) + }) + } + , + jd.prototype.selectIds = function() { + return this.query.select(function(e) { + return e.ids + }) + } + , + jd.prototype.activate = function(e) { + this.rebase(e) + } + , + jd.prototype.forEachId = function(e, t) { + for (var i = this.resolvedIds(e), r = 0, n = i.length; r < n; r++) { + var s = i[r]; + this.hasEntity(s) && t(this.getEntity(s)) + } + } + , + jd), Kd = (lt(Hd, $d = A), + Object.defineProperty(Hd.prototype, "hasPast$", { + get: function() { + return this._hasPast$ + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(Hd.prototype, "hasFuture$", { + get: function() { + return this._hasFuture$ + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(Hd.prototype, "hasPast", { + get: function() { + return 0 < this.history.past.length + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(Hd.prototype, "hasFuture", { + get: function() { + return 0 < this.history.future.length + }, + enumerable: !0, + configurable: !0 + }), + Object.defineProperty(Hd.prototype, "property", { + get: function() { + return this.params.watchProperty + }, + enumerable: !0, + configurable: !0 + }), + Hd.prototype.updateHasHistory = function() { + this.hasFutureSubject.next(this.hasFuture), + this.hasPastSubject.next(this.hasPast) + } + , + Hd.prototype.activate = function() { + var r = this; + this.hasPastSubject = new gi(!1), + this._hasPast$ = this.hasPastSubject.asObservable().pipe(Es()), + this.hasFutureSubject = new gi(!1), + this._hasFuture$ = this.hasFutureSubject.asObservable().pipe(Es()), + this.history.present = this.getSource(this._entityId, this.property), + this.subscription = this.selectSource(this._entityId, this.property).pipe(ca()).subscribe(function(e) { + var t = ft(e, 2) + , i = t[0] + , e = t[1]; + r.skip ? r.skip = !1 : (t = r.params.comparator(i, e), + !r.skipUpdate && t && (r.history.past.length === r.params.maxAge && (r.history.past = r.history.past.slice(1)), + r.history.past = mt(r.history.past, [i]), + r.history.present = e, + r.updateHasHistory())) + }) + } + , + Hd.prototype.undo = function() { + var e, t, i; + 0 < this.history.past.length && (e = (i = this.history).past, + t = i.present, + i = e[e.length - 1], + this.history.past = e.slice(0, e.length - 1), + this.history.present = i, + this.history.future = mt([t], this.history.future), + this.update()) + } + , + Hd.prototype.redo = function() { + var e, t, i, r; + 0 < this.history.future.length && (e = (r = this.history).past, + t = r.present, + i = this.history.future[0], + r = this.history.future.slice(1), + this.history.past = mt(e, [t]), + this.history.present = i, + this.history.future = r, + this.update("Redo")) + } + , + Hd.prototype.jumpToPast = function(e) { + var t, i, r, n; + e < 0 || e >= this.history.past.length || (t = (r = this.history).past, + n = r.future, + i = r.present, + r = t.slice(0, e), + n = mt(t.slice(e + 1), [i], n), + e = t[e], + this.history.past = r, + this.history.present = e, + this.history.future = n, + this.update()) + } + , + Hd.prototype.jumpToFuture = function(e) { + var t, i, r; + e < 0 || e >= this.history.future.length || (i = (r = this.history).past, + t = r.future, + i = mt(i, [r.present], t.slice(0, e)), + r = t[e], + e = t.slice(e + 1), + this.history.past = i, + this.history.present = r, + this.history.future = e, + this.update("Redo")) + } + , + Hd.prototype.jump = function(e) { + return 0 < e ? this.jumpToFuture(e - 1) : e < 0 ? this.jumpToPast(this.history.past.length + e) : void 0 + } + , + Hd.prototype.clear = function(e) { + this.history = Uo(e) ? e(this.history) : { + past: [], + present: null, + future: [] + }, + this.updateHasHistory() + } + , + Hd.prototype.destroy = function(e) { + (e = void 0 === e ? !1 : e) && this.clear(), + this.subscription.unsubscribe() + } + , + Hd.prototype.ignoreNext = function() { + this.skip = !0 + } + , + Hd.prototype.update = function(e) { + void 0 === e && (e = "Undo"), + this.skipUpdate = !0, + Co("@StateHistory - " + e), + this.updateStore(this.history.present, this._entityId, this.property), + this.updateHasHistory(), + this.skipUpdate = !1 + } + , + Hd); + function Hd(e, t, i) { + void 0 === t && (t = {}); + var r = $d.call(this, e, { + resetFn: function() { + return r.clear() + } + }) || this; + return r.query = e, + r.params = t, + r._entityId = i, + r.skip = !1, + r.history = { + past: [], + present: null, + future: [] + }, + r.skipUpdate = !1, + t.maxAge = t.maxAge || 10, + t.comparator = t.comparator || function() { + return !0 + } + , + r.activate(), + r + } + function jd(e, t) { + this.query = e, + this.entityIds = t, + this.entities = new Map + } + function qd(e, t) { + var i = Vd.call(this, e, (t = void 0 === t ? {} : t).entityIds) || this; + return i.query = e, + (i.params = t).maxAge = Yo(t.maxAge) ? t.maxAge : 10, + i.activate(), + i.selectIds().pipe(Oa(1)).subscribe(function(e) { + return i.activate(e) + }), + i + } + lt(qd, Vd = Br), + qd.prototype.redo = function(e) { + this.forEachId(e, function(e) { + return e.redo() + }) + } + , + qd.prototype.undo = function(e) { + this.forEachId(e, function(e) { + return e.undo() + }) + } + , + qd.prototype.hasPast = function(e) { + if (this.hasEntity(e)) + return this.getEntity(e).hasPast + } + , + qd.prototype.hasFuture = function(e) { + if (this.hasEntity(e)) + return this.getEntity(e).hasFuture + } + , + qd.prototype.jumpToFuture = function(e, t) { + this.forEachId(e, function(e) { + return e.jumpToFuture(t) + }) + } + , + qd.prototype.jumpToPast = function(e, t) { + this.forEachId(e, function(e) { + return e.jumpToPast(t) + }) + } + , + qd.prototype.clear = function(e) { + this.forEachId(e, function(e) { + return e.clear() + }) + } + , + qd.prototype.destroy = function(e, t) { + void 0 === t && (t = !1), + this.forEachId(e, function(e) { + return e.destroy(t) + }) + } + , + qd.prototype.ignoreNext = function(e) { + this.forEachId(e, function(e) { + return e.ignoreNext() + }) + } + , + qd.prototype.instantiatePlugin = function(e) { + return new Kd(this.query,this.params,e) + } + ; + var Qd = { + comparator: function(e, t) { + return JSON.stringify(e) !== JSON.stringify(t) + } + }; + function Gd(e, t) { + return t.split(".").reduce(function(e, t) { + return e && "undefined" !== e[t] ? e[t] : void 0 + }, e) + } + var Wd, zd, Xd = (lt(Yd, Wd = A), + Yd.prototype.reset = function(e) { + var t = this.head; + Uo((e = void 0 === e ? {} : e).updateFn) && (t = this.isEntityBased(this._entityId) ? e.updateFn(this.head, this.getQuery().getEntity(this._entityId)) : e.updateFn(this.head, this.getQuery().getValue())), + Co("@DirtyCheck - Revert"), + this.updateStore(t, this._entityId), + this._reset.next() + } + , + Yd.prototype.setHead = function() { + return this.active ? this.head = this._getHead() : (this.activate(), + this.active = !0), + this.updateDirtiness(!1), + this + } + , + Yd.prototype.isDirty = function() { + return !!this.dirty.value + } + , + Yd.prototype.hasHead = function() { + return !!this.getHead() + } + , + Yd.prototype.destroy = function() { + this.head = null, + this.subscription && this.subscription.unsubscribe(), + this._reset && this._reset.complete() + } + , + Yd.prototype.isPathDirty = function(e) { + var t = this.getHead() + , i = Gd(this.getQuery().getValue(), e) + , e = Gd(t, e); + return this.params.comparator(i, e) + } + , + Yd.prototype.getHead = function() { + return this.head + } + , + Yd.prototype.activate = function() { + var i = this; + this.head = this._getHead(); + var e = this.params.watchProperty ? this.params.watchProperty.map(function(t) { + return i.query.select(function(e) { + return e[t] + }).pipe(ur(function(e) { + return { + val: e, + __akitaKey: t + } + })) + }) : [this.selectSource(this._entityId)]; + this.subscription = Cr.apply(void 0, mt(e)).pipe(Oa(1)).subscribe(function(e) { + $o(i.head) || (e = e.some(function(e) { + var t = e.__akitaKey ? i.head[e.__akitaKey] : i.head + , e = e.__akitaKey ? e.val : e; + return i.params.comparator(t, e) + }), + i.updateDirtiness(e)) + }) + } + , + Yd.prototype.updateDirtiness = function(e) { + this.dirty.next(e) + } + , + Yd.prototype._getHead = function() { + var e = this.getSource(this._entityId); + return e = this.params.watchProperty ? this.getWatchedValues(e) : e + } + , + Yd.prototype.getWatchedValues = function(i) { + return this.params.watchProperty.reduce(function(e, t) { + return e[t] = i[t], + e + }, {}) + } + , + Yd); + function Yd(e, t, i) { + var r = Wd.call(this, e) || this; + return r.query = e, + r.params = t, + r._entityId = i, + r.dirty = new gi(!1), + r.active = !1, + r._reset = new zt, + r.isDirty$ = r.dirty.asObservable().pipe(Es()), + r.reset$ = r._reset.asObservable(), + r.params = ut({}, Qd, t), + r.params.watchProperty && (t = xo(r.params.watchProperty), + e instanceof Od && t.includes("entities") && !t.includes("ids") && t.push("ids"), + r.params.watchProperty = t), + r + } + function Jd() { + return Math.random().toString(36).slice(2) + } + function Zd(e) { + return Cr(e).pipe(Bn(0)) + } + function el(e, t) { + var i = zd.call(this, e, (t = void 0 === t ? {} : t).entityIds) || this; + return i.query = e, + i.params = t, + i._someDirty = new zt, + i.someDirty$ = nn(i.query.select(function(e) { + return e.entities + }), i._someDirty.asObservable()).pipe(Bn(0), ur(function() { + return i.checkSomeDirty() + })), + i.params = ut({}, Qd, t), + i.activate(), + i.selectIds().pipe(Oa(1)).subscribe(function(e) { + zd.prototype.rebase.call(i, e, { + afterAdd: function(e) { + return e.setHead() + } + }) + }), + i + } + lt(el, zd = Br), + el.prototype.setHead = function(e) { + if (this.params.entityIds && e) { + var t = xo(e); + if (!1 === xo(this.params.entityIds).some(function(e) { + return -1 < t.indexOf(e) + })) + return this + } + return this.forEachId(e, function(e) { + return e.setHead() + }), + this._someDirty.next(), + this + } + , + el.prototype.hasHead = function(e) { + return !!this.entities.has(e) && this.getEntity(e).hasHead() + } + , + el.prototype.reset = function(e, t) { + void 0 === t && (t = {}), + this.forEachId(e, function(e) { + return e.reset(t) + }) + } + , + el.prototype.isDirty = function(e, t) { + if (void 0 === t && (t = !0), + this.entities.has(e)) { + e = this.getEntity(e); + return t ? e.isDirty$ : e.isDirty() + } + return !1 + } + , + el.prototype.someDirty = function() { + return this.checkSomeDirty() + } + , + el.prototype.isPathDirty = function(e, t) { + if (this.entities.has(e)) { + var i = this.getEntity(e).getHead() + , e = Gd(this.query.getEntity(e), t) + , t = Gd(i, t); + return this.params.comparator(e, t) + } + return null + } + , + el.prototype.destroy = function(e) { + this.forEachId(e, function(e) { + return e.destroy() + }), + e || this._someDirty.complete() + } + , + el.prototype.instantiatePlugin = function(e) { + return new Xd(this.query,this.params,e) + } + , + el.prototype.checkSomeDirty = function() { + var e, t, i = this.resolvedIds(); + try { + for (var r = pt(i), n = r.next(); !n.done; n = r.next()) { + var s = n.value; + if (this.getEntity(s).isDirty()) + return !0 + } + } catch (t) { + e = { + error: t + } + } finally { + try { + n && !n.done && (t = r.return) && t.call(r) + } finally { + if (e) + throw e.error + } + } + return !1 + } + , + (gc = gc || {}).Update = "UPDATE", + {}[gc.Update] = "update", + (gr = gu = gu || {}).Update = "UPDATE", + gr.AddEntities = "ADD_ENTITIES", + gr.SetEntities = "SET_ENTITIES", + gr.UpdateEntities = "UPDATE_ENTITIES", + gr.RemoveEntities = "REMOVE_ENTITIES", + gr.UpsertEntities = "UPSERT_ENTITIES", + gr.UpsertManyEntities = "UPSERT_MANY_ENTITIES", + (mu = {})[gu.Update] = "update", + mu[gu.AddEntities] = "add", + mu[gu.SetEntities] = "set", + mu[gu.UpdateEntities] = "update", + mu[gu.RemoveEntities] = "remove", + mu[gu.UpsertEntities] = "upsert", + mu[gu.UpsertManyEntities] = "upsertMany"; + const tl = /^((?:[^\/;?#]+:)?)(\/\/[^\/\;?#]*)?(.*?)??(;.*?)?(\?.*?)?(#.*?)?$/ + , il = /^([^\/;?#]*)(.*)$/ + , rl = /(?:\/|^)\.(?=\/)/g + , nl = /(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g + , sl = { + buildAbsoluteURL: function(e, t, i) { + if (i = i || {}, + e = e.trim(), + !(t = t.trim())) { + if (!i.alwaysNormalize) + return e; + const t = sl.parseURL(e); + if (!t) + throw new Error("Error trying to parse base URL."); + return t.path = sl.normalizePath(t.path), + sl.buildURLFromParts(t) + } + const r = sl.parseURL(t); + if (!r) + throw new Error("Error trying to parse relative URL."); + if (r.scheme) + return i.alwaysNormalize ? (r.path = sl.normalizePath(r.path), + sl.buildURLFromParts(r)) : t; + const n = sl.parseURL(e); + if (!n) + throw new Error("Error trying to parse base URL."); + if (!n.netLoc && n.path && "/" !== n.path[0]) { + const e = il.exec(n.path); + n.netLoc = e[1], + n.path = e[2] + } + n.netLoc && !n.path && (n.path = "/"); + const s = { + scheme: n.scheme, + netLoc: r.netLoc, + path: null, + params: r.params, + query: r.query, + fragment: r.fragment + }; + if (!r.netLoc && (s.netLoc = n.netLoc, + "/" !== r.path[0])) + if (r.path) { + i.inheritQuery && (r.query || (s.query = n.query)); + const e = n.path + , t = e.substring(0, e.lastIndexOf("/") + 1) + r.path; + s.path = sl.normalizePath(t) + } else + s.path = n.path, + r.params || (s.params = n.params, + r.query || (s.query = n.query)); + return null === s.path && (s.path = i.alwaysNormalize ? sl.normalizePath(r.path) : r.path), + sl.buildURLFromParts(s) + }, + parseURL: function(e) { + e = tl.exec(e); + return e ? { + scheme: e[1] || "", + netLoc: e[2] || "", + path: e[3] || "", + params: e[4] || "", + query: e[5] || "", + fragment: e[6] || "" + } : null + }, + normalizePath: function(e) { + for (e = e.split("").reverse().join("").replace(rl, ""); e.length !== (e = e.replace(nl, "")).length; ) + ; + return e.split("").reverse().join("") + }, + buildURLFromParts: function(e) { + return e.scheme + e.netLoc + e.path + e.params + e.query + e.fragment + }, + getHostName: function(e) { + let t; + return e && (t = -1 < e.indexOf("://") ? e.split("/")[2] : e.split("/")[0], + t = t.split(":")[0], + t = t.split("?")[0]), + t + } + }; + var al, ol, dl, ll, ul, cl, hl, pl, fl = sl; + function ml(e) { + return null != e && !e.startsWith("http://") && !e.startsWith("https://") + } + function gl(e) { + return null == e || ml(e) ? null : sl.getHostName(e) + } + function yl(e, t) { + return !e || e === gl(t) + } + (w = al = al || {})[w.DOVI = 4] = "DOVI", + w[w.HEVC = 3] = "HEVC", + w[w.VP09 = 2] = "VP09", + w[w.AVC = 1] = "AVC", + w[w.UNKNOWN = 0] = "UNKNOWN", + (yi = ol = ol || {})[yi.PQ = 3] = "PQ", + yi[yi.HLG = 2] = "HLG", + yi[yi.SDR = 1] = "SDR", + yi[yi.UNKNOWN = 0] = "UNKNOWN", + (A = dl = dl || {})[A.ALAC = 7] = "ALAC", + A[A.FLAC = 6] = "FLAC", + A[A.EC3 = 5] = "EC3", + A[A.AC3 = 4] = "AC3", + A[A.XHEAAC = 3] = "XHEAAC", + A[A.AAC = 2] = "AAC", + A[A.MP3 = 1] = "MP3", + A[A.UNKNOWN = 0] = "UNKNOWN", + (Br = ll = ll || {})[Br.VALID = 1] = "VALID", + Br[Br.INVALID = 0] = "INVALID"; + const vl = ["via", "x-apple-request-uuid"] + , Sl = { + maxNumRetry: 4, + retryDelayMs: 0, + maxRetryDelayMs: 0 + } + , bl = { + maxNumRetry: 6, + retryDelayMs: 1e3, + maxRetryDelayMs: 8e3 + } + , Tl = { + maxNumRetry: 0, + retryDelayMs: 0, + maxRetryDelayMs: 0 + } + , El = { + default: { + maxTimeToFirstByteMs: 5e3, + maxLoadTimeMs: 2e4, + autoRetry: !1, + timeoutRetry: Tl, + errorRetry: Tl + }, + customURL: { + maxTimeToFirstByteMs: 1e4, + maxLoadTimeMs: 2e4, + autoRetry: !1, + timeoutRetry: Tl, + errorRetry: Tl + } + } + , Il = { + maxNumRetry: 8, + retryDelayMs: 1e3, + maxRetryDelayMs: 2e4, + backoff: "linear" + } + , wl = Object.assign(Object.assign({}, Il), { + maxNumRetry: 1 + }) + , Al = { + autoStartLoad: !0, + startPosition: NaN, + defaultAudioCodec: void 0, + defaultVideoCodec: void 0, + debug: !1, + debugLevel: "info", + buildType: void 0, + minFramesBeforeSwitchingLevel: 11, + minTargetDurations: 3, + maxBufferLength: 60, + maxBufferHole: .5, + maxSeekHole: 2, + discontinuitySeekTolerance: 2, + almostDryBufferSec: .5, + maxTotalDurationTolerance: .1, + lowBufferThreshold: .5, + lowBufferWatchdogPeriod: .5, + highBufferWatchdogPeriod: 3, + seekWatchdogPeriod: 5, + nudgeOffset: .1, + nudgeMaxRetry: 3, + maxFragLookUpTolerance: .2, + initialLiveManifestSize: 1, + liveSyncDurationCount: 3, + liveMaxLatencyDurationCount: 1 / 0, + liveSyncDuration: void 0, + liveMaxLatencyDuration: void 0, + liveFlushExpiredFrags: !0, + liveMaxUnchangedPlaylistRefresh: 3, + liveEdgeForZeroStartPositon: !1, + allowFastSwitchUp: !1, + minMatchGroupDuration: 5, + desiredIframeFPS: 8, + initialIframeFPS: 6, + minRemainingTimeInMediaPipeline: 3, + leftMediaTimeToAutoPause: 10, + startTargetDurationFactor: .9, + enableWorker: !0, + enableWebCrypto: !0, + keySystemPreference: void 0, + clearMediaKeysOnPromise: !0, + useMultipleKeySessions: !1, + enablePlayReadyKeySystem: !1, + useMediaKeySystemAccessFilter: !1, + playReadyMessageFormat: "utf16", + startLevel: void 0, + livePlaylistRefreshDelay: 2500, + liveMinPlayingBufferLen: 5, + enableIFramePreloading: !0, + useMediaCapabilities: !1, + enableID3Cues: !0, + certLoadPolicy: El, + keyLoadPolicy: { + default: { + maxTimeToFirstByteMs: 5e3, + maxLoadTimeMs: 2e4, + autoRetry: !1, + timeoutRetry: wl, + errorRetry: Il + }, + customURL: { + maxTimeToFirstByteMs: 1e4, + maxLoadTimeMs: 2e4, + autoRetry: !1, + timeoutRetry: wl, + errorRetry: Il + } + }, + manifestLoadPolicy: { + default: { + maxTimeToFirstByteMs: 1e4, + maxLoadTimeMs: 2e4, + autoRetry: !1, + timeoutRetry: { + maxNumRetry: 2, + retryDelayMs: 0, + maxRetryDelayMs: 0 + }, + errorRetry: { + maxNumRetry: 1, + retryDelayMs: 1e3, + maxRetryDelayMs: 8e3 + } + }, + customURL: { + maxTimeToFirstByteMs: 1e4, + maxLoadTimeMs: 1e4, + autoRetry: !1, + timeoutRetry: { + maxNumRetry: 2, + retryDelayMs: 0, + maxRetryDelayMs: 0 + }, + errorRetry: { + maxNumRetry: 1, + retryDelayMs: 1e3, + maxRetryDelayMs: 8e3 + } + } + }, + trickPlaybackConfig: { + enabled: !0, + minIframeDuration: 8 + }, + playlistLoadPolicy: { + default: { + maxTimeToFirstByteMs: 1e4, + maxLoadTimeMs: 2e4, + autoRetry: !1, + timeoutRetry: { + maxNumRetry: 2, + retryDelayMs: 0, + maxRetryDelayMs: 0 + }, + errorRetry: { + maxNumRetry: 2, + retryDelayMs: 1e3, + maxRetryDelayMs: 8e3 + } + }, + customURL: { + maxTimeToFirstByteMs: 1e4, + maxLoadTimeMs: 1e4, + autoRetry: !1, + timeoutRetry: { + maxNumRetry: 2, + retryDelayMs: 0, + maxRetryDelayMs: 0 + }, + errorRetry: { + maxNumRetry: 2, + retryDelayMs: 1e3, + maxRetryDelayMs: 8e3 + } + } + }, + fragLoadPolicy: { + default: { + maxTimeToFirstByteMs: 5e3, + maxLoadTimeMs: 2e4, + autoRetry: !1, + timeoutRetry: Sl, + errorRetry: bl, + forceContentLenCheckIfNoHeader: !1, + reportCDNServer: !0 + }, + customURL: { + maxTimeToFirstByteMs: 1e4, + maxLoadTimeMs: 2e4, + autoRetry: !1, + timeoutRetry: Sl, + errorRetry: bl, + reportCDNServer: !0 + } + }, + steeringManifestLoadPolicy: { + default: { + maxTimeToFirstByteMs: 1e4, + maxLoadTimeMs: 2e4, + autoRetry: !1, + timeoutRetry: { + maxNumRetry: 2, + retryDelayMs: 0, + maxRetryDelayMs: 0 + }, + errorRetry: { + maxNumRetry: 1, + retryDelayMs: 1e3, + maxRetryDelayMs: 8e3 + } + }, + customURL: { + maxTimeToFirstByteMs: 1e4, + maxLoadTimeMs: 1e4, + autoRetry: !1, + timeoutRetry: { + maxNumRetry: 2, + retryDelayMs: 0, + maxRetryDelayMs: 0 + }, + errorRetry: { + maxNumRetry: 1, + retryDelayMs: 1e3, + maxRetryDelayMs: 8e3 + } + } + }, + maxNumAddLevelToPenaltyBox: 4, + firstAudioMustOverlapVideoStart: !1, + keyMinHoldTimeBeforeCleanup: 15e3, + startFragPrefetch: !1, + appendErrorMaxRetry: 3, + alwaysResetOnNewCC: !1, + fLoader: void 0, + pLoader: void 0, + xhrSetup: void 0, + iframeMaxExitSeekDuration: 2e3, + iframeStallMaxRetry: 5, + audioPrimingDelay: 0, + enableCEA708Captions: !0, + customTextTrackCueRenderer: !1, + enableWebVTT: !0, + captionsTextTrack1Label: "English", + captionsTextTrack1LanguageCode: "en", + captionsTextTrack2Label: "Spanish", + captionsTextTrack2LanguageCode: "es", + enableDualTrackSelection: !1, + condenseSubtitleTrack: !1, + earlyFragTolerance: 7, + vttConcurrentLoadCount: 1, + trottleCheckInterval: 2e3, + subtitleLeadTime: 30, + stretchShortVideoTrack: !1, + forceKeyFrameOnDiscontinuity: !0, + useFirstLevelAtIncompatDiscontinuity: !0, + abrBandwidthEstimator: "bandwidth-history-controller", + abrEwmaDefaultEstimate: 5e5, + abrDefaultEstimate: 5e5, + abrBandWidthFactor: .95, + abrBandWidthUpFactor: .9, + abrMaxWithRealBitrate: !1, + maxStarvationDelay: 4, + maxLoadingDelay: 4, + minAutoBitrate: 0, + enableRtcReporting: !1, + rtcIntervalTimeout: 3e5, + rtcSender: "HLSJS", + rtcSessionTag: "none", + useHTTPPlaybackSessionId: !1, + warmupCdms: !1, + enablePerformanceLogging: !1, + overridePlaybackRate: !1, + nativeControlsEnabled: !1, + useCustomMediaFunctions: !0, + seekEventThrottleMs: 150, + enableAdaptiveStartup: !0, + bandwidthHistoryWindowSize: 12e4, + bandwidthHistoryTTL: 6e5, + bandwidthHistoryAggregationMethod: "quadratic-time-weighted", + bandwidthHistoryGetEstimateThrottleMs: 1e3, + defaultTargetDuration: 10, + targetStartupMs: 4e3, + adaptiveStartupMetricsOverride: { + maxValidHeight: 1080, + maxValidBitrate: 1 / 0, + maxPreferredBitrate: 1 / 0 + }, + bandwidthHistoryStorageKey: "AppleHLS-bandwidth-estimation", + storageKeyPrefix: "AppleHLS-", + storage: { + get: "undefined" == typeof localStorage ? void 0 : localStorage.getItem.bind(localStorage), + set: "undefined" == typeof localStorage ? void 0 : localStorage.setItem.bind(localStorage) + }, + minFragmentCount: 10, + minPlaylistCount: 5, + enableCDNFallback: !0, + enableQueryParamsForITunes: !1, + gapless: !1, + useViewportSizeForLevelCap: !1, + statDefaults: { + playlistLoadTimeMs: 500, + playlistParseTimeMs: 50, + fragParseTimeMs: 50, + fragBufferCreationDelayMs: 200, + dataFragAppendMs: 50, + initFragAppendMs: 50 + }, + disableVideoCodecList: new Set([]), + disableAudioCodecList: new Set([dl.ALAC, dl.FLAC, dl.XHEAAC]), + useHighestVideoCodecPrivate: !0, + sessionDataAutoLoad: { + "com.apple.hls.chapters": !0 + } + } + , Ol = Object.assign(Object.assign({}, { + itemId: "Nah", + mediaOptionId: "Nah" + }), { + mediaOptionType: void 0 + }) + , kl = e=>{ + var {itemId: t, mediaOptionId: e} = e; + return "Nah" !== t && "Nah" !== e + } + ; + (gc = ul = ul || {})[gc.Variant = 0] = "Variant", + gc[gc.AltAudio = 1] = "AltAudio", + gc[gc.Subtitle = 2] = "Subtitle"; + const Cl = ["variant", "altAudio", "subtitle"] + , Dl = [ul.Variant, ul.AltAudio, ul.Subtitle] + , Ml = [ul.Variant, ul.AltAudio]; + (gr = cl = cl || {})[gr.Variant = 0] = "Variant", + gr[gr.AltAudio = 1] = "AltAudio"; + const Pl = ["variant", "altAudio"]; + function xl(e) { + switch (e) { + case ul.Variant: + return cl.Variant; + case ul.AltAudio: + return cl.AltAudio; + default: + return null + } + } + function Rl(e) { + return e === cl.Variant ? ul.Variant : ul.AltAudio + } + (mu = hl = hl || {})[mu.NO = 0] = "NO", + mu[mu.YES = 1] = "YES", + (gu = pl = pl || {}).UNKNOWN = "unkn", + gu.VIDEO = "vide", + gu.AUDIO = "soun", + gu.SUBTITLE = "sbtl", + gu.CLOSEDCAPTION = "clcp"; + const Ll = { + search: function(e, t) { + let i, r, n = 0, s = (null == e ? void 0 : e.length) - 1; + for (; n <= s; ) { + var a = t(r = e[i = (n + s) / 2 | 0]); + if (0 < a) + n = 1 + i; + else { + if (!(a < 0)) + return r; + s = i - 1 + } + } + return null + } + }; + var _l = Ll + , Nl = { + findFragmentBySNAndBuffer: function(e, t, i=0, r=0, n=0) { + let s; + e = e ? t[e.mediaSeqNum - t[0].mediaSeqNum + 1] : null; + return s = i < r ? (r - n < i && (n = 0), + e && !this.fragmentWithinToleranceTest(i, n, e) ? e : Ll.search(t, this.fragmentWithinToleranceTest.bind(null, i, n))) : t[t.length - 1], + s + }, + fragmentWithinToleranceTest: function(e, t, i) { + t = Math.min(t, i.duration); + return i.start + i.duration - t <= e ? 1 : i.start - t > e && i.start ? -1 : 0 + } + }; + const Fl = { + startFragmentInCC: function(e, t, i) { + let r = t - i.discoSeqNum; + if (0 === r) { + const t = e[i.mediaSeqNum - e[0].mediaSeqNum - 1]; + r = t && t.discoSeqNum === i.discoSeqNum ? -1 : 0 + } + return r + }, + endFragmentInCC: function(e, t, i) { + let r = t - i.discoSeqNum; + if (0 === r) { + const t = e[i.mediaSeqNum - e[0].mediaSeqNum + 1]; + r = t && t.discoSeqNum === i.discoSeqNum ? 1 : 0 + } + return r + }, + findStartEndFragmentsInCC: function(e, t, i) { + let r, n; + return 0 < (null == e ? void 0 : e.length) && ne(t) && (r = Ll.search(e, Fl.startFragmentInCC.bind(null, e, t)), + n = Ll.search(e, Fl.endFragmentInCC.bind(null, e, t))), + r && !ne(r.discoSeqNum) && (r = void 0), + n && !ne(n.discoSeqNum) && (n = void 0), + { + startFrag: r, + endFrag: n + } + }, + getTimeRangeDictForCC: function(e, t, i) { + var {startFrag: t, endFrag: i} = Fl.findStartEndFragmentsInCC(e, t, i); + return { + start: t.start, + end: i.start + i.duration + } + }, + getTimeRangeForCC: function(e, t, i) { + var {startFrag: t, endFrag: i} = Fl.findStartEndFragmentsInCC(e, t, i); + let r = []; + return t && i && (r = [t.start, i.start + i.duration]), + r + }, + snapToCCTimeRange: function(e, t, i, r) { + r = Fl.getTimeRangeForCC(t, i, r); + return null != r && r.length ? Math.min(r[1], Math.max(r[0], e)) : e + }, + getMinTimeForCC(e, t, i, r) { + if (null == e || !e.length) + return 0; + let n = 0; + if (ne(i) && e) { + e = Fl.getTimeRangeForCC(e, i, r); + if (e) { + const s = Fl.getTimeRangeForCC(t, i, r); + n = null != s && s.length ? Math.max(s[0], e[0]) : e[0] + } + } + return n + }, + ccForTime(e, t) { + t = Ll.search(e, Nl.fragmentWithinToleranceTest.bind(null, t, 0)); + return null == t ? void 0 : t.discoSeqNum + } + }; + var Bl = Fl; + const Ul = Bi(void 0); + function $l(e, t, i=1) { + return e.pipe(an(t), Cs(i)) + } + function Vl(e, t) { + var i = e.timeline; + return { + seconds: (e.seconds - i.rootTimeSeconds) / i.rate * t.rate + t.rootTimeSeconds, + timeline: t + } + } + class Kl { + constructor() { + this._timeline = null + } + get forward() { + var e; + return 0 < (null === (e = this.timeline) || void 0 === e ? void 0 : e.rate) + } + get isStarted() { + return Boolean(this.hostClock) + } + start(e) { + this.stopTime = null, + this._timeline = Object.assign({}, e); + const t = { + rootTimeSeconds: performance.now() / 1e3, + rate: 1 + }; + this.hostClock = { + timeline: t, + getCurrentTime: ()=>({ + seconds: performance.now() / 1e3, + timeline: t + }) + } + } + stop() { + this.isStarted && (this.stopTime = this.getCurrentTime()), + this.hostClock = null, + this._timeline = null + } + get timeline() { + return this._timeline + } + getCurrentTime() { + return this.stopTime || Vl(this.hostClock.getCurrentTime(), this.timeline) + } + } + class Hl { + constructor(e) { + this._timeline = e, + this.lastTimeSeconds = e.rootTimeSeconds + } + get timeline() { + return Object.assign({}, this._timeline) + } + getCurrentTime() { + return { + seconds: this.lastTimeSeconds, + timeline: Object.assign({}, this._timeline) + } + } + } + const jl = { + name: "ifm" + }; + class ql { + constructor(e, t) { + this.config = e, + this.logger = t, + this.scaledFragments = [], + this.iframeClock = new Kl, + this.hasMore$ = new gi(!0), + this.logger = t.child(jl) + } + destroy() { + this.stop() + } + resetScaledSegments() { + this.scaledFragments = [] + } + get anchorFrag() { + return this.scaledFragments.length ? this.scaledFragments[0] : null + } + get lastFrag() { + return this.scaledFragments.length ? this.scaledFragments.slice(-1)[0] : null + } + get isStarted() { + return Boolean(this.iframeClock.isStarted) + } + get iframeRate() { + var e; + return null !== (e = null === (e = this.iframeClock.timeline) || void 0 === e ? void 0 : e.rate) && void 0 !== e ? e : 0 + } + get iframeClockTimeSeconds() { + return this.iframeClock.getCurrentTime().seconds + } + get mediaAppendClockTimeSeconds() { + var e; + return null !== (e = null === (e = this.mediaAppendClock) || void 0 === e ? void 0 : e.getCurrentTime().seconds) && void 0 !== e ? e : 0 + } + stop() { + this.hasMore$.next(!0), + this.iframeClock.stop(), + this.mediaAppendClock = null, + this.resetScaledSegments() + } + checkHasMore() { + this.hasMore$.next(!0) + } + startClocksAndGetFirstFragment(e, t, i, r, n) { + let s = Ll.search(e, Nl.fragmentWithinToleranceTest.bind(null, r, 1e-4)); + if (!s && r >= e[e.length - 1].start && (s = e[e.length - 1]), + !s) + return this.logger.error(`startClocksAndGetFirstFragment => no anchorFrag for time ${r}`), + this.hasMore$.next(!1), + null; + var a = ne(n) ? n : s.discoSeqNum + , a = Bl.getMinTimeForCC(e, t, a, this.logger) + , r = ne(n) && 1 < i ? a : r + , a = 1 < i ? Math.ceil(r) : Math.ceil(a); + return this.iframeClock.start({ + rootTimeSeconds: r, + rate: i + }), + this.mediaAppendClock = new Hl({ + rootTimeSeconds: a, + rate: 1 + }), + { + frag: s, + newMediaRootTime: a + } + } + getNextFragment(e, t, i) { + const r = this.lastFrag + , {iframeClock: n, mediaAppendClock: s} = this + , a = n.timeline; + s.lastTimeSeconds = t; + var o = n.forward ? 1 : -1; + let d, l = Math.max(0, Math.min(r.mediaSeqNum - e[0].mediaSeqNum + o, e.length - 1)); + if (r.mediaSeqNum !== e[l].mediaSeqNum) + do { + d = e[l]; + const i = n.forward ? d.start : d.start + d.duration; + if (Vl({ + seconds: i, + timeline: a + }, s.timeline).seconds >= t && (n.forward && i >= this.iframeClockTimeSeconds || !n.forward && i <= this.iframeClockTimeSeconds)) + break + } while (l += o, + 0 < l && l < e.length); + return d || (this.logger.error(`getNextFragment(bufferEnd: ${t}) => no more frags, but we should have found an end fragment, setting hasMore to false`), + this.hasMore$.next(!1)), + { + frag: d + } + } + nextFragment(e, t, i, r) { + let n, s; + if (this.isStarted && i !== this.iframeRate && (s = this.iframeClockTimeSeconds, + this.stop()), + this.isStarted) { + if (n = this.getNextFragment(e, r, i), + !n.frag) + return; + if (n.frag.discoSeqNum !== this.anchorFrag.discoSeqNum) { + const a = this.iframeClockTimeSeconds; + this.stop(); + const s = this.startClocksAndGetFirstFragment(e, t, i, a, n.frag.discoSeqNum)["newMediaRootTime"]; + n.newMediaRootTime = s + } + } else if (n = this.startClocksAndGetFirstFragment(e, t, i, null != s ? s : r), + !n) + return; + var r = n["frag"] + , r = this.handleNextFrag(e, r); + return Object.assign(Object.assign({}, n), { + frag: r + }) + } + handleNextFrag(e, t) { + const i = Object.assign(Object.assign({}, t), { + iframeMediaStart: NaN, + iframeMediaDuration: NaN + }) + , {mediaAppendClock: r, iframeClock: n} = this; + this.iframeClockBounds = Bl.getTimeRangeDictForCC(e, i.discoSeqNum, this.logger); + var s = r.getCurrentTime().seconds + , t = n.timeline.rate; + return i.start = i.iframeMediaStart = s, + i.iframeMediaDuration = Math.max(i.duration / Math.abs(t), 1 / this.config.minIframeDuration), + this.scaledFragments.push(i), + this.isEndFrag(e, i) && this.hasMore$.next(!1), + i + } + get hasMore() { + return this.hasMore$.value + } + handleWaitForMore() { + return this.isStarted ? (this.iframeClock.getCurrentTime(), + $l(this.hasMore$, e=>!0 === e).pipe(Ja(()=>{} + ))) : Ul + } + isEndFrag(e, t) { + var i = e[0] + , r = e[e.length - 1] + , e = this.iframeClock.forward; + return !e && (null == i ? void 0 : i.mediaSeqNum) === t.mediaSeqNum || e && (null == r ? void 0 : r.mediaSeqNum) === t.mediaSeqNum + } + } + var Ql = {} + , w = {}; + Object.defineProperty(w, "__esModule", { + value: !0 + }), + w.hide = void 0, + w.hide = function() { + return function(e) { + return e.lift(new Gl) + } + } + ; + var Gl = (Wl.prototype.call = function(e, t) { + return t.subscribe(e) + } + , + Wl) + , yi = {}; + function Wl() { + this.hide = !0 + } + Object.defineProperty(yi, "__esModule", { + value: !0 + }), + yi.tag = void 0, + yi.tag = function(t) { + return function(e) { + return e.lift(new Jl(t)) + } + } + ; + var zl, Xl, Yl, Jl = (Zl.prototype.call = function(e, t) { + return t.subscribe(e) + } + , + Zl); + function Zl(e) { + this.tag = e + } + function eu(e) { + const {method: t, isEncrypted: i, uri: r, format: n, formatversions: s} = e + , a = { + method: t, + isEncrypted: i, + uri: r, + format: n, + formatversions: s, + iv: e.ivBuf ? new Uint8Array(e.ivBuf) : null + }; + return e.keyIdBuf && (a.keyId = new Uint8Array(e.keyIdBuf)), + e.keyBuf && (a.key = new Uint8Array(e.keyBuf)), + e.psshBuf && (a.pssh = new Uint8Array(e.psshBuf)), + a + } + A = Ql, + Yl = e && e.__createBinding || (Object.create ? function(e, t, i, r) { + void 0 === r && (r = i), + Object.defineProperty(e, r, { + enumerable: !0, + get: function() { + return t[i] + } + }) + } + : function(e, t, i, r) { + e[r = void 0 === r ? i : r] = t[i] + } + ), + Br = e && e.__exportStar || function(e, t) { + for (var i in e) + "default" === i || t.hasOwnProperty(i) || Yl(t, e, i) + } + , + Object.defineProperty(A, "__esModule", { + value: !0 + }), + Br(w, A), + Br(yi, A), + (gc = zl = zl || {}).MustRequestResponse = "MustRequestResponse", + gc.WaitingForKeyResponse = "WaitingForKeyResponse", + gc.GotKeyResponse = "GotKeyResponse"; + class tu extends Error { + constructor(e, t) { + super(e), + this.code = t + } + } + class iu extends p { + constructor(e, t, i, r, n, s) { + super(o, e, t, i, n), + this.code = r, + this.isTimeout = s, + this.response = n + } + } + class ru extends iu { + constructor(e, t, i, r, n) { + super(n ? "manifestLoadTimeOut" : "manifestLoadError", e, t, i, r, n) + } + } + class nu extends iu { + constructor(e, t, i, r, n, s, a, o) { + switch (super("", e, t, i, r, n), + this.mediaOptionType = s, + this.mediaOptionId = a, + this.url = o, + s) { + case ul.Variant: + this.details = n ? "levelLoadTimeOut" : N; + break; + case ul.AltAudio: + this.details = n ? "audioTrackLoadTimeOut" : "audioTrackLoadError"; + break; + case ul.Subtitle: + this.details = n ? "subtitleTrackLoadTimeout" : "subtitleTrackLoadError" + } + } + } + class su extends iu { + constructor(e, t, i, r) { + super("sessionDataLoadError", e, t, i, r, !1) + } + } + class au extends iu { + constructor(e, t, i, r, n, s, a) { + super(n ? "fragLoadTimeOut" : "fragLoadError", e, t, i, r, n), + this.mediaOptionId = s.mediaOptionId, + this.mediaOptionType = s.mediaOptionType, + this.stats = a + } + } + class ou extends or { + constructor(e, t, i) { + super(), + this.message = e, + this.code = t, + this.stats = i + } + } + class du extends iu { + constructor(e, t, i) { + super("fragAbortError", !1, "Fragment abort", 0, i, !1), + this.candidateMediaOptionId = t, + this.mediaOptionId = e.mediaOptionId, + this.mediaOptionType = e.mediaOptionType + } + } + class lu extends iu { + constructor(e, t, i, r=[]) { + super("keyLoadTimeOut", !1, e, i.code, i, !0), + this.keyuri = t, + this.response = i, + this.mediaOptionIds = r + } + } + (gr = Xl = Xl || {})[gr.InvalidState = 0] = "InvalidState", + gr[gr.Abort = 1] = "Abort", + gr[gr.OutputRestricted = 2] = "OutputRestricted", + gr[gr.AlreadyFailedKey = 3] = "AlreadyFailedKey", + gr[gr.HttpError = 4] = "HttpError", + gr[gr.InternalError = 5] = "InternalError", + gr[gr.LicenseServerError = 6] = "LicenseServerError", + gr[gr.InsufficientCPC = 7] = "InsufficientCPC"; + class uu extends iu { + constructor(e, t, i, r, n, s, a=!1, o=[]) { + super("keyLoadError", a, e, i, r, !1), + this.keyuri = t, + this.isOkToRetry = n, + this.keyErrorReason = s, + this.mediaOptionIds = o + } + } + class cu extends p { + constructor(e, t, i, r, n) { + super(s, "keySystemGenericError", !0, e, r), + this.keyuri = t, + this.code = i, + this.response = r, + this.keysystemstring = n + } + } + function hu(e, t) { + return e instanceof uu ? new uu(e.message,e.keyuri,e.code,e.response,e.isOkToRetry,e.keyErrorReason,e.fatal,t) : e instanceof lu ? new lu(e.message,e.keyuri,$.CryptResponseReceivedSlowly,t) : e ? new V(e.fatal,e.reason,$.InternalError) : null + } + const pu = { + id: "fairplaystreaming", + systemStringPrefix: "com.apple.fps", + keyFormatString: "com.apple.streamingkeydelivery", + securityLevels: { + AppleBaseline: 0, + AppleMain: 1, + Main: 1, + Baseline: 0 + } + }; + class fu extends Od { + constructor(e) { + super(e), + this.store = e + } + get unresolvedUriLoading$() { + return this.selectEntityAction(To.Add).pipe(ur(e=>e.map(e=>this.getEntity(e)))) + } + } + var mu = {}; + Object.defineProperty(mu, "__esModule", { + value: !0 + }); + var gu = "undefined" != typeof Symbol && "symbol" == typeof Symbol("x") + , yu = "undefined" != typeof Map + , vu = "undefined" != typeof Set + , Su = "undefined" != typeof Proxy && void 0 !== Proxy.revocable && "undefined" != typeof Reflect + , bu = gu ? Symbol.for("immer-nothing") : ((yc = {})["immer-nothing"] = !0, + yc) + , Tu = gu ? Symbol.for("immer-draftable") : "__$immer_draftable" + , Eu = gu ? Symbol.for("immer-state") : "__$immer_state" + , Iu = "undefined" != typeof Symbol && Symbol.iterator || "@@iterator" + , wu = { + 0: "Illegal state", + 1: "Immer drafts cannot have computed properties", + 2: "This object has been frozen and should not be mutated", + 3: function(e) { + return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + e + }, + 4: "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.", + 5: "Immer forbids circular references", + 6: "The first or second argument to `produce` must be a function", + 7: "The third argument to `produce` must be a function or undefined", + 8: "First argument to `createDraft` must be a plain object, an array, or an immerable object", + 9: "First argument to `finishDraft` must be a draft returned by `createDraft`", + 10: "The given draft is already finalized", + 11: "Object.defineProperty() cannot be used on an Immer draft", + 12: "Object.setPrototypeOf() cannot be used on an Immer draft", + 13: "Immer only supports deleting array indices", + 14: "Immer only supports setting array indices and the 'length' property", + 15: function(e) { + return "Cannot apply patch, path doesn't resolve: " + e + }, + 16: 'Sets cannot have "replace" patches.', + 17: function(e) { + return "Unsupported patch operation: " + e + }, + 18: function(e) { + return "The plugin for '" + e + "' has not been loaded into Immer. To enable the plugin, import and call `enable" + e + "()` when initializing your application." + }, + 20: "Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available", + 21: function(e) { + return "produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '" + e + "'" + }, + 22: function(e) { + return "'current' expects a draft, got: " + e + }, + 23: function(e) { + return "'original' expects a draft, got: " + e + } + }; + function Au(e) { + for (var t = arguments.length, i = new Array(1 < t ? t - 1 : 0), r = 1; r < t; r++) + i[r - 1] = arguments[r]; + var n = wu[e] + , e = n ? "function" == typeof n ? n.apply(null, i) : n : "unknown error nr: " + e; + throw new Error("[Immer] " + e) + } + function Ou(e) { + return !!e && !!e[Eu] + } + function ku(t) { + return !!t && (function() { + if (!t || "object" != typeof t) + return !1; + var e = Object.getPrototypeOf(t); + return !e || e === Object.prototype + }() || Array.isArray(t) || !!t[Tu] || !!t.constructor[Tu] || Nu(t) || Fu(t)) + } + var Cu = "undefined" != typeof Reflect && Reflect.ownKeys ? Reflect.ownKeys : void 0 !== Object.getOwnPropertySymbols ? function(e) { + return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e)) + } + : Object.getOwnPropertyNames + , Du = Object.getOwnPropertyDescriptors || function(t) { + var i = {}; + return Cu(t).forEach(function(e) { + i[e] = Object.getOwnPropertyDescriptor(t, e) + }), + i + } + ; + function Mu(i, r, t) { + void 0 === t && (t = !1), + 0 === Pu(i) ? (t ? Object.keys : Cu)(i).forEach(function(e) { + t && "symbol" == typeof e || r(e, i[e], i) + }) : i.forEach(function(e, t) { + return r(t, e, i) + }) + } + function Pu(e) { + var t = e[Eu]; + return t ? 3 < t.type_ ? t.type_ - 4 : t.type_ : Array.isArray(e) ? 1 : Nu(e) ? 2 : Fu(e) ? 3 : 0 + } + function xu(e, t) { + return 2 === Pu(e) ? e.has(t) : Object.prototype.hasOwnProperty.call(e, t) + } + function Ru(e, t) { + return 2 === Pu(e) ? e.get(t) : e[t] + } + function Lu(e, t, i) { + var r = Pu(e); + 2 === r ? e.set(t, i) : 3 === r ? (e.delete(t), + e.add(i)) : e[t] = i + } + function _u(e, t) { + return e === t ? 0 !== e || 1 / e == 1 / t : e != e && t != t + } + function Nu(e) { + return yu && e instanceof Map + } + function Fu(e) { + return vu && e instanceof Set + } + function Bu(e) { + return e.copy_ || e.base_ + } + function Uu(e) { + if (Array.isArray(e)) + return Array.prototype.slice.call(e); + var t = Du(e); + delete t[Eu]; + for (var i = Cu(t), r = 0; r < i.length; r++) { + var n = i[r] + , s = t[n]; + !1 === s.writable && (s.writable = !0, + s.configurable = !0), + (s.get || s.set) && (t[n] = { + configurable: !0, + writable: !0, + enumerable: s.enumerable, + value: e[n] + }) + } + return Object.create(Object.getPrototypeOf(e), t) + } + function $u(e, t) { + Ku(e) || Ou(e) || !ku(e) || (1 < Pu(e) && (e.set = e.add = e.clear = e.delete = Vu), + Object.freeze(e), + t && Mu(e, function(e, t) { + return $u(t, !0) + }, !0)) + } + function Vu() { + Au(2) + } + function Ku(e) { + return null == e || "object" != typeof e || Object.isFrozen(e) + } + var Hu, ju = {}; + function qu(e) { + var t = ju[e]; + return t || Au(18, e), + t + } + function Qu(e, t) { + ju[e] || (ju[e] = t) + } + function Gu() { + return Hu || Au(0), + Hu + } + function Wu(e, t) { + t && (qu("Patches"), + e.patches_ = [], + e.inversePatches_ = [], + e.patchListener_ = t) + } + function zu(e) { + Xu(e), + e.drafts_.forEach(Ju), + e.drafts_ = null + } + function Xu(e) { + e === Hu && (Hu = e.parent_) + } + function Yu(e) { + return Hu = { + drafts_: [], + parent_: Hu, + immer_: e, + canAutoFreeze_: !0, + unfinalizedDrafts_: 0 + } + } + function Ju(e) { + e = e[Eu]; + 0 === e.type_ || 1 === e.type_ ? e.revoke_() : e.revoked_ = !0 + } + function Zu(e, t) { + t.unfinalizedDrafts_ = t.drafts_.length; + var i = t.drafts_[0] + , r = void 0 !== e && e !== i; + return t.immer_.useProxies_ || qu("ES5").willFinalizeES5_(t, e, r), + r ? (i[Eu].modified_ && (zu(t), + Au(4)), + ku(e) && (e = ec(t, e), + t.parent_ || ic(t, e)), + t.patches_ && qu("Patches").generateReplacementPatches_(i[Eu], e, t.patches_, t.inversePatches_)) : e = ec(t, i, []), + zu(t), + t.patches_ && t.patchListener_(t.patches_, t.inversePatches_), + e !== bu ? e : void 0 + } + function ec(i, r, n) { + if (Ku(r)) + return r; + var s, a = r[Eu]; + return a ? a.scope_ !== i ? r : a.modified_ ? (a.finalized_ || (a.finalized_ = !0, + a.scope_.unfinalizedDrafts_--, + s = 4 === a.type_ || 5 === a.type_ ? a.copy_ = Uu(a.draft_) : a.copy_, + Mu(3 === a.type_ ? new Set(s) : s, function(e, t) { + return tc(i, a, s, e, t, n) + }), + ic(i, s, !1), + n && i.patches_ && qu("Patches").generatePatches_(a, n, i.patches_, i.inversePatches_)), + a.copy_) : (ic(i, a.base_, !0), + a.base_) : (Mu(r, function(e, t) { + return tc(i, a, r, e, t, n) + }, !0), + r) + } + function tc(e, t, i, r, n, s) { + if (n === i && Au(5), + Ou(n)) { + s = ec(e, n, s && t && 3 !== t.type_ && !xu(t.assigned_, r) ? s.concat(r) : void 0); + if (Lu(i, r, s), + !Ou(s)) + return; + e.canAutoFreeze_ = !1 + } + ku(n) && !Ku(n) && (!e.immer_.autoFreeze_ && e.unfinalizedDrafts_ < 1 || (ec(e, n), + t && t.scope_.parent_ || ic(e, n))) + } + function ic(e, t, i) { + void 0 === i && (i = !1), + e.immer_.autoFreeze_ && e.canAutoFreeze_ && $u(t, i) + } + var rc = { + get: function(e, t) { + if (t === Eu) + return e; + var i, r, n = Bu(e); + if (!xu(n, t)) + return i = e, + (r = ac(n, t)) ? "value"in r ? r.value : null === (r = r.get) || void 0 === r ? void 0 : r.call(i.draft_) : void 0; + n = n[t]; + return !e.finalized_ && ku(n) && n === sc(e.base_, t) ? (dc(e), + e.copy_[t] = uc(e.scope_.immer_, n, e)) : n + }, + has: function(e, t) { + return t in Bu(e) + }, + ownKeys: function(e) { + return Reflect.ownKeys(Bu(e)) + }, + set: function(e, t, i) { + var r = ac(Bu(e), t); + if (null != r && r.set) + return r.set.call(e.draft_, i), + !0; + if (!e.modified_) { + var n = sc(Bu(e), t) + , r = null == n ? void 0 : n[Eu]; + if (r && r.base_ === i) + return e.copy_[t] = i, + !(e.assigned_[t] = !1); + if (_u(i, n) && (void 0 !== i || xu(e.base_, t))) + return !0; + dc(e), + oc(e) + } + return e.copy_[t] = i, + e.assigned_[t] = !0 + }, + deleteProperty: function(e, t) { + return void 0 !== sc(e.base_, t) || t in e.base_ ? (e.assigned_[t] = !1, + dc(e), + oc(e)) : delete e.assigned_[t], + e.copy_ && delete e.copy_[t], + !0 + }, + getOwnPropertyDescriptor: function(e, t) { + var i = Bu(e) + , r = Reflect.getOwnPropertyDescriptor(i, t); + return r && { + writable: !0, + configurable: 1 !== e.type_ || "length" !== t, + enumerable: r.enumerable, + value: i[t] + } + }, + defineProperty: function() { + Au(11) + }, + getPrototypeOf: function(e) { + return Object.getPrototypeOf(e.base_) + }, + setPrototypeOf: function() { + Au(12) + } + } + , nc = {}; + function sc(e, t) { + var i = e[Eu]; + return (i ? Bu(i) : e)[t] + } + function ac(e, t) { + if (t in e) + for (var i = Object.getPrototypeOf(e); i; ) { + var r = Object.getOwnPropertyDescriptor(i, t); + if (r) + return r; + i = Object.getPrototypeOf(i) + } + } + function oc(e) { + e.modified_ || (e.modified_ = !0, + e.parent_ && oc(e.parent_)) + } + function dc(e) { + e.copy_ || (e.copy_ = Uu(e.base_)) + } + Mu(rc, function(e, t) { + nc[e] = function() { + return arguments[0] = arguments[0][0], + t.apply(this, arguments) + } + }), + nc.deleteProperty = function(e, t) { + return isNaN(parseInt(t)) && Au(13), + rc.deleteProperty.call(this, e[0], t) + } + , + nc.set = function(e, t, i) { + return "length" !== t && isNaN(parseInt(t)) && Au(14), + rc.set.call(this, e[0], t, i, e[0]) + } + ; + (w = lc.prototype).produce = function(e, s, t) { + if ("function" == typeof e && "function" != typeof s) { + var a = s; + s = e; + var o = this; + return function(e) { + var t = this; + void 0 === e && (e = a); + for (var i = arguments.length, r = new Array(1 < i ? i - 1 : 0), n = 1; n < i; n++) + r[n - 1] = arguments[n]; + return o.produce(e, function(e) { + return s.call.apply(s, [t, e].concat(r)) + }) + } + } + var i; + if ("function" != typeof s && Au(6), + void 0 !== t && "function" != typeof t && Au(7), + ku(e)) { + var r = Yu(this) + , n = uc(this, e, void 0) + , d = !0; + try { + i = s(n), + d = !1 + } finally { + (d ? zu : Xu)(r) + } + return "undefined" != typeof Promise && i instanceof Promise ? i.then(function(e) { + return Wu(r, t), + Zu(e, r) + }, function(e) { + throw zu(r), + e + }) : (Wu(r, t), + Zu(i, r)) + } + if (!e || "object" != typeof e) + return (i = s(e)) === bu ? void 0 : (void 0 === i && (i = e), + this.autoFreeze_ && $u(i, !0), + i); + Au(21, e) + } + , + w.produceWithPatches = function(n, e, t) { + var i, r, s = this; + return "function" == typeof n ? function(e) { + for (var t = arguments.length, i = new Array(1 < t ? t - 1 : 0), r = 1; r < t; r++) + i[r - 1] = arguments[r]; + return s.produceWithPatches(e, function(e) { + return n.apply(void 0, [e].concat(i)) + }) + } + : [this.produce(n, e, function(e, t) { + i = e, + r = t + }), i, r] + } + , + w.createDraft = function(e) { + ku(e) || Au(8), + Ou(e) && (e = cc(e)); + var t = Yu(this) + , e = uc(this, e, void 0); + return e[Eu].isManual_ = !0, + Xu(t), + e + } + , + w.finishDraft = function(e, t) { + e = e && e[Eu]; + e && e.isManual_ || Au(9), + e.finalized_ && Au(10); + e = e.scope_; + return Wu(e, t), + Zu(void 0, e) + } + , + w.setAutoFreeze = function(e) { + this.autoFreeze_ = e + } + , + w.setUseProxies = function(e) { + e && !Su && Au(20), + this.useProxies_ = e + } + , + w.applyPatches = function(e, t) { + for (var i = t.length - 1; 0 <= i; i--) { + var r = t[i]; + if (0 === r.path.length && "replace" === r.op) { + e = r.value; + break + } + } + var n = qu("Patches").applyPatches_; + return Ou(e) ? n(e, t) : this.produce(e, function(e) { + return n(e, t.slice(i + 1)) + }) + } + , + Br = lc; + function lc(e) { + this.useProxies_ = Su, + this.autoFreeze_ = !0, + "boolean" == typeof (null == e ? void 0 : e.useProxies) && this.setUseProxies(e.useProxies), + "boolean" == typeof (null == e ? void 0 : e.autoFreeze) && this.setAutoFreeze(e.autoFreeze), + this.produce = this.produce.bind(this), + this.produceWithPatches = this.produceWithPatches.bind(this) + } + function uc(e, t, i) { + t = Nu(t) ? qu("MapSet").proxyMap_(t, i) : Fu(t) ? qu("MapSet").proxySet_(t, i) : e.useProxies_ ? function(e, t) { + var i = Array.isArray(e) + , r = { + type_: i ? 1 : 0, + scope_: t ? t.scope_ : Gu(), + modified_: !1, + finalized_: !1, + assigned_: {}, + parent_: t, + base_: e, + draft_: null, + copy_: null, + revoke_: null, + isManual_: !1 + } + , t = r + , e = rc; + i && (t = [r], + e = nc); + t = Proxy.revocable(t, e), + e = t.revoke, + t = t.proxy; + return r.draft_ = t, + r.revoke_ = e, + t + }(t, i) : qu("ES5").createES5Proxy_(t, i); + return (i ? i.scope_ : Gu()).drafts_.push(t), + t + } + function cc(e) { + return Ou(e) || Au(22, e), + function i(e) { + if (!ku(e)) + return e; + var r, n = e[Eu], t = Pu(e); + if (n) { + if (!n.modified_ && (n.type_ < 4 || !qu("ES5").hasChanges_(n))) + return n.base_; + n.finalized_ = !0, + r = hc(e, t), + n.finalized_ = !1 + } else + r = hc(e, t); + return Mu(r, function(e, t) { + n && Ru(n.base_, e) === t || Lu(r, e, i(t)) + }), + 3 === t ? new Set(r) : r + }(e) + } + function hc(e, t) { + switch (t) { + case 2: + return new Map(e); + case 3: + return Array.from(e) + } + return Uu(e) + } + function pc() { + var r = {}; + function d(i, e) { + var t = r[i]; + return t ? t.enumerable = e : r[i] = t = { + configurable: !0, + enumerable: e, + get: function() { + var e = this[Eu]; + return a(e), + rc.get(e, i) + }, + set: function(e) { + var t = this[Eu]; + a(t), + rc.set(t, i, e) + } + }, + t + } + function n(e) { + for (var t = e.length - 1; 0 <= t; t--) { + var i = e[t][Eu]; + if (!i.modified_) + switch (i.type_) { + case 5: + u(i) && oc(i); + break; + case 4: + s(i) && oc(i) + } + } + } + function s(e) { + for (var t = e.base_, i = e.draft_, r = Cu(i), n = r.length - 1; 0 <= n; n--) { + var s = r[n]; + if (s !== Eu) { + var a = t[s]; + if (void 0 === a && !xu(t, s)) + return !0; + var o = i[s] + , s = o && o[Eu]; + if (s ? s.base_ !== a : !_u(o, a)) + return !0 + } + } + e = !!t[Eu]; + return r.length !== Cu(t).length + (e ? 0 : 1) + } + function u(e) { + var t = e.draft_; + if (t.length !== e.base_.length) + return !0; + t = Object.getOwnPropertyDescriptor(t, t.length - 1); + return !(!t || t.get) + } + function a(e) { + e.revoked_ && Au(3, JSON.stringify(Bu(e))) + } + Qu("ES5", { + createES5Proxy_: function(e, t) { + var i = Array.isArray(e) + , r = function(e, t) { + if (e) { + for (var i = new Array(t.length), r = 0; r < t.length; r++) + Object.defineProperty(i, "" + r, d(r, !0)); + return i + } + var n = Du(t); + delete n[Eu]; + for (var s = Cu(n), a = 0; a < s.length; a++) { + var o = s[a]; + n[o] = d(o, e || !!n[o].enumerable) + } + return Object.create(Object.getPrototypeOf(t), n) + }(i, e) + , e = { + type_: i ? 5 : 4, + scope_: t ? t.scope_ : Gu(), + modified_: !1, + finalized_: !1, + assigned_: {}, + parent_: t, + base_: e, + draft_: r, + copy_: null, + revoked_: !1, + isManual_: !1 + }; + return Object.defineProperty(r, Eu, { + value: e, + writable: !0 + }), + r + }, + willFinalizeES5_: function(e, t, i) { + i ? Ou(t) && t[Eu].scope_ === e && n(e.drafts_) : (e.patches_ && function t(e) { + if (e && "object" == typeof e) { + var i = e[Eu]; + if (i) { + var r = i.base_ + , n = i.draft_ + , s = i.assigned_; + if (4 === (e = i.type_)) + Mu(n, function(e) { + e !== Eu && (void 0 !== r[e] || xu(r, e) ? s[e] || t(n[e]) : (s[e] = !0, + oc(i))) + }), + Mu(r, function(e) { + void 0 !== n[e] || xu(n, e) || (s[e] = !1, + oc(i)) + }); + else if (5 === e) { + if (u(i) && (oc(i), + s.length = !0), + n.length < r.length) + for (var a = n.length; a < r.length; a++) + s[a] = !1; + else + for (var o = r.length; o < n.length; o++) + s[o] = !0; + for (var d = Math.min(n.length, r.length), l = 0; l < d; l++) + void 0 === s[l] && t(n[l]) + } + } + } + }(e.drafts_[0]), + n(e.drafts_)) + }, + hasChanges_: function(e) { + return (4 === e.type_ ? s : u)(e) + } + }) + } + function fc() { + var m = "replace" + , g = "add" + , y = "remove"; + function l(e) { + if (!ku(e)) + return e; + if (Array.isArray(e)) + return e.map(l); + if (Nu(e)) + return new Map(Array.from(e.entries()).map(function(e) { + return [e[0], l(e[1])] + })); + if (Fu(e)) + return new Set(Array.from(e).map(l)); + var t, i = Object.create(Object.getPrototypeOf(e)); + for (t in e) + i[t] = l(e[t]); + return i + } + function v(e) { + return Ou(e) ? l(e) : e + } + Qu("Patches", { + applyPatches_: function(d, e) { + return e.forEach(function(e) { + for (var t = e.path, i = e.op, r = d, n = 0; n < t.length - 1; n++) + "object" != typeof (r = Ru(r, t[n])) && Au(15, t.join("/")); + var s = Pu(r) + , a = l(e.value) + , o = t[t.length - 1]; + switch (i) { + case m: + switch (s) { + case 2: + return r.set(o, a); + case 3: + Au(16); + default: + return r[o] = a + } + case g: + switch (s) { + case 1: + return r.splice(o, 0, a); + case 2: + return r.set(o, a); + case 3: + return r.add(a); + default: + return r[o] = a + } + case y: + switch (s) { + case 1: + return r.splice(o, 1); + case 2: + return r.delete(o); + case 3: + return r.delete(e.value); + default: + return delete r[o] + } + default: + Au(17, i) + } + }), + d + }, + generatePatches_: function(c, e, t, i) { + switch (c.type_) { + case 0: + case 4: + case 2: + return l = e, + u = t, + h = i, + p = c.base_, + f = c.copy_, + void Mu(c.assigned_, function(e, t) { + var i = Ru(p, e) + , r = Ru(f, e) + , t = t ? xu(p, e) ? m : g : y; + i === r && t == m || (e = l.concat(e), + u.push(t == y ? { + op: t, + path: e + } : { + op: t, + path: e, + value: r + }), + h.push(t == g ? { + op: y, + path: e + } : t == y ? { + op: g, + path: e, + value: v(i) + } : { + op: m, + path: e, + value: v(i) + })) + }); + case 5: + case 1: + return function(e, t, i) { + var r, n = c.base_, s = c.assigned_, a = c.copy_; + a.length < n.length && (n = (r = [a, n])[0], + a = r[1], + t = (r = [i, t])[0], + i = r[1]); + for (var o, d = 0; d < n.length; d++) + s[d] && a[d] !== n[d] && (o = e.concat([d]), + t.push({ + op: m, + path: o, + value: v(a[d]) + }), + i.push({ + op: m, + path: o, + value: v(n[d]) + })); + for (var l = n.length; l < a.length; l++) { + var u = e.concat([l]); + t.push({ + op: g, + path: u, + value: v(a[l]) + }) + } + n.length < a.length && i.push({ + op: m, + path: e.concat(["length"]), + value: n.length + }) + }(e, t, i); + case 3: + return r = e, + n = t, + s = i, + a = c.base_, + o = c.copy_, + d = 0, + a.forEach(function(e) { + var t; + o.has(e) || (t = r.concat([d]), + n.push({ + op: y, + path: t, + value: e + }), + s.unshift({ + op: g, + path: t, + value: e + })), + d++ + }), + d = 0, + void o.forEach(function(e) { + var t; + a.has(e) || (t = r.concat([d]), + n.push({ + op: g, + path: t, + value: e + }), + s.unshift({ + op: y, + path: t, + value: e + })), + d++ + }) + } + var r, n, s, a, o, d, l, u, h, p, f + }, + generateReplacementPatches_: function(e, t, i, r) { + i.push({ + op: m, + path: [], + value: t + }), + r.push({ + op: m, + path: [], + value: e.base_ + }) + } + }) + } + function mc() { + var r = function(e, t) { + return (r = Object.setPrototypeOf || { + __proto__: [] + }instanceof Array && function(e, t) { + e.__proto__ = t + } + || function(e, t) { + for (var i in t) + t.hasOwnProperty(i) && (e[i] = t[i]) + } + )(e, t) + }; + function i(e, t) { + function i() { + this.constructor = e + } + r(e, t), + e.prototype = (i.prototype = t.prototype, + new i) + } + var n = function() { + function e(e, t) { + return this[Eu] = { + type_: 2, + parent_: t, + scope_: t ? t.scope_ : Gu(), + modified_: !1, + finalized_: !1, + copy_: void 0, + assigned_: void 0, + base_: e, + draft_: this, + isManual_: !1, + revoked_: !1 + }, + this + } + i(e, Map); + var t = e.prototype; + return Object.defineProperty(t, "size", { + get: function() { + return Bu(this[Eu]).size + } + }), + t.has = function(e) { + return Bu(this[Eu]).has(e) + } + , + t.set = function(e, t) { + var i = this[Eu]; + return d(i), + Bu(i).has(e) && Bu(i).get(e) === t || (s(i), + oc(i), + i.assigned_.set(e, !0), + i.copy_.set(e, t), + i.assigned_.set(e, !0)), + this + } + , + t.delete = function(e) { + if (!this.has(e)) + return !1; + var t = this[Eu]; + return d(t), + s(t), + oc(t), + t.assigned_.set(e, !1), + t.copy_.delete(e), + !0 + } + , + t.clear = function() { + var t = this[Eu]; + d(t), + Bu(t).size && (s(t), + oc(t), + t.assigned_ = new Map, + Mu(t.base_, function(e) { + t.assigned_.set(e, !1) + }), + t.copy_.clear()) + } + , + t.forEach = function(r, n) { + var s = this; + Bu(this[Eu]).forEach(function(e, t, i) { + r.call(n, s.get(t), t, s) + }) + } + , + t.get = function(e) { + var t = this[Eu]; + d(t); + var i = Bu(t).get(e); + if (t.finalized_ || !ku(i)) + return i; + if (i !== t.base_.get(e)) + return i; + i = uc(t.scope_.immer_, i, t); + return s(t), + t.copy_.set(e, i), + i + } + , + t.keys = function() { + return Bu(this[Eu]).keys() + } + , + t.values = function() { + var e, t = this, i = this.keys(); + return (e = {})[Iu] = function() { + return t.values() + } + , + e.next = function() { + var e = i.next(); + return e.done ? e : { + done: !1, + value: t.get(e.value) + } + } + , + e + } + , + t.entries = function() { + var e, i = this, r = this.keys(); + return (e = {})[Iu] = function() { + return i.entries() + } + , + e.next = function() { + var e = r.next(); + if (e.done) + return e; + var t = i.get(e.value); + return { + done: !1, + value: [e.value, t] + } + } + , + e + } + , + t[Iu] = function() { + return this.entries() + } + , + e + }(); + function s(e) { + e.copy_ || (e.assigned_ = new Map, + e.copy_ = new Map(e.base_)) + } + var a = function() { + function e(e, t) { + return this[Eu] = { + type_: 3, + parent_: t, + scope_: t ? t.scope_ : Gu(), + modified_: !1, + finalized_: !1, + copy_: void 0, + base_: e, + draft_: this, + drafts_: new Map, + revoked_: !1, + isManual_: !1 + }, + this + } + i(e, Set); + var t = e.prototype; + return Object.defineProperty(t, "size", { + get: function() { + return Bu(this[Eu]).size + } + }), + t.has = function(e) { + var t = this[Eu]; + return d(t), + t.copy_ ? !!t.copy_.has(e) || !(!t.drafts_.has(e) || !t.copy_.has(t.drafts_.get(e))) : t.base_.has(e) + } + , + t.add = function(e) { + var t = this[Eu]; + return d(t), + this.has(e) || (o(t), + oc(t), + t.copy_.add(e)), + this + } + , + t.delete = function(e) { + if (!this.has(e)) + return !1; + var t = this[Eu]; + return d(t), + o(t), + oc(t), + t.copy_.delete(e) || !!t.drafts_.has(e) && t.copy_.delete(t.drafts_.get(e)) + } + , + t.clear = function() { + var e = this[Eu]; + d(e), + Bu(e).size && (o(e), + oc(e), + e.copy_.clear()) + } + , + t.values = function() { + var e = this[Eu]; + return d(e), + o(e), + e.copy_.values() + } + , + t.entries = function() { + var e = this[Eu]; + return d(e), + o(e), + e.copy_.entries() + } + , + t.keys = function() { + return this.values() + } + , + t[Iu] = function() { + return this.values() + } + , + t.forEach = function(e, t) { + for (var i = this.values(), r = i.next(); !r.done; ) + e.call(t, r.value, r.value, this), + r = i.next() + } + , + e + }(); + function o(i) { + i.copy_ || (i.copy_ = new Set, + i.base_.forEach(function(e) { + var t; + ku(e) ? (t = uc(i.scope_.immer_, e, i), + i.drafts_.set(e, t), + i.copy_.add(t)) : i.copy_.add(e) + })) + } + function d(e) { + e.revoked_ && Au(3, JSON.stringify(Bu(e))) + } + Qu("MapSet", { + proxyMap_: function(e, t) { + return new n(e,t) + }, + proxySet_: function(e, t) { + return new a(e,t) + } + }) + } + var yi = new Br + , A = yi.produce + , gc = yi.produceWithPatches.bind(yi) + , gr = yi.setAutoFreeze.bind(yi) + , yc = yi.setUseProxies.bind(yi) + , gu = yi.applyPatches.bind(yi) + , w = yi.createDraft.bind(yi) + , yi = yi.finishDraft.bind(yi); + mu.Immer = Br, + mu.applyPatches = gu, + mu.castDraft = function(e) { + return e + } + , + mu.castImmutable = function(e) { + return e + } + , + mu.createDraft = w, + mu.current = cc, + mu.default = A, + mu.enableAllPlugins = function() { + pc(), + mc(), + fc() + } + , + mu.enableES5 = pc; + w = mu.enableMapSet = mc; + mu.enablePatches = fc, + mu.finishDraft = yi, + mu.immerable = Tu, + mu.isDraft = Ou, + mu.isDraftable = ku, + mu.nothing = bu, + mu.original = function(e) { + return Ou(e) || Au(23, e), + e[Eu].base_ + } + ; + var vc = mu.produce = A; + mu.produceWithPatches = gc, + mu.setAutoFreeze = gr, + mu.setUseProxies = yc; + class Sc { + constructor(e) { + this.store = e + } + createUnresolvedUriLoading(e, t, i) { + Co("loader.create.unresolvedUriLoading"), + this.store.add({ + uri: e, + responseType: t, + userAgent: i + }) + } + removeUnresolvedUriLoading(e) { + Co("loader.remove.unresolvedUriLoading"), + this.store.remove(e) + } + } + const bc = new class extends pd { + constructor() { + super({}, { + name: "loader", + producerFn: vc, + idKey: "uri" + }) + } + } + ; + let Tc = null; + class Ec extends t { + trigger(e, t) { + try { + this.emit(e, e, t), + "hlsFragLoadProgress" !== e.toString() && ("hlsInternalError" !== e && "hlsError" !== e || !t.length || JSON.stringify(t[0], ["fatal", "details", "reason"]), + e.toString()) + } catch (t) { + qe().warn(`error in event listener for ${e}: ${t.message}`) + } + } + } + class Ic { + constructor(e, t) { + this.target = e, + this._this = t + } + eventWithOptions(e, t, i, r=this._this) { + let n = en(this.target, e, t); + return this.target instanceof Ec && (n = n.pipe(ur(([,e])=>e))), + i && (r && (i = i.bind(r)), + n = n.pipe(Ja(i))), + n + } + event(e, t, i=this._this) { + return this.eventWithOptions(e, void 0, t, i) + } + listen(e, t, i, r=this._this) { + return this.event(e, i, r).pipe($a(t)).subscribe() + } + } + function wc(e, t) { + return new Ic(e,t) + } + function Ac(e, t, i) { + var r; + return { + currentTarget: null !== (r = null == i ? void 0 : i.currentTarget) && void 0 !== r ? r : e, + target: null !== (i = null == i ? void 0 : i.target) && void 0 !== i ? i : e, + type: t + } + } + function Oc(y, v) { + return new Ut(e=>{ + const {maxTimeToFirstByteMs: t, maxLoadTimeMs: i} = v + , r = new XMLHttpRequest + , n = { + trequest: performance.now(), + tfirst: NaN, + tload: NaN, + loaded: 0, + total: NaN, + complete: !1 + } + , s = wc(r) + , a = s.event("progress").pipe(wa(), so(300, Zi, { + leading: !0, + trailing: !0 + }), ur(e=>(isNaN(n.tfirst) && (n.tfirst = performance.now()), + n.loaded = e.loaded, + e.lengthComputable && (n.total = e.total), + e.target)), an(e=>3 <= e.readyState)) + , o = s.event("readystatechange").pipe(wa(), Hi(Zi), ur(e=>e.target), an(e=>2 <= e.readyState), Ja(e=>{ + isNaN(n.tfirst) && 3 <= e.readyState && (n.tfirst = performance.now()) + } + )); + let d = Ti; + isFinite(t) && 0 < t && (d = nn(a, o).pipe(Cs(1), vo(0 < y.extendMaxTTFB ? y.extendMaxTTFB : t), Ra(()=>Ti))); + let l = Ti; + isFinite(i) && 0 < i && (l = o.pipe(an(e=>4 <= e.readyState), Cs(1), vo(i), Ra(()=>Ti))); + let u = Ti; + y.onProgress && (u = nn(Bi(r), a).pipe(ur(e=>{ + const {getData: t, cb: i} = y.onProgress; + return i(y.url, e.status, n, t ? e.response : void 0) + } + ), Qa(e=>!e, !0)).pipe(Ua(Ti))); + const c = nn(a.pipe(Ra(()=>Ti)), o, d, l, u).pipe(Ra(e=>{ + if (4 <= e.readyState) { + if (n.complete = !0, + 200 <= e.status && e.status < 300) { + if (n.tload = performance.now(), + n.contentType = e.getResponseHeader("Content-Type"), + v.reportCDNServer && (n.cdnServer = e.getResponseHeader("CDN-Server")), + n.contentLength = v.forceContentLenCheckIfNoHeader ? function(e) { + let t; + const i = e.getResponseHeader("Content-Encoding") + , r = e.getResponseHeader("Transfer-Encoding") + , n = !i || i && "identity" === i.toLowerCase() + , s = !r || r && "identity" === r.toLowerCase(); + return n && s && (t = function(e) { + e = /([0-9]+)\-([0-9]+)\/([0-9]+)/.exec(e); + return e ? parseInt(e[2]) - parseInt(e[1]) + 1 : void 0 + }(e.getResponseHeader("Content-Range")), + ne(t) || (t = parseInt(e.getResponseHeader("Content-Length")))), + t + }(e) : null, + i = e, + (r = y).collectServerInstanceInfo && (r.serverInstanceInfo = {}, + r.collectServerInstanceInfo.forEach(e=>{ + var t = i.getResponseHeader(e); + t && (r.serverInstanceInfo[e] = t) + } + )), + "arraybuffer" === y.responseType ? n.loaded = e.response.byteLength : n.loaded = e.responseText.length, + n.total = n.loaded, + y.checkContentLength && (0 === n.total || ne(n.contentLength) && n.total != n.contentLength)) + throw new tu("Network error",e.status); + return Bi([e, n]) + } + throw new tu("Network error",e.status) + } + var i, r; + return Ti + } + ), Cs(1), Un(e=>{ + if (e instanceof or) + throw new ou(e.message,0,n); + if (!(e instanceof tu)) + throw new tu(e.message,0); + throw e + } + )).subscribe(e) + , {url: h, method: p, byteRangeOffset: f, responseType: m, body: g} = y; + y.mimeType && r.overrideMimeType(y.mimeType); + try { + const v = y.xhrSetup; + if (v) + try { + v(r, h) + } catch (e) { + r.open(p, y.url, !0), + v(r, y.url) + } + r.readyState || r.open(p, y.url, !0) + } catch (e) { + throw new tu(e.message,r.status) + } + if (r.responseType = m, + f && ne(f.start) && ne(f.end) && 0 <= f.start && f.end > f.start) { + const {start: y, end: v} = f; + r.setRequestHeader("Range", `bytes=${y}-${v - 1}`) + } + if (y.headers) + for (const [v,e] of Object.entries(y.headers)) + r.setRequestHeader(v, e); + return "POST" === p && g ? r.send(g) : r.send(), + ()=>{ + r.abort(), + c.unsubscribe() + } + } + ) + } + const kc = { + name: "CustomUrlLoader" + }; + class Cc { + constructor(e) { + this.loaderService = e, + this.requestMap = {}, + this.logger = qe() + } + load(a, o) { + return new Ut(e=>{ + const t = a.url + , i = o["maxTimeToFirstByteMs"] + , r = { + trequest: performance.now(), + tfirst: NaN, + tload: NaN, + loaded: 0, + total: NaN, + complete: !1 + } + , n = (this.requestMap[t] = new Ji).pipe(vo(0 < a.extendMaxTTFB ? a.extendMaxTTFB : i), Ra(e=>(r.tfirst = performance.now(), + this.handleExternalResponse(e, a, o, r))), Un(e=>{ + if (e instanceof or) + throw new ou(e.message,0,r); + throw e + } + ), $s(()=>{ + this.requestMap[t] = void 0, + this.loaderService.removeUnresolvedUriLoading(t) + } + )); + a.onProgress && a.onProgress.cb(t, 0, r, void 0); + const s = n.subscribe(e); + return this.loaderService.createUnresolvedUriLoading(t, a.responseType, navigator.userAgent), + ()=>{ + s.unsubscribe(), + this.requestMap[t] = void 0 + } + } + ) + } + setCustomUrlResponse(e, t) { + const i = this.requestMap[e]; + i && (i.next(t), + i.complete(), + this.requestMap[e] = void 0) + } + handleExternalResponse(e, t, i, r) { + r.tload = performance.now(); + var n = e.response.status || 200; + return 200 <= n && n < 300 ? ("arraybuffer" === t.responseType && e.response.data instanceof ArrayBuffer ? r.loaded = e.response.data.byteLength : r.loaded = e.response.data.length, + r.total = r.loaded, + r.complete = !0, + Bi({ + status: n, + data: e, + stats: r + })) : 300 === n || 302 === n || 303 === n || 305 === n ? this.redirectRequest(e.response.uri, t, i, r) : (this.logger.warn(kc, `unable to load custom url > uri=${oe(e.response.uri)}, status=${n}`), + Ui(new tu("Unable to load custom url",n))) + } + redirectRequest(e, t, i, n) { + var {maxLoadTimeMs: r, maxTimeToFirstByteMs: s} = i + , r = r - (performance.now() - n.trequest) + , s = 0 < t.extendMaxTTFB ? t.extendMaxTTFB : s - (performance.now() - n.trequest) + , i = Object.assign(Object.assign({}, i), { + maxLoadTimeMs: r, + maxTimeToFirstByteMs: s + }) + , e = Object.assign(Object.assign({}, t), { + url: e + }); + return r <= 0 || s <= 0 ? Ui(new or) : Oc(e, i).pipe(ur(([e,t])=>{ + var {responseURL: i, status: r} = e + , i = i || "" + , i = { + uri: i, + response: { + status: r, + uri: i, + data: e.response + } + }; + return n.loaded = n.total = t.loaded, + n.tload = performance.now(), + n.complete = !0, + { + status: e.status, + data: i, + stats: n + } + } + )) + } + } + let Dc; + function Mc(e) { + return Dc || (e = e || (Tc = Tc || new Sc(bc), + Tc), + Dc = new Cc(e)), + Dc + } + function Pc(e, t) { + const i = Object.assign(Object.assign({}, e), { + method: "GET", + responseType: "arraybuffer" + }) + , r = Mc(); + return ml(i.url) ? r.load(i, t).pipe(ur(e=>[e.data.response.data, e.stats, i.serverInstanceInfo])) : Oc(i, t).pipe(ur(([e,t])=>[e.response, t, i.serverInstanceInfo])) + } + function xc(e, t) { + return !e.url || ml(e.url) ? t.customURL : t.default + } + function Rc(e, t) { + return e instanceof iu ? e.isTimeout ? t.timeoutRetry : t.errorRetry : null + } + function Lc(e) { + var t = e.type + , i = e.liveOrEvent; + let r = "VOD"; + "EVENT" === t && i ? r = "EVENT" : t && 0 !== t.length && "LIVE" !== t || !i || (r = "LIVE"), + e.type !== r && (e.type = r) + } + const _c = { + id: "playready", + systemStringPrefix: "com.microsoft.playready", + keyFormatString: "com.microsoft.playready", + securityLevels: { + SL2000: 0, + SL3000: 1 + } + } + , Nc = { + id: "widevine", + systemStringPrefix: "com.widevine.alpha", + keyFormatString: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed", + securityLevels: { + WIDEVINE_SOFTWARE: 0, + WIDEVINE_HARDWARE: 1 + } + }; + function Fc(e) { + return e.replace(/\+/g, "-").replace(/\//g, "_").replace(/\=+$/, "") + } + class Bc { + static strToBase64Encode(e) { + return btoa(e) + } + static base64DecodeToStr(e) { + return atob(e) + } + static base64Encode(e) { + return btoa(String.fromCharCode(...e)) + } + static base64UrlEncode(e) { + return Fc(Bc.base64Encode(e)) + } + static base64Decode(e) { + return Uint8Array.from(atob(e), e=>e.charCodeAt(0)) + } + } + class Uc { + static strToBase64Encode(e) { + return d.Buffer.from(e).toString("base64") + } + static base64DecodeToStr(e) { + return d.Buffer.from(e, "base64").toString() + } + static base64Encode(e) { + return d.Buffer.from(e).toString("base64") + } + static base64UrlEncode(e) { + return Fc(Uc.base64Encode(e)) + } + static base64Decode(e) { + e = d.Buffer.from(e, "base64"); + return new Uint8Array(e.buffer,e.byteOffset,e.byteLength) + } + } + var $c, Vc = void 0 !== d.Buffer ? Uc : Bc; + const Kc = { + avc1: "video/mp4", + avc3: "video/mp4", + dvav: "video/mp4", + dva1: "video/mp4", + hev1: "video/mp4", + hvc1: "video/mp4", + dvh1: "video/mp4", + dvhe: "video/mp4" + } + , Hc = { + mp4a: "audio/mp4", + "ac-3": "audio/mp4", + "ec-3": "audio/mp4" + }; + function jc(e) { + const t = O.strToUtf8array(e).subarray(0, 16) + , i = new Uint8Array(16); + return i.set(t, 16 - t.length), + i + } + const qc = { + getCapabilities: function(e, t) { + const i = { + videoCapabilities: [], + audioCapabilities: [] + }; + return e && e.forEach(e=>{ + var t = e.split(".")[0].trim(); + t in Kc && i.videoCapabilities.push({ + contentType: Kc[t] + ";codecs=" + e, + robustness: "" + }) + } + ), + t && t.forEach(e=>{ + var t = e.split(".")[0].trim(); + t in Hc && i.audioCapabilities.push({ + contentType: Hc[t] + ";codecs=" + e, + robustness: "" + }) + } + ), + i + }, + changeEndianness: function(e) { + function t(e, t, i) { + var r = e[t]; + e[t] = e[i], + e[i] = r + } + t(e, 0, 3), + t(e, 1, 2), + t(e, 4, 5), + t(e, 6, 7) + }, + getKeyIdBytes: jc, + convertDataUriToArrayBytes: function(e) { + const t = e.split(":"); + let i = null; + if ("data" === t[0] && 2 === t.length) { + const e = t[1].split(";") + , r = e[e.length - 1].split(","); + if (2 === r.length) { + const t = "base64" === r[0] + , n = r[1]; + i = t ? (e.splice(-1, 1), + Vc.base64Decode(n)) : jc(n) + } + } + return i + }, + makeKeyIdsInitData: function(e) { + e = { + kids: e.map(Vc.base64UrlEncode) + }; + return O.strToUtf8array(JSON.stringify(e)) + }, + parsePSSHList: function(e) { + const i = new DataView(e); + let r = 0; + const n = {}; + for (; r < i.buffer.byteLength; ) { + const e = r + , t = i.getUint32(r); + r += 4; + var s = e + t; + if (1886614376 === i.getUint32(r)) { + switch (r += 4, + i.getUint8(r)) { + case 0: + case 1: + r += 1; + break; + default: + r = s + } + r += 3; + let t = ""; + for (let e = 0; e < 16; ++e, + ++r) + switch (t += i.getUint8(r).toString(16), + e) { + case 4: + case 6: + case 8: + case 10: + t += "-" + } + r += 4, + n[t] = i.buffer.slice(e, s) + } else + r = s + } + return n + } + }; + let Qc = {}; + class Gc { + constructor(e, t, i, r, n) { + if (this.method = e, + this.uri = t, + this.iv = i, + this.format = r, + this.formatversions = n, + this.isEncrypted = this.method && "NONE" !== this.method, + this.formatversions && 0 !== this.formatversions.length || (this.formatversions = [1]), + this.key = void 0, + this.keyId = void 0, + this.isEncrypted) { + const a = qc.convertDataUriToArrayBytes(this.uri); + if (a) + switch (r) { + case _c.keyFormatString: + { + this.pssh = a; + const e = new Uint16Array(a.buffer,a.byteOffset,a.byteLength / 2) + , t = String.fromCharCode.apply(null, Array.from(e)) + , i = t.substring(t.indexOf("<"), t.length) + , r = (new DOMParser).parseFromString(i, "text/xml").getElementsByTagName("KID")[0]; + if (r) { + var s = null; + if (s = r.childNodes[0] ? r.childNodes[0].nodeValue : r.getAttribute("VALUE")) { + const t = Vc.base64Decode(s).subarray(0, 16); + qc.changeEndianness(t), + this.keyId = t + } + } + break + } + case Nc.keyFormatString: + this.pssh = a, + 22 <= a.length && (this.keyId = a.subarray(a.length - 22, a.length - 6)); + break; + default: + { + let e = a.subarray(0, 16); + if (16 !== e.length) { + const t = new Uint8Array(16); + t.set(e, 16 - e.length), + e = t + } + this.keyId = e; + break + } + } + if (!this.keyId || 16 !== this.keyId.byteLength) { + let e = Qc[this.uri]; + if (!e) { + const t = Object.keys(Qc).length % Number.MAX_SAFE_INTEGER; + e = new Uint8Array(16), + new DataView(e.buffer,12,4).setUint32(0, t), + Qc[this.uri] = e + } + this.keyId = e + } + } + } + get keyTagInfo() { + var {method: e, isEncrypted: t, uri: i, iv: r, keyId: n, key: s, format: a, formatversions: o} = this; + return { + method: e, + isEncrypted: t, + uri: i, + iv: r, + keyId: n, + key: s, + format: a, + formatversions: o + } + } + static clearKeyUriToKeyIdMap() { + Qc = {} + } + } + (gc = $c = $c || {}).NONE = "NONE", + gc.GET_REQUEST_INFO = "GET_REQUEST_INFO", + gc.GET_CHALLENGE = "GET_CHALLENGE", + gc.GET_KEY_RESPONSE = "GET_KEY_RESPONSE", + gc.PROCESS_LICENSE = "PROCESS_LICENSE"; + class Wc { + constructor(e, t, i, r) { + this.session = e, + this.onkeystatuseschange = t, + this.onkeymessage = i, + this.logger = r, + this.isClosing$ = new gi(!1), + this.closed$ = new gi(!1); + const n = wc(this.session); + n.listen("keystatuseschange", this.isClosing$.pipe(an(e=>!0 === e)), this.onkeystatuseschange), + n.listen("message", this.closed$.pipe(an(e=>!0 === e)), this.onkeymessage) + } + get isClosing() { + return this.isClosing$.value + } + get isClosed() { + return this.closed$.value + } + destroy() { + this.isClosing$.next(!0); + const e = this.session; + return Lr(e.remove().catch(e=>{} + ).then(()=>e.close()).catch(e=>{} + )).pipe(Ja(()=>{ + this.isClosing$.next(!1), + this.closed$.next(!0) + } + ), $s(()=>{ + this.isClosing$.next(!1), + this.closed$.next(!0) + } + )) + } + } + class zc { + constructor(e, t=null) { + this.decryptdata = e, + this._requestState$ = new gi($c.NONE), + this.destroy$ = new zt, + this.currentObservable = null, + this.session = null, + this.oldSessions = [], + this.session = t + } + get requestState() { + return this._requestState$.value + } + get onKeyRequestState$() { + return this._requestState$ + } + destroy() { + this.destroy$.next() + } + abort() { + var e; + this.requestState !== $c.NONE && (e = new uu("Aborted",this.decryptdata.uri,0,$.KeySystemAbort,!0,Xl.Abort), + this.error(e)) + } + setKeyRequestState(e) { + if (this.currentObservable) { + const t = new uu(`Unexpected state transition ${this.requestState}->${e}`,this.decryptdata.uri,0,$.KeySystemUnexpectedStateTransition,!0,Xl.InvalidState); + this.error(t) + } + this._requestState$.next(e); + const t = new Ji; + return e === $c.NONE ? (t.complete(), + this.currentObservable = null) : this.currentObservable = t, + t + } + resolveState(e, t) { + if (this.currentObservable) + if (e === this.requestState) + if (t instanceof Error) + this.error(t); + else { + const e = this.currentObservable; + this.currentObservable = null, + e.next(t), + e.complete() + } + else { + const t = new uu(`Unexpected state ${this.requestState} != ${e}`,this.decryptdata.uri,0,$.KeySystemUnexpectedState,!0,Xl.InvalidState); + this.error(t) + } + } + error(e) { + if (this.currentObservable) { + const t = this.currentObservable; + this.currentObservable = null, + t.error(e) + } + this.setKeyRequestState($c.NONE) + } + } + function Xc(e) { + return `uri=${oe(e.uri)} keyId=${je(e.keyId)}` + } + class Yc { + constructor(e, t, i, r, n, s, a) { + this.mediaKeys = e, + this.systemString = t, + this.config = i, + this.eventEmitter = r, + this.useSingleKeySession = n, + this.sessionHandler = s, + this.logger = a, + this.destroy$ = new zt, + this.setCert = !1, + this.certificate$ = new gi(null), + this._keyStatusChange$ = new zt, + this.shouldDestroyMediaKeys = !1, + this.itemId = "", + this.sessions = [], + this.keyIdToKeyInfo = {}, + this.keyUriToKeyInfo = {}, + this.sessionIdToKeyUri = {}, + this.onkeystatuseschange = this.handleKeyStatusesChange.bind(this), + this.onkeymessage = this.handleKeyMessage.bind(this) + } + get keyStatusChange$() { + return this._keyStatusChange$ + } + destroy() { + this.isDestroying = !0, + this.destroy$.next(); + for (const e of Object.values(this.keyIdToKeyInfo)) + this._abortKeyRequest(e); + const e = this.sessions.map(e=>e.destroy()) + , t = tn(()=>0 === e.length, Ul, Jr(e)).pipe(Js(void 0), $s(()=>{ + this.mediaKeys = void 0, + this.keyIdToKeyInfo = {}, + this.keyUriToKeyInfo = {}, + this.sessionIdToKeyUri = {} + } + )); + return Gc.clearKeyUriToKeyIdMap(), + t + } + setServerCertificate(e=null) { + return this.needsCert ? (e && this.certificate$.next(e), + $l(this.certificate$, e=>null != e).pipe(vo(1e4)).pipe(Ra(e=>this.setCert ? Bi(!0) : !this.setCertSubject || this.setCertSubject.isStopped ? (this.setCertSubject = new Ji, + Lr(this.mediaKeys.setServerCertificate(e)).pipe(Ja(e=>{ + e = void 0 === e || e; + this.setCert = e, + this.setCertSubject.next(e), + this.setCertSubject.complete() + } + ), Un(e=>(this.setCert = !1, + this.setCertSubject.error(e), + Ul)), Ra(()=>this.setCertSubject))) : this.setCertSubject), Un(e=>{ + throw e + } + ))) : Bi(!0) + } + ensureKeyContext(e) { + var t = e.uri; + this.keyUriToKeyInfo[t] || (this.keyUriToKeyInfo[t] = new zc(e)); + const i = this.keyUriToKeyInfo[t]; + if (i.session) + return i; + if (this.useSingleKeySession && 0 < this.sessions.length) + return i.session = this.sessions[0].session, + i; + t = this.mediaKeys.createSession(); + return t && this.sessions.push(new Wc(t,this.onkeystatuseschange,this.onkeymessage,this.logger)), + i.session = t, + i + } + startKeyRequest(t) { + const i = t.uri + , r = this.ensureKeyContext(t); + if (!r.session) + return Ui(new cu("Could not create key session",t.uri,0,$.KeySystemFailedToCreateSession,this.systemString)); + var e = O.utf8arrayToStr(t.keyId); + return this.keyIdToKeyInfo[e] = r, + Jr([this.getKeyRequestInfo(r), this.setServerCertificate()]).pipe(ur(e=>e[0]), Ra(e=>{ + var t; + return null === (t = this.sessionHandler) || void 0 === t || t.licenseChallengeSubmitted({ + keyuri: i, + keyFormat: this.systemString + }), + this.generateLicenseChallenge(r, e).pipe(Un(e=>{ + var t; + throw null === (t = this.sessionHandler) || void 0 === t || t.licenseChallengeError({ + keyuri: i + }), + e + } + )) + } + ), Ra(e=>{ + var t; + return null === (t = this.sessionHandler) || void 0 === t || t.licenseChallengeCreated({ + keyuri: i, + cdmVersion: this.cdmVersion + }), + this.getKeyRequestResponse(r, e) + } + ), Ra(e=>{ + var t; + return null === (t = this.sessionHandler) || void 0 === t || t.licenseResponseSubmitted({ + keyuri: i + }), + this.handleParsedKeyResponse(r, e).pipe(Un(e=>{ + var t; + throw null === (t = this.sessionHandler) || void 0 === t || t.licenseResponseError({ + keyuri: i + }), + e + } + )) + } + ), ur(()=>{ + var e; + return null === (e = this.sessionHandler) || void 0 === e || e.licenseResponseProcessed({ + keyuri: i + }), + r.setKeyRequestState($c.NONE), + this.removeSessions(r.decryptdata, !1).subscribe(), + t + } + ), Un(e=>{ + throw this.handleKeyExchangeError(r, e), + e + } + ), $s(()=>{ + this._abortKeyRequest(r) + } + )) + } + _abortKeyRequest(e) { + var t, i; + e && (i = e.decryptdata.uri, + O.utf8arrayToStr(e.decryptdata.keyId), + e.requestState !== $c.NONE && (null === (t = this.sessionHandler) || void 0 === t || t.keyAborted({ + keyuri: i + })), + e.abort()) + } + handleKeyExchangeError(e, t) { + e.error(t), + O.utf8arrayToStr(e.decryptdata.keyId) + } + updateItemId(e) { + this.itemId = e + } + removeKey(e) { + return this.removeKeyInternal(e) + } + removeKeyInternal(e) { + const t = this.keyUriToKeyInfo[e.uri]; + if (t && t.session) { + var i = t.session; + t.abort(), + t.destroy(); + var r = O.utf8arrayToStr(e.keyId); + return this.keyIdToKeyInfo[r] = void 0, + this.keyUriToKeyInfo[e.uri] = void 0, + this.removeSession(i) + } + } + removeSessions(e, t) { + const i = this.keyUriToKeyInfo[e.uri]; + if (i) { + const r = i.oldSessions.map(e=>this.removeSession(e)); + return i.oldSessions = [], + tn(()=>0 === r.length, Ul, Jr(r)).pipe(Ra(()=>t ? this.removeKeyInternal(e) : Ul)) + } + return Ul + } + removeSession(t) { + const e = this.sessions.findIndex(e=>e.session === t) + , i = this.sessions[e]; + return -1 < e && this.sessions.splice(e, 1), + this.sessionIdToKeyUri[t.sessionId] = void 0, + i ? i.destroy() : Ul + } + getKeyRequestInfo(e) { + var t = e.decryptdata + , i = t.uri + , e = e.setKeyRequestState($c.GET_REQUEST_INFO); + return this.eventEmitter.trigger(x.KEY_REQUEST_STARTED, { + keyuri: i, + decryptdata: t, + timestamp: Date.now() + }), + e + } + setKeyRequestInfo(e, t) { + const i = this.keyUriToKeyInfo[e]; + i && i.resolveState($c.GET_REQUEST_INFO, t) + } + sanitizeRequest(e) { + return e + } + generateLicenseChallengeInternal(t, e, i) { + const r = t.decryptdata + , n = t.session + , s = r.uri + , a = r.keyId; + let o; + var d = t.setKeyRequestState($c.GET_CHALLENGE); + if (n.generateRequestPromise) + o = Lr(n.generateRequestPromise).pipe(Ra(()=>this.generateRequestInitialized(t, "usable" === i))); + else { + const i = this.generateInitData(a, r, e); + n.generateRequestPromise = n.generateRequest(i.initDataType, i.initData), + o = Lr(n.generateRequestPromise).pipe(Ja(()=>{ + this.sessionIdToKeyUri[n.sessionId] = s + } + ), Un(e=>{ + throw new cu(e.message,t.decryptdata.uri,0,$.KeySystemFailedToGenerateLicenseRequest,this.systemString) + } + )) + } + return Jr([d, o]).pipe(ur(e=>new Uint8Array(e[0]))) + } + generateLicenseChallenge(e, t) { + const i = e.decryptdata + , r = e.session + , n = i.uri + , s = i.keyId; + let a, o; + if (O.utf8arrayToStr(i.keyId), + e.licenseChallenge && e.resolveState($c.GET_CHALLENGE, e.licenseChallenge), + t = this.sanitizeRequest(t), + e.requestInfo = t, + this.sessionId = this.sessionId || t && t.sessionId || this.itemId, + this.systemString === _c.systemStringPrefix) { + const e = new Uint8Array(s); + qc.changeEndianness(e), + a = r.keyStatuses.get(e) + } else + a = r.keyStatuses.get(s); + switch (a) { + case "status-pending": + case "usable": + case "expired": + case void 0: + o = this.generateLicenseChallengeInternal(e, t, a); + break; + default: + o = Ui(new cu(`Bad internal state state=${a}`,n,0,$.KeySystemUnexpectedState,this.systemString)) + } + return o + } + setParsedResponse(e, t) { + this.keyUriToKeyInfo[e].resolveState($c.GET_KEY_RESPONSE, t) + } + handleKeyStatusesChange(e) { + e.target.keyStatuses.forEach((e,t,i)=>{ + t = new Uint8Array(t); + this.systemString === _c.systemStringPrefix && qc.changeEndianness(t); + t = O.utf8arrayToStr(t), + t = this.keyIdToKeyInfo[t]; + this.handleKeyStatusForKey(e, t) + } + ) + } + handleKeyStatusForKey(e, t) { + if (t) { + var i = t.decryptdata + , r = i.uri; + switch (e) { + case "internal-error": + this.logger.error(`${this.systemString} internal-error for key ${Xc(i)}`), + this._signalError(t, new uu("Got internal error from key system",r,0,$.KeySystemInternalError,!1,Xl.InternalError)); + break; + case "usable": + t.requestState === $c.PROCESS_LICENSE && t.resolveState($c.PROCESS_LICENSE, void 0); + break; + case "output-restricted": + this.logger.warn(`${this.systemString} output-restricted for key ${Xc(i)}`), + t.session && this.removeSession(t.session).pipe($a(this.destroy$)).subscribe(), + this._signalError(t, new uu("output-restricted",r,0,$.KeySystemOutputRestricted,!1,Xl.OutputRestricted)) + } + } + } + _scheduleRenewal(e, t) { + vn(t).pipe(Ja(()=>this._signalRenewal(e)), $a(hn(e.destroy$, this.destroy$, $l(e.onKeyRequestState$, e=>e === $c.GET_REQUEST_INFO)))).subscribe() + } + _signalRenewal(e) { + this._keyStatusChange$.next({ + decryptdata: e.decryptdata, + status: "needs-renewal" + }) + } + _signalError(e, t) { + this._keyStatusChange$.next({ + decryptdata: e.decryptdata, + status: "error", + error: t + }), + e.error(t) + } + } + const Jc = "org.w3.clearkey" + , Zc = { + id: "clearkey", + systemStringPrefix: Jc, + keyFormatString: Jc, + securityLevels: { + NONE: 0 + } + } + , eh = ["clearkey", "fairplaystreaming", "playready", "widevine"] + , th = { + initDataTypes: ["keyids", "cenc"] + }; + var ih, gr = class extends Yc { + constructor(e, t, i, r, n, s) { + super(e, t, i, r, !1, n, s) + } + static get requestAccessConfig() { + return th + } + get needsCert() { + return !1 + } + getKeyRequestResponse(e, t) { + return Pc({ + url: e.decryptdata.uri, + xhrSetup: this.config.xhrSetup + }, { + maxLoadTimeMs: 0, + maxTimeToFirstByteMs: 0, + autoRetry: !1, + timeoutRetry: null, + errorRetry: null + }).pipe(ur(([e])=>{ + e = new Uint8Array(e); + return { + response: this.parseResponse(t, e) + } + } + )) + } + parseResponse(e, t) { + t = { + kty: "oct", + kid: Vc.base64UrlEncode(e), + k: Vc.base64UrlEncode(t) + }; + return O.strToUtf8array(JSON.stringify({ + keys: [t] + })) + } + handleParsedKeyResponse(i, e) { + e = e.response; + return Jr([i.setKeyRequestState($c.PROCESS_LICENSE), Lr(i.session.update(e)).pipe(Ja(()=>{ + var e = i.decryptdata.keyId + , e = i.session.keyStatuses.get(e); + this.handleKeyStatusForKey(e, i) + } + ), Un(e=>{ + var t = { + code: e.code, + text: "Failed to update with key response" + }; + throw new cu(e.message,i.decryptdata.uri,e.code,t,this.systemString) + } + ))]).pipe(Js(void 0)) + } + generateInitData(e) { + return { + initData: qc.makeKeyIdsInitData([e]), + initDataType: "keyids" + } + } + generateRequestInitialized() { + return Ul + } + sanitizeRequest(e) { + return e + } + handleKeyMessage(e) { + if (!this.isDestroying && "license-request" === e.messageType) { + e = new Uint8Array(e.message), + e = JSON.parse(O.utf8arrayToStr(e).trim()); + if (1 === e.kids.length) { + const t = Vc.base64Decode(e.kids[0]) + , i = O.utf8arrayToStr(t) + , r = this.keyIdToKeyInfo[i]; + r && r.resolveState($c.GET_CHALLENGE, t) + } + } + } + } + ; + const rh = { + initDataTypes: ["cenc"] + } + , nh = new Uint8Array([148, 206, 134, 251, 7, 255, 79, 67, 173, 184, 147, 210, 250, 150, 140, 162]); + (mu = ih = ih || {})[mu.CENC = 1667591779] = "CENC", + mu[mu.CBCS = 1667392371] = "CBCS"; + class sh extends Yc { + constructor(e, t, i, r, n, s, a) { + super(e, t, i, r, n, s, a), + this._hasSetRenewal = !1 + } + static get systemId() { + return nh + } + static get requestAccessConfig() { + return rh + } + get needsCert() { + return !0 + } + sanitizeRequest(e) { + return { + assetId: e && e.assetId ? new Uint8Array(e.assetId) : void 0, + ssc: e && e.ssc ? new Uint8Array(e.ssc) : void 0, + sessionId: e && e.sessionId ? e.sessionId : void 0 + } + } + _scheduleRenewal(e, t) { + this.useSingleKeySession ? this._hasSetRenewal || (this._hasSetRenewal = !0, + vn(t).pipe(Ja(()=>{ + var e = Object.values(this.keyUriToKeyInfo)[0]; + this._signalRenewal(e) + } + ), $s(()=>{ + this._hasSetRenewal = !1 + } + ), $a(this.destroy$)).subscribe()) : super._scheduleRenewal(e, t) + } + handleParsedKeyResponse(t, e) { + var i = t.decryptdata.uri + , r = e.statusCode + , n = e.ckc && 0 !== e.ckc.byteLength ? e.ckc : e.license && 0 !== e.license.byteLength ? e.license : void 0; + if (0 === r && !n) + return Ui(new uu("License request resulted in HTTP Error",i,r,{ + code: r, + text: "HTTP Error" + },!0,Xl.HttpError)); + if (0 !== r) + return Ui(new uu("License server responded with error",i,r,{ + code: r, + text: "Server Error" + },!1,Xl.LicenseServerError)); + if (!n) + return Ui(new uu("License server responded with invalid license",i,r,{ + code: r, + text: "Invalid license" + },!1,Xl.LicenseServerError)); + const s = e.renewalDate + , a = new Date + , o = s > a ? s.getTime() - a.getTime() : 0; + 0 < o && this._scheduleRenewal(t, o); + const d = this.makeProcessLicenseRequestMessage(t, n, o) + , l = t.session + , u = Lr(l.update(d)).pipe(Ja(()=>{ + var e = t.decryptdata.keyId + , e = l.keyStatuses.get(e); + this.handleKeyStatusForKey(e, t) + } + ), Un(e=>{ + throw new cu(e.message,t.decryptdata.uri,0,$.KeySystemFailedToUpdateSession,this.systemString) + } + )); + return Jr([t.setKeyRequestState($c.PROCESS_LICENSE), u]).pipe(Js(void 0)) + } + makeKeyRequests(e) { + const t = []; + for (const i of e) { + const e = i.decryptdata + , r = i.requestInfo + , n = e.keyId; + t.push({ + keyId: n, + assetId: r ? r.assetId : void 0, + ssc: r ? r.ssc : void 0, + versionList: e.formatversions + }) + } + return t + } + getSchemeAndFlags(e) { + return { + scheme: "ISO-23001-7" === e.method ? ih.CENC : ih.CBCS, + flags: 0 + } + } + generateInitData(e, t, i) { + var {scheme: r, flags: n} = this.getSchemeAndFlags(t) + , i = this.makeKeyRequests([{ + decryptdata: t, + requestInfo: i + }]); + return { + initData: this.makeFpsKeySystemInitData(r, n, i), + initDataType: "cenc" + } + } + generateRequestInitialized(t, e) { + Ql.tag(`[Keys] challenge create start uri=${oe(t.decryptdata.uri)} versions=${JSON.stringify(t.decryptdata.formatversions)}`); + e = this.makeKeyRequestMessage(t, e); + return e ? Lr(t.session.update(e)).pipe(Ja(()=>{ + t.requestInfo = void 0 + } + ), Un(e=>{ + throw Ql.tag(`[Keys] ${this.systemString} FAIL: generateRequestInitialized keyuri=${oe(t.decryptdata.uri)} message=${e.message}`), + new cu(e.message,t.decryptdata.uri,0,$.KeySystemFailedToGenerateLicenseRenewal,this.systemString) + } + )) : Ui(new uu("Unable to generate request using existing keySession",t.decryptdata.uri,0,$.KeySystemFailedToGenerateLicenseRequest,!0,Xl.InvalidState)) + } + getKeyRequestResponse(e, t) { + var i = e.decryptdata.uri + , e = e.setKeyRequestState($c.GET_KEY_RESPONSE); + return this.eventEmitter.trigger(x.LICENSE_CHALLENGE_CREATED, { + keyuri: i, + licenseChallenge: t, + keysystem: this.systemString + }), + e + } + resolveSPCPromise(e, t) { + e.resolveState($c.GET_CHALLENGE, t) + } + } + const ah = {} + , oh = 1919710053; + function dh(e, t, i) { + if (!(i + 4 > e.byteLength)) { + t = t.getUint32(i); + if (!((i += 4) + t > e.byteLength)) { + e = e.slice(i, i + t); + return { + pos: i += t, + data: e + } + } + } + } + function lh(t) { + const i = {} + , r = new DataView(t.buffer); + let n = 4; + const s = r.getUint32(n); + n += 4; + for (let e = 0; e < s && n < t.byteLength && !(n + 16 > t.byteLength); ++e) { + const s = t.slice(n, n + 16); + if (n += 16, + n + 4 > t.byteLength) + break; + var a = dh(t, r, n); + if (!a) + break; + n = a.pos, + i[O.utf8arrayToStr(s)] = a.data + } + return i + } + function uh(e, t, i, r) { + var n = r ? r.byteLength : 0; + return t.setUint32(i, n), + n && e.set(r, i + 4), + i + (4 + n) + } + function ch(e) { + let t = 4; + for (const i of e) + t += 28 + (i.assetId ? i.assetId.byteLength : 0) + (i.ssc ? i.ssc.byteLength : 0) + (i.versionList ? 4 * i.versionList.length : 0); + return t + } + function hh(e, t, i, r) { + t.setUint32(i, r.length), + i += 4; + for (const n of r) + if (e.set(n.keyId, i), + i = uh(e, t, i += 16, n.assetId), + i = uh(e, t, i, n.ssc), + t.setUint32(i, n.versionList ? n.versionList.length : 0), + i += 4, + n.versionList) + for (const e of n.versionList) + t.setUint32(i, e), + i += 4; + return i + } + class ph extends sh { + constructor(e, t, i, r, n, s) { + super(e, t, i, r, void 0 === i.useMultipleKeySessions || !i.useMultipleKeySessions, n, s) + } + makeProcessLicenseRequestMessage(e, t, i) { + t = new Uint8Array(t); + return function(e) { + let t = 0; + for (const i of e) + t += 24 + i.ckc.byteLength; + let i = 0; + const r = new Uint8Array(8 + t) + , n = new DataView(r.buffer); + n.setUint32(0, 1667982195), + n.setUint32(4, e.length), + i += 8; + for (const t of e) + r.set(t.keyId, i), + i += 16, + n.setUint32(i, t.expirySec), + i += 4, + i = uh(r, n, i, t.ckc); + return r + }([{ + keyId: e.decryptdata.keyId, + expirySec: i / 1e3, + ckc: t + }]) + } + makeFpsKeySystemInitData(e, t, i) { + i = function(e, t, i) { + var r = ch(i); + const n = new Uint8Array(8 + r) + , s = new DataView(n.buffer); + return s.setUint32(0, e), + s.setUint32(4, 1 << 24 | 16777215 & t), + hh(n, s, 8, i), + n + }(e, t, i); + return me.pssh(ph.systemId, [], i) + } + makeKeyRequestMessage(e) { + return function(e) { + var t = ch(e); + const i = new Uint8Array(4 + t) + , r = new DataView(i.buffer); + return r.setUint32(0, 1668442994), + hh(i, r, 4, e), + i + }([{ + keyId: e.decryptdata.keyId, + assetId: e.requestInfo ? e.requestInfo.assetId : void 0, + ssc: e.requestInfo ? e.requestInfo.ssc : void 0, + versionList: e.decryptdata.formatversions + }]) + } + handleKeyMessage(e) { + if (e.message.byteLength < 4) + this.logger.warn("Unexpected message"); + else { + const t = new Uint8Array(e.message) + , i = new DataView(e.message) + , r = i.getUint32(0); + if (this.isDestroying && r !== oh) + this.logger.warn(`In the middle of destroying, ignore command: ${r.toString(16)}`); + else + switch (r) { + case 1667592820: + this.logger.warn("Certificate not set!"); + break; + case 1919837559: + { + const e = lh(t); + for (const t in e) + if (Object.prototype.hasOwnProperty.call(e, t)) { + const e = this.keyIdToKeyInfo[t]; + this._signalRenewal(e) + } + break + } + case 1936745331: + { + const e = lh(t); + for (const t in e) + if (Object.prototype.hasOwnProperty.call(e, t)) { + const i = this.keyIdToKeyInfo[t] + , r = e[t]; + this.resolveSPCPromise(i, r) + } + break + } + case oh: + this._handleLicenseRelease(t); + break; + case 1667525993: + { + const e = dh(t, i, 4); + e && (this.cdmVersion = O.utf8arrayToStr(e.data)); + break + } + default: + this.logger.warn(`Unrecognized command:'0x${r.toString(16)}'`) + } + } + } + _handleLicenseRelease(e) { + const t = {} + , i = new DataView(e.buffer); + switch (i.getUint32(4)) { + case 1936946288: + ah, + 0, + t[ah.SessionId] = this.sessionId; + var r; + if (e.byteLength < 12) + break; + t[ah.APIProvider] = i.getUint32(8) === ih.CENC ? "EC396D13-FB13-4993-9D0D-71518ACF3D6F" : "F19BF03B-7470-41A4-9655-86D078307D59", + 0; + var n = dh(e, i, 12); + if (!n) + break; + if (r = n.pos, + t[ah.MovieID] = O.utf8arrayToStr(n.data), + !(n = dh(e, i, r))) + break; + if (r = n.pos, + t[ah.SecureStopSPC] = n.data, + !(n = dh(e, i, r))) + break; + n.pos, + t[ah.SessionLifespanSPC] = n.data + } + this.eventEmitter.trigger(x.LICENSE_RELEASED, { + keysystem: this.systemString, + itemId: this.itemId, + releaseRecord: t + }) + } + } + yc = ph; + const fh = { + fpsd: O.strToUtf8array("fpsd"), + fpsi: O.strToUtf8array("fpsi"), + fpsk: O.strToUtf8array("fpsk"), + fkri: O.strToUtf8array("fkri"), + fkai: O.strToUtf8array("fkai"), + fkcx: O.strToUtf8array("fkcx"), + fkvl: O.strToUtf8array("fkvl") + }; + t = class extends sh { + constructor(e, t, i, r, n, s) { + super(e, t, i, r, !1, n, s), + this.sessions = [], + this.keyIdToKeyInfo = {}, + this.keyUriToKeyInfo = {}, + this.sessionIdToKeyUri = {} + } + static get needsCert() { + return !0 + } + handleKeyExchangeError(e, t) { + this.removeKey(e.decryptdata).subscribe(), + super.handleKeyExchangeError(e, t) + } + _abortKeyRequest(e) { + return !this.isDestroying && e && e.requestState !== $c.NONE && this.removeKey(e.decryptdata).subscribe(), + super._abortKeyRequest(e) + } + makeFpsKeySystemInitData(e, t, i) { + const r = [fh.fpsd, (n = e, + e = t, + t = new Uint8Array(4), + me.set32(n, t, 0), + me.box(fh.fpsi, new Uint8Array([0, e >> 16 & 255, e >> 8 & 255, 255 & e]), t))]; + var n; + for (const s of i) + r.push(function(t, e, i, r) { + const n = [fh.fpsk] + , s = me.box(fh.fkri, new Uint8Array([0, 0, 0, 0]), t); + if (n.push(s), + e && e.byteLength && n.push(me.box(fh.fkai, e)), + i && i.byteLength && n.push(me.box(fh.fkcx, i)), + r && r.length) { + const t = new Uint8Array(4 * r.length); + let e = 0; + for (const i of r) + me.set32(i, t, e), + e += 4; + n.push(me.box(fh.fkvl, t)) + } + return me.box.apply(null, n) + }(s.keyId, s.assetId, s.ssc, s.versionList)); + i = me.box.apply(null, r); + return me.pssh(sh.systemId, null, i) + } + makeKeyRequestMessage(e, t) { + if (t) + return O.strToUtf8array("renew") + } + makeProcessLicenseRequestMessage(e, t, i) { + t = JSON.stringify([{ + keyID: Vc.base64Encode(e.decryptdata.keyId), + payload: Vc.base64Encode(new Uint8Array(t)) + }]); + return O.strToUtf8array(t) + } + handleKeyMessage(e) { + const t = e.target + , i = t.sessionId + , r = e.messageType + , n = this.sessionIdToKeyUri[i]; + let s; + if (n) + s = this.keyUriToKeyInfo[n]; + else + for (const e of Object.values(this.keyUriToKeyInfo)) + e && e.session === t && (s = e); + if (s) + switch (r) { + case "license-request": + { + const t = new Uint8Array(e.message) + , i = O.utf8arrayToStr(t); + try { + JSON.parse(i).forEach(e=>{ + var t = Vc.base64DecodeToStr(e.keyID) + , e = Vc.base64Decode(e.payload) + , t = this.keyIdToKeyInfo[t]; + this.resolveSPCPromise(t, e) + } + ) + } catch (e) { + this.logger.warn("[Keys] got unexpected license-request format"), + this.resolveSPCPromise(s, t) + } + break + } + case "license-renewal": + { + const t = new Uint8Array(e.message); + this.resolveSPCPromise(s, t); + break + } + case "license-release": + this._handleLicenseRelease(t); + break; + default: + this.logger.warn(`[Keys] Unexpected messageType ${r}`) + } + else + this.logger.warn("[Keys] No key associated with session") + } + _handleLicenseRelease(e) { + e.update(O.strToUtf8array("acknowledged")).catch(e=>{ + this.logger.error(`Promise error: ${e.message}`) + } + ) + } + } + ; + const mh = { + initDataTypes: ["cenc"] + } + , gh = new Uint8Array([154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149]); + class yh extends Yc { + constructor(e, t, i, r, n, s) { + super(e, t, i, r, !1, n, s), + this.shouldDestroyMediaKeys = !0 + } + static get systemId() { + return gh + } + static get requestAccessConfig() { + return mh + } + get needsCert() { + return !1 + } + generateInitData(e, t) { + t = t.pssh; + return { + initData: me.pssh(yh.systemId, [], t), + initDataType: "cenc" + } + } + removeKey(e) { + return super.removeSessions(e, !0) + } + ensureKeyContext(e) { + const t = e.uri + , i = this.keyUriToKeyInfo[t]; + return null != i && i.session && (i.oldSessions.push(i.session), + i.session = null), + super.ensureKeyContext(e) + } + getKeyRequestResponse(e, t) { + var i = e.decryptdata.uri + , r = e.setKeyRequestState($c.GET_KEY_RESPONSE); + return this.eventEmitter.trigger(x.LICENSE_CHALLENGE_CREATED, { + keyuri: i, + licenseChallenge: t, + keysystem: this.systemString, + keyId: e.decryptdata.keyId + }), + r + } + generateRequestInitialized(e) { + var t = e.licenseChallenge; + return e.requestInfo = void 0, + e.resolveState($c.GET_CHALLENGE, t), + Ul + } + handleParsedKeyResponse(t, e) { + const i = t.decryptdata.uri + , r = e.statusCode; + if (0 !== r) + return Ui(new uu("License server responded with error",i,r,{ + code: r, + text: "Server error" + },!1,Xl.LicenseServerError)); + if (!e.license || !e.license.byteLength) + return Ui(new uu("License server responded with invalid license",i,r,{ + code: r, + text: "Invalid license" + },!1,Xl.LicenseServerError)); + if (e.renewalDate) { + const i = e.renewalDate + , r = new Date + , n = i > r ? i.getTime() - r.getTime() : 0; + 0 < n && this._scheduleRenewal(t, n) + } + return Jr([t.setKeyRequestState($c.PROCESS_LICENSE), Lr(t.session.update(e.license)).pipe(Ja(()=>{ + t.resolveState($c.PROCESS_LICENSE, void 0) + } + ), Un(e=>{ + throw this.logger.error(`${this.systemString} FAIL: Failed to update with key response message=${e.message}`), + new cu(e.message,t.decryptdata.uri,0,$.KeySystemFailedToUpdateSession,this.systemString) + } + ))]).pipe(Js(void 0)) + } + handleKeyMessage(e) { + if (this.isDestroying) + this.logger.warn("In the middle of destroying, ignore key message"); + else { + const t = new DOMParser + , i = new ("utf16" === this.config.playReadyMessageFormat ? Uint16Array : Uint8Array)(e.message.buffer || e.message) + , r = String.fromCharCode.apply(null, Array.from(i)) + , n = t.parseFromString(r, "application/xml").getElementsByTagName("PlayReadyKeyMessage")[0]; + if (n && "LicenseAcquisition" === n.getAttribute("type")) { + const s = t.parseFromString(r, "application/xml").getElementsByTagName("Challenge")[0]; + if (s && "base64encoded" === s.getAttribute("encoding") && 0 !== s.childNodes.length) { + const a = Vc.base64Decode(s.childNodes[0].nodeValue) + , o = O.utf8arrayToStr(a) + , d = t.parseFromString(o, "application/xml").getElementsByTagName("KID")[0]; + e = null, + e = d.childNodes[0] ? d.childNodes[0].nodeValue : d.getAttribute("VALUE"), + e = Vc.base64Decode(e).subarray(0, 16); + qc.changeEndianness(e); + const l = this.keyIdToKeyInfo[O.utf8arrayToStr(e)]; + l.licenseChallenge = a, + l.resolveState($c.GET_CHALLENGE, a) + } else + this.logger.warn(`${this.systemString} wrong challenge format or empty challenge`) + } else + this.logger.warn(`${this.systemString} unrecognized message ignore it`) + } + } + } + gc = yh; + const vh = { + initDataTypes: ["cenc", "keyids"] + } + , Sh = new Uint8Array([237, 239, 139, 169, 121, 214, 74, 206, 163, 200, 39, 220, 213, 29, 33, 237]) + , bh = { + clearkey: Zc, + fairplaystreaming: pu, + playready: _c, + widevine: Nc + } + , Th = { + clearkey: [["org.w3.clearkey", gr]], + fairplaystreaming: [["com.apple.fps.3_0", t], ["com.apple.fps", yc]], + playready: [["com.microsoft.playready.recommendation", gc]], + widevine: [["com.widevine.alpha", class extends Yc { + constructor(e, t, i, r, n, s) { + super(e, t, i, r, !1, n, s), + this.shouldDestroyMediaKeys = !0 + } + static get systemId() { + return Sh + } + static get requestAccessConfig() { + return vh + } + get needsCert() { + return !0 + } + removeKey(e) { + return super.removeSessions(e, !0) + } + ensureKeyContext(e) { + const t = e.uri + , i = this.keyUriToKeyInfo[t]; + return null != i && i.session && (i.oldSessions.push(i.session), + i.session = null), + super.ensureKeyContext(e) + } + getKeyRequestResponse(e, t) { + var i = e.decryptdata.uri + , r = e.setKeyRequestState($c.GET_KEY_RESPONSE); + return this.eventEmitter.trigger(x.LICENSE_CHALLENGE_CREATED, { + keyuri: i, + licenseChallenge: t, + keysystem: this.systemString, + keyId: e.decryptdata.keyId + }), + r + } + handleParsedKeyResponse(t, e) { + t.licenseChallenge = void 0; + const i = t.decryptdata.uri + , r = e.statusCode; + if (0 !== r) + return Ui(new uu("License server responded with error",i,r,{ + code: r, + text: "Server error" + },!1,Xl.LicenseServerError)); + if (!e.license || !e.license.byteLength) + return Ui(new uu("License server responded with invalid license",i,r,{ + code: r, + text: "Invalid license" + },!1,Xl.LicenseServerError)); + if (e.renewalDate) { + const i = e.renewalDate + , r = new Date + , n = i > r ? i.getTime() - r.getTime() : 0; + 0 < n && this._scheduleRenewal(t, n) + } + return Jr([t.setKeyRequestState($c.PROCESS_LICENSE), Lr(t.session.update(e.license)).pipe(Ja(()=>{ + var e = t.decryptdata.keyId + , e = t.session.keyStatuses.get(e); + this.handleKeyStatusForKey(e, t) + } + ), Un(e=>{ + throw this.logger.error(`${this.systemString} FAIL: Failed to update with key response code=${e.code} message=${e.message}`), + new cu(e.message,t.decryptdata.uri,e.code,{ + code: e.code, + text: "Failed to update with key response" + },this.systemString) + } + ))]).pipe(Js(void 0)) + } + generateInitData(e, t) { + return { + initData: t.pssh, + initDataType: "cenc" + } + } + generateRequestInitialized(e) { + var t = e.licenseChallenge; + return e.requestInfo = void 0, + e.resolveState($c.GET_CHALLENGE, t), + Ul + } + handleKeyMessage(i) { + if (this.isDestroying) + this.logger.warn("In the middle of destroying, ignore key message"); + else { + const r = i.target; + let e = null + , t = null; + if (r.sessionId in this.sessionIdToKeyUri) + e = this.sessionIdToKeyUri[r.sessionId], + t = this.keyUriToKeyInfo[e]; + else + for (const [i,n] of Object.entries(this.keyUriToKeyInfo)) + if (n.session === r) { + e = i, + t = n; + break + } + if (t) + switch (i.messageType) { + case "license-request": + { + const r = new Uint8Array(i.message); + t.resolveState($c.GET_CHALLENGE, r); + break + } + } + else + this.logger.warn(`${this.systemString} empty keyuri and keyInfo`) + } + } + } + ]] + } + , Eh = Zc.id; + class Ih { + createMediaKeys(t, e, i, r, n) { + let s = Ih.idToMediaKeysInfoMap[t]; + if (!s) { + const a = qc.getCapabilities(e, i) + , o = new Ji; + Ih.requestKeySystemAccess(t, a, n, r).pipe(Ra(function(e) { + return Lr((Ih.idToMediaKeysInfoMap[t].keySystemAccess = e).createMediaKeys()) + }), Ja(e=>{ + o.next(e), + o.complete() + } + ), Un(e=>(o.error(new cu(`could not initialize key system: ${e.message}`,void 0,0,$.KeySystemFailedToInitialize,t)), + Ti)), $a(Ih.destroy$)).subscribe(), + s = Ih.idToMediaKeysInfoMap[t] = { + mediaKeys$: o, + keySystemAccess: null + } + } + return s.mediaKeys$ + } + destroyMediaKeys() { + Ih.destroy$.next(), + Ih.idToMediaKeysInfoMap = {} + } + static getKeySystemIdForDecryptData(e) { + let t; + if (e) { + t = Eh; + var i = e.format; + for (const e of eh) { + var r = bh[e]; + if ((null == r ? void 0 : r.keyFormatString) === i) { + t = e; + break + } + } + } + if (!t) + throw Error("No matching key system"); + return t + } + static requestKeySystemAccess(e, t, i, r) { + if ("undefined" == typeof navigator || void 0 === navigator.requestMediaKeySystemAccess) + return Ui(new cu("navigator undefined",void 0,0,$.KeySystemUndefinedNavigator,e)); + const n = Th[e]; + let s = Ui(new cu("no key systems to try",void 0,0,$.KeySystemNoKeySystemsToTry,e)); + for (const e of n) { + const n = e[0] + , o = e[1] + , d = (a = i) && "object" == typeof a ? i : o.requestAccessConfig + , l = [Object.assign({}, d, t)]; + s = s.pipe(Un(()=>Ih.requestKeySystemInternal(n, l, r))) + } + var a; + return s + } + static requestKeySystemInternal(e, t, i) { + return Yr(()=>Lr(navigator.requestMediaKeySystemAccess(e, t))) + } + make(e, t, i, r, n, s) { + var a = null === (d = Ih.idToMediaKeysInfoMap[e]) || void 0 === d ? void 0 : d.keySystemAccess; + if (!a) + throw new cu(`No keySystemAccess for ${e}`,void 0,0,$.KeySystemNoKeySystemAccess,e); + let o; + var d = bh[e].systemStringPrefix; + for (const t of Th[e]) + if (t[0] === a.keySystem) { + o = t[1]; + break + } + if (!o) + throw new cu(`No constructor associated with ${e}`,void 0,0,$.KeySystemNoConstructor,d); + return new o(t,d,i,r,n,s) + } + static get availableKeySystems() { + return Object.keys(bh) + } + static getKeySystemFormat(e) { + e = bh[e]; + return e ? e.keyFormatString : "" + } + static getKeySystemSecurityLevel(e) { + e = bh[e]; + return e ? e.securityLevels : void 0 + } + } + Ih.idToMediaKeysInfoMap = {}, + Ih.destroy$ = new zt; + const wh = ["avc1.42E01E"] + , Ah = ["mp4a.40.2"]; + function Oh(e, t, i) { + if (t) { + if (t instanceof or) + t = new lu("Key request timed out",e,$.KeySystemRequestTimedOut); + else if (t instanceof cu) { + const i = (null == t ? void 0 : t.response) || $.InternalError; + t = new uu(t.message,e,0,i,!1,Xl.InternalError,!0) + } + } else + t = new uu("Unknown error from CDM",e,0,$.KeySystemCDMUnknownError,!1,Xl.InternalError); + return (t instanceof uu || t instanceof lu) && (t.mediaOptionIds = [...i]), + t + } + class kh { + constructor(e, t, i, r, n, s, a, o=new Ih) { + this.ksService = e, + this.mediaSink = t, + this.config = i, + this.platformQuery = r, + this.eventEmitter = n, + this.sessionHandler = s, + this.keySystemFactory = o, + this.reset$ = new zt, + this.keyRequest$ = new zt, + this.abort$ = new zt, + this.keySystem$ = new gi(null), + this._keyStatusChange$ = new zt, + this.protectionData = {}, + this.keySystemId = null, + this.keyUriToRequest = {}, + this.ksQuery = e.getQuery(), + this.logger = a.child({ + name: "eme" + }), + this.config.warmupCdms && this.keySystemFactory.createMediaKeys(pu.id, wh, Ah, this.logger, void 0).subscribe(), + nn(r.platformInfo$.pipe(Es((e,t)=>e && t && e.requiresCDMAttachOnStart === t.requiresCDMAttachOnStart), Ra(e=>null != e && e.requiresCDMAttachOnStart ? this.attachMediaKeys().pipe(Un(e=>(this.handleKeySystemError(e), + Ti))) : Ul), Ua(Ti)), this.keyRequest$.pipe(Kr(e=>e.pipe(Un(()=>Ti)))), this.keySystem$.pipe(Ra(e=>e ? e.keyStatusChange$.pipe(Ja(e=>{ + var t = e.decryptdata.uri + , i = this.ksQuery.getKeyInfo(t); + "needs-renewal" === e.status ? this.ksService.updateKeyRequestState(t, zl.MustRequestResponse, e=>e === zl.GotKeyResponse) : (i = Oh(t, e.error, null !== (i = null == i ? void 0 : i.mediaOptionIds) && void 0 !== i ? i : []), + this.ksService.setError(t, i)), + this._keyStatusChange$.next(e) + } + )) : Ti)), this.isKeyCleanupSupported() ? this.mediaSink.mediaQuery.bufferedSegmentsTuple$.pipe(Kr(e=>{ + const [t,i] = e + , r = new Set; + return t.forEach(e=>{ + e = null === (e = null === (e = e.frag) || void 0 === e ? void 0 : e.keyTagInfo) || void 0 === e ? void 0 : e.uri; + e && r.add(e) + } + ), + i.forEach(e=>{ + e = null === (e = null === (e = e.frag) || void 0 === e ? void 0 : e.keyTagInfo) || void 0 === e ? void 0 : e.uri; + e && r.add(e) + } + ), + this.handleKeyCleanup(r) + } + )) : Ul).pipe($a(this.reset$)).subscribe() + } + get keyStatusChange$() { + return this._keyStatusChange$ + } + get keySystem() { + return this.keySystem$.value + } + destroy() { + this.reset$.next(), + this.ksService.removeAll(), + this.keySystemId = null; + const e = this.keySystem; + let t = Ul; + return e && (this.keySystem$.next(null), + e.shouldDestroyMediaKeys && this.keySystemFactory.destroyMediaKeys(), + t = e.destroy()), + Cr([t, this.mediaSink.clearMediaKeys(this.config.clearMediaKeysOnPromise)]).pipe(Js(void 0)) + } + attachMediaKeys() { + if (this.keySystem) + return Ul; + var e = this.config.keySystemPreference ? Ih.getKeySystemFormat(this.config.keySystemPreference) : pu.keyFormatString; + return this.makeKeySystem(new Gc("NONE",null,null,e,[1])).pipe(Js(void 0)) + } + isKeyCleanupSupported() { + return !0 === this.config.useMultipleKeySessions || "widevine" === this.config.keySystemPreference || "playready" === this.config.keySystemPreference + } + handleKeyCleanup(i) { + if (this.ksQuery.getCount() < 6) + return Ul; + const r = performance.now() + , e = this.ksQuery.getAll().map(e=>{ + var t = e.keyUri; + if (!i.has(t)) { + const i = eu(e.decryptdata); + if ("AES-128" !== i.method && r > e.minHoldTime) + return this._removeKey(t, i) + } + return Ul + } + ); + return e.length ? Jr(e).pipe(Ua(Ul)) : Ul + } + _removeKey(e, t) { + return this.abort$.next(e), + this.ksService.removeKey(e), + this.keySystem.removeKey(t) + } + removeKeysForItems(i) { + const r = []; + return sd(()=>{ + for (const e of i) { + this.ksService.removeAllKeysForItem(e); + const i = this.ksQuery.getAll({ + filterBy: e=>0 === e.itemIds.length + }); + for (const t of i) + r.push(this._removeKey(t.keyUri, eu(t.decryptdata))) + } + } + ), + r.length ? Jr(r).pipe(Ra(()=>Ul)) : Ul + } + get availableKeySystems() { + return Ih.availableKeySystems + } + initialize(e) { + var t = this.protectionData; + this.protectionData = {}; + var i = this.config.keySystemPreference; + for (const a of Ih.availableKeySystems) { + var r = e[a]; + if (r) + if (i === a) { + var n, s = r.certificate, r = r.serverCertUrl ? fl.buildAbsoluteURL(window.location.href, r.serverCertUrl) : void 0; + let e; + this.protectionData[a] = { + serverCertUrl: r, + certificate: s + }, + s ? e = Bi({ + keysystem: a, + certificate: s + }) : r && (null === (n = null == t ? void 0 : t[a]) || void 0 === n ? void 0 : n.serverCertUrl) !== r && (n = ml(r) ? this.config.certLoadPolicy.customURL : this.config.certLoadPolicy.default, + e = Pc({ + url: r, + xhrSetup: this.config.xhrSetup + }, n).pipe(ur(([e])=>({ + keysystem: a, + certificate: new Uint8Array(e) + })))), + e && e.pipe(Ra(e=>this.onServerCertificateLoaded(e)), Un(e=>{ + throw this.eventEmitter.trigger(x.INTERNAL_ERROR, { + type: o, + details: "certificateLoadError", + fatal: !1, + handled: !0, + reason: "Error handling cert", + response: $.KeySystemCertificateLoadError, + message: e.message, + name: "certificateLoadError" + }), + e + } + ), $a(this.reset$)).subscribe() + } else + this.logger.warn(`Key system ${a} does not match preference ${i}, ignoring`) + } + } + generateRequest(e, t) { + this.keySystem && this.keySystem.setKeyRequestInfo(e, t) + } + setLicenseResponse(e, t) { + this.keySystem && this.keySystem.setParsedResponse(e, t) + } + getKeyFromDecryptData(e, t) { + if (!e || !e.isEncrypted) + return Bi(e); + let i; + return sd(()=>{ + i = this._getKeyFromDecryptData(e, t) + } + ), + i + } + _getKeyFromDecryptData(t, i) { + let r = null + , n = null; + i && (r = i.itemId, + n = i.mediaOptionId); + const s = t.uri + , e = this.ksQuery.getKeyInfo(s); + if (e && null != i && this.ksService.addMediaOption(s, i), + (null == e ? void 0 : e.error)instanceof uu && !1 === e.error.isOkToRetry) + return Ui(e.error); + if (e && e.requestState !== zl.MustRequestResponse) + return e.requestState === zl.GotKeyResponse ? Bi(eu(e.decryptdata)) : this.keyUriToRequest[s]; + { + const o = performance.now() + this.config.keyMinHoldTimeBeforeCleanup; + let e; + this.abort$.next(s), + this.ksService.upsertKey({ + keyUri: s, + decryptdata: function(e) { + var {method: t, isEncrypted: i, uri: r, format: n, formatversions: s} = e; + return { + method: t, + isEncrypted: i, + uri: r, + format: n, + formatversions: s, + ivBuf: null !== (s = null === (s = e.iv) || void 0 === s ? void 0 : s.buffer) && void 0 !== s ? s : null, + keyIdBuf: null === (s = e.keyId) || void 0 === s ? void 0 : s.buffer, + keyBuf: null === (s = e.key) || void 0 === s ? void 0 : s.buffer, + psshBuf: null === (e = e.key) || void 0 === e ? void 0 : e.buffer + } + }(t), + minHoldTime: o, + mediaOptionIds: [n], + requestState: zl.WaitingForKeyResponse, + itemIds: [r] + }); + var a = t.method; + switch (a) { + case "SAMPLE-AES": + case "ISO-23001-7": + case "SAMPLE-AES-CTR": + { + const o = this.config.keyLoadPolicy.customURL; + e = this.fetchKeyEME(t).pipe(vo(o.maxLoadTimeMs)); + break + } + case "AES-128": + e = this.fetchKeyHTTP(t.uri, t, this.config.keyLoadPolicy); + break; + default: + return Ui(new V(!1,`Unexpected METHOD attribute ${a}`,$.KeySystemUnexpectedMETHOD)) + } + i = this.keyUriToRequest[s] = e.pipe(ur(e=>{ + var t = e.decryptdata; + return this.ksService.updateKeyValue(s, t.key), + this.eventEmitter.trigger(x.KEY_LOADED, e), + e.decryptdata + } + ), Un(e=>{ + var t = this.ksQuery.getKeyInfo(s); + return e = Oh(s, e, null !== (t = null == t ? void 0 : t.mediaOptionIds) && void 0 !== t ? t : []), + this.ksService.setError(s, e), + Ui(e) + } + ), $s(()=>{ + this.ksService.updateKeyRequestState(s, zl.MustRequestResponse, e=>e === zl.WaitingForKeyResponse), + this.keyUriToRequest[s] = null + } + ), wa(), $a(hn(this.abort$.pipe(an(e=>e === s)), this.reset$).pipe(Ja(e=>this.logger.warn(e ? `aborted ${oe(e)}` : "got reset"))))); + return this.keyRequest$.next(i), + i + } + } + fetchKeyEME(e) { + return this.requestKey(e).pipe(ur(e=>({ + timestamp: performance.now(), + keyuri: e.uri, + decryptdata: e + }))) + } + fetchKeyHTTP(e, t, i) { + return kh.fetchKeyHTTP(e, this.config, t, i) + } + static fetchKeyHTTP(t, e, i, r) { + e = { + url: t, + xhrSetup: e.xhrSetup + }; + return Pc(e, xc(e, r)).pipe(ur(([e])=>(i.key = new Uint8Array(e), + { + decryptdata: i, + keyuri: t, + timestamp: performance.now() + }))) + } + requestKey(t) { + return this.makeKeySystem(t).pipe(Ra(e=>e.startKeyRequest(t))) + } + ensureKeySystem(t) { + return Yr(()=>{ + if (!this.keySystem && this.keySystemId) { + this.keySystem$.next(this.keySystemFactory.make(this.keySystemId, t, this.config, this.eventEmitter, this.sessionHandler, this.logger)); + var e = this.protectionData && this.protectionData[this.keySystemId]; + if (e) + return this.keySystem.setServerCertificate(e.certificate).pipe(Js(this.keySystem)) + } + return Bi(this.keySystem) + } + ) + } + makeKeySystem(e) { + return this.ensureMediaKeys(e).pipe(Ra(e=>this.mediaSink.setMediaKeys(e).pipe(Ra(()=>this.ensureKeySystem(e))))) + } + ensureMediaKeys(e) { + var t = Ih.getKeySystemIdForDecryptData(e); + if (null == this.keySystemId) + this.keySystemId = t; + else if (this.keySystemId !== t) + return Ui(new uu(`New key system string does not match existing ${t} !== ${this.keySystemId}`,e.uri,0,$.KeySystemUnmatchedString,!1,Xl.InternalError)); + return this.keySystemFactory.createMediaKeys(this.keySystemId, wh, Ah, this.logger, null === (e = this.platformQuery.platformInfo) || void 0 === e ? void 0 : e.keySystemConfig) + } + onServerCertificateLoaded(e) { + var t = e.keysystem + , e = e.certificate; + return this.protectionData[t].certificate = e, + this.keySystem && this.keySystemId === t ? this.keySystem.setServerCertificate(e).pipe(Js(void 0)) : Ul + } + handleKeySystemError(e) { + e = new cu(e.message,void 0,void 0,$.KeySystemSetupError,void 0); + this.eventEmitter.trigger(x.INTERNAL_ERROR, e) + } + } + class Ch extends Od { + constructor(e) { + super(e) + } + getKeyInfo(e) { + e = this.getEntity(e); + return e ? Object.assign(Object.assign({}, e), { + error: hu(e.error, e.mediaOptionIds) + }) : null + } + getKeyInfo$(e) { + return this.selectEntity(e).pipe(ur(e=>e ? Object.assign(Object.assign({}, e), { + error: hu(e.error, e.mediaOptionIds) + }) : null)) + } + getKeyRequestState$(e) { + return this.selectEntity(e, e=>null == e ? void 0 : e.requestState) + } + getKeyStatus$(e) { + return this.selectEntity(e, e=>null == e ? void 0 : e.status) + } + getKeyError$(e) { + return this.selectEntity(e, e=>hu(null == e ? void 0 : e.error, null == e ? void 0 : e.mediaOptionIds)).pipe(Id) + } + } + class Dh { + constructor(e) { + this.store = e + } + getQuery() { + return new Ch(this.store) + } + upsertKey(i) { + Co("keys.upsert", i.keyUri); + const r = new Set(i.itemIds.filter(e=>null != e)) + , n = new Set(i.mediaOptionIds.filter(e=>null != e)); + this.store.upsert(i.keyUri, e=>{ + const t = Object.assign(Object.assign({}, e), i); + if ("itemIds"in e) + for (const i of e.itemIds) + r.add(i); + if (t.itemIds = Array.from(r), + "mediaOptionIds"in e) + for (const i of e.mediaOptionIds) + n.add(i); + return t.mediaOptionIds = Array.from(n), + t + } + , ()=>Object.assign(Object.assign({}, i), { + itemIds: Array.from(r), + mediaOptionIds: Array.from(n) + })) + } + removeKey(e) { + Co("keys.removeKey", e), + this.store.remove(e) + } + removeAllKeysForItem(i) { + Co(`keys.removeAllKeysForItem ${i}`), + this.store.update(null, e=>{ + var t = e.itemIds.findIndex(e=>e === i); + 0 <= t && e.itemIds.splice(t, 1) + } + ) + } + removeAll() { + Co("keys.remove"), + this.store.remove() + } + updateKeyValue(e, t) { + Co("keys.updateKeyValue", e), + this.store.update(e, e=>{ + null == e.decryptdata.keyBuf && null != t && (e.decryptdata.keyBuf = t.buffer), + e.requestState = zl.GotKeyResponse + } + ) + } + updateKeyStatus(e, t) { + Co(`keys.updateKeyStatus ${t}`, e), + this.store.update(e, e=>{ + e.status = t + } + ) + } + updateKeyRequestState(e, t, i) { + Co(`keys.updateKeyRequestState ${t}`, e), + this.store.update(e, e=>{ + i && !i(e.requestState) || (e.requestState = t) + } + ) + } + addMediaOption(e, t) { + const {itemId: i, mediaOptionId: r} = t; + Co(`keys.addMediaOption itemId: ${i}, mediaOptionId: ${r}`, e), + this.store.update(e, e=>{ + null != r && e.mediaOptionIds.every(e=>e !== r) && e.mediaOptionIds.push(r), + null != i && e.itemIds.every(e=>e !== i) && e.itemIds.push(i) + } + ) + } + setError(e, t) { + var i; + Co(`keys.setError ${null === (i = null == t ? void 0 : t.constructor) || void 0 === i ? void 0 : i.name}`, e), + this.store.update(e, e=>{ + e.error = hu(t), + e.requestState = zl.MustRequestResponse + } + ) + } + } + const Mh = new class extends pd { + constructor() { + super({}, { + name: "key-system-store", + idKey: "keyUri", + producerFn: vc + }) + } + } + ; + let Ph = null; + function xh(e) { + let t = e; + return Lh.hasOwnProperty(e) && (t = Lh[e]), + String.fromCharCode(t) + } + function Rh(t) { + const i = []; + for (let e = 0; e < t.length; e++) + i.push(t[e].toString(16)); + return i + } + const Lh = { + 42: 225, + 92: 233, + 94: 237, + 95: 243, + 96: 250, + 123: 231, + 124: 247, + 125: 209, + 126: 241, + 127: 9608, + 128: 174, + 129: 176, + 130: 189, + 131: 191, + 132: 8482, + 133: 162, + 134: 163, + 135: 9834, + 136: 224, + 137: 32, + 138: 232, + 139: 226, + 140: 234, + 141: 238, + 142: 244, + 143: 251, + 144: 193, + 145: 201, + 146: 211, + 147: 218, + 148: 220, + 149: 252, + 150: 8216, + 151: 161, + 152: 42, + 153: 8217, + 154: 9473, + 155: 169, + 156: 8480, + 157: 8226, + 158: 8220, + 159: 8221, + 160: 192, + 161: 194, + 162: 199, + 163: 200, + 164: 202, + 165: 203, + 166: 235, + 167: 206, + 168: 207, + 169: 239, + 170: 212, + 171: 217, + 172: 249, + 173: 219, + 174: 171, + 175: 187, + 176: 195, + 177: 227, + 178: 205, + 179: 204, + 180: 236, + 181: 210, + 182: 242, + 183: 213, + 184: 245, + 185: 123, + 186: 125, + 187: 92, + 188: 94, + 189: 95, + 190: 124, + 191: 8764, + 192: 196, + 193: 228, + 194: 214, + 195: 246, + 196: 223, + 197: 165, + 198: 164, + 199: 9475, + 200: 197, + 201: 229, + 202: 216, + 203: 248, + 204: 9487, + 205: 9491, + 206: 9495, + 207: 9499 + } + , _h = 100 + , Nh = { + 17: 1, + 18: 3, + 21: 5, + 22: 7, + 23: 9, + 16: 11, + 19: 12, + 20: 14 + } + , Fh = { + 17: 2, + 18: 4, + 21: 6, + 22: 8, + 23: 10, + 19: 13, + 20: 15 + } + , Bh = { + 25: 1, + 26: 3, + 29: 5, + 30: 7, + 31: 9, + 24: 11, + 27: 12, + 28: 14 + } + , Uh = { + 25: 2, + 26: 4, + 29: 6, + 30: 8, + 31: 10, + 27: 13, + 28: 15 + } + , $h = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "black", "transparent"] + , Vh = { + verboseFilter: { + DATA: 3, + DEBUG: 3, + INFO: 2, + WARNING: 2, + TEXT: 1, + ERROR: 0 + }, + time: null, + verboseLevel: 0, + setTime: function(e) { + this.time = e + }, + log: function(e, t) { + var i = this.verboseFilter[e]; + this.verboseLevel >= i && console.log(this.time + " [" + e + "] " + t) + } + }; + class Kh { + constructor(e, t, i, r, n) { + this.foreground = e || "white", + this.underline = t || !1, + this.italics = i || !1, + this.background = r || "black", + this.flash = n || !1 + } + reset() { + this.foreground = "white", + this.underline = !1, + this.italics = !1, + this.background = "black", + this.flash = !1 + } + setStyles(e) { + Object.assign(this, e) + } + isDefault() { + return "white" === this.foreground && !this.underline && !this.italics && "black" === this.background && !this.flash + } + equals(e) { + return this.foreground === e.foreground && this.underline === e.underline && this.italics === e.italics && this.background === e.background && this.flash === e.flash + } + copy(e) { + this.foreground = e.foreground, + this.underline = e.underline, + this.italics = e.italics, + this.background = e.background, + this.flash = e.flash + } + toString() { + return "color=" + this.foreground + ", underline=" + this.underline + ", italics=" + this.italics + ", background=" + this.background + ", flash=" + this.flash + } + } + class Hh { + constructor(e, t, i, r, n, s) { + this.uchar = e || " ", + this.penState = new Kh(t,i,r,n,s) + } + reset() { + this.uchar = " ", + this.penState.reset() + } + setChar(e, t) { + this.uchar = e, + this.penState.copy(t) + } + setPenState(e) { + this.penState.copy(e) + } + equals(e) { + return this.uchar === e.uchar && this.penState.equals(e.penState) + } + copy(e) { + this.uchar = e.uchar, + this.penState.copy(e.penState) + } + isEmpty() { + return " " === this.uchar && this.penState.isDefault() + } + } + class jh { + constructor() { + this.chars = []; + for (let e = 0; e < _h; e++) + this.chars.push(new Hh); + this.pos = 0, + this.currPenState = new Kh + } + equals(t) { + let i = !0; + for (let e = 0; e < _h; e++) + if (!this.chars[e].equals(t.chars[e])) { + i = !1; + break + } + return i + } + copy(t) { + for (let e = 0; e < _h; e++) + this.chars[e].copy(t.chars[e]) + } + isEmpty() { + let t = !0; + for (let e = 0; e < _h; e++) + if (!this.chars[e].isEmpty()) { + t = !1; + break + } + return t + } + setCursor(e) { + this.pos !== e && (this.pos = e), + this.pos < 0 ? (Vh.log("ERROR", "Negative cursor position " + this.pos), + this.pos = 0) : this.pos > _h && (Vh.log("ERROR", "Too large cursor position " + this.pos), + this.pos = _h) + } + moveCursor(e) { + var t = this.pos + e; + if (1 < e) + for (let e = this.pos + 1; e < t + 1; e++) + this.chars[e].setPenState(this.currPenState); + this.setCursor(t) + } + backSpace() { + this.moveCursor(-1), + this.chars[this.pos].setChar(" ", this.currPenState) + } + insertChar(e) { + 144 <= e && this.backSpace(); + var t = xh(e); + this.pos >= _h ? Vh.log("ERROR", "Cannot insert " + e.toString(16) + " (" + t + ") at position " + this.pos + ". Skipping it!") : (this.chars[this.pos].setChar(t, this.currPenState), + this.moveCursor(1)) + } + clearFromPos(e) { + let t; + for (t = e; t < _h; t++) + this.chars[t].reset() + } + clear() { + this.clearFromPos(0), + this.pos = 0, + this.currPenState.reset() + } + clearToEndOfRow() { + this.clearFromPos(this.pos) + } + getTextString() { + const t = []; + let i = !0; + for (let e = 0; e < _h; e++) { + var r = this.chars[e].uchar; + " " !== r && (i = !1), + t.push(r) + } + return i ? "" : t.join("") + } + setPenStyles(e) { + this.currPenState.setStyles(e), + this.chars[this.pos].setPenState(this.currPenState) + } + } + class qh { + constructor() { + this.rows = []; + for (let e = 0; e < 15; e++) + this.rows.push(new jh); + this.currRow = 14, + this.nrRollUpRows = null, + this.reset() + } + reset() { + for (let e = 0; e < 15; e++) + this.rows[e].clear(); + this.currRow = 14 + } + equals(t) { + let i = !0; + for (let e = 0; e < 15; e++) + if (!this.rows[e].equals(t.rows[e])) { + i = !1; + break + } + return i + } + copy(t) { + for (let e = 0; e < 15; e++) + this.rows[e].copy(t.rows[e]) + } + isEmpty() { + let t = !0; + for (let e = 0; e < 15; e++) + if (!this.rows[e].isEmpty()) { + t = !1; + break + } + return t + } + backSpace() { + this.rows[this.currRow].backSpace() + } + clearToEndOfRow() { + this.rows[this.currRow].clearToEndOfRow() + } + insertChar(e) { + this.rows[this.currRow].insertChar(e) + } + setPen(e) { + this.rows[this.currRow].setPenStyles(e) + } + moveCursor(e) { + this.rows[this.currRow].moveCursor(e) + } + setCursor(e) { + Vh.log("INFO", "setCursor: " + e), + this.rows[this.currRow].setCursor(e) + } + setPAC(t) { + Vh.log("INFO", "pacData = " + JSON.stringify(t)); + let i = t.row - 1; + if (this.nrRollUpRows && i < this.nrRollUpRows - 1 && (i = this.nrRollUpRows - 1), + this.nrRollUpRows && this.currRow !== i) { + for (let e = 0; e < 15; e++) + this.rows[e].clear(); + const t = this.currRow + 1 - this.nrRollUpRows + , r = this.lastOutputScreen; + if (r) { + const e = r.rows[t].cueStartTime; + if (e && e < Vh.time) + for (let e = 0; e < this.nrRollUpRows; e++) + this.rows[i - this.nrRollUpRows + e + 1].copy(r.rows[t + e]) + } + } + this.currRow = i; + const r = this.rows[this.currRow]; + if (null !== t.indent) { + const i = t.indent + , e = Math.max(i - 1, 0); + r.setCursor(t.indent), + t.color = r.chars[e].penState.foreground + } + const e = { + foreground: t.color, + underline: t.underline, + italics: t.italics, + background: "black", + flash: !1 + }; + this.setPen(e) + } + setBkgData(e) { + Vh.log("INFO", "bkgData = " + JSON.stringify(e)), + this.backSpace(), + this.setPen(e), + this.insertChar(32) + } + setRollUpRows(e) { + this.nrRollUpRows = e + } + rollUp() { + if (null !== this.nrRollUpRows) { + Vh.log("INFO", "TEXT " + this.getDisplayText()); + const e = this.currRow + 1 - this.nrRollUpRows + , t = this.rows.splice(e, 1)[0]; + t.clear(), + this.rows.splice(this.currRow, 0, t), + Vh.log("INFO", "Rolling up") + } else + Vh.log("DEBUG", "roll_up but nrRollUpRows not set yet") + } + getDisplayText(t) { + t = t || !1; + const i = []; + let e = "", r; + for (let e = 0; e < 15; e++) { + const n = this.rows[e].getTextString(); + n && (r = e + 1, + t ? i.push("Row " + r + ": '" + n + "'") : i.push(n.trim())) + } + return 0 < i.length && (e = t ? "[" + i.join(" | ") + "]" : i.join("\n")), + e + } + getTextAndFormat() { + return this.rows + } + } + class Qh { + constructor(e, t) { + this.chNr = e, + this.outputFilter = t, + this.mode = null, + this.verbose = 0, + this.displayedMemory = new qh, + this.nonDisplayedMemory = new qh, + this.lastOutputScreen = new qh, + this.currRollUpRow = this.displayedMemory.rows[14], + this.writeScreen = this.displayedMemory, + this.mode = null, + this.cueStartTime = null + } + reset() { + this.mode = null, + this.displayedMemory.reset(), + this.nonDisplayedMemory.reset(), + this.lastOutputScreen.reset(), + this.currRollUpRow = this.displayedMemory.rows[14], + this.writeScreen = this.displayedMemory, + this.mode = null, + this.cueStartTime = null, + this.lastCueEndTime = null + } + getHandler() { + return this.outputFilter + } + setHandler(e) { + this.outputFilter = e + } + setPAC(e) { + this.writeScreen.setPAC(e) + } + setBkgData(e) { + this.writeScreen.setBkgData(e) + } + setMode(e) { + e !== this.mode && (this.mode = e, + Vh.log("INFO", "MODE=" + e), + "MODE_POP-ON" === this.mode ? this.writeScreen = this.nonDisplayedMemory : (this.writeScreen = this.displayedMemory, + this.writeScreen.reset()), + "MODE_ROLL-UP" !== this.mode && (this.displayedMemory.nrRollUpRows = null, + this.nonDisplayedMemory.nrRollUpRows = null), + this.mode = e) + } + insertChars(t) { + for (let e = 0; e < t.length; e++) + this.writeScreen.insertChar(t[e]); + var e = this.writeScreen === this.displayedMemory ? "DISP" : "NON_DISP"; + Vh.log("INFO", e + ": " + this.writeScreen.getDisplayText(!0)), + "MODE_PAINT-ON" !== this.mode && "MODE_ROLL-UP" !== this.mode || (Vh.log("TEXT", "DISPLAYED: " + this.displayedMemory.getDisplayText(!0)), + this.outputDataUpdate()) + } + ccRCL() { + Vh.log("INFO", "RCL - Resume Caption Loading"), + this.setMode("MODE_POP-ON") + } + ccBS() { + Vh.log("INFO", "BS - BackSpace"), + "MODE_TEXT" !== this.mode && (this.writeScreen.backSpace(), + this.writeScreen === this.displayedMemory && this.outputDataUpdate()) + } + ccAOF() {} + ccAON() {} + ccDER() { + Vh.log("INFO", "DER- Delete to End of Row"), + this.writeScreen.clearToEndOfRow(), + this.outputDataUpdate() + } + ccRU(e) { + Vh.log("INFO", "RU(" + e + ") - Roll Up"), + this.writeScreen = this.displayedMemory, + this.setMode("MODE_ROLL-UP"), + this.writeScreen.setRollUpRows(e) + } + ccFON() { + Vh.log("INFO", "FON - Flash On"), + this.writeScreen.setPen({ + flash: !0 + }) + } + ccRDC() { + Vh.log("INFO", "RDC - Resume Direct Captioning"), + this.setMode("MODE_PAINT-ON") + } + ccTR() { + Vh.log("INFO", "TR"), + this.setMode("MODE_TEXT") + } + ccRTD() { + Vh.log("INFO", "RTD"), + this.setMode("MODE_TEXT") + } + ccEDM() { + Vh.log("INFO", "EDM - Erase Displayed Memory"), + this.displayedMemory.reset(), + this.outputDataUpdate(!0) + } + ccCR() { + Vh.log("INFO", "CR - Carriage Return"), + this.writeScreen.rollUp(), + this.outputDataUpdate(!0) + } + ccENM() { + Vh.log("INFO", "ENM - Erase Non-displayed Memory"), + this.nonDisplayedMemory.reset() + } + ccEOC() { + var e; + Vh.log("INFO", "EOC - End Of Caption"), + "MODE_POP-ON" === this.mode && (e = this.displayedMemory, + this.displayedMemory = this.nonDisplayedMemory, + this.nonDisplayedMemory = e, + this.writeScreen = this.nonDisplayedMemory, + Vh.log("TEXT", "DISP: " + this.displayedMemory.getDisplayText())), + this.outputDataUpdate(!0) + } + ccTO(e) { + Vh.log("INFO", "TO(" + e + ") - Tab Offset"), + this.writeScreen.moveCursor(e) + } + ccMIDROW(e) { + const t = { + flash: !1, + underline: !1, + italics: !1 + }; + t.underline = e % 2 == 1, + t.italics = 46 <= e, + t.italics ? t.foreground = "white" : (e = Math.floor(e / 2) - 16, + t.foreground = ["white", "green", "blue", "cyan", "red", "yellow", "magenta"][e]), + Vh.log("INFO", "MIDROW: " + JSON.stringify(t)), + this.writeScreen.setPen(t) + } + outputDataUpdate(e=!1) { + var t = Vh.time; + null !== t && this.outputFilter && (this.outputFilter.updateData && this.outputFilter.updateData(t, this.displayedMemory), + null !== this.cueStartTime || this.displayedMemory.isEmpty() ? this.displayedMemory.equals(this.lastOutputScreen) || (this.outputFilter.newCue && (this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen), + !0 === e && this.outputFilter.dispatchCue && this.outputFilter.dispatchCue()), + this.cueStartTime = this.displayedMemory.isEmpty() ? null : t) : this.cueStartTime = t, + this.lastOutputScreen.copy(this.displayedMemory)) + } + cueSplitAtTime(e) { + this.outputFilter && (this.displayedMemory.isEmpty() || (this.outputFilter.newCue && this.outputFilter.newCue(this.cueStartTime, e, this.displayedMemory), + this.cueStartTime = e)) + } + } + var Gh = class { + constructor(e=1, t, i) { + this.field = e, + this.currChNr = -1, + this.lastCmdA = null, + this.lastCmdB = null, + this.channels = [new Qh(1,t), new Qh(2,i)], + this.dataCounters = { + padding: 0, + char: 0, + cmd: 0, + other: 0 + } + } + getHandler(e) { + return this.channels[e].getHandler() + } + setHandler(e, t) { + this.channels[e].setHandler(t) + } + addData(e, t) { + let i, r, n, s = null; + Vh.setTime(e); + for (let e = 0; e < t.length; e += 2) + r = 127 & t[e], + n = 127 & t[e + 1], + 16 <= r && r <= 31 && r === this.lastCmdA && n === this.lastCmdB ? (this.lastCmdA = null, + this.lastCmdB = null, + Vh.log("DEBUG", "Repeated command (" + Rh([r, n]) + ") is dropped")) : 0 != r || 0 != n ? (Vh.log("DATA", "[" + Rh([t[e], t[e + 1]]) + "] -> (" + Rh([r, n]) + ")"), + i = this.parseCmd(r, n), + i = i || this.parseMidrow(r, n), + i = i || this.parsePAC(r, n), + i = i || this.parseBackgroundAttributes(r, n), + !i && (s = this.parseChars(r, n), + s) && (this.currChNr && 0 <= this.currChNr ? this.channels[this.currChNr - 1].insertChars(s) : Vh.log("WARNING", "No channel found yet. TEXT-MODE?")), + i ? this.dataCounters.cmd += 2 : s ? this.dataCounters.char += 2 : (this.dataCounters.other += 2, + Vh.log("WARNING", "Couldn't parse cleaned data " + Rh([r, n]) + " orig: " + Rh([t[e], t[e + 1]])))) : this.dataCounters.padding += 2 + } + parseCmd(e, t) { + var i; + if (!((20 === e || 21 === e || 28 === e || 29 === e) && 32 <= t && t <= 47 || (23 === e || 31 === e) && 33 <= t && t <= 35)) + return !1; + const r = this.channels[(i = 20 === e || 23 === e ? 1 : 2) - 1]; + return 20 === e || 21 === e || 28 === e || 29 === e ? 32 === t ? r.ccRCL() : 33 === t ? r.ccBS() : 34 === t ? r.ccAOF() : 35 === t ? r.ccAON() : 36 === t ? r.ccDER() : 37 === t ? r.ccRU(2) : 38 === t ? r.ccRU(3) : 39 === t ? r.ccRU(4) : 40 === t ? r.ccFON() : 41 === t ? r.ccRDC() : 42 === t ? r.ccTR() : 43 === t ? r.ccRTD() : 44 === t ? r.ccEDM() : 45 === t ? r.ccCR() : 46 === t ? r.ccENM() : 47 === t && r.ccEOC() : r.ccTO(t - 32), + this.lastCmdA = e, + this.lastCmdB = t, + this.currChNr = i, + !0 + } + parseMidrow(e, t) { + var i; + if ((17 === e || 25 === e) && 32 <= t && t <= 47) { + if ((i = 17 === e ? 1 : 2) !== this.currChNr) + return Vh.log("ERROR", "Mismatch channel in midrow parsing"), + !1; + const r = this.channels[i - 1]; + return r.insertChars([32]), + r.ccMIDROW(t), + Vh.log("DEBUG", "MIDROW (" + Rh([e, t]) + ")"), + this.lastCmdA = e, + this.lastCmdB = t, + !0 + } + return !1 + } + parsePAC(e, t) { + if (!((17 <= e && e <= 23 || 25 <= e && e <= 31) && 64 <= t && t <= 127 || (16 === e || 24 === e) && 64 <= t && t <= 95)) + return !1; + var i = e <= 23 ? 1 : 2 + , r = (64 <= t && t <= 95 ? 1 == i ? Nh : Bh : 1 == i ? Fh : Uh)[e] + , r = this.interpretPAC(r, t); + return this.channels[i - 1].setPAC(r), + this.lastCmdA = e, + this.lastCmdB = t, + this.currChNr = i, + !0 + } + interpretPAC(e, t) { + var i; + const r = { + color: null, + italics: !1, + indent: null, + underline: !1, + row: e + }; + return i = 95 < t ? t - 96 : t - 64, + r.underline = 1 == (1 & i), + i <= 13 ? r.color = ["white", "green", "blue", "cyan", "red", "yellow", "magenta", "white"][Math.floor(i / 2)] : i <= 15 ? (r.italics = !0, + r.color = "white") : r.indent = 4 * Math.floor((i - 16) / 2), + r + } + parseChars(e, t) { + let i = null + , r = null + , n = null; + var s; + if (n = 25 <= e ? (i = 2, + e - 8) : (i = 1, + e), + 17 <= n && n <= 19 ? (s = t, + s = 17 === n ? t + 80 : 18 === n ? t + 112 : t + 144, + Vh.log("INFO", "Special char '" + xh(s) + "' in channel " + i), + r = [s], + this.lastCmdA = e, + this.lastCmdB = t) : 32 <= e && e <= 127 && (r = 0 === t ? [e] : [e, t], + this.lastCmdA = null, + this.lastCmdB = null), + r) { + const e = Rh(r); + Vh.log("DEBUG", `Char codes = ${e.join(",")}`) + } + return r + } + parseBackgroundAttributes(e, t) { + let i, r, n; + return ((16 === e || 24 === e) && 32 <= t && t <= 47 || (23 === e || 31 === e) && 45 <= t && t <= 47) && (i = { + underline: !1 + }, + 16 === e || 24 === e ? (r = Math.floor((t - 32) / 2), + i.background = $h[r], + t % 2 == 1 && (i.background = i.background + "_semi")) : 45 === t ? i.background = "transparent" : (i.foreground = "black", + 47 === t && (i.underline = !0)), + n = this.channels[(e < 24 ? 1 : 2) - 1], + n.setBkgData(i), + this.lastCmdA = null, + !(this.lastCmdB = null)) + } + reset() { + for (let e = 0; e < this.channels.length; e++) + this.channels[e] && this.channels[e].reset(); + this.lastCmdA = null, + this.lastCmdB = null + } + cueSplitAtTime(t) { + for (let e = 0; e < this.channels.length; e++) + this.channels[e] && this.channels[e].cueSplitAtTime(t) + } + } + ; + class Wh { + constructor(e, t) { + this.handler = e, + this.track = t, + this.startTime = null, + this.endTime = null, + this.screen = null + } + dispatchCue() { + null !== this.startTime && (this.handler.addCues("cc" + this.track, this.startTime, this.endTime, this.screen), + this.startTime = null) + } + newCue(e, t, i) { + (null === this.startTime || this.startTime > e) && (this.startTime = e), + this.endTime = t, + this.screen = i, + this.handler.createHTMLCaptionsTrack(this.track) + } + } + var zh = {} + , mu = {} + , gr = {} + , t = {}; + Object.defineProperty(t, "__esModule", { + value: !0 + }), + t.isValidPercentValue = function(e) { + return "number" == typeof e && 0 <= e && e <= 100 + } + , + t.isValidAlignSetting = function(e) { + return "string" == typeof e && ["start", "center", "end", "left", "right", "middle"].includes(e) + } + , + t.isValidDirectionSetting = function(e) { + return "string" == typeof e && ["", "rl", "lr"].includes(e) + } + , + t.isValidLineAndPositionSetting = function(e) { + return "number" == typeof e || "auto" === e + } + , + t.isValidLineAlignSetting = function(e) { + return "string" == typeof e && ["start", "center", "end"].includes(e) + } + , + t.isValidPositionAlignSetting = function(e) { + return "string" == typeof e && ["line-left", "center", "line-right", "auto", "left", "start", "middle", "end", "right"].includes(e) + } + , + t.isValidScrollSetting = function(e) { + return ["", "up"].includes(e) + } + ; + yc = {}; + Object.defineProperty(yc, "__esModule", { + value: !0 + }); + const Xh = { + "&": "&", + "<": "<", + ">": ">", + "‎": "‎", + "‏": "‏", + " ": " " + } + , Yh = { + c: "span", + i: "i", + b: "b", + u: "u", + ruby: "ruby", + rt: "rt", + v: "span", + lang: "span" + } + , Jh = { + v: "title", + lang: "lang" + } + , Zh = { + rt: "ruby" + } + , ep = { + "text-combine-upright": "-webkit-text-combine:horizontal; text-orientation: mixed;" + }; + class tp { + static parseTimeStamp(e) { + function t(e) { + var [t,i,r,e] = e.map(e=>e ? parseInt("" + e) : 0); + return 3600 * t + 60 * i + r + e / 1e3 + } + const i = /^(\d+):(\d{2})(:\d{2})?\.(\d{3})/.exec(e); + return i ? i[3] ? t([i[1], i[2], i[3].substring(1), i[4]]) : 59 < parseInt(i[1]) ? t([i[1], i[2], null, i[4]]) : t([null, i[1], i[2], i[4]]) : null + } + static parseContent(s, t, a) { + let i = t.text; + function e(e) { + return Xh[e] + } + const r = s.document.createElement("div") + , n = []; + let o, d, l = r; + for (; null !== (o = function() { + if (!i) + return null; + var e = (e = /^([^<]*)(<[^>]+>?)?/.exec(i))[1] || e[2]; + return i = i.substr(e.length), + e + }()); ) + if ("<" !== o[0]) + l.appendChild(s.document.createTextNode(o.replace(/&(amp|lt|gt|lrm|rlm|nbsp);/g, e))); + else { + if ("/" === o[1]) { + n.length && n[n.length - 1] === o.substr(2).replace(">", "") && (n.pop(), + l = l.parentNode); + continue + } + const t = tp.parseTimeStamp(o.substr(1, o.length - 2)); + let e; + if (t) { + e = s.document.createProcessingInstruction("timestamp", t.toString()), + l.appendChild(e); + continue + } + if (!(d = /^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/.exec(o))) + continue; + if (e = function(e, t, i) { + var r = Yh[e]; + if (!r) + return null; + const n = s.document.createElement(r); + if (n.dataset.localName = r, + (e = Jh[e]) && i && (n[e] = i.trim()), + t) + if (a[t]) { + const s = function(e) { + let t = ""; + for (const i in e) + t += ep[i] || i + ":" + e[i] + ";"; + return t + }(a[t]); + n.setAttribute("style", s) + } else + console.info(`WebVTT: parseContent: Style referenced, but no style defined for '${t}'!`); + return n + }(d[1], d[2], d[3]), + !e) + continue; + if (u = l, + c = e, + Zh[c.dataset.localName] && Zh[c.dataset.localName] !== u.dataset.localName) + continue; + n.push(d[1]), + l.appendChild(e), + l = e + } + var u, c; + return r + } + } + yc.default = tp; + gc = e && e.__decorate || function(e, t, i, r) { + var n, s = arguments.length, a = s < 3 ? t : null === r ? r = Object.getOwnPropertyDescriptor(t, i) : r; + if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) + a = Reflect.decorate(e, t, i, r); + else + for (var o = e.length - 1; 0 <= o; o--) + (n = e[o]) && (a = (s < 3 ? n(a) : 3 < s ? n(t, i, a) : n(t, i)) || a); + return 3 < s && a && Object.defineProperty(t, i, a), + a + } + ; + Object.defineProperty(gr, "__esModule", { + value: !0 + }); + const ip = t + , rp = yc; + gc = gc([function(e) { + let t = e; + return "undefined" != typeof window && null != window.VTTCue && (t = window.VTTCue, + t.create = e.create, + t.fromJSON = e.fromJSON, + t.prototype.toJSON = e.prototype.toJSON), + t + } + ], gc = class { + constructor(e, t, i) { + this._id = "", + this._pauseOnExit = !1, + this._region = null, + this._vertical = "", + this._snapToLines = !0, + this._line = "auto", + this._lineAlign = "start", + this._position = "auto", + this._positionAlign = "auto", + this._size = 100, + this._align = "center", + this.hasBeenReset = !1, + this._startTime = e, + this._endTime = t, + this._text = i + } + get id() { + return this._id + } + set id(e) { + this._id = "" + e + } + get pauseOnExit() { + return this._pauseOnExit + } + set pauseOnExit(e) { + this._pauseOnExit = !!e + } + get startTime() { + return this._startTime + } + set startTime(e) { + if ("number" != typeof e) + throw new TypeError(`Start time must be set to a number: ${e}`); + this._startTime = e, + this.hasBeenReset = !0 + } + get endTime() { + return this._endTime + } + set endTime(e) { + if ("number" != typeof e) + throw new TypeError(`End time must be set to a number: ${e}`); + this._endTime = e, + this.hasBeenReset = !0 + } + get text() { + return this._text + } + set text(e) { + this._text = "" + e, + this.hasBeenReset = !0 + } + get region() { + return this._region + } + set region(e) { + this._region = e, + this.hasBeenReset = !0 + } + get vertical() { + return this._vertical + } + set vertical(e) { + if (!ip.isValidDirectionSetting(e)) + throw new SyntaxError(`An invalid or illegal string was specified for vertical: ${e}`); + this._vertical = e, + this.hasBeenReset = !0 + } + get snapToLines() { + return this._snapToLines + } + set snapToLines(e) { + this._snapToLines = !!e, + this.hasBeenReset = !0 + } + get line() { + return this._line + } + set line(e) { + if (!ip.isValidLineAndPositionSetting(e)) + throw new SyntaxError(`An invalid number or illegal string was specified for line: ${e}`); + this._line = e, + this.hasBeenReset = !0 + } + get lineAlign() { + return this._lineAlign + } + set lineAlign(e) { + if (!ip.isValidLineAlignSetting(e)) + throw new SyntaxError(`An invalid or illegal string was specified for lineAlign: ${e}`); + this._lineAlign = e, + this.hasBeenReset = !0 + } + get position() { + return this._position + } + set position(e) { + if (!ip.isValidLineAndPositionSetting(e)) + throw new Error(`Position must be between 0 and 100 or auto: ${e}`); + this._position = e, + this.hasBeenReset = !0 + } + get positionAlign() { + return this._positionAlign + } + set positionAlign(e) { + if (!ip.isValidPositionAlignSetting(e)) + throw new SyntaxError(`An invalid or illegal string was specified for positionAlign: ${e}`); + this._positionAlign = e, + this.hasBeenReset = !0 + } + get size() { + return this._size + } + set size(e) { + if (e < 0 || 100 < e) + throw new Error(`Size must be between 0 and 100: ${e}`); + this._size = e, + this.hasBeenReset = !0 + } + get align() { + return this._align + } + set align(e) { + if (!ip.isValidAlignSetting(e)) + throw new SyntaxError(`An invalid or illegal string was specified for align: ${e}`); + this._align = e, + this.hasBeenReset = !0 + } + getCueAsHTML() { + return rp.default.parseContent(window, this, {}) + } + static create(t) { + if (!t.hasOwnProperty("startTime") || !t.hasOwnProperty("endTime") || !t.hasOwnProperty("text")) + throw new Error("You must at least have start time, end time, and text."); + const i = new this(t.startTime,t.endTime,t.text); + return Object.keys(t).forEach(e=>{ + i.hasOwnProperty(e) && (i[e] = t[e]) + } + ), + i + } + static fromJSON(e) { + return this.create(JSON.parse(e)) + } + toJSON() { + const t = {}; + return Object.keys(this).forEach(e=>{ + this.hasOwnProperty(e) && "getCueAsHTML" !== e && "hasBeenReset" !== e && "displayState" !== e && (t[e] = this[e]) + } + ), + t + } + } + ); + gr.VTTCue = gc; + gc = {}, + e = e && e.__decorate || function(e, t, i, r) { + var n, s = arguments.length, a = s < 3 ? t : null === r ? r = Object.getOwnPropertyDescriptor(t, i) : r; + if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) + a = Reflect.decorate(e, t, i, r); + else + for (var o = e.length - 1; 0 <= o; o--) + (n = e[o]) && (a = (s < 3 ? n(a) : 3 < s ? n(t, i, a) : n(t, i)) || a); + return 3 < s && a && Object.defineProperty(t, i, a), + a + } + ; + Object.defineProperty(gc, "__esModule", { + value: !0 + }); + const np = t; + e = e([function(e) { + let t = e; + return "undefined" != typeof window && null != window.VTTRegion && (t = window.VTTRegion, + t.create = e.create, + t.fromJSON = e.fromJSON, + t.prototype.toJSON = e.prototype.toJSON), + t + } + ], e = class { + constructor() { + this._id = "", + this._lines = 3, + this._regionAnchorX = 0, + this._regionAnchorY = 100, + this._scroll = "", + this._viewportAnchorX = 0, + this._viewportAnchorY = 100, + this._width = 100 + } + get id() { + return this._id + } + set id(e) { + if ("string" != typeof e) + throw new Error("ID must be a string."); + this._id = e + } + get lines() { + return this._lines + } + set lines(e) { + if ("number" != typeof e) + throw new TypeError("Lines must be set to a number."); + this._lines = e + } + get regionAnchorX() { + return this._regionAnchorX + } + set regionAnchorX(e) { + if (!np.isValidPercentValue(e)) + throw new TypeError("RegionAnchorX must be between 0 and 100."); + this._regionAnchorX = e + } + get regionAnchorY() { + return this._regionAnchorY + } + set regionAnchorY(e) { + if (!np.isValidPercentValue(e)) + throw new TypeError("RegionAnchorY must be between 0 and 100."); + this._regionAnchorY = e + } + get scroll() { + return this._scroll + } + set scroll(e) { + if ("string" == typeof e) { + e = e.toLowerCase(); + if (np.isValidScrollSetting(e)) + return void (this._scroll = e) + } + throw new SyntaxError("An invalid or illegal string was specified.") + } + get viewportAnchorX() { + return this._viewportAnchorX + } + set viewportAnchorX(e) { + if (!np.isValidPercentValue(e)) + throw new TypeError("ViewportAnchorX must be between 0 and 100."); + this._viewportAnchorX = e + } + get viewportAnchorY() { + return this._viewportAnchorY + } + set viewportAnchorY(e) { + if (!np.isValidPercentValue(e)) + throw new TypeError("ViewportAnchorY must be between 0 and 100."); + this._viewportAnchorY = e + } + get width() { + return this._width + } + set width(e) { + if (!np.isValidPercentValue(e)) + throw new TypeError("Width must be between 0 and 100."); + this._lines = e + } + toJSON() { + const t = {}; + return Object.keys(this).forEach(e=>{ + this.hasOwnProperty(e) && (t[e] = this[e]) + } + ), + t + } + static create(t) { + const i = new this; + return Object.keys(t).forEach(e=>{ + i.hasOwnProperty(e) && (i[e] = t[e]) + } + ), + i + } + static fromJSON(e) { + return this.create(JSON.parse(e)) + } + } + ); + gc.VTTRegion = e, + Object.defineProperty(mu, "__esModule", { + value: !0 + }); + const sp = gr; + mu.VTTCue = sp.VTTCue; + const ap = gc; + mu.VTTRegion = ap.VTTRegion; + const op = yc; + class dp extends Error { + constructor(e, t) { + super(), + this.name = "ParsingError", + this.code = "number" == typeof e ? e : e.code, + t ? this.message = t : e instanceof dp && (this.message = e.message) + } + } + (mu.ParsingError = dp).Errors = { + BadSignature: new dp(0,"Malformed WebVTT signature."), + BadTimeStamp: new dp(1,"Malformed time stamp.") + }; + class lp { + constructor() { + this.values = {} + } + set(e, t) { + this.get(e) || "" === t || (this.values[e] = t) + } + get(e, t, i) { + return "object" == typeof t && "string" == typeof i ? this.has(e) ? this.values[e] : t[i] : this.has(e) ? this.values[e] : t + } + has(e) { + return e in this.values + } + alt(t, i, r) { + for (let e = 0; e < r.length; ++e) + if (i === r[e]) { + this.set(t, i); + break + } + } + integer(e, t) { + /^-?\d+$/.test(t) && this.set(e, parseInt(t, 10)) + } + percent(e, t) { + if (t.match(/^([\d]{1,3})(\.[\d]*)?%$/)) + try { + var i = parseFloat(t); + if (0 <= i && i <= 100) + return this.set(e, i), + !0 + } catch (e) { + return !1 + } + return !1 + } + } + class up { + constructor(e, t, i) { + this.window = e, + this.state = "INITIAL", + this.styleCollector = "", + this.buffer = "", + this.decoder = t || new TextDecoder("utf8"), + this.regionList = [], + this.onStylesParsedCallback = i, + this._styles = {} + } + static StringDecoder() { + return { + decode: e=>{ + if (!e) + return ""; + if ("string" != typeof e) + throw new Error("Error - expected string data."); + return decodeURIComponent(encodeURIComponent(e)) + } + } + } + reportOrThrowError(e) { + if (!(e instanceof dp && "function" == typeof this.onparsingerror)) + throw e; + this.onparsingerror(e) + } + parseOptions(e, t, i, r) { + e = r ? e.split(r) : [e]; + for (const n of e) + if ("string" == typeof n) { + const r = n.split(i); + 2 === r.length && t(r[0], r[1]) + } + } + parseCue(t, e, a) { + const i = t + , r = ()=>{ + var e = op.default.parseTimeStamp(t); + if (null === e) + throw new dp(dp.Errors.BadTimeStamp,"Malformed timestamp: " + i); + return t = t.replace(/^[^\sa-zA-Z-]+/, ""), + e + } + , n = ()=>{ + t = t.replace(/^\s+/, "") + } + ; + if (n(), + e.startTime = r(), + n(), + "--\x3e" !== t.substr(0, 3)) + throw new dp(dp.Errors.BadTimeStamp,`Malformed time stamp (time stamps must be separated by '--\x3e'): ${i}`); + t = t.substr(3), + n(), + e.endTime = r(), + n(), + ((e,t)=>{ + const s = new lp; + this.parseOptions(e, (t,i)=>{ + let e, r; + switch (t) { + case "region": + for (let e = a.length - 1; 0 <= e; e--) + if (a[e].id === i) { + s.set(t, a[e].region); + break + } + break; + case "vertical": + s.alt(t, i, ["rl", "lr"]); + break; + case "line": + e = i.split(","), + r = e[0], + s.integer(t, r), + s.percent(t, r) && s.set("snapToLines", !1), + s.alt(t, r, ["auto"]), + 2 === e.length && s.alt("lineAlign", e[1], ["start", "center", "end"]); + break; + case "position": + e = i.split(","), + s.percent(t, e[0]), + 2 === e.length && (n = ["line-left", "line-right", "center", "auto", "left", "start", "middle", "end", "right"], + s.alt("positionAlign", e[1], n)); + break; + case "size": + s.percent(t, i); + break; + case "align": + var n = ["start", "center", "end", "left", "right", "middle"]; + s.alt(t, i, n) + } + } + , /:/, /\s/), + t.region = s.get("region", null), + t.vertical = s.get("vertical", ""), + t.line = s.get("line", void 0 === t.line ? "auto" : t.line), + t.lineAlign = s.get("lineAlign", "start"), + t.snapToLines = s.get("snapToLines", !0), + t.size = s.get("size", 100); + e = s.get("align", "center"); + t.align = "middle" === e ? "center" : e, + t.position = s.get("position", "auto"); + e = s.get("positionAlign", { + start: "start", + left: "start", + center: "center", + right: "end", + end: "end" + }, t.align); + t.positionAlign = { + start: "start", + "line-left": "start", + left: "start", + center: "center", + middle: "center", + "line-right": "end", + right: "end", + end: "end" + }[e] + } + )(t, e) + } + parseRegion(e) { + const n = new lp; + if (this.parseOptions(e, (e,t)=>{ + switch (e) { + case "id": + n.set(e, t); + break; + case "width": + n.percent(e, t); + break; + case "lines": + n.integer(e, t); + break; + case "regionanchor": + case "viewportanchor": + { + var i = t.split(","); + if (2 !== i.length) + break; + const r = new lp; + if (r.percent("x", i[0]), + r.percent("y", i[1]), + !r.has("x") || !r.has("y")) + break; + n.set(e + "X", r.get("x")), + n.set(e + "Y", r.get("y")); + break + } + case "scroll": + n.alt(e, t, ["up"]) + } + } + , /=/, /\s/), + n.has("id")) { + const e = new ap.VTTRegion; + e.width = n.get("width", 100), + e.lines = n.get("lines", 3), + e.regionAnchorX = n.get("regionanchorX", 0), + e.regionAnchorY = n.get("regionanchorY", 100), + e.viewportAnchorX = n.get("viewportanchorX", 0), + e.viewportAnchorY = n.get("viewportanchorY", 100), + e.scroll = n.get("scroll", ""), + this.onregion && this.onregion(e), + this.regionList.push({ + id: n.get("id"), + region: e + }) + } + } + parseStyle(i) { + const e = i.split("}"); + e.pop(); + for (const i of e) { + let e = null + , t = null; + const r = i.split("{"); + r[0] && (e = r[0].trim()), + r[1] && (t = (e=>{ + const t = {} + , i = e.split(";"); + for (let e = 0; e < i.length; e++) + if (i[e].includes(":")) { + const r = i[e].split(":", 2) + , n = r[0].trim() + , s = r[1].trim(); + "" !== n && "" !== s && (t[n] = s) + } + return t + } + )(r[1])), + e && t && (this._styles[e] = t) + } + this.onStylesParsedCallback && this.onStylesParsedCallback(this._styles) + } + parseHeader(e) { + this.parseOptions(e, function(e, t) { + "Region" === e && this.parseRegion(t) + }, /:/) + } + parse(i) { + i && (this.buffer += this.decoder.decode(i, { + stream: !0 + })); + const r = ()=>{ + const e = this.buffer; + let t = 0; + let i = { + start: e.length, + length: 0 + }; + for (; t < e.length; ) { + const r = ((t,i)=>{ + const r = { + start: -1, + length: -1 + }; + if ("\r" === t[i]) + r.start = i, + r.length = 1; + else if ("\n" === t[i]) + r.start = i, + r.length = 1; + else if ("<" === t[i] && i + 1 < t.length && "b" === t[i + 1] && i + 2 < t.length && "r" === t[i + 2]) { + let e = i + 2; + for (; e < t.length && ">" !== t[e++]; ) + ; + r.start = i, + r.length = e - i + } + return r + } + )(e, t); + if (0 < r.length) { + i = r; + break + } + ++t + } + const r = e.substr(0, i.start); + return this.buffer = e.substr(i.start + i.length), + r + } + ; + try { + let e; + if ("INITIAL" === this.state) { + if (!/\r\n|\n/.test(this.buffer)) + return this; + e = r(); + var n = /^()?WEBVTT([ \t].*)?$/.exec(e); + if (!n || !n[0]) + throw new dp(dp.Errors.BadSignature); + this.state = "HEADER" + } + let t = !1; + for (; this.buffer; ) { + if (!/\r\n|\n/.test(this.buffer)) + return this; + switch (t ? t = !1 : e = r(), + this.state) { + case "HEADER": + e.includes(":") ? this.parseHeader(e) : e || (this.state = "ID"); + continue; + case "NOTE": + e || (this.state = "ID"); + continue; + case "STYLE": + e ? this.styleCollector += e : (this.parseStyle(this.styleCollector), + this.state = "ID", + this.styleCollector = ""); + continue; + case "ID": + if (/^NOTE($|[ \t])/.test(e)) { + this.state = "NOTE"; + break + } + if (/^STYLE($|[ \t])/.test(e)) { + this.state = "STYLE"; + break + } + if (!e) + continue; + if (this.cue = new sp.VTTCue(0,0,""), + this.state = "CUE", + !e.includes("--\x3e")) { + this.cue.id = e; + continue + } + case "CUE": + try { + this.parseCue(e, this.cue, this.regionList) + } catch (i) { + this.reportOrThrowError(i), + this.cue = null, + this.state = "BADCUE"; + continue + } + this.state = "CUETEXT"; + continue; + case "CUETEXT": + { + const r = e.includes("--\x3e"); + if (!e || r) { + t = !0, + this.oncue && this.oncue(this.cue), + this.cue = null, + this.state = "ID"; + continue + } + this.cue.text && (this.cue.text += "\n"), + this.cue.text += e; + continue + } + case "BADCUE": + e || (this.state = "ID"); + continue + } + } + } catch (i) { + this.reportOrThrowError(i), + "CUETEXT" === this.state && this.cue && this.oncue && this.oncue(this.cue), + this.cue = null, + this.state = "INITIAL" === this.state ? "BADWEBVTT" : "BADCUE" + } + return this + } + flush() { + try { + if (this.buffer += this.decoder.decode(), + !this.cue && "HEADER" !== this.state || (this.buffer += "\n\n", + this.parse()), + "INITIAL" === this.state) + throw new dp(dp.Errors.BadSignature) + } catch (e) { + this.reportOrThrowError(e) + } + return this.onflush && this.onflush(), + this + } + styles() { + return this._styles + } + } + mu.default = up, + mu.WebVTTParser = up; + var cp, gc = {}; + Object.defineProperty(gc, "__esModule", { + value: !0 + }); + const hp = gr; + gc.VTTCue = hp.VTTCue; + const pp = yc + , fp = [/^(::cue\()(\..*)(\))/, /^(::cue\()(#.*)(\))/, /^(::cue\()(c|i|b|u|ruby|rt|v|lang)(\))/] + , mp = [[1470, 1470], [1472, 1472], [1475, 1475], [1478, 1478], [1488, 1514], [1520, 1524], [1544, 1544], [1547, 1547], [1549, 1549], [1563, 1563], [1566, 1610], [1645, 1647], [1649, 1749], [1765, 1766], [1774, 1775], [1786, 1805], [1807, 1808], [1810, 1839], [1869, 1957], [1969, 1969], [1984, 2026], [2036, 2037], [2042, 2042], [2048, 2069], [2074, 2074], [2084, 2084], [2088, 2088], [2096, 2110], [2112, 2136], [2142, 2142], [2208, 2208], [2210, 2220], [8207, 8207], [64285, 64285], [64287, 64296], [64298, 64310], [64312, 64316], [64318, 64318], [64320, 64321], [64323, 64324], [64326, 64449], [64467, 64829], [64848, 64911], [64914, 64967], [65008, 65020], [65136, 65140], [65142, 65276], [67584, 67589], [67592, 67592], [67594, 67637], [67639, 67640], [67644, 67644], [67647, 67669], [67671, 67679], [67840, 67867], [67872, 67897], [67903, 67903], [67968, 68023], [68030, 68031], [68096, 68096], [68112, 68115], [68117, 68119], [68121, 68147], [68160, 68167], [68176, 68184], [68192, 68223], [68352, 68405], [68416, 68437], [68440, 68466], [68472, 68479], [68608, 68680], [126464, 126467], [126469, 126495], [126497, 126498], [126500, 126500], [126503, 126503], [126505, 126514], [126516, 126519], [126521, 126521], [126523, 126523], [126530, 126530], [126535, 126535], [126537, 126537], [126539, 126539], [126541, 126543], [126545, 126546], [126548, 126548], [126551, 126551], [126553, 126553], [126555, 126555], [126557, 126557], [126559, 126559], [126561, 126562], [126564, 126564], [126567, 126570], [126572, 126578], [126580, 126583], [126585, 126588], [126590, 126590], [126592, 126601], [126603, 126619], [126625, 126627], [126629, 126633], [126635, 126651], [1114109, 1114109]]; + class gp { + applyStyles(e, t) { + t = t || this.div; + for (const i in e) + e.hasOwnProperty(i) && (t.style[i] = e[i]) + } + formatStyle(e, t) { + return 0 === e ? "0" : e + t + } + } + gc.StyleBox = gp; + class yp extends gp { + constructor(e, t, i, r, n) { + super(); + let s = { + textAlign: { + start: "left", + "line-left": "left", + left: "left", + center: "center", + middle: "center", + "line-right": "right", + right: "right", + end: "right" + }[(this.cue = t).positionAlign] || t.align, + whiteSpace: "pre-line", + position: "absolute" + }; + s.direction = this.determineBidi(this.cueDiv), + s.writingMode = this.directionSettingToWritingMode(t.vertical), + s.unicodeBidi = "plaintext", + this.div = e.document.createElement("div"), + this.applyStyles(s), + s = { + backgroundColor: r.backgroundColor, + display: "inline-block" + }, + this.parseOpacity(s.backgroundColor) && (s.padding = "5px", + s.borderRadius = "5px"), + this.backgroundDiv = e.document.createElement("div"), + this.applyStyles(s, this.backgroundDiv), + s = { + color: i.color, + backgroundColor: i.backgroundColor, + textShadow: i.textShadow, + fontSize: i.fontSize, + fontFamily: i.fontFamily, + position: "relative", + left: "0", + right: "0", + top: "0", + bottom: "0", + display: "inline-block", + textOrientation: "upright" + }, + s.writingMode = this.directionSettingToWritingMode(t.vertical), + s.unicodeBidi = "plaintext", + this.cueDiv = pp.default.parseContent(e, t, n), + this.applyStyles(s, this.cueDiv), + this.backgroundDiv.appendChild(this.cueDiv), + this.div.appendChild(this.backgroundDiv); + let a = 0; + if ("number" == typeof t.position) { + n = t.positionAlign || t.align; + if (n) + switch (n) { + case "start": + case "left": + a = t.position; + break; + case "center": + case "middle": + a = t.position - t.size / 2; + break; + case "end": + case "right": + a = t.position - t.size + } + } + "" === t.vertical ? this.applyStyles({ + left: this.formatStyle(a, "%"), + width: this.formatStyle(t.size, "%") + }) : this.applyStyles({ + top: this.formatStyle(a, "%"), + height: this.formatStyle(t.size, "%") + }) + } + determineBidi(e) { + let t = [] + , i = ""; + if (!e || !e.childNodes) + return "ltr"; + function n(t, i) { + for (let e = i.childNodes.length - 1; 0 <= e; e--) + t.push(i.childNodes[e]) + } + for (n(t, e); i = function e(t) { + if (!t || !t.length) + return null; + let i = t.pop() + , r = i.textContent || i.innerText; + if (r) { + const i = /^.*(\n|\r)/.exec(r); + return i ? i[t.length = 0] : r + } + return "ruby" === i.tagName ? e(t) : i.childNodes ? (n(t, i), + e(t)) : void 0 + }(t); ) + for (let e = 0; e < i.length; e++) + if (function(e, t) { + for (const i of t) + if (e >= i[0] && e <= i[1]) + return 1 + }(i.charCodeAt(e), mp)) + return "rtl"; + return "ltr" + } + parseOpacity(e) { + if (!e || "string" != typeof e) + return null; + e = (e = e.replace(/ /g, "").replace("rgba(", "").replace(")", "")).split(","); + return e && 4 <= e.length ? e[3] : null + } + directionSettingToWritingMode(e) { + return "" === e ? "horizontal-tb" : "lr" === e ? "vertical-lr" : "vertical-rl" + } + move(e) { + this.applyStyles({ + top: this.formatStyle(e.top, "px"), + bottom: this.formatStyle(e.bottom, "px"), + left: this.formatStyle(e.left, "px"), + right: this.formatStyle(e.right, "px"), + height: this.formatStyle(e.height, "px"), + width: this.formatStyle(e.width, "px") + }) + } + } + gc.CueStyleBox = yp; + class vp { + constructor(e) { + var t; + let i, r, n, s, a, o; + if (e instanceof yp && e.cue ? (t = e.cue) && "" !== t.vertical ? this.property = "width" : this.property = "height" : e instanceof vp && (this.property = e.property || "height"), + e instanceof yp && e.div) { + n = e.div.offsetHeight, + s = e.div.offsetWidth, + a = e.div.offsetTop; + const t = e.div.firstChild; + if (o = (t || e.div).getBoundingClientRect(), + i = o && o[this.property] || null, + t && t.firstChild) { + const e = t.firstChild; + e && "string" == typeof e.textContent && (r = i / this.calculateNewLines(e.textContent)) + } + } else + e instanceof vp && (o = e); + this.left = o.left, + this.right = o.right, + this.top = o.top || a, + this.height = o.height || n, + this.bottom = o.bottom || a + (o.height || n), + this.width = o.width || s, + this.lineHeight = null !== i ? i : o.lineHeight, + this.singleLineHeight = null !== r ? r : o.singleLineHeight, + this.singleLineHeight || (this.singleLineHeight = 41) + } + calculateNewLines(t) { + let i = 1; + for (let e = 0; e < t.length; e++) + "\n" === t[e] && i++; + return i + } + move(e, t) { + switch (t = void 0 !== t ? t : this.singleLineHeight, + e) { + case "+x": + this.left += t, + this.right += t; + break; + case "-x": + this.left -= t, + this.right -= t; + break; + case "+y": + this.top += t, + this.bottom += t; + break; + case "-y": + this.top -= t, + this.bottom -= t + } + } + overlaps(e) { + return this.left < e.right && this.right > e.left && this.top < e.bottom && this.bottom > e.top + } + overlapsAny(e) { + for (const t of e) + if (this.overlaps(t)) + return !0; + return !1 + } + within(e) { + return this.top >= e.top && this.bottom <= e.bottom && this.left >= e.left && this.right <= e.right + } + moveIfOutOfBounds(e, t) { + switch (t) { + case "+x": + this.left < e.left && (this.left = e.left, + this.right = this.left + this.width); + break; + case "-x": + this.right > e.right && (this.right = e.right, + this.left = this.right - this.width); + break; + case "+y": + this.top < e.top && (this.top = e.top, + this.bottom = this.top + this.height); + break; + case "-y": + this.bottom > e.bottom && (this.bottom = e.bottom, + this.top = this.bottom - this.height) + } + } + toCSSCompatValues(e) { + return { + top: this.top - e.top, + bottom: e.bottom - this.bottom, + left: this.left - e.left, + right: e.right - this.right, + height: this.height, + width: this.width + } + } + static getSimpleBoxPosition(e) { + let t = null; + e instanceof gp && e.div ? t = e.div : e instanceof HTMLElement && (t = e); + let i = t.offsetHeight || 0 + , r = t.offsetWidth || 0 + , n = t.offsetTop || 0 + , s = n + i + , a = t.getBoundingClientRect(); + var {left: o, right: e} = a; + return a.top && (n = a.top), + a.height && (i = a.height), + a.width && (r = a.width), + a.bottom && (s = a.bottom), + { + left: o, + right: e, + top: n, + height: i, + bottom: s, + width: r + } + } + static getBoxPosition(r, n) { + if (r && 0 < r.length) { + let t = 0 + , i = r[0][n]; + for (let e = 0; e < r.length; e++) + n in ["top", "right"] ? r[e][n] > i && (t = e, + i = r[e][n]) : n in ["bottom", "left"] && r[e][n] < i && (t = e, + i = r[e][n]); + return r[t] + } + return null + } + static moveToMinimumDistancePlacement(e, t, i) { + "height" === e.property ? "+y" === t ? (e.top = i.topMostBoxPosition.bottom + 0, + e.bottom = e.top + e.height) : "-y" === t && (e.bottom = +i.bottomMostBoxPosition.top, + e.top = e.bottom - e.height) : "width" === e.property && ("+x" === t ? (e.left = i.rightMostBoxPosition.right + 0, + e.right = e.left + e.width) : "-x" === t && (e.right = +i.leftMostBoxPosition.left, + e.left = e.right - e.width)) + } + static moveBoxToLinePosition(e, a, o) { + var n = e.cue; + let i, r = new vp(e), s = function() { + if ("number" == typeof n.line && (n.snapToLines || 0 <= n.line && n.line <= 100)) + return n.line; + if (!n.track || !n.track.textTrackList || !n.track.textTrackList.mediaElement) + return -1; + let t = 0; + var i = n.track + , r = i.textTrackList; + for (let e = 0; e < r.length && r[e] !== i; e++) + "showing" === r[e].mode && t++; + return -1 * ++t + }(), d = []; + if (n.snapToLines) { + let t = 0; + switch (n.vertical) { + case "": + d = ["+y", "-y"], + i = "height"; + break; + case "rl": + d = ["+x", "-x"], + i = "width"; + break; + case "lr": + d = ["-x", "+x"], + i = "width" + } + const o = r.lineHeight + , l = a[i] + o + , u = d[0]; + if (s < 0) { + let e = 0; + switch (n.vertical) { + case "": + e = a.height - o - .05 * a.height; + break; + case "rl": + case "lr": + e = -a.width + o + .05 * a.width + } + t = e, + d = d.reverse() + } else { + switch (n.vertical) { + case "": + t = o * Math.round(s); + break; + case "rl": + t = a.width - o * Math.round(s); + break; + case "lr": + t = o * Math.round(s) + } + Math.abs(t) > l && (t = t < 0 ? -1 : 1, + t *= Math.ceil(l / o) * o) + } + r.move(u, t) + } else { + const o = "" === n.vertical ? a.height : a.width + , i = r.lineHeight / o * 100; + switch (n.lineAlign) { + case "center": + s -= i / 2; + break; + case "end": + s -= i + } + switch (n.vertical) { + case "": + e.applyStyles({ + top: e.formatStyle(s, "%") + }); + break; + case "rl": + e.applyStyles({ + right: e.formatStyle(s, "%") + }); + break; + case "lr": + e.applyStyles({ + left: e.formatStyle(s, "%") + }) + } + d = ["+y", "-y", "+x", "-x"], + "+y" === n.axis ? d = ["+y", "-y", "+x", "-x"] : "-y" === n.axis && (d = ["-y", "+y", "+x", "-x"]), + r = new vp(e) + } + const l = function(r, n) { + let s; + for (let i = 0; i < n.length; i++) { + r.moveIfOutOfBounds(a, n[i]); + let e = 0 + , t = !1; + for (; r.overlapsAny(o) && !(9 < e); ) + t ? r.move(n[i]) : (o && 0 < o.length && (s = s || { + topMostBoxPosition: vp.getBoxPosition(o, "top"), + bottomMostBoxPosition: vp.getBoxPosition(o, "bottom"), + leftMostBoxPosition: vp.getBoxPosition(o, "left"), + rightMostBoxPosition: vp.getBoxPosition(o, "right") + }, + vp.moveToMinimumDistancePlacement(r, n[i], s)), + t = !0), + e++ + } + return r + }(r, d); + e.move(l.toCSSCompatValues(a)) + } + } + gc.BoxPosition = vp; + class Sp { + constructor(e, t, i=!0) { + if (!e) + return null; + this.window = e, + this.overlay = t, + this.loggingEnabled = i, + this.foregroundStyleOptions = { + fontFamily: "Helvetica", + fontSize: "36px", + color: "rgba(255, 255, 255, 1)", + textShadow: "", + backgroundColor: "rgba(0, 0, 0, 0)" + }, + this.backgroundStyleOptions = { + backgroundColor: "rgba(0, 0, 0, 0.5)" + }, + this.globalStyleCollection = {}; + const r = e.document.createElement("div"); + r.style.position = "absolute", + r.style.left = "0", + r.style.right = "0", + r.style.top = "0", + r.style.bottom = "0", + r.style.margin = "1.5%", + this.paddedOverlay = r, + t.appendChild(this.paddedOverlay), + this.initSubtitleCSS() + } + initSubtitleCSS() { + var e = [new hp.VTTCue(0,0,"String to init CSS - Won't be visible to user")]; + this.paddedOverlay.style.opacity = "0", + this.processCues(e), + this.processCues([]), + this.paddedOverlay.style.opacity = "1" + } + convertCueToDOMTree(e) { + return e ? pp.default.parseContent(this.window, e, this.globalStyleCollection) : null + } + setStyles(i) { + function r(e, t, i) { + for (const r in t) + t.hasOwnProperty(r) && (!0 === i && void 0 !== e[r] || !1 === i) && (e[r] = t[r]) + } + for (const a in i) { + let t = !1 + , e = null; + "::cue" === a ? (e = this.foregroundStyleOptions, + t = !0) : "::-webkit-media-text-track-display" === a && (e = this.backgroundStyleOptions, + t = !0); + var n = i[a]; + if (!0 === t) + r(e, n, t); + else + for (let e = 0; e < fp.length; e++) { + var s = fp[e].exec(a); + if (s && 4 === s.length) { + const i = s[2] + , o = {}; + r(o, n, t), + this.globalStyleCollection[i] = o + } + } + } + this.initSubtitleCSS(), + this.loggingEnabled && (console.log("WebVTTRenderer setStyles foregroundStyleOptions: " + JSON.stringify(this.foregroundStyleOptions)), + console.log("WebVTTRenderer setStyles backgroundStyleOptions: " + JSON.stringify(this.backgroundStyleOptions)), + console.log("WebVTTRenderer setStyles globalStyleCollection: " + JSON.stringify(this.globalStyleCollection))) + } + processCues(r) { + if (r) { + for (; this.paddedOverlay.firstChild; ) + this.paddedOverlay.removeChild(this.paddedOverlay.firstChild); + if (function(t) { + for (let e = 0; e < t.length; e++) + if (t[e].hasBeenReset || !t[e].displayState) + return 1 + }(r)) { + const n = [] + , s = vp.getSimpleBoxPosition(this.paddedOverlay); + 1 < r.length && (r = function(t) { + const i = []; + let r = 0; + for (let e = 0; e < t.length; e++) { + var n = t[e]; + if ("number" != typeof n.line) + return t; + r += n.line, + i.push(n) + } + return r /= t.length, + 50 < r ? (i.forEach(function(e) { + e.axis = "-y" + }), + i.sort((e,t)=>t.line - e.line)) : (i.forEach(function(e) { + e.axis = "+y" + }), + i.sort((e,t)=>e.line - t.line)), + i + }(r)); + for (let i = 0; i < r.length; i++) { + let e = r[i] + , t = new yp(this.window,e,this.foregroundStyleOptions,this.backgroundStyleOptions,this.globalStyleCollection); + this.paddedOverlay.appendChild(t.div), + vp.moveBoxToLinePosition(t, s, n), + e.displayState = t.div, + n.push(vp.getSimpleBoxPosition(t)) + } + } else + for (let e = 0; e < r.length; e++) + this.paddedOverlay.appendChild(r[e].displayState) + } + } + setSize(e, t) { + e && (this.overlay.style.width = e + "px"), + t && (this.overlay.style.height = t + "px") + } + getOverlay() { + return this.overlay + } + } + function bp(e) { + for (var t in e) + cp.hasOwnProperty(t) || (cp[t] = e[t]) + } + gc.default = Sp, + gc.WebVTTRenderer = Sp, + cp = zh, + Object.defineProperty(cp, "__esModule", { + value: !0 + }), + bp(mu), + bp(gc); + function Tp(e, t, i) { + return e.substr(i || 0, t.length) === t + } + function Ep(e) { + let t = 5381 + , i = e.length; + for (; i; ) + t = 33 * t ^ e.charCodeAt(--i); + return (t >>> 0).toString() + } + function Ip(e) { + var t = Math.floor(e) + , i = t + .5 + , r = t + 1; + return i <= e ? r - e <= e - i ? r : i : i - e <= e - t ? i : t + } + function wp(e, t=0, i=8589934592) { + if (!Number.isFinite(t)) + return e; + var r = i / 2 + , n = Math.abs(e - t) % i; + return t + (t < e ? -1 : 1) * (r < n ? i - n : -n) + } + var Ap, Op, kp, Cp = function(e, t, i, r, n, s, a, o) { + const d = O.utf8arrayToStr(new Uint8Array(e)).trim().replace(/\r\n|\n\r|\n|\r/g, "\n").split("\n") + , l = { + baseTime: Math.floor(9e4 * t.baseTime / t.timescale), + timescale: 9e4 + }; + let u = 0 + , c = 0; + const h = []; + let p = null + , f = !0; + const m = new zh.WebVTTParser(window,zh.WebVTTParser.StringDecoder(),a); + m.oncue = function(e) { + var t = S({ + baseTime: wp(wp(u) - l.baseTime, 9e4 * i), + timescale: 9e4 + }); + e.startTime = wp(e.startTime + t - c, 0, 95443.7176888889), + e.endTime = wp(e.endTime + t - c, 0, 95443.7176888889), + e.id = Ep(Ip(e.startTime).toString()) + Ep(Ip(e.endTime - e.startTime).toString()) + Ep(e.text), + e.text = decodeURIComponent(encodeURIComponent(e.text)), + 0 < e.endTime && h.push(e) + } + , + m.onparsingerror = function(e) { + p = e + } + , + m.onflush = function() { + p && s ? s(p) : n(h) + } + , + d.forEach(a=>f && Tp(a, "X-TIMESTAMP-MAP=") ? (f = !1, + void a.substr(16).split(",").forEach(e=>{ + if (Tp(e, "LOCAL:")) { + let t; + try { + t = (i = e.substr(6), + r = parseInt(i.substr(-3)), + n = parseInt(i.substr(-6, 2)), + s = parseInt(i.substr(-9, 2)), + i = 9 < i.length ? parseInt(i.substr(0, i.indexOf(":"))) : 0, + ne(r) && ne(n) && ne(s) && ne(i) ? (r += 1e3 * n, + r += 6e4 * s, + r += 36e5 * i) : -1) + } catch (e) { + t = -1 + } + -1 !== t ? c = t / 1e3 : p = new Error(`Malformed X-TIMESTAMP-MAP: ${a}`) + } else + Tp(e, "MPEGTS:") && (u = parseInt(e.substr(7))); + var i, r, n, s + } + )) : void m.parse(a + "\n")), + m.flush() + }, Dp = { + newCue: function(e, t, i, r, n) { + let s, a, o, d, l; + var u, c, h = { + foreground: !1, + background: !1, + italics: !1, + underline: !1, + flash: !1, + styleStack: [] + }; + for ([u,c] of r.rows.entries()) + if (a = !0, + o = 0, + d = "", + !c.isEmpty()) { + for (let e = 0; e < c.chars.length; e++) + c.chars[e].uchar.match(/\s/) && a ? o++ : (d += this.getFormattedChar(c.chars[e], h), + a = !1); + (c.cueStartTime = t) === i && (i += 1e-4), + d = d.trim().replace(//gi, "\n"), + d += this.closeStyles(h), + s = new zh.VTTCue(t,i,d), + 16 <= o ? o-- : o++, + l = !navigator.userAgent.match(/Firefox\//) && 7 < u ? u : u + 1, + s.snapToLines = !1, + s.line = 10 + 5.33 * l, + s.align = "left", + s.position = this.getPosition(o, n), + e.addCue(s) + } + }, + getPosition: function(e, t) { + let i = 1.3333333333333333; + t && t.offsetWidth && t.offsetHeight && 1.6 <= t.offsetWidth / t.offsetHeight && (i = 1.7777777777777777); + let r = 10 + e / 32 * 80 + , n = 10 + , s = 90; + return 1.7777777777777777 === i && (r = 12.5 + .75 * r, + n = 20, + s = 80), + Math.max(n, Math.min(s, r + (navigator.userAgent.match(/Firefox\//) ? 50 : 0))) + }, + getRootStyleTag: function(e) { + var t = e[0]; + return "c" === t ? t : e + }, + closeStyles: function(t) { + let i = ""; + for (let e = t.styleStack.length - 1; 0 <= e; --e) + i += "", + t.styleStack.pop(); + return i + }, + beginStyleAndBalance: function(e, t) { + let i = ""; + return "c" === t[0] && (i += this.closeStyleAndBalance(e, "c")), + i += "<" + t + ">", + e.styleStack.push(t), + i + }, + closeStyleAndBalance: function(t, i) { + var r = t.styleStack.length; + let n = 0 + , s = ""; + for (let e = r - 1; 0 <= e; --e) { + var a = t.styleStack[e] + , o = this.getRootStyleTag(a); + if (i[0] === a[0]) { + s += "", + t.styleStack.splice(r - 1 - n); + break + } + "c" === o[0] ? (t.background = "", + t.foreground = "", + t.flash = !1, + s += "") : "u" === o[0] ? (t.underline = !1, + s += "") : "i" === o[0] && (t.italics = !1, + s += ""), + n++ + } + return s + }, + getFormattedChar: function(e, t) { + let i = "" + , r = e.uchar + , n = ""; + var s = e.penState.foreground !== t.foreground + , a = e.penState.background !== t.background + , o = e.penState.flash !== t.flash; + return (s || a || o) && (n = "." + e.penState.foreground, + n += ".bg_" + e.penState.background, + e.penState.flash && o && (n += ".blink"), + e.penState.foreground || e.penState.background || e.penState.blink ? i += this.beginStyleAndBalance(t, "c" + n) : i += this.closeStyleAndBalance(t, "c"), + s && (t.foreground = e.penState.foreground), + a && (t.background = e.penState.background), + o && (t.flash = e.penState.flash)), + e.penState.underline !== t.underline && (i += e.penState.underline ? this.beginStyleAndBalance(t, "u") : this.closeStyleAndBalance(t, "u"), + t.underline = e.penState.underline), + e.penState.italics !== t.italics && (i += e.penState.italics ? this.beginStyleAndBalance(t, "i") : this.closeStyleAndBalance(t, "i"), + t.italics = e.penState.italics), + i + r + } + }; + (gc = Ap = Ap || {}).CloseEnough = "CloseEnough", + gc.TooFar = "TooFar", + gc.Unknown = "Unknown"; + const Mp = e=>"cc1" === e || "cc2" === e; + function Pp(t) { + const i = []; + for (let e = 0; e < t.length; e++) { + var r = t[e]; + ("captions" === r.kind || "subtitles" === r.kind || "metadata" === r.kind && r.customTextTrackCueRenderer) && i.push(r) + } + return i + } + function xp(e) { + if (e && e.cues) + for (; 0 < e.cues.length; ) + e.removeCue(e.cues[0]) + } + class Rp extends Ut { + constructor(e, t, i, r) { + super(e=>{ + const t = wc(this.hls, this); + if (e.add(t.event(x.INLINE_STYLES_PARSED, this.onInlineStylesParsed).pipe($s(()=>this.destroy())).subscribe()), + e.add(vn(0, this.config.trottleCheckInterval).pipe(Ra(()=>(this.checkReadyToLoadNextSubtitleFragment(), + Ul))).subscribe()), + this.mediaSink.textTracks && "onchange"in this.mediaSink.textTracks) { + const t = wc(this.mediaSink.textTracks, this); + e.add(t.event("change", this._onTextTracksChanged).subscribe()) + } else + e.add(vn(0, 500).pipe(Ra(()=>(this._onTextTracksChanged(), + Ul))).subscribe()) + } + ), + this.config = t, + this.hls = i, + this.logger = r.child({ + name: "legible" + }), + this.mediaSink = e, + this.enableCaption = !0, + this.Cues = Dp, + this.tracks = [], + this.cueRanges = [], + this.channelToTrackMap = {}, + this.htmlTextTrackMap = new Map, + this.lastCueEndTime = 0, + this.gotTracks = !1, + this.tryAgain$ = new gi(!0), + this.needNextSubtitle$ = new gi(!0) + } + destroy() { + xp(this.textTrack1), + xp(this.textTrack2), + this.mediaSink = void 0, + this.nativeSubtitleTrackChange$ = void 0 + } + convertCuesIntoSubtitleFragInfo(t) { + const i = {}; + if (null != t && 0 < t.length) + for (let e = 0; e < t.length; e++) { + var r = t[e]; + if (ne(r.fragSN)) { + const n = i[r.fragSN]; + n ? (n.count++, + n.startTime = Math.min(r.startTime, n.startTime), + n.endTime = Math.max(r.endTime, n.endTime)) : i[r.fragSN] = { + count: 1, + startTime: r.startTime, + endTime: r.endTime + } + } + } + return i + } + checkReadyToLoadNextSubtitleFragment() { + let e = !1; + this.mediaSink.mediaQuery.currentTime >= this.lastCueEndTime - this.config.subtitleLeadTime && (e = !0), + this.needNextSubtitle$.next(e) + } + checkReadyToLoadNextSubtitleFragment$() { + return this.checkReadyToLoadNextSubtitleFragment(), + this.needNextSubtitle$ + } + getNextFragment(e, t) { + t = t.mediaSeqNum + 1; + return t < e.fragments.length ? e.fragments[t - e.startSN] : null + } + calculateFragInfoMap(e, t, i, r) { + var n = this.convertCuesIntoSubtitleFragInfo(t); + let s = { + len: 0, + start: e, + end: e + } + , a = e + , o = e + , d = null + , l = null; + for (const t in n) + if (Object.prototype.hasOwnProperty.call(n, t)) { + var u = Number(t); + if (ne(u)) { + var c = n[u]; + if (this.isFragmentComplete(u, c.count, i)) + if (u === r.startSN && e < c.startTime && (a = o = s.start = s.end = e = c.startTime), + e >= c.startTime && (a === e || ne(d) && 1 < u - d) && (a = o = c.startTime), + e >= c.startTime) + o = c.endTime, + d = u; + else { + if (!ne(d) || u - d != 1) { + l = u; + break + } + o = c.endTime, + d = u + } + } else + this.logger.warn(`$fragInfoMap has invalid key ${u}`) + } + return s = { + len: o - a, + start: a, + end: o + }, + { + fragInfoMap: n, + bufferInfo: s, + prevFragSN: d, + nextFragSN: l + } + } + findFrags$(t, i) { + return this.tryAgain$.pipe(Hi(Zi), Ra(()=>{ + var e = this.findFragmentsForPosition(this.mediaSink.mediaQuery.currentTime, i, t); + return e.foundFrags ? (this.lastCueEndTime = 0, + this.needNextSubtitle$.next(!0), + Bi(e)) : Ti + } + )) + } + reviewParsedFrag(e, i, r) { + var n = e.frag + , s = e.cueRange + , t = i.subtitleBufferInfo + , a = i.subtitleParsedInfo + , o = this.mediaSink.mediaQuery.currentTime + , e = i.foundFrags; + let d = !0; + if (n.mediaSeqNum === e[0].mediaSeqNum) { + if (!i.timelineEstablished) + return Ap.TooFar; + if (!s) + return this.logger.warn(`[subtitle] 1st frag sn ${n.mediaSeqNum} has no cue; details ${r.fragments.length} frags`), + Ap.Unknown; + if (s.startTime < o) { + const l = r.fragments + , i = n.mediaSeqNum - r.startSN; + let e = i + , t = s.startTime; + for (; e < l.length && (t += l[e].duration, + !(t >= o)); ++e) + ; + d = e - i + 1 <= this.config.earlyFragTolerance + } else if (s.startTime > o && n.mediaSeqNum !== r.startSN) { + const l = t.prevFragSN; + if (n.mediaSeqNum === l + 1 && (null === (t = t.fragInfoMap[l]) || void 0 === t ? void 0 : t.count) === (null === (a = a[l]) || void 0 === a ? void 0 : a.count)) + d = !0; + else { + const l = r.fragments[n.mediaSeqNum - r.startSN - 1]; + d = s.startTime - o < l.duration + } + } + } + return d ? Ap.CloseEnough : Ap.TooFar + } + isFragmentComplete(e, t, i) { + e = i ? i[e] : null; + return (null == e ? void 0 : e.count) === t + } + getEarlierFragmentInSameDisco(e, t, i) { + var r = t.mediaSeqNum - e.startSN - 1; + if (r < 0 || r > e.fragments.length - 1) + return this.logger.error(`[subtitle] getEarlierFragmentInSameDisco index ${r} out of range`), + t; + r = e.fragments[r]; + return r && r.discoSeqNum === t.discoSeqNum && !i[t.mediaSeqNum] ? r : t + } + inferSubtitleFragmentForPosition(i, r, t, e, n) { + let s, a, o, d, l; + if (ne(e.prevFragSN) && (a = e.prevFragSN - n.startSN, + o = t[e.prevFragSN]), + ne(e.nextFragSN) && (d = e.nextFragSN - n.startSN, + l = t[e.nextFragSN]), + ne(a) && 0 <= a && a < n.fragments.length && o) { + let t = o.startTime; + for (let e = a; e < n.fragments.length; ++e) { + const o = n.fragments[e]; + if (!ne(r) || o.discoSeqNum === r) { + if (t + o.duration > i && e > a) { + s = { + foundFrag: o, + timelineEstablished: !0 + }; + break + } + t += o.duration + } + } + } else if (ne(d) && 0 <= d && d < n.fragments.length && l) { + let t = l.startTime; + for (let e = d - 1; 0 <= e; --e) { + const a = n.fragments[e]; + if (!ne(r) || a.discoSeqNum === r) { + if (t <= i) { + s = { + foundFrag: a, + timelineEstablished: !0 + }; + break + } + t -= a.duration + } + } + } else + for (let e = 0; e < n.fragments.length; ++e) { + const t = n.fragments[e]; + if (ne(r) && t.discoSeqNum === r) { + s = { + foundFrag: t, + timelineEstablished: !1 + }; + break + } + } + return s + } + generateFragmentBatch(t, i, e, r, n, s) { + var a; + const o = [] + , d = null == e ? void 0 : e.foundFrag; + if (!d) + return { + foundFrags: void 0, + subtitleParsedInfo: void 0, + subtitleBufferInfo: void 0, + timelineEstablished: null == e ? void 0 : e.timelineEstablished + }; + for (let e = d ? d.mediaSeqNum - s.startSN : s.fragments.length; e < s.fragments.length && o.length < t; ++e) { + const t = s.fragments[e]; + if (t.discoSeqNum === i) { + const d = null === (a = n.fragInfoMap[t.mediaSeqNum]) || void 0 === a ? void 0 : a.count; + this.isFragmentComplete(t.mediaSeqNum, null != d ? d : 0, r) || o.push(t) + } + } + return { + foundFrags: o, + subtitleParsedInfo: r, + subtitleBufferInfo: n, + timelineEstablished: null == e ? void 0 : e.timelineEstablished + } + } + findFragmentsForPosition(e, t, i) { + var r = this.mediaSink.mediaQuery.getParsedSubtitleRecordsForMediaOption(this.selectedTrack.persistentID) + , n = this.getCuesOfEnabledTrack(this.selectedMediaOption.mediaOptionId, !1) + , s = this.calculateFragInfoMap(e, n, r, i) + , n = s.bufferInfo + , n = Math.max(e, n.end) + , n = this.inferSubtitleFragmentForPosition(n, t, r, s, i); + return this.generateFragmentBatch(1 / 0, t, n, r, s, i) + } + get selectedMediaOption() { + return this.selectedTrack || this._disabledMediaOption + } + set selectedMediaOption(e) { + this.selectedTrack = "groupId"in e ? e : void 0 + } + get selectedTrack() { + return this._selectedMediaOption + } + set selectedTrack(e) { + e !== this._selectedMediaOption && (this._selectedMediaOption = e, + this.updateTextTrackState()) + } + getTrack(t) { + return this._availableMediaOptions.find(e=>e.mediaOptionId === t) + } + updateTextTrackState() { + if (this.mediaSink.textTracks) { + const i = this.selectedTrack ? this.getExistingHTMLTextTrack(this.selectedTrack) : void 0 + , r = Pp(this.mediaSink.textTracks); + for (let e = 0; e < r.length; e++) { + var t = r[e]; + t === i && "showing" !== r[e].mode ? r[e].mode = "showing" : t !== i && "hidden" !== r[e].mode && (r[e].mode = "hidden") + } + } + } + mapHTMLTextTrackIndexToMediaOptionId(e) { + const i = this.mediaSink.textTracks[e]; + let r; + return this.htmlTextTrackMap.forEach((e,t)=>{ + i === e && (r = t) + } + ), + r + } + get mediaSelectionOptions() { + return this._availableMediaOptions + } + _makeDisableOption(e) { + return { + itemId: e.itemId, + mediaOptionType: e.mediaOptionType, + mediaOptionId: "Nah" + } + } + _onTextTracksChanged() { + if (this.mediaSink) { + let t, i = !1; + const r = Pp(this.mediaSink.textTracks); + for (let e = 0; e < r.length; e++) + r[e].seen ? "showing" === r[e].mode && (t = r[e].persistentId) : (r[e].seen = !0, + i = !0); + if (!i) { + const e = this.selectedTrack; + if ((null == e ? void 0 : e.persistentID) !== t) { + const e = this.mediaSelectionOptions.find(function(e) { + return e.persistentID === t + }); + this.nativeSubtitleTrackChange$.next(e || this._disabledMediaOption) + } + } + } + } + addCues(e, t, i, r) { + const n = this.cueRanges; + let s = !1; + for (let e = n.length; e--; ) { + const r = n[e] + , l = (a = r[0], + o = r[1], + d = t, + Math.min(o, i) - Math.max(a, d)); + if (0 <= l && (r[0] = Math.min(r[0], t), + r[1] = Math.max(r[1], i), + s = !0, + .5 < l / (i - t))) + return + } + var a, o, d; + s || n.push([t, i]), + this.Cues.newCue(this.channelToTrackMap[e], t, i, r, this.mediaSink) + } + getExistingHTMLTextTrackWithChannelNumber(t) { + var i = this.mediaSink; + if (i) + for (let e = 0; e < i.textTracks.length; e++) { + var r = i.textTracks[e] + , n = "cc" + t; + if (Mp(n) && !0 === r[n]) + return r + } + return null + } + sendAddTrackEvent(e, t) { + let i = null; + try { + i = new window.Event("addtrack") + } catch (e) { + i = document.createEvent("Event"), + i.initEvent("addtrack", !1, !1) + } + i.track = e, + t.dispatchEvent(i) + } + createHTMLCaptionsTrackGuts(e, t, i, r) { + var n = "cc" + e; + if (!this.channelToTrackMap[n]) { + e = this.getExistingHTMLTextTrackWithChannelNumber(e); + if (e) + this.channelToTrackMap[n] = e, + xp(this.channelToTrackMap[n]), + this.sendAddTrackEvent(this.channelToTrackMap[n], this.mediaSink); + else { + const s = this.createHTMLTextTrackGuts("captions", t, i, r); + s && Mp(n) && (s[n] = !0, + this.channelToTrackMap[n] = s) + } + } + return this.channelToTrackMap[n] + } + createHTMLCaptionsTrack(e) { + return this.createHTMLCaptionsTrackGuts(e, this.config[1 === e ? "captionsTextTrack1Label" : "captionsTextTrack2Label"], this.config.captionsTextTrack1LanguageCode, !1) + } + getExistingHTMLTextTrack(e) { + return this.config.condenseSubtitleTrack ? this.htmlTextTrackMap.get(e.persistentID) : this.htmlTextTrackMap.get(e.id) + } + getExistingHTMLTextTrackWithSubtitleTrackId(t) { + var e = this._availableMediaOptions.find(e=>e.id === t); + return e ? this.getExistingHTMLTextTrack(e) : void 0 + } + getExistingHTMLTextTrackIndex(e) { + var t = this.getExistingHTMLTextTrack(e) + , i = this.mediaSink.textTracks; + let r = -1; + for (let e = 0; e < i.length; ++e) + if (i[e] === t) { + r = e; + break + } + return r + } + setExistingHTMLTextTrack(e, t) { + return t.persistentId = e.persistentID, + this.config.condenseSubtitleTrack ? this.htmlTextTrackMap.set(e.persistentID, t) : this.htmlTextTrackMap.set(e.id, t) + } + createHTMLTextTrack(t) { + let i = this.getExistingHTMLTextTrack(t); + if (!i) { + if ("sbtl" === t.mediaType) + i = this.createHTMLTextTrackGuts("subtitles", t.name, t.lang, t.forced); + else { + let e = 1; + t.inStreamID && (e = Number(t.inStreamID.substring(2))), + i = this.createHTMLCaptionsTrackGuts(e, t.name, t.lang, !1) + } + i ? this.setExistingHTMLTextTrack(t, i) : this.logger.error(`failed to create HTML text track for track ${t.id}: persistent id ${t.persistentID} name ${t.name} lang ${t.lang} inStreamID ${t.inStreamID}`) + } + return i + } + createHTMLTextTrackGuts(t, i, r, e) { + const n = this.mediaSink; + if (n) { + let e = !1; + "metadata" !== t && this.config.customTextTrackCueRenderer && (e = !0, + t = "metadata"); + const s = n.addTextTrack(t, i, r); + return e && (s.customTextTrackCueRenderer = !0), + s + } + } + resetLoadSource() { + this.resetTracks() + } + resetTracks() { + this._cleanTracks(), + this.cueRanges = [] + } + _cleanTracks() { + var e = this.mediaSink; + if (e) { + var t = e.textTracks; + if (t) + for (let e = 0; e < t.length; e++) + xp(t[e]) + } + } + getCuesOfEnabledTrack(e, t=!1) { + let i = []; + if (t) { + const t = this._getCuesOfEnabledTrack(e); + for (let e = 0; e < t.length; e++) { + var r = t[e]; + Boolean(r.webVTTCue) && i.push(r) + } + } else + i = this._getCuesOfEnabledTrack(e); + return i + } + _getCuesOfEnabledTrack(e) { + e = this.getTrack(e), + e = this.config.condenseSubtitleTrack ? null == e ? void 0 : e.persistentID : null == e ? void 0 : e.id, + e = this.htmlTextTrackMap.get(e); + return e && e.cues ? Array.from(e.cues) : [] + } + attachSubtitleTracks() { + this.gotTracks && this.tracks.forEach(e=>{ + this.createHTMLTextTrack(e) + } + ) + } + attachId3Tracks() { + this.id3Track = this.mediaSink.addTextTrack("metadata", "id3"), + this.id3Track.mode = "hidden" + } + setTracks(e, t, i) { + this._cleanTracks(), + this.htmlTextTrackMap = new Map, + this.cueRanges = [], + this.config.enableWebVTT && (this.tracks = e || []), + this.gotTracks = !0, + this._availableMediaOptions = e, + this._disabledMediaOption = i, + this.attachSubtitleTracks(), + this.attachId3Tracks(), + this.selectedTrack = t, + this.nativeSubtitleTrackChange$ = new zt, + this.mediaSink.textTracksCreated = !0 + } + onInlineStylesParsed(e) {} + processSubtitleFrag(e, t, i, r) { + var n = new Uint8Array(r) + , e = this.getExistingHTMLTextTrackIndex(e); + if (t && r.byteLength) { + const s = this._parseVTTs(e, t, i, n); + return s && (this.lastCueEndTime = Math.max(this.lastCueEndTime, s.endTime)), + s + } + } + _parseVTTs(r, n, e, t) { + let s; + return Cp(t, e, n.start, n.discoSeqNum, e=>{ + const t = this.mediaSink.textTracks[r] + , i = { + count: 0, + startTime: Number.POSITIVE_INFINITY, + endTime: 0 + }; + e.map(e=>{ + !t || t.cues && t.cues.getCueById(e.id) || (e.fragSN = n.mediaSeqNum, + e.webVTTCue = !0, + t.addCue(e), + i.count++), + i.startTime = Math.min(e.startTime, i.startTime), + i.endTime = Math.max(e.endTime, i.endTime) + } + ), + ne(i.startTime) && (s = i, + this.mediaSink.archiveParsedSubtitleFragmentRecord(this.selectedTrack.persistentID, n.mediaSeqNum, i)) + } + , e=>{} + , e=>{ + this.hls.trigger(x.INLINE_STYLES_PARSED, { + styles: e + }) + } + , this.logger), + s + } + _ensureParser() { + var e, t; + this.cea608Parser || (e = new Wh(this,1), + t = new Wh(this,2), + this.cea608Parser = new Gh(0,e,t)) + } + anchorTimeChanged() { + this.resetClosedCaptionParser() + } + resetClosedCaptionParser() { + var e; + null === (e = this.cea608Parser) || void 0 === e || e.reset() + } + addLegibleSamples(e, t, i, r) { + t && this.addClosedCaptionSamples(e, t), + i && 0 < i.length && this.addId3Samples(e, i, S(r)) + } + addClosedCaptionSamples(e, t) { + t.mp4 ? this.addMP4CaptionSamples(e, t.mp4) : t.ts && this.addTSCaptionSamples(e, t.ts) + } + addMP4CaptionSamples(e, i) { + if (this.enableCaption && this.config.enableCEA708Captions) { + var r = S(e); + this._ensureParser(); + for (let e = 0; e < i.length; e++) { + let t = i[e].pts - r; + var n = i[e].bytes; + for (let e = 0; e < n.length; e += 2) { + const i = []; + i.push(n[e]), + e + 1 < n.length ? i.push(n[e + 1]) : i.push(80), + this.cea608Parser.addData(t, i), + t += .03336666666666667 + } + } + } + } + addTSCaptionSamples(e, t) { + if (this.enableCaption && this.config.enableCEA708Captions) { + var i = S(e); + this._ensureParser(); + for (let e = 0; e < t.length; e++) { + var r = t[e].pts - i + , n = Rp.extractCea608Data(t[e].bytes); + this.cea608Parser.addData(r, n) + } + } + } + addId3Samples(e, t, r) { + if (this.config.enableID3Cues) { + const n = window.WebKitDataCue || window.VTTCue || window.TextTrackCue + , s = S(e); + for (let e = 0; e < t.length; e++) { + const a = t[e].pts - s; + let i = (e < t.length - 1 ? t[e + 1].pts : r) - s; + a === i && (i += 1e-4), + t[e].frames && t[e].frames.forEach(e=>{ + if (e && !this.id3shouldIgnore(e)) { + const t = new n(a,i,""); + t.value = e, + this.id3Track.addCue(t) + } + } + ) + } + } + } + id3shouldIgnore(e) { + return "PRIV" === e.key && ("com.apple.streaming.transportStreamTimestamp" === e.info || "com.apple.streaming.audioDescription" === e.info) + } + static extractCea608Data(t) { + var i = 31 & t[0]; + let r, n, s, a = 2; + const o = []; + for (let e = 0; e < i; e++) + r = t[a++], + n = 127 & t[a++], + s = 127 & t[a++], + 0 == n && 0 == s || 0 != (4 & r) && 0 == (3 & r) && (o.push(n), + o.push(s)); + return o + } + } + const Lp = { + name: "plist" + }; + class _p { + constructor(e, t, i, r) { + this.config = e, + this.xhrLoader = t, + this.customUrlLoader = i, + this.sessionDataCheckForCompleteness = e=>{ + const t = this.config["sessionDataAutoLoad"] + , i = Object.assign({}, e); + return e.complete || (e.itemList ? i.complete = e.itemList.every(e=>t[e["DATA-ID"]] && !e.VALUE && !e._STATUS && e.URI ? (this.logger.warn(`Incomplete because ${e["DATA-ID"]} was autoloaded but no response yet`), + !1) : (t[e["DATA-ID"]] && !e.URI && this.logger.warn(`id=${e["DATA-ID"]} missing uri`), + !0)) : this.logger.warn("Uninitialized SessionData")), + i + } + , + this.logger = r.child({ + name: "SessionDataLoader" + }) + } + loadSessionData(r) { + const n = this.config["sessionDataAutoLoad"] + , t = r.itemList || []; + let s = Bi(r); + return t.forEach(e=>{ + const i = e["DATA-ID"] + , t = e.URI; + if (t && n[i]) { + const n = fl.buildAbsoluteURL(r.baseUrl, t, { + alwaysNormalize: !0 + }) + , e = ""; + s = s.pipe(Ra(t=>this.loadSessionDataItemWithUrl(n, i, "", this.config, t, this.xhrLoader, this.customUrlLoader).pipe(Un(e=>(this.logger.error(`Error loading SessionData > url=${n}, id=${i}, err=${e}`), + Bi(t)))))) + } + } + ), + s.pipe(ur(e=>{ + if (t.length < 1) + return e; + e = this.sessionDataCheckForCompleteness(e); + if (e.complete) + return e; + throw new V(!1,"Session data not complete after loading all items",$.IncompleteSessionData) + } + ), $s(()=>{} + )) + } + loadSessionDataItemWithUrl(e, t, i, r, n, s, a) { + const o = qe() + , d = { + url: e, + method: "GET", + responseType: i, + xhrSetup: r.xhrSetup, + mimeType: "application/xml" + } + , l = xc({ + url: e + }, r.fragLoadPolicy); + let u; + return u = ml(e) ? a(d, l).pipe(ur(e=>this.onLoadSuccess(n, t, e.data.response.data, e.data.response.data))) : s(d, l).pipe(ur(([e])=>this.onLoadSuccess(n, t, e.response, e.responseXML))), + u.pipe(Un(e=>(e instanceof or ? e = new su(!1,e.message,0,$.SessionDataLoadTimeout) : e instanceof tu && (e = new su(!1,e.message,e.code,{ + code: e.code, + text: "Failed to load SessionData" + })), + o.error(`Unable to load SessionData > err=${e}`), + Bi(this.onLoadError(n, t, e))))) + } + onLoadSuccess(e, t, i, r) { + let n = null + , s = e; + if (function(e) { + const t = /[\s]*<\?xml/i; + t.lastIndex = 0; + var i = t.exec(e); + return i || /[\s]*"), + null) + } else if ("string" === i) { + const e = a[0]; + s = e ? e.nodeValue : null + } else if ("integer" === i) { + const e = a[0]; + s = e ? parseInt(e.nodeValue) : 0 + } else if ("float" === i) { + const e = a[0]; + s = e ? parseFloat(e.nodeValue) : 0 + } else if ("date" === i) { + const e = a[0]; + s = e ? new Date(e.nodeValue) : null + } else if ("data" === i) { + const e = a[0]; + s = e ? atob(e.nodeValue) : null + } else + "true" === i ? s = !0 : "false" === i && (s = !1) + } else if (a.length < 1) + t.warn(Lp, `unknown node with unknown value > nodeType=${e.nodeType} tagName=${e.tagName} nodeName=${e.nodeName} value=${e.nodeValue}`); + else { + s = []; + for (let e = 0; e < a.length; ++e) { + const r = a[e]; + r.tagName && s.push(n(r)) + } + 1 === s.length && (s = s[0]) + } + return s + }(n); + s = this.setSessionData(e, t, "VALUE", i) + } else if (function(e) { + const t = /[\s]*[\{\[]/; + return t.lastIndex = 0, + t.exec(e) + }(i)) + try { + const r = JSON.parse(i); + s = this.setSessionData(e, t, "VALUE", r) + } catch (r) { + this.logger.error(`JSON parser error: ${r}`), + s = this.setSessionData(e, t, "VALUE", i), + s = this.setSessionData(s, t, "_STATUS", -1) + } + else + s = this.setSessionData(e, t, "VALUE", i); + return s + } + setSessionData(t, i, r, n) { + let s = t; + if (t.itemList) { + let e; + const a = [...t.itemList]; + for (e = 0; e < t.itemList.length; ++e) { + const t = Object.assign({}, a[e]); + if (t["DATA-ID"] === i) { + t[r] = n, + a[e] = t; + break + } + } + e === t.itemList.length && this.logger.error(`Can't set ${r} of session data ${i}`), + s = Object.assign(Object.assign({}, t), { + itemList: a + }) + } else + this.logger.error(`Can't set ${r} on uninitialized session data`); + return s + } + onLoadError(e, t, i) { + return this.setSessionData(e, t, "_STATUS", null === (i = i.response) || void 0 === i ? void 0 : i.code) + } + } + function Np(e) { + return null != e && "iframeMediaDuration"in e && "iframeMediaStart"in e + } + function Fp(e, t) { + return e === t || e && t && e.itemId === t.itemId && e.mediaOptionId === t.mediaOptionId && e.mediaSeqNum === t.mediaSeqNum && e.discoSeqNum === t.discoSeqNum + } + function Bp(e) { + return JSON.stringify(e, ["mediaOptionId", "mediaSeqNum", "discoSeqNum", "start", "duration"]) + } + function Up() { + return e=>e.pipe(an(e=>null != e), ur(e=>e)) + } + function $p(e) { + return Se.isDolby(e) ? al.DOVI : Se.isHEVC(e) ? al.HEVC : Se.isVP09(e) ? al.VP09 : Se.isAVC(e) ? al.AVC : al.UNKNOWN + } + function Vp(e) { + return null == e ? void 0 : e.split(".")[0] + } + function Kp(e) { + return Se.isALAC(e) ? dl.ALAC : Se.isFLAC(e) ? dl.FLAC : Se.isEC3(e) ? dl.EC3 : Se.isAC3(e) ? dl.AC3 : Se.isXHEAAC(e) ? dl.XHEAAC : Se.isAAC(e) ? dl.AAC : Se.isMP3(e) ? dl.MP3 : dl.UNKNOWN + } + class Hp { + constructor(...e) { + this.identifier = e + } + ensureSameIdentifierLength(e) { + if (this.identifier.length !== e.identifier.length) + throw new Error(`Identifiers have non-matching lengths! (${this.identifier.length} vs ${e.identifier.length})`) + } + isGreaterThan(t) { + this.ensureSameIdentifierLength(t); + for (let e = 0; e < this.identifier.length; ++e) { + if (this.identifier[e] < t.identifier[e]) + return !1; + if (this.identifier[e] > t.identifier[e]) + return !0 + } + return !1 + } + isEqualTo(i) { + return this.ensureSameIdentifierLength(i), + this.identifier.every((e,t)=>e === i.identifier[t]) + } + } + function jp(e) { + return ne(e) && 0 !== e && 1 !== e + } + const qp = { + isBuffered(t, i) { + for (let e = 0; t && e < t.length; e++) + if (i >= t.start(e) && i <= t.end(e)) + return !0; + return !1 + }, + timeRangesToBufferedRange(t) { + const i = []; + for (let e = 0; t && e < t.length; e++) + i.push({ + start: t.start(e), + end: t.end(e) + }); + return i + }, + subtitleBufferInfo(e, t, i) { + if (e) { + e = this.bufferedCues(e); + return this.getBufferedInfo(e, t, i) + } + return { + len: 0, + start: t, + end: t, + nextStart: void 0 + } + }, + fragmentsBufferedInfo(e, t, i) { + const r = []; + for (const t of e) + r.push({ + start: t.start, + end: t.start + t.duration + }); + return this.getBufferedInfo(r, t, i) + }, + bufferedCues(t) { + const i = []; + if (t) + for (let e = 0; e < t.length; e++) + i.push({ + start: t[e].startTime, + end: t[e].endTime + }); + return i + }, + bufferedInfoFromMedia: (e,t,i)=>qp.getBufferedInfo(qp.timeRangesToBufferedRange(e.buffered), t, i), + getBufferedInfo(e, t, i) { + const r = []; + let n, s, a, o, d; + const l = e.map(({start: e, end: t})=>({ + start: e, + end: t + })); + for (l.sort((e,t)=>{ + return e.start - t.start || t.end - e.end + } + ), + d = 0; d < l.length; d++) { + const e = r.length; + if (e) { + const t = r[e - 1].end; + l[d].start - t < i ? l[d].end > t && (r[e - 1].end = l[d].end) : r.push(l[d]) + } else + r.push(l[d]) + } + for (d = 0, + n = 0, + s = a = t; d < r.length; d++) { + const e = r[d]["start"] + , l = r[d]["end"]; + if (t + i >= e && t < l) + s = e, + a = l, + n = a - t; + else if (t + i < e) { + o = e; + break + } + } + return { + len: n, + start: s, + end: a, + nextStart: o + } + }, + toRangeString: e=>`[${e.start.toFixed(3)},${e.end.toFixed(3)}]` + }; + (gc = Op = Op || {}).Seek = "Seek", + gc.HighBuffer = "HighBuffer", + gc.LowBuffer = "LowBuffer", + (gc = kp = kp || {}).AlmostDry = "AlmostDry", + gc.LowWater = "LowWater", + gc.HighWater = "HighWater", + gc.AboveHighWater = "AboveHighWater"; + const Qp = { + [kp.AlmostDry]: 0, + [kp.LowWater]: 1, + [kp.HighWater]: 2, + [kp.AboveHighWater]: 3 + }; + function Gp(t, e) { + return [{ + threshold: e.highWaterLevelSeconds, + level: kp.HighWater + }, { + threshold: e.lowWaterLevelSeconds, + level: kp.LowWater + }, { + threshold: e.almostDryWaterLevelSeconds, + level: kp.AlmostDry + }].find(({threshold: e})=>e < t) + } + function Wp(t, e) { + return [{ + threshold: e.almostDryWaterLevelSeconds, + level: kp.AlmostDry + }, { + threshold: e.lowWaterLevelSeconds, + level: kp.LowWater + }, { + threshold: e.highWaterLevelSeconds, + level: kp.HighWater + }, { + threshold: 1 / 0, + level: kp.AboveHighWater + }].find(({threshold: e})=>t <= e) + } + function zp(t, i) { + const e = Wp(t.getCurrentWaterLevel(i), t.bufferMonitorInfo).level + , r = [null, null]; + return [cl.Variant, cl.AltAudio].forEach(e=>{ + null != t.sourceBufferEntityByType(e) && (r[e] = Wp(t.getCurrentWaterLevelByType(e, i), t.bufferMonitorInfo).level) + } + ), + { + combined: e, + sbTuple: r + } + } + function Xp(s, a) { + return Zd([s.combinedBuffer$, s.gotPlaying$, s.seeking$, s.waterLevelChangedForType$(null), s.stallInfo$]).pipe(Ra(([e,t,i,r,n])=>0 === e.length || !t || i || null == r || null != n ? Ti : function t(i, r, e) { + const n = i.getCurrentWaterLevel(r) + , s = Gp(n, i.bufferMonitorInfo); + if (s) { + const e = s["threshold"]; + return vn(Math.ceil(1e3 * (n - e))).pipe(Ra(()=>{ + const e = Gp(i.getCurrentWaterLevel(r), i.bufferMonitorInfo); + return (null == e ? void 0 : e.level) === s.level ? t(i, r) : Ul + } + ), ur(()=>zp(i, r))) + } + return Ti + }(s, a))) + } + class Yp extends Od { + constructor(e, t) { + super(t), + this.mediaElement = e + } + get mediaElementDuration$() { + return this.selectActive(({mediaElementDuration: e})=>e) + } + get mediaElementDuration() { + var e; + return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.mediaElementDuration) && void 0 !== e ? e : 1 / 0 + } + get msDuration() { + var e; + return null !== (e = null === (e = this.mediaSourceEntity) || void 0 === e ? void 0 : e.duration) && void 0 !== e ? e : 1 / 0 + } + get minSBDuration() { + var e; + let t = 1 / 0; + return null === (e = null === (e = this.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities) || void 0 === e || e.forEach(e=>{ + return t = Math.min(t, null !== (e = null == e ? void 0 : e.totalDuration) && void 0 !== e ? e : 1 / 0) + } + ), + t + } + get currentTime() { + return this.mediaElement.currentTime + } + get clientWidth() { + return this.mediaElement.clientWidth + } + get clientHeight() { + return this.mediaElement.clientHeight + } + getBufferedDuration(e=.5) { + var t = qp.timeRangesToBufferedRange(this.mediaElement.buffered) + , e = qp.getBufferedInfo(t, this.currentTime, e); + return e.end - e.start + } + get mediaSourceEntity() { + var e; + return null === (e = this.getActive()) || void 0 === e ? void 0 : e.mediaSourceEntity + } + get msReadyState() { + var e; + return null === (e = this.mediaSourceEntity) || void 0 === e ? void 0 : e.readyState + } + get sourceBufferEntities() { + var e; + return null === (e = this.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities + } + sourceBufferEntityByType(e) { + var t; + return null === (t = this.sourceBufferEntities) || void 0 === t ? void 0 : t[e] + } + initSegmentEntityByType(e) { + return null === (e = this.sourceBufferEntityByType(e)) || void 0 === e ? void 0 : e.initSegmentInfo + } + get maxBufferSize() { + var e = null === (e = this.sourceBufferEntities) || void 0 === e ? void 0 : e[cl.Variant]; + let t = 1 / 0; + return null != e && e.gotQuotaExceeded && (t = null !== (e = e.maxTotalBytes) && void 0 !== e ? e : 1 / 0), + t + } + get autoPausedRestartTime() { + return this.getActive().autoPausedRestartTime + } + get seekable() { + return this.mediaElement.seekable + } + get desiredRate() { + var e; + return (null === (e = this.getActive()) || void 0 === e ? void 0 : e.desiredRate) || 0 + } + get desiredRate$() { + return this.selectActive(({desiredRate: e})=>null != e ? e : 0) + } + get effectiveRate() { + return this.isIframeRate ? this.desiredRate : this.paused ? 0 : 1 + } + get playbackRate() { + return this.mediaElement.playbackRate + } + get isIframeRate() { + return jp(this.desiredRate) + } + get isIframeRate$() { + return this.desiredRate$.pipe(ur(jp)) + } + get msObjectUrl$() { + return this.selectActive(({mediaSourceEntity: e})=>null == e ? void 0 : e.objectUrl).pipe(Es()) + } + get msReadyState$() { + return this.selectActive(({mediaSourceEntity: e})=>{ + return null !== (e = null == e ? void 0 : e.readyState) && void 0 !== e ? e : null + } + ) + } + get readyState() { + var e; + return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.readyState) && void 0 !== e ? e : 0 + } + get readyState$() { + return this.selectActive(({readyState: e})=>null != e ? e : 0) + } + get mediaSourceEntity$() { + return this.selectActive(({mediaSourceEntity: e})=>e) + } + get expectedSbCount$() { + return this.selectActive(({expectedSbCount: e})=>e) + } + get expectedSbCount() { + var e; + return null === (e = this.getActive()) || void 0 === e ? void 0 : e.expectedSbCount + } + get paused$() { + return this.selectActive(({paused: e})=>e) + } + get paused() { + var e; + return null === (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.paused) || void 0 === e || e + } + get flushing$() { + return this.selectActive(({flushing: e})=>e) + } + get flushing() { + var e; + return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.flushing) && void 0 !== e && e + } + get waitingForDisco$() { + return this.selectActive(({waitingForDisco: e})=>e) + } + get waitingForDisco() { + var e; + return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.waitingForDisco) && void 0 !== e && e + } + get gotPlaying() { + var e; + return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.gotPlaying) && void 0 !== e && e + } + get gotPlaying$() { + return this.selectActive(({gotPlaying: e})=>e) + } + get gotLoadStart$() { + return this.selectActive(({gotLoadStart: e})=>e) + } + get seekTo() { + var e; + return null === (e = this.getActive()) || void 0 === e ? void 0 : e.seekTo + } + get seekTo$() { + return this.selectActive(({seekTo: e})=>e) + } + get seeking() { + var e; + return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.seeking) && void 0 !== e && e + } + get seeking$() { + return this.selectActive(({seeking: e})=>e) + } + get nudgeTarget$() { + return this.selectActive(({nudgeInfo: e})=>null == e ? void 0 : e.nudgeTarget) + } + get nudgeCount() { + var e; + return null !== (e = null === (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.nudgeInfo) || void 0 === e ? void 0 : e.nudgeCount) && void 0 !== e ? e : 0 + } + get sourceBufferEntities$() { + return this.selectActive(({mediaSourceEntity: e})=>null == e ? void 0 : e.sourceBufferEntities) + } + sourceBufferEntityByType$(t) { + return this.selectActive(({mediaSourceEntity: e})=>{ + return null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[t] + } + ) + } + bufferedSegmentsByType$(t) { + return this.selectActive(({mediaSourceEntity: e})=>{ + return null !== (e = null === (e = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[t]) || void 0 === e ? void 0 : e.bufferedSegments) && void 0 !== e ? e : [] + } + ) + } + getBufferedSegmentsByType(e) { + return null !== (e = null === (e = this.sourceBufferEntityByType(e)) || void 0 === e ? void 0 : e.bufferedSegments) && void 0 !== e ? e : [] + } + get bufferedSegmentsTuple$() { + return Zd([this.bufferedSegmentsByType$(cl.Variant), this.bufferedSegmentsByType$(cl.AltAudio)]).pipe(Hi(Zi), wa(), Qn(10)) + } + get timeupdate$() { + return wc(this.mediaElement).event("timeupdate").pipe(Hi(Zi), wa(), so(125), ur(e=>this.currentTime), an(e=>ne(e))) + } + get playingEvent$() { + return wc(this.mediaElement).event("playing").pipe(ur(()=>{} + )) + } + get mediaElementEntity$() { + return this.selectActive(e=>Boolean(e)) + } + get ended$() { + return this.selectActive(e=>{ + return null !== (e = null == e ? void 0 : e.ended) && void 0 !== e && e + } + ) + } + sbUpdating$(t) { + return this.selectActive(e=>{ + return null !== (e = null === (e = null === (e = null === (e = null == e ? void 0 : e.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[t]) || void 0 === e ? void 0 : e.updating) && void 0 !== e && e + } + ) + } + sbUpdating(e) { + var t; + return null !== (e = null === (e = null === (t = null === (t = null === (t = this.getActive()) || void 0 === t ? void 0 : t.mediaSourceEntity) || void 0 === t ? void 0 : t.sourceBufferEntities) || void 0 === t ? void 0 : t[e]) || void 0 === e ? void 0 : e.updating) && void 0 !== e && e + } + sbError$(t) { + return this.selectActive(e=>{ + return null === (e = null === (e = null === (e = null == e ? void 0 : e.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[t]) || void 0 === e ? void 0 : e.error + } + ) + } + get updating$() { + return Zd([this.sbUpdating$(cl.Variant), this.sbUpdating$(cl.AltAudio)]).pipe(ur(e=>e.some(e=>e))) + } + get bufferedRangeTuple$() { + return Zd([this.selectActive(e=>{ + return null !== (e = null === (e = null === (e = null === (e = null == e ? void 0 : e.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[ul.Variant]) || void 0 === e ? void 0 : e.bufferedRanges) && void 0 !== e ? e : null + } + ), this.selectActive(e=>{ + return null !== (e = null === (e = null === (e = null === (e = null == e ? void 0 : e.mediaSourceEntity) || void 0 === e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[ul.AltAudio]) || void 0 === e ? void 0 : e.bufferedRanges) && void 0 !== e ? e : null + } + )]) + } + getBufferedRangeByType(e) { + return null !== (e = null === (e = this.sourceBufferEntities[e]) || void 0 === e ? void 0 : e.bufferedRanges) && void 0 !== e ? e : [] + } + get combinedBuffer$() { + return this.selectActive(e=>{ + return null !== (e = null == e ? void 0 : e.bufferedRanges) && void 0 !== e ? e : [] + } + ) + } + getBufferInfo(n, s) { + var e; + const t = null === (e = this.sourceBufferEntities) || void 0 === e ? void 0 : e.map(e=>null == e ? void 0 : e.bufferedRanges) + , i = { + buffered: { + start: n, + end: n, + len: 0 + }, + bufferedSegments: [] + } + , a = [i, i]; + return t && t.forEach((e,t)=>{ + if (e) { + const i = qp.getBufferedInfo(e, n, s) + , r = (null !== (e = this.sourceBufferEntities[t].bufferedSegments) && void 0 !== e ? e : []).filter(e=>!(e.endPTS < i.start || e.startPTS > i.end)); + a[t] = { + buffered: i, + bufferedSegments: r + } + } + } + ), + a + } + getCombinedBufferInfo(e, t) { + var i = this.getActive(); + return i ? qp.getBufferedInfo(i.bufferedRanges, e, t) : null + } + get bufferMonitorInfo() { + var e; + return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.bufferMonitorInfo) && void 0 !== e ? e : null + } + get bufferMonitorThresholds$() { + return this.selectActive(e=>{ + var t = null == e ? void 0 : e.bufferMonitorInfo; + if (!t) + return null; + var {almostDryWaterLevelSeconds: i, lowWaterLevelSeconds: r, highWaterLevelSeconds: e, maxBufferSeconds: t} = t; + return { + almostDryWaterLevelSeconds: i, + lowWaterLevelSeconds: r, + highWaterLevelSeconds: e, + maxBufferSeconds: t + } + } + ).pipe(Es((e,t)=>(null == e ? void 0 : e.lowWaterLevelSeconds) === (null == t ? void 0 : t.lowWaterLevelSeconds))) + } + get waterLevelType$() { + return this.selectActive(e=>{ + return null !== (e = null == e ? void 0 : e.bufferMonitorInfo.waterLevelType) && void 0 !== e ? e : null + } + ) + } + waterLevelForType(e) { + var t; + return null !== (e = null === (t = null === (t = this.getActive()) || void 0 === t ? void 0 : t.bufferMonitorInfo.waterLevelType) || void 0 === t ? void 0 : t.sbTuple[e]) && void 0 !== e ? e : null + } + waterLevelChangedForType$(t) { + return this.waterLevelType$.pipe(ur(e=>null == e ? null : null == t ? e.combined : e.sbTuple[t])) + } + get fellBelowLowWater$() { + return this.waterLevelChangedForType$(cl.Variant).pipe(ca(), ur(([e,t])=>function(e, t) { + return Qp[e] > Qp[t] + }(e, t) && (t === kp.LowWater || t === kp.AlmostDry)), So(this.seekTo$, this.waitingForDisco$), ur(([e,t,i])=>e && !ne(null == t ? void 0 : t.pos) && !i), xa(!1)) + } + isBufferedToEnd$(r, n=!0) { + return Zd([this.combinedBuffer$, this.selectActive(e=>e.bufferMonitorInfo).pipe(Up(), ur(e=>Math.max(e.almostDryWaterLevelSeconds, e.lowWaterLevelSeconds / 2))), this.seeking$]).pipe(ur(([e,t])=>{ + if (!e || !ne(this.minSBDuration) && n) + return !1; + e = qp.getBufferedInfo(e, this.currentTime, r).end; + let i = this.mediaElementDuration; + return n && (i = Math.min(this.mediaElementDuration, this.minSBDuration)), + i - e <= t + } + ), Es()) + } + needData$(e, r=!1, t) { + var i = !r; + return Zd([this.msReadyState$, this.waterLevelChangedForType$(null), this.isBufferedToEnd$(e, i), this.bufferedRangeTuple$]).pipe(Hi(Zi), Qn(10), wa(), ur(([e,t,i])=>"closed" !== e && (!!r || null == t || !i && t !== kp.AboveHighWater)), Ql.tag("needData")) + } + getSourceBufferInfoAction(e, t, i, r) { + var {currentTime: n, sourceBufferEntities: s, msReadyState: a} = this; + let o = [null, null]; + return !e && i.every(e=>!(null != e && e.userInitiated)) ? null : "open" === a && s && null != s[0] ? (o = this.getBufferInfo(n, r), + { + position: n, + bufferInfoTuple: o, + switchContexts: i + }) : { + position: t, + bufferInfoTuple: o, + switchContexts: i + } + } + get haveEnough() { + var e; + return null !== (e = null === (e = this.getActive()) || void 0 === e ? void 0 : e.haveEnough) && void 0 !== e && e + } + get haveEnough$() { + return this.selectActive(({haveEnough: e})=>e) + } + static likelyToKeepUp(e, t, i) { + return t && i >= e.HAVE_FUTURE_DATA + } + get playbackLikelyToKeepUp() { + return Yp.likelyToKeepUp(this.mediaElement, this.haveEnough, this.readyState) + } + get playbackLikelyToKeepUp$() { + return Zd([this.haveEnough$, this.readyState$]).pipe(ur(([e,t])=>Yp.likelyToKeepUp(this.mediaElement, e, t))) + } + getCurrentWaterLevel(e) { + var t = this.currentTime + , i = null !== (i = null === (i = this.getActive()) || void 0 === i ? void 0 : i.bufferedRanges) && void 0 !== i ? i : []; + return qp.getBufferedInfo(i, t, e).len + } + getCombinedMediaSourceBufferInfo(e) { + var t = this.currentTime + , [i,r] = null === (r = null === (i = this.getActive()) || void 0 === i ? void 0 : i.mediaSourceEntity) || void 0 === r ? void 0 : r.sourceBufferEntities; + return [qp.getBufferedInfo(null !== (i = null == i ? void 0 : i.bufferedRanges) && void 0 !== i ? i : [], t, e), qp.getBufferedInfo(null !== (r = null == r ? void 0 : r.bufferedRanges) && void 0 !== r ? r : [], t, e)] + } + getCurrentWaterLevelByType(e, t) { + var i = this.currentTime + , e = this.sourceBufferEntityByType(e) + , e = null !== (e = null == e ? void 0 : e.bufferedRanges) && void 0 !== e ? e : []; + return qp.getBufferedInfo(e, i, t).len + } + canContinuePlaybackWithoutGap(e, t, i, r) { + if (!e.liveOrEvent) + return !0; + if (!e.ptsKnown) + return !1; + var n = this.currentTime + , i = performance.now() + i.avgPlaylistLoadTimeMs; + return e.fragments[0].start + (i - t) / 1e3 <= this.getCombinedBufferInfo(n, r).end + } + get stallInfo$() { + return this.selectActive(e=>{ + return null !== (e = null == e ? void 0 : e.stallInfo) && void 0 !== e ? e : null + } + ) + } + get textTracks() { + return this.mediaElement.textTracks + } + get textTracksCreated$() { + return this.selectActive(e=>null == e ? void 0 : e.textTracksCreated) + } + get mediaOptionParsedSubtitleRecord() { + var e; + return null === (e = this.getActive()) || void 0 === e ? void 0 : e.mediaOptionParsedSubtitleRecord + } + getParsedSubtitleRecordsForMediaOption(e) { + return this.mediaOptionParsedSubtitleRecord ? this.mediaOptionParsedSubtitleRecord[e] || {} : null + } + } + class Jp { + constructor(e, t, i, r) { + this.mediaSink = e, + this.media = t, + this.logger = r, + this.useCustomMediaFunctions = i.useCustomMediaFunctions, + this.overridePlaybackRate = i.overridePlaybackRate + } + install() { + const e = this.media; + e && (this.useCustomMediaFunctions && e && e.play && e.pause && (e.originalPlay || (e.originalPlay = e.play.bind(e)), + e.originalPause || (e.originalPause = e.pause.bind(e)), + e.play = ()=>(this.mediaSink.checkForReplay(), + this.mediaSink.desiredRate = 1, + 0 < e.currentTime && !e.paused && !e.ended && 2 < e.readyState ? Promise.resolve() : new Promise((e,t)=>{ + this.pendingPlayPromises || (this.pendingPlayPromises = []), + this.pendingPlayPromises.push({ + resolve: e, + reject: t + }) + } + )), + e.pause = ()=>{ + this.mediaSink.desiredRate = 0 + } + ), + "function" == typeof HTMLMediaElement && this.overridePlaybackRate && Object.defineProperty(e, "playbackRate", { + enumerable: !0, + configurable: !0, + get: function() { + return 1 + }, + set: function(e) { + Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype, "playbackRate").set.call(this, e) + } + }), + this.playPromise = null, + this.expectPauseEvent = this.expectPlayEvent = !1) + } + uninstall() { + const e = this.media; + e && (e.originalPlay && (e.play = e.originalPlay, + delete e.originalPlay), + e.originalPause && (e.pause = e.originalPause, + delete e.originalPause), + this.overridePlaybackRate && (e.playbackRate = 1, + delete e.playbackRate)), + this.playPromise = null, + this.expectPauseEvent = this.expectPlayEvent = !1 + } + play() { + var e; + this.media && (e = this.mediaSink.flushing, + this.playPromise || e ? this.logger.warn(`Ignoring play command playPromise/flushing ${Boolean(this.playPromise)}/${e}`) : (this.expectPlayEvent = this.expectPlayEvent || this.media.paused, + this.playPromise = this._mediaPlayInternal(), + this.playPromise && this.playPromise.then(function() { + this.playPromise = null, + this._handlePendingPlayPromises(null) + } + .bind(this)).catch(function(e) { + this.playPromise = null, + this.expectPlayEvent = !1, + this._handlePendingPlayPromises(e || new Error("Play rejected for unknown reason")), + "NotAllowedError" === (null == e ? void 0 : e.name) ? (this.logger.warn("play() not allowed, going back to rate 0"), + this.mediaSink.desiredRate = 0) : this.logger.error(`play() error: ${null == e ? void 0 : e.message}`) + } + .bind(this)))) + } + pause() { + this.media && (this.playPromise ? this.playPromise.then(()=>{ + var e = this.mediaSink.mediaQuery; + (0 === this.mediaSink.desiredRate || e.seeking && !e.playbackLikelyToKeepUp) && this._mediaPauseInternal() + } + ).catch(e=>{ + this.logger.error(`Promise error in pause(): ${e.message}`) + } + ) : this._mediaPauseInternal()) + } + _handlePendingPlayPromises(t) { + var e, i = null === (e = this.pendingPlayPromises) || void 0 === e ? void 0 : e.length; + if (t) + for (let e = 0; e < i; e++) + this.pendingPlayPromises[e].reject(t); + else + for (let e = 0; e < i; e++) + this.pendingPlayPromises[e].resolve(); + this.pendingPlayPromises = [] + } + _mediaPlayInternal() { + return (this.media.originalPlay || this.media.play.bind(this.media))() + } + _mediaPauseInternal() { + return this.expectPauseEvent = this.expectPauseEvent || !this.media.paused, + (this.media.originalPause || this.media.pause.bind(this.media))() + } + } + class Zp extends Error { + } + class ef extends p { + constructor(e, t, i, r, n) { + super(L, e, t, i, r), + this.sbType = n, + this.response = r + } + } + class tf extends ef { + constructor(e, t, i, r) { + super("bufferAddCodecError", !1, e, t, i), + this.mediaOptionId = r, + this.mediaOptionType = Rl(this.sbType) + } + } + class rf extends ef { + constructor(e, t, i, r, n, s) { + super(e, t, i, r, n), + this.isTimeout = s, + this.mediaOptionType = Rl(this.sbType) + } + } + class nf extends rf { + constructor(e, t, i, r) { + super("bufferFullError", !1, e, t, i, !1), + this.maxTotalBytes = r + } + } + class sf extends rf { + constructor(e, t, i) { + super(n, !1, e, t, i, !0) + } + } + class af extends rf { + constructor(e, t, i, r) { + super(n, !1, e, t, i, !1), + this.mediaOptionId = r, + this.mediaOptionType = Rl(this.sbType) + } + } + class of extends p { + constructor(e, t, i, r, n, s, a=NaN) { + super(L, e, t, i, r), + this.stallType = n, + this.bufferLen = s, + this.nudgePosition = a, + this.response = r + } + } + class df extends Ut { + constructor(n, e, s, a, o, d, l, u, c) { + super(e=>{ + const t = wc(d) + , i = u.child({ + sb: o + }); + n.setSourceBufferEntity(o, l), + l.mimeType.includes("audio/mpeg") && (this.updateMp3Timestamps = !0); + const r = nn(t.event("updatestart").pipe(Ja(()=>{ + n.setSourceBufferUpdating(o) + } + )), t.event("updateend").pipe(Hi(Zi), Ja(()=>{ + var e = qp.timeRangesToBufferedRange(d.buffered) + , t = qp.timeRangesToBufferedRange(s.buffered); + n.setBufferedRangesUpdated(o, e, t, !1, c.maxBufferHole) + } + )), t.event("error").pipe(Ja(()=>{ + n.setSourceBufferError(o, "Got source buffer error") + } + ))).pipe(Ra(()=>Ti)).subscribe(e); + return ()=>{ + r.unsubscribe(); + try { + "open" === a.readyState && d.abort(), + a.removeSourceBuffer(d) + } catch (e) { + i.error(`Error aborting SourceBuffer on unsubscribe: ${e.message}`) + } + } + } + ), + this.mediaElementStore = n, + this.mediaElementQuery = e, + this.mediaElement = s, + this.type = o, + this.sourceBuffer = d, + this.config = c, + this.updateMp3Timestamps = !1 + } + get buffered() { + return this.sourceBuffer.buffered + } + appendBuffer(e, t) { + return Yr(()=>this.sourceBuffer.updating ? this._waitForUpdateEndOrError().pipe(Ra(()=>this.appendBuffer(e, t))) : this._appendBufferAsync(e, t)) + } + _appendBufferAsync(e, t) { + let i = NaN + , r = null; + const n = ("startPTS"in t ? t.frag : t).mediaOptionId; + try { + "startPTS"in t && (r = { + startPTS: t.startPTS, + endPTS: t.endPTS, + bytes: t.bytes, + frag: Object.assign({}, t.frag) + }), + this.mediaElementStore.setInflightSegment(this.type, r), + i = performance.now(), + this.sourceBuffer.appendBuffer(e) + } catch (e) { + return 22 !== e.code ? (this.mediaElementStore.setInflightSegment(this.type, null), + this.mediaElement.error ? Ui(new af(e.message,$.VideoDecoderBadDataErr,this.type,n)) : Ui(e)) : (this.mediaElementStore.setBufferedRangesUpdated(this.type, qp.timeRangesToBufferedRange(this.sourceBuffer.buffered), qp.timeRangesToBufferedRange(this.mediaElement.buffered), !0, this.config.maxBufferHole), + Ui(new nf(e.message,$.AllocationFailed,this.type,this.maxTotalBytes))) + } + return this._waitForUpdateEndOrError().pipe(ur(()=>({ + startAppend: i, + endAppend: performance.now(), + bytesAppend: e.byteLength + })), vo(1e4), Un(e=>{ + throw e instanceof or ? (this.sourceBuffer.abort(), + e = new sf("Append took longer than 10000ms",$.InternalError,this.type)) : e instanceof ef && (e = new af("Decode error",$.VideoDecoderBadDataErr,this.type,n)), + e + } + )) + } + remove(e, t) { + return this._waitForUpdateEndOrError().pipe(Ra(this._removeAsync.bind(this, e, t))) + } + _removeAsync(e, t) { + try { + this.sourceBuffer.remove(e, t) + } catch (e) { + return Ui(new ef(r,!1,e.message,$.InternalError,this.type)) + } + return this._waitForUpdateEndOrError() + } + abort() { + try { + this.sourceBuffer.abort() + } catch (e) { + return Ui(new ef(r,!1,e.message,$.InternalError,this.type)) + } + return this._waitForUpdateEndOrError() + } + get updating() { + return this.sourceBuffer.updating + } + get timestampOffset() { + return this.sourceBuffer.timestampOffset + } + set timestampOffset(e) { + this.sourceBuffer.timestampOffset = e + } + get gotQuotaExceeded() { + var e; + return null !== (e = null === (e = this.mediaElementQuery.sourceBufferEntityByType(this.type)) || void 0 === e ? void 0 : e.gotQuotaExceeded) && void 0 !== e && e + } + get bufferedSegments() { + var e; + return null !== (e = null === (e = this.mediaElementQuery.sourceBufferEntityByType(this.type)) || void 0 === e ? void 0 : e.bufferedSegments) && void 0 !== e ? e : [] + } + get totalBytes() { + var e; + return null !== (e = null === (e = this.mediaElementQuery.sourceBufferEntityByType(this.type)) || void 0 === e ? void 0 : e.totalBytes) && void 0 !== e ? e : 0 + } + get maxTotalBytes() { + var e = null !== (e = null === (e = this.mediaElementQuery.sourceBufferEntityByType(this.type)) || void 0 === e ? void 0 : e.maxTotalBytes) && void 0 !== e ? e : 1 / 0; + return this.gotQuotaExceeded ? e : 1 / 0 + } + _waitForUpdateEndOrError() { + return this.sourceBuffer.updating && this.mediaElementStore.setSourceBufferUpdating(this.type), + this.mediaElementQuery.sbUpdating$(this.type).pipe(an(e=>!1 === e), So(this.mediaElementQuery.sbError$(this.type)), ur(([,e])=>{ + if (e) + throw new ef(r,!1,"Got error during sourceBuffer operation",$.InternalError,this.type) + } + ), Cs(1)) + } + } + class lf extends Ut { + constructor(a, o, e, d, t, i) { + super(e=>{ + const t = wc(d) + , i = nn(t.event("sourceopen"), t.event("sourceclose"), t.event("sourceended")).pipe(Ja(e=>{ + e = (null !== (e = null == e ? void 0 : e.target) && void 0 !== e ? e : d).readyState; + o.msReadyState = e + } + )) + , r = this.sourceBuffers$.pipe(Ra(e=>e ? nn(...e.filter(e=>null != e)) : Ti)) + , n = nn(i, r).pipe(Ra(()=>Ti)).subscribe(e) + , s = URL.createObjectURL(d); + return a.src = s, + o.setMediaSourceEntity(s, d.readyState), + ()=>{ + n.unsubscribe(), + this.teardownWorker.addWork(Yr(()=>(URL.revokeObjectURL(s), + a.src === s && (a.removeAttribute("src"), + a.load(), + o.setMediaSourceEntity(null)), + Ul))), + this.sourceBuffers$.next(null) + } + } + ), + this.mediaElement = a, + this.mediaElementStore = o, + this.mediaElementQuery = e, + this.mediaSource = d, + this.teardownWorker = t, + this.logger = i, + this.sourceBuffers$ = new gi(null) + } + get readyState() { + return this.mediaSource.readyState + } + set duration(e) { + this.mediaSource.duration = e + } + get duration() { + return this.mediaSource.duration + } + endOfStream(e) { + this.mediaSource.endOfStream(e) + } + createSourceBuffers(e, a) { + const o = this.mediaSource; + sd(()=>{ + try { + const s = [null, null]; + e.forEach((t,i)=>{ + if (t) { + var {mimeType: r, mediaOptionId: n} = t; + let e; + try { + e = o.addSourceBuffer(r) + } catch (t) { + throw new tf(t.message,$.IncompatibleAsset,i,n) + } + s[i] = new df(this.mediaElementStore,this.mediaElementQuery,this.mediaElement,this.mediaSource,i,e,t,this.logger,a) + } + } + ), + this.sourceBuffers$.next(s) + } catch (e) { + if (!(e instanceof p)) + throw new Zp(`error initializing sourcebuffers ${e.message} readyState=${o.readyState}`); + throw e + } + } + ) + } + get needSourceBuffers() { + return null == this.sourceBuffers$.value || null == this.sourceBuffers$.value[0] + } + get sourceBuffers() { + return this.sourceBuffers$.value + } + getSourceBufferByType(e) { + var t = this.sourceBuffers$.value; + return t ? t[e] : null + } + updateLiveSeekableRange(e, t) { + const i = this.mediaSource; + null != i && i.setLiveSeekableRange && "open" === (null == i ? void 0 : i.readyState) && i.setLiveSeekableRange(e, t) + } + clearLiveSeekableRange() { + const e = this.mediaSource; + null != e && e.clearLiveSeekableRange && "open" === (null == e ? void 0 : e.readyState) && e.clearLiveSeekableRange() + } + } + function uf(e, c, t) { + const {lowBufferThreshold: h, lowBufferWatchdogPeriod: p, highBufferWatchdogPeriod: f, seekWatchdogPeriod: m} = t + , i = Zd([c.desiredRate$, c.ended$, c.combinedBuffer$, c.seekTo$]).pipe(ur(e=>{ + var t, [i,r,n,s] = e; + return t = c.currentTime, + e = i, + i = r, + r = n, + n = isFinite(null == s ? void 0 : s.pos), + s = r.some(e=>e.start <= t && e.end > t), + !(1 !== e || i || 0 === r.length || n && !s) + } + ), Es()) + , r = c.combinedBuffer$.pipe(ur(()=>c.getCurrentWaterLevel(0) <= t.lowBufferThreshold || !c.haveEnough ? Op.LowBuffer : Op.HighBuffer), Es()) + , n = Zd([i, c.seekTo$, c.gotPlaying$, r]).pipe(Ra(e=>{ + var [t,i,r] = e; + if (!t) + return Bi(null); + var n, s, a, o, d, l, u, e = c.nudgeCount, t = m + +e; + return isFinite(null == i ? void 0 : i.pos) || !r ? (n = c, + s = performance.now(), + t = t, + a = h, + vn(1e3 * t).pipe(ur(()=>{ + var e = n.currentTime + , t = n.getCombinedBufferInfo(e, 0); + return cf(Op.Seek, e, s, t, a, n.haveEnough) + } + ))) : (o = c, + d = p, + l = f + +e, + u = h, + nn(Bi(o.currentTime), o.timeupdate$).pipe(Ra(e=>{ + const t = performance.now() + , i = o.getCombinedBufferInfo(e, 0); + let r, n; + return r = i.len <= u || !o.haveEnough ? (n = d, + Op.LowBuffer) : (n = l, + Op.HighBuffer), + vn(Math.max(100, 1e3 * n)).pipe(ur(()=>e < o.currentTime ? null : cf(r, e, t, i, u, o.haveEnough))) + } + ))) + } + )) + , s = n.pipe(Up(), So(c.combinedBuffer$), Ra(([])=>Zd([c.seeking$, c.paused$])), Ra(([e,t])=>e || t ? Ti : c.timeupdate$.pipe(ca(), an(([e,t])=>ne(e) && ne(t) && e < t), Cs(1))), ur(()=>null)); + return nn(n, s) + } + function cf(e, t, i, r, n, s) { + var a = performance.now() - i; + return { + type: e, + isLowBufferStall: r.len <= n || !s, + tstalled: i, + stallDurationMs: a, + currentTime: t + } + } + class hf extends Ut { + constructor(w, A, e, t, i, r) { + super(e=>{ + const t = this.config + , i = A.startMediaSession(w, t.maxBufferLength, t.almostDryBufferSec, t.defaultTargetDuration) + , r = Bi(w).pipe(pf(A, this._mediaQuery, this, this.hlsGapless, t, this.logger)) + , n = this.mediaSource$.pipe(Ra(e=>e || Ti)) + , s = this._mediaQuery.seekTo$.pipe((u = w, + c = this._mediaQuery, + p = (h = this).config, + f = (f = this.logger).child({ + name: "seek" + }), + e=>e.pipe(Ja(e=>{} + ), an(e=>e && ne(e.pos)), Ra(e=>c.readyState$.pipe(an(e=>e >= u.HAVE_METADATA), Cs(1), Js(e), Ra(({pos: e, fromEvent: t})=>(h.checkForInconsistentStoreBufferRangesAndUpdate(), + u.paused || h.pause(), + t || (u.currentTime = e), + $l(c.haveEnough$, e=>e).pipe(Js(e)))), Ra(e=>{ + var t = c.getCombinedBufferInfo(e, 0) + , i = t.nextStart; + return 0 === t.len && ne(i) && e < i && i - e <= p.maxSeekHole ? (h.seekTo = i, + Ti) : Bi(e) + } + ), So(c.desiredRate$), ur(([,e])=>{ + u.paused && 0 !== e && h.play() + } + ), Ua(Ti), Un(e=>(f.error(`error during seek ${e.message}`), + Ti))))))) + , a = this._mediaQuery.desiredRate$.pipe((o = w, + d = this._mediaQuery, + l = this, + e=>e.pipe(So(d.seekTo$), Ra(([e,t])=>ne(null == t ? void 0 : t.pos) ? Ti : 0 === e ? (o.paused || l.pause(), + Ti) : $l(d.haveEnough$, e=>e).pipe(Ja(()=>{ + o.paused && l.play() + } + ))), Ua(Ti)))); + var o, d, l, u, c, h, p, f; + this.mediaFunctions = this.mediaFunctions || new Jp(this,w,t,this.logger), + this.mediaFunctions.install(); + var m, g, y, v, S, b, T, E, I = nn(uf(this.logger, this._mediaQuery, this.config).pipe(Ja(e=>{ + A.setStallInfo(e) + } + )), this.mediaQuery.stallInfo$.pipe((g = A, + y = (m = this).config, + v = this.logger, + e=>e.pipe(Ls(e=>e ? function(i, e, r, n) { + const s = i.mediaQuery; + return nn(Zd([s.seekTo$, s.nudgeTarget$]).pipe(an(([e,t])=>e && ne(e.pos) && ne(t) && (e.pos < t || e.pos - t > r.maxSeekHole)), Js(null)), s.stallInfo$).pipe(So(s.desiredRate$), Hi(Zi), ur(([c,e],t)=>{ + if (!c) + return NaN; + var h = s.getCombinedBufferInfo(c.currentTime, 0) + , e = jp(e); + return function(e, t, i, r, n) { + var {type: s, isLowBufferStall: a, currentTime: o} = c + , d = h.len + , l = t.maxSeekHole; + let u = NaN; + if (a) { + const t = h.nextStart - o <= l ? h.nextStart : 1 / 0; + ne(t) ? u = t : e.mediaQuery.msDuration - o < .1 && (u = o + .1) + } else if (n < t.nudgeMaxRetry) + u = o + t.nudgeOffset; + else { + if (!r) + throw i.error(`still stuck in high buffer @${o} after ${t.nudgeMaxRetry}, raise fatal error`), + new of("bufferStalledError",!0,"got fatal buffer error",$.VideoDecoderBadDataErr,s,d); + i.error(`still stuck in high buffer @${o} after ${t.nudgeMaxRetry}, non fatal in iframeMode`) + } + return ne(u) && e.nudgeSeek(u, n + 1), + u + }(i, r, n, e, t) + } + ), Qa(e=>ne(e)), $s(()=>{ + e.setNudgeInfo(null) + } + )) + }(m, g, y, v) : Bi(NaN)))))); + nn(r, n, s, a, I, (S = this.mediaQuery, + b = A, + I = t.maxBufferHole, + nn((E = I, + Zd([(T = S).bufferMonitorThresholds$, T.combinedBuffer$, T.seeking$]).pipe(ur(([e])=>null == e ? null : zp(T, E)))), Xp(S, I)).pipe(Hi(Zi), Ja(({combined: e, sbTuple: t})=>{ + b.updateWaterLevels(e, t) + } + )))).pipe(Ua(Ti), $s(()=>{ + A.remove(i), + this.mediaFunctions.uninstall(), + this.mediaFunctions = void 0 + } + )).subscribe(e) + } + ), + this.mediaElement = w, + this.mediaElementStore = A, + this.config = e, + this.hlsGapless = t, + this.logger = i, + this.teardownWorker = r, + this.mediaSource$ = new gi(null), + this._mediaQuery = new Yp(w,A), + this.logger = i.child({ + name: "mse" + }), + this.mediaFunctions = new Jp(this,w,e,this.logger) + } + get mediaSourceAdapter() { + return this.mediaSource$.value + } + get sourceBuffers() { + var e; + return null !== (e = null === (e = this.mediaSourceAdapter) || void 0 === e ? void 0 : e.sourceBuffers) && void 0 !== e ? e : [] + } + get needSourceBuffers() { + return !this.sourceBuffers[0] + } + get mediaQuery() { + return this._mediaQuery + } + sourceBuffersBufferedRangeByType(e) { + var t, e = null === (t = null === (t = this.mediaSourceAdapter) || void 0 === t ? void 0 : t.sourceBuffers) || void 0 === t ? void 0 : t[e]; + return e ? qp.timeRangesToBufferedRange(e.sourceBuffer.buffered) : null + } + checkForInconsistentStoreBufferRangesAndUpdate() { + var e = qp.timeRangesToBufferedRange(this.mediaElement.buffered) + , t = this.sourceBuffersBufferedRangeByType(cl.Variant) + , i = this.sourceBuffersBufferedRangeByType(cl.AltAudio) + , r = null !== (n = null === (r = this.mediaQuery.sourceBufferEntityByType(cl.Variant)) || void 0 === r ? void 0 : r.bufferedRanges) && void 0 !== n ? n : null + , n = null !== (n = null === (n = this.mediaQuery.sourceBufferEntityByType(cl.AltAudio)) || void 0 === n ? void 0 : n.bufferedRanges) && void 0 !== n ? n : null; + this.shouldUpdateStoreValues(t, r) && (this.logger.warn(`[${Pl[cl.Variant]}] SourceBuffer's loaded bufferedRanges ${JSON.stringify(t)} & mediaElementStore's bufferedRanges ${JSON.stringify(r)} are out of sync!`), + this.updateMediaElementStoreBufferedRanges(e, cl.Variant)), + this.shouldUpdateStoreValues(i, n) && (this.logger.warn(`[${Pl[cl.AltAudio]}] SourceBuffer's loaded bufferedRanges ${JSON.stringify(i)} & mediaElementStore's bufferedRanges ${JSON.stringify(n)} are out of sync!`), + this.updateMediaElementStoreBufferedRanges(e, cl.AltAudio)) + } + shouldUpdateStoreValues(e, i) { + return !(null == e && null == i || (null == e ? void 0 : e.length) == (null == i ? void 0 : i.length) && !e.find(t=>{ + var e = Ll.search(i, e=>t.start >= e.start && t.end <= e.end ? 0 : t.end < e.start ? -1 : 1); + return null == e || e.start != t.start || e.end != t.end || void 0 + } + )) + } + updateMediaElementStoreBufferedRanges(e, t) { + var i = this.sourceBuffersBufferedRangeByType(t); + i && !this.mediaQuery.sbUpdating(t) && this.mediaElementStore.setBufferedRangesUpdated(t, i, e, !1, this.config.maxBufferHole) + } + destroyMediaSource() { + this.mediaSource$.next(null) + } + makeMediaSource() { + return new MediaSource + } + openMediaSource(t) { + sd(()=>{ + var e; + t ? (e = new lf(this.mediaElement,this.mediaElementStore,this.mediaQuery,t,this.teardownWorker,this.logger), + this.mediaSource$.next(e)) : this.mediaSource$.next(null) + } + ) + } + createSourceBuffers(e) { + const t = this.mediaSource$.value; + if (!t) + throw new Error("createSourceBuffers empty mediaSource"); + t.createSourceBuffers(e, this.config) + } + _waitForMediaSourceOpen(i) { + const r = this.mediaQuery.mediaSourceEntity.objectUrl; + return Zd([this.mediaQuery.msReadyState$, this.mediaQuery.msObjectUrl$]).pipe(Ra(([e,t])=>t !== r ? Bi(null) : "open" === e || "ended" === e ? Bi(i) : Ti)) + } + get appendOrder() { + return this.mediaQuery.isIframeRate ? [cl.Variant, cl.AltAudio] : [cl.AltAudio, cl.Variant] + } + clearFlush(e) { + e.forEach(e=>{ + e && (e.dataSeg.flushBeforeAppend = { + start: 0, + end: 0 + }) + } + ) + } + getSwitchPosition(e) { + return e.reduce((e,t)=>{ + t = t ? t.dataSeg.switchPosition : void 0; + return ne(t) ? ne(e) ? Math.min(e, t) : t : e + } + , void 0) + } + checkForReplay() { + var e = this.mediaElement; + e.paused && !e.seeking && e.duration && e.currentTime && e.currentTime >= e.duration - this.config.maxTotalDurationTolerance && (this.seekTo = 0) + } + resetMediaSourceIfNeeded(r) { + const n = this["mediaQuery"] + , e = n["sourceBufferEntities"] + , t = n.getActive()["expectedSbCount"]; + if (!e || this.needSourceBuffers) + return this._waitForMediaSourceOpen(r); + var i = function(e, s, t, i, r) { + const n = s.filter(e=>Boolean(e)).length + , a = e.filter(e=>Boolean(e)).length + , d = [null, null]; + e.forEach((e,t)=>{ + var i, r, n, s, a, o; + e && (s = e["offsetTimestamp"], + a = S(s), + i = e.initSeg.mimeType, + {audioCodec: r, videoCodec: n} = e.initSeg.initParsedData, + o = e["dataSeg"], + s = S(o.startPts) - a, + a = S(o.endPts) - a, + o = o.discoSeqNum, + d[t] = { + audioCodec: r, + videoCodec: n, + mimeType: i, + startPTSSec: s, + endPTSSec: a, + discoSeqNum: o, + mediaOptionId: e.initSeg.mediaOptionId + }) + } + ); + let o = n === t + , l = a === t; + if (1 === a && a < t && 0 !== n) { + const t = e[ul.Variant] ? ul.Variant : ul.AltAudio + , n = 1 - t + , a = d[t] + , o = d[n] = ff(s[n], a.startPTSSec, a.discoSeqNum, i, a.mediaOptionId, r) || ff(s[n], a.endPTSSec, a.discoSeqNum, i, a.mediaOptionId, r); + o || r.warn(`${Cl[t]} No matching frag found ${se(a)} buffered=${se(s[n].bufferedSegments.map(e=>{ + var {mediaSeqNum: t, discoSeqNum: i} = e.frag; + return { + mediaSeqNum: t, + discoSeqNum: i, + startPTS: e.startPTS, + endPTS: e.endPTS + } + } + ))}`), + l = null != o + } + let u = NaN + , c = NaN; + return l && d.forEach((e,t)=>{ + if (!e) + return null; + t = s[t]; + if (t) { + const s = t.audioCodec + , i = t.videoCodec + , {audioCodec: r, videoCodec: n} = e; + o = o && (i === n || Se.isCompatibleVideoCodec(i, n)), + o = o && (s === r || Se.isCompatibleAudioCodec(s, r)) + } else + o = !1; + u = ne(u) ? (c = Math.abs(e.startPTSSec - u), + Math.max(e.startPTSSec, u)) : (c = 0, + e.startPTSSec) + } + ), + { + compatible: o && l, + boundary: u, + allowance: c + } + }(r, e, t, this.config.maxBufferHole, this.logger); + if (i.compatible) + return this._waitForMediaSourceOpen(r); + let s = i.boundary; + const a = i.allowance + , o = this.getSwitchPosition(r); + if (ne(o) && (s = o), + !ne(s)) + return this.logger.warn("not enough info #disco"), + Bi(null); + const d = hn($l(nn(Bi(n.currentTime), n.timeupdate$), e=>e >= s), $l(n.stallInfo$.pipe(ur(e=>{ + return null !== (e = null == e ? void 0 : e.currentTime) && void 0 !== e ? e : NaN + } + )), e=>e >= s - a - this.config.discontinuitySeekTolerance)); + return this.mediaElementStore.waitingForDisco = !0, + d.pipe(Js(s), Ra(e=>{ + performance.now(); + const t = n.currentTime + , i = this.msDuration; + return this.resetMediaSource(Math.max(t, e)), + this._waitForMediaSourceOpen(r).pipe(Ja(()=>{ + performance.now(), + this.msDuration = i + } + )) + } + ), $s(()=>{ + this.mediaElementStore.waitingForDisco = !1 + } + )) + } + resetMediaSource(e=NaN) { + var t; + ne(e) || (e = null !== (t = null === (t = this.mediaQuery.seekTo) || void 0 === t ? void 0 : t.pos) && void 0 !== t ? t : this.mediaQuery.currentTime), + 0 < this.sourceBuffers.length && (this.openMediaSource(this.makeMediaSource()), + this.seekTo = e) + } + setExpectedSbCount(e) { + this.mediaElementStore.expectedSbCount = e + } + appendInitSegments(d, l) { + const {mediaQuery: e, mediaElementStore: u, sourceBuffers: c} = this + , h = e["sourceBufferEntities"]; + if (!c) + throw new Error("appendInitSegments: null sourceBuffers"); + if (!h) + throw new Error("appendInitSegments: null sourceBufferEntities"); + var t = this.appendOrder.map(t=>{ + if (d[t]) { + const i = c[t] + , r = d[t] + , n = h[t] + , s = r["initSeg"]; + if (!n) + throw new Error(`appendInitSegments: sb[${Pl[t]}] null currentSbEntity`); + if (!i) + throw new Error(`appendInitSegments: sb[${Pl[t]}] null source buffer`); + const a = n.initSegmentInfo + , o = function() { + var {itemId: e, mediaOptionId: t, discoSeqNum: i, keyTagInfo: r} = s; + return { + itemId: e, + mediaOptionId: t, + discoSeqNum: i, + keyId: je(null == r ? void 0 : r.keyId) + } + }(); + if ((e = o) && a && e.itemId === a.itemId && e.mediaOptionId === a.mediaOptionId && e.discoSeqNum === a.discoSeqNum && e.keyId === a.keyId) + return Bi(null); + var e = Rl(t); + return i.appendBuffer(s.data, s).pipe(Ja(e=>{ + u.setInitSegmentEntity(t, o) + } + ), l(i, e, s.mediaOptionId, this.config, this.mediaQuery)) + } + } + ).filter(e=>Boolean(e)); + return 0 === t.length ? Bi(null) : Jr(t) + } + appendDataSegments(m, g) { + var e = this.appendOrder.map(e=>{ + const t = m[e] + , {mediaQuery: i, sourceBuffers: r} = this + , n = i["sourceBufferEntities"]; + if (!r) + throw new Error("appendDataSegments: null sourceBuffers"); + if (!n) + throw new Error("appendDataSegments: null sourceBufferEntities"); + if (!t) + return null; + const s = r[e] + , a = m[e] + , o = n[e]; + if (!o) + throw new Error("appendDataSegments: null currentSbEntity"); + const d = o.initSegmentInfo + , l = a["dataSeg"]; + if (!d) + throw new Error(`appendDataSegments: sb[${Pl[e]}] null currentInitSegmentInfo`); + if (!o) + throw new Error(`appendDataSegments: sb[${Pl[e]}] null currentSbEntity`); + if (!s) + throw new Error(`appendDataSegments: sb[${Pl[e]}] null source buffer`); + const u = s.timestampOffset + , c = { + startPTS: S(l.startPts) + u, + endPTS: S(l.endPts) + u, + firstKeyframePts: l.firstKeyframePts ? S(l.firstKeyframePts) + u : void 0, + bytes: l.data2 ? l.data1.byteLength + l.data2.byteLength : l.data1.byteLength, + frag: { + itemId: l.itemId, + mediaOptionId: l.mediaOptionId, + mediaSeqNum: l.mediaSeqNum, + discoSeqNum: l.discoSeqNum, + keyTagInfo: l.keyTagInfo, + isLastFragment: l.isLastFragment, + iframe: l.iframe, + framesWithoutIDR: l.framesWithoutIDR, + dropped: l.dropped + } + } + , h = Rl(e); + let p = Ul; + var f = t.dataSeg.flushBeforeAppend; + return f && f.start !== f.end && (p = this.flushData(e, f.start, f.end)), + p.pipe(Ra(()=>Bi(l.data1, l.data2).pipe(Up()).pipe(qn(e=>s.appendBuffer(e, c).pipe(g(s, h, l.mediaOptionId, this.config, this.mediaQuery))))), Ja(()=>{ + i.getBufferedRangeByType(e) + } + )) + } + ).filter(e=>Boolean(e)); + return 0 === e.length ? Bi(null) : Jr(e) + } + setStoreSbTimeoffsets(s) { + const {mediaElementStore: a, sourceBuffers: e} = this; + e.forEach((t,i)=>{ + if (t && s[i]) { + var {offsetTimestamp: r, dataSeg: n} = s[i] + , n = S(n.startPts); + let e = -1 * S(r); + t.updateMp3Timestamps && .1 < Math.abs(t.timestampOffset - n) && (e = n + e), + t.timestampOffset !== e && (t.timestampOffset = e, + a.setTimestampOffset(i, t.timestampOffset)) + } + } + ) + } + adjustJaggedStart() { + var e; + const {mediaQuery: t, logger: r} = this + , {sourceBufferEntities: i, currentTime: n, seekTo: s} = t; + if (!i) + throw new Error("appendSourceBufferData null currentSbEntity"); + const a = (null == s ? void 0 : s.pos) || n; + let o = NaN; + i.forEach((e,t)=>{ + if (e) { + e = qp.getBufferedInfo(e.bufferedRanges, a, 0); + if (0 === e.len) { + const i = e["nextStart"]; + r.warn(`sb[${Pl[t]}] jagged start: ${i} current=${o}`), + ne(i) && (!ne(o) || o < i) && (o = i) + } + } + } + ), + ne(o) && (r.warn(`[seek] jagged start, adjusting currentTime:${n.toFixed(3)} seekTo=${null === (e = null == s ? void 0 : s.pos) || void 0 === e ? void 0 : e.toFixed(3)}->${o}`), + this.seekTo = o) + } + addCues(e, t) { + const i = this.mediaElement.textTracks[e]; + i && t.forEach(e=>{ + i.addCue(e) + } + ) + } + _flushInternal(e, t, i) { + return Yr(()=>e.remove(t, i)).pipe(Ja(()=>{} + )) + } + flushAll(i, r, n=!1) { + return 0 === this.sourceBuffers.length ? Ul : Jr(this.sourceBuffers.map((e,t)=>e ? this.flushData(t, i, r, n) : Ul)).pipe(Js(void 0)) + } + flushData(o, d, l, u=!1) { + const {mediaQuery: t, logger: c} = this; + return $l(t.updating$, e=>!1 === e).pipe(Ra(()=>{ + var e = t["sourceBufferEntities"] + , e = e[o]; + null != e && e.updating && this.logger.warn(`trying to flush while updating ${o}`); + const r = this.sourceBuffers[o]; + let n, s, a = Ul; + e = -1 === navigator.userAgent.toLowerCase().indexOf("firefox"); + if (this.flushing = !0, + e) + return this._flushInternal(r, d, l); + for (let i = 0; i < r.buffered.length; i++) { + let e, t; + n = r.buffered.start(i), + s = r.buffered.end(i), + t = l === 1 / 0 ? (e = d, + l) : (e = Math.max(n, d), + Math.min(s, l)), + Math.min(t, s) > e && (u || .5 < Math.min(t, s) - e) ? a = a.pipe(Ua(this._flushInternal(r, e, t))) : c.warn(`ignoring sb[${Pl[o]}] flush ${e},${t}`) + } + return a + } + ), $s(()=>{ + this.flushing = !1 + } + )) + } + static convertInitSegToCompatInfo(e) { + return { + mimeType: e.mimeType, + audioCodec: e.initParsedData.audioCodec, + videoCodec: e.initParsedData.videoCodec, + startPTSSec: void 0, + endPTSSec: void 0, + discoSeqNum: e.discoSeqNum, + mediaOptionId: e.mediaOptionId + } + } + static combineAppendDataInfoWithCompatInfo(e, t, i, r=0) { + const n = [...t]; + e.forEach((e,t)=>null != e && e.initSeg ? n[t] = hf.convertInitSegToCompatInfo(e.initSeg) : null); + t = n[cl.Variant].videoCodec, + e = Vp(t); + if (i && i.has(e)) { + const s = i.get(e); + n[cl.Variant].mimeType = n[cl.Variant].mimeType.replace(t, s), + n[cl.Variant].videoCodec = s + } + return n + } + convertSourceBufferEntitiesToCompatInfo(e) { + const t = e.sourceBufferEntities + , i = [null, null]; + return t.forEach((e,t)=>{ + e && (i[t] = { + mimeType: e.mimeType, + audioCodec: e.audioCodec, + videoCodec: e.videoCodec, + startPTSSec: void 0, + endPTSSec: void 0, + discoSeqNum: void 0, + mediaOptionId: null === (e = e.initSegmentInfo) || void 0 === e ? void 0 : e.mediaOptionId + }) + } + ), + i + } + appendData(e, t, i) { + const {mediaQuery: r, logger: n} = this + , o = this.convertSourceBufferEntitiesToCompatInfo(r); + return e.every(e=>null == e) ? Bi([]) : this.resetMediaSourceIfNeeded(e).pipe(Ra(e=>e ? r.updating$.pipe(an(e=>!1 === e), Cs(1), Js(e)) : Bi(null)), Ra(e=>{ + if (!e) + return Bi([]); + let s = NaN + , a = NaN; + if (this.needSourceBuffers) { + s = performance.now(); + const t = hf.combineAppendDataInfoWithCompatInfo(e, o, i, n); + this.createSourceBuffers(t), + a = performance.now(), + this.clearFlush(e) + } + return e.forEach(e=>{ + e = null == e ? void 0 : e.dataSeg; + null != e && e.cues && ne(null == e ? void 0 : e.texttrackIdx) && this.addCues(e.texttrackIdx, e.cues) + } + ), + this.setStoreSbTimeoffsets(e), + Xr(Yr(()=>this.appendInitSegments(e, t)), Yr(()=>this.appendDataSegments(e, t))).pipe(function(r, i) { + return 2 <= arguments.length ? function(e) { + return Ft(na(r, i), Qs(1), (void 0 === (t = i) && (t = null), + function(e) { + return e.lift(new es(t)) + } + ))(e); + var t + } + : function(e) { + return Ft(na(function(e, t, i) { + return r(e, t) + }), Qs(1))(e) + } + }((e,t)=>(e.push(t), + e), new Array), ur(([i,r])=>{ + const n = [null, null]; + return [cl.Variant, cl.AltAudio].forEach(e=>{ + var t; + null != (null == i ? void 0 : i[e]) && (t = { + fragmentType: Rl(e), + bufferCreationStart: s, + bufferCreationEnd: a, + startInitAppend: i[e].startAppend, + endInitAppend: i[e].endAppend, + initBytesAppend: i[e].bytesAppend, + startDataAppend: r[e].startAppend, + endDataAppend: r[e].endAppend, + dataBytesAppend: r[e].bytesAppend + }, + n[e] = t) + } + ), + n + } + ), Ja(e=>{ + this.adjustJaggedStart() + } + )) + } + ), Cs(1)) + } + endStream() { + try { + this.mediaSourceAdapter.endOfStream() + } catch (e) { + this.logger.warn(`endOfStream failed: ${e.message}`) + } + } + setMediaKeys(e) { + const t = this.mediaElement; + return t.done$ || (t.done$ = new gi(!1)), + nn(Ul, t.done$).pipe(Ra(()=>!0 === t.updating ? Ti : t.mediaKeys === e ? Ul : (t.updating = !0, + Lr(t.setMediaKeys(e).then(()=>{ + t.updating = !1, + t.done$.next(!0) + } + ).catch(e=>{ + throw t.updating = !1, + t.done$.next(!0), + e + } + )))), Cs(1), Ja(()=>{} + ), ya(e=>e.pipe(Kr((e,t)=>{ + if (t < 3) + return vn(100 * t); + throw e + } + ))), wa()) + } + clearMediaKeys(i) { + return Yr(()=>{ + if (!this.mediaElement) + return Ul; + const e = -1 < navigator.userAgent.toLowerCase().indexOf("chrome") + , t = this.mediaElement.src; + return e && (this.mediaElement.src = ""), + i ? this.setMediaKeys(null).pipe(qn(()=>(this.mediaElement.src = t, + Ul))) : nn(Lr(this.mediaElement.setMediaKeys(null)).pipe(qn(()=>(this.mediaElement.src = t, + Ul))), Ul) + } + ) + } + set autoPausedRestartTime(e) { + this.mediaElementStore.autoPausedRestartTime = e + } + set seekTo(e) { + this.mediaElementStore.setSeekToPos(e, !1) + } + set skip(e) { + this.seekTo = this.mediaElement.currentTime + e + } + nudgeSeek(e, t) { + sd(()=>{ + this.mediaElementStore.setSeekToPos(e, !1), + this.mediaElementStore.setNudgeInfo({ + nudgeTarget: e, + nudgeCount: t + }) + } + ) + } + set desiredRate(e) { + this.mediaElementStore.desiredRate = e + } + toggleTrickPlaybackMode(e) { + if (this.config.overridePlaybackRate) { + const t = e ? 2 : 1; + try { + this.mediaElement.playbackRate = t + } catch (e) { + this.logger.error({ + name: "iframes" + }, `Exception when setting playbackRate=${t}: ${e.message}`) + } + } + const t = this.muteValueOnTrickPlaybackToggle; + e && void 0 === t ? (this.muteValueOnTrickPlaybackToggle = this.mediaElement.muted, + this.mediaElement.muted = e) : e || void 0 === t || (this.mediaElement.muted = t, + this.muteValueOnTrickPlaybackToggle = void 0) + } + play() { + this.mediaFunctions.play() + } + pause() { + this.mediaFunctions.pause() + } + get expectPlayEvent() { + return this.mediaFunctions.expectPlayEvent + } + set expectPlayEvent(e) { + this.mediaFunctions.expectPlayEvent = e + } + get expectPauseEvent() { + return this.mediaFunctions.expectPauseEvent + } + set expectPauseEvent(e) { + this.mediaFunctions.expectPauseEvent = e + } + set textTracksCreated(e) { + const t = this["mediaElementStore"]; + t.textTracksCreated = e + } + get msDuration() { + return this._mediaQuery.msDuration + } + set msDuration(e) { + try { + const t = this["mediaElementStore"] + , i = this.mediaSource$.value; + i.duration !== e && (i.duration = e, + t.msDuration = e) + } catch (e) { + this.logger.warn(`Error setting duration ${e.message}`) + } + } + set haveEnough(e) { + this.mediaElementStore.haveEnough = e + } + set flushing(e) { + this.mediaElementStore.flushing = e + } + set bufferMonitorTargetDuration(e) { + this.mediaElementStore.bufferMonitorTargetDuration = e + } + get textTracks() { + return this.mediaElement.textTracks + } + addTextTrack(e, t, i) { + return this.mediaElement.addTextTrack(e, t, i) + } + dispatchEvent(e) { + return this.mediaElement.dispatchEvent(e) + } + get offsetWidth() { + return this.mediaElement.offsetWidth + } + get offsetHeight() { + return this.mediaElement.offsetHeight + } + archiveParsedSubtitleFragmentRecord(e, t, i) { + return this.mediaElementStore.archiveParsedSubtitleFragmentRecord(e, t, i) + } + updateLiveSeekableRange(e) { + var t = e.fragments + , e = t.length; + if (1 < e) { + const i = t[0].start + , r = t[e - 1].start + t[e - 1].duration; + this.mediaSource$.value.updateLiveSeekableRange(i, r) + } + } + clearLiveSeekableRange() { + this.mediaSource$.value.clearLiveSeekableRange() + } + } + const pf = (r,n,s,a,o,d)=>e=>e.pipe(Ra(t=>{ + if (!t) + return Ti; + const e = wc(t); + return nn(e.event("durationchange").pipe(ur(e=>Ac(t, "durationchange", e)), Ja(e=>{ + e = e.currentTarget; + r.mediaElementDuration = e.duration + } + )), e.event("seeking").pipe(so(o.seekEventThrottleMs), ur(e=>Ac(t, "seeking", e)), Ja(e=>{ + var t = e.currentTarget + , e = t.currentTime; + if (t.readyState >= t.HAVE_METADATA) { + const i = n.seekTo; + !i || !i.fromEvent && 1e-5 < Math.abs(i.pos - e) ? a.inGaplessMode ? function(e, t, i, r, n) { + let s = !1; + e < t.playingItem.itemStartOffset && (n.warn(`[Gapless] Seeking past track boundary oldSeek=${e}, adjustedSeek=${t.playingItem.itemStartOffset}`), + e = t.playingItem.itemStartOffset, + s = !0), + t.isPreloading && (e > t.loadingItem.itemStartOffset && (n.warn(`[Gapless] Seeking past track boundary oldSeek=${e}, adjustedSeek=${t.loadingItem.itemStartOffset}`), + e = t.loadingItem.itemStartOffset, + s = !0), + t.dequeueSource("SeekToUnbufferedTimeRanges")), + s ? i.resetMediaSource(e) : r.setSeekToPos(e, !0) + }(e, a, s, r, d) : r.setSeekToPos(e, !0) : r.seeking = !0 + } + } + )), e.event("seeked").pipe(ur(e=>Ac(t, "seeked", e)), Ja(()=>{ + r.setSeekToPos(null, !0) + } + )), e.event("play").pipe(ur(e=>Ac(t, "play", e)), So(n.desiredRate$), ur(([e])=>{ + var t = e.currentTarget; + r.paused = t.paused; + var i = s.expectPlayEvent + , t = t.controls || o.nativeControlsEnabled; + return !i && t && (s.checkForReplay(), + r.desiredRate = 1), + s.expectPlayEvent = !1, + e + } + )), e.event("playing").pipe(ur(e=>Ac(t, "playing", e)), Ja(e=>{ + e = e.currentTarget; + r.paused = e.paused, + r.gotPlayingEvent() + } + )), e.event("loadstart").pipe(ur(e=>Ac(t, "loadstart", e)), Ja(()=>{ + r.gotLoadStartEvent() + } + )), e.event("pause").pipe(ur(e=>Ac(t, "pause", e)), Ja(e=>{ + var t = e.currentTarget; + r.paused = t.paused; + e = s.expectPauseEvent, + t = t.controls || o.nativeControlsEnabled; + !e && t && (r.desiredRate = 0), + s.expectPauseEvent = !1 + } + )), e.event("loadedmetadata").pipe(ur(e=>Ac(t, "loadedmetadata", e))), e.event("loadeddata").pipe(ur(e=>Ac(t, "loadeddata", e))), e.event("canplay").pipe(ur(e=>Ac(t, "canplay", e))), e.event("canplaythrough").pipe(ur(e=>Ac(t, "canplaythrough", e))), e.event("waiting").pipe(ur(e=>Ac(t, "waiting", e))), e.event("emptied").pipe(ur(e=>Ac(t, "emptied", e))), e.event("error").pipe(ur(e=>Ac(t, "error", e)), qn(e=>Ui(t.error))), e.event("ended").pipe(ur(e=>Ac(t, "ended", e)))).pipe(So(n.bufferedRangeTuple$), od(([e])=>{ + var t = e.currentTarget + , e = t.readyState; + r.readyState = e, + r.ended = t.ended + } + ), Un(e=>e instanceof MediaError ? (d.warn(`mediaElementError, code: ${e.code}, message: ${e.message}`), + Ui(e)) : (d.error(`media event error: ${e.message}`), + Ti))) + } + ), Ra(()=>Ti)); + function ff(e, t, i, r, n, s) { + const a = null == e ? void 0 : e.bufferedSegments; + if (!a) + return s.warn("getMatchingInfo trying to query null sbEntity"), + null; + let o = a.find(e=>t >= e.startPTS && t < e.endPTS && e.frag.discoSeqNum === i); + if (!o) { + const e = a[0] && Math.abs(+a[0].startPTS) < r ? a[0] : void 0; + e && t < e.startPTS && i === e.frag.discoSeqNum && (o = e) + } + if (null == o) + return null; + { + const {audioCodec: t, videoCodec: r, mimeType: s} = e; + return { + mimeType: s, + audioCodec: t, + videoCodec: r, + startPTSSec: o.startPTS, + endPTSSec: o.endPTS, + discoSeqNum: i, + mediaOptionId: n + } + } + } + const mf = new class extends pd { + constructor() { + super({}, { + name: "media-element-store", + producerFn: vc + }), + this._activeId = "" + } + get activeId() { + return this._activeId + } + startMediaSession(i, r, n, s) { + return Co("playback.session.start"), + this._activeId = `media session: ${(new Date).toISOString()}`, + sd(()=>{ + var e = s + , t = Math.max(e, r - e) + , t = { + id: this.activeId, + desiredRate: !i.autoplay && i.paused ? 0 : 1, + paused: i.paused, + gotPlaying: !1, + gotLoadStart: !1, + seeking: i.seeking, + flushing: !1, + readyState: i.readyState, + ended: i.ended, + bufferedRanges: [], + haveEnough: !1, + mediaSourceEntity: null, + expectedSbCount: NaN, + bufferMonitorInfo: { + waterLevelType: null, + almostDryWaterLevelSeconds: n, + lowWaterLevelSeconds: e, + highWaterLevelSeconds: t, + maxBufferSeconds: r + }, + mediaOptionParsedSubtitleRecord: [], + textTracksCreated: !1, + waitingForDisco: !1 + }; + this.add(t), + this.setActive(this.activeId) + } + ), + this.activeId + } + setMediaSourceEntity(t, i) { + Co("playback.set.msObjectUrl"), + this.updateActive(e=>{ + e.mediaSourceEntity = null != t && null != i ? { + objectUrl: t, + readyState: i, + duration: NaN, + sourceBufferEntities: [null, null] + } : null, + e.bufferedRanges = [], + e.haveEnough = !1, + e.readyState = 0, + e.bufferMonitorInfo.waterLevelType = null + } + ) + } + set mediaElementDuration(t) { + Co("playback.set.mediaElementDuration"), + this.updateActive(e=>{ + e && (e.mediaElementDuration = t) + } + ) + } + set msReadyState(t) { + Co("playback.set.msReadyState"), + this.updateActive(({mediaSourceEntity: e})=>{ + e && (e.readyState = t) + } + ) + } + set readyState(t) { + Co(`playback.set.readyState ${t}`), + this.updateActive(e=>{ + e.readyState = t + } + ) + } + set ended(t) { + Co(`playback.set.ended ${t}`), + this.updateActive(e=>{ + e.ended = t + } + ) + } + set msDuration(t) { + Co("playback.set.msDuration"), + this.updateActive(e=>{ + e.mediaSourceEntity.duration = t + } + ) + } + set textTracksCreated(t) { + Co("playback.set.textTracksCreated ${created}"), + this.updateActive(e=>{ + e.textTracksCreated = t + } + ) + } + set expectedSbCount(t) { + Co("playback.set.expectedSbCount"), + this.updateActive(e=>{ + e.expectedSbCount = t + } + ) + } + set autoPausedRestartTime(e) { + this.updateActive({ + autoPausedRestartTime: e + }) + } + setSeekToPos(t, i) { + Co(`playback.set.seekToPos: ${null == t ? void 0 : t.toFixed(3)}`), + this.updateActive(e=>{ + ne(t) ? (e.seekTo = { + pos: t, + fromEvent: i + }, + e.gotPlaying = !1, + e.haveEnough = !1) : e.seekTo = null, + i && (e.seeking = ne(t)) + } + ) + } + set seeking(t) { + Co(`playback.set.seeking: ${t}`), + this.updateActive(e=>{ + e.seeking = t + } + ) + } + set paused(t) { + Co(`playback.set.paused: ${t}`), + this.updateActive(e=>{ + (e.paused = t) && (e.gotPlaying = !1) + } + ) + } + gotPlayingEvent() { + Co("playback.set.playing"), + this.updateActive(e=>{ + e.paused || (e.gotPlaying = !0) + } + ) + } + gotLoadStartEvent() { + Co("playback.set.loadstart"), + this.updateActive(e=>{ + e.gotLoadStart = !0 + } + ) + } + set desiredRate(t) { + Co(`playback.set.desiredRate: ${t}`), + this.updateActive(e=>{ + e.desiredRate = t + } + ) + } + set haveEnough(t) { + Co(`playback.set.haveEnough: ${t}`), + this.updateActive(e=>{ + e.haveEnough = t + } + ) + } + set flushing(e) { + Co(`playback.set.flushing: ${e}`), + this.updateActive({ + flushing: e + }) + } + set waitingForDisco(t) { + Co(`playback.set.waitingForDisco: ${t}`), + this.updateActive(e=>{ + e && (e.waitingForDisco = t) + } + ) + } + setSourceBufferUpdating(i) { + Co(`playback.set.sourcebuffers[${Pl[i]}].updating`), + this.updateActive(({mediaSourceEntity: e})=>{ + const t = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[i]; + t && (t.updating = !0, + t.error = void 0) + } + ) + } + setTimestampOffset(i, r) { + Co(`playback.set.sourcebuffers[${Pl[i]}].timestampOffset`), + this.updateActive(({mediaSourceEntity: e})=>{ + const t = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[i]; + t && (t.timestampOffset = r) + } + ) + } + setBufferedRangesUpdated(n, s, a, o, d) { + Co(`playback.set.sourcebuffers[${Pl[n]}].bufferupdated`), + this.updateActive(e=>{ + var t; + const i = null == e ? void 0 : e.mediaSourceEntity + , r = null === (t = null == i ? void 0 : i.sourceBufferEntities) || void 0 === t ? void 0 : t[n]; + if (r) { + const n = null == i ? void 0 : i.duration; + r.updating = !1, + r.bufferedRanges = [...s], + function(e, t, i, r) { + const n = e.inFlight + , s = e.bufferedSegments; + n && ne(n.startPTS) && ne(n.endPTS) && function(t, i) { + let r = !1; + for (let e = t.length - 1; -1 < e; e--) { + const s = t[e] + , a = Math.max(i.startPTS, s.startPTS) + , o = Math.min(i.endPTS, s.endPTS); + var n; + o <= a || ((n = (1 - (o - a) / (s.endPTS - s.startPTS)) * s.bytes) <= 0 ? t.splice(e, 1) : (s.bytes = n, + s.startPTS < i.startPTS ? s.endPTS = a : (s.startPTS = o, + r || (t.splice(e, 0, i), + r = !0)))) + } + r || t.push(i) + }(s, n); + const a = e.bufferedRanges; + let o, d = 0; + for (let e = s.length - 1; -1 < e; e--) { + const t = s[e] + , n = !t.frag.iframe; + n && t.frag.isLastFragment && (o = t.frag); + var l = t.endPTS - t.startPTS; + if (l <= 0) + s.splice(e, 1); + else { + var u = a.find(e=>e.start <= t.endPTS && e.end > t.startPTS); + if (u) { + const a = Math.max(u.start, t.startPTS) + , o = Math.min(u.end, t.endPTS) + , c = o - a; + if (d += t.bytes * c / l, + n) + if (c < Math.min(l, i)) + s.splice(e, 1); + else { + const n = t.appendedDuration; + n ? !(n > c && c != l) || t.frag.isLastFragment && o === r || s.splice(e, 1) : t.appendedDuration = c + } + } else + s.splice(e, 1) + } + } + e.totalDuration = o && 0 < a.length ? a[a.length - 1].end : 1 / 0, + e.inFlight = null, + e.gotQuotaExceeded = e.gotQuotaExceeded || t, + e.totalBytes = d, + e.maxTotalBytes = Math.max(e.totalBytes, e.maxTotalBytes) + }(r, o, d, n) + } + e.bufferedRanges = [...a] + } + ) + } + setSourceBufferEntity(n, s) { + Co(`playback.set.sourcebuffers[${Pl[n]}].setSourceBufferEntity`), + this.updateActive(({mediaSourceEntity: e})=>{ + var t, i, r; + e && ({mimeType: t, audioCodec: i, videoCodec: r} = s, + e.sourceBufferEntities[n] = { + mimeType: t, + audioCodec: i, + videoCodec: r, + updating: !1, + bufferedRanges: [], + timestampOffset: 0, + inFlight: null, + bufferedSegments: [], + totalBytes: 0, + maxTotalBytes: 0, + gotQuotaExceeded: !1, + totalDuration: 1 / 0 + }) + } + ) + } + setInflightSegment(i, r) { + Co(`playback.set.sourcebuffers[${Pl[i]}].setInflightSegment`), + this.updateActive(({mediaSourceEntity: e})=>{ + const t = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[i]; + t && (t.inFlight = r) + } + ) + } + setInitSegmentEntity(i, r) { + Co(`playback.set.sourcebuffers[${Pl[i]}].setInitSegmentEntity`), + this.updateActive(({mediaSourceEntity: e})=>{ + const t = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[i]; + t && (t.initSegmentInfo = r) + } + ) + } + setSourceBufferError(i, r) { + Co(`playback.set.sourcebuffers[${i}].error: ${r}`), + this.updateActive(({mediaSourceEntity: e})=>{ + const t = null === (e = null == e ? void 0 : e.sourceBufferEntities) || void 0 === e ? void 0 : e[i]; + t && (t.inFlight = null, + t.updating = !1, + t.error = r) + } + ) + } + setStallInfo(t) { + Co(`playback.set.stallInfo stalled=${null != t}`), + this.updateActive(e=>{ + e.stallInfo = t + } + ) + } + setNudgeInfo(t) { + Co(`playback.set.nudgeInfo ${se(t)}`), + this.updateActive(e=>{ + e.nudgeInfo = t + } + ) + } + updateWaterLevels(t, i) { + Co("playback.set.updateWaterLevels"), + this.updateActive(e=>{ + e.bufferMonitorInfo.waterLevelType = { + combined: t, + sbTuple: [...i] + } + } + ) + } + set bufferMonitorTargetDuration(i) { + Co(`playback.set.targetDuration: ${i}`), + this.updateActive(e=>{ + if (ne(i) && 0 < i) { + const t = e.bufferMonitorInfo; + t.lowWaterLevelSeconds = Math.min(i, t.maxBufferSeconds), + t.highWaterLevelSeconds = Math.max(t.lowWaterLevelSeconds, t.maxBufferSeconds - i) + } + } + ) + } + archiveParsedSubtitleFragmentRecord(i, r, n) { + Co(`playback.cues.set persistentId ${i} mediaSeqNum ${r}: parsed ${n.count} time-range ${n.startTime}:${n.endTime}`), + this.updateActive(e=>{ + let t = e.mediaOptionParsedSubtitleRecord[i]; + t || (t = {}, + e.mediaOptionParsedSubtitleRecord[i] = t), + t[r] = n + } + ) + } + } + ; + class gf extends Si { + constructor(e) { + super(e), + this.store = e, + this.displaySupportsHdr$ = this.select("supportsHdr"), + this.platformInfo$ = this.select("platformInfo"), + this.viewportInfo$ = this.select("viewportInfo") + } + get platformInfo() { + return this.getValue().platformInfo + } + get displaySupportsHdr() { + return this.getValue().supportsHdr + } + get viewportInfo() { + return this.getValue().viewportInfo + } + } + class yf { + constructor(e) { + this.store = e + } + getQuery() { + return new gf(this.store) + } + updateSupportsHdr(t) { + this.store.update(e=>{ + e.supportsHdr = t + } + ) + } + updatePlatformInfo(e) { + this.store.update({ + platformInfo: e + }) + } + updateViewportInfo(t) { + this.store.update(e=>{ + e.viewportInfo = t + } + ) + } + } + const vf = new class extends dd { + constructor() { + super({ + supportsHdr: !0 + }, { + name: "platform", + producerFn: vc + }) + } + } + ; + let Sf = null; + function bf() { + return Sf = Sf || new yf(vf), + Sf + } + class Tf extends Ut { + constructor(e) { + super(), + this._vanillaRPC = e, + this._handler$ = new zt + } + _subscribe(e) { + return e.add(this._handler$.pipe(Kr(([e,t,i])=>e(...t).pipe(Ja({ + next(e) { + i(e, null) + }, + error(e) { + i(null, e) + } + })))).subscribe()), + ()=>{ + this.teardown() + } + } + register(e, i) { + return this._vanillaRPC.register(e, (...t)=>e=>{ + this._handler$.next([i, t, e]) + } + ) + } + invoke(e, t, r) { + return new Ut(i=>{ + this._vanillaRPC.invoke(e, t, r)((e,t)=>{ + null != t ? i.error(t) : (i.next(e), + i.complete()) + } + ) + } + ) + } + teardown() {} + } + class Ef extends Tf { + constructor(e) { + super(e) + } + decrypt(e, t, i, r, n) { + return this.invoke("decrypt", [e, t, i, r, n], [e, t, r]) + } + } + class If extends Tf { + constructor(e) { + super(e), + this.rpcService = e, + this.sessions = {}, + this._onEvent = (e,t,i)=>()=>{ + null != this.sessions[e] && this.sessions[e].observer.trigger(t, i) + } + , + this.rpcService.register("demuxer.event", this._onEvent) + } + teardown() { + this.rpcService.unregister("demuxer.event") + } + init(e, t, i) { + return [{maxSeekHole: r, maxBufferHole: n, audioPrimingDelay: s, stretchShortVideoTrack: a, forceKeyFrameOnDiscontinuity: o}] = [t], + this.invoke("demuxer.init", [e, t = { + maxSeekHole: r, + maxBufferHole: n, + audioPrimingDelay: s, + stretchShortVideoTrack: a, + forceKeyFrameOnDiscontinuity: o + }, i], []).pipe(ur(e=>{ + var t = new wf(this,e); + return this.sessions[e] = t + } + )); + var r, n, s, a, o + } + } + class wf { + constructor(e, t) { + this.rpc = e, + this.demuxSessionID = t, + this.observer = new a + } + push(e, t, i, r, n, s, a, o, d, l, u, c, h) { + return this.rpc.invoke("demuxer.push", [this.demuxSessionID, e, t, i, r, n, s, a, o, d, l, u, c], null != h ? h : [e]) + } + pushWithoutTransfer(e, t, i, r, n, s, a, o, d, l, u, c) { + return this.push(e, t, i, r, n, s, a, o, d, l, u, c, []) + } + destroy() { + this.observer.removeAllListeners(), + this.rpc.invoke("demuxer.destroy", [this.demuxSessionID], []).subscribe() + } + } + class Af { + constructor() { + this.handlers = {} + } + register(e, t) { + if (null != this.handlers[e]) + return !1; + this.handlers[e] = t + } + unregister(e) { + if (null != this.handlers[e]) + return !1; + delete this.handlers[e] + } + invoke(e, i) { + return (t=Af._fallbackCallback)=>{ + try { + if (null == this.handlers[e]) + throw new Error(`command ${e} not found`); + this.handlers[e](...i)(t) + } catch (e) { + t(void 0, e) + } + } + } + teardown() { + this.handlers = null + } + } + Af._fallbackCallback = (e,t)=>{ + if (null != t) + throw t + } + ; + const Of = e=>{ + e = e.child({ + name: "InlineRPCService" + }); + var t = new Af; + return new i(t,e), + new at(t,e), + t + } + ; + let kf; + const Cf = t=>{ + try { + return (e=>{ + try { + if (null == kf) { + const e = new Blob(["(" + Ky.toString() + ")(true);"],{ + type: "text/javascript" + }) + , r = URL.createObjectURL(e); + kf = new Worker(r) + } + var t = new ot(kf); + return i = t, + n = e.child({ + name: "WorkerRPCService" + }), + i.register("logger.log", (e,i,...r)=>t=>{ + try { + for (const i of e) + n = n.child(i); + "function" == typeof n[i] && n[i](...r), + t() + } catch (e) { + t(void 0, e) + } + } + ), + t + } catch (e) { + throw new Error("Failed to create WebWorker") + } + var i, n + } + )(t) + } catch (e) { + t.warn(e) + } + return Of(t) + } + , Df = a=>(e,t)=>{ + let i = 0 + , r = 0; + for (var {timestamp: n, value: s} of e) { + const e = Math.pow(Math.max(0, n - t) / 1e3, a); + i += e * s, + r += e + } + return i / r + } + , Mf = { + "uniform-time-weighted": Df(0), + "linear-time-weighted": Df(1), + "quadratic-time-weighted": Df(2) + }; + class Pf { + constructor(e, t="quadratic-time-weighted", i={ + avgLatencyMs: NaN, + avgBandwidth: NaN + }) { + this.windowSize = e, + this.aggregationMethod = t, + this.latencyEntries = [], + this.bandwidthEntries = [], + this.minEntries = 1, + this.cleanUpExpiredEntries = this.cleanUpExpiredEntries.bind(this), + this.bwSubject = new gi(i) + } + get estimate$() { + return this.bwSubject.asObservable() + } + record(e) { + var {trequest: t, tfirst: i, tload: r, bitsDownloaded: e} = e; + t !== r && (this.recordLatency(t, i), + this.recordBandwidth(t, r, 1e3 * e / (r - t)), + this.bwSubject.closed || (t = this.getEstimate(), + this.bwSubject.next(t))) + } + getEstimate() { + if (this.latencyEntries.length < this.minEntries) + return { + avgLatencyMs: NaN, + avgBandwidth: NaN + }; + const e = performance.now() - this.windowSize + , t = Mf[this.aggregationMethod] + , i = this.latencyEntries.map(({start: e, end: t})=>({ + timestamp: t, + value: t - e, + duration: 1 + })); + this.bandwidthEntries = function(r) { + function n(t, i) { + if (t.length) { + for (let e = 0; e < t.length; e++) + if (t[e].start > i.start || t[e].start === i.start && t[e].end > i.end) { + t.splice(e, 0, i); + break + } + } else + t.push(i) + } + const s = [...r].sort((e,t)=>e.start !== t.start ? e.start - t.start : e.end - t.end) + , t = []; + for (; s.length; ) { + const r = s[0]; + let e; + if (s.shift(), + t.length && (e = t[t.length - 1]), + 0 === t.length || e.end <= r.start) + t.push(r); + else if (r.start === e.start) + r.end === e.end ? e.bitsPerSec += r.bitsPerSec : r.end < e.end || (e.bitsPerSec += r.bitsPerSec, + r.start = e.end, + n(s, r)); + else { + var a = e.end + , o = e.bitsPerSec; + e.end = r.start; + var i = { + start: r.start, + end: Math.min(a, r.end), + bitsPerSec: r.bitsPerSec + o + }; + if (t.push(i), + a !== r.end) { + let e = 0 + , t = 0 + , i = 0; + i = a < r.end ? (e = a, + t = r.end, + r.bitsPerSec) : (e = r.end, + t = a, + o), + n(s, { + start: e, + end: t, + bitsPerSec: i + }) + } + } + } + return t + }(this.bandwidthEntries); + var r = this.bandwidthEntries.map(({end: e, bitsPerSec: t})=>({ + timestamp: e, + duration: 1, + value: t + })); + return { + avgLatencyMs: t(i, e), + avgBandwidth: t(r, e) + } + } + getLatest() { + if (0 === this.latencyEntries.length) + return { + avgLatencyMs: NaN, + avgBandwidth: NaN + }; + var e = this.latencyEntries[this.latencyEntries.length - 1] + , t = this.bandwidthEntries[this.bandwidthEntries.length - 1]; + return { + avgLatencyMs: e.end - e.start, + avgBandwidth: t.bitsPerSec + } + } + recordLatency(e, t) { + this.latencyEntries.push({ + start: e, + end: t + }), + this.updateCleanupTimeout(t) + } + recordBandwidth(e, t, i) { + this.bandwidthEntries.push({ + start: e, + end: t, + bitsPerSec: i + }), + this.updateCleanupTimeout(t) + } + setCleanupTimeout(e) { + this.cleanupTimeout = setTimeout(this.cleanUpExpiredEntries, Math.max(e - performance.now(), 0)), + this.cleanupTimestamp = e + } + clearCleanupTimeout() { + void 0 !== this.cleanupTimeout && (clearTimeout(this.cleanupTimeout), + this.cleanupTimeout = void 0), + this.cleanupTimestamp = void 0 + } + updateCleanupTimeout(e) { + e += this.windowSize; + (!this.cleanupTimestamp || e < this.cleanupTimestamp) && (this.clearCleanupTimeout(), + this.setCleanupTimeout(e)) + } + cleanUpExpiredEntries() { + this.clearCleanupTimeout(); + const t = performance.now() - this.windowSize; + if (this.latencyEntries = this.latencyEntries.filter(e=>e.end >= t), + this.bandwidthEntries = this.bandwidthEntries.filter(e=>e.end >= t), + this.bwSubject.closed || this.bwSubject.next(this.getEstimate()), + 0 < this.latencyEntries.length || 0 < this.bandwidthEntries.length) { + const t = Math.min(...this.latencyEntries.map(e=>e.end), ...this.bandwidthEntries.map(e=>e.end)); + this.updateCleanupTimeout(t) + } + } + destroy() { + this.clearCleanupTimeout() + } + } + const xf = { + setCombinedEstimate: function(t, i, r) { + const n = qe(); + if (void 0 !== t.storage.set) { + var s = t.bandwidthHistoryStorageKey + , a = { + avgLatencyMs: i.avgLatencyMs, + avgBandwidth: i.avgBandwidth + } + , a = Object.assign({}, a, { + expires: Date.now() + t.bandwidthHistoryTTL + }); + try { + t.storage.set(s, JSON.stringify(a)) + } catch (t) { + n.warn(`Error stringifying! Not persisting bandwidth estimates: ${t.message}`) + } + i = { + maxDuration: i.maxDurationSec, + avgFragParseTimeMs: i.avgParseTimeMs, + avgFragBufferCreationDelayMs: i.avgBufferCreateMs, + avgPlaylistLoadTimeMs: i.avgPlaylistLoadTimeMs, + avgPlaylistParseTimeMs: i.avgPlaylistParseTimeMs, + avgInitFragAppendMs: i.avgInitFragAppendMs, + avgDataFragAppendMs: i.avgDataFragAppendMs + }; + let e = t.storageKeyPrefix; + r && (e += r); + try { + t.storage.set(e, JSON.stringify(i)) + } catch (t) { + n.warn(`Error stringifying! Not persisting bandwidth estimates: ${t.message}`) + } + } else + n.warn("storage.set is not supported! Not persisting bandwidth estimates") + }, + getCombinedEstimate: function(t, e) { + const i = qe(); + let r = {}; + if (void 0 === t.storage.get) + return i.warn("storage.get is not supported! unable to retreive bandwidth estimates"), + this.convertStorageJsonToCombinedEstimate(r); + try { + let e = JSON.parse(t.storage.get(t.bandwidthHistoryStorageKey)); + e = null != e && e.expires && e.expires < Date.now() ? null : { + avgLatencyMs: null == e ? void 0 : e.avgLatencyMs, + avgBandwidth: null == e ? void 0 : e.avgBandwidth + }, + r = Object.assign(Object.assign({}, r), e) + } catch (t) { + i.warn(`Unable to get persisted bandwidth history: ${t.message}`) + } + let n = t.storageKeyPrefix; + e && (n += e); + try { + const e = JSON.parse(t.storage.get(n)); + r = Object.assign(Object.assign({}, r), e) + } catch (t) { + i.warn(`Unable to get persisted bandwidth history: ${t.message}`) + } + return this.convertStorageJsonToCombinedEstimate(r) + }, + convertStorageJsonToCombinedEstimate: function(e) { + return { + avgLatencyMs: (null == e ? void 0 : e.avgLatencyMs) || NaN, + avgBandwidth: (null == e ? void 0 : e.avgBandwidth) || NaN, + maxDurationSec: (null == e ? void 0 : e.maxDuration) || NaN, + avgParseTimeMs: (null == e ? void 0 : e.avgFragParseTimeMs) || NaN, + avgBufferCreateMs: (null == e ? void 0 : e.avgFragBufferCreationDelayMs) || NaN, + avgPlaylistLoadTimeMs: (null == e ? void 0 : e.avgPlaylistLoadTimeMs) || NaN, + avgPlaylistParseTimeMs: (null == e ? void 0 : e.avgPlaylistParseTimeMs) || NaN, + avgInitFragAppendMs: (null == e ? void 0 : e.avgInitFragAppendMs) || NaN, + avgDataFragAppendMs: (null == e ? void 0 : e.avgDataFragAppendMs) || NaN + } + }, + getBandwidthEstimate: function(e, t) { + const i = this.getCombinedEstimate(e, t) + , r = { + avgLatencyMs: null == i ? void 0 : i.avgLatencyMs, + avgBandwidth: null == i ? void 0 : i.avgBandwidth + }; + return ne(r.avgLatencyMs) || (r.avgLatencyMs = NaN), + ne(r.avgBandwidth) || (r.avgBandwidth = NaN), + r + }, + getPlaylistEstimate: function(e, t) { + const i = this.getCombinedEstimate(e, t) + , r = { + avgPlaylistLoadTimeMs: null == i ? void 0 : i.avgPlaylistLoadTimeMs, + avgPlaylistParseTimeMs: null == i ? void 0 : i.avgPlaylistParseTimeMs + }; + return ne(r.avgPlaylistLoadTimeMs) || (r.avgPlaylistLoadTimeMs = NaN), + ne(r.avgPlaylistParseTimeMs) || (r.avgPlaylistParseTimeMs = NaN), + r + }, + getFragEstimate: function(e, t) { + const i = this.getCombinedEstimate(e, t) + , r = { + maxDurationSec: null == i ? void 0 : i.maxDurationSec, + avgParseTimeMs: null == i ? void 0 : i.avgParseTimeMs + }; + return ne(r.maxDurationSec) || (r.maxDurationSec = NaN), + ne(r.avgParseTimeMs) || (r.avgParseTimeMs = NaN), + r + }, + getBufferEstimate: function(e, t) { + const i = this.getCombinedEstimate(e, t) + , r = { + avgBufferCreateMs: null == i ? void 0 : i.avgBufferCreateMs, + avgInitFragAppendMs: null == i ? void 0 : i.avgInitFragAppendMs, + avgDataFragAppendMs: null == i ? void 0 : i.avgDataFragAppendMs + }; + return ne(r.avgBufferCreateMs) || (r.avgBufferCreateMs = NaN), + ne(r.avgInitFragAppendMs) || (r.avgInitFragAppendMs = NaN), + ne(r.avgDataFragAppendMs) || (r.avgDataFragAppendMs = NaN), + r + } + }; + var Rf = xf; + class Lf { + constructor(e=0) { + this._minSamples = e, + this._sum = 0, + this._max = Number.NEGATIVE_INFINITY, + this._numSamples = 0 + } + get avg() { + return this._numSamples < this._minSamples ? NaN : this._sum / this._numSamples + } + get max() { + return 0 < this.count ? this._max : NaN + } + get count() { + return this._numSamples + } + reset() { + this._sum = 0, + this._numSamples = 0, + this._max = Number.NEGATIVE_INFINITY + } + add(e) { + this._sum += e, + this._max = Math.max(this._max, e), + ++this._numSamples + } + } + class _f extends Od { + constructor(e, t) { + super(e), + this.id = t + } + getBandwidthEstimate(e, t) { + var i; + const r = Object.assign({}, null === (i = this.statsEntity) || void 0 === i ? void 0 : i.bandwidthEstimate); + if (ne(r.avgBandwidth) && ne(r.avgLatencyMs)) + return r; + if (e) { + const i = xf.getBandwidthEstimate(e, t); + ne(r.avgBandwidth) || (r.avgBandwidth = i.avgBandwidth), + ne(r.avgLatencyMs) || (r.avgLatencyMs = i.avgLatencyMs) + } + return r + } + getPlaylistEstimate(e, t) { + var i; + const r = Object.assign({}, null === (i = this.statsEntity) || void 0 === i ? void 0 : i.playlistEstimate) + , n = e=>ne(e.avgPlaylistLoadTimeMs) && ne(e.avgPlaylistParseTimeMs); + if (n(r)) + return r; + if (e) { + const i = xf.getPlaylistEstimate(e, t); + if (ne(r.avgPlaylistLoadTimeMs) || (r.avgPlaylistLoadTimeMs = i.avgPlaylistLoadTimeMs), + ne(r.avgPlaylistParseTimeMs) || (r.avgPlaylistParseTimeMs = i.avgPlaylistParseTimeMs), + n(r)) + return r; + ne(r.avgPlaylistLoadTimeMs) || (r.avgPlaylistLoadTimeMs = e.statDefaults.playlistLoadTimeMs), + ne(r.avgPlaylistParseTimeMs) || (r.avgPlaylistParseTimeMs = e.statDefaults.playlistParseTimeMs) + } + return r + } + getBufferEstimate(e, t) { + var i; + const r = Object.assign({}, null === (i = this.statsEntity) || void 0 === i ? void 0 : i.bufferEstimate) + , n = e=>ne(e.avgBufferCreateMs) && ne(e.avgDataFragAppendMs) && ne(e.avgInitFragAppendMs); + if (n(r)) + return r; + if (e) { + const i = xf.getBufferEstimate(e, t); + if (ne(r.avgBufferCreateMs) || (r.avgBufferCreateMs = i.avgBufferCreateMs), + ne(r.avgDataFragAppendMs) || (r.avgDataFragAppendMs = i.avgDataFragAppendMs), + ne(r.avgInitFragAppendMs) || (r.avgInitFragAppendMs = i.avgInitFragAppendMs), + n(r)) + return r; + ne(r.avgBufferCreateMs) || (r.avgBufferCreateMs = e.statDefaults.fragBufferCreationDelayMs), + ne(r.avgDataFragAppendMs) || (r.avgDataFragAppendMs = e.statDefaults.dataFragAppendMs), + ne(r.avgInitFragAppendMs) || (r.avgInitFragAppendMs = e.statDefaults.initFragAppendMs) + } + return r + } + getFragEstimate(e, t) { + var i; + const r = Object.assign({}, null === (i = this.statsEntity) || void 0 === i ? void 0 : i.fragEstimate) + , n = e=>ne(e.maxDurationSec) && ne(e.avgParseTimeMs); + if (n(r)) + return r; + if (e) { + const i = xf.getFragEstimate(e, t); + if (ne(r.maxDurationSec) || (r.maxDurationSec = i.maxDurationSec), + ne(r.avgParseTimeMs) || (r.avgParseTimeMs = i.avgParseTimeMs), + n(r)) + return r; + ne(r.maxDurationSec) || (r.maxDurationSec = e.defaultTargetDuration), + ne(r.avgParseTimeMs) || (r.avgParseTimeMs = e.statDefaults.fragParseTimeMs) + } + return r + } + getCombinedEstimate() { + return Object.assign(Object.assign(Object.assign(Object.assign({}, this.getFragEstimate()), this.getPlaylistEstimate()), this.getBufferEstimate()), this.getBandwidthEstimate()) + } + get statsEntity() { + return this.getEntity(this.id) + } + get bandwidthSample() { + var e; + return null === (e = this.statsEntity) || void 0 === e ? void 0 : e.bandwidthSample + } + get bandwidthStatus() { + var e; + return null === (e = this.statsEntity) || void 0 === e ? void 0 : e.bandwidthStatus + } + get fragSample() { + var e; + return null === (e = this.statsEntity) || void 0 === e ? void 0 : e.fragSample + } + get bandwidthEstimate$() { + return this.selectEntity(this.id, "bandwidthEstimate") + } + get fragEstimate$() { + return this.selectEntity(this.id, "fragEstimate") + } + get playlistEstimate$() { + return this.selectEntity(this.id, "playlistEstimate") + } + get bufferEstimate$() { + return this.selectEntity(this.id, "bufferEstimate") + } + get bandwidthSample$() { + return this.selectEntity(this.id, ({bandwidthSample: e})=>e).pipe(Up()) + } + get fragSample$() { + return this.selectEntity(this.id, ({fragSample: e})=>e).pipe(Up()) + } + get playlistSample$() { + return this.selectEntity(this.id, ({playlistSample: e})=>e).pipe(Up()) + } + get bufferMetric$() { + return this.selectEntity(this.id, ({bufferMetric: e})=>e).pipe(Up()) + } + } + class Nf { + constructor(e) { + this.statsStore = e + } + getQuery() { + return new Od(this.statsStore) + } + getQueryForItem(e) { + return new _f(this.statsStore,e) + } + remove(e) { + this.statsStore.remove(e) + } + removeAll() { + this.statsStore.remove() + } + setBandwidthSample(e) { + this.statsStore.bandwidthSample = e + } + setFragSample(e) { + this.statsStore.fragSample = e + } + setPlaylistSample(e) { + this.statsStore.playlistSample = e + } + setBufferMetric(e) { + this.statsStore.bufferMetric = e + } + setBandwidthEstimate(e) { + this.statsStore.bandwidthEstimate = e + } + setFragEstimate(e) { + this.statsStore.fragEstimate = e + } + setPlaylistEstimate(e) { + this.statsStore.playlistEstimate = e + } + setBufferEstimate(e) { + this.statsStore.bufferEstimate = e + } + } + const Ff = new class extends pd { + constructor() { + super({}, { + name: "stats-store", + producerFn: vc + }) + } + set statsEntity(e) { + Co("statsStore.set.stats"), + sd(()=>{ + this.add(e), + this.setActive(e.id) + } + ) + } + set playlistSample(t) { + Co(`stats.set.playlistSample: ${t}`), + this.updateActive(e=>{ + e.playlistSample = t + } + ) + } + set bandwidthSample(t) { + Co(`stats.set.bandwidthSample: ${t}`), + this.updateActive(e=>{ + e.bandwidthSample = t, + e.bandwidthStatus.bandwidthSampleCount += 1, + e.bandwidthStatus.instantBw = 8e3 * t.loaded / (t.tload - t.trequest) + } + ) + } + set fragSample(t) { + Co(`stats.set.fragSample: ${t}`), + this.updateActive(e=>{ + e.fragSample = t + } + ) + } + set bufferMetric(t) { + Co(`stats.set.bufferMetric: ${t}`), + this.updateActive(e=>{ + e.bufferMetric = t + } + ) + } + set bandwidthEstimate(t) { + Co(`stats.set.bandwidthEstimate: ${t}`), + this.updateActive(e=>{ + e.bandwidthEstimate = t + } + ) + } + set fragEstimate(t) { + Co(`stats.set.fragEstimate: ${t}`), + this.updateActive(e=>{ + e.fragEstimate = t + } + ) + } + set playlistEstimate(t) { + Co(`stats.set.playlistEstimate: ${t}`), + this.updateActive(e=>{ + e.playlistEstimate = t + } + ) + } + set bufferEstimate(t) { + Co(`stats.set.bufferEstimate: ${t}`), + this.updateActive(e=>{ + e.bufferEstimate = t + } + ) + } + } + ; + let Bf = null; + const Uf = e=>new _f(Ff,e); + function $f(e, t) { + if (e === t) + return !0; + if (!e || !t) + return !1; + let i = Object.keys(e).length === Object.keys(t).length; + for (const r of Object.keys(e)) + i = i && (isNaN(e[r]) && isNaN(t[r]) || e[r] === t[r]); + return i + } + function Vf(f, m, g) { + return new Ut(e=>{ + (e=>{ + const t = Uf(e); + t.hasEntity(e) ? Bi(t) : (i = Ff, + e = e, + Co("stats.loading"), + i.setLoading(!0), + i.statsEntity = { + id: e, + bandwidthEstimate: { + avgLatencyMs: NaN, + avgBandwidth: NaN + }, + bandwidthStatus: { + bandwidthSampleCount: 0, + instantBw: NaN + }, + fragEstimate: { + maxDurationSec: NaN, + avgParseTimeMs: NaN + }, + playlistEstimate: { + avgPlaylistLoadTimeMs: NaN, + avgPlaylistParseTimeMs: NaN + }, + bufferEstimate: { + avgBufferCreateMs: NaN, + avgInitFragAppendMs: NaN, + avgDataFragAppendMs: NaN + } + }, + i.setLoading(!1), + Co("stats.loaded")); + var i + } + )(g.itemId); + const t = Uf(g.itemId) + , {fragSample$: i, playlistSample$: r, bandwidthSample$: n, bufferMetric$: s} = t; + return nn(r.pipe(Hi(Zi), (h = f, + p = m, + e=>e.pipe(Ql.tag("statsPlaylistProcessingEpic.in"), na((e,t)=>(e.playlistLoadTimeMs.add(t.playlistLoadTimeMs), + e.playlistParseTimeMs.add(t.playlistParseTimeMs), + e), { + playlistLoadTimeMs: new Lf(h.minPlaylistCount), + playlistParseTimeMs: new Lf(h.minPlaylistCount) + }), ur(e=>({ + avgPlaylistLoadTimeMs: e.playlistLoadTimeMs.avg, + avgPlaylistParseTimeMs: e.playlistParseTimeMs.avg + })), Es($f), Ja(e=>{ + p.setPlaylistEstimate(e) + } + )))), n.pipe(Hi(Zi), (u = f, + c = m, + n=>new Ut(e=>{ + let t = new Pf(u.bandwidthHistoryWindowSize,u.bandwidthHistoryAggregationMethod,{ + avgLatencyMs: NaN, + avgBandwidth: NaN + }); + const i = t.estimate$ + , r = nn(n.pipe(an(e=>e.complete), Ja(e=>{} + ), ur(e=>({ + trequest: e.trequest, + tfirst: e.tfirst, + tload: e.tload, + bitsDownloaded: 8 * e.loaded + })), Ql.tag("statsBandwidthProcessingEpic.in"), Ra(e=>(t.record(e), + Ti))), i.pipe(Es(), Ql.tag("statsBandwidthProcessingEpic.change"), Ja(e=>{ + c && c.setBandwidthEstimate(e) + } + ))).subscribe(e); + return ()=>{ + r.unsubscribe(), + t.destroy(), + t = void 0 + } + } + ))), i.pipe(Hi(Zi), (d = f, + l = m, + e=>e.pipe(Ql.tag("statsFragProcessingEpic.in"), na((e,t)=>(e.durationSec.add(t.durationSec), + e.fragParseMs.add(t.parseTimeMs), + e), { + durationSec: new Lf, + fragParseMs: new Lf(d.minFragmentCount) + }), ur(e=>({ + maxDurationSec: e.durationSec.max, + avgParseTimeMs: e.fragParseMs.avg + })), Es($f), Ja(e=>l.setFragEstimate(e))))), s.pipe(Hi(Zi), (a = f, + o = m, + e=>e.pipe(Ql.tag("statsBufferMetricProcessingEpic.in"), na((e,t)=>(ne(t.bufferCreationStart) && ne(t.bufferCreationEnd) && e.bufferCreateMs.add(t.bufferCreationEnd - t.bufferCreationStart), + ne(t.startInitAppend) && ne(t.endInitAppend) && e.initFragAppendMs.add(t.endInitAppend - t.startInitAppend), + ne(t.startDataAppend) && ne(t.endDataAppend) && e.dataFragAppendMs.add(t.endDataAppend - t.startDataAppend), + e), { + bufferCreateMs: new Lf, + initFragAppendMs: new Lf, + dataFragAppendMs: new Lf(a.minFragmentCount) + }), ur(e=>({ + avgBufferCreateMs: e.bufferCreateMs.avg, + avgInitFragAppendMs: e.initFragAppendMs.avg, + avgDataFragAppendMs: e.dataFragAppendMs.avg + })), Es($f), Ja(e=>{ + o.setBufferEstimate(e) + } + ))))).pipe(Ua(Ti)).subscribe(e), + ()=>{ + Rf.setCombinedEstimate(f, Object.assign(Object.assign(Object.assign(Object.assign({}, t.getFragEstimate()), t.getPlaylistEstimate()), t.getBufferEstimate()), t.getBandwidthEstimate()), g.serviceName), + m.remove(g.itemId) + } + ; + var a, o, d, l, u, c, h, p + } + ) + } + const Kf = { + isWebkitMediaElement: e=>"webkitDroppedFrameCount"in e, + isHtmlVideoElement: e=>"getVideoPlaybackQuality"in e, + timeRangeToArray(t) { + const i = []; + for (let e = 0; e < t.length; e++) + i.push([t.start(e), t.end(e)]); + return i + } + }; + class Hf extends Ut { + constructor() { + super(e=>this.works$.pipe(ur(e=>Lr(e)), zr()).subscribe(e)), + this.works$ = new zt + } + addWork(e) { + this.works$.next(e) + } + complete() { + this.works$.complete() + } + } + class jf { + constructor(e, t) { + this.hls = e, + this.sessionID = t, + this.rtcQuery = null, + this.accessLogData = this.createAccessLogEntry(), + this.accesslog = [], + this.errorlog = [] + } + destroy() { + this.rtcQuery = null, + this.accesslog = [], + this.errorlog = [], + this.accessLogData = void 0, + this.accessLogReporter = void 0 + } + setRTCQuery(e) { + this.rtcQuery = e + } + setupReporter(e) { + this.accessLogReporter = { + SessionID: this.sessionID, + ClientName: null == e ? void 0 : e.clientName, + ServiceName: null == e ? void 0 : e.serviceName + } + } + addPlayTime(e) { + var t, e = null === (t = this.rtcQuery) || void 0 === t ? void 0 : t.getEntity(e); + !e || "RTC_STATE_PLAY" === (e = e.sessionControlRecord).state && (this.accessLogData.PlayTimeWC = (this.accessLogData.PlayTimeWC || 0) + e.eventStartTime) + } + updatePlaybackInfo(e, t) { + this.accessLogData.ViFrDr = this.rtcQuery.getEntity(e).sessionControlRecord.droppedVideoFrames || 0 + } + updateStallCount(e) { + "RTC_STATE_PLAY" === this.rtcQuery.getEntity(e).sessionControlRecord.state && this.accessLogData.StallCount++ + } + updateMediaEngineStallCount(e) { + "RTC_STATE_PLAY" === this.rtcQuery.getEntity(e).sessionControlRecord.state && this.accessLogData.MediaEngineStallCount++ + } + updateCanPlay(e) { + this.accessLogData.StartupTime = this.rtcQuery.getEntity(e).sessionControlRecord.eventStartTime + } + updateFragLoaded(e, t, i) { + var r; + i.fragType === ul.Variant ? (this.accessLogData.NetBytes += i.bytes, + this.accessLogData.ADT += i.adt, + r = this.aggregateFragObserverdBitrate(i, ++this.accessLogData.fragmentCnt, this.accessLogData.NetBytes, this.accessLogData.ADT), + this.accessLogData.OBRLast = r.obrLast, + this.accessLogData.OBRMean = r.obrMean, + this.aggregateFragMinMaxBitrate(this.accessLogData, r.obr), + this.hls.realCurrentTime > i.startPTS && !t && this.accessLogData.overdue++, + this.hasGap(i.startPTS, i.endPTS, this.accessLogData.lastStartPTS, this.accessLogData.lastEndPTS) && this.addToAccessLog(e), + this.accessLogData.startPTS || (this.accessLogData.startPTS = i.startPTS), + this.accessLogData.lastStartPTS = i.startPTS, + this.accessLogData.lastEndPTS = i.endPTS, + this.accessLogData.videoBytes += i.bytes, + this.accessLogData.videoDuration += i.duration) : i.fragType === ul.AltAudio && (this.accessLogData.audioBytes += i.bytes, + this.accessLogData.audioDuration += i.duration) + } + addToAccessLog(e) { + var t = this.getVariantInfo(e) + , i = this.rtcQuery.getEntity(e).sessionControlRecord.curLevelUrl + , r = this.rtcQuery.getEntity(e).playEndedRecord.PlayType; + if (i && "" !== i) { + r = this.translateToAccessLogItem(e, i, t, r); + if (r) { + const n = this.accesslog.length - 20; + 0 < n && this.accesslog.splice(0, n), + this.accesslog.push(r) + } + this.accessLogData = this.createAccessLogEntry(); + e = this.rtcQuery.getEntity(e).switchCompleteRecord.MediaDur; + this.accessLogData.lastMediaDur = e || this.hls.bufferedDuration + } + } + addToErrorLog(e, t) { + var i = null === (r = this.rtcQuery) || void 0 === r ? void 0 : r.getEntity(e); + if (i) { + var r = Number(("mediaError" === t ? i.playErrorRecord : i.nwErrorRecord).ErrCode) + , i = i.sessionControlRecord.curLevelUrl + , r = this.translateToErrorLogItem(e, i, { + domain: t, + code: r + }); + if (r) { + const e = this.errorlog.length - 20; + 0 < e && this.errorlog.splice(0, e), + this.errorlog.push(r) + } + } + } + getAccessLog(e) { + var t; + const i = this.accesslog.slice(0) + , r = null === (t = this.rtcQuery) || void 0 === t ? void 0 : t.getEntity(e); + if (i && r) { + const t = r.sessionControlRecord.curLevelUrl; + if (t && "" !== t) { + const r = this.getVariantInfo(e) + , n = this.translateToAccessLogItem(e, t, r, this.rtcQuery.getEntity(e).playEndedRecord.PlayType); + n && (n["c-provisional-entry"] = !0, + i.push(n)) + } + } + return i + } + get errorLog() { + return this.errorlog + } + createAccessLogEntry() { + return { + fragmentCnt: 0, + overdue: 0, + startPTS: 0, + obrMax: 0, + obrMin: 0, + audioBytes: 0, + audioDuration: 0, + videoBytes: 0, + videoDuration: 0, + svrAddrChanged: 0, + svrAddr: "", + PlayTimeWC: 0, + ViFrDr: 0, + StallCount: 0, + MediaEngineStallCount: 0, + ADT: 0, + NetBytes: 0, + StartupTime: 0, + OBRMean: 0, + OBRLast: 0 + } + } + convertStringObjectToPrimitive(e) { + return e ? "object" == typeof e ? e.toString() : e : "" + } + updateSvrAddrStats(t) { + const i = fl.parseURL(t); + if (i && i.netLoc) { + const t = i.netLoc.indexOf(":"); + let e = 0 <= t ? i.netLoc.slice(0, t) : i.netLoc; + e.startsWith("//") && (e = e.slice(2)), + this.accessLogData.svrAddr ? e !== this.accessLogData.svrAddr && this.accessLogData.svrAddrChanged++ : this.accessLogData.svrAddrChanged = 0, + this.accessLogData.svrAddr = e + } + } + translateToAccessLogItem(e, t, i, r) { + t = this.convertStringObjectToPrimitive(t); + this.updateSvrAddrStats(t); + let n = this.rtcQuery.getEntity(e).switchCompleteRecord.MediaDur; + n = n || this.hls.bufferedDuration, + n = n || 0; + const s = { + uri: t, + "s-ip": this.accessLogData.svrAddr, + "s-ip-changes": this.accessLogData.svrAddrChanged, + "sc-wwan-count": -1, + "c-transfer-duration": this.accessLogData.ADT, + bytes: this.accessLogData.NetBytes, + "c-total-media-requests": this.accessLogData.fragmentCnt, + "cs-guid": this.accessLogReporter.SessionID, + "c-start-time": this.accessLogData.startPTS, + "c-startup-time": this.accessLogData.StartupTime, + "c-duration-watched": this.accessLogData.PlayTimeWC / 1e3, + "c-frames-dropped": this.accessLogData.ViFrDr, + "c-stalls": this.accessLogData.StallCount + this.accessLogData.MediaEngineStallCount, + "c-duration-downloaded": this.accessLogData.lastMediaDur ? n - this.accessLogData.lastMediaDur : n, + "c-overdue": this.accessLogData.overdue, + "c-avg-video-bitrate": 8 * this.accessLogData.videoBytes / (this.accessLogData.videoDuration || 1), + "c-observed-max-bitrate": this.accessLogData.obrMax, + "c-observed-min-bitrate": this.accessLogData.obrMin, + "sc-indicated-bitrate": i.bandwidth || 0, + "sc-indicated-avg-bitrate": i.avgBandwidth || 0, + "c-observed-bitrate": this.accessLogData.OBRMean, + "c-switch-bitrate": this.accessLogData.OBRLast, + "c-provisional-entry": !1 + }; + return s["s-playback-type"] = r, + this.accessLogData.audioBytes && (s["c-avg-audio-bitrate"] = 8 * this.accessLogData.audioBytes / (this.accessLogData.audioDuration || 1)), + s + } + translateToErrorLogItem(e, t, i) { + t = this.convertStringObjectToPrimitive(t); + return this.updateSvrAddrStats(t), + { + date: new Date, + "cs-guid": this.accessLogReporter.SessionID + "-" + e, + uri: t, + "s-ip": this.accessLogData.svrAddr, + status: "" + i.code, + domain: i.domain + } + } + hasGap(e, t, i, r) { + return void 0 !== e && void 0 !== i && (1 < e - r || 1 < i - t) + } + aggregateFragObserverdBitrate(e, t, i, r) { + r = 8 * i / (r / 1e3); + return { + obr: r, + obrLast: 8 * e.bytes / (e.adt / 1e3), + obrMean: r / t + } + } + aggregateFragMinMaxBitrate(e, t) { + (!e.obrMax || t > e.obrMax) && (e.obrMax = t), + (!e.obrMin || t < e.obrMin) && (e.obrMin = t) + } + getVariantInfo(e) { + var t = this.rtcQuery.getEntity(e).sessionControlRecord.curLevelUrl + , e = null === (e = this.rtcQuery.getEntity(e).sessionControlRecord.manifestData) || void 0 === e ? void 0 : e.variantList; + return t && e && e[t] ? e[t] : {} + } + } + const qf = (r,e,t,i,n,s)=>{ + var a, {absoluteUrl: o, byteRangeOffset: d, keyTagInfo: l, iframe: u, isInitSegment: c} = r, h = o, p = l["method"], {start: o, end: l} = d, t = xc({ + url: h + }, t); + let f, m = o, g = l, y = !1, v = ne(o) || ne(l) ? d : void 0; + if ("AES-128" === p && l && (u || c)) { + const r = l - o; + r % 16 && (g = l + (16 - r % 16)), + 0 !== o && (y = !0, + m = o - 16), + v = { + start: m, + end: g + } + } + return n && ne(r.mediaSeqNum) && r.mediaOptionType === ul.Variant && (f = [], + null === (n = t.reportHTTPResponseHeaders) || void 0 === n || n.forEach(function(e) { + vl.includes(e) ? f.push(e) : qe().warn({ + name: "load-media-fragment" + }, `${e} is not in approved privacy list. Actions required.`) + }), + 0 === f.length && (f = void 0)), + Pc({ + url: h, + byteRangeOffset: v, + checkContentLength: !0, + extendMaxTTFB: s, + collectServerInstanceInfo: f, + onProgress: i, + xhrSetup: e.xhrSetup + }, t).pipe(ur(([e,t,i])=>{ + if (y) { + const t = e; + r.keyTagInfo.iv = new Uint8Array(t.slice(0, 16)), + e = t.slice(16) + } + return [r, e, t, i] + } + ), (a = r, + e=>e.pipe(Un(e=>{ + if (e instanceof ou) + throw new au(!1,"Timeout",0,$.FragmentTimeoutError,!0,a,e.stats); + if (e instanceof tu) + throw new au(!1,e.message,e.code,{ + code: e.code, + text: "Fragment Network Error" + },!1,a); + throw e + } + )))) + } + , Qf = { + clearkey: Zc, + fairplaystreaming: pu, + playready: _c, + widevine: Nc + } + , Gf = { + getKeySystemFormat(e) { + e = Qf[e]; + return e ? e.keyFormatString : "" + }, + getKeySystemSecurityLevel(e) { + e = Qf[e]; + return e ? e.securityLevels : null + } + } + , Wf = { + NONE: "", + "AES-128": "", + "ISO-23001-7": "", + "SAMPLE-AES": "", + "SAMPLE-AES-CTR": "" + } + , zf = { + NONE: 0, + "TYPE-0": 1, + "TYPE-1": 2, + "TYPE-2": 3 + }; + function Xf(e) { + return e in zf + } + function Yf(e) { + return null == e ? 4 : zf[e] + } + const Jf = ["SDR", "PQ", "HLG"] + , Zf = { + afr: "af", + aka: "ak", + amh: "am", + ara: "ar", + arg: "an", + asm: "as", + ava: "av", + ave: "ae", + aym: "ay", + aze: "az", + bam: "bm", + bel: "be", + ben: "bn", + bih: "bh", + bod: "bo", + bos: "bs", + bre: "br", + bul: "bg", + cat: "ca", + ces: "cs", + cha: "ch", + che: "ce", + chu: "cu", + chv: "cv", + cor: "kw", + cos: "co", + cre: "cr", + cym: "cy", + dan: "da", + deu: "de", + div: "dv", + dzo: "dz", + ell: "el", + eng: "en", + epo: "eo", + est: "et", + eus: "eu", + ewe: "ee", + fao: "fo", + fas: "fa", + fin: "fi", + fra: "fr", + fry: "fy", + ful: "ff", + gla: "gd", + gle: "ga", + glg: "gl", + glv: "gv", + grn: "gn", + guj: "gu", + hat: "ht", + heb: "he", + her: "hz", + hin: "hi", + hmo: "ho", + hrv: "hr", + hun: "hu", + hye: "hy", + ibo: "ig", + ido: "io", + iii: "ii", + iku: "iu", + ile: "ie", + ina: "ia", + ind: "id", + isl: "is", + ita: "it", + jav: "jv", + jpn: "ja", + kal: "kl", + kan: "kn", + kas: "ks", + kat: "ka", + kau: "kr", + kaz: "kk", + khm: "km", + kik: "ki", + kin: "rw", + kir: "ky", + kom: "kv", + kon: "kg", + kor: "ko", + kua: "kj", + kur: "ku", + lao: "lo", + lat: "la", + lav: "lv", + lim: "li", + lit: "lt", + ltz: "lb", + lub: "lu", + lug: "lg", + mah: "mh", + mal: "ml", + mar: "mr", + mkd: "mk", + mlg: "mg", + mlt: "mt", + mol: "mo", + mon: "mn", + mri: "mi", + msa: "ms", + mya: "my", + nav: "nv", + nbl: "nr", + nde: "nd", + ndo: "ng", + nep: "ne", + nld: "nl", + nno: "nn", + nob: "nb", + nya: "ny", + oci: "oc", + oji: "oj", + ori: "or", + orm: "om", + oss: "os", + pan: "pa", + pli: "pi", + pol: "pl", + por: "pt", + pus: "ps", + que: "qu", + roh: "rm", + ron: "ro", + run: "rn", + rus: "ru", + san: "sa", + sin: "si", + slk: "sk", + slv: "sl", + sme: "se", + snd: "sd", + som: "so", + spa: "es", + sqi: "sq", + srd: "sc", + srp: "sr", + sun: "su", + swa: "sw", + swe: "sv", + tah: "ty", + tam: "ta", + tat: "tt", + tel: "te", + tgk: "tg", + tgl: "tl", + tha: "th", + tir: "ti", + ton: "to", + tuk: "tk", + tur: "tr", + uig: "ug", + ukr: "uk", + urd: "ur", + uzb: "uz", + ven: "ve", + vie: "vi", + wln: "wa", + yid: "yi", + zha: "za", + zho: "zh" + } + , em = { + isLanguageCode: e=>e in Zf, + shortenLanguageCode(e) { + let t; + var i, r; + return e && (r = 0 <= (i = e.indexOf("-")) ? e.slice(0, i) : e, + em.isLanguageCode(r) && (t = Zf[r]), + t = t || r, + 0 < i && (t += "-" + e.slice(i + 1))), + t + } + } + , tm = { + getRichestVideoCodec(e) { + if (e && e.length) { + e = e.sort((e,t)=>$p(t) - $p(e)); + return e && e.length ? e[0] : void 0 + } + }, + getRichestAudioCodec(e) { + if (e && e.length) { + e = e.sort((e,t)=>Kp(t) - Kp(e)); + return e && e.length ? e[0] : void 0 + } + }, + getRichestChannelLayoutForGroupId(t, i) { + if (t && i && i.length) { + let e; + const r = i.filter(e=>e.groupId === t); + if (r && r.length) { + const t = r.sort((e,t)=>Se.getChannelCount(t.channels) - Se.getChannelCount(e.channels)); + t && t.length && (e = t[0].channels) + } + return e + } + } + }; + function im(e) { + return new R(L,"steeringManifestParsingError",!1,e,$.FormatError) + } + class rm { + constructor(e) { + this._url = null, + this._programDateTime = null, + this._byteRange = null, + this.relurl = null, + this.baseurl = null, + this.isInitSegment = !1, + this.mediaSeqNum = NaN, + this.cc = NaN, + this.iframe = !1, + this.bitrate = NaN, + this.start = NaN, + this.duration = NaN, + this.lastByteRangeEndOffset = NaN, + this.inheritQuery = e, + this.tagList = new Array, + this.iframe = !1 + } + getMediaFragment(e, t, i) { + const r = { + mediaOptionType: i, + absoluteUrl: this.url, + start: this.start, + duration: this.duration, + mediaSeqNum: this.mediaSeqNum, + discoSeqNum: this.cc, + mediaOptionId: t, + itemId: e, + isLastFragment: !1, + isInitSegment: this.isInitSegment + }; + return null !== (e = this.byteRange) && void 0 !== e && e.length && (r.byteRangeOffset = { + start: this.byteRangeStartOffset, + end: this.byteRangeEndOffset + }), + this.iframe && (r.iframe = this.iframe), + this.levelkey && (r.keyTagInfo = this.levelkey), + this.programDateTime && (r.programDateTime = this.programDateTime), + r + } + get url() { + return !this._url && this.relurl && this.baseurl && (this._url = fl.buildAbsoluteURL(this.baseurl, this.relurl, { + alwaysNormalize: !0, + inheritQuery: this.inheritQuery + })), + this._url + } + set url(e) { + this._url = e + } + get programDateTime() { + return !this._programDateTime && this.rawProgramDateTime && (this._programDateTime = new Date(Date.parse(this.rawProgramDateTime))), + this._programDateTime + } + get byteRange() { + if (!this._byteRange) { + const i = new Array(2); + var e, t; + this.rawByteRange && (1 === (e = this.rawByteRange.split("@", 2)).length ? (t = this["lastByteRangeEndOffset"], + i[0] = t || 0) : i[0] = parseInt(e[1]), + i[1] = parseInt(e[0]) + i[0]), + this._byteRange = i + } + return this._byteRange + } + get byteRangeStartOffset() { + return this.byteRange[0] + } + get byteRangeEndOffset() { + return this.byteRange[1] + } + get rangeString() { + return 0 <= this.start && 0 <= this.duration ? `${this.start.toFixed(2)}-${(this.start + this.duration).toFixed(2)}` : "N/A" + } + get fragTag() { + return `sn/cc/levelId: ${this.mediaSeqNum}/${this.cc}` + } + } + const nm = { + parseMediaCharacteristics: e=>e ? e.split(/\s*,\s*/) : new Array, + addMediaToSelectionArray(e, t, i) { + if (void 0 === e) + return -1; + const r = e.MediaSelectionGroupOptions; + let n = r.find(e=>e.MediaSelectionOptionsMediaType === t.mediaType && e.MediaSelectionOptionsName === t.name && e.MediaSelectionOptionsExtendedLanguageTag === t.lang); + return n || (n = { + MediaSelectionOptionsMediaType: t.mediaType, + MediaSelectionOptionsExtendedLanguageTag: t.lang, + MediaSelectionOptionsIsDefault: t.default, + MediaSelectionOptionsName: t.name, + MediaSelectionOptionsPersistentID: i, + MediaSelectionOptionsTaggedMediaCharacteristics: t.characteristics + }, + t.mediaType === pl.SUBTITLE && (n.MediaSelectionOptionsDisplaysNonForcedSubtitles = t.forced ? hl.NO : hl.YES), + i++, + r.push(n)), + t.persistentID = n.MediaSelectionOptionsPersistentID, + i + }, + addDefaultClosedCaptionOption(e, t, i, r) { + e = { + itemId: e, + mediaOptionType: ul.Subtitle, + id: 0, + mediaOptionId: "cc1_" + Jd(), + mediaType: pl.CLOSEDCAPTION, + inStreamID: "CC1", + groupId: "cc", + name: "English-CC", + type: "CLOSED-CAPTIONS", + default: !1, + autoselect: !1, + forced: !1, + lang: "en", + characteristics: ["public.accessibility.transcribes-spoken-dialog", "public.accessibility.describes-music-and-sound"], + persistentID: r + }; + t.push(e), + nm.addMediaToSelectionArray(i, e, r) + } + } + , sm = { + BANDWIDTH: NaN, + "AVERAGE-BANDWIDTH": NaN + } + , am = { + "TIME-OFFSET": NaN, + "FRAME-RATE": NaN, + SCORE: NaN, + "PLANNED-DURATION": NaN, + DURATION: NaN + } + , om = /^(\d+)x(\d+)$/ + , dm = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; + class lm { + constructor(e) { + this.validTags = e + } + isKey(e) { + return e in this.validTags + } + trySetValue(e, t, i) { + return !!this.isKey(e) && (i[e] = this.parseFunc(t), + !0) + } + } + class um { + static parseTags(t) { + let i; + var r = {}; + if (!t) + return r; + for (dm.lastIndex = 0; null !== (i = dm.exec(t)); ) { + const t = i[1].toUpperCase(); + let e = i[2]; + 0 === e.indexOf('"') && e.lastIndexOf('"') === e.length - 1 && (e = e.slice(1, -1)); + for (const i of um.tagParsers) + if (i.trySetValue(t, e, r)) + break + } + return r + } + } + um.tagParsers = [new class extends lm { + parseFunc(e) { + return e + } + } + ({ + NAME: "", + TYPE: "", + DEFAULT: "", + AUTOSELECT: "", + FORCED: "", + LANGUAGE: "", + URI: "", + AUDIO: "", + "VIDEO-RANGE": "", + "CLOSED-CAPTIONS": "", + CODECS: "", + BYTERANGE: "", + "INSTREAM-ID": "", + "GROUP-ID": "", + CHANNELS: "", + CHARACTERISTICS: "", + KEYFORMAT: "", + KEYFORMATVERSIONS: "", + "DATA-ID": "", + VALUE: "", + METHOD: "", + "HDCP-LEVEL": "", + "ALLOWED-CPC": "", + SUBTITLES: "", + ID: "", + CLASS: "", + "START-DATE": "", + "END-DATE": "", + "END-ON-NEXT": "", + "SERVER-URI": "", + "PATHWAY-ID": "" + }), new class extends lm { + parseFunc(e) { + e = parseInt(e); + return e > Number.MAX_SAFE_INTEGER ? 1 / 0 : e + } + } + (sm), new class extends lm { + constructor() { + super(...arguments), + this.parseFunc = parseFloat + } + } + (am), new class extends lm { + parseFunc(e) { + let t = (e || "0x").slice(2); + t = (1 & t.length ? "0" : "") + t; + const i = new Uint8Array(t.length / 2); + for (let e = 0; e < t.length / 2; e++) { + var r = parseInt(t.slice(2 * e, 2 * e + 2), 16); + if (!ne(r)) + return; + i[e] = r + } + return i + } + } + ({ + IV: null + }), new class extends lm { + parseFunc(e) { + e = om.exec(e); + let t; + return null !== e && (t = { + width: parseInt(e[1], 10), + height: parseInt(e[2], 10) + }), + t + } + } + ({ + RESOLUTION: null + })]; + const cm = { + ExtractVariableParameter: /{\$(.*?)}/g, + LevelPlaylistFast: /#EXTINF:(\d*(?:\.\d+)?)(?:,(.*))?|(?!#)(\S.+)|#EXT-X-BYTERANGE: *(.+)|#EXT-X-PROGRAM-DATE-TIME:(.+)|#EXT-X-BITRATE:(.+)|#EXT-X-DATERANGE:(.+)|#.*/g, + LevelPlaylistSlow: /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:#EXT-X-(I-FRAMES)-ONLY)|(?:#EXT-X-(DEFINE):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/, + MasterPlaylist: /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)|#EXT-X-I-FRAME-STREAM-INF:([^\r\n]+)|#EXT-X-DEFINE:([^\n\r]*)|#EXT-X-CONTENT-STEERING:([^\n\r]*)/g, + MasterPlaylistAlternateMedia: /#EXT-X-MEDIA:(.*)/g, + SessionData: /#EXT-X-SESSION-DATA[^:]*:(.*)/g, + SessionKeys: /#EXT-X-SESSION-KEY:([^\n\r]*)/g, + VARIABLE_PLAYLIST_REGEX: /(NAME|VALUE)=\"(.*)\",(NAME|VALUE)=\"(.*)\"|(IMPORT)=\"(.*)\"/ + }; + function hm(e, t, i) { + return sl.buildAbsoluteURL(t, e, { + alwaysNormalize: !0, + inheritQuery: i + }) + } + class pm { + static isValidPlaylist(e) { + return 0 === e.indexOf("#EXTM3U") + } + static isMediaPlaylist(e) { + return 0 < e.indexOf("#EXTINF:") || 0 < e.indexOf("#EXT-X-PLAYLIST-TYPE:") + } + static replaceVariables(e, t) { + let i, r = !1; + return e && t && (i = e.replace(cm.ExtractVariableParameter, e=>{ + cm.ExtractVariableParameter.lastIndex = 0; + e = cm.ExtractVariableParameter.exec(e)[1]; + if (e && t.hasOwnProperty(e)) + return t[e]; + r = !0 + } + )), + { + updatedString: i, + error: r + } + } + static parseDecryptData(e, t, i) { + const r = um.parseTags(e) + , n = (e = r.METHOD) && e in Wf ? r.METHOD : null; + e = null !== (e = r.KEYFORMAT) && void 0 !== e ? e : null; + if (n && pm.shouldSelectKeyTag(e, n, i)) { + const s = r.URI + , i = r.IV || null; + if (s && r.IV && !i) { + const s = new R(L,_,!0,`Invalid IV: ${r.IV}`,$.PlaylistErrorInvalidEntry); + throw s.url = t, + s + } + const a = s ? sl.buildAbsoluteURL(t, s, { + alwaysNormalize: !0 + }) : t + , o = (r.KEYFORMATVERSIONS || "1").split("/").map(Number).filter(isFinite); + return new Gc(n,a,i,e,o) + } + } + static shouldSelectKeyTag(e, t, i) { + return "AES-128" === t || "NONE" === t || null == i || e === Gf.getKeySystemFormat(i) + } + static optOutClosedCaption(t) { + let i = !1 + , r = !1; + if (t) + for (let e = 0; e < t.length; ++e) { + const n = t[e]; + if (n.videoCodec && ((r = !0) !== n.iframes && n.closedcaption && "none" === n.closedcaption.toLowerCase())) { + i = !0; + break + } + } + return !r || i + } + static parseRootPlaylistAlternateMediaOptions(a, o, d, l, u, c) { + let h, p; + var f = { + MediaSelectionGroupAllowEmptySelection: 1, + MediaSelectionGroupMediaCharacteristics: ["public.audible"], + MediaSelectionGroupMediaType: pl.AUDIO, + MediaSelectionGroupOptions: [] + } + , m = { + MediaSelectionGroupAllowEmptySelection: 1, + MediaSelectionGroupMediaCharacteristics: ["public.legible"], + MediaSelectionGroupMediaType: pl.SUBTITLE, + MediaSelectionGroupOptions: [] + } + , g = { + videoAlternateOptions: [], + audioAlternateOptions: [], + subtitleAlternateOptions: [], + audioMediaSelectionGroup: f, + subtitleMediaSelectionGroup: m + }; + let y = 0; + for (cm.MasterPlaylistAlternateMedia.lastIndex = 0; null != (h = cm.MasterPlaylistAlternateMedia.exec(o)); ) { + const o = pm.replaceVariables(h[1], c); + if (o.error) { + p = new R(L,N,!0,$.PlaylistErrorInvalidEXTXDEFINE.text,$.PlaylistErrorInvalidEXTXDEFINE); + break + } + var v = um.parseTags(o.updatedString); + let e, t, i, r = pl.UNKNOWN; + const S = nm.parseMediaCharacteristics(v.CHARACTERISTICS) + , b = v["GROUP-ID"] + , T = v.CHANNELS; + let n, s = null; + switch (v.TYPE) { + case "VIDEO": + r = pl.VIDEO, + t = g.videoAlternateOptions; + break; + case "AUDIO": + r = pl.AUDIO, + s = ul.AltAudio, + t = g.audioAlternateOptions, + i = f; + const a = l.find(e=>e.audioGroupId === b); + n = a ? a.audioCodecList : []; + break; + case "SUBTITLES": + r = pl.SUBTITLE, + s = ul.Subtitle, + t = g.subtitleAlternateOptions, + i = m; + break; + case "CLOSED-CAPTIONS": + r = pl.CLOSEDCAPTION, + s = ul.Subtitle, + e = v["INSTREAM-ID"], + t = g.subtitleAlternateOptions, + i = m + } + const E = { + itemId: a, + mediaOptionType: s, + mediaType: r, + groupId: b, + channels: T, + groupCodecList: n, + name: v.NAME, + type: v.TYPE, + default: "YES" === v.DEFAULT, + autoselect: "YES" === v.AUTOSELECT, + forced: "YES" === v.FORCED, + characteristics: S, + persistentID: y, + id: t ? t.length : 0, + mediaOptionId: `${v.NAME}_${b}_${y}`, + lang: em.shortenLanguageCode(v.LANGUAGE) + }; + v.URI && (E.url = hm(v.URI, d, u)), + E.name || (E.name = E.lang, + E.mediaType === pl.CLOSEDCAPTION && (E.name += " CC")), + E.mediaType === pl.CLOSEDCAPTION && e && (E.inStreamID = e), + t && (E.id = t.length, + t.push(E)), + y = nm.addMediaToSelectionArray(i, E, y) + } + return 0 !== g.subtitleAlternateOptions.length || pm.optOutClosedCaption(l) || nm.addDefaultClosedCaptionOption(a, g.subtitleAlternateOptions, m, y), + { + alternateMediaInfo: g, + playlistParsingError: p + } + } + static parseMediaOptionPlaylist(e, t, i=!0, r, n, s, a, o, d, l=0) { + var u; + let c = 0 + , h = 0; + const p = { + itemId: s, + mediaOptionId: a, + mediaOptionType: o, + type: "", + version: 0, + url: t, + initSegments: {}, + fragments: [], + liveOrEvent: !0, + startSN: 0, + endSN: 0, + iframesOnly: !1, + targetduration: 0, + totalduration: 0, + averagetargetduration: 0, + ptsKnown: !1 + }; + let f, m, g, y = new Gc("NONE",t,null,null,null), v = !1, S = !1, b = 0, T = null, E = new rm(i), I = 0; + const w = {}; + let A, O, k, C = !0, D = !0; + cm.LevelPlaylistFast.lastIndex = 0; + for (var M = ()=>new R(L,_,!0,"Invalid key system preference for the playlist",$.IncompatibleAsset); null !== (f = cm.LevelPlaylistFast.exec(e)); ) { + const e = f[1]; + if (e) { + E.duration = parseFloat(e); + const t = (" " + f[2]).slice(1); + E.title = t || null, + E.tagList.push(t ? ["INF", e, t] : ["INF", e]) + } else if (f[3]) { + if (ne(E.duration)) { + const e = c++; + if (E.start = h + l, + E.levelkey = y, + S && !v) { + O = M(); + break + } + if (v = !1, + S = !1, + E.mediaSeqNum = e, + E.cc = b, + E.iframe = p.iframesOnly, + E.baseurl = t, + (A = pm.replaceVariables((" " + f[3]).slice(1), w)).error) { + O = new R(L,N,!0,$.PlaylistErrorInvalidEXTXDEFINE.text,$.PlaylistErrorInvalidEXTXDEFINE); + break + } + if (E.relurl = A.updatedString, + E.bitrate = ne(E.byteRangeEndOffset) ? 8 * (E.byteRangeEndOffset - E.byteRangeStartOffset) / E.duration : I, + null != g) { + E.rawProgramDateTime = g, + E.tagList.push(["PROGRAM-DATE-TIME", E.rawProgramDateTime]); + const e = E.programDateTime.getTime(); + p.programDateTimeMap = null !== (u = p.programDateTimeMap) && void 0 !== u ? u : {}, + p.programDateTimeMap[e] = E.mediaSeqNum, + p.dateMediaTimePairs = null !== (u = p.dateMediaTimePairs) && void 0 !== u ? u : [], + p.dateMediaTimePairs.push([e, E.start]), + g = void 0 + } + if (p.fragments.push(E.getMediaFragment(s, a, o)), + T = E, + h += E.duration, + C || !p.initSegments[b] || D) + if (p.iframesOnly && 0 < E.byteRangeStartOffset && !p.initSegments[b] && !D) { + const e = new rm(i); + if (e.url = E.url, + e.rawByteRange = Math.min(E.byteRangeStartOffset, 1316) + "@0", + e.baseurl = t, + e.isInitSegment = !0, + e.cc = b, + e.levelkey = y, + e.iframe = !0, + S && !v) { + O = M(); + break + } + v = !1, + S = !1, + p.initSegments[b] = e.getMediaFragment(s, a, o) + } else + k && (k.discoSeqNum = b, + p.initSegments[b] = k); + C = !1, + D = !1, + E = new rm(i) + } + } else if (f[4]) { + if (E.rawByteRange = (" " + f[4]).slice(1), + T) { + const e = T.byteRangeEndOffset; + e && (E.lastByteRangeEndOffset = e) + } + } else if (f[5]) + g = (" " + f[5]).slice(1); + else if (f[6]) { + const e = parseInt(f[6]); + ne(e) && (I = 1e3 * e) + } else if (f[7]) { + const e = f[7] + , t = um.parseTags(e); + t.ID && (p.daterangeTags || (p.daterangeTags = {}), + p.daterangeTags[t.ID] = t) + } else { + for (f = f[0].match(cm.LevelPlaylistSlow), + m = 1; m < f.length && void 0 === f[m]; m++) + ; + const e = pm.replaceVariables((" " + f[m + 1]).slice(1), w) + , d = pm.replaceVariables((" " + f[m + 2]).slice(1), w); + if (e.error || d.error) { + O = new R(L,N,!0,$.PlaylistErrorInvalidEXTXDEFINE.text,$.PlaylistErrorInvalidEXTXDEFINE); + break + } + const l = e.updatedString + , P = d.updatedString; + switch (f[m]) { + case "#": + E.tagList.push(P ? [l, P] : [l]); + break; + case "PLAYLIST-TYPE": + p.type = l.toUpperCase(), + "VOD" === p.type && (p.liveOrEvent = !1); + break; + case "MEDIA-SEQUENCE": + 0 === p.fragments.length && (c = p.startSN = parseInt(l)); + break; + case "TARGETDURATION": + p.targetduration = parseFloat(l); + break; + case "VERSION": + p.version = parseInt(l); + break; + case "EXTM3U": + break; + case "ENDLIST": + p.liveOrEvent = !1; + break; + case "DIS": + b++, + E.tagList.push(["DIS"]), + C = !0; + break; + case "DISCONTINUITY-SEQ": + b = parseInt(l); + break; + case "KEY": + const e = l; + if (S = !0, + !v) { + try { + y = pm.parseDecryptData(e, t, r) + } catch (e) { + O = e + } + y && (v = !0) + } + break; + case "START": + const d = l + , u = um.parseTags(d)["TIME-OFFSET"]; + ne(u) && (p.startTimeOffset = u); + break; + case "I-FRAMES": + p.iframesOnly = !0; + break; + case "MAP": + const h = um.parseTags(l); + if (E.relurl = h.URI, + E.rawByteRange = h.BYTERANGE, + E.baseurl = t, + E.isInitSegment = !0, + E.levelkey = y, + S && !v) { + O = M(); + break + } + v = !1, + S = !1, + k = E.getMediaFragment(s, a, o), + D = !0, + E = new rm(i); + break; + case "DEFINE": + const f = cm.VARIABLE_PLAYLIST_REGEX.exec(l) + , m = "NAME" === f[1] ? f[2] : f[4] + , g = "VALUE" === f[1] ? f[2] : f[4] + , N = f[5] + , T = f[6]; + if (m || g || "IMPORT" !== N || !n.hasOwnProperty(T)) { + if (!m || N || f[1] === f[3] || w.hasOwnProperty(m)) { + O = new R(L,_,!0,$.PlaylistErrorMissingImportReference.text,$.PlaylistErrorMissingImportReference); + break + } + w[m] = g + } else + w[T] = n[T] + } + } + } + return E = T, + E && !E.relurl && (p.fragments.pop(), + h -= E.duration), + !p.liveOrEvent && 0 < p.fragments.length && (p.fragments[p.fragments.length - 1].isLastFragment = !0), + p.totalduration = h, + p.averagetargetduration = h / p.fragments.length, + p.endSN = c - 1, + { + mediaOptionDetails: p, + playlistParsingError: O + } + } + static parseRootPlaylist(t, e, i, r) { + const n = [] + , s = {}; + let a, o, d, l, u = null, c = !0; + for (cm.MasterPlaylist.lastIndex = 0; null != (a = cm.MasterPlaylist.exec(e)); ) + if (a[4]) { + a = cm.VARIABLE_PLAYLIST_REGEX.exec(a[4]); + const t = "NAME" === a[1] ? a[2] : a[4] + , e = "VALUE" === a[1] ? a[2] : a[4] + , i = a[5]; + if (!t || s.hasOwnProperty(t) || i || a[1] === a[3]) { + l = new R(L,_,!0,$.PlaylistErrorInvalidEXTXDEFINE.text,$.PlaylistErrorInvalidEXTXDEFINE); + break + } + s[t] = e + } else if (a[5]) { + const t = pm.replaceVariables(a[5], s); + if (t.error) { + l = new R(L,_,!0,$.PlaylistErrorInvalidEXTXDEFINE.text,$.PlaylistErrorInvalidEXTXDEFINE); + break + } + const e = um.parseTags(t.updatedString); + if ("string" != typeof e["SERVER-URI"]) { + l = new R(L,_,!0,$.PlaylistErrorInvalidSERVERURI.text,$.PlaylistErrorInvalidSERVERURI); + break + } + if (null != e["PATHWAY-ID"] && "string" != typeof e["PATHWAY-ID"]) { + l = new R(L,_,!0,$.PlaylistErrorInvalidPATHWAYID.text,$.PlaylistErrorInvalidPATHWAYID); + break + } + u = { + serverURI: hm(e["SERVER-URI"], i, !1), + initPathwayID: e["PATHWAY-ID"] || "." + } + } else { + d = pm.replaceVariables(a[1] || a[3], s); + const e = um.parseTags(d.updatedString); + if (o = pm.replaceVariables(a[2] || e.URI, s), + d.error || o.error) { + l = new R(L,_,!0,$.PlaylistErrorInvalidEXTXDEFINE.text,$.PlaylistErrorInvalidEXTXDEFINE); + break + } + if (void 0 !== e.SCORE && !ne(e.SCORE) || e.SCORE < 0) { + l = new R(L,_,!0,$.PlaylistErrorInvalidSCORE.text,$.PlaylistErrorInvalidSCORE), + c = !1; + break + } + c && void 0 === e.SCORE && (c = !1); + const u = e.BANDWIDTH + , p = e["AVERAGE-BANDWIDTH"] + , f = p || u + , m = null !== (h = e["VIDEO-RANGE"]) && void 0 !== h ? h : "SDR"; + if (null == (h = m) || !Jf.includes(h)) + continue; + const g = { + itemId: t, + mediaOptionId: `level_${(f || 0) + n.length % 1e3 / 1e3}`, + mediaOptionType: ul.Variant, + attrs: e, + url: hm(o.updatedString, i, r), + name: e.NAME, + audioGroupId: e.AUDIO, + subtitleGroupId: e.SUBTITLES, + iframes: !!a[3], + bandwidth: u, + avgBandwidth: p, + bitrate: f, + videoRange: m, + frameRate: e["FRAME-RATE"], + allowedCPCMap: pm.parseAllowedCPC(e["ALLOWED-CPC"]), + closedcaption: e["CLOSED-CAPTIONS"], + levelCodec: e.CODECS, + score: e.SCORE, + pathwayID: e["PATHWAY-ID"] || "." + } + , y = e["HDCP-LEVEL"]; + Xf(y) && (g.hdcpLevel = y); + var h = e.RESOLUTION; + if (h && (g.width = h.width, + g.height = h.height), + e.CODECS) { + g.videoCodecList = new Array, + g.audioCodecList = new Array; + const t = e.CODECS.split(/[ ,]+/) + , i = t["length"]; + for (let e = 0; e < i; e++) { + const i = t[e]; + switch (i.slice(0, 4)) { + case "avc1": + g.videoCodec = Se.avc1toavcoti(i), + g.videoCodecList.push(g.videoCodec); + break; + case "avc3": + case "dvav": + case "dva1": + case "hev1": + case "hvc1": + case "dvh1": + case "dvhe": + case "vp09": + g.videoCodec = i, + g.videoCodecList.push(g.videoCodec); + break; + default: + g.audioCodec = i, + g.audioCodecList.push(g.audioCodec) + } + } + 1 < g.audioCodecList.length && (g.audioCodec = tm.getRichestAudioCodec(g.audioCodecList)), + 1 < g.videoCodecList.length && (g.videoCodec = tm.getRichestVideoCodec(g.videoCodecList)) + } + if (null != (l = "string" != typeof (h = g.pathwayID) ? im("invalid steering manifest PATHWAY-PRIORITY list item data type") : /^[\w\-\.]+$/.test(h) ? void 0 : im("steering manifest contains invalid pathway ID: " + h))) + break; + n.push(g) + } + return { + variantMediaOptions: n, + contentSteeringOption: u, + masterVariableList: s, + playlistParsingError: l, + scoreAvailable: c + } + } + static parseAllowedCPC(e) { + if ("string" != typeof e) + return null; + const n = {}; + return e.split(",").forEach(e=>{ + const t = e.split(":"); + let i, r; + if (2 === t.length) + i = t[0].trim(), + r = t[1].trim(); + else { + if (!(2 < t.length)) + return; + r = t[t.length - 1].trim(), + t.pop(), + i = t.join(":") + } + if (!(i in n)) { + let e = new Array; + "" !== r && (e = r.split("/").map(e=>e.trim())), + n[i] = e + } + } + ), + n + } + static parseSessionKeys(e, t, i) { + var r; + const n = []; + for (cm.SessionData.lastIndex = 0; r = cm.SessionKeys.exec(e); ) + try { + const e = pm.parseDecryptData(r[1], t, i); + e && e.isEncrypted && n.push(e) + } catch (e) {} + return n + } + static parseSessionData(e, t) { + var i; + const r = [] + , n = new Set; + for (cm.SessionData.lastIndex = 0; null != (i = cm.SessionData.exec(e)); ) { + const e = um.parseTags(i[1]); + e.LANGUAGE = em.shortenLanguageCode(e.LANGUAGE); + const t = e.LANGUAGE ? e["DATA-ID"] + "|" + e.LANGUAGE : void 0; + "DATA-ID"in e ? t && n.has(t) || ("com.apple.hls.other-tags" === e["DATA-ID"] && (e.VALUE = function(t) { + let i; + try { + i = JSON.parse(Vc.base64DecodeToStr(t)) + } catch (e) { + i = t + } + return i + }(e.VALUE)), + r.push(e), + t && n.add(t)) : qe().error(`Error processing DATA-ID ${e["DATA-ID"]} and LANGUAGE ${e.LANGUAGE}`) + } + return { + itemList: r, + baseUrl: t + } + } + } + var fm, mm, gm, ym, vm, Sm = pm; + const bm = (e,t,i)=>{ + i = Object.assign(Object.assign({}, e), { + method: "GET", + responseType: "text", + extendMaxTTFB: i + }); + return ml(i.url) ? Mc().load(i, t).pipe(ur(e=>({ + responseText: e.data.response.data, + responseURL: e.data.response.uri, + stats: e.stats + }))) : Oc(i, t).pipe(ur(([e,t])=>({ + responseText: e.responseText, + responseURL: e.responseURL, + stats: t + }))) + } + , Tm = (e,n,t,i,s,a,o,d,r)=>{ + const {url: l, itemId: u, mediaOptionId: c, mediaOptionType: h} = e + , p = xc(e, i); + return bm({ + url: l, + xhrSetup: t.xhrSetup + }, p, r).pipe(ur(({responseText: e, stats: t})=>{ + var i = performance.now() + , r = pm.parseMediaOptionPlaylist(e, l, !0, a, d, u, c, h, s, n); + Lc(r.mediaOptionDetails); + var e = performance.now() + , r = r["mediaOptionDetails"] + , i = { + playlistLoadTimeMs: t.tload - t.trequest, + playlistParseTimeMs: e - i + }; + return o.setPlaylistSample(i), + { + mediaOptionDetails: r, + stats: t + } + } + ), (f = h, + m = c, + g = l, + e=>e.pipe(Un(e=>{ + if (e instanceof ou) + throw new nu(!1,"Timeout",0,$.PlaylistTimeoutError,!0,f,m,g); + if (e instanceof tu) + throw new nu(!1,e.message,e.code,{ + code: e.code, + text: "Playlist Network Error" + },!1,f,m,g); + throw e + } + )))); + var f, m, g + } + , Em = (f,e,m,t,g)=>Bi(e).pipe(Ra(e=>{ + const {keyTagInfo: t, isInitSegment: i, iframe: r, byteRangeOffset: n} = f + , s = t["method"] + , {start: a, end: o} = n; + if ("AES-128" !== s) + return Bi(e); + { + !t.uri || t.iv || t.format && "identity" !== t.format || (t.iv = function(t) { + const i = new Uint8Array(16); + for (let e = 12; e < 16; e++) + i[e] = t >> 8 * (15 - e) & 255; + return i + }(f.mediaSeqNum)); + const n = e + , s = t.key.buffer + , d = t.iv.buffer + , l = o && (r || i) ? o - a : void 0 + , u = !m.enableWebCrypto || !!l + , c = s.slice(0) + , h = d.slice(0) + , p = { + useJSCrypto: u, + plainTextLength: l + }; + return g.decrypt(c, h, "AES-CBC", n, p) + } + } + )); + class Im { + constructor(e) { + this.option = e + } + get name() { + return this.option.name + } + get priority() { + return this.option.priority + } + get expiry() { + return this.option.expiry + } + filter(i, e) { + const r = this.option.initFn && this.option.initFn(i, e) || (e ? Object.assign({}, e) : {}); + let t = i; + return this.option.firstPassFn && i.forEach((e,t)=>this.option.firstPassFn(e, t, r, i)), + this.option.filterFn && (t = i.filter((e,t)=>this.option.filterFn(e, t, r, i))), + null != this.option.filterFn && 0 !== t.length || !this.option.minSortingFn || (t = i.sort((e,t)=>this.option.minSortingFn(e, t, r, i))), + this.option.finalFn && this.option.finalFn(t, r, i), + t + } + } + function wm(e, t, i) { + return (t || []).reduce((e,t)=>t.filter(e, i), Array.from(e)) + } + function Am(t, e) { + return e.filter(e=>{ + return yl(t, null !== (e = e.url) && void 0 !== e ? e : null) + } + ) + } + function Om() { + return [new Im({ + name: "Remove Filter", + priority: 0, + filterFn: (t,e,i)=>!i || i.removed.every(e=>t.mediaOptionId !== e) + }), new Im({ + name: "Penalty Box Filter", + priority: 1, + filterFn: (t,e,i)=>{ + const r = performance.now(); + return !i || i.penaltyBoxQueue.every(e=>e.expiry <= r || t.mediaOptionId !== e.mediaOptionId) + } + }), new Im({ + name: "Compatible IDs Filter", + priority: 1, + filterFn: (t,e,i)=>!i || null == i.compatibleIds || i.compatibleIds.some(e=>e === t.mediaOptionId) + })] + } + class km extends Od { + constructor(e, t, i) { + super(e), + this.itemId = t, + this.mediaOptionType = i, + this.allowFilters = this._initFilters() + } + get mediaOptionList() { + var e; + return (null === (e = this.mediaOptionListInfo) || void 0 === e ? void 0 : e.mediaOptions) || null + } + get mediaOptionList$() { + return this.mediaOptionListInfo$.pipe(ur(({mediaOptions: e})=>e)) + } + mediaOptionFromId(t) { + var e; + return null !== (e = (null !== (e = this.mediaOptionList) && void 0 !== e ? e : []).find(e=>e.mediaOptionId === t)) && void 0 !== e ? e : null + } + _getFilteredList(e) { + return wm(e.mediaOptions, this.allowFilters, e) + } + get filteredMediaOptionList() { + return this.mediaOptionListInfo ? this._getFilteredList(this.mediaOptionListInfo) : null + } + get filteredMediaOptionList$() { + return this.mediaOptionListInfo$.pipe(Ra(e=>{ + const t = [Ul] + , i = performance.now(); + for (const r of e.penaltyBoxQueue) + ne(r.expiry) && r.expiry > i && t.push(vn(r.expiry - i)); + return nn(...t).pipe(ur(()=>this._getFilteredList(e))) + } + ), yd()) + } + get preferredMediaOptionList() { + return this.filteredMediaOptionList ? Am(this.preferredHost, this.filteredMediaOptionList) : [] + } + get preferredMediaOptionList$() { + return Zd([this.preferredHost$, this.filteredMediaOptionList$]).pipe(ur(([e,t])=>Am(e, t))) + } + getNewHost(e) { + e = this.getFallbackVariant(e, !1, !0); + return null != e && e.url ? gl(e.url) : this.preferredHost + } + } + function Cm(e) { + return "PQ" === e.videoRange || "HLG" === e.videoRange + } + function Dm(e, t) { + return t.iframes === e + } + function Mm(e, t, i, r) { + return !r || i.bitrate > r.bitrate && i.bitrate <= e.bitrate ? fm.Better : i.bitrate === r.bitrate ? fm.Same : fm.Worse + } + function Pm(e, t) { + return e && !t ? -1 : !e && t ? 1 : 0 + } + (dd = fm = fm || {})[dd.Better = 1] = "Better", + dd[dd.Same = 0] = "Same", + dd[dd.Worse = -1] = "Worse"; + class xm extends km { + constructor(e, t) { + super(e, t, ul.Variant) + } + static makeFilters() { + return [...Om().concat([new Im({ + name: "HDR Filter", + priority: 1, + filterFn: (e,t,i)=>!i || (i.hasHdrLevels && i.preferHDR) === Cm(e) + }), new Im({ + name: "Viewport Filter", + priority: 1, + firstPassFn: (e,t,i)=>{ + if (i && e && !e.iframes && e.videoCodec) { + const t = !i.lowestBitrate || e.bitrate < i.lowestBitrate ? e.bitrate : i.lowestBitrate; + i.lowestBitrate = t + } + } + , + filterFn: (e,t,i)=>!(e && i && i.viewportInfo && e.videoCodec && i.lowestBitrate) || function(e, t) { + return e.width < 1.35 * t.width && e.height < 1.35 * t.height && e.width * e.height < t.width * t.height * 1.35 + }({ + width: e.width, + height: e.height + }, i.viewportInfo) || e.bitrate === i.lowestBitrate + }), new Im({ + name: "HDCP Filter", + priority: 2, + filterFn: (e,t,i)=>!i || !Xf(i.maxHdcpLevel) || Yf(e.hdcpLevel) < Yf(i.maxHdcpLevel) + })])].sort((e,t)=>{ + return (null !== (e = e.priority) && void 0 !== e ? e : Number.MAX_SAFE_INTEGER) - (null !== (t = t.priority) && void 0 !== t ? t : Number.MAX_SAFE_INTEGER) + } + ) + } + _initFilters() { + return xm.kAllowFilters + } + get preferredHost() { + var e; + return null !== (e = null === (e = this.mediaOptionListInfo) || void 0 === e ? void 0 : e.preferredHost) && void 0 !== e ? e : null + } + get preferredHost$() { + return this.selectEntity(this.itemId, e=>{ + return null !== (e = null == e ? void 0 : e.mediaOptionListTuple[ul.Variant].preferredHost) && void 0 !== e ? e : null + } + ) + } + get mediaOptionListInfo() { + var e; + return null !== (e = null === (e = this.getEntity(this.itemId)) || void 0 === e ? void 0 : e.mediaOptionListTuple[ul.Variant]) && void 0 !== e ? e : null + } + get mediaOptionListInfo$() { + return this.selectEntity(this.itemId, e=>{ + return null === (e = null == e ? void 0 : e.mediaOptionListTuple) || void 0 === e ? void 0 : e[ul.Variant] + } + ).pipe(Up()) + } + get hdrMode$() { + return this.mediaOptionListInfo$.pipe(ur(e=>!0 === e.preferHDR && e.hasHdrLevels), Es()) + } + get maxHdcpLevel$() { + return this.selectEntity(this.itemId, e=>{ + e = null === (e = null == e ? void 0 : e.mediaOptionListTuple) || void 0 === e ? void 0 : e[ul.Variant]; + return null == e ? void 0 : e.maxHdcpLevel + } + ).pipe(Es()) + } + listFallbackVariants(t, e, i, r, n) { + var s = this.mediaOptionListInfo + , a = null === (o = this.mediaOptionList) || void 0 === o ? void 0 : o.find(e=>e.mediaOptionId === t); + if (!a || !s) + return null; + var o = this.makeFilteredListFromVariant(a, e, n); + if (!o) + return null; + e = gl(a.url), + s = s.hasScore; + return xm._listFallbackVariants(o, a, e, s, i, r, n) + } + getFallbackVariant(t, e, i, r) { + var n = this.mediaOptionListInfo + , s = null === (s = this.mediaOptionList) || void 0 === s ? void 0 : s.find(e=>e.mediaOptionId === t); + if (!s || !n) + return null; + e = this.makeFilteredListFromVariant(s, e, r); + if (!e) + return null; + r = gl(s.url), + n = n.hasScore; + return xm._getFallbackVariant(e, s, r, n, i) + } + makeFilteredListFromVariant(e, t, i) { + let r = this.mediaOptionListInfo; + if (!e || !this.mediaOptionList || !r) + return null; + r = Object.assign(Object.assign({}, r), { + includeAllEligiblePathways: !0 + }); + e = Array.from(this.mediaOptionList); + let n = t ? wm(e, this.allowFilters, Object.assign(Object.assign({}, r), { + preferHDR: !1, + compatibleIds: null + })) : this._getFilteredList(r); + return n ? (i && 0 < i.length && (n = n.filter(e=>!i.includes(e.mediaOptionId))), + n) : null + } + get hasIframes() { + var e; + return null !== (e = null === (e = this.mediaOptionListInfo) || void 0 === e ? void 0 : e.hasIframeLevels) && void 0 !== e && e + } + canSwitchToSDR(e, t, i=!1) { + var r = this.mediaOptionListInfo; + if (!this.mediaOptionList || !r) + return !1; + var n = this.mediaOptionFromId(e); + if (!n) + return !1; + if (!Cm(n)) + return !1; + var s = gl(n.url) + , e = wm(Array.from(this.mediaOptionList), this.allowFilters, Object.assign(Object.assign({}, r), { + preferHDR: !1, + compatibleIds: null + })) + , r = r.hasScore; + return null != xm._getFallbackVariant(e, n, s, r, t, i) + } + static _listFallbackVariants(e, r, n, t, s, a=!1, i=null) { + let o = !1; + const d = function(e, s, a) { + const t = [...e] + , o = gl(s.url) + , d = s.audioGroupId; + return t.sort((e,t)=>{ + let i = 0; + var r = a && ne(e.score) && ne(t.score) + , n = r ? e.score > t.score && e.score <= s.score : e.bitrate > t.bitrate && e.bitrate <= s.bitrate + , r = r ? e.score === t.score : e.bitrate === t.bitrate; + return n ? i = -1 : r ? (i = Pm(yl(o, e.url), yl(o, t.url)), + 0 === i && (i = Pm(!d || e.audioGroupId === d, !d || t.audioGroupId === d))) : i = 1, + i + } + ), + t + }(e.filter(e=>{ + var t = !(e.iframes !== r.iframes || s && yl(n, e.url)) + , i = a ? e.bitrate < r.bitrate : e.bitrate <= r.bitrate + , i = t && i; + return r.mediaOptionId === e.mediaOptionId ? (o = i, + !1) : i + } + ), r, t); + return !o || i && i.includes(r.mediaOptionId) || d.unshift(r), + d + } + static _getFallbackVariant(e, t, i, r, n, s=!1) { + let a = null; + e = (e = s ? e.filter(e=>e.bitrate < t.bitrate) : e).filter(e=>e.mediaOptionId !== t.mediaOptionId && e.iframes === t.iframes); + if (n && null != i) + for (const o of e) + Mm(t, 0, o, a) !== fm.Better || yl(i, o.url) || (a = o); + else + for (const o of e) { + const r = Mm(t, 0, o, a); + r !== fm.Better && (r !== fm.Same || !yl(i, o.url) || yl(i, a.url) && o.audioGroupId !== t.audioGroupId) || (a = o) + } + return a + } + getMatchingVariant(e, t) { + var i = this.mediaOptionFromId(e) + , r = gl(null == i ? void 0 : i.url) + , n = t.mediaOptionType === ul.AltAudio ? "audioGroupId" : "subtitleGroupId"; + let s = null; + this.mediaOptionListInfo.hasScore; + for (const e of this.filteredMediaOptionList) + if (e[n] === t.groupId) { + if (!i) { + s = e; + break + } + var a = Mm(i, 0, e, s); + a !== fm.Better && (a !== fm.Same || s.mediaOptionId === i.mediaOptionId || e.mediaOptionId !== i.mediaOptionId && !yl(r, e.url)) || (s = e) + } + return s + } + get currentPathwayID() { + var e; + return null === (e = this.mediaOptionListInfo) || void 0 === e ? void 0 : e.currentPathwayID + } + } + function Rm(e, t) { + switch (e) { + case mm.SendAlternateToPenaltyBox: + e = mm.RetryRequest, + 401 !== t && 403 !== t && 407 !== t && t !== $.CorruptStream.code && t !== $.LivePlaylistUpdateError.code || (e = mm.SendEndCallback); + break; + case mm.RemoveAlternatePermanently: + e = mm.SendEndCallback + } + return e + } + function Lm(e, t, i, r, n, s, a, o=!1) { + const d = s.mediaOptionListQueries[n] + , l = 0 != (e.errorActionFlags & gm.MoveAllAlternatesMatchingHost) + , u = s.mediaOptionListQueries[n].mediaOptionFromId(r) + , c = a.getFallbackMediaOptionTupleFromMediaOptionId(s, n, r, u.backingMediaOptionId, !1, l, o); + let {errorAction: h, errorActionFlags: p} = e; + return s.isValidMediaOptionTuple(c) ? yl(d.preferredHost, c[n].url) && (p &= ~gm.MoveAllAlternatesMatchingHost) : (t || (h = Rm(h, i), + p = 0), + d instanceof xm && (!0 === d.mediaOptionFromId(r).iframes ? (h = mm.DoNothing, + p = 0) : !t && a.canSwitchToSDR(s, r, l, o) && (h = e.errorAction, + p = gm.SwitchToSDR))), + { + errorAction: h, + errorActionFlags: p + } + } + function _m(e) { + let t, i = 0; + switch (e) { + case 0: + t = mm.SendAlternateToPenaltyBox, + i = gm.MoveAllAlternatesMatchingHost; + break; + case 410: + t = mm.RemoveAlternatePermanently; + break; + case 500: + case 502: + case 503: + case 504: + case 404: + case 409: + case 401: + case 403: + case 407: + case $.LivePlaylistUpdateError.code: + case $.PlaylistNotReceived.code: + default: + t = mm.SendAlternateToPenaltyBox, + i = 0 + } + return { + errorAction: t, + errorActionFlags: i + } + } + function Nm(i, r, n, s, a, o, d) { + var {errorAction: l, errorActionFlags: u} = i; + let e = !0; + switch (l) { + case mm.RemoveAlternatePermanently: + case mm.SendAlternateToPenaltyBox: + { + if (null == a || null == o) + return r.handled = !1; + const i = n.itemId; + let e = o + , t = n.mediaOptionListQueries[a].mediaOptionFromId(o); + t.backingMediaOptionId && (e = t.backingMediaOptionId, + t = n.mediaOptionListQueries[a].mediaOptionFromId(e)); + var c = 0 != (u & gm.MoveAllAlternatesMatchingHost) + , h = 0 != (u & gm.MoveAllAlternatesMatchingHDCP) + , p = 0 != (u & gm.SwitchToSDR) + , f = l === mm.RemoveAlternatePermanently; + if (h && "hdcpLevel"in t) { + const r = t.hdcpLevel; + s.setMaxHdcpLevel(i, r) + } + if (p && s.switchToSDROnly(i), + c) { + const r = gl(t.url); + s.moveAllWithMatchingHosts(i, a, r, f) + } else + f ? s.removePermanently(i, a, e) : s.addToPenaltyBox(i, a, e); + if (n.enabledMediaOptionIdByType(a) === o) { + let e = [Ol, Ol, Ol]; + e = s.getFallbackMediaOptionTupleFromMediaOptionId(n, a, o, null, !1, c, d), + n.isValidMediaOptionTuple(e) ? s.setPreferredHost(i, gl(e[ul.Variant].url)) : r.fatal = !0, + r.fatal && (e = [Ol, Ol, Ol]), + s.setNextMediaOptions(n.itemId, e) + } + break + } + case mm.SendEndCallback: + r.fatal = !0; + break; + case mm.RetryRequest: + case mm.DoNothing: + default: + e = !1 + } + return r.handled = e, + e + } + function Fm(e, t) { + t instanceof ru || t instanceof nu || t instanceof au || (t instanceof uu || t instanceof lu) && oe(t.keyuri) + } + function Bm(t, i, r) { + if (t.handled = !0, + r && i < r.maxNumRetry && ne(r.retryDelayMs)) { + let e; + return e = "linear" === r.backoff ? (i + 1) * r.retryDelayMs : Math.pow(2, i) * r.retryDelayMs, + e = Math.min(r.maxRetryDelayMs, e), + Fm(0, t), + vn(e) + } + return t.fatal = !0, + Fm(0, t), + Ui(t) + } + function Um(e, t, i, r, n, s, a, o, d=!1) { + return (null == r ? void 0 : r.errorAction) === mm.RetryRequest ? Bm(e, t, i, s.logger) : $m(e, 0, r, n, s, a, o, d) + } + function $m(e, t, i, r, n, s, a, o=!1) { + const d = new Ji; + return sd(()=>{ + i && (Fm(n.logger, e), + Nm(i, e, r, n, s, a, o)), + d.error(e) + } + ), + d + } + function Vm(t, i, r, n) { + return e=>e.pipe(Un(e=>{ + if (t.logger.error(`Got demux error ${e.message}`), + e instanceof D || e instanceof F) { + mm.SendAlternateToPenaltyBox; + return $m(e, 0, { + errorAction: e.fatal ? mm.SendEndCallback : e instanceof F ? mm.SendAlternateToPenaltyBox : mm.RemoveAlternatePermanently, + errorActionFlags: 0 + }, i, t, r, n) + } + throw e + } + )) + } + function Km(e, t, i, r, n) { + e = null !== (e = null === (e = n.getKeyInfo(e)) || void 0 === e ? void 0 : e.mediaOptionIds) && void 0 !== e ? e : []; + for (const s of e) + for (const n of i.mediaOptionListQueries) + null != n.mediaOptionFromId(s) && r.updateConsecutiveTimeouts(i.itemId, n.mediaOptionType, t, "key") + } + function Hm(r, t, e, n, s, a) { + const o = n.logger + , i = s.enabledMediaOptionKeys + , d = []; + for (const t of r.mediaOptionIds) { + const r = i.some(e=>e.mediaOptionId === t) + , e = s.mediaOptionListQueries.find(e=>null != e.mediaOptionFromId(t)); + if (e) { + const n = e.mediaOptionType + , a = { + mediaOptionId: t, + mediaOptionType: n + }; + r ? d.push(a) : d.unshift(a) + } else + o.warn(`Couldn't find query for ${t}`) + } + const l = new Ji; + return sd(()=>{ + const e = r instanceof lu; + Km(r.keyuri, e, s, n, a); + let t, i = !1; + for (const {mediaOptionId: e, mediaOptionType: a} of d) + t = function(e, t, i, r, n) { + let s = { + errorAction: mm.SendAlternateToPenaltyBox, + errorActionFlags: 0 + }; + if (e instanceof lu) + s.errorAction = mm.SendAlternateToPenaltyBox; + else { + const t = e.isOkToRetry; + e.keyErrorReason === Xl.OutputRestricted ? (s.errorAction = mm.RemoveAlternatePermanently, + s.errorActionFlags |= gm.MoveAllAlternatesMatchingHDCP) : t ? s = _m(e.code) : s.errorAction = mm.RemoveAlternatePermanently + } + s.errorActionFlags &= ~gm.MoveAllAlternatesMatchingHost; + var a = r.enabledMediaOptionIdByType(i); + return t === a ? Lm(s, !1, e.code, a, i, r, n, e.isTimeout) : s + }(r, e, a, s, n), + o.error(`[Keys] handleNetworkError uri=${oe(r.keyuri)} mediaOptionId=${e} mediaOptionType=${a} action=${JSON.stringify(t)}`), + t.errorAction === mm.RetryRequest && (i = !0), + Nm(t, r, s, n, a, e); + i ? (l.next(), + l.complete()) : (Fm(0, r), + l.error(r)) + } + ), + l.pipe(Ra(()=>Bm(r, t, e, n.logger))) + } + function jm(t, i, r, n, s, a, o, d) { + return n = Math.max(0, n), + e=>e.pipe(Ja(()=>{ + null != i && o.updateConsecutiveTimeouts(t, i, !1, "load") + } + ), ya(e=>e.pipe(Kr((e,t)=>function(e, t, i, r, n, s, a, o) { + var d; + if (!(e instanceof p)) + return Ui(e); + let l, u, c, h = !1; + if (e instanceof ru) + c = { + errorAction: Rm(_m((d = e).response.code).errorAction, d.response.code), + errorActionFlags: 0 + }; + else if (e instanceof nu || e instanceof au) { + ({mediaOptionType: u, mediaOptionId: l, isTimeout: h} = e); + const t = null === (d = s.mediaOptionListQueries[u]) || void 0 === d ? void 0 : d.mediaOptionFromId(l); + if (!r && e.isTimeout && null != t && (!("iframes"in t) || !0 !== t.iframes) && (a.updateConsecutiveTimeouts(s.itemId, e.mediaOptionType, !0, "load"), + e instanceof au && e.stats)) { + const t = performance.now(); + o.setBandwidthSample(Object.assign(Object.assign({}, e.stats), { + tfirst: e.stats.tfirst || t, + tload: e.stats.tload || t, + complete: !0, + mediaOptionType: u + })) + } + c = function(e, t, i, r, n) { + var s = e.response.code; + let a = _m(s); + var {mediaOptionId: o, mediaOptionType: d} = e; + return t ? a.errorActionFlags &= ~gm.MoveAllAlternatesMatchingHost : a = function(e, t, i, r, n) { + let {errorAction: s, errorActionFlags: a} = t; + if (e.isTimeout) { + const t = e["mediaOptionType"] + , o = null !== (n = null === (n = n.getErrorInfoByType(t)) || void 0 === n ? void 0 : n.timeouts.load) && void 0 !== n ? n : 0; + !i && r <= o && (s = mm.DoNothing, + a = 0) + } + return { + errorAction: s, + errorActionFlags: a + } + }(e, a, t, i, r), + a = Lm(a, t, s, o, d, r, n, e.isTimeout), + a + }(e, r, n, s, a) + } + return Um(e, t, i, c, s, a, u, l, h) + }(e, t, Rc(e, r), s, n, a, o, d))))) + } + xm.kAllowFilters = xm.makeFilters(), + (dd = mm = mm || {})[dd.DoNothing = 0] = "DoNothing", + dd[dd.SendEndCallback = 1] = "SendEndCallback", + dd[dd.SendAlternateToPenaltyBox = 2] = "SendAlternateToPenaltyBox", + dd[dd.RemoveAlternatePermanently = 3] = "RemoveAlternatePermanently", + dd[dd.InsertDiscontinuity = 4] = "InsertDiscontinuity", + dd[dd.RetryRequest = 5] = "RetryRequest", + (dd = gm = gm || {})[dd.MoveAllAlternatesMatchingHost = 1] = "MoveAllAlternatesMatchingHost", + dd[dd.MoveAllAlternatesMatchingHDCP = 2] = "MoveAllAlternatesMatchingHDCP", + dd[dd.SwitchToSDR = 4] = "SwitchToSDR"; + class qm extends Od { + constructor(e) { + super(e) + } + get currentConfig() { + var e; + return null === (e = this.getActive()) || void 0 === e ? void 0 : e.config + } + get extendMaxTTFB() { + var e; + return null === (e = this.getActive()) || void 0 === e ? void 0 : e.extendMaxTTFB + } + get config$() { + return this.selectActive(e=>null == e ? void 0 : e.config) + } + get userSeek$() { + return this.selectActive(e=>null == e ? void 0 : e.userSeek) + } + } + w(); + class Qm extends pd { + constructor() { + super({}, { + name: "hls-store", + producerFn: vc + }) + } + } + class Gm { + constructor(e) { + this.store = e + } + getQuery() { + return new qm(this.store) + } + setHlsEntity(e) { + const t = e.id; + Co(`hls.set.entity ${t}`), + sd(()=>{ + this.store.add(de(e)), + this.store.setActive(t) + } + ) + } + removeEntity(e) { + Co(`hls.remove ${e}`), + this.store.remove(e) + } + setStartTime(t) { + this.store.updateActive(e=>{ + e.config.startPosition = t + } + ) + } + setUserSeek(t) { + this.store.updateActive(e=>{ + e.userSeek = t + } + ) + } + setExtendMaxTTFB(t) { + this.store.updateActive(e=>{ + e.extendMaxTTFB = t + } + ) + } + } + let Wm, zm; + function Xm() { + return Wm = Wm || new Gm(new Qm), + Wm + } + function Ym() { + return Xm().getQuery().currentConfig + } + function Jm(e, t, i, r) { + var n = t.mediaSeqNum - e.startSN; + if (n < 0 || n >= e.fragments.length) + return e; + const s = Object.assign(Object.assign({}, e), { + fragments: e.fragments.map(e=>Object.assign({}, e)) + }) + , a = s.fragments + , o = a[n]; + if (!Fp(t, a[n])) + return null == r || r.warn("Parsed and existing fragments don't match"), + e; + var {startDtsTs: d, startPts: e, endPts: t} = t; + o.startDtsTs = d, + o.startPts = e, + o.endPts = t, + o.start = i, + o.duration = b(o.endPts, o.startPts); + for (let e = n; 0 < e; e--) + Zm(a, e, e - 1, r); + for (let e = n; e < a.length - 1; e++) + Zm(a, e, e + 1, r); + s.totalduration = 0; + for (const l of a) + s.totalduration += l.duration; + return s.ptsKnown = !0, + eg(s), + s + } + function Zm(e, t, i, r) { + const n = e[t] + , s = e[i]; + s.startPts ? (t < i && n.start + n.duration > s.start || i < t && s.start + s.duration > n.start) && (null == r || r.warn(`overlapping segments found ${n.mediaSeqNum}->${s.mediaSeqNum}`)) : s.start = t < i ? n.start + n.duration : Math.max(n.start - s.duration, 0) + } + function eg(e) { + if (e.programDateTimeMap) { + e.dateMediaTimePairs = []; + for (var [t,i] of Object.entries(e.programDateTimeMap)) { + t = Number(t), + i = e.fragments[i - e.startSN]; + i && (i = i.start, + e.dateMediaTimePairs.push([t, i])) + } + e.dateMediaTimePairs.sort((e,t)=>e[0] - t[0]) + } + } + function tg(t, i) { + if ("VOD" === t.type || "VOD" === i.type || t.iframesOnly !== i.iframesOnly) + return i; + var r = t.mediaOptionId === i.mediaOptionId; + let n = Object.assign(Object.assign({}, i), { + initSegments: {}, + fragments: [], + ptsKnown: !1 + }); + const s = Math.max(t.startSN, n.startSN) - n.startSN + , a = Math.min(t.endSN, n.endSN) - n.startSN + , o = n.startSN - t.startSN + , d = t.fragments + , l = i.fragments; + let u = 0; + for (let e = s; e <= a; ++e) + if (d[o + e] && l[e]) { + u = d[o + e].discoSeqNum - l[e].discoSeqNum; + break + } + const c = n.initSegments; + let h = null; + for (let e = 0; e < l.length; e++) { + const p = d[o + e] + , s = l[e] + , a = Object.assign({}, s) + , f = s.discoSeqNum + u; + i.initSegments[s.discoSeqNum] && (c[f] = Object.assign(Object.assign({}, i.initSegments[s.discoSeqNum]), { + discoSeqNum: f + })), + a.discoSeqNum = f, + r && a.mediaSeqNum === (null == p ? void 0 : p.mediaSeqNum) && null != p.startPts && (a.start = p.start, + a.duration = p.duration, + a.startDtsTs = p.startDtsTs, + a.endDtsTs = p.endDtsTs, + a.startPts = p.startPts, + a.endPts = p.endPts, + h = a), + n.fragments.push(a) + } + if (h) + n = Jm(n, h, h.start); + else if (0 <= o && o < d.length) { + const t = d[o].start + , i = n.fragments; + for (let e = 0; e < l.length; e++) + i[e].start += t + } + return n.ptsKnown = n.ptsKnown || r && !0 === t.ptsKnown && t.endSN >= i.startSN, + eg(n), + n + } + function ig(e, t, i) { + let r = t.targetduration; + return ne(i.liveSyncDuration) ? r = i.liveSyncDuration : ne(i.liveSyncDurationCount) && (r = i.liveSyncDurationCount * t.targetduration), + e + Math.max(0, t.totalduration - r) + } + function rg(e, t, i, r, n) { + if (!t.ptsKnown) + return 0; + var s = t.targetduration + , a = t.fragments[0].start + , r = n.canContinuePlaybackWithoutGap(t, i, { + avgPlaylistLoadTimeMs: 0, + avgPlaylistParseTimeMs: 0 + }, r); + let o = Math.max(0, e - s); + return e < a && !r && (o = a), + o + } + function ng(e) { + return 1e3 * (e.averagetargetduration || e.targetduration) + } + function sg(e, t) { + var i = ng(e) + , t = performance.now() - t; + return e.liveOrEvent && i <= t + } + function ag(e, t) { + return function(e) { + const t = [] + , i = e.fragments; + for (const e of i) { + const {discoSeqNum: i, start: r} = e; + t.push({ + timelineOffset: r, + mediaFragment: e + }) + } + return t + }(e).find(e=>t(e.mediaFragment)) + } + function og(s, e, a, t, o) { + var i; + const d = !t.liveOrEvent || t.ptsKnown; + let r = null !== (i = ag(t, t=>{ + var e = t.mediaSeqNum >= a + , i = 0 < t.duration + , r = t.start + t.duration + , n = !d || s < r || s - r < 1 && t.isLastFragment + , r = o.every(e=>!Fp(e.frag, t)); + return e && i && n && r + } + )) && void 0 !== i ? i : null + , n = NaN; + null != r && ne(e) && r.mediaFragment.discoSeqNum !== e && (n = r.mediaFragment.discoSeqNum, + r = null); + e = o.some(e=>0 < e.frag.framesWithoutIDR); + return r && e && o[o.length - 1].frag.mediaOptionId !== t.mediaOptionId && (r = null !== (t = ag(t, e=>e.mediaSeqNum === r.mediaFragment.mediaSeqNum - 1)) && void 0 !== t ? t : r), + { + foundFrag: r, + nextDisco: n + } + } + function dg(e) { + const t = e.fragments; + return t.map(e=>e.duration).reduce((e,t)=>e + t, null !== (e = t[0].start) && void 0 !== e ? e : 0) + } + class lg extends Od { + constructor(e, t) { + super(e), + this.mediaOption = t + } + get itemId() { + return this.mediaOption.itemId + } + get mediaOptionId() { + return this.mediaOption.mediaOptionId + } + get initSegmentEntities() { + var e; + return null === (e = this.mediaOptionDetailsEntity) || void 0 === e ? void 0 : e.initSegmentCacheEntities + } + get mediaLibraryEntity() { + return this.getEntity(this.itemId) + } + get mediaOptionDetailsEntityRecord() { + var e; + return null === (e = this.mediaLibraryEntity) || void 0 === e ? void 0 : e.mediaOptionDetailsEntityRecord + } + get mediaOptionDetailsEntity() { + return this.mediaOptionDetailsEntityRecord ? this.mediaOptionDetailsEntityRecord[this.mediaOptionId] : null + } + get mediaOptionDetails() { + var e; + return null === (e = this.mediaOptionDetailsEntity) || void 0 === e ? void 0 : e.mediaOptionDetails + } + get playlistDuration() { + var e; + return null === (e = this.mediaOptionDetailsEntity) || void 0 === e ? void 0 : e.playlistDuration + } + get mediaOptionDetailsEntity$() { + const {itemId: e, mediaOptionId: t} = this; + return this.selectEntity(e, e=>{ + if (null != e && e.mediaOptionDetailsEntityRecord) + return null == e ? void 0 : e.mediaOptionDetailsEntityRecord[t] + } + ) + } + get mediaOptionDetails$() { + return this.selectEntity(this.itemId, e=>{ + return null === (e = null == e ? void 0 : e.mediaOptionDetailsEntityRecord[this.mediaOptionId]) || void 0 === e ? void 0 : e.mediaOptionDetails + } + ).pipe(Up()) + } + get playlistDuration$() { + return this.mediaOptionDetailsEntity$.pipe(ur(e=>null == e ? void 0 : e.playlistDuration), Up(), Es()) + } + get live$() { + return this.mediaOptionDetails$.pipe(ur(e=>null == e ? void 0 : e.liveOrEvent), Es()) + } + } + class ug extends pd { + constructor() { + super({}, { + name: "media-library-store", + idKey: "itemId", + producerFn: vc + }) + } + } + class cg { + constructor(e) { + this.store = e + } + getQuery() { + return new Od(this.store) + } + getQueryForOption(e) { + return new lg(this.store,e) + } + createMediaLibraryEntity(e) { + var t = { + itemId: e, + mediaOptionDetailsEntityRecord: {} + }; + Co(`library.entity.create: ${e}`), + this.store.add(t) + } + setDetailsLoading(e) { + const {itemId: t, mediaOptionId: i} = e; + Co(`library.details.loading: ${i}`), + this.store.update(t, ({mediaOptionDetailsEntityRecord: e})=>{ + e[i] || (e[i] = { + initSegmentCacheEntities: {}, + unchangedCount: 0 + }), + e[i].detailsLoading = !0 + } + ) + } + archiveMediaOptionDetails(i, r, n) { + const {itemId: e, mediaOptionId: s} = i + , a = performance.now() + , o = dg(i); + Co(`library.details.loaded: ${s}`), + this.store.update(e, e=>{ + const t = e.mediaOptionDetailsEntityRecord[s]; + t.detailsLoading = !1, + t.mediaOptionDetails = i, + t.lastUpdateMillis = a, + n ? t.unchangedCount = 0 : ++t.unchangedCount, + t.playlistDuration = o, + t.stats = r, + e.liveOrEvent = i.liveOrEvent + } + ) + } + setInitSegmentLoading(e) { + const {itemId: t, mediaOptionId: i, discoSeqNum: r} = e; + Co(`library.initsegs.loading: ${i}/${r}`), + this.store.update(t, e=>{ + e.mediaOptionDetailsEntityRecord[i].initSegLoading = r + } + ) + } + archiveInitSegmentEntity(i, r) { + const {itemId: e, mediaOptionId: n, discoSeqNum: s} = i; + Co(`library.initseg.loaded: ${n}/${s}`), + this.store.update(e, ({mediaOptionDetailsEntityRecord: e})=>{ + const t = e[n]; + t.initSegmentCacheEntities[s] = [i, r], + t.initSegLoading = null + } + ) + } + updatePTSDTS(e, r, n, s) { + this.store.update(e, ({mediaOptionDetailsEntityRecord: e})=>{ + const t = e[r]; + var i; + null != t && t.mediaOptionDetails && ({variantDTS: i, timelineOffset: e} = n, + e = S(s.startDtsTs) - S(i) + e, + e = Jm(t.mediaOptionDetails, s, e), + t.mediaOptionDetails = e, + t.playlistDuration = dg(e)) + } + ) + } + remove(e) { + this.store.remove(e) + } + clear() { + this.store.remove() + } + } + function hg() { + return zm = zm || new cg(new ug), + zm + } + const pg = e=>hg().getQueryForOption(e) + , fg = (d,e,t=!1)=>{ + if (!kl(e)) + return Bi(null); + const i = e["itemId"] + , r = d["mediaLibraryService"] + , n = r.getQueryForOption(e); + n.hasEntity(i) || r.createMediaLibraryEntity(i); + var s = n.mediaOptionDetailsEntity + , a = n.mediaOptionDetails; + return null == a || t || "VOD" !== a.type && (!a.liveOrEvent || sg(a, s.lastUpdateMillis)) ? (r.setDetailsLoading(e), + function(l) { + var e; + const {logger: t, config: u, rootPlaylistQuery: c, rootPlaylistService: h, statsService: i, mediaLibraryService: p, mediaSink: r} = d + , f = r.mediaQuery + , n = u.playlistLoadPolicy + , s = u.keySystemPreference + , a = c.masterVariableList + , o = null === (e = null === (e = Xm()) || void 0 === e ? void 0 : e.getQuery()) || void 0 === e ? void 0 : e.extendMaxTTFB; + return Tm(l, c.itemStartOffset, u, n, t, s, i, a, o).pipe(Hi(Zi), ur(t=>{ + const i = p.getQueryForOption(l) + , r = i.mediaOptionDetails; + let n = t["mediaOptionDetails"]; + var e = t["stats"]; + let s = !0; + if (n.liveOrEvent) { + const d = n["mediaOptionType"]; + t = n, + s = null == r || t.endSN !== r.endSN || t.liveOrEvent !== r.liveOrEvent; + let e = n; + r && (e = tg(r, n)); + const i = c.lastLoadedMediaOptionByType(d) + , u = i ? null === (t = p.getQueryForOption(i)) || void 0 === t ? void 0 : t.mediaOptionDetails : null; + !e.ptsKnown && u && u.mediaOptionId !== (null == r ? void 0 : r.mediaOptionId) && (e = tg(u, n)), + n = e + } + n && (p.archiveMediaOptionDetails(n, e, s), + h.setLastLoadedMediaOptionByType(c.itemId, l.mediaOptionType, l)); + const a = !s && i.mediaOptionDetailsEntity.unchangedCount >= u.liveMaxUnchangedPlaylistRefresh + , o = function(e, t, i, r) { + t = rg(r.currentTime, e, t, i, r), + i = e.fragments[e.fragments.length - 1], + r = i.start + i.duration; + return { + expired: null != i && e.liveOrEvent && e.ptsKnown && r < t, + windowEnd: r, + minPosition: t + } + }(n, e.tload, u.maxBufferHole, f); + if (a || o.expired) { + e = a ? $.LivePlaylistUpdateError : { + text: `Live window too far in the past end:${o.windowEnd.toFixed(3)} minPosition:${o.minPosition}`, + code: 0 + }; + throw new nu(!1,e.text,e.code,e,!1,l.mediaOptionType,l.mediaOptionId,l.url) + } + return n + } + ), Ql.tag("getMediaOptionDetailsCommon.emit.loaded"), jm(l.itemId, l.mediaOptionType, xc(l, n), u.maxNumAddLevelToPenaltyBox, !1, c, h, i)).pipe(Cs(1)) + }(e)) : Bi(a).pipe(Ql.tag("retrieveMediaOptionDetails.emit.cached")).pipe(Cs(1)) + } + ; + const mg = (t,i)=>{ + if (!i) + return Bi(null); + const {mediaLibraryService: r, mediaParser: n} = t + , e = r.getQueryForOption(i) + , {mediaOption: s, mediaOptionDetailsEntityRecord: a, mediaOptionDetails: o} = e + , d = s["mediaOptionId"]; + if (null == a || !a[d]) + throw new Error("retrieveInitSegmentCacheEntity no details entity"); + if (!o) + throw new Error("retrieveInitSegmentCacheEntity no details"); + var l = a[d]["initSegmentCacheEntities"] + , u = o["initSegments"] + , c = i["discoSeqNum"]; + if (l[c]) { + const [t,r] = l[c]; + let e = t; + return r && (e = n.willBeTrackSwitch(i) ? t : r), + Bi(e) + } + const h = u[c]; + return h ? (r.setInitSegmentLoading(h), + yg(t, h, !1, !1).pipe(Hi(Zi), Ra(e=>gg(e, h, t)), Ql.tag("retrieveInitSegmentCacheEntity.emit"))) : Bi(null) + } + ; + function gg(e, n, t) { + const {logger: s, mediaSink: i, rootPlaylistService: r, rootPlaylistQuery: a, mediaParser: o, mediaLibraryService: d, gaplessInstance: l} = t + , u = i["mediaQuery"] + , c = d.getQueryForOption(n) + , {mediaOption: h, mediaOptionDetails: p} = c + , {itemId: f, mediaOptionId: m} = h + , {keyTagInfo: g, discoSeqNum: y, mediaOptionType: v} = n + , S = u.seeking + , b = p.liveOrEvent + , T = v === ul.Variant && p.ptsKnown; + let E, I; + n.isInitSegment ? I = new Uint8Array(e) : E = new Uint8Array(e); + var e = { + segment: E, + initSegment: I, + frag: n, + ptsKnown: T, + seeking: S, + live: b, + totalDuration: p.totalduration + }; + return o.parseInitSegment(e, null !== (e = null === navigator || void 0 === navigator ? void 0 : navigator.vendor) && void 0 !== e ? e : "").pipe(ur(e=>{ + var {track: t, moovData: i, mimeType: r} = e + , e = t["initSegment"]; + l.inGaplessMode && Se.isVideoCodec(t.codec) && (s.warn(`Video codec discovered in gapless mode codec:${t.codec}`), + l.dequeueSource("InvalidFormat")); + r = { + itemId: f, + mediaOptionId: m, + discoSeqNum: y, + initParsedData: i, + data: e, + mimeType: r, + keyTagInfo: g, + fragment: n + }; + return d.archiveInitSegmentEntity(r), + r + } + ), Vm(r, a, v, m)) + } + function yg(n, s, i, r) { + var e; + const {rootPlaylistQuery: t, rootPlaylistService: a, config: o, rtcService: d, statsService: l} = n + , {itemId: u, mediaOptionType: c} = s + , h = o.fragLoadPolicy + , p = ne(s.mediaSeqNum); + let f; + p && (f = { + getData: !1, + cb: (e,t,i,r)=>(a.updateInflightFrag(u, s.mediaOptionType, s, "loading", i), + !1) + }); + let m = !1; + return r && null === d.serverInfoInstance && (m = !0), + Jr([Sg(n, s.keyTagInfo, { + itemId: s.itemId, + mediaOptionId: s.mediaOptionId + }), qf(s, o, h, f, m, null === (e = null === (e = Xm()) || void 0 === e ? void 0 : e.getQuery()) || void 0 === e ? void 0 : e.extendMaxTTFB).pipe(Ja(([,,e,t])=>{ + i && l.setBandwidthSample(Object.assign(Object.assign({}, e), { + mediaOptionType: s.mediaOptionType + })), + r && m && (d.serverInfoInstance = t), + p && a.updateInflightFrag(u, s.mediaOptionType, s, "loaded", e) + } + ), jm(u, c, xc(s, h), o.maxNumAddLevelToPenaltyBox, !1, t, a, l))]).pipe(Cs(1), Ja(([,e])=>{ + var t; + r && ([t,,e] = e, + d.handleFragLoaded(t, e)) + } + ), Ra(([e,t])=>{ + const [i,r] = t; + return i.keyTagInfo.key = e.key, + Em(i, r, o, n.logger, n.rpcClients.crypto) + } + ), Ql.tag("getMediaFragmentCommon.emit")) + } + const vg = (i,e,t)=>{ + const {rootPlaylistService: r, rootPlaylistQuery: n} = i + , {timelineOffset: s, mediaFragment: a} = t.foundFrag + , {itemId: o, discoSeqNum: d} = a; + return r.updateInflightFrag(o, a.mediaOptionType, a, "loading", null), + Jr([Sg(i, a.keyTagInfo, { + itemId: a.itemId, + mediaOptionId: a.mediaOptionId + }), mg(i, a).pipe(Ra(t=>yg(i, a, !0, !0).pipe(Ra(e=>{ + return function(e, t, i, y, v, S) { + const r = new Uint8Array(e) + , {rootPlaylistService: n, mediaSink: s, mediaParser: a, rootPlaylistQuery: o, mediaLibraryService: b} = S + , d = s["mediaQuery"] + , l = b.getQueryForOption(y) + , {mediaOption: u, mediaOptionDetails: c} = l + , {itemId: T, mediaOptionId: E} = u + , {discoSeqNum: I, mediaSeqNum: w, mediaOptionType: h, isLastFragment: A} = y + , p = d.seeking + , f = c.liveOrEvent + , m = h === ul.Variant && c.ptsKnown + , O = { + segment: r, + frag: y, + seeking: p, + live: f, + ptsKnown: m, + totalDuration: c.totalduration, + defaultInitPTS: t, + iframeMediaStart: Np(y) ? y.iframeMediaStart : void 0, + iframeDuration: Np(y) ? y.iframeMediaDuration : void 0 + }; + let g; + if (null != i && (null === (t = y.keyTagInfo) || void 0 === t ? void 0 : t.uri) === (null === (t = i.keyTagInfo) || void 0 === t ? void 0 : t.uri)) + g = Bi(i); + else if (null != i) { + const e = Object.assign(Object.assign({}, i.fragment), { + keyTagInfo: y.keyTagInfo + }); + g = gg(i.data, e, S) + } else + g = gg(e, y, S); + return g.pipe(Ra(m=>{ + const g = performance.now(); + if (null != m) { + const g = m["data"] + , e = new Uint8Array(g); + O.initSegment = e + } + return a.parseSegment(O, "").pipe(ur(e=>{ + var t = performance.now() + , {startPTS: i, startDTS: r, endPTS: n, endDTS: s, firstKeyframePts: a, framesWithoutIDR: o, dropped: d, data1: l, data2: u, captionData: c, id3Samples: h, parsedInitSegment: e} = e + , t = { + durationSec: n.baseTime / n.timescale - i.baseTime / i.timescale, + parseTimeMs: t - g + }; + S.statsService.setFragSample(t); + let p = Object.assign({}, m); + if (e) { + const {track: g, moovData: f, mimeType: v} = e + , S = g["initSegment"]; + p = { + itemId: T, + mediaOptionId: E, + discoSeqNum: I, + initParsedData: f, + data: S, + mimeType: v, + keyTagInfo: y.keyTagInfo, + fragment: y + }, + b.archiveInitSegmentEntity(m, p) + } + e = y.keyTagInfo; + return [p, { + itemId: T, + mediaOptionId: E, + mediaSeqNum: w, + discoSeqNum: I, + startDtsTs: r, + endDtsTs: s, + timelineOffset: v, + firstKeyframePts: a, + framesWithoutIDR: o, + dropped: d, + data1: l, + data2: u, + startPts: i, + endPts: n, + keyTagInfo: e, + isLastFragment: A, + iframe: null !== (e = y.iframe) && void 0 !== e && e, + duration: y.duration, + iframeMediaDuration: Np(y) ? y.iframeMediaDuration : void 0, + captionData: c, + id3Samples: h + }] + } + )) + } + ), Vm(n, o, h, E)) + }(e, null === (e = n.getInitPTS(d)) || void 0 === e ? void 0 : e.offsetTimestamp, t, a, s, i) + } + ), Ja(e=>{} + ), Ql.tag(`retrieveMediaFragmentCacheEntity.${e}.emit`)))).pipe(Cs(1))]).pipe(Ra(([,e])=>Bi(e))) + } + ; + function Sg(e, t, i) { + const {keySystemAdapter: r, rootPlaylistQuery: n, rootPlaylistService: s, config: a} = e; + return r.getKeyFromDecryptData(t, i).pipe((o = t.uri, + d = xc({ + url: t.uri + }, a.keyLoadPolicy), + l = n, + u = s, + c = r.ksQuery, + e=>e.pipe(od(()=>{ + Km(o, !1, l, u, c) + } + ), ya(e=>e.pipe(Kr((e,t)=>{ + if (e instanceof lu || e instanceof uu) + return Hm(e, t, Rc(e, d), u, l, c); + throw e + } + )))))); + var o, d, l, u, c + } + class bg { + constructor(e, t, i) { + this.hls = e, + this.destroy$ = new zt, + this.iframeSwitchStart = 0, + this.logger = t.child({ + name: "hls-player-events" + }), + this.rtc = i, + this.subscribeAndEmit() + } + destroy() { + this.destroy$.next() + } + subscribeAndEmit() { + var e = this.loaderQueryListener(new fu(bc)) + , t = this.hls.publicQueries$.pipe(Ra(([e,t])=>nn(this.rootPlaylistQueryListener(e, t), this.mediaElementQueryListener(t, e)))); + nn(e, t, this.activeItemListener(this.hls.itemQueue)).pipe(Un(e=>{ + var t = e.message; + return this.logger.error(`Got error in HlsPlayerEvents ${t}`, e), + Ti + } + ), $a(this.destroy$), $s(()=>{} + )).subscribe() + } + activeItemListener(e) { + return e.activeItemById$.pipe(Up(), Ra(e=>{ + e = e.url; + return this.hls.trigger(P.MANIFEST_LOADING, { + url: e + }), + Ti + } + )) + } + rootPlaylistQueryListener(t, e) { + var i = t.enabledMediaOptionByType$(ul.Variant).pipe(an(e=>!!e), Ra(e=>{ + var t; + return this.hls.trigger(P.LEVEL_SWITCHING, e), + null === (t = this.rtc) || void 0 === t || t.handleLevelSwitching(e.url), + Ti + } + )) + , r = t.enabledMediaOptionByType$(ul.Variant).pipe(Ra(i=>pg(i).mediaOptionDetailsEntity$.pipe(an(e=>!0 === (null == e ? void 0 : e.detailsLoading)), Ja(e=>{ + var t = { + url: oe(null == i ? void 0 : i.url), + level: i.mediaOptionId, + type: Cl[i.mediaOptionType] + }; + return this.hls.trigger(P.LEVEL_LOADING, t), + Ti + } + )))) + , n = t.enabledMediaOptionByType$(ul.Variant).pipe(Ra(e=>{ + const t = pg(e); + let i = 0; + return t.mediaOptionDetailsEntity$.pipe(Up(), an(e=>{ + var t = null !== e.stats && !1 === e.detailsLoading && e.lastUpdateMillis > i; + return i = null !== (e = e.lastUpdateMillis) && void 0 !== e ? e : 0, + t + } + )) + } + ), Ra(e=>{ + var t = e.mediaOptionDetails + , i = e.stats + , r = { + mediaOptionId: t.mediaOptionId, + details: t, + playlistType: t.type, + stats: i + }; + if (null === (i = this.rtc) || void 0 === i || i.handleLevelLoaded(t, r.stats), + this.hls.trigger(P.LEVEL_LOADED, r), + 0 === e.unchangedCount) { + const e = { + level: 0, + details: t + }; + this.hls.trigger(P.LEVEL_UPDATED, e) + } + if (null != t && t.daterangeTags) { + const e = { + daterangeTags: t.daterangeTags + }; + this.hls.trigger(P.DATERANGE_UPDATED, e) + } + return Ti + } + )) + , s = t.enableMediaOptionSwitchedForType$(ul.AltAudio).pipe(Ra(e=>{ + e = t.alternateMediaOptionById(ul.AltAudio, e.mediaOptionId); + return e && this.triggerAudioSwitch(e), + Ti + } + )) + , a = t.rootPlaylistEntity$.pipe(an(e=>null !== e.enabledMediaOptionKeys[ul.AltAudio].mediaOptionId), Cs(1), Ra(e=>{ + const t = e.enabledMediaOptionKeys[ul.AltAudio].mediaOptionId; + return t && (e = e.mediaOptionListTuple[ul.AltAudio].mediaOptions.find(e=>e.mediaOptionId === t), + this.triggerAudioSwitch(e)), + Ti + } + )); + return nn(i, s, $l(e.textTracksCreated$, e=>e).pipe(Ra(()=>t.enabledMediaOptionByType$(ul.Subtitle).pipe(Ra(e=>{ + e = t.alternateMediaOptionById(ul.Subtitle, e.mediaOptionId); + return e ? this.hls.trigger(P.SUBTITLE_TRACK_SWITCH, { + track: Object.assign({}, e), + hidden: !1 + }) : this.hls.trigger(P.SUBTITLE_TRACK_SWITCH, { + track: void 0, + hidden: !1 + }), + Ti + } + )))), t.sessionData$.pipe(an(e=>null != e.complete), Cs(1), Ja(e=>{} + ), ur(e=>{ + this.hls.trigger(P.SESSION_DATA_COMPLETE, e) + } + )), t.getPreferredMediaOptionsByType$(ul.Variant).pipe(Oa(1), ur(e=>{ + const t = e; + null === (e = this.rtc) || void 0 === e || e.handleLevelsChanged(t), + t.forEach(e=>{} + ), + this.hls.trigger(P.LEVELS_CHANGED, { + requiresReset: !1, + levels: t + }) + } + )), t.getPreferredMediaOptionsByType$(ul.AltAudio).pipe(ur(e=>{ + this.hls.trigger(P.AUDIO_TRACKS_UPDATED, { + audioTracks: e + }) + } + )), $l(e.textTracksCreated$, e=>e).pipe(Ra(()=>t.getPreferredMediaOptionsByType$(ul.Subtitle).pipe(Cs(1), ur(e=>{ + this.hls.trigger(P.SUBTITLE_TRACKS_UPDATED, { + subtitleTracks: e + }), + this.hls.trigger(P.SUBTITLE_TRACKS_CREATED) + } + )))), n, r, a) + } + mediaElementQueryListener(s, e) { + return nn(s.seekTo$.pipe(ur(e=>{ + var t; + e && ne(e.pos) ? (null === (t = this.rtc) || void 0 === t || t.handleSeek("SEEKING"), + this.hls.trigger(P.SEEKING, { + seekToPos: e.pos + })) : null === e && (null === (e = this.rtc) || void 0 === e || e.handleSeek("SEEKED"), + this.hls.trigger(P.SEEKED)) + } + )), s.desiredRate$.pipe(xa(0), ca(), ur(e=>{ + var t = e[0] + , i = e[1]; + jp(i) ? 0 == this.iframeSwitchStart && (this.iframeSwitchStart = performance.now()) : this.iframeSwitchStart = 0, + this.hls.trigger(P.DESIRED_RATE_CHANGED, { + oldRate: t, + newRate: i + }), + null === (e = this.rtc) || void 0 === e || e.handleDesiredRateChanged(t, i) + } + )), s.sourceBufferEntityByType$(cl.AltAudio).pipe(an(e=>!!e), Es((e,t)=>e.totalBytes === t.totalBytes), ur(e=>{ + this.hls.trigger(P.BUFFER_APPENDED) + } + )), s.sourceBufferEntityByType$(cl.Variant).pipe(an(e=>!!e), Es((e,t)=>e.totalBytes === t.totalBytes), ur(e=>{ + var t; + null === (t = this.rtc) || void 0 === t || t.handleVariantBufferAppended(e.timestampOffset, e.totalBytes), + this.hls.trigger(P.BUFFER_APPENDED) + } + )), s.stallInfo$.pipe(Up(), So(s.combinedBuffer$), ur(([e])=>{ + var t; + null === (t = this.rtc) || void 0 === t || t.handleStalled(e, s.getCombinedBufferInfo(e.currentTime, 0).len), + this.hls.trigger(P.STALLED, e) + } + )), Cr([Bi(e), Zd([s.timeupdate$, s.bufferedSegmentsByType$(cl.Variant)]).pipe(so(1e3), ur(([t,e])=>null == e ? void 0 : e.find(e=>e.startPTS <= t && e.endPTS > t)), an(e=>!!e), xa(null), ca())]).pipe(Ra(([e,[t,i]])=>{ + var r = null == i ? void 0 : i.frag + , t = null == t ? void 0 : t.frag; + if (r && !Fp(t, r) && (this.hls.trigger(P.FRAG_CHANGED, i), + this.hls.inGaplessMode && this.checkAndTriggerReadyForNext(s, i), + !t || r.mediaOptionId !== t.mediaOptionId)) { + const s = e.mediaOptionListQueries[ul.Variant].mediaOptionFromId(r.mediaOptionId); + if (!s) + return this.logger.warn("variantInfo is undefined in fragChangeMonitor"), + Ti; + const n = t ? t.mediaOptionId : "" + , i = r.mediaOptionId; + s.iframes && (performance.now(), + this.iframeSwitchStart), + null === (r = this.rtc) || void 0 === r || r.handleLevelSwitched({ + url: s.url, + mediaOptionId: s.mediaOptionId, + oldVariant: "" !== n ? n : void 0, + newVariant: i + }), + this.hls.trigger(P.LEVEL_SWITCHED, s) + } + return Ti + } + )), s.isBufferedToEnd$(this.hls.config.maxBufferHole, !1).pipe(an(e=>!0 === e), Hi(Zi), ur(e=>{ + if (e && !this.hls.itemQueue.isPreloading() && this.hls.inGaplessMode) { + const i = s.getCombinedBufferInfo(s.currentTime, 0); + var t = 0; + i && (t = i.end, + e = s.mediaElementDuration, + 0 < t && e - s.currentTime < 10 && this.hls.trigger(P.READY_FOR_NEXT_ITEM, { + duration: t + })) + } + } + ))) + } + checkAndTriggerReadyForNext(e, t) { + var i, r; + t && t.frag && (i = e.currentTime, + (r = e.getCombinedBufferInfo(i, 0)) && (i = r.end, + r = e.mediaElementDuration, + e = e.bufferMonitorInfo, + e = Math.max(e.almostDryWaterLevelSeconds, e.lowWaterLevelSeconds / 2), + (r - t.endPTS <= e || t.frag.isLastFragment) && this.hls.inGaplessMode && !this.hls.isPreloading && this.hls.trigger(P.READY_FOR_NEXT_ITEM, { + duration: i + }))) + } + loaderQueryListener(e) { + return nn(e.unresolvedUriLoading$.pipe(ur(e=>e.map(e=>{ + e = { + uri: e.uri, + responseType: e.responseType, + userAgent: e.userAgent + }; + this.hls.trigger(P.UNRESOLVED_URI_LOADING, e) + } + )))) + } + triggerAudioSwitch(e) { + e && this.hls.trigger(P.AUDIO_TRACK_SWITCHED, { + id: e.id + }) + } + triggerManifestLoaded(e) { + e = { + levels: e.rootMediaOptionsTuple[ul.Variant], + audioTracks: e.rootMediaOptionsTuple[ul.AltAudio], + subtitleTracks: e.rootMediaOptionsTuple[ul.Subtitle], + url: e.baseUrl, + audioMediaSelectionGroup: e.audioMediaSelectionGroup, + subtitleMediaSelectionGroup: e.subtitleMediaSelectionGroup, + stats: e.stats, + isMediaPlaylist: e.isMediaPlaylist + }; + this.hls.trigger(P.MANIFEST_LOADED, e) + } + triggerManifestParsed(e) { + var t = { + levels: e.mediaOptionListQueries[ul.Variant].filteredMediaOptionList, + firstLevel: 0, + audio: !1, + video: !0, + altAudio: !1, + audioTracks: e.mediaOptionListQueries[ul.AltAudio].filteredMediaOptionList, + audioMediaSelectionGroup: e.audioMediaSelectionGroup, + subtitleMediaSelectionGroup: e.subtitleMediaSelectionGroup, + stats: e.loadStats + }; + null === (e = this.rtc) || void 0 === e || e.handleManifestParsed(t), + this.hls.trigger(P.MANIFEST_PARSED, t) + } + urlRedactedManifestLoaded(e) { + const t = Object.assign({}, e); + return t.url = oe(t.url), + t.levels = le(t.levels), + t.audioTracks = ue(t.audioTracks), + t.subtitleTracks = ue(t.subtitleTracks), + t + } + urlRedactedManifestParsed(e) { + const t = Object.assign({}, e); + return t.levels = le(t.levels), + t.audioTracks = ue(t.audioTracks), + t + } + } + (w = ym = ym || {}).LowBandwidth = "LowBandwidth", + w.HighBandwidth = "HighBandwidth", + w.PreferredListChanged = "PreferredListChanged", + w.IframeModeChange = "IframeModeChange", + w.None = ""; + const Tg = { + minValidBitrate: 2e6, + maxValidBitrate: 5e6, + maxPreferredBitrate: 3e6, + minValidHeight: 480, + maxValidHeight: 720 + }; + function Eg(e, a, o, d, l, u) { + return e.reduce((e,t)=>{ + if (t.iframes) + return e; + let i = e; + const r = (n = t.score, + s = a && o && d && l && !Ig(t, a, o, d, l, u) ? ll.INVALID : ll.VALID, + new Hp(s,n)); + var n, s; + return (!e || r.isGreaterThan(e.bestRank) || r.isEqualTo(e.bestRank) && t.bandwidth < e.selected.bandwidth) && (i = { + selected: t, + bestRank: r + }), + i + } + , null).selected + } + function Ig(e, t, i, r, n, s) { + var {targetDuration: a, targetStartupMs: o} = i + , d = r["avgPlaylistLoadTimeMs"] + , l = n["avgParseTimeMs"] + , {avgBufferCreateMs: i, avgInitFragAppendMs: r, avgDataFragAppendMs: n} = s + , {avgBandwidth: s, avgLatencyMs: t} = t; + return e.bandwidth <= s && (e.avgBandwidth || e.bandwidth) * a / s * 1e3 + d + i + +(t + l + (r + n)) <= o + } + const wg = { + name: "abr" + }; + function Ag(e, t) { + return ne(e) ? Math.min(e, t) : t + } + function Og(e) { + return ne(null == e ? void 0 : e.avgBandwidth) + } + function kg(e, t) { + return e.getCurrentWaterLevelByType(cl.Variant, t) / (0 !== e.playbackRate ? Math.abs(e.playbackRate) : 1) + } + function Cg(t, i, e, r) { + if (e) + return t; + let n = -1; + if (t < 0) + return n; + for (let e = t; e < i.length; ++e) { + const t = Mg(i[e], r); + if (t.altAudio && t.subtitle) { + n = e; + break + } + } + return n + } + function Dg(t, e, i, r, n, s, a) { + const o = i.preferredMediaOptions[ul.Variant].filter(e=>e.iframes === t); + if (!o.length) + return { + variantMediaOption: Ol.mediaOptionId, + holdOffDuration: 0, + lowestCandidate: null + }; + let d = 0; + const l = i.nextMinAutoOptionId; + if (l !== Ol.mediaOptionId) { + const t = o.findIndex(e=>e.mediaOptionId === l); + 0 <= t && (d = t) + } + if (d = Cg(d, o, t, i), + d < 0) + return { + variantMediaOption: Ol.mediaOptionId, + holdOffDuration: 0, + lowestCandidate: null + }; + let u = o.length - 1; + const c = i.nextMaxAutoOptionId; + if (c !== Ol.mediaOptionId) { + const t = o.findIndex(e=>e.mediaOptionId === c); + 0 <= t && (u = t) + } + var h = i.variantMediaOptionById(r.mediaOptionId) + , p = r.mediaOptionDetails + , f = (null == h ? void 0 : h.iframes) !== t ? 0 : kg(n, e.maxBufferHole); + let m, g; + if (t) { + const t = e.desiredIframeFPS; + g = p ? p.targetduration / t : 0, + g = Math.max(1 / t, g) + } else + g = p ? p.targetduration : 0; + h = e.abrBandWidthUpFactor, + p = e.abrBandWidthFactor; + return m = Pg(o, g, d, u, f, t, s.getCombinedEstimate(), s.bandwidthStatus, p, h, e, i, r, n, a), + m.variantMediaOption === Ol.mediaOptionId && (m = Pg(o, g, d, u, f + Ag(g, e.maxStarvationDelay), t, s.getCombinedEstimate(), s.bandwidthStatus, p, h, e, i, r, n, a), + m.variantMediaOption === Ol.mediaOptionId && 0 <= d && (m.variantMediaOption = o[d].mediaOptionId, + m.alternates = t ? null : Mg(o[d], i))), + m + } + function Mg(e, t) { + var i = t.enabledMediaOptionKeys + , r = i[ul.AltAudio] + , r = kl(r) ? t.mediaOptionListQueries[ul.AltAudio].getMatchingAlternate(r.mediaOptionId, e) : Ol + , i = i[ul.Subtitle]; + return { + altAudio: r, + subtitle: kl(i) ? t.mediaOptionListQueries[ul.Subtitle].getMatchingAlternate(i.mediaOptionId, e) : Ol + } + } + function Pg(i, r, n, e, s, a, o, d, t, l, u, c, h, p, f) { + "bandwidth-history-controller" !== u.abrBandwidthEstimator && f.warn(`Unsupported configuration: ${u.abrBandwidthEstimator} for ABR bandwidth estimator`); + const m = d.bandwidthSampleCount + , g = c.abrStatus + , y = p.maxBufferSize + , v = u.minTargetDurations || 1 + , S = c.mediaOptionListQueries[ul.Variant].mediaOptionListInfo.hasScore; + if (!i.length) + return { + variantMediaOption: Ol.mediaOptionId, + holdOffDuration: -1, + lowestCandidate: null + }; + const b = c.enabledMediaOptionIdByType(ul.Variant) + , T = c.variantMediaOptionById(b) + , E = null != i.find(e=>e.mediaOptionId === b) + , I = T && T.iframes === a + , w = T && I ? T.score : void 0 + , A = T && I ? T.frameRate : void 0 + , O = T && I ? T.height : void 0 + , k = I ? kg(p, u.maxBufferHole) : 0; + e = Math.max(0, Math.min(i.length - 1, e)), + n = Math.max(0, Math.min(i.length - 1, n)); + var C = h.mediaOptionDetailsEntityRecord + , D = xg(o.avgBandwidth, l, t, m); + let M; + for (let t = e; t >= n; t--) { + const n = i[t]; + let e = n.mediaOptionId; + const l = n.score + , u = C && C[e] ? C[e].mediaOptionDetails : void 0 + , h = C && C[e] ? C[e].lastUpdateMillis : null + , p = u ? u.totalduration / u.fragments.length : r + , f = null != T && n.bitrate > T.bitrate + , B = null != T && n.bitrate < T.bitrate + , m = !(null != A && (f && n.frameRate < A || B && n.frameRate > A)) + , U = !(f && null != O && O > n.height) + , $ = !(B && (n.bitrate === T.bitrate - 1 || n.bitrate === T.bitrate + 1)) + , V = !(S && f && null != w && (l < w || l === w && T && n.bitrate >= T.bitrate)) + , K = n.iframes === a; + if (ne(p) && K && m && U && $ && V) { + var {adjustedbw: P, bitrate: x, fetchDuration: R, rejectLevelDueToPeakBW: L, canFitMultipleSegments: _, requireAlternates: N, alternates: F} = function(e, t, i, r, n, s, a, o, d, l, u, c) { + var h = n ? a.bwUp : a.bwDown + , n = e.bitrate + , a = t ? t.totalduration / t.fragments.length : o + , s = Rg(e, t, o, h, ne(s.avgPlaylistLoadTimeMs) ? s.avgPlaylistLoadTimeMs : s.avgLatencyMs, l) + , l = e.bandwidth + , i = n < h && h < l && i <= 2 * a + , d = r * ((l || n || 0) * ((null == t ? void 0 : t.targetduration) || a)) / 8 <= d; + let p = null; + u = !u; + return u && (p = Mg(e, c), + p.altAudio && p.subtitle || (p = null)), + { + adjustedbw: h, + bitrate: n, + fetchDuration: s, + rejectLevelDueToPeakBW: i, + canFitMultipleSegments: d, + requireAlternates: u, + alternates: p + } + }(n, u, k, v, f, o, D, r, y, h, a, c); + if (N && Boolean(F) && (M = e), + x < P && _ && !L && (!N || Boolean(F)) && (a || !R || R < s)) + return L = P, + N = g, + P = (P = d).instantBw, + (N.fragDownloadSlow || N.fragDownloadTooSlow || ne(P) && P < L) && E && I && k <= 2 * p && f && (e = b), + { + variantMediaOption: e, + holdOffDuration: R, + alternates: F, + lowestCandidate: M + } + } + } + return { + variantMediaOption: Ol.mediaOptionId, + holdOffDuration: -1, + lowestCandidate: M + } + } + function xg(e, t, i, r) { + let n, s; + return 4 <= r ? (n = e * t, + s = e * i) : n = s = e / 1.8, + { + bwUp: n, + bwDown: s + } + } + function Rg(e, t, i, r, n, s) { + let a = e.bitrate * (t ? t.totalduration / t.fragments.length : i) / r; + return null == t || !t.liveOrEvent || t.ptsKnown && !_g(t.totalduration, n, s) || (a *= 2), + ne(n) && (!ne(s) || null != t && t.liveOrEvent) && (a += n / 1e3), + a + } + function Lg(t, e) { + let i = 1 / 0; + if (t === Ol.mediaOptionId) + return i; + var r = e.find(e=>e.mediaOptionId === t); + if (!r) + return 1 / 0; + const n = r.iframes + , s = r.bitrate + , a = r.frameRate + , o = e.find(e=>e.iframes === n && (void 0 === a || e.frameRate >= a) && e.bitrate > s); + return o && (i = o.bitrate), + i + } + function _g(e, t, i) { + return t = ne(t) ? t : 0, + !ne(i) || performance.now() - i + t > 1e3 * e + } + function Ng(e, t) { + return (null == e ? void 0 : e.fragDownloadSlow) === (null == t ? void 0 : t.fragDownloadSlow) && e.fragDownloadTooSlow === (null == t ? void 0 : t.fragDownloadTooSlow) + } + function Fg(e) { + return "loading" === (null == e ? void 0 : e.state) && ne(null === (e = e.bwSample) || void 0 === e ? void 0 : e.trequest) + } + const Bg = 2e3; + function Ug(e, t, i, r) { + let {fragDownloadSlow: n, fragDownloadTooSlow: s} = t; + var a = i.variantMediaOptionById(e.mediaOptionId).bitrate + , t = e.bwSample; + r = r.child(wg); + i = t.total || Math.max(t.loaded, Math.round(e.duration * a / 8)), + a = performance.now() - t.tfirst, + i = t.loaded * e.duration * 1e3 / i; + return a >= Bg && 1e3 <= a - i && (n || r.warn(`flow indicates low bandwidth, after time/duration behind real time: ${a}/${a - i}`), + n = !0), + a >= 1e3 * e.duration && (s || r.warn(`too much time spent downloading fragment, likely to switch down ${a} > ${1e3 * e.duration}`), + s = !0), + { + fragDownloadSlow: n, + fragDownloadTooSlow: s + } + } + function $g(e, t, i, r, n) { + var s; + const a = n.logger.child(wg) + , o = r.isIframeRate + , d = i.mediaOptionListQueries[ul.Variant].preferredMediaOptionList + , l = i.enabledMediaOptionKeys[ul.Variant]; + let u = e; + if (u !== ym.None || d.some(e=>e.mediaOptionId === l.mediaOptionId) || (u = ym.PreferredListChanged), + u !== ym.None && !(o && u !== ym.IframeModeChange && r.getBufferedSegmentsByType(cl.Variant).filter(e=>e.frag.iframe).length < t.minFramesBeforeSwitchingLevel)) { + const c = Uf(i.itemId) + , h = pg(l) + , p = [Ol, Ol, Ol] + , f = function(e, t, i, r, n, s, a) { + let o = t.nextMaxAutoOptionId; + if (o === Ol.mediaOptionId || Og(s.getBandwidthEstimate())) + return d = e, + l = t, + u = r, + e = n, + r = s, + s = a.child({ + name: "abr" + }), + a = e.isIframeRate, + l.enabledMediaOptionIdByType(ul.Variant), + Dg(a, d, l, u, e, r, s); + if (n.isIframeRate) + return { + variantMediaOption: o, + holdOffDuration: 0, + lowestCandidate: null + }; + { + const c = t.variantMediaOptionById(o) + , h = t.enabledAlternateMediaOptionByType(ul.Subtitle) + , n = t.enabledAlternateMediaOptionByType(ul.AltAudio) + , p = null == n ? void 0 : n.persistentID + , f = null == h ? void 0 : h.persistentID + , m = !t.preferHDR + , g = i.getBestMediaOptionTupleFromVariantAndPersistentId(t, c, p, f, void 0, [], m, !1, !1); + return t.isValidMediaOptionTuple(g) ? (o = g[ul.Variant].mediaOptionId, + { + variantMediaOption: o, + holdOffDuration: 0, + alternates: { + altAudio: g[ul.AltAudio], + subtitle: g[ul.Subtitle] + }, + lowestCandidate: null + }) : { + variantMediaOption: t.enabledMediaOptionKeys[ul.Variant].mediaOptionId, + holdOffDuration: 0, + lowestCandidate: null + } + } + var d, l, u + }(t, i, n, h, r, c, a); + if (f.variantMediaOption !== l.mediaOptionId) { + p[ul.Variant] = { + itemId: i.itemId, + mediaOptionId: f.variantMediaOption + }; + for (const e of [ul.AltAudio, ul.Subtitle]) { + const t = i.enabledMediaOptionIdByType(e); + if (t !== Ol.mediaOptionId) { + const r = e === ul.AltAudio ? null === (s = f.alternates) || void 0 === s ? void 0 : s.altAudio : null === (s = f.alternates) || void 0 === s ? void 0 : s.subtitle; + p[e] = r || { + itemId: i.itemId, + mediaOptionId: t + } + } + } + return n.setEnabledMediaOptions(i.itemId, p), + 1 + } + } + } + const Vg = { + name: "iframes" + } + , Kg = new pd({},{ + name: "item-queue", + producerFn: vc, + idKey: "itemId", + resettable: !0 + }) + , Hg = new class extends Od { + } + (Kg); + class jg { + constructor() { + this.firstItem = !0, + this.playingEntity = null, + this.loadingEntity = null + } + static createItem(e, t, i, r, n) { + const s = new Date + , a = `${s.getHours()}:${s.getMinutes()}:${s.getSeconds()}`; + qe(); + var o = function(e) { + e = sl.parseURL(e).fragment.substr(1); + if (0 === e.length) + return null; + const t = new URLSearchParams(e); + if (!t.has("t")) + return null; + e = Number(t.get("t")); + return ne(e) ? e : null + }(t); + if (o) + i = o; + else { + const e = Ym(); + ne(null == e ? void 0 : e.startPosition) && (i = e.startPosition) + } + return { + itemId: `${e}_${a}`, + name: e, + url: t, + serviceName: n, + createTime: a, + initialSeekTime: i, + itemStartOffset: 0, + platformInfo: r, + config: {} + } + } + get activeItemById$() { + return Hg.selectActiveId().pipe(ur(e=>Hg.getActive())) + } + get removedItems$() { + return Hg.selectEntityAction(To.Remove).pipe(ur(e=>e)) + } + get activeItem() { + return Hg.getActive() + } + get queueItems$() { + return Hg.selectAll().pipe(ur(e=>null != e ? e : [])) + } + get isFirstItem() { + return this.firstItem + } + get playingItem() { + return this.playingEntity + } + get loadingItem() { + return this.loadingEntity + } + addQueueItem(e, t, i, r, n, s) { + Hg.getCount(); + const a = jg.createItem(e, t, i, r, s); + null != this.playingEntity && (a.initialSeekTime = void 0), + n && (a.itemStartOffset = n, + this.firstItem = !1, + this.playingEntity = this.activeItem, + this.loadingEntity = a), + Co(`queue.add.item: ${e}`), + sd(()=>{ + Kg.add(a), + Kg.setActive(a.itemId) + } + ) + } + updatePlayingItemId() { + this.playingEntity = this.loadingEntity, + this.loadingEntity = null, + this.clearAllButActive() + } + resetLoadingItem() { + this.removeQueueItem(this.loadingEntity.itemId), + this.loadingEntity = null, + sd(()=>{ + Kg.setActive(this.playingEntity.itemId) + } + ) + } + isPreloading() { + return null !== this.playingEntity && null !== this.loadingEntity + } + setQueueItem(t, i, r, n, s) { + Co("queue.set.item"), + this.loadingEntity = null, + sd(()=>{ + Kg.reset(); + var e = jg.createItem(t, i, r, n, s); + Kg.add(e), + Kg.setActive(e.itemId) + } + ), + this.playingEntity = this.activeItem + } + removeQueueItem(e) { + Kg.remove(e) + } + clearQueue() { + Kg.reset() + } + clearAllButActive() { + var e; + const t = null === (e = this.activeItem) || void 0 === e ? void 0 : e.itemId; + sd(()=>{ + Hg.getAll().forEach(e=>{ + e.itemId !== t && Kg.remove(e.itemId) + } + ) + } + ) + } + set earlyAudioSelection(t) { + Kg.updateActive(e=>{ + e.earlySelection || (e.earlySelection = {}), + e.earlySelection.audioPersistentId = t + } + ) + } + get earlyAudioSelection() { + var e; + return null === (e = this.activeItem.earlySelection) || void 0 === e ? void 0 : e.audioPersistentId + } + set earlySubtitleSelection(t) { + Kg.updateActive(e=>{ + e.earlySelection || (e.earlySelection = {}), + e.earlySelection.subtitlePersistentId = t + } + ) + } + get earlySubtitleSelection() { + var e; + return null === (e = this.activeItem.earlySelection) || void 0 === e ? void 0 : e.subtitlePersistentId + } + } + function qg(e, t, i, r, n, s) { + return $m(e, 0, Lm({ + errorAction: mm.RemoveAlternatePermanently, + errorActionFlags: 0 + }, !1, e.response.code, i, t, s, n), s, n, t, i).pipe(Un(e=>{ + throw !1 === e.fatal && r.resetMediaSource(), + e + } + )) + } + function Qg(e, t) { + if (!e || 0 === e.length) + return 0; + const i = [...e].sort((e,t)=>t[0] - e[0]) + , r = t.getTime() + , n = null !== (t = i.find(([e])=>r >= e)) && void 0 !== t ? t : i[i.length - 1] + , [s,a] = n + , o = a + (r - s) / 1e3; + return Math.max(0, o) + } + function Gg(e, t) { + if (e && 0 !== e.length) { + const i = [...e].sort((e,t)=>t[1] - e[1]) + , r = null !== (e = i.find(([,e])=>e <= t)) && void 0 !== e ? e : i[i.length - 1] + , [n,s] = r; + return new Date(n + 1e3 * (t - s)) + } + } + function Wg(l, e, u, c, h, p) { + return e.child({ + name: "seek" + }), + e=>e.pipe(Ra((e,t)=>{ + var i, r, n, s, a, o, d = u.mediaQuery.seekTo$.pipe(Up()); + return i = 0 === t, + r = l, + n = h, + s = p, + (null == (t = e) ? Ti : t instanceof Date ? (a = t, + o = s, + n.enabledMediaOptionByType$(ul.Variant).pipe(Ra(e=>o.getQueryForOption(e).mediaOptionDetails$), ur(e=>Qg(e.dateMediaTimePairs, a)), Cs(1))) : function(n, e, s, a, t) { + let i = a.enabledMediaOptionByType$(ul.Variant).pipe(Ra(e=>t.getQueryForOption(e).mediaOptionDetails$), an(e=>ne(null == e ? void 0 : e.totalduration)), Cs(1), ur(e=>{ + var t = !e.liveOrEvent + , i = e.totalduration + , r = a.itemStartOffset; + return t ? ne(n) ? 0 <= n ? n : r + (i + n) : r + (ne(e.startTimeOffset) ? e.startTimeOffset : 0) : !ne(n) || n < 0 || 0 === n && s.liveEdgeForZeroStartPositon ? ig(0, e, s) : n + } + )); + return e && (i = i.pipe(Ja(e=>{} + ))), + i + }(t, i, r, n, s)).pipe($s(()=>{ + null != e && c.setPendingSeek(h.itemId, void 0) + } + ), $a(d)) + } + ), Ja(e=>{ + ne(e) && (u.seekTo = e) + } + )) + } + class zg { + constructor(e, t, i, r, n, s) { + this.logger = e, + this._rootPlaylistService = t, + this._rootQuery = i, + this._mediaQuery = r, + this._iframeMachine = n, + this._anchorMSNs = [NaN, NaN], + this._avDetails = [null, null], + this.logger = e.child({ + name: "fpicker" + }), + this._discoSeqNum = NaN, + this.lookUpTolerance = Math.max(s.maxBufferHole, s.maxFragLookUpTolerance) + } + destroy() { + this._anchorMSNs = [NaN, NaN], + this._avDetails = [null, null], + this._rootQuery = null, + this._mediaQuery = null, + this._rootPlaylistService = null, + this._iframeMachine = null + } + get discoSeqNum() { + return this._discoSeqNum + } + get _discoSeqNum() { + return this._rootQuery.discoSeqNum + } + set _discoSeqNum(e) { + this._rootPlaylistService.setDiscoSeqNum(this._rootQuery.itemId, e) + } + get anchorMSNs() { + return this._anchorMSNs + } + _resolvePosition(e, t, i) { + let r = e; + t = this._avDetails[t]; + if ((null == t ? void 0 : t.mediaOptionId) !== (null == i ? void 0 : i.mediaOptionId) && i.liveOrEvent && !1 === i.ptsKnown) + if (null != (null == t ? void 0 : t.dateMediaTimePairs) && i.dateMediaTimePairs) { + const n = Gg(t.dateMediaTimePairs, e); + r = Qg(i.dateMediaTimePairs, n) + } else { + const e = 3 * i.targetduration + , n = i.fragments[0].start + i.totalduration; + r = Math.max(0, n - e) + } + return r + } + _updateAnchorByPosition(e, t) { + let i = NaN; + const r = t[cl.Variant]; + if (r) { + const t = r.fragments + , n = this._resolvePosition(e, cl.Variant, r); + if (i = Bl.ccForTime(t, n), + !ne(i)) { + const r = t[0] + , s = t[t.length - 1] + , a = r.start + , o = s.start + s.duration; + this.logger.warn(`${e.toFixed(3)} out of range [${a.toFixed(3)},${o.toFixed(3)}]`), + e <= a ? i = r.discoSeqNum : e >= o && (i = s.discoSeqNum) + } + } else + this.logger.warn("No variant details for anchoring"); + this._updateAnchor(i, t) + } + _updateAnchor(e, n) { + const s = e !== this._discoSeqNum; + s && (this._discoSeqNum = e), + Ml.forEach(e=>{ + const t = this._avDetails[e] + , i = n[e] + , r = (null == t ? void 0 : t.mediaOptionId) !== (null == i ? void 0 : i.mediaOptionId); + if (s || r) + this._updateAnchorForType(xl(e), i); + else if (i) { + const {mediaOptionId: n, ptsKnown: s, dateMediaTimePairs: t} = i; + this._avDetails[e] = { + mediaOptionId: n, + ptsKnown: s, + dateMediaTimePairs: t + } + } + } + ) + } + getNextFragments(e, i) { + const {position: r, bufferInfoTuple: t, switchContexts: n} = e + , s = t.map((e,t)=>Xg(r, i[t], n[t], null == e ? void 0 : e.buffered, this.lookUpTolerance)).reduce((e,t)=>Math.min(t, e), Number.POSITIVE_INFINITY); + return this._updateAnchorByPosition(s, i), + this._getNextFragmentsInternal(e, i) + } + _getNextFragmentsInternal(i, r) { + const n = [null, null]; + r.forEach((e,t)=>{ + n[t] = this._getNextFragmentForType(i, r, t) + } + ); + var e = n[cl.Variant] + , t = n[cl.AltAudio] + , s = null === (a = null == e ? void 0 : e.foundFrag) || void 0 === a ? void 0 : a.mediaFragment + , a = null === (a = null == t ? void 0 : t.foundFrag) || void 0 === a ? void 0 : a.mediaFragment; + if (s && a && (a.start > s.start + s.duration ? (this.logger.warn("Audio too far ahead"), + n[cl.AltAudio] = zg.noopResult) : s.start > a.start + a.duration && !this._mediaQuery.isIframeRate && (this.logger.warn("Video too far ahead"), + n[cl.Variant] = zg.noopResult)), + !isFinite(null == e ? void 0 : e.nextDisco) || null != t && !ne(t.nextDisco)) + return n; + { + const o = n[cl.Variant].nextDisco; + return this._updateAnchor(o, r), + this._getNextFragmentsInternal(i, r) + } + } + _getNextFragmentForType(e, t, i) { + var {position: r, bufferInfoTuple: n, switchContexts: s} = e + , a = t[i] + , o = null !== (l = null === (c = n[i]) || void 0 === c ? void 0 : c.buffered) && void 0 !== l ? l : { + start: r, + end: r, + len: 0 + } + , d = this._mediaQuery.getBufferedSegmentsByType(i) + , l = null !== (c = null === (e = s[i]) || void 0 === e ? void 0 : e.userInitiated) && void 0 !== c && c + , u = Xg(r, a, s[i], o, this.lookUpTolerance); + if (!a) + return null; + var {highWaterLevelSeconds: e, lowWaterLevelSeconds: c} = this._mediaQuery.bufferMonitorInfo + , r = o.len; + if (!l && e <= r) + return zg.noopResult; + var e = i === cl.Variant ? cl.AltAudio : cl.Variant + , n = null === (n = n[e]) || void 0 === n ? void 0 : n.buffered + , e = null !== (e = null === (e = s[e]) || void 0 === e ? void 0 : e.userInitiated) && void 0 !== e && e; + let h = !1; + i === cl.Variant && c <= r && 1 < this._mediaQuery.expectedSbCount && null != n && n.end < o.end && (e || n.end - n.start < c) && (h = !0); + let p, f = null, m = NaN; + if (this._mediaQuery.isIframeRate && i === cl.Variant && a.iframesOnly) { + const g = function(e, t, i) { + e = i.nextFragment(a.fragments, (null == e ? void 0 : e.fragments) || [], t, u); + if (!e) + return null; + var {frag: t, newMediaRootTime: e} = e; + return { + foundFrag: { + timelineOffset: t.iframeMediaStart, + mediaFragment: t + }, + nextDisco: NaN, + newMediaRootTime: e + } + }(t[cl.AltAudio], this._mediaQuery.desiredRate, this._iframeMachine); + if (g) { + ({foundFrag: f, nextDisco: m, newMediaRootTime: p} = g); + const i = f.mediaFragment; + i.discoSeqNum !== this._discoSeqNum && this._updateAnchor(i.discoSeqNum, t) + } + } else { + const g = this._anchorMSNs[i]; + ({foundFrag: f, nextDisco: m, newMediaRootTime: p} = og(u, this._discoSeqNum, g, a, d)) + } + return h && this._rootQuery.getInitPTS(null == f ? void 0 : f.mediaFragment.discoSeqNum) ? zg.noopResult : { + foundFrag: f, + nextDisco: m, + newMediaRootTime: p + } + } + _updateAnchorForType(e, t) { + var i, r, n; + if (!t) + return this._anchorMSNs[e] = NaN, + void (this._avDetails[e] = null); + ne(this._discoSeqNum) ? (n = this._discoSeqNum, + n = null !== (r = null == (n = (r = t.fragments, + i = n, + r.find(e=>e.discoSeqNum === i))) ? void 0 : n.mediaSeqNum) && void 0 !== r ? r : t.startSN, + this._anchorMSNs[e] = n, + {mediaOptionId: r, ptsKnown: n, dateMediaTimePairs: t} = t, + this._avDetails[e] = { + mediaOptionId: r, + ptsKnown: n, + dateMediaTimePairs: t + }) : this.logger.warn("Trying to anchor with non-finite discoSeqNum") + } + } + function Xg(e, t, i, r, n) { + r = null != r ? r : { + start: e, + end: e, + len: 0 + }; + i = null !== (i = null == i ? void 0 : i.userInitiated) && void 0 !== i && i, + n = null != t && t.iframesOnly ? 0 : n; + return i || 0 === r.len ? e : r.end + n + } + zg.noopResult = { + foundFrag: null, + nextDisco: NaN + }; + const Yg = { + name: "avpipe" + }; + function Jg(r) { + const {config: o, rootPlaylistService: d, rootPlaylistQuery: l, mediaSink: e, gaplessInstance: t} = r + , u = e.mediaQuery + , i = Zd(Ml.map(e=>l.enabledMediaOptionSwitchForType$(e).pipe(Ja(e=>{} + )))).pipe(Ra(e=>{ + if (!kl({ + itemId: l.itemId, + mediaOptionId: e[ul.Variant].toId + })) + throw new V(!0,`No valid variant enabled id:${e[ul.Variant].toId}`,$.NoValidAlternates); + e = e.map(({fromId: e, toId: t},i)=>function(t, i, r, n, s) { + var e, a, o; + const {rootPlaylistQuery: d, rootPlaylistService: l, mediaSink: u, mediaParser: c, config: h, iframeMachine: p} = t + , f = u.mediaQuery; + if (!n || !s || n === s) + return Ul; + switch (r) { + case ul.Variant: + { + c.reset(ul.Variant); + const t = xl(r) + , l = d.variantMediaOptionById(n) + , g = d.variantMediaOptionById(s); + if (null == g || null == l) + return Ul; + let e = NaN; + if (l.iframes !== g.iframes || !g.iframes && p.isStarted) { + if (u.toggleTrickPlaybackMode(g.iframes), + !g.iframes && p.isStarted) { + const t = u.mediaQuery.autoPausedRestartTime + , i = t || p.iframeClockTimeSeconds; + u.autoPausedRestartTime = void 0, + e = i, + p.stop() + } + return u.pause(), + u.flushData(t, 0, 1 / 0, !0).pipe(Ja(()=>{ + isFinite(e) && (u.seekTo = e) + } + )) + } + if (!h.allowFastSwitchUp || g.iframes) + return Ul; + var m = pg(l).mediaOptionDetails; + if (null != m && null != g && l.bitrate < g.bitrate) { + const r = m.targetduration + , n = pg(g) + , s = n.mediaOptionDetails + , c = n.mediaOptionDetailsEntity.lastUpdateMillis + , p = f.getCurrentWaterLevelByType(t, h.maxBufferHole) + , y = function(e, t, i, r, n, s, a, o) { + if (n.nextMaxAutoOptionId !== Ol.mediaOptionId && !Og(s.getBandwidthEstimate())) + return Number.POSITIVE_INFINITY; + a = xg(s.getBandwidthEstimate().avgBandwidth, a.abrBandWidthUpFactor, a.abrBandWidthFactor, s.bandwidthStatus.bandwidthSampleCount), + s = ne(s.getPlaylistEstimate().avgPlaylistLoadTimeMs) ? s.getPlaylistEstimate().avgPlaylistLoadTimeMs : s.getBandwidthEstimate().avgLatencyMs, + a = t.bitrate > e.bitrate ? a.bwUp : a.bwDown; + return null == i || !i.liveOrEvent || i.ptsKnown && !_g(i.totalduration, s, o) ? Rg(t, i, r, a, s, o) : Number.POSITIVE_INFINITY + }(l, g, s, r, d.abrStatus, i, h, c) + h.maxStarvationDelay + , v = f.currentTime + y + , S = null === (o = null === (a = f.sourceBufferEntityByType(t)) || void 0 === a ? void 0 : a.bufferedSegments) || void 0 === o ? void 0 : o.find(e=>e.startPTS >= v); + let e; + if (S) { + const t = S.endPTS - S.startPTS; + e = S.startPTS + Math.min(Math.max(t - h.maxFragLookUpTolerance, .5 * t), .75 * t) + } + if (ne(e) && p >= y) + return u.flushData(t, e, 1 / 0) + } + } + break; + case ul.AltAudio: + e = d, + m = s, + o = "Nah" === (a = n) ? null : e.alternateMediaOptionById(ul.AltAudio, a), + o = Boolean(o && o.url), + m = "Nah" === a ? null : e.alternateMediaOptionById(ul.AltAudio, m), + m = Boolean(m && m.url), + o && !m && (l.setEnabledMediaOptionSwitchContextByType(d.itemId, ul.AltAudio, s, void 0), + u.resetMediaSource(f.currentTime)), + c.reset(ul.AltAudio) + } + return Ul + }(r, n, i, e, t)); + return Xr(Bi(!0), Jr(e).pipe(Js(!1))) + } + ), Ql.tag("mediaOptionSwitch.audiovideo.out")) + , n = Uf(l.itemId) + , s = r.logger.child(Yg) + , a = new zg(s,d,l,u,r.iframeMachine,o); + return Zd([l.anchorTime$.pipe(Ql.tag("anchorTime.audiovideo.in")), i]).pipe(Ra(([i,e])=>e ? Ti : u.needData$(o.maxBufferHole, t.inGaplessMode, t.isPreloading).pipe(ur(e=>{ + var t = [l.enabledMediaOptionSwitchContexts[ul.Variant], l.enabledMediaOptionSwitchContexts[ul.AltAudio]]; + return u.getSourceBufferInfoAction(e, i, t, o.maxBufferHole) + } + ), Ls(e=>{ + if (!e) + return Ti; + e = Bi(e).pipe(Zg(r, a), ty(r)); + return hn($l(function(e) { + const {mediaSink: t, rootPlaylistQuery: i, rootPlaylistService: r} = e + , n = t.mediaQuery + , s = e.logger.child(wg); + return nn((a = i, + o = s, + Zd([n.fellBelowLowWater$, a.getInFlightFragByType$(ul.Variant)]).pipe(Ra(e=>{ + var [,t] = e; + if (!Fg(t)) + return Ti; + const i = performance.now() - t.bwSample.trequest + , r = Bg - i + , n = 1e3 * t.duration - i + , s = [Ul]; + return 0 < r && s.push(vn(r)), + 0 < n && s.push(vn(n)), + nn(...s).pipe(Js(e)) + } + ), na((e,[t,i])=>{ + const r = Object.assign({}, e); + return t && (r.fragDownloadSlow = !0), + Ug(i, r, a, o) + } + , { + fragDownloadSlow: !1, + fragDownloadTooSlow: !1 + }), xa({ + fragDownloadSlow: !1, + fragDownloadTooSlow: !1 + }), Es(Ng))), function(r) { + const s = r.mediaSink.mediaQuery + , {rootPlaylistQuery: e, config: a} = r; + return s.desiredRate$.pipe(Ra(t=>0 === t ? Ti : Zd([e.getInFlightFragByType$(ul.Variant), e.mediaOptionListQueries[ul.Variant].preferredMediaOptionList$.pipe(ur(e=>e.filter(Dm.bind(null, jp(t)))))])), so(100), Ra(e=>{ + const [t,i] = e; + if (!Fg(t) || i.findIndex(e=>e.mediaOptionId === t.mediaOptionId) <= 0) + return Ti; + var r = performance.now() - t.bwSample.trequest + , n = Ag(t.duration, a.maxStarvationDelay) + , n = Math.min(1e3 * n, 500 * t.duration / s.playbackRate); + return vn(Math.max(0, n - r), 100).pipe(Js(e)) + } + )).pipe(na((e,[t,i])=>function(t, i, r, e) { + let {fragDownloadSlow: n, fragDownloadTooSlow: s} = t; + const {config: a, rootPlaylistService: o, rootPlaylistQuery: d, mediaSink: l, statsService: u, mediaLibraryService: c} = e + , h = e.logger.child(wg) + , p = l.mediaQuery; + if (p.paused) + return t; + e = i.bwSample; + if (!ne(e.tfirst)) + return t; + const f = performance.now() + , m = f - e.trequest + , g = Ag(i.duration, a.maxStarvationDelay) + , y = ul.Variant + , v = i.mediaOptionId + , S = d.variantMediaOptionById(v) + , b = c.getQueryForOption(S) + , T = S.bitrate + , E = Math.max(1, 8e3 * e.loaded / m) + , I = 8 * ((ne(e.total) ? e.total : Math.max(e.loaded, Math.round(i.duration * T / 8))) - e.loaded) / E + , w = kg(p, a.maxBufferHole); + let A; + if (ne(w) && 0 < w && !ne(null === (O = p.seekTo) || void 0 === O ? void 0 : O.pos)) + A = w; + else { + const _ = m / 1e3; + A = _ < g ? g - _ : g + } + var O = n; + ({fragDownloadSlow: n, fragDownloadTooSlow: s} = Ug(i, t, d, h)); + t = 2 * ((null === (t = b.mediaOptionDetails) || void 0 === t ? void 0 : t.targetduration) || i.duration); + if (!(w <= t && (I >= A || n))) + return Xm().getQuery().extendMaxTTFB && Xm().setExtendMaxTTFB(0), + { + fragDownloadSlow: n, + fragDownloadTooSlow: s + }; + O || h.warn(`likely to stall ${se({ + maxTimeToLoadSec: A, + minSwitchDuration: t, + stats: e, + elapsedMs: m, + remainingTimeSec: I, + instantBw: E, + bufferAheadSec: w, + fragDownloadSlow: n + })}`), + n = !0, + Xm().getQuery().extendMaxTTFB || Xm().setExtendMaxTTFB(6e5); + O = I >= A; + let k; + const C = i.itemId + , D = u.getQueryForItem(C) + , M = D.getCombinedEstimate() + , P = Object.assign(Object.assign({}, M), { + avgBandwidth: E + }) + , x = D.bandwidthStatus + , R = S.iframes + , L = Cg(0, r, R, d); + if (L < 0) + return { + fragDownloadSlow: n, + fragDownloadTooSlow: s + }; + t = Math.max(L, r.findIndex(e=>e && e.mediaOptionId === S.mediaOptionId)); + if (O) { + let e = Pg(r, i.duration, L, t, A, R, P, x, 1, 1, a, d, b, p, h); + const N = Ol.mediaOptionId; + k = e.variantMediaOption !== N || (e = Pg(r, i.duration, L, t, I, R, P, x, 1, 1, a, d, b, p, h)).variantMediaOption !== N ? e.variantMediaOption : e.lowestCandidate + } else { + const _ = Cg(0, r.slice(L, t).reverse(), R, d) + , i = t - 1 - _; + (0 <= _ || t === L) && (k = r[i].mediaOptionId) + } + if (null != k && k !== d.abrStatus.nextMaxAutoOptionId && o.setNextMaxAutoOptionId(C, k), + O) + throw h.warn(`loading too slow, abort fragment loading and switch to level ${k}`), + u.setBandwidthSample(Object.assign(Object.assign({}, e), { + tfirst: e.tfirst || f, + tload: e.tload || f, + complete: !0, + mediaOptionType: y + })), + s = !0, + new du({ + mediaOptionType: y, + mediaOptionId: v + },k,$.FragmentAbortError); + return { + fragDownloadSlow: n, + fragDownloadTooSlow: s + } + }(e, t, i, r), { + fragDownloadSlow: !1, + fragDownloadTooSlow: !1 + }), xa({ + fragDownloadSlow: !1, + fragDownloadTooSlow: !1 + }), Es(Ng)) + }(e)).pipe(xa({ + fragDownloadSlow: !1, + fragDownloadTooSlow: !1 + }), na((e,t)=>({ + fragDownloadSlow: e.fragDownloadSlow || t.fragDownloadSlow, + fragDownloadTooSlow: e.fragDownloadTooSlow || t.fragDownloadTooSlow + })), Es(Ng), ur(e=>(r.setFragLoadSlow(i.itemId, e), + !1)), Un(e=>{ + if (e instanceof du) { + const e = { + fragDownloadSlow: !0, + fragDownloadTooSlow: !0 + }; + return r.setFragLoadSlow(i.itemId, e), + Bi(!0) + } + return Ui(e) + } + )); + var a, o + }(r), e=>e), e).pipe(Cs(1), $s(()=>{ + Ml.forEach(e=>{ + d.updateInflightFrag(l.itemId, e, null, null, null) + } + ) + } + )) + } + ))), ur(()=>{ + if (!l.getEntity(l.itemId).manualMode) { + let e = ym.None; + var i, r, n, s; + i = bf(), + r = u, + n = o, + s = null == r ? void 0 : r.clientWidth, + a = null == r ? void 0 : r.clientHeight, + r = "object" == typeof window && window.devicePixelRatio ? window.devicePixelRatio : 1, + a = s && a ? { + width: s * r, + height: a * r + } : void 0, + r = (r = (null === (r = i.getQuery()) || void 0 === r ? void 0 : r.viewportInfo) || {}) && a && (r.width !== a.width || r.height !== a.height), + n.useViewportSizeForLevelCap && r && (i.updateViewportInfo(a), + 1) && (e = ym.PreferredListChanged); + let t = !1; + var a = l.enabledVariantMediaOption; + !function(e, t) { + const i = d.logger.child(wg) + , r = e.abrStatus + , n = r.fragDownloadSlow || r.fragDownloadTooSlow + , s = ne(null === (t = t.seekTo) || void 0 === t ? void 0 : t.pos); + return n && !r.fragDownloadTooSlow && s ? (i.warn("could be ignoring low bandwidth due to seek"), + 0) : n + }(l, u) ? function(e, t) { + const i = Uf(t.itemId) + , r = i.getBandwidthEstimate() + , n = t.abrStatus; + if (Og(r)) { + var t = (null === (t = i.bandwidthStatus) || void 0 === t ? void 0 : t.bandwidthSampleCount) || 0 + , t = xg(r.avgBandwidth, e.abrBandWidthUpFactor, e.abrBandWidthFactor, t)["bwUp"]; + return t > n.highBWTrigger + } + }(o, l) && (e = ym.HighBandwidth, + d.setNextMinAutoOptionId(a.itemId, a.mediaOptionId)) : (e = ym.LowBandwidth, + l.nextMaxAutoOptionId === Ol.mediaOptionId && (d.setNextMaxAutoOptionId(a.itemId, a.mediaOptionId), + t = !0)), + $g(e, o, l, u, d), + t ? d.setNextMaxAutoOptionId(a.itemId, Ol.mediaOptionId) : e === ym.HighBandwidth && d.setNextMinAutoOptionId(a.itemId, Ol.mediaOptionId) + } + } + ), $s(()=>{} + )) + } + const Zg = (r,n)=>e=>{ + const {rootPlaylistQuery: t, mediaSink: a} = r + , i = r.logger.child(Yg); + return e.pipe(Hi(Zi), So(t.enabledMediaOptionKeys$), Ra(([s,e])=>bn(ey(s, ul.Variant, r, e).pipe(Ja(e=>{ + var e = e.detailsEntity; + if (!e.mediaOptionDetails.liveOrEvent || e.mediaOptionDetails.ptsKnown) { + const t = e.playlistDuration + , i = (null === (e = s.bufferInfoTuple[0]) || void 0 === e ? void 0 : e.buffered.end) || 0 + , r = (null === (e = s.bufferInfoTuple[1]) || void 0 === e ? void 0 : e.buffered.end) || 0 + , n = Math.max(i, r); + a.msDuration = ne(a.msDuration) ? Math.max(a.msDuration, t, n) : t + } + } + )), ey(s, ul.AltAudio, r, e)).pipe(ur(e=>({ + action: s, + detailsAndContext: e + })))), Ra(({action: e, detailsAndContext: t})=>function t(i, r, n, s, l) { + var e; + const {mediaSink: u, iframeMachine: c, rootPlaylistQuery: a} = n + , o = [l[ul.Variant].detailsEntity.mediaOptionDetails, null === (e = null === (e = l[ul.AltAudio]) || void 0 === e ? void 0 : e.detailsEntity) || void 0 === e ? void 0 : e.mediaOptionDetails]; + let d = r.getNextFragments(s, o); + const h = d.reduce((e,t)=>Math.max(e, ne(null == t ? void 0 : t.newMediaRootTime) ? t.newMediaRootTime : -1 / 0), -1 / 0); + return ne(h) && (u.seekTo = h, + d = [null, null]), + d.every(e=>null == (null == e ? void 0 : e.foundFrag)) ? Bi(null) : bn(...d.map((e,d)=>e && null != e.foundFrag ? vg(n, d, e).pipe(Ja(e=>{ + const t = e[1] + , i = l[d].switchContext; + t.switchPosition = null == i ? void 0 : i.switchPosition; + const r = null !== (e = null == i ? void 0 : i.userInitiated) && void 0 !== e && e + , n = u["mediaQuery"] + , {desiredRate: s, isIframeRate: a} = n + , o = a && c.isStarted && s && s < 0 && s !== c.iframeRate; + (r || o) && (t.flushBeforeAppend = { + start: 0, + end: Number.POSITIVE_INFINITY + }) + } + )) : Bi(null))).pipe(ur(e=>function(g, e, t, i) { + const {rootPlaylistService: r, rootPlaylistQuery: n, mediaSink: s, mediaLibraryService: a, config: y} = e + , v = s.mediaQuery + , o = n.itemId + , d = v.isIframeRate; + let l = n.getInitPTS(t); + if (null == l || !d && l.iframeMode !== d) { + const c = null !== (e = null === (e = i[ul.Variant]) || void 0 === e ? void 0 : e[1].startDtsTs) && void 0 !== e ? e : null; + if (null == c) + return g.warn("updatePTSInfo: Variant data missing."), + null; + const n = null !== (e = null === (e = i[ul.Variant]) || void 0 === e ? void 0 : e[1].timelineOffset) && void 0 !== e ? e : 0 + , s = B(n, c.timescale) + , a = { + baseTime: c.baseTime - s.baseTime, + timescale: c.timescale + }; + r.setInitPTS(o, t, c, n, a, d), + l = { + variantDTS: c, + timelineOffset: n, + offsetTimestamp: a, + iframeMode: d + } + } + i.forEach(e=>{ + e && !ne(e[1].iframeMediaDuration) && a.updatePTSDTS(o, e[1].mediaOptionId, l, e[1]) + } + ); + const S = [null, null]; + if (i[ul.Variant]) { + const [g,c] = i[ul.Variant]; + let e = l.offsetTimestamp; + if (d) { + const g = c.startDtsTs + , i = B(c.timelineOffset, g.timescale); + e = { + baseTime: g.baseTime - i.baseTime, + timescale: g.timescale + } + } + S[cl.Variant] = { + initSeg: g, + dataSeg: c, + offsetTimestamp: e + } + } + if (i[ul.AltAudio]) { + const [g,c] = i[ul.AltAudio]; + S[cl.AltAudio] = { + initSeg: g, + dataSeg: c, + offsetTimestamp: l.offsetTimestamp + } + } + const u = S.map((e,t)=>{ + const i = null == e ? void 0 : e.dataSeg; + if (i) { + const {itemId: r, mediaOptionId: n, mediaSeqNum: s, discoSeqNum: a, startPts: o, endPts: d, duration: l, iframe: u} = i + , c = e["offsetTimestamp"] + , h = b(o, c) + , p = b(d, c) + , f = pg(i) + , m = S[0]; + return m && m.dataSeg.dropped || i.flushBeforeAppend || !((null === (e = null === (e = v.getBufferInfo(h, y.maxBufferHole)[t]) || void 0 === e ? void 0 : e.buffered) || void 0 === e ? void 0 : e.len) >= p - h) ? { + start: h, + duration: u ? l : p - h, + itemId: r, + mediaOptionId: n, + mediaSeqNum: s, + discoSeqNum: a, + targetDuration: f.mediaOptionDetails.targetduration + } : (g.warn(`${Cl[t]} Discarding append due to complete overlap with existing buffer`), + S[t] = null) + } + return null + } + ); + return u.every(e=>!e) ? null : { + appendDataTuple: S, + inFlightFrags: u, + initPTSInfo: l + } + }(i, n, r.discoSeqNum, e)), Ra(e=>{ + if (e) + return Bi(e); + { + const e = function(e, r) { + const n = e.enabledMediaOptionKeys + , s = [null, null] + , a = [null, null]; + return Ml.map(e=>{ + var t; + if (kl(n[e])) { + const i = pg(n[e]).mediaOptionDetailsEntity; + a[e] = null === (t = i.mediaOptionDetails) || void 0 === t ? void 0 : t.ptsKnown, + s[e] = { + detailsEntity: i, + switchContext: null === (e = r[e]) || void 0 === e ? void 0 : e.switchContext + } + } + } + ), + s + }(a, l); + return t(i, r, n, s, e) + } + } + )) + }(i, n, r, e, t)), Ql.tag("mediaProducerEpic.emit")) + } + ; + function ey(e, i, t, r) { + const {rootPlaylistQuery: n, mediaLibraryService: s} = t + , a = r[i]; + if (t.logger.child({ + name: Cl[i] + }), + !a || "Nah" === a.mediaOptionId) + return Bi({ + detailsEntity: null, + switchContext: null + }); + const o = s.getQueryForOption(a); + return Cr([Bi(e), o.mediaOptionDetailsEntity$.pipe(Es((e,t)=>(null == e ? void 0 : e.lastUpdateMillis) === (null == t ? void 0 : t.lastUpdateMillis)))]).pipe(an(([,e])=>{ + if (i === ul.AltAudio && !n.altMediaOptionHasValidUrl(i, a.mediaOptionId)) + return !0; + var t = null == e ? void 0 : e.mediaOptionDetails; + return null != t && (e = null !== (e = e.lastUpdateMillis) && void 0 !== e ? e : 0, + !t.liveOrEvent || !t.ptsKnown || !_g(null == t ? void 0 : t.totalduration, 0, e)) + } + ), Cs(1), So(n.enabledMediaOptionSwitchContextsByType$(i)), ur(([[,e],t])=>({ + detailsEntity: e, + switchContext: t + }))) + } + const ty = t=>e=>{ + const {rootPlaylistQuery: g, rootPlaylistService: y, mediaSink: v, legibleSystemAdapter: o, statsService: d, rtcService: l} = t; + return e.pipe(Ql.tag("mediaConsumerEpic.in"), Ra(e=>{ + if (!e) + return Bi(!1); + const {appendDataTuple: r, inFlightFrags: m, initPTSInfo: t} = e + , i = t["offsetTimestamp"]; + return m.forEach((e,t)=>{ + e && y.updateInflightFrag(e.itemId, t, e, "appending", null) + } + ), + r.forEach(e=>{ + e && (e = e.dataSeg, + o.addLegibleSamples(i, e.captionData, e.id3Samples, e.endPts)) + } + ), + v.appendData(r, (e,t,i,r,n)=>{ + var s, a, o, d, l, u, c, h, p, f = null !== (f = m[t].targetDuration) && void 0 !== f ? f : 10; + return s = v, + a = e, + o = t, + d = i, + l = f, + u = r, + c = g, + h = y, + p = n, + e=>e.pipe(Ja(()=>{ + h.updateConsecutiveTimeouts(c.itemId, o, !1, "append") + } + ), ya(e=>e.pipe(Kr((e,t)=>{ + var i = e instanceof rf && e.isTimeout; + if (h.updateConsecutiveTimeouts(c.itemId, o, i, "append"), + i) + return function(e, t, i, r, n, s, a, o) { + let d = { + errorAction: mm.SendAlternateToPenaltyBox, + errorActionFlags: 0 + }; + var l = s.getCurrentWaterLevel(i.maxBufferHole) + , u = l < i.almostDryBufferSec; + let c = NaN; + s = i.appendErrorMaxRetry, + i = a.rootPlaylistEntity.errorsByType[r].timeouts.append; + u && s <= i || s <= t ? d.errorAction = mm.SendEndCallback : c = 1e3 * l; + s = { + retryDelayMs: c, + maxNumRetry: s, + maxRetryDelayMs: c + }; + return d = Lm(d, !1, e.response.code, n, r, a, o), + Um(e, t, s, d, a, o, r, n).pipe() + }(e, t, u, o, d, p, c, h); + if (e instanceof nf) + return function(e, t, i, r, n, s, a, o, d, l) { + var u = t.type + , u = o.getCurrentWaterLevelByType(u, n.maxBufferHole); + if (u >= n.almostDryBufferSec) { + const t = 1e3 * r + , n = { + errorAction: mm.RetryRequest, + errorActionFlags: 0 + }; + return 1e3 * u < t && (l.hasFallbackMediaOptionTuple(d, s, a, !1) ? n.errorAction = mm.SendAlternateToPenaltyBox : n.errorAction = mm.SendEndCallback), + Um(e, i, { + retryDelayMs: t, + maxNumRetry: 1 / 0, + maxRetryDelayMs: t + }, n, d, l, s, a) + } + return i < n.appendErrorMaxRetry ? t.remove(0, Number.POSITIVE_INFINITY) : (e.fatal = !0, + Ui(e)) + }(e, a, t, l, u, o, d, p, c, h); + if (e instanceof af) { + const {mediaOptionType: a, mediaOptionId: o} = e; + return qg(e, a, o, s, h, c) + } + throw e + } + )))) + } + , g.highestVideoCodec).pipe(ur(e=>{ + m.forEach((e,t)=>{ + e && y.updateInflightFrag(e.itemId, t, e, "appended", null) + } + ); + var t = e.filter(e=>(null == e ? void 0 : e.fragmentType) === ul.Variant); + t.length && (d.setBufferMetric(t[0]), + null == l || l.handleFragBuffered(t[0])); + e = r[cl.AltAudio]; + if (null !== (t = null == e ? void 0 : e.dataSeg) && void 0 !== t && t.flushBeforeAppend || ne(null === (t = null == e ? void 0 : e.dataSeg) || void 0 === t ? void 0 : t.switchPosition)) { + const {itemId: i, mediaOptionId: r} = e.dataSeg; + y.setEnabledMediaOptionSwitchContextByType(i, ul.AltAudio, r, void 0) + } + return !0 + } + ), (n = v, + s = y, + a = g, + e=>e.pipe(Un(e=>{ + if (e instanceof tf) { + var {mediaOptionType: t, mediaOptionId: i} = e; + return qg(e, t, i, n, s, a) + } + throw e + } + )))); + var n, s, a + } + )) + } + ; + function iy(e) { + const {logger: r, rootPlaylistService: n, rootPlaylistQuery: t} = e + , s = t.itemId; + return e=>e.pipe(ya(e=>e.pipe(Kr(e=>{ + if (r.error(`Got error in pipeline ${e.message} fatal:${null == e ? void 0 : e.fatal} handled:${null == e ? void 0 : e.handled}`), + !(e instanceof p) || e.fatal) + throw e; + return e.handled ? (t = n, + i = s, + vn(0).pipe(ur(()=>{ + t.updateEnabledMediaOptions(i) + } + ))) : Ti; + var t, i + } + )))) + } + const ry = ()=>e=>e.pipe(Ql.tag("mediaFragmentPipelineEpic.in"), Ra(i=>{ + if (!i) + return Ti; + const {logger: e, config: t, platformService: r, rootPlaylistService: n, rootPlaylistQuery: s, keySystemAdapter: a, mediaSink: o, mediaParser: d, gaplessInstance: l, mediaLibraryService: u} = i + , c = s["itemId"] + , h = o["mediaQuery"] + , p = a.keyStatusChange$.pipe((f = i, + e=>e.pipe(Ra(e=>{ + const {decryptdata: t, status: i, error: r} = e + , n = f["rootPlaylistQuery"]; + if ("needs-renewal" === i) + return Sg(f, t, null); + if ("error" !== i || !(r instanceof uu || r instanceof lu) || r.handled) + return Ti; + { + const {rootPlaylistService: e, keySystemAdapter: t} = f; + return Hm(r, 0, null, e, n, t.ksQuery) + } + } + ), Ra(()=>Ti)))); + var f; + const m = r.getQuery() + , g = m.displaySupportsHdr$.pipe(Es(), Ra(e=>(n.setHDRPreference(c, e, !0), + Ti))) + , y = m.viewportInfo$.pipe(Es((e,t)=>e && t && e.width === t.width && e.height === t.height), Ja(e=>{ + t.useViewportSizeForLevelCap && n.setViewportInfo(c, e) + } + ), Ua(Ti)) + , v = Zd([s.hdrMode$.pipe(Es()), s.maxHdcpLevel$.pipe(Es())]).pipe(Ra(([])=>(l.inGaplessMode || 0 !== s.itemStartOffset || (o.resetMediaSource(), + d.reset()), + Ti))) + , S = nn(function(i) { + const {rootPlaylistQuery: t, mediaSink: r} = i + , e = t.enabledMediaOptions$.pipe(Up(), Ja(e=>{ + e = e[ul.AltAudio], + e = kl(e) && null != (null == e ? void 0 : e.url) ? 2 : 1; + r.setExpectedSbCount(e) + } + )) + , n = t.enabledMediaOptionByType$(ul.Variant).pipe(an(e=>kl(e)), Ra(e=>pg(e).mediaOptionDetails$), Cs(1), Ja(e=>{ + r.bufferMonitorTargetDuration = e.targetduration + } + )) + , s = Dl.map(e=>t.enabledMediaOptionByType$(e).pipe(Ql.tag("mediaOptionRetrieve.switch"), Ra(t=>{ + if (!t || !t.url || !kl(t)) + return Ti; + var e = r.mediaQuery.desiredRate$.pipe(ur(e=>0 !== e), Es()); + return fg(i, t).pipe(Ql.tag("mediaOptionRetrieve.first"), Ua(e), Ra(e=>e ? function e(t, i) { + const r = t.mediaLibraryService; + return function(e) { + if (!e) + return Ti; + var {mediaOptionDetails: t, lastUpdateMillis: i, unchangedCount: e} = e; + if (null == t || !t.liveOrEvent) + return Ti; + if (sg(t, i)) + return vn(0).pipe(Ja(()=>{} + )); + let r = ng(t); + return 0 < e && (r /= 2, + r = Math.max(r, 5e3)), + r -= performance.now() - i, + r += 0, + r = Math.max(1e3, Math.round(r)), + vn(r).pipe(Ja(()=>{} + )) + }(r.getQueryForOption(i).mediaOptionDetailsEntity).pipe(Ra(()=>fg(t, i, !0)), Ra(()=>e(t, i))) + }(i, t) : Ti)) + } + ))); + return nn(e, n, nn(...s)).pipe(Ua(Ti)) + }(i), Jg(i), function(t) { + const {rootPlaylistQuery: i, mediaSink: e} = t; + return $l(e.mediaQuery.mediaElementEntity$, e=>!!e).pipe(Ra(e=>i.anchorTime$.pipe(Up(), Ql.tag("anchorTime.subtitle.in"), (s=>e=>{ + const {rootPlaylistQuery: i, rootPlaylistService: t, legibleSystemAdapter: r} = s + , n = i.enabledAlternateMediaOptionByType(ul.Subtitle); + if (r.gotTracks) + r.selectedTrack = n; + else { + const s = i.preferredMediaOptions[ul.Subtitle]; + r.setTracks(s, n, i.getDisabledMediaOption(ul.Subtitle)) + } + return e.pipe(Ql.tag("subtitleEpic.select.in"), Ra(()=>(r.anchorTimeChanged(), + nn(r.nativeSubtitleTrackChange$.pipe(Ra(e=>(e.mediaOptionId !== r.selectedMediaOption.mediaOptionId && t.setEnabledMediaOptionByType(e.itemId, ul.Subtitle, e), + Ti))), i.enabledMediaOptionByType$(ul.Subtitle).pipe(ur(e=>{ + const t = kl(e) ? i.alternateMediaOptionById(ul.Subtitle, e.mediaOptionId) : e; + return r.selectedMediaOption = t, + t + } + )).pipe(Es((e,t)=>(null == e ? void 0 : e.mediaOptionId) === (null == t ? void 0 : t.mediaOptionId)))))), Ql.tag("subtitleEpic.select.emit")) + } + )(t), (s=>e=>{ + const {mediaSink: t, rootPlaylistQuery: i, legibleSystemAdapter: r, logger: n} = s; + return e.pipe(Ql.tag("subtitleEpic.process.in"), Ra(e=>{ + if (!e || !e.url || !kl(e)) + return Bi([null, null, null]); + return Zd([pg(e).mediaOptionDetails$, i.discoSeqNum$.pipe(an(e=>ne(e)))]).pipe(Ra(([e,t])=>((i,r,e)=>{ + const {legibleSystemAdapter: n, rootPlaylistQuery: t} = i; + return t.initPTS$(e).pipe(Ra(t=>t ? n.findFrags$(r, e).pipe(Ra(e=>r && (null == e ? void 0 : e.foundFrags) ? ny(i, t.offsetTimestamp, e, r) : Ul)) : sn)) + } + )(s, e, t))) + } + ), Ql.tag("subtitleEpic.process.emit")) + } + )(t)))) + }(i), p).pipe(Js(void 0), iy(i)) + , b = h.seekTo$.pipe(ur(e=>null == e ? void 0 : e.pos), an(e=>ne(e)), Es((e,t)=>Math.abs(e - t) < Number.EPSILON), Ra(e=>(n.setAnchorTime(c, e), + Ti))) + , T = h.gotPlaying$.pipe(an(e=>e), Ja(e=>{ + s.mediaOptionListQueries[ul.Variant].filteredMediaOptionList.forEach(e=>{} + ) + } + ), Cs(1), Ua(Ti)); + return nn(s.pendingSeek$.pipe(Wg(t, e, o, n, s, u)), function() { + const {config: s, mediaSink: a, rootPlaylistQuery: e, mediaLibraryService: t} = i + , o = i.logger.child({ + name: "live" + }) + , d = a.mediaQuery; + return e.enabledMediaOptionByType$(ul.Variant).pipe(an(kl), Ra(e=>t.getQueryForOption(e).mediaOptionDetailsEntity$.pipe(an(e=>{ + var t; + return (null === (t = null == e ? void 0 : e.mediaOptionDetails) || void 0 === t ? void 0 : t.ptsKnown) && e.mediaOptionDetails.liveOrEvent + } + ), Es((e,t)=>(null == e ? void 0 : e.lastUpdateMillis) === (null == t ? void 0 : t.lastUpdateMillis)))), ur(e=>{ + var t = e.mediaOptionDetails + , i = d.currentTime + , r = d.msDuration; + let n = NaN; + return i < rg(i, t, e.lastUpdateMillis, s.maxBufferHole, d) && (n = ig(t.fragments[0].start, t, s), + n >= r && (o.warn(`seekTo position > duration, updating ${a.msDuration}->${e.playlistDuration}`), + a.msDuration = e.playlistDuration), + a.seekTo = n), + n + } + )) + }(), b, S, g, y, v, function() { + const e = i.mediaSink.mediaQuery; + return Cr([Bi(i), e.desiredRate$.pipe(ca())]).pipe(Ra(([e,[t,i]])=>{ + const {rootPlaylistQuery: s, rootPlaylistService: r, config: a, mediaSink: n, mediaLibraryService: o, statsService: d} = e + , l = n.mediaQuery; + if (jp(t) !== jp(i)) + $g(ym.IframeModeChange, a, s, l, r); + else if (0 === t && 1 === i && !Ml.every(e=>{ + const t = s.enabledMediaOptionKeys[e] + , i = o.getQueryForOption(t) + , r = d.getQueryForItem(s.itemId) + , n = i.mediaOptionDetailsEntity; + return !(null !== (e = null == n ? void 0 : n.mediaOptionDetails) && void 0 !== e && e.ptsKnown) || l.canContinuePlaybackWithoutGap(n.mediaOptionDetails, n.lastUpdateMillis, r.getPlaylistEstimate(), a.maxBufferHole) + } + )) + return n.pause(), + n.flushAll(0, 1 / 0, !0); + return Ti + } + ), Ua(Ti)) + }(), function(e) { + const s = e.rootPlaylistQuery + , t = e.mediaSink.mediaQuery + , i = s.enabledMediaOptionByType$(ul.Variant); + return Cr([Bi(e), t.desiredRate$.pipe(ca()), i]).pipe(Es((e,t)=>e[1] === t[1]), Ra(([e,[t,i],r])=>{ + t = jp(t), + i = jp(i); + if (t === i) + return Ti; + const n = e["rootPlaylistService"]; + return i ? e.rootPlaylistQuery.nextMaxAutoOptionId === Ol.mediaOptionId && n.setNextMaxAutoOptionId(e.rootPlaylistQuery.itemId, r.mediaOptionId) : n.setNextMaxAutoOptionId(s.itemId, Ol.mediaOptionId), + Ti + } + )) + }(i), T).pipe(Ql.tag("mediaFragmentPiplineEpic.emit"), Js(void 0)) + } + )) + , ny = (i,r,t,n)=>{ + const s = i.legibleSystemAdapter; + return Lr(t.foundFrags).pipe(ur(e=>{ + return ((e,t,i)=>{ + const {rootPlaylistQuery: r, legibleSystemAdapter: n} = e; + return Yr(()=>((t,i)=>yg(e, i, !1, !1).pipe(ur(e=>({ + initPTS: t, + data: e, + mediaFragment: i + })), Ql.tag("retrieveSubtitleFragmentCacheEntity.emit")))(t, i).pipe(ur(({initPTS: e, data: t, mediaFragment: i})=>({ + frag: i, + cueRange: function(e, t, i, r, n) { + if (e) + return n.processSubtitleFrag(e, t, i, r) + }(r.enabledAlternateMediaOptionByType(ul.Subtitle), i, e, t, n) + })))) + } + )(i, r, e).pipe((t = e=>s.checkReadyToLoadNextSubtitleFragment$().pipe(an(e=>e)), + function(e) { + return e.lift(new ms(t)) + } + )); + var t + } + ), Wr(i.config.vttConcurrentLoadCount), Ja(e=>{ + s.reviewParsedFrag(e, t, n) !== Ap.CloseEnough && i.legibleSystemAdapter.tryAgain$.next(!0) + } + )) + } + , sy = (e,t)=>{ + let i, r = ""; + return i = e.videoCodec && e.audioCodec ? (r = `${e.videoCodec}, ${e.audioCodec}`, + t = null != t ? t : "video/mp4", + "audiovideo") : e.videoCodec ? (r = `${e.videoCodec}`, + t = null != t ? t : "video/mp4", + "video") : (r = `${null !== (e = e.audioCodec) && void 0 !== e ? e : ""}`, + t = null != t ? t : "audio/mp4", + "audio"), + { + mimeType: `${t};codecs=${r}`, + codec: r, + container: t, + type: i + } + } + ; + class ay { + constructor(e, t, i) { + this.config = e, + this.logger = t, + this.demuxClient = i, + this.typeSupported = { + mp4: MediaSource.isTypeSupported("video/mp4"), + mpeg: MediaSource.isTypeSupported("audio/mpeg"), + mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'), + ac3: MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"'), + ec3: MediaSource.isTypeSupported('audio/mp4; codecs="ec-3"') + }, + this.demuxers = [], + this.lastInitFrags = [], + this.lastFrags = [] + } + parseInitSegment(h, e) { + return this.getDemuxerInfo(h, this.lastInitFrags, e, this.demuxClient).pipe(Ra(({demuxer: e, contiguous: t, trackSwitch: i, discontinuity: r, accurateTimeOffset: n})=>{ + const s = h["frag"] + , {keyTagInfo: a, start: o, mediaOptionType: d} = s; + if (this.lastInitFrags[d] = s, + h.initSegment) { + const e = We.remuxInitSegment(new Uint8Array(h.initSegment), this.logger, a) + , t = Je.parseInitSegment(e) + , {mimeType: i, type: r, codec: n, container: s} = sy(t); + return Bi({ + moovData: t, + mimeType: i, + track: { + type: r, + codec: n, + initSegment: e, + container: s + } + }) + } + const l = h.segment || h.initSegment + , u = l ? h.initSegment : void 0 + , c = wc(e.observer); + return Bi(c.event(v.FRAG_PARSING_INIT_SEGMENT).pipe(ur(this.handleInitSegmentData)), c.event(x.INTERNAL_ERROR).pipe(Ra(this.handleError)), e.pushWithoutTransfer(l, a, u, o, r, i, t, h.totalDuration, n, void 0, h.iframeMediaStart, h.iframeDuration).pipe(Ua(Ti))).pipe(Wr(), Cs(1)) + } + )) + } + parseSegment(y, e) { + return this.getDemuxerInfo(y, this.lastFrags, e, this.demuxClient).pipe(Ra(({demuxer: e, contiguous: t, trackSwitch: i, discontinuity: r, accurateTimeOffset: n})=>{ + const {frag: h, defaultInitPTS: p} = y + , {keyTagInfo: s, start: a, duration: f, mediaOptionType: m} = h; + let g; + this.lastFrags[m] = h; + const o = wc(e.observer); + return Bi(o.event(v.FRAG_PARSING_INIT_SEGMENT).pipe(Ra(e=>{ + var t; + return e.track.initSegment.byteLength !== (null === (t = y.initSegment) || void 0 === t ? void 0 : t.byteLength) && (g = this.handleInitSegmentData(e)), + Ti + } + )), o.event(v.FRAG_PARSING_DATA).pipe(ur(e=>{ + var {startPTS: t, startDTS: i, firstKeyframePts: r, framesWithoutIDR: n, dropped: s, data1: a, data2: o, captionData: d, id3Samples: l} = e; + let {endPTS: u, endDTS: c} = e; + return null == u && (this.logger.warn(`${Cl[m]} ${Bp(h)}: null endPTS parsed, using duration ${f}`), + u = Object.assign(Object.assign({}, t), { + baseTime: t.baseTime + B(f, t.timescale).baseTime + })), + null == c && (this.logger.warn(`${Cl[m]} ${Bp(h)}: null endDTS parsed, using duration ${f}`), + c = Object.assign(Object.assign({}, i), { + baseTime: i.baseTime + B(f, i.timescale).baseTime + })), + ne(y.iframeMediaStart) || function(e, t, i, r) { + let n = NaN + , s = NaN; + if (ne(i)) + s = i, + n = .01, + isFinite(s) && isFinite(r) && (s += r); + else { + { + const o = void 0 + } + } + var {startPTS: a, startDTS: i, endPTS: r, endDTS: t} = t; + if (!(0 <= a.baseTime && 0 <= i.baseTime && 0 < e.duration && (null == r || 0 < b(r, a)) && (null == t || 0 < b(t, i)) && (!ne(n) || !ne(s) || Math.abs(S(i) - s) <= n))) + throw new D(!1,`Failed demuxer sanity check frag=${Bp(e)} parsed=${JSON.stringify({ + startPTS: a, + endPTS: r, + startDTS: i, + endDTS: t + })} ${se({ + expectedStartDTS: s, + fudge: n + })}`,$.FailedDemuxerSanityCheck) + }(h, e, (p, + y.iframeMediaStart), this.config.audioPrimingDelay), + { + startPTS: t, + endPTS: u, + startDTS: i, + endDTS: c, + firstKeyframePts: r, + framesWithoutIDR: n, + dropped: s, + data1: a, + data2: o, + captionData: d, + id3Samples: l, + parsedInitSegment: g + } + } + )), o.event(x.INTERNAL_ERROR).pipe(Ra(this.handleError)), e.push(y.segment, s, y.initSegment, a, r, i, t, y.totalDuration, n, p, y.iframeMediaStart, y.iframeDuration).pipe(Ua(Ti))).pipe(Wr(), Cs(1)) + } + )) + } + reset(e) { + if (null == e) + return this.demuxers.forEach(e=>{ + e && e.destroy() + } + ), + void (this.demuxers = []); + const t = this.demuxers[e]; + null == t || t.destroy(), + this.demuxers[e] = null + } + destroy(e) { + null != e ? this.reset(e) : this.reset() + } + willBeTrackSwitch(e, t) { + var {mediaOptionType: i, mediaOptionId: e} = e + , i = (t || this.lastFrags)[i]; + return !(i && i.mediaOptionId === e) + } + getDemuxerInfo(e, r, t, i) { + const {frag: n, ptsKnown: s, seeking: a, live: o} = e + , {discoSeqNum: d, mediaSeqNum: l, mediaOptionType: u} = n; + return Yr(()=>{ + var e = this.demuxers[u]; + return e ? Bi(e) : i.init(this.typeSupported, this.config, t).pipe(Ja(e=>this.demuxers[u] = e)) + } + ).pipe(ur(e=>{ + var t = r[u] + , i = this.willBeTrackSwitch(n, r); + return { + demuxer: e, + trackSwitch: i, + discontinuity: !(t && d === t.discoSeqNum), + contiguous: !!t && !i && t.mediaSeqNum + 1 === l, + accurateTimeOffset: !a && (s || !o) + } + } + )) + } + handleInitSegmentData(e) { + var t = e["track"] + , i = t["initSegment"] + , r = Je.parseInitSegment(i) + , {mimeType: n, type: s, codec: a, container: e} = sy(r, t.container); + return { + moovData: r, + mimeType: n, + track: Object.assign(Object.assign({}, t), { + type: s, + codec: a, + initSegment: i, + container: e + }) + } + } + handleError(e) { + return Ui(e) + } + } + function oy(e) { + return Math.min(e.targetduration, 15) + } + function dy(e, t, i, r) { + if (200 === t && r && 10 < r.length) { + if (Sm.isValidPlaylist(r)) + return !0; + { + const t = new R(o,_,!0,"response doesnt have #EXTM3U tag",$.PlaylistErrorMissingEXTM3U); + throw t.url = e, + t + } + } + return !1 + } + const ly = { + name: "pltfrm" + }; + function uy(e, t) { + t = Ih.getKeySystemSecurityLevel(t); + return null != e && void 0 !== t[e] + } + function cy(e) { + return e.every(e=>e.iframes) + } + function hy(e, t) { + return !ne(e) || !ne(t) || e <= t + } + function py() { + const n = new Set + , s = new Set; + return e=>{ + const i = (e,t)=>{ + t = t ? "audio" : "video"; + n.has(e) || s.has(e) || (((e,t)=>{ + let i = MediaSource.isTypeSupported(`${e}/mp4;codecs=${t}`); + return "mp4a.40.34" !== t || i || (i = MediaSource.isTypeSupported(`${e}/mpeg`)), + i + } + )(t, e) ? n : s).add(e) + } + , t = (e,t)=>(i(e, t), + s.has(e)); + let r = !1; + return e.audioCodecList && (r = e.audioCodecList.some(e=>t(e, !0))), + !r && e.videoCodecList && (r = e.videoCodecList.some(e=>t(e, !1))), + !r + } + } + function fy(e, t) { + for (const i in e) + if (e[i].type === t) + return e[i]; + return {} + } + function my(e, t, i) { + t.filter(e=>!i.includes(e)).map(e=>e.mediaOptionId) + } + function gy(e, i, s) { + const a = new Map + , r = new Array; + return e.forEach(t=>{ + var e = Array(); + !function(e, t, i) { + var r = qc.getCapabilities(t.videoCodecList, t.audioCodecList) + , t = JSON.stringify(r); + let n; + a.has(t) ? n = a.get(t) : (n = Ih.requestKeySystemAccess(e, r, void 0, s).pipe(ur(()=>!0), Un(e=>(s.warn(`Request key system error: ${e.message}`), + Bi(!1))), Aa({ + bufferSize: 1, + refCount: !0 + })), + a.set(t, n)), + i.push(n) + }(i, t, e); + e = Jr(e).pipe(ur(e=>{ + if (void 0 === e.find(e=>!1 === e)) + return t + } + )); + r.push(e) + } + ), + Jr(r).pipe(ur(e=>e.filter(e=>Boolean(e)))) + } + function yy(e, r) { + const o = new Set + , d = new Set + , l = !MediaSource.isTypeSupported('audio/mp4; codecs="mp4a.40.2"; channels="-1"') + , u = l && !MediaSource.isTypeSupported('audio/mp4; codecs="mp4a.40.2"; channels="2"; features="INVALID"') + , t = e.filter(e=>{ + let t = !1; + var i; + return e.audioCodecList && e.audioGroupId && (i = tm.getRichestChannelLayoutForGroupId(e.audioGroupId, r), + 0 < e.audioCodecList.length && i && (t = ((e,t)=>{ + var i, r, n, s = Se.isDolbyAtmos(e, t); + if (u || l && !s) { + n = `${i = e}/${r = t}`, + o.has(n) || d.has(n) || (((e,t)=>{ + const i = t.split("/") + , r = parseInt(i[0]); + let n, s; + if (1 < i.length) { + const t = i[1].split(",")[0]; + n = `audio/mp4;codecs="${e}";channels="${r}";features="${t}"`, + s = `audio/mp4;codecs="${e}";channels="8";features="${t}"` + } else + n = `audio/mp4;codecs="${e}";channels="${r}"`; + let a = MediaSource.isTypeSupported(n); + return !a && s && (a = MediaSource.isTypeSupported(s)), + a + } + )(i, r) ? o : d).add(n); + const a = `${e}/${t}`; + return d.has(a) + } + return !!s + } + )(tm.getRichestAudioCodec(e.audioCodecList), i))), + !t + } + ); + return my(0, e, t), + t + } + function vy(e, t, d) { + const n = 0 < (null == t ? void 0 : t.length) + , i = e.filter(o=>{ + var e = function() { + if (!d) + return { + highestPlayableAverageBitRate: void 0, + highestPlayablePeakBitRate: void 0, + highestPlayableWidth: void 0, + highestPlayableHeight: void 0, + highestPlayableFrameRate: void 0 + }; + const e = o.videoCodec + , t = o.videoRange + , i = d.videoDynamicRangeFormats + , r = d.videoCodecs + , n = Se.getDynamicRangeType(t, e) + , s = Se.getCompressionType(e) + , a = function(e, t, i, r) { + if (!r && !i) + return {}; + var n, s, t = i ? fy(i, t) : {}, r = r ? fy(r, e) : {}; + let a, o; + return o = e === pe.SDR ? (a = t, + r) : (a = r, + t), + n = Object.assign({}, a), + s = o, + Object.keys(s).forEach(e=>{ + n[e] || (n[e] = s[e]) + } + ), + n + }(n, s, r, i); + return s !== fe.VP09 && (a.highestPlayablePeakBitRateForClearContent = void 0), + a + }() + , t = e["highestPlayablePeakBitRateForClearContent"] + , i = o.allowedCPCMap || n + , r = hy(o.bandwidth, e.highestPlayablePeakBitRate); + return (i || !t ? r : r || hy(o.bandwidth, t)) && hy(o.avgBandwidth, e.highestPlayableAverageBitRate) && hy(o.width, e.highestPlayableWidth) && hy(o.height, e.highestPlayableHeight) && hy(o.frameRate, e.highestPlayableFrameRate) + } + ); + return my(0, e, i), + i + } + function Sy(e, a, o, d, l, u) { + var r = (null == d ? void 0 : d.maxHdcpLevel) || void 0; + let c = [...e]; + (0 < l.disableVideoCodecList.size || 0 < l.disableAudioCodecList.size) && (c = function(e, t, i) { + let r = e.filter(e=>!e.videoCodec || e.videoCodecList.every(e=>{ + e = $p(e); + return !t.has(e) + } + )); + return r = r.filter(e=>!(!e.iframes && e.audioCodec) || e.audioCodecList.every(e=>{ + e = Kp(e); + return !i.has(e) + } + )), + my(0, e, r), + r + }(c, l.disableVideoCodecList, l.disableAudioCodecList)), + r && Xf(r) && (c = function(e) { + const t = Yf(r) + , i = e.filter(e=>{ + e = e.hdcpLevel; + return !e || Yf(e) <= t + } + ); + return my(0, e, i), + i + }(c)); + var t = null == d ? void 0 : d.maxSecurityLevel + , e = null == l ? void 0 : l.keySystemPreference; + t && e && uy(t, e) && (c = function(e, t, i) { + function r(e) { + return uy(e, i) ? n[e] : -1 + } + const n = Ih.getKeySystemSecurityLevel(i) + , s = Ih.getKeySystemFormat(i) + , a = r(t) + , o = e.filter(e=>{ + e = null !== (e = null === (e = e.allowedCPCMap) || void 0 === e ? void 0 : e[s]) && void 0 !== e ? e : []; + let t = !0; + for (const i of e) + if (t = r(i) <= a, + !t) + break; + return t + } + ); + return my(0, e, o), + [...o] + }(c, t, e)), + c = c.map(t=>{ + var e; + return t.audioCodecList && t.audioGroupId && ((e = null == (e = a.find(e=>e.groupId === t.audioGroupId)) ? void 0 : e.channels) && (t.audioChannelCount = parseInt(e))), + t + } + ); + const h = !(null == l || !l.useMediaKeySystemAccessFilter) && e && navigator && "function" == typeof navigator.requestMediaKeySystemAccess; + return (h ? gy(c, e, u) : Bi(c)).pipe(Ra(e=>{ + if (0 === e.length || cy(e)) + throw new R(L,f,void 0,"no media option with compatible codecs found in playlist",void 0); + h && my(0, c, e); + const t = navigator && navigator.mediaCapabilities + , n = !(null == l || !l.useMediaCapabilities) && t && "function" == typeof t.decodingInfo; + let i; + return i = n ? function(e, n, s) { + const a = [] + , o = py() + , d = function(o) { + const d = new Map + , l = navigator && navigator.mediaCapabilities; + return (i,e,t,n,r)=>{ + const s = { + type: "media-source" + }; + n ? s.video = function(e) { + const t = { + contentType: `video/mp4;codecs=${e}`, + width: i.width, + height: i.height, + bitrate: i.bandwidth || i.avgBandwidth, + framerate: i.iframes ? 8 : i.frameRate + }; + if (i.videoRange) + switch (i.videoRange) { + case "PQ": + Se.isDolby(e) ? (t.hdrMetadataType = vm.DoVi, + t.colorGamut = "rec2020") : (Se.isHEVC(e) || Se.isVP09(e)) && (t.hdrMetadataType = vm.HDR10, + t.colorGamut = "rec2020"), + t.transferFunction = "pq"; + break; + case "HLG": + t.colorGamut = "rec2020", + t.transferFunction = "hlg" + } + return t + }(t) : s.audio = function(e, t, i) { + const r = { + contentType: `audio/mp4;codecs=${e}` + } + , n = tm.getRichestChannelLayoutForGroupId(t.audioGroupId, i); + return n && (r.channels = Se.getChannelCount(n).toString(), + r.spatialRendering = Se.isDolbyAtmos(e, n)), + r + }(t, i, e); + e = JSON.stringify(s); + let a; + return d.has(e) ? a = d.get(e) : (a = Lr(l.decodingInfo(s)).pipe(ur(e=>{ + const t = e.configuration || e.supportedConfiguration + , i = t instanceof Object && (!s.video || null == Object.keys(s.video).find(e=>!(e in t.video))) && (!s.audio || null == Object.keys(s.audio).find(e=>!(e in t.audio))) + , r = e.supported && (!n || e.powerEfficient) && i; + return r || o.warn(ly, `Unsupported config ${e.supported}/${e.powerEfficient}/${i} ${JSON.stringify(s)} supportedConfig=${JSON.stringify(t)}`), + r + } + )), + d.set(e, a)), + [...r, a] + } + }(s); + return e.forEach(t=>{ + var e; + let i = []; + if (null === (e = t.videoCodecList) || void 0 === e || e.forEach(e=>{ + i = d(t, n, e, !0, i) + } + ), + 0 < (null === (e = t.audioCodecList) || void 0 === e ? void 0 : e.length)) { + const s = tm.getRichestAudioCodec(t.audioCodecList); + i = d(t, n, s, !1, i) + } + let r = Bi(t); + 0 < i.length && (r = Jr(i).pipe(ur(e=>null == e.find(e=>!1 === e) ? t : null), Un(e=>(s.warn(ly, `decodingInfo errror: ${e.message}`), + Bi(o(t) ? t : null))))), + a.push(r) + } + ), + Jr(a).pipe(ur(e=>e.filter(e=>Boolean(e)))) + }(e, a, u) : Bi(e = yy((r = e, + s = py(), + s = r.filter(s), + my(0, r, s), + e = s), a)), + i.pipe(ur(e=>{ + if (0 === e.length || cy(e)) + throw new R(L,f,void 0,"no media option with compatible codecs found in manifest",void 0); + if (0 === (t = e = vy(e, o, d), + r = t.filter(e=>!e.iframes || !e.width || !e.height || e.width * e.height <= 2488320), + my(0, t, r), + (e = r).length) || cy(e)) + throw new R(L,f,void 0,"no media option with compatible codecs found in manifest",void 0); + var t; + let i = (null == d ? void 0 : d.videoDynamicRangeFormats) || []; + n && 0 === i.length && (i = [{ + type: pe.SDR + }, { + type: pe.HDR + }, { + type: pe.HDR10 + }, { + type: pe.DolbyVision + }, { + type: pe.HLG + }]); + var {hdrMediaOptions: r, sdrMediaOptions: e} = function(e, t) { + const i = t.reduce((e,t)=>{ + switch (t.type) { + case pe.DolbyVision: + e.doViSupported = !0; + break; + case pe.HDR10: + e.hdr10Supported = !0; + break; + case pe.HLG: + e.hlgSupported = !0 + } + return e + } + , { + doViSupported: !1, + hdr10Supported: !1, + hlgSupported: !1 + }) + , {doViSupported: r, hdr10Supported: n, hlgSupported: s} = i; + return e.reduce((e,t)=>{ + var i; + switch (Se.getDynamicRangeType(t.videoRange, null !== (i = t.videoCodec) && void 0 !== i ? i : "")) { + case pe.HDR: + case pe.HDR10: + n && e.hdrMediaOptions.push(t); + break; + case pe.DolbyVision: + r && e.hdrMediaOptions.push(t); + break; + case pe.HLG: + s && e.hdrMediaOptions.push(t); + break; + default: + "SDR" !== t.videoRange && null != t.videoRange || e.sdrMediaOptions.push(t) + } + return e + } + , { + hdrMediaOptions: new Array, + sdrMediaOptions: new Array + }) + }(e, i); + if (0 === r.length && 0 === e.length || cy(r) && cy(e)) + throw new R(L,"manifestIncompatibleVideoRangeError",void 0,"mediaOption with compatible VIDEO-RANGE not found in manifest",void 0); + return { + hdrMediaOptions: r, + sdrMediaOptions: e + } + } + ), Un(e=>{ + throw e instanceof R && (e.fatal = !0, + e.response = $.IncompatibleAsset), + e + } + )); + var r, s + } + )) + } + function by(e, t) { + return t.mediaOptionId !== e.mediaOptionId && t.persistentID === e.persistentID && t.groupId !== e.groupId + } + (w = vm = vm || {}).HDR10 = "smpteSt2086", + w.DoVi = "smpteSt2094-10", + w.HDR10Plus = "smpteSt2094-40"; + class Ty extends km { + constructor(e, t, i) { + super(e, t, i) + } + static makeFilters() { + return Om() + } + _initFilters() { + return Ty.kAllowFilters + } + get _mediaOptionType() { + return this.mediaOptionType + } + get preferredHost() { + return null + } + get preferredHost$() { + return Bi(null) + } + get mediaOptionListInfo() { + var e; + return null !== (e = null === (e = this.getEntity(this.itemId)) || void 0 === e ? void 0 : e.mediaOptionListTuple[this._mediaOptionType]) && void 0 !== e ? e : null + } + get mediaOptionListInfo$() { + return this.selectEntity(this.itemId, e=>e && e.mediaOptionListTuple ? e.mediaOptionListTuple[this._mediaOptionType] : null).pipe(Up()) + } + getFallbackVariant(t, e, i, r) { + var n; + const s = null === (n = this.mediaOptionList) || void 0 === n ? void 0 : n.find(e=>e.mediaOptionId === t); + if (!s) + return null; + const a = this.filteredMediaOptionList; + if (!a) + return null; + const o = gl(s.url); + if (i) + return null !== (i = a.find(e=>by(s, e) && !yl(o, e.url))) && void 0 !== i ? i : null; + let d = null; + for (const t of a) + !by(s, t) || d && !yl(o, t.url) || (d = t); + return d + } + getMatchingAlternateWithPersistentId(t, i, r) { + var e; + return null !== (e = this.preferredMediaOptionList.find(e=>!(0 < (null == r ? void 0 : r.length) && r.includes(e.mediaOptionId)) && (!ne(t) || e.persistentID === t) && (!i || this.matchGroup(e, i.audioGroupId, i.subtitleGroupId, i.closedcaption)))) && void 0 !== e ? e : null + } + matchGroup(e, t, i, r) { + let n = !1; + switch (e.type) { + case "CLOSED-CAPTIONS": + n = !r || e.groupId === r; + break; + case "SUBTITLES": + n = !i || e.groupId === i; + break; + case "AUDIO": + n = !t || e.groupId === t + } + return n + } + getMatchingAlternate(e, t) { + e = this.mediaOptionFromId(e); + return this.getMatchingAlternateWithPersistentId(null == e ? void 0 : e.persistentID, t, []) + } + packageAlternateMediaOption(e, t, i) { + return t.mediaType === pl.CLOSEDCAPTION ? this.augmentClosedCaptionsWithForcedSubtitles(null == e ? void 0 : e.subtitleGroupId, t, i) : t + } + augmentClosedCaptionsWithForcedSubtitles(e, t, i) { + i = this.pairForcedSubtitleMediaOptionWithClosedCaption(e, t, i); + return i ? Object.assign(Object.assign({}, t), { + url: i.url, + backingMediaOptionId: i.mediaOptionId + }) : t + } + pairForcedSubtitleMediaOptionWithClosedCaption(t, i, r) { + let n; + if (i && i.mediaType === pl.CLOSEDCAPTION) { + let e = this.mediaOptionList; + r && (e = this.preferredMediaOptionList), + n = Ty.pairForcedSubtitleMediaOptionWithClosedCaptionInList(t, i, e) + } + return n + } + static pairForcedSubtitleMediaOptionWithClosedCaptionInList(t, i, e) { + return e.find(function(e) { + return e.mediaType === pl.SUBTITLE && e.lang === i.lang && e.forced && e.autoselect && (!t || e.groupId === t) + }) + } + } + Ty.kAllowFilters = Ty.makeFilters(); + class Ey extends Od { + constructor(e, t) { + super(e), + this.itemId = t, + this.mediaOptionListQueries = [new xm(e,this.itemId), new Ty(e,this.itemId,ul.AltAudio), new Ty(e,this.itemId,ul.Subtitle)] + } + get rootPlaylistEntity() { + return this.getEntity(this.itemId) + } + get rootMediaOptionsTuple() { + var e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.mediaOptionListTuple; + return e ? [e[0].mediaOptions, e[1].mediaOptions, e[2].mediaOptions] : [[], [], []] + } + get itemStartOffset() { + var e, t; + return null !== (e = this.rootPlaylistEntity) && void 0 !== e && e.itemStartOffset && ne(null === (t = this.rootPlaylistEntity) || void 0 === t ? void 0 : t.itemStartOffset) ? null === (t = this.rootPlaylistEntity) || void 0 === t ? void 0 : t.itemStartOffset : 0 + } + get highestVideoCodec() { + var e; + return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.highestVideoCodec + } + get baseUrl() { + var e; + return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.baseUrl + } + get anchorTime() { + var e; + return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.anchorTime + } + get discoSeqNum() { + var e; + return null !== (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.discoSeqNum) && void 0 !== e ? e : NaN + } + get discoSeqNum$() { + return this.selectEntity(this.itemId, "discoSeqNum") + } + get audioMediaSelectionGroup() { + var e; + return null !== (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.audioMediaSelectionGroup) && void 0 !== e ? e : null + } + get subtitleMediaSelectionGroup() { + var e; + return null !== (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.subtitleMediaSelectionGroup) && void 0 !== e ? e : null + } + get audioMediaSelectionOptions() { + var e; + return null !== (e = null === (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.audioMediaSelectionGroup) || void 0 === e ? void 0 : e.MediaSelectionGroupOptions) && void 0 !== e ? e : [] + } + get subtitleMediaSelectionOptions() { + var e; + return null !== (e = null === (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.subtitleMediaSelectionGroup) || void 0 === e ? void 0 : e.MediaSelectionGroupOptions) && void 0 !== e ? e : [] + } + get contentSteeringOption() { + var e; + return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.contentSteeringOption + } + get masterVariableList() { + var e; + return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.masterVariableList + } + get loadStats() { + var e; + return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.loadStats + } + get isMediaPlaylist() { + var e; + return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.isMediaPlaylist + } + getInitPTS(e) { + var t; + return null === (t = this.rootPlaylistEntity) || void 0 === t ? void 0 : t.initPtsRecord[e] + } + get abrStatus$() { + return this.selectEntity(this.itemId, e=>null == e ? void 0 : e.abrStatus) + } + get abrStatus() { + var e; + return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.abrStatus + } + get nextMaxAutoOptionId() { + var e; + return null === (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.abrStatus) || void 0 === e ? void 0 : e.nextMaxAutoOptionId + } + get nextMinAutoOptionId() { + var e; + return null === (e = null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.abrStatus) || void 0 === e ? void 0 : e.nextMinAutoOptionId + } + initPTS$(t) { + return this.selectEntity(this.itemId, ({initPtsRecord: e})=>e[t]) + } + get rootPlaylistEntity$() { + return this.selectEntity(this.itemId).pipe(an(e=>Boolean(e)), ur(e=>e)) + } + get rootPlaylistEntityAdded$() { + return this.selectEntityAction(To.Add).pipe(ur(e=>e.map(e=>this.getEntity(e)))) + } + get rootMediaOptionsTuple$() { + return Zd([this.selectEntity(this.itemId, e=>e.mediaOptionListTuple[0].mediaOptions), this.selectEntity(this.itemId, e=>e.mediaOptionListTuple[1].mediaOptions), this.selectEntity(this.itemId, e=>e.mediaOptionListTuple[2].mediaOptions)]) + } + get sessionData() { + var e; + return null === (e = this.rootPlaylistEntity) || void 0 === e ? void 0 : e.sessionData + } + get sessionData$() { + return this.selectEntity(this.itemId, ({sessionData: e})=>e).pipe(Up()) + } + get anchorTime$() { + return this.selectEntity(this.itemId, "anchorTime").pipe(Ra(e=>ne(e) ? e !== this.anchorTime ? (qe().warn(`anchorTime doesn't match stored value! ${e} !== ${this.anchorTime}`), + Ti) : Bi(e) : Ti)) + } + get pendingSeek$() { + return this.selectEntity(this.itemId, ({pendingSeek: e})=>e).pipe(Es((e,t)=>e === t || "number" == typeof e && "number" == typeof t && isNaN(e) && isNaN(t))) + } + get enabledMediaOptionKeys$() { + return this.selectEntity(this.itemId, "enabledMediaOptionKeys").pipe(an(e=>Boolean(e))) + } + get enabledMediaOptionKeys() { + var e; + return null !== (e = null === (e = this.getEntity(this.itemId)) || void 0 === e ? void 0 : e.enabledMediaOptionKeys) && void 0 !== e ? e : [Ol, Ol, Ol] + } + get enabledMediaOptionSwitchContexts() { + var e; + return null !== (e = null === (e = this.getEntity(this.itemId)) || void 0 === e ? void 0 : e.mediaOptionSwitchContexts) && void 0 !== e ? e : [null, null, null] + } + enabledMediaOptionSwitchContextsByType$(t) { + return this.selectEntity(this.itemId, "mediaOptionSwitchContexts").pipe(ur(e=>null == e ? void 0 : e[t])) + } + get enabledMediaOptions$() { + return Zd([this.enabledMediaOptionByType$(ul.Variant), this.enabledMediaOptionByType$(ul.AltAudio), this.enabledMediaOptionByType$(ul.Subtitle)]) + } + get enabledAVOptions$() { + return Zd([this.enabledMediaOptionByType$(ul.Variant), this.enabledMediaOptionByType$(ul.AltAudio)]) + } + rawEnabledMediaOptionByType$(t) { + return this.enabledMediaOptionKeys$.pipe(ur(e=>{ + const i = e[t]; + return kl(i) && this.rootMediaOptionsTuple[t].find(e=>{ + return t = i, + e.itemId === t.itemId && e.mediaOptionId === t.mediaOptionId; + var t + } + ) || Ol + } + )) + } + enabledMediaOptionByType$(e) { + return this.rawEnabledMediaOptionByType$(e).pipe(Es((e,t)=>e.mediaOptionId === t.mediaOptionId && e.url === t.url)) + } + enabledMediaOptionSwitchForType$(e) { + return this.rawEnabledMediaOptionByType$(e).pipe(So(this.enabledMediaOptionSwitchContextsByType$(e)), xa(null), ca(), ur(([e,t])=>({ + fromId: null == e ? void 0 : e[0].mediaOptionId, + toId: null == t ? void 0 : t[0].mediaOptionId, + switchContext: null == t ? void 0 : t[1] + })), Es((e,t)=>e.fromId === t.fromId && e.toId === t.toId)) + } + enableMediaOptionSwitchedForType$(t) { + return this.enabledMediaOptionByType$(t).pipe(Ra(e=>$l(Cr([Bi(e), this.enabledMediaOptionSwitchContextsByType$(t).pipe(ca())]), ([,e])=>e[0] && !e[1])), ur(([e])=>e)) + } + enabledMediaOptionIdByType(e) { + return this.getEntity(this.itemId).enabledMediaOptionKeys[e].mediaOptionId + } + variantMediaOptionById(e) { + return this.mediaOptionListQueries[ul.Variant].mediaOptionFromId(e) + } + alternateMediaOptionById(e, t) { + return this.mediaOptionListQueries[e].mediaOptionFromId(t) + } + enabledAlternateMediaOptionByType(e) { + var t = this.enabledMediaOptionIdByType(e); + return this.alternateMediaOptionById(e, t) + } + get enabledVariantMediaOption() { + var e = this.enabledMediaOptionIdByType(ul.Variant); + return this.variantMediaOptionById(e) + } + lastLoadedMediaOptionByType(e) { + var t; + return null === (t = this.getEntity(this.itemId).lastLoadedMediaOptionKeys) || void 0 === t ? void 0 : t[e] + } + get nextMediaOptionsKeys$() { + return this.selectEntity(this.itemId, "nextMediaOptionKeys") + } + get preferredMediaOptions() { + return [this.mediaOptionListQueries[0].preferredMediaOptionList, this.mediaOptionListQueries[1].preferredMediaOptionList, this.mediaOptionListQueries[2].preferredMediaOptionList] + } + get preferredMediaOptions$() { + return Zd([this.mediaOptionListQueries[0].preferredMediaOptionList$, this.mediaOptionListQueries[1].preferredMediaOptionList$, this.mediaOptionListQueries[2].preferredMediaOptionList$]) + } + get filteredMediaOptions() { + return [this.mediaOptionListQueries[0].filteredMediaOptionList, this.mediaOptionListQueries[1].filteredMediaOptionList, this.mediaOptionListQueries[2].filteredMediaOptionList] + } + getDisabledMediaOption(e) { + return { + itemId: this.itemId, + mediaOptionType: e, + mediaOptionId: "Nah" + } + } + getEnabledMediaOptionMask() { + return this.enabledMediaOptionKeys.map(e=>kl(e)) + } + getPreferredMediaOptionsByType$(e) { + return this.mediaOptionListQueries[e].preferredMediaOptionList$ + } + altMediaOptionHasValidUrl(e, t) { + t = this.alternateMediaOptionById(e, t); + return Boolean(null == t ? void 0 : t.url) + } + get hdrMode$() { + return this.mediaOptionListQueries[ul.Variant].hdrMode$ + } + get maxHdcpLevel$() { + return this.mediaOptionListQueries[ul.Variant].maxHdcpLevel$ + } + get currentPathwayID() { + return this.mediaOptionListQueries[ul.Variant].currentPathwayID + } + get preferredHost() { + return this.mediaOptionListQueries[ul.Variant].preferredHost + } + getErrorInfoByType(e) { + var t; + return null != (null === (t = this.rootPlaylistEntity) || void 0 === t ? void 0 : t.errorsByType) ? this.rootPlaylistEntity.errorsByType[e] : null + } + getInFlightFragByType(e) { + var t; + return null !== (e = null === (t = null === (t = this.getEntity(this.itemId)) || void 0 === t ? void 0 : t.inFlightFrags) || void 0 === t ? void 0 : t[e]) && void 0 !== e ? e : null + } + getInFlightFragByType$(t) { + return this.selectEntity(this.itemId, e=>{ + return null === (e = null == e ? void 0 : e.inFlightFrags) || void 0 === e ? void 0 : e[t] + } + ) + } + matchAlternates(e, t, i, r) { + t = ne(t) ? this.mediaOptionListQueries[ul.AltAudio].getMatchingAlternateWithPersistentId(t, e, r) : void 0, + r = ne(i) ? this.mediaOptionListQueries[ul.Subtitle].getMatchingAlternateWithPersistentId(i, e, r) : void 0; + return [t || Ol, r || Ol] + } + getLegacyMatchingAlternateWithPersistentId(e, t, i) { + let r = this.mediaOptionListQueries[e].getMatchingAlternateWithPersistentId(t, i, []); + return r = r || this.mediaOptionListQueries[e].getMatchingAlternateWithPersistentId(t, void 0, []), + r + } + isValidMediaOptionTuple(i, e) { + const r = e || this.getEnabledMediaOptionMask(); + return [ul.Variant, ul.AltAudio, ul.Subtitle].reduce((e,t)=>e && r[t] === kl(i[t]), !0) + } + matchGroup(e, t, i, r) { + var n = e.mediaOptionType; + return this.mediaOptionListQueries[n].matchGroup(e, t, i, r) + } + get preferHDR() { + return this.mediaOptionListQueries[ul.Variant].mediaOptionListInfo.preferHDR + } + } + const Iy = { + name: "rps" + }; + class wy { + constructor(e, t) { + this.store = e, + this.logger = t + } + getQuery() { + return new Od(this.store) + } + getQueryForId(e) { + return new Ey(this.store,e) + } + set rootPlaylistEntity(e) { + Co("root.add.rootPlaylist"), + this.store.add(e) + } + removeItems(e) { + Co(`root.add.remove ${JSON.stringify(e)}`), + this.store.remove(e) + } + removeAll() { + Co("root.add.clear"), + this.store.remove() + } + setRootPlaylistEntity(e, t) { + Co("root.set.rootPlaylistEntity"), + this.store.update(e, e=>t) + } + setSessionData(e, t) { + Co("root.set.sessionData"), + this.store.update(e, e=>{ + e.sessionData = t + } + ) + } + setAnchorTime(e, t) { + Co(`root.set.anchorTime: ${t}`), + this.store.update(e, e=>{ + e.anchorTime = t + } + ) + } + setDiscoSeqNum(e, t) { + Co(`root.set.discoSeqNum: ${t}`), + this.store.update(e, e=>{ + e.discoSeqNum = t + } + ) + } + setPendingSeek(e, t) { + Co("root.set.pendingSeek"), + this.store.update(e, e=>{ + e.pendingSeek = t + } + ), + void 0 === t && Xm().setUserSeek(t) + } + setEnabledMediaOptionSwitchContextByType(e, i, r, n) { + this.store.update(e, e=>{ + var t; + if (e.enabledMediaOptionKeys[i].mediaOptionId === r) { + const r = null !== (t = e.mediaOptionSwitchContexts) && void 0 !== t ? t : [null, null, null]; + r[i] = n ? { + userInitiated: n.userInitiated, + switchPosition: n.switchPosition + } : null, + e.mediaOptionSwitchContexts = r + } else + Co(`root.set.mediaOptionSwitchContextByType ${r} doesn't match existing mediaOption ${e.enabledMediaOptionKeys[i].mediaOptionId}`) + } + ) + } + setEnabledMediaOptionByType(r, n, s, a=!1, o) { + s = s || { + itemId: r, + mediaOptionType: n, + mediaOptionId: "Nah" + }, + this.store.update(r, e=>{ + var t; + const i = null !== (t = [...e.enabledMediaOptionKeys]) ? t : [Ol, Ol, Ol]; + if (i[n] = { + itemId: r, + mediaOptionId: s.mediaOptionId + }, + this._updateEnabledMediaOptionKeys(e, i), + a) { + const r = null !== (t = e.mediaOptionSwitchContexts) && void 0 !== t ? t : [null, null, null]; + r[n] = o ? { + userInitiated: o.userInitiated, + switchPosition: o.switchPosition + } : null, + e.mediaOptionSwitchContexts = r + } + } + ) + } + _associateForcedSubtitleWithClosedCaption(e, t, i, r) { + if ((null == i ? void 0 : i.mediaType) === pl.CLOSEDCAPTION) { + t = r.variantMediaOptionById(t), + r = r.mediaOptionListQueries[ul.Subtitle].packageAlternateMediaOption(t, i, !0); + if (r.url !== i.url) { + const n = My(t, r, e.mediaOptionListTuple[ul.Subtitle].mediaOptions, qe()); + e.mediaOptionListTuple[ul.Subtitle].mediaOptions = n + } + } + } + _updateEnabledMediaOptionKeys(t, i) { + var e, r; + const n = null !== (e = t.enabledMediaOptionKeys) && void 0 !== e ? e : [Ol, Ol, Ol]; + let s; + for (let e = 0; e < i.length; ++e) { + var a = i[e] + , o = n[e].mediaOptionId !== a.mediaOptionId; + if (o && (n[e] = Object.assign({}, a)), + e === ul.Variant) { + const i = this.getQueryForId(a.itemId).mediaOptionListQueries[e].mediaOptionList; + o ? t.abrStatus = (r = a.mediaOptionId, + o = i, + o = Lg(r, o), + { + fragDownloadSlow: !1, + fragDownloadTooSlow: !1, + nextMinAutoOptionId: Ol.mediaOptionId, + nextMaxAutoOptionId: Ol.mediaOptionId, + highBWTrigger: o + }) : t.abrStatus.highBWTrigger = Lg(a.mediaOptionId, i), + s = a + } else if (e === ul.Subtitle && kl(a)) { + const i = this.getQueryForId(a.itemId) + , n = i.alternateMediaOptionById(e, a.mediaOptionId); + this._associateForcedSubtitleWithClosedCaption(t, s.mediaOptionId, n, i) + } + } + t.enabledMediaOptionKeys = n, + t.nextMediaOptionKeys = void 0 + } + setManualMode(e, t) { + this.store.update(e, e=>{ + e.manualMode = t + } + ) + } + setEnabledMediaOptions(e, i) { + this.store.update(e, e=>{ + var t = i.map(({mediaOptionId: e, itemId: t})=>({ + mediaOptionId: e, + itemId: t + })); + this._updateEnabledMediaOptionKeys(e, t) + } + ) + } + setEnabledMediaOptionsAndSwitchContexts(e, i, r) { + this.store.update(e, e=>{ + var t = i.map(({mediaOptionId: e, itemId: t})=>({ + mediaOptionId: e, + itemId: t + })); + this._updateEnabledMediaOptionKeys(e, t), + e.mediaOptionSwitchContexts = r + } + ) + } + setNextMediaOptions(e, i) { + Co(`root.set.nextMediaOptions: ${JSON.stringify(null == i ? void 0 : i.map(e=>e.mediaOptionId))}`), + this.store.update(e, e=>{ + var t = i ? i.map(({itemId: e, mediaOptionId: t})=>({ + itemId: e, + mediaOptionId: t + })) : null; + e.nextMediaOptionKeys = t + } + ) + } + updateEnabledMediaOptions(e) { + Co("root.set.updateEnabledMediaOptions"), + this.store.update(e, e=>{ + e.nextMediaOptionKeys && !0 !== e.manualMode && (Co(`root.set.updateEnabledMediaOptions ${JSON.stringify(e.nextMediaOptionKeys)}`), + this._updateEnabledMediaOptionKeys(e, [...e.nextMediaOptionKeys])), + e.nextMediaOptionKeys = void 0 + } + ) + } + setLastLoadedMediaOptionByType(r, n, s) { + Co(`root.set.lastLoadedMediaOptionByType: ${n} ${(s = s || { + itemId: r, + mediaOptionType: n, + mediaOptionId: "Nah" + }).mediaOptionId}`), + this.store.update(r, e=>{ + var t; + const i = null !== (t = e.lastLoadedMediaOptionKeys) && void 0 !== t ? t : [Ol, Ol, Ol]; + i[n] = { + itemId: r, + mediaOptionId: s.mediaOptionId + }, + e.lastLoadedMediaOptionKeys = i + } + ) + } + setPreferredHost(e, t) { + Co(`root.set.preferredHost: ${t}`), + this.store.update(e, e=>{ + e && (e.mediaOptionListTuple[ul.Variant].preferredHost = t) + } + ) + } + setViewportInfo(e, t) { + Co(`root.set.viewportInfo: ${JSON.stringify(t)}`), + this.store.update(e, e=>{ + e && (e.mediaOptionListTuple[ul.Variant].viewportInfo = t) + } + ) + } + static getExistingPersistentIds(e) { + var t; + const i = {} + , r = null === (t = e.enabledMediaOptionKeys[ul.AltAudio]) || void 0 === t ? void 0 : t.mediaOptionId; + if ("Nah" !== r) { + const s = e.mediaOptionListTuple[ul.AltAudio] + , t = wm(s.mediaOptions, Ty.kAllowFilters, s).find(e=>e.mediaOptionId === r); + i.audioPersistentId = null == t ? void 0 : t.persistentID + } + const n = null === (t = e.enabledMediaOptionKeys[ul.Subtitle]) || void 0 === t ? void 0 : t.mediaOptionId; + if ("Nah" !== n) { + const s = e.mediaOptionListTuple[ul.Subtitle] + , t = wm(s.mediaOptions, Ty.kAllowFilters, s).find(e=>e.mediaOptionId === n); + i.subtitlePersistentId = null == t ? void 0 : t.persistentID + } + return i + } + static doUpdateRootHDRSwitch(e, t, i, r) { + const n = e.mediaOptionListTuple.map(e=>Object.assign({}, e)); + n[ul.Variant].preferHDR = t, + n[ul.Variant].hasHdrLevels = i; + const s = Ym() + , a = Hg.getEntity(e.itemId) + , o = Uf(e.itemId) + , d = o.getBandwidthEstimate(s, null == a ? void 0 : a.serviceName) + , l = o.getPlaylistEstimate(s, null == a ? void 0 : a.serviceName) + , u = o.getFragEstimate(s, null == a ? void 0 : a.serviceName) + , c = o.getBufferEstimate(s, null == a ? void 0 : a.serviceName) + , h = { + targetDuration: u.maxDurationSec || (null == s ? void 0 : s.defaultTargetDuration), + targetStartupMs: null == s ? void 0 : s.targetStartupMs + } + , p = wy.getExistingPersistentIds(e); + return Py(Object.assign(Object.assign({}, e), { + mediaOptionListTuple: n, + nextMediaOptionKeys: null + }), p, r, d, h, l, u, c) + } + switchToSDROnly(e) { + Co("root.switchToSDROnly"), + this.store.update(e, e=>{ + var t = wy.doUpdateRootHDRSwitch(e, !1, !1, this.logger)["mediaOptionListTuple"]; + e.mediaOptionListTuple = t + } + ) + } + setHDRPreference(e, i, r) { + Co(`root.set.HDRPreference: ${i}`), + this.store.update(e, e=>{ + var t = e.mediaOptionListTuple[ul.Variant]; + if (t.preferHDR !== i && (!i || t.hasHdrLevels)) { + t = wy.doUpdateRootHDRSwitch(e, i, t.hasHdrLevels, this.logger); + if (r) + return t; + e.mediaOptionListTuple = t.mediaOptionListTuple + } + } + ) + } + setPathwayPriority(e, i) { + Co(`root.set.PathwayPriority: [ ${i.join(", ")} ]`), + this.store.update(e, e=>{ + if (e) { + const t = e.mediaOptionListTuple[ul.Variant]; + t.pathwayPriority = i, + t.preferredHost = null + } + } + ) + } + setCurrentPathwayID(e, t) { + Co(`root.set.currentPathwayID: ${t}`), + this.store.update(e, e=>{ + e && (e.mediaOptionListTuple[ul.Variant].currentPathwayID = t) + } + ) + } + setInitPTS(e, t, i, r, n, s) { + Co(`root.set.initPTS: ${e} ${t} variantDTS:${JSON.stringify(i)} timelineOffset: ${r}`), + this.store.update(e, e=>{ + e.initPtsRecord[t] = { + variantDTS: i, + timelineOffset: r, + offsetTimestamp: n, + iframeMode: s + } + } + ) + } + static prunePenaltyBox(e, t) { + return e.filter(e=>!(e.expiry <= t)) + } + static addToPenaltyBox(e, t, i) { + return e.push({ + mediaOptionId: i, + expiry: t + 12e4 + }) + } + addToPenaltyBox(e, r, n) { + Co(`root.set.penaltyBox: ${r}: ${n}`), + this.store.update(e, ({mediaOptionListTuple: e})=>{ + const t = e[r] + , i = performance.now(); + t.penaltyBoxQueue = wy.prunePenaltyBox(t.penaltyBoxQueue, i), + wy.addToPenaltyBox(t.penaltyBoxQueue, i, n) + } + ) + } + prunePenaltyBox(e, r=null) { + Co(`root.set.prunePenaltyBox: ${r}`), + this.store.update(e, ({mediaOptionListTuple: e})=>{ + var e = r ? [e[r]] : e + , t = performance.now(); + for (const i of e) + i.penaltyBoxQueue = wy.prunePenaltyBox(i.penaltyBoxQueue, t) + } + ) + } + removePermanently(e, r, n) { + Co(`root.set.removePermanently: ${r}: ${n}`), + this.store.update(e, ({mediaOptionListTuple: e})=>{ + const t = e[r] + , i = new Set(t.removed); + i.add(n), + t.removed = Array.from(i) + } + ) + } + moveAllWithMatchingHosts(e, r, n, s) { + Co(`root.set.moveAllMatchingHosts: ${r}:${n} remove:${s}`), + this.store.update(e, ({mediaOptionListTuple: e})=>{ + const t = e[r] + , i = [...t.mediaOptions].filter(e=>yl(n, e.url)).map(e=>e.mediaOptionId); + if (s) { + const e = new Set([...t.removed, ...i]); + t.removed = Array.from(e) + } else { + const e = performance.now(); + t.penaltyBoxQueue = wy.prunePenaltyBox(t.penaltyBoxQueue, e); + for (const r of i) + wy.addToPenaltyBox(t.penaltyBoxQueue, e, r) + } + } + ) + } + setMaxHdcpLevel(e, i, r=!1) { + Co(`root.set.maxHdcpLevel: ${i}`), + this.store.update(e, ({mediaOptionListTuple: e})=>{ + const t = e[ul.Variant]; + (r || Yf(i) < Yf(t.maxHdcpLevel)) && (t.maxHdcpLevel = i) + } + ) + } + updateConsecutiveTimeouts(e, i, r, n) { + this.store.update(e, e=>{ + const t = e.errorsByType || [{ + timeouts: { + load: 0, + append: 0, + key: 0 + } + }, { + timeouts: { + load: 0, + append: 0, + key: 0 + } + }, { + timeouts: { + load: 0, + append: 0, + key: 0 + } + }]; + r ? ++t[i].timeouts[n] : t[i].timeouts[n] = 0, + e.errorsByType = t + } + ) + } + updateInflightFrag(d, l, u, c, h) { + Co("root.set.updateInflightFrag"), + this.store.update(d, r=>{ + if (r.inFlightFrags || (r.inFlightFrags = [null, null]), + !(l === ul.Subtitle || u && u.itemId !== d)) + if (u) { + let {start: e, duration: t} = u; + var {mediaOptionId: n, mediaSeqNum: s, discoSeqNum: a} = u + , o = r.inFlightFrags[l]; + let i = null == o ? void 0 : o.tstart; + c !== (null == o ? void 0 : o.state) && (i = performance.now()), + Fp(o, u) && (e = o.start, + t = o.duration), + r.inFlightFrags[l] = { + itemId: d, + mediaOptionId: n, + mediaSeqNum: s, + discoSeqNum: a, + start: e, + duration: t, + tstart: i, + state: c, + bwSample: Object.assign({}, h) + } + } else + r.inFlightFrags[l] = null + } + ) + } + setNextMaxAutoOptionId(e, t) { + Co(`root.set.nextMaxAutoOptionId: ${t}`), + this.store.update(e, ({abrStatus: e})=>{ + e.nextMaxAutoOptionId = t + } + ) + } + setNextMinAutoOptionId(e, t) { + Co(`root.set.nextMinAutoOptionId: ${t}`), + this.store.update(e, ({abrStatus: e})=>{ + e.nextMinAutoOptionId = t + } + ) + } + setHighBWTrigger(e, t) { + Co(`root.set.setHighBWTrigger: ${t}`), + this.store.update(e, ({abrStatus: e})=>{ + e.highBWTrigger = t + } + ) + } + setFragLoadSlow(e, t) { + Co(`root.set.setFragLoadSlow ${e} ${JSON.stringify(t)}`), + this.store.update(e, ({abrStatus: e})=>{ + e.fragDownloadSlow = t.fragDownloadSlow, + e.fragDownloadTooSlow = t.fragDownloadTooSlow + } + ) + } + pickMediaOptionTupleByPersistentId(e, t, i, r=!1, n=!1) { + var s = e.enabledMediaOptionIdByType(ul.Variant) + , s = e.variantMediaOptionById(s); + let a, o; + if (t === ul.AltAudio) { + const t = e.enabledAlternateMediaOptionByType(ul.Subtitle); + o = null == t ? void 0 : t.persistentID, + a = i + } else { + const t = e.enabledAlternateMediaOptionByType(ul.AltAudio); + a = null == t ? void 0 : t.persistentID, + o = i + } + const d = e.getEnabledMediaOptionMask(); + return d[t] = !!(ne(i) && 0 <= i), + s ? this.getBestMediaOptionTupleFromVariantAndPersistentId(e, s, a, o, d, void 0, r, n, !1) : [Ol, Ol, Ol] + } + getFallbackMediaOptionTupleFromMediaOptionId(e, t, i, r, n=!1, s=!1, a=!1) { + var o = r ? [r] : [i] + , d = e.enabledMediaOptionIdByType(ul.Variant) + , r = e.variantMediaOptionById(d) + , d = t === ul.AltAudio ? e.alternateMediaOptionById(ul.AltAudio, i) : e.enabledAlternateMediaOptionByType(ul.AltAudio) + , d = null == d ? void 0 : d.persistentID + , i = t === ul.Subtitle ? e.alternateMediaOptionById(ul.Subtitle, i) : e.enabledAlternateMediaOptionByType(ul.Subtitle) + , i = null == i ? void 0 : i.persistentID; + return r ? this.getBestMediaOptionTupleFromVariantAndPersistentId(e, r, d, i, void 0, o, n, s, a) : [Ol, Ol, Ol] + } + hasFallbackMediaOptionTuple(e, t, i, r) { + var n = e.mediaOptionListQueries[t].mediaOptionFromId(i); + return e.isValidMediaOptionTuple(this.getFallbackMediaOptionTupleFromMediaOptionId(e, t, i, n.backingMediaOptionId, !1, r)) + } + setLegacyAlternateMediaOption(e, t, i, r, n) { + var s = e.enabledMediaOptionIdByType(ul.Variant) + , s = e.variantMediaOptionById(s) + , s = e.getLegacyMatchingAlternateWithPersistentId(i, r, s); + s ? this.setEnabledMediaOptionByType(t, i, s, !0, n) : this.logger.warn(`${Cl[i]} can't find matching mediaOption for persistent id ${r}`) + } + setEnabledMediaOptionTupleWithMatchedGroups(t, i, e, r) { + const n = ky(t) + , s = this.pickMediaOptionTupleByPersistentId(n, i, e); + if (!n.isValidMediaOptionTuple(s)) + return this.setLegacyAlternateMediaOption(n, t, i, e, r); + sd(()=>{ + this.setEnabledMediaOptionByType(t, i, s[i], !0, r), + s[ul.Variant].mediaOptionId !== n.enabledMediaOptionIdByType(ul.Variant) && this.setPreferredHost(t, gl(s[ul.Variant].url)), + this.setEnabledMediaOptionByType(t, ul.Variant, s[ul.Variant]); + var e = i === ul.AltAudio ? ul.Subtitle : ul.AltAudio; + s[e].mediaOptionId !== n.enabledMediaOptionIdByType(e) && this.setEnabledMediaOptionByType(t, e, s[e], !1) + } + ) + } + canSwitchToSDR(e, t, i, r=!1) { + var n = e.mediaOptionListQueries[ul.Variant].mediaOptionFromId(t) + , r = this.getFallbackMediaOptionTupleFromMediaOptionId(e, ul.Variant, t, n.backingMediaOptionId, !0, i, r); + return e.isValidMediaOptionTuple(r) + } + getBestMediaOptionTupleFromVariantAndPersistentId(t, e, i, r, n, s, a, o, d) { + var l, u = t.mediaOptionListQueries[ul.Variant].listFallbackVariants(e.mediaOptionId, a, o, d, s); + let c = [Ol, Ol, Ol]; + for (let e = 0; e < u.length; ++e) { + const a = u[e]; + if (l = t.matchAlternates(a, i, r, s), + t.isValidMediaOptionTuple([a, ...l], n)) { + c = [a, ...l]; + break + } + } + return c + } + } + const Ay = new class extends pd { + constructor() { + super({}, { + name: "root-playlist-store", + idKey: "itemId", + producerFn: vc + }) + } + akitaPreAddEntity(e) { + return null == e.errorsByType ? Object.assign(Object.assign({}, e), { + errorsByType: [{ + timeouts: { + load: 0, + append: 0, + key: 0 + } + }, { + timeouts: { + load: 0, + append: 0, + key: 0 + } + }, { + timeouts: { + load: 0, + append: 0, + key: 0 + } + }] + }) : e + } + } + ; + new Od(Ay); + let Oy = null; + function ky(e) { + return new Ey(Ay,e) + } + const Cy = (n,e,t,s,i)=>{ + const {rootMediaOptionsTuple: r, sessionKeys: a} = n + , o = Array.from(r[ul.Variant]) + , d = Array.from(r[ul.AltAudio]); + let l = !1 + , u = !1 + , c = o.map(e=>(l = l || Boolean(e.videoCodec), + u = u || Boolean(e.audioCodec) || Boolean(e.audioGroupId), + e)); + return l && u && (c = c.filter(({videoCodec: e})=>Boolean(e))), + Sy(o, d, a, e, t, i).pipe(ur(({hdrMediaOptions: e, sdrMediaOptions: t})=>{ + var i = e.concat(t) + , r = 0 < e.length; + return e.concat(t), + function(e, t, i, r) { + var {itemId: n, itemStartOffset: s, rootMediaOptionsTuple: a, audioMediaSelectionGroup: o, subtitleMediaSelectionGroup: d} = e + , l = Array.from(a[ul.AltAudio]) + , u = Array.from(a[ul.Subtitle]) + , c = t.every(e=>ne(e.score)) + , h = t.some(e=>Dm(!0, e)) + , p = function(e, t) { + const i = [...e]; + return t ? i.sort((e,t)=>e.score - t.score || t.bitrate - e.bitrate) : i.sort((e,t)=>e.bitrate - t.bitrate), + i + }(t, c) + , f = e.baseUrl + , t = null === (a = e.contentSteeringOption) || void 0 === a ? void 0 : a.initPathwayID + , a = e.sessionData; + return { + itemId: n, + baseUrl: f, + mediaOptionListTuple: [{ + mediaOptions: p, + hasHdrLevels: i, + hasIframeLevels: h, + hasScore: c, + preferHDR: r, + compatibleIds: null, + penaltyBoxQueue: [], + removed: [], + currentPathwayID: t + }, { + mediaOptions: l, + compatibleIds: null, + penaltyBoxQueue: [], + removed: [] + }, { + mediaOptions: u, + penaltyBoxQueue: [], + removed: [] + }], + audioMediaSelectionGroup: o, + subtitleMediaSelectionGroup: d, + enabledMediaOptionKeys: [Ol, Ol, Ol], + mediaOptionSwitchContexts: [null, null, null], + anchorTime: 0, + discoSeqNum: NaN, + pendingSeek: void 0, + itemStartOffset: s, + initPtsRecord: {}, + contentSteeringOption: e.contentSteeringOption, + masterVariableList: e.masterVariableList, + loadStats: e.stats, + isMediaPlaylist: e.isMediaPlaylist, + abrStatus: { + fragDownloadSlow: !1, + fragDownloadTooSlow: !1, + nextMinAutoOptionId: Ol.mediaOptionId, + nextMaxAutoOptionId: Ol.mediaOptionId, + highBWTrigger: NaN + }, + sessionData: a + } + }(n, i, r, s) + } + )) + } + ; + function Dy(e, t, i, r, n, s, a) { + var o, d, l, u, c, h, p, f = e.mediaOptionListTuple[ul.Variant], m = wm(f.mediaOptions, xm.kAllowFilters, Object.assign(Object.assign({}, f), { + compatibleIds: null + })), g = Am(f.preferredHost, m); + return { + firstVariant: (o = g, + e = Tg, + f = f.hasScore, + t = t, + i = i, + r = r, + n = n, + s = s, + a = a, + !o || o.length < 1 || o.every(e=>e.iframes) ? void t.warn("no non-iframe media option found") : ((o = f ? Eg(o, i, r, n, s, a) : (d = e, + l = i, + u = r, + c = n, + h = s, + p = a, + o.reduce((e,t)=>{ + if (t.iframes) + return e; + let i = e; + const r = function(e, t, i, r, n, s, a) { + var o, d, l = (o = e.bitrate, + u = e.height, + (d = (e,t,i)=>(e - t) * (e - i) <= 0)(o, t.minValidBitrate, t.maxValidBitrate) && d(u, t.minValidHeight, t.maxValidHeight) ? ll.VALID : ll.INVALID), o = "PQ" === (c = e.videoRange) ? ol.PQ : "HLG" === c ? ol.HLG : "SDR" === c ? ol.SDR : ol.UNKNOWN, {videoCodecRank: u, audioCodecRank: c} = { + videoCodecRank: $p((d = e).videoCodec), + audioCodecRank: Kp(d.audioCodec) + }, d = e.bitrate < t.maxPreferredBitrate ? ll.VALID : ll.INVALID, t = e.audioChannelCount || 1, a = i && r && n && s && !Ig(e, i, r, n, s, a) ? ll.INVALID : ll.VALID; + return new Hp(l,o,u,t,c,a,d,e.height) + }(t, d, l, u, c, h, p); + return (!e || r.isGreaterThan(e.bestRank) || r.isEqualTo(e.bestRank) && t.bitrate > e.selected.bitrate) && (i = { + selected: t, + bestRank: r + }), + i + } + , null).selected)) || t.warn("no valid first media option found"), + o)), + filteredVariants: m, + preferredVariants: g + } + } + function My(e, t, i) { + if ((null == t ? void 0 : t.mediaType) === pl.CLOSEDCAPTION) { + const r = Ty.pairForcedSubtitleMediaOptionWithClosedCaptionInList(e.subtitleGroupId, t, i); + if (r) + return t = Object.assign(Object.assign({}, t), { + url: r.url, + backingMediaOptionId: r.mediaOptionId + }), + i.map(e=>e.mediaOptionId === t.mediaOptionId ? t : e) + } + return i + } + function Py(e, t, i, r, n, s, a, o) { + var d; + const l = e.itemId + , u = e.mediaOptionListTuple[ul.Variant] + , c = e.mediaOptionListTuple[ul.AltAudio] + , h = e.mediaOptionListTuple[ul.Subtitle] + , p = wm(c.mediaOptions, Ty.kAllowFilters, c) + , f = wm(h.mediaOptions, Ty.kAllowFilters, h); + let {firstVariant: m, filteredVariants: g} = Dy(e, i, r, n, s, a, o); + if (!m) { + const U = u.preferHDR; + u.preferHDR = !U && u.hasHdrLevels, + u.preferHDR !== U && (i.warn(`No valid first variant found, toggling hdr preference=${U}->${u.preferHDR}`), + {firstVariant: m, filteredVariants: g} = Dy(e, i, r, n, s, a, o)) + } + if (!m) + throw new V(!0,"No valid first variant found",$.NoValidAlternates); + const y = gl(m.url) + , v = { + itemId: l, + mediaOptionId: null !== (o = null == m ? void 0 : m.mediaOptionId) && void 0 !== o ? o : null + } + , S = null != p && p.length ? null === (o = ((i,r,e,n)=>{ + if (e) { + let t; + return t = ne(i) ? e.MediaSelectionGroupOptions.find(function(e) { + return e.MediaSelectionOptionsPersistentID === i + }) : e.MediaSelectionGroupOptions.find(function(e) { + return e.MediaSelectionOptionsIsDefault + }), + t = t || e.MediaSelectionGroupOptions[0], + n.find(e=>(!r || e.groupId === r) && e.persistentID === (null == t ? void 0 : t.MediaSelectionOptionsPersistentID)) + } + } + )(null == t ? void 0 : t.audioPersistentId, m.audioGroupId, e.audioMediaSelectionGroup, p)) || void 0 === o ? void 0 : o.mediaOptionId : null + , b = S ? { + itemId: l, + mediaOptionId: S + } : Ol + , T = ((i,r,n,s,a,o)=>{ + if (s) { + let t, e; + return t = ne(i) ? s.MediaSelectionGroupOptions.find(function(e) { + return e.MediaSelectionOptionsPersistentID === i + }) : s.MediaSelectionGroupOptions.find(function(e) { + return e.MediaSelectionOptionsIsDefault + }), + t && (e = a.find(e=>e.mediaType === pl.CLOSEDCAPTION ? (!r || e.groupId === r) && e.persistentID === t.MediaSelectionOptionsPersistentID : e.mediaType === pl.SUBTITLE ? (!n || e.groupId === n) && e.persistentID === t.MediaSelectionOptionsPersistentID : void o.warn(Iy, `subtitle media option has unknown type ${e.mediaType}`))), + e + } + } + )(null == t ? void 0 : t.subtitlePersistentId, m.closedcaption, m.subtitleGroupId, e.subtitleMediaSelectionGroup, f, i) + , E = null != f && f.length ? null == T ? void 0 : T.mediaOptionId : null + , I = E ? { + itemId: l, + mediaOptionId: E, + mediaOptionType: ul.Subtitle + } : Ol + , {mediaOptions: w, audioGroups: A, subtitleGroups: O} = (t = g, + d = m, + t.reduce((e,t)=>{ + if (((e,t)=>{ + let i = !0; + e.videoCodec && t.videoCodec && (i = Se.isCompatibleVideoCodec(e.videoCodec, t.videoCodec)); + let r = !1; + e.videoRange && t.videoRange ? r = e.videoRange == t.videoRange : e.videoRange || t.videoRange || (r = !0); + let n = !0; + return e.audioCodec && t.audioCodec && (n = Se.isCompatibleAudioCodec(e.audioCodec, t.audioCodec)), + i && r && n + } + )(d, t)) { + const d = t.audioGroupId; + d && e.audioGroups.add(d), + e.mediaOptions.add(t) + } + var i = t.subtitleGroupId; + i && e.subtitleGroups.add(i); + t = t.closedcaption; + return t && e.closedCaptionGroups.add(t), + e + } + , { + mediaOptions: new Set, + audioGroups: new Set, + subtitleGroups: new Set, + closedCaptionGroups: new Set + })) + , k = Array.from(w).map(e=>e.mediaOptionId) + , C = m.pathwayID + , D = Object.assign(Object.assign({}, u), { + compatibleIds: k, + preferredHost: y, + currentPathwayID: C + }) + , M = [] + , P = c.mediaOptions.reduce((e,t)=>(A.has(t.groupId) && (e.persistentIds.add(t.persistentID), + M.push(t.mediaOptionId), + e.filteredAudioMediaOptions.push(t), + e.altAudio || (e.altAudio = !!t.url)), + e), { + filteredAudioMediaOptions: [], + persistentIds: new Set, + altAudio: !1 + }) + , x = Object.assign(Object.assign({}, c), { + compatibleIds: M + }); + let R = e.audioMediaSelectionGroup; + const L = null == R ? void 0 : R.MediaSelectionGroupOptions; + if (L) { + const e = L.reduce((e,t)=>(P.persistentIds.has(t.MediaSelectionOptionsPersistentID) && e.push(t), + e), new Array); + R = Object.assign(Object.assign({}, R), { + MediaSelectionGroupOptions: e + }) + } + h.mediaOptions = My(m, T, h.mediaOptions); + const _ = h.mediaOptions.reduce((e,t)=>(O.has(t.groupId) && (e.persistentIds.add(t.persistentID), + e.filteredSubtitleMediaOptions.push(t)), + e), { + filteredSubtitleMediaOptions: [], + persistentIds: new Set + }); + let N = e.subtitleMediaSelectionGroup; + const F = null == N ? void 0 : N.MediaSelectionGroupOptions; + if (F) { + const e = F.reduce((e,t)=>(_.persistentIds.has(t.MediaSelectionOptionsPersistentID) && e.push(t), + e), new Array); + N = Object.assign(Object.assign({}, N), { + MediaSelectionGroupOptions: e + }) + } + i = [D, x, h]; + let B = new Map; + Ym().useHighestVideoCodecPrivate && (B = null == D ? void 0 : D.mediaOptions.reduce((e,t)=>{ + const i = t.videoCodecList; + if (i) + for (const t of i) { + const i = Vp(t) + , r = e.get(i); + Se.isHigherCodecByFamily(r, t) && e.set(i, t) + } + return e + } + , B)), + B.size && B.forEach((e,t)=>{} + ); + t = { + fragDownloadSlow: !1, + fragDownloadTooSlow: !1, + nextMinAutoOptionId: Ol.mediaOptionId, + nextMaxAutoOptionId: Ol.mediaOptionId, + highBWTrigger: Lg(v.mediaOptionId, D.mediaOptions) + }; + return Object.assign(Object.assign({}, e), { + enabledMediaOptionKeys: [v, b, I], + mediaOptionListTuple: i, + audioMediaSelectionGroup: R, + abrStatus: t, + highestVideoCodec: B + }) + } + const xy = (o,d,l,u,c,h,p)=>e=>e.pipe(Ql.tag("retrieveRootMediaOptions.input"), Ra(t=>{ + var e; + if (!t) + return Ti; + const {itemId: i, platformInfo: r} = t + , n = ky(i) + , s = d["logger"]; + if (n.hasEntity(i)) + return Bi(n); + Ay.setLoading(!0); + const a = performance.now(); + return function(e, t, u, c, i) { + const {itemId: h, url: p, itemStartOffset: f} = e + , r = xc(e, t); + return bm({ + url: p, + onProgress: { + getData: !0, + cb: dy + }, + xhrSetup: c.xhrSetup + }, r, i).pipe(ur(({responseText: e, stats: t})=>{ + var i = c["keySystemPreference"]; + if (Sm.isMediaPlaylist(e)) { + const c = "media-pl-" + Jd() + , d = Sm.parseMediaOptionPlaylist(e, p, !0, i, {}, h, c, ul.Variant, u, f); + Lc(d.mediaOptionDetails); + var r = { + itemId: h, + mediaOptionId: c, + mediaOptionType: ul.Variant, + url: p, + bandwidth: 0, + bitrate: 0, + iframes: d.mediaOptionDetails.iframesOnly, + pathwayID: "." + }; + return { + itemId: h, + itemStartOffset: f, + rootMediaOptionsTuple: [[r], [], []], + stats: t, + baseUrl: p, + initialDetails: d.mediaOptionDetails, + isMediaPlaylist: !0 + } + } + { + const u = Sm.parseSessionData(e, p) + , c = Sm.parseSessionKeys(e, p, i) + , l = Sm.parseRootPlaylist(h, e, p, !0); + if (l.playlistParsingError) + throw l.playlistParsingError; + var {variantMediaOptions: n, contentSteeringOption: s, masterVariableList: a} = l + , o = Sm.parseRootPlaylistAlternateMediaOptions(h, e, p, l.variantMediaOptions, !0, a); + if (o.playlistParsingError) + throw o.playlistParsingError; + var {audioAlternateOptions: r, subtitleAlternateOptions: i, audioMediaSelectionGroup: e, subtitleMediaSelectionGroup: o} = o.alternateMediaInfo; + return { + itemId: h, + itemStartOffset: f, + rootMediaOptionsTuple: [n, r, i], + stats: t, + baseUrl: p, + audioMediaSelectionGroup: e, + subtitleMediaSelectionGroup: o, + contentSteeringOption: s, + sessionData: u, + sessionKeys: c, + masterVariableList: a + } + } + } + ), e=>e.pipe(Un(e=>{ + if (e instanceof ou) + throw new ru(!1,"Timeout",0,$.ManifestTimeoutError,!0); + if (e instanceof tu) + throw new ru(!1,e.message,e.code,{ + code: e.code, + text: "Manifest network error" + },!1); + throw e + } + ))) + }(t, o, s, l, null === (e = null === (e = Xm()) || void 0 === e ? void 0 : e.getQuery()) || void 0 === e ? void 0 : e.extendMaxTTFB).pipe(Ja(e=>p.triggerManifestLoaded(e)), Ja(({initialDetails: e, stats: t})=>{ + e && (e = e, + t = t, + hg().archiveMediaOptionDetails(e, t, !0)) + } + ), So(u.displaySupportsHdr$), Ra(([e,t])=>Cy(e, r, l, t, s)), ur(e=>(d.rootPlaylistEntity = function(e, t, i, r, n, s) { + const {itemId: a, initialSeekTime: o} = e + , d = Uf(a) + , l = n.enableAdaptiveStartup ? d.getBandwidthEstimate(n, e.serviceName) : void 0 + , u = n.enableAdaptiveStartup ? d.getPlaylistEstimate(n, e.serviceName) : void 0 + , c = n.enableAdaptiveStartup ? d.getFragEstimate(n, e.serviceName) : void 0 + , h = n.enableAdaptiveStartup ? d.getBufferEstimate(n, e.serviceName) : void 0 + , p = n.targetStartupMs - (performance.now() - r) + , f = n.enableAdaptiveStartup ? { + targetDuration: c.maxDurationSec || n.defaultTargetDuration, + targetStartupMs: p + } : void 0 + , m = Py(t, i, s, l, f, u, c, h); + return m.pendingSeek = o, + m + }(t, e, c, a, l, s), + n)), jm(i, null, xc(t, o), 0, !1, n, d, h), $s(()=>{ + Ay.setLoading(!1) + } + )) + } + ), Ql.tag("retrieveRootMediaOptions.emit")); + class Ry { + } + Ry.PlayEnded = 6101, + Ry.Periodic = 6110, + Ry.PlayStalled = 6103, + Ry.KeySessionComplete = 6104, + Ry.PlayLikelyToKeepUp = 6105, + Ry.PlayRateChanged = 6106, + Ry.PlayError = 6107, + Ry.MediaEngineStalled = 6108, + Ry.SwitchComplete = 6109, + Ry.VariantEnded = 6111, + Ry.NwError = 6202; + const Ly = { + avc1: 1, + avc3: 1, + hvc1: { + SDR: 2, + HLG: 10, + PQ: 11 + }, + hev1: { + SDR: 2, + HLG: 10, + PQ: 11 + }, + vp09: { + SDR: 3, + HLG: 14, + PQ: 13 + }, + dvh1: { + PQ: 12 + } + }; + class _y { + constructor(e, t) { + this.query = e, + this.logger = t + } + setReportingAgent(e) { + this.reportingAgent = e + } + sendPlayEnded(e) { + var t = Ry.PlayEnded; + this.fillAndFire(t, this.query.playEnded(e)) + } + sendPlayStalled(e) { + var t = Ry.PlayStalled; + this.fillAndFire(t, this.query.playStalled(e)) + } + sendMediaEngineStalled(e) { + var t = Ry.MediaEngineStalled; + this.fillAndFire(t, this.query.mediaEngineStalled(e)) + } + sendKeySessionComplete(e) { + var t = Ry.KeySessionComplete; + this.fillAndFire(t, this.query.keySessionComplete(e)) + } + sendPlayLikelyToKeepUp(e) { + var t = Ry.PlayLikelyToKeepUp; + this.fillAndFire(t, this.query.playLikelyToKeepUp(e)) + } + sendPlayRateChange(e) { + var t = Ry.PlayRateChanged; + this.fillAndFire(t, this.query.playRateChanged(e)) + } + sendSwitchComplete(e) { + var t = Ry.SwitchComplete; + this.fillAndFire(t, this.query.switchComplete(e)) + } + sendVariantEnded(e) { + var t = Ry.VariantEnded; + this.fillAndFire(t, this.query.variantEnded(e)) + } + sendPlayError(e) { + var t = Ry.PlayError; + this.fillAndFire(t, this.query.playError(e)) + } + sendNwError(e) { + var t = Ry.NwError; + this.fillAndFire(t, this.query.nwError(e)) + } + sendPeriodic(e) { + var t = Ry.Periodic; + this.fillAndFire(t, this.query.periodic(e)) + } + fillAndFire(e, t) { + var r = e === Ry.PlayEnded || e === Ry.Periodic ? 1 : 0; + if (this.reportingAgent) { + let i = {}; + Object.entries(t).forEach(([e,t])=>{ + "object" == typeof (t = ne(t) ? Number(Number(t).toFixed(2)) : t) ? "ServerInfo" === e && Object.entries(t).forEach(([e,t])=>{ + i[e] = t + } + ) : i[e] = t + } + ), + i = JSON.parse(JSON.stringify(i)); + try { + this.reportingAgent.issueReportingEvent(e, i, r) + } catch (e) {} + } + } + } + class Ny extends Od { + constructor(e, t) { + super(e), + this.logger = t + } + get activeEntity() { + return this.getActive() + } + entity(e) { + return this.getEntity(e) + } + playEnded(e) { + return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.playEndedRecord + } + periodic(e) { + return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.periodicRecord + } + playStalled(e) { + return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.playStalledRecord + } + mediaEngineStalled(e) { + return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.mediaEngineStalledRecord + } + keySessionComplete(e) { + return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.keySessionCompleteRecord + } + playLikelyToKeepUp(e) { + return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.playLikelyToKeepUpRecord + } + playRateChanged(e) { + return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.playRateChangedRecord + } + switchComplete(e) { + return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.switchCompleteRecord + } + variantEnded(e) { + return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.variantEndedRecord + } + playError(e) { + return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.playErrorRecord + } + nwError(e) { + return null === (e = this.getEntity(e)) || void 0 === e ? void 0 : e.nwErrorRecord + } + } + class Fy extends pd { + constructor(e) { + super({}, { + name: "rtc-store", + idKey: "itemId", + producerFn: vc, + resettable: !0 + }), + this.logger = e + } + createEntity(e) { + e = { + itemId: e, + sessionControlRecord: { + state: "RTC_STATE_INIT", + rate: 0, + oldRate: 0, + eventStartTime: Date.now(), + sessionStartTime: Date.now(), + lastLikelyToKeepUpTime: Date.now(), + lastPeriodicTime: Date.now(), + playLikelyToKeepUpEventCounter: 1, + periodicEventCounter: 1, + activeKeySessions: {}, + intervalVariantList: {}, + sessionVariantList: {} + }, + playEndedRecord: {}, + periodicRecord: {}, + playStalledRecord: {}, + keySessionCompleteRecord: {}, + playLikelyToKeepUpRecord: {}, + playRateChangedRecord: {}, + playErrorRecord: {}, + mediaEngineStalledRecord: {}, + switchCompleteRecord: {}, + variantEndedRecord: {}, + nwErrorRecord: {} + }; + this.add(e) + } + updateEnded(e) { + this._prepareEventPlayEnded(e) + } + updatePeriodic(e, t) { + this._prepareEventPeriodic(e, { + isFinal: t + }) + } + updateBufferStalled(e, t) { + this.update(e, ({sessionControlRecord: e, variantEndedRecord: t, periodicRecord: i, playEndedRecord: r})=>{ + e.rate = 0, + t.StallCount = (t.StallCount || 0) + 1, + i.StallCount = (i.StallCount || 0) + 1, + r.StallCount = (r.StallCount || 0) + 1 + } + ), + this._prepareEventPlayStalled(e, t) + } + updateSegmentKeyLoaded(e, r) { + this.update(e, ({sessionControlRecord: e})=>{ + const t = {} + , i = r.timestamp; + t.keyFormat = "identity", + t.keyDeliveryTime = r.adt, + t.currentMediaTime = r.currentTime, + "RTC_STATE_INIT" === e.state && (t.keyInitTime = i - e.sessionStartTime), + e.activeKeySessions[r.keyuri] = t + } + ), + this._prepareEventKeySessionComplete(e, r) + } + updateLicenseResponseProcessed(e, i) { + this.update(e, ({sessionControlRecord: e})=>{ + const t = e.activeKeySessions[i.keyuri]; + t.licenseResponseProcessTime = i.timestamp - t.licenseResponseSubmitTime, + e.lastKeyDeliveryTime = t.keyDeliveryTime = i.timestamp - t.licenseChallengeStartTime, + t.currentMediaTime = i.currentTime, + e.finishedKeyUri = i.keyuri + } + ), + this._prepareEventKeySessionComplete(e, i) + } + updateLicenseChallengeError(e, i) { + this.update(e, ({sessionControlRecord: e})=>{ + const t = e.activeKeySessions[i.keyuri]; + e.lastKeyErrorType = t.keyErrorType = "licenseChallengeError", + e.finishedKeyUri = i.keyuri + } + ), + this._prepareEventKeySessionComplete(e, i) + } + updateLicenseResponseError(e, i) { + this.update(e, ({sessionControlRecord: e})=>{ + const t = e.activeKeySessions[i.keyuri]; + e.lastKeyErrorType = t.keyErrorType = "licenseResponseError", + e.finishedKeyUri = i.keyuri + } + ), + this._prepareEventKeySessionComplete(e, i) + } + updateKeyAborted(e, t) { + this.update(e, ({sessionControlRecord: e})=>{ + e.activeKeySessions[t.keyuri].keyErrorType = "keyAborted", + e.finishedKeyUri = t.keyuri + } + ), + this._prepareEventKeySessionComplete(e, t) + } + updateCanPlay(e, t) { + this.update(e, ({})=>{} + ), + this._prepareEventPlayLikelyToKeepUp(e, t) + } + updateRateChanged(e, t) { + this.update(e, ({sessionControlRecord: e})=>{ + e.rate = 100 * t.rate, + 0 < t.rate && 0 === e.oldRate && (e.playInfo || (e.playInfo = []), + e.playInfo.push({ + latency: t.latency + }), + e.curLevelUrl || (e.curLevelUrl = t.url)) + } + ), + this._prepareEventPlayRateChanged(e, t) + } + updateMediaError(e, r) { + this.update(e, ({sessionControlRecord: e, periodicRecord: t, playEndedRecord: i})=>{ + t.PlayerErrCount = (t.PlayerErrCount || 0) + 1, + i.PlayerErrCount = (i.PlayerErrCount || 0) + 1, + r.fatal && (e.rate = 0, + t.FatalPlayerErrCount = (t.FatalPlayerErrCount || 0) + 1, + i.FatalPlayerErrCount = (i.FatalPlayerErrCount || 0) + 1, + i.ErrCode = r.details, + i.ErrReason = r.code, + i.ErrIsFatal = !0, + i.ErrDomain = "mediaError") + } + ), + r.fatal ? this._prepareEventPlayError(e, r) : this.update(e, ({sessionControlRecord: e})=>{ + var t = r.details + "/" + r.code; + e.nonFatalPlayErrList[t] = (e.nonFatalPlayErrList[t] || 0) + 1 + } + ) + } + updateMediaElementError(e, t) { + let i; + try { + i = JSON.parse(t.message) + } catch (e) { + this.logger.warn(`message is not JSON, ignoring; ${t.message}`) + } + var r = i ? parseInt(i.ErrReason) : null + , n = i ? parseInt(i.ErrDetail) : null; + this._prepareEventPlayError(e, { + domain: "mediaElementError", + mediaElemCode: t.code, + mediaElemReason: r, + mediaElemDetail: n, + code: null, + details: null, + fatal: null + }) + } + updateMediaEngineStalled(e, t) { + this.update(e, ({sessionControlRecord: e, variantEndedRecord: t, periodicRecord: i, playEndedRecord: r})=>{ + e.rate = 0, + t.MediaEngineStallCount = (t.MediaEngineStallCount || 0) + 1, + i.MediaEngineStallCount = (i.MediaEngineStallCount || 0) + 1, + r.MediaEngineStallCount = (r.MediaEngineStallCount || 0) + 1 + } + ), + this._prepareEventMediaEngineStalled(e, t) + } + updateLevelSwitched(e, l) { + this.update(e, ({sessionControlRecord: e, switchCompleteRecord: t, periodicRecord: i, playEndedRecord: r})=>{ + i.SwCnt = (i.SwCnt || 0) + 1, + r.SwCnt = (r.SwCnt || 0) + 1; + var n = Date.now() + , s = e.curLevelUrl + , a = l.url + , i = this._getVariantInfo(s, e) + , r = this._getVariantInfo(a, e); + let o, d = !1; + s && (o = r.bandwidth < i.bandwidth ? "Down" : "Up", + d = r.iframes), + t.BadSw = this._isBadSw(o, e.lastSwitchDir || o, d, e.lastLevelIsIframe || d, n, e.lastSwitchTime || n, l.isSeeking), + e.lastSwitchDir = o, + e.lastSwitchTime = n, + e.lastLevelIsIframe = d, + e.curLevelUrl = a, + e.variantStartTimeMedia = l.currentTime + } + ), + this._prepareEventSwitchComplete(e, l) + } + updateLevelLoadError(e, o) { + this.update(e, ({sessionControlRecord: e, switchCompleteRecord: t, periodicRecord: i, playEndedRecord: r})=>{ + var n = Date.now(); + let s, a = !1; + if (e.curLevelUrl) { + const t = this._getVariantInfo(e.curLevelUrl, e) + , i = this._getVariantInfo(o.url, e); + s = i.bandwidth < t.bandwidth ? "Down" : "Up", + a = i.iframes + } + i.SwCnt = (i.SwCnt || 0) + 1, + r.SwCnt = (r.SwCnt || 0) + 1, + t.BadSw = this._isBadSw(s, e.lastSwitchDir || s, a, e.lastLevelIsIframe || a, n, e.lastSwitchTime || n, o.isSeeking), + t.SwFail = !0 + } + ), + this._prepareEventSwitchComplete(e, o) + } + updateVariantEnd(e, t) { + this._prepareEventVariantEnded(e, t) + } + updateNwError(e, r) { + this.update(e, ({sessionControlRecord: e, periodicRecord: t, playEndedRecord: i})=>{ + t.NwErrCount = (t.NwErrCount || 0) + 1, + i.NwErrCount = (i.NwErrCount || 0) + 1, + r.fatal && (e.rate = 0, + t.FatalNwErrCount = (t.FatalNwErrCount || 0) + 1, + i.FatalNwErrCount = (i.FatalNwErrCount || 0) + 1, + i.ErrCode = r.details, + i.ErrReason = r.code, + i.ErrIsFatal = !0, + i.ErrDomain = "networkError") + } + ), + r.fatal ? this._prepareEventNwError(e, r) : this.update(e, ({sessionControlRecord: e})=>{ + var t = r.details + "/" + r.code; + e.nonFatalNwErrList[t] = (e.nonFatalNwErrList[t] || 0) + 1 + } + ) + } + finalize(e, t) { + switch (t) { + case Ry.PlayEnded: + this.update(e, ({sessionControlRecord: e})=>{ + e.state = "RTC_STATE_STOP", + e.oldRate = 0 + } + ), + this.update(e, e=>{ + e.playEndedRecord = {} + } + ); + break; + case Ry.Periodic: + this.update(e, ({sessionControlRecord: t})=>{ + t.lastPeriodicTime = Date.now(), + t.periodicEventCounter += 1, + Object.keys(t.intervalVariantList).forEach(e=>{ + t.intervalVariantList[e].playTime = 0 + } + ) + } + ), + this.update(e, e=>{ + e.periodicRecord = {} + } + ); + break; + case Ry.PlayStalled: + this.update(e, ({sessionControlRecord: e})=>{ + e.state = "RTC_STATE_STALL", + e.oldRate = 0 + } + ), + this.update(e, e=>{ + e.playStalledRecord = {} + } + ); + break; + case Ry.KeySessionComplete: + this.update(e, ({sessionControlRecord: e})=>{ + delete e.activeKeySessions[e.finishedKeyUri] + } + ), + this.update(e, e=>{ + e.keySessionCompleteRecord = {} + } + ); + break; + case Ry.PlayLikelyToKeepUp: + this.update(e, ({sessionControlRecord: e})=>{ + "RTC_STATE_PLAY" !== e.state && (e.state = "RTC_STATE_CANPLAY", + e.lastLikelyToKeepUpTime = Date.now(), + e.playLikelyToKeepUpEventCounter += 1) + } + ), + this.update(e, e=>{ + e.playLikelyToKeepUpRecord = {} + } + ); + break; + case Ry.PlayRateChanged: + this.update(e, ({sessionControlRecord: e, playEndedRecord: t, playStalledRecord: i, mediaEngineStalledRecord: r, playErrorRecord: n, nwErrorRecord: s})=>{ + 0 !== e.rate ? (e.state = "RTC_STATE_PLAY", + delete t.LastStall, + delete t.LastMediaEngineStall, + delete t.LastPause, + delete n.LastPause, + delete s.LastPause) : (e.state = "RTC_STATE_PAUSE", + delete i.LastResume, + delete r.LastResume, + delete n.LastResume, + delete s.LastResume), + e.oldRate = e.rate + } + ), + this.update(e, e=>{ + e.playRateChangedRecord = {} + } + ); + break; + case Ry.PlayError: + this.update(e, ({sessionControlRecord: e})=>{ + e.state = "RTC_STATE_PLAYERROR" + } + ), + this.update(e, e=>{ + e.playErrorRecord = {} + } + ); + break; + case Ry.MediaEngineStalled: + this.update(e, ({sessionControlRecord: e})=>{ + e.state = "RTC_STATE_MEDIAENGINESTALL", + e.oldRate = 0 + } + ), + this.update(e, e=>{ + e.mediaEngineStalledRecord = {} + } + ); + break; + case Ry.SwitchComplete: + this.update(e, e=>{ + e.switchCompleteRecord = {}, + e.sessionControlRecord.prevLevelUrl = e.sessionControlRecord.curLevelUrl + } + ); + break; + case Ry.VariantEnded: + this.update(e, ({sessionControlRecord: e})=>{ + e.decodedFramesForVariant = 0, + e.decodedFramesForVariantSampleCount = 0 + } + ), + this.update(e, e=>{ + e.variantEndedRecord = {} + } + ); + break; + case Ry.NwError: + this.update(e, ({sessionControlRecord: e})=>{ + e.state = "RTC_STATE_NWERROR" + } + ), + this.update(e, e=>{ + e.nwErrorRecord = {} + } + ) + } + this.update(e, ({sessionControlRecord: e})=>{ + e.eventStartTime = Date.now() + } + ) + } + updatePlaybackInfo(e, s) { + this.update(e, ({sessionControlRecord: e, periodicRecord: t, playEndedRecord: i})=>{ + s.droppedVideoFrames < e.droppedVideoFrames && (e.droppedVideoFrames = 0), + s.decodedFrameCount < e.decodedFrameCount && (e.decodedFrameCount = 0); + var r = s.droppedVideoFrames - (e.droppedVideoFrames || 0) + , n = s.decodedFrameCount - (e.decodedFrameCount || 0); + e.droppedVideoFrames = s.droppedVideoFrames, + e.decodedFrameCount = s.decodedFrameCount, + e.decodedFramesForVariant += n, + e.decodedFramesForVariantSampleCount += 1, + r && (3 <= r ? (t.GroupViFrDr = (t.GroupViFrDr || 0) + r, + t.GroupViFrDrEvtCount = (t.GroupViFrDrEvtCount || 0) + 1, + i.GroupViFrDr = (i.GroupViFrDr || 0) + r, + i.GroupViFrDrEvtCount = (i.GroupViFrDrEvtCount || 0) + 1) : (t.SparseViFrDr = (t.SparseViFrDr || 0) + r, + t.SparseViFrDrEvtCount = (t.SparseViFrDrEvtCount || 0) + 1, + i.SparseViFrDr = (i.SparseViFrDr || 0) + r, + i.SparseViFrDrEvtCount = (i.SparseViFrDrEvtCount || 0) + 1)) + } + ) + } + updateBufferAppended(e, t) { + this.update(e, ({sessionControlRecord: e})=>{ + e.bufferAppendInfo || (e.bufferAppendInfo = []), + e.bufferAppendInfo.push(t) + } + ) + } + updateSeeked(e, t) { + this.update(e, ({sessionControlRecord: e})=>{ + e.seekInfo || (e.seekInfo = []), + e.seekInfo.push(t) + } + ) + } + updateManifestParsed(e, r) { + this.update(e, ({sessionControlRecord: e, periodicRecord: t, playEndedRecord: i})=>{ + t.MasterPlaylistADT = (t.MasterPlaylistADT || 0) + r.adt, + i.MasterPlaylistADT = (i.MasterPlaylistADT || 0) + r.adt; + t = this._computeVariantInfo(r.levels); + i.IsAudioOnly = r.isAudioOnly, + i.IsGapless = r.isGapless, + i.IsFirstItem = r.isFirstItem, + i.ItemID = r.itemID, + i.MaxVideoQltyIndex = t.maxVideoQltyIndex, + i.MaxReWd = t.maxWidth, + i.MaxReHt = t.maxHeight, + e.manifestData = { + variantList: t.variantList, + varListString: t.varListString + } + } + ) + } + updateFragLoaded(e, r) { + this.update(e, ({sessionControlRecord: e, periodicRecord: t, playEndedRecord: i})=>{ + if (t.MediaRequestsSent = (t.MediaRequestsSent || 0) + 1, + i.MediaRequestsSent = (i.MediaRequestsSent || 0) + 1, + r.cdnServer) { + const e = r.cdnServer.toLowerCase(); + "aapl" !== e && "akam" !== e && "llnw" !== e || (i.LastMediaCDNServer = e) + } + r.serverInfo && (i.ServerInfo = r.serverInfo), + e.segmentMimeTypes || (e.segmentMimeTypes = []), + void 0 === e.segmentMimeTypes.find(e=>e == r.contentType) && e.segmentMimeTypes.push(r.contentType), + r.fragType === ul.Variant ? (e.variantVideoBytes = (e.variantVideoBytes || 0) + r.bytes, + e.variantVideoDuration = (e.variantVideoDuration || 0) + r.duration, + e.intervalVideoBytes = (e.intervalVideoBytes || 0) + r.bytes, + e.intervalVideoDuration = (e.intervalVideoDuration || 0) + r.duration, + e.sessionVideoBytes = (e.sessionVideoBytes || 0) + r.bytes, + e.sessionVideoDuration = (e.sessionVideoDuration || 0) + r.duration, + e.obrLast = 8 * r.bytes / (r.duration / 1e3), + t.NetBytes = (t.NetBytes || 0) + r.bytes, + t.ADT = (t.ADT || 0) + r.adt, + t.SegmentProcessTime = (t.SegmentProcessTime || 0) + r.processTime, + i.ADT = (i.ADT || 0) + r.adt, + i.NetBytes = (i.NetBytes || 0) + r.bytes, + i.SegmentProcessTime = (i.SegmentProcessTime || 0) + r.processTime) : r.fragType === ul.AltAudio && (e.variantAudioBytes = (e.variantAudioBytes || 0) + r.bytes, + e.variantAudioDuration = (e.variantAudioDuration || 0) + r.duration, + e.intervalAudioBytes = (e.intervalAudioBytes || 0) + r.bytes, + e.intervalAudioDuration = (e.intervalAudioDuration || 0) + r.duration, + e.sessionAudioBytes = (e.sessionAudioBytes || 0) + r.bytes, + e.sessionAudioDuration = (e.sessionAudioDuration || 0) + r.duration) + } + ) + } + updateFragBuffered(e, i) { + this.update(e, ({periodicRecord: e, playEndedRecord: t})=>{ + i.fragType === ul.Variant && (e.SegmentParseTime = (e.SegmentParseTime || 0) + i.parseTime, + t.SegmentParseTime = (t.SegmentParseTime || 0) + i.parseTime) + } + ) + } + updateLevelLoaded(e, n) { + this.update(e, ({sessionControlRecord: e, playLikelyToKeepUpRecord: t, periodicRecord: i, playEndedRecord: r})=>{ + t.PlaylistADT = (t.PlaylistADT || 0) + n.adt, + i.PlaylistADT = (i.PlaylistADT || 0) + n.adt, + r.PlaylistADT = (r.PlaylistADT || 0) + n.adt, + i.MaxPlaylistDT = n.adt > i.MaxPlaylistDT ? n.adt : i.MaxPlaylistDT, + r.MaxPlaylistDT = n.adt > r.MaxPlaylistDT ? n.adt : r.MaxPlaylistDT, + r.PlayType = n.playType, + this._setTargetDuration(n.url, n.targetduration, e), + e.playlistMimeTypes || (e.playlistMimeTypes = []), + void 0 === e.playlistMimeTypes.find(e=>e == n.contentType) && e.playlistMimeTypes.push(n.contentType); + i = n.url, + r = this._getVariantInfo(i, e); + e.intervalVariantList[i] || (e.intervalVariantList[i] = Object.assign({}, r)), + e.sessionVariantList[i] || (e.sessionVariantList[i] = Object.assign({}, r)) + } + ) + } + updateLevelsChanged(e, r) { + this.update(e, ({sessionControlRecord: t, playEndedRecord: e})=>{ + const i = this._computeVariantInfo(r.levels); + e.MaxVideoQltyIndex = i.maxVideoQltyIndex, + e.MaxReWd = i.maxWidth, + e.MaxReHt = i.maxHeight, + t.manifestData = { + variantList: i.variantList, + varListString: i.varListString + }, + Object.keys(i.variantList).forEach(e=>{ + t.intervalVariantList[e] && (t.intervalVariantList[e].brRnk = i.variantList[e].brRnk), + t.sessionVariantList[e] && (t.sessionVariantList[e].brRnk = i.variantList[e].brRnk) + } + ) + } + ) + } + updateLicenseChallengeRequested(e, r) { + this.update(e, ({sessionControlRecord: e})=>{ + const t = {} + , i = r.timestamp; + t.licenseChallengeStartTime = i, + "RTC_STATE_INIT" === e.state && (t.keyInitTime = i - e.sessionStartTime), + e.activeKeySessions[r.keyuri] = t + } + ) + } + updateLicenseChallengeReceived(e, i) { + this.update(e, ({sessionControlRecord: e})=>{ + const t = e.activeKeySessions[i.keyuri]; + t.licenseChallengeRequestTime = i.timestamp - t.licenseChallengeStartTime + } + ) + } + updateLicenseChallengeSubmitted(e, i) { + this.update(e, ({sessionControlRecord: e})=>{ + const t = e.activeKeySessions[i.keyuri]; + t.keyFormat = i.keyFormat, + t.licenseChallengeSubmitTime = i.timestamp + } + ) + } + updateLicenseChallengeCreated(e, i) { + this.update(e, ({sessionControlRecord: e})=>{ + const t = e.activeKeySessions[i.keyuri]; + t.cdmVersion = i.cdmVersion, + t.licenseChallengeCreationTime = i.timestamp - t.licenseChallengeSubmitTime + } + ) + } + updateLicenseResponseRequested(e, t) { + this.update(e, ({sessionControlRecord: e})=>{ + e.activeKeySessions[t.keyuri].licenseResponseRequestTime = t.timestamp + } + ) + } + updateLicenseResponseReceived(e, i) { + this.update(e, ({sessionControlRecord: e})=>{ + const t = e.activeKeySessions[i.keyuri]; + t.licenseResponseReceiveTime = i.timestamp - t.licenseResponseRequestTime + } + ) + } + updateLicenseResponseSubmitted(e, t) { + this.update(e, ({sessionControlRecord: e})=>{ + e.activeKeySessions[t.keyuri].licenseResponseSubmitTime = t.timestamp + } + ) + } + _prepareEventPlayEnded(e) { + this.update(e, ({sessionControlRecord: e, playEndedRecord: t})=>{ + t.AvgVideoBitrate = 8 * (e.sessionVideoBytes || 0) / (e.sessionVideoDuration || 1), + t.AvgAudioBitrate = 8 * (e.sessionAudioBytes || 0) / (e.sessionAudioDuration || 1); + var i = 1e3 * Math.round((t.NetBytes || 0) / 1e3); + t.NetBytes = i; + var r = t.ADT || 1 + , n = t.ADT + t.SegmentProcessTime || 1 + , s = t.ADT + t.SegmentProcessTime + t.SegmentParseTime || 1; + t.TWOBR = 8 * i / (r / 1e3), + t.PerceivedTWOBR = 8 * i / (n / 1e3), + t.NetTWOBR = 8 * i / (s / 1e3); + var s = this._findTimeWeightedValues("RTC_STATE_PLAY" === e.state ? Date.now() - e.eventStartTime : 0, e.sessionVariantList, e.curLevelUrl); + t.PlayerTWIBR = s.twIBR, + t.PlayerTWIABR = s.twIABR, + t.TWBitRk = s.twBRnk; + s = this._getVariantInfo(e.curLevelUrl, e); + t.TargetDur = s.targetduration, + t.ReWd = s.width, + t.ReHt = s.height, + t.VariantList = null === (s = e.manifestData) || void 0 === s ? void 0 : s.varListString; + let a = ""; + e.playlistMimeTypes && (e.playlistMimeTypes.forEach(e=>{ + a += e + "," + } + ), + a = a.slice(0, -1)); + let o = ""; + e.segmentMimeTypes && (e.segmentMimeTypes.forEach(e=>{ + o += e + "," + } + ), + o = o.slice(0, -1)), + t.PlaylistMimeType = a, + t.SegmentMimeType = o, + t.Rate = e.rate + } + ), + this._aggregateTimes(e) + } + _prepareEventPeriodic(e, o) { + this.update(e, ({sessionControlRecord: e, periodicRecord: t, playEndedRecord: i})=>{ + t.EventCounter = e.periodicEventCounter, + t.PInterval = Date.now() - e.lastPeriodicTime, + t.AvgVideoBitrate = 8 * (e.intervalVideoBytes || 0) / (e.intervalVideoDuration || 1), + t.AvgAudioBitrate = 8 * (e.intervalAudioBytes || 0) / (e.intervalAudioDuration || 1); + let r = t.NetBytes || 0; + o.isFinal && (t.NetBytes = r = 1e3 * Math.round(r / 1e3)); + var n = t.ADT || 1 + , s = t.ADT + t.SegmentProcessTime || 1 + , a = t.ADT + t.SegmentProcessTime + t.SegmentParseTime || 1; + t.TWOBR = 8 * r / (n / 1e3), + t.PerceivedTWOBR = 8 * r / (s / 1e3), + t.NetTWOBR = 8 * r / (a / 1e3); + var a = this._findTimeWeightedValues("RTC_STATE_PLAY" === e.state ? Date.now() - e.eventStartTime : 0, e.intervalVariantList, e.curLevelUrl); + t.PlayerTWIBR = a.twIBR, + t.PlayerTWIABR = a.twIABR, + t.TWBitRk = a.twBRnk; + a = this._getVariantInfo(e.curLevelUrl, e); + t.TargetDur = a.targetduration, + t.ReWd = a.width, + t.ReHt = a.height, + t.VariantList = null === (a = e.manifestData) || void 0 === a ? void 0 : a.varListString, + t.Rate = e.rate; + e = this._computeMediaStats(e); + e && (t.MedianBufferAppendLatency = e.bufLatencyInfo.median, + t.MaxBufferAppendLatency = e.bufLatencyInfo.max, + t.MedianBufferAppendSize = e.bufSizeInfo.median, + t.MaxBufferAppendSize = e.bufSizeInfo.max, + t.MedianSeekLatency = e.seekLatencyInfo.median, + t.MaxSeekLatency = e.seekLatencyInfo.max, + t.MedianPlayLatency = e.playLatencyInfo.median, + t.MaxPlayLatency = e.playLatencyInfo.max), + this._copyCommonKeys(t, i) + } + ), + this._aggregateTimes(e) + } + _prepareEventPlayStalled(e, s) { + this.update(e, ({sessionControlRecord: e, playStalledRecord: t, playEndedRecord: i})=>{ + var r = this._getVariantInfo(e.curLevelUrl, e) + , n = Date.now(); + t.MediaDur = s.mediaDur, + t.BitRnk = r.brRnk, + t.Codecs = r.codecs, + t.LastLikelyToKeepUp = n - e.lastLikelyToKeepUpTime, + t.LastSwitch = n - e.lastSwitchTime, + t.StallDetectionTime = s.stallDurationMs, + t.StallType = s.type, + t.BufferLength = s.bufferLen, + "networkError" === i.ErrDomain && (t.NwErrTime = i.NwErrTime, + t.NwErrCode = i.ErrCode), + t.LaSwDir = e.lastSwitchDir, + t.TargetDur = r.targetduration, + t.PlayerIABR = r.avgBandwidth, + t.PlayerIBR = r.bandwidth, + t.Rate = e.rate, + t.OBRLast = e.obrLast, + t.OBRMean = 8 * i.NetBytes / (i.ADT / 1e3), + this._copyCommonKeys(t, i) + } + ), + this._aggregateTimes(e) + } + _prepareEventKeySessionComplete(e, r) { + this.update(e, ({sessionControlRecord: e, keySessionCompleteRecord: t, playEndedRecord: i})=>{ + e = e.activeKeySessions[r.keyuri]; + e ? (t.KeyFormat = e.keyFormat, + t.CDMVersion = e.cdmVersion, + t.LicenseChallengeRequestTime = e.licenseChallengeRequestTime, + t.LicenseChallengeCreationTime = e.licenseChallengeCreationTime, + t.LicenseResponseReceiveTime = e.licenseResponseReceiveTime, + t.LicenseResponseProcessTime = e.licenseResponseProcessTime, + t.KeyDeliveryTime = e.keyDeliveryTime, + t.CurrentMediaTime = 1e3 * e.currentMediaTime, + t.KeyInitTime = e.keyInitTime, + t.KeyErrorType = e.keyErrorType, + this._copyCommonKeys(t, i)) : this.logger.warn(`_prepareEventKeySessionComplete no keySessionInfo for ${oe(r.keyuri)}`) + } + ), + this._aggregateTimes(e) + } + _prepareEventPlayLikelyToKeepUp(e, n) { + this.update(e, ({sessionControlRecord: e, playLikelyToKeepUpRecord: t, playEndedRecord: i})=>{ + var r = this._getVariantInfo(e.curLevelUrl, e); + t.EventCounter = e.playLikelyToKeepUpEventCounter, + t.PlayerIABR = r.avgBandwidth, + t.PlayerIBR = r.bandwidth, + t.MediaDur = n.mediaDur, + t.BitRnk = r.brRnk, + t.Codecs = r.codecs, + t.TargetDur = r.targetduration, + this._copyCommonKeys(t, i) + } + ), + this._aggregateTimes(e) + } + _prepareEventPlayRateChanged(e, n) { + this.update(e, ({sessionControlRecord: e, playRateChangedRecord: t, playEndedRecord: i})=>{ + var r = this._getVariantInfo(e.curLevelUrl, e); + t.Rate = e.rate, + t.StNPT = n.currentTime, + t.PlayerIABR = r.avgBandwidth, + t.PlayerIBR = r.bandwidth, + t.BitRnk = r.brRnk, + t.MediaDur = n.mediaDur, + t.Codecs = r.codecs, + this._copyCommonKeys(t, i) + } + ), + this._aggregateTimes(e) + } + _prepareEventPlayError(e, s) { + this.update(e, ({sessionControlRecord: e, playErrorRecord: t, playEndedRecord: i})=>{ + var r = this._getVariantInfo(e.curLevelUrl, e) + , n = Date.now(); + "mediaElementError" == s.domain ? (t.ErrDomain = t.ErrCode = "mediaElementError", + t.ErrIsFatal = !0, + t.ErrCodeMediaElement = s.mediaElemCode, + t.ErrReason = s.mediaElemReason, + t.ErrDetail = s.mediaElemDetail) : (t.ErrCode = s.details, + t.ErrReason = s.code, + t.ErrIsFatal = s.fatal, + t.ErrDomain = "mediaError"), + t.PlayerErrCount = s.count || 1, + t.BitRnk = r.brRnk, + t.MediaDur = s.mediaDur, + t.PlayTime = i.PlayTime, + t.PlayTimeWC = i.PlayTimeWC, + t.PlayerIABR = r.avgBandwidth, + t.PlayerIBR = r.bandwidth, + t.LastLikelyToKeepUp = n - e.lastLikelyToKeepUpTime, + t.LastSwitch = n - e.lastSwitchTime, + t.VideoQltyIndex = r.qltyIndex, + t.Rate = e.rate, + t.KeyErrorType = e.lastKeyErrorType, + t.KeyDeliveryTime = e.lastKeyDeliveryTime, + this._copyCommonKeys(t, i) + } + ), + this._aggregateTimes(e) + } + _prepareEventMediaEngineStalled(e, s) { + this.update(e, ({sessionControlRecord: e, mediaEngineStalledRecord: t, playEndedRecord: i})=>{ + var r = Date.now() + , n = this._getVariantInfo(e.curLevelUrl, e); + t.MediaDur = s.mediaDur, + t.BitRnk = n.brRnk, + t.Codecs = n.codecs, + t.LastLikelyToKeepUp = r - e.lastLikelyToKeepUpTime, + t.LastSwitch = r - e.lastSwitchTime, + t.StallDetectionTime = s.stallDurationMs, + t.StallType = s.type, + t.BufferLength = s.bufferLen, + t.LaSwDir = e.lastSwitchDir, + t.TargetDur = n.targetduration, + t.PlayerIABR = n.avgBandwidth, + t.PlayerIBR = n.bandwidth, + t.Rate = e.rate, + t.OBRLast = e.obrLast, + t.OBRMean = 8 * i.NetBytes / (i.ADT / 1e3), + this._copyCommonKeys(t, i) + } + ), + this._aggregateTimes(e) + } + _prepareEventSwitchComplete(e, s) { + this.update(e, ({sessionControlRecord: e, switchCompleteRecord: t, playEndedRecord: i})=>{ + var r = this._getVariantInfo(e.prevLevelUrl, e) + , n = this._getVariantInfo(e.curLevelUrl, e); + t.FrBitRnk = r.brRnk, + t.ToBitRnk = n.brRnk, + t.TimeToBitrate = Date.now() - e.sessionStartTime, + t.MediaDur = s.mediaDur, + t.Rate = e.rate, + t.PlayerIBR = n.bandwidth, + t.PlayerIABR = n.avgBandwidth, + t.LastPlayerIBR = r.bandwidth, + t.LastPlayerIABR = r.avgBandwidth, + t.ReWd = n.width, + t.ReHt = n.height, + this._copyCommonKeys(t, i) + } + ), + this._aggregateTimes(e) + } + _prepareEventVariantEnded(e, n) { + this.update(e, ({sessionControlRecord: e, variantEndedRecord: t, playEndedRecord: i})=>{ + var r = this._getVariantInfo(e.curLevelUrl, e); + t.Rate = e.rate, + t.VarAvgBitrate = r.avgBandwidth, + t.VarPeakBitrate = r.bandwidth, + t.VarBitRk = r.brRnk, + t.VarSTTime = e.variantStartTimeMedia, + t.VarEndTime = 1e3 * n.currentTime, + t.IFR = r.framerate, + t.ODR = e.decodedFramesForVariant / e.decodedFramesForVariantSampleCount, + t.ReWd = r.width, + t.ReHt = r.height, + t.Codecs = r.codecs, + t.AvgVideoBitrate = 8 * (e.variantVideoBytes || 0) / (e.variantVideoDuration || 1), + t.AvgAudioBitrate = 8 * (e.variantAudioBytes || 0) / (e.variantAudioDuration || 1), + this._copyCommonKeys(t, i) + } + ), + this._aggregateTimes(e) + } + _prepareEventNwError(e, n) { + this.update(e, ({sessionControlRecord: e, nwErrorRecord: t, playEndedRecord: i})=>{ + var r = this._getVariantInfo(e.curLevelUrl, e); + t.ErrCode = n.details, + t.ErrReason = n.code, + t.ErrIsFatal = n.fatal, + t.NwErrCount = n.count || 1, + t.ErrDomain = "networkError", + t.PlayTime = i.PlayTime, + t.PlayTimeWC = i.PlayTimeWC, + t.BitRnk = r.brRnk, + t.Rate = e.rate, + t.KeyErrorType = e.lastKeyErrorType, + t.KeyDeliveryTime = e.lastKeyDeliveryTime, + this._copyCommonKeys(t, i) + } + ), + this._aggregateTimes(e) + } + _copyCommonKeys(e, t) { + e.PlayType = t.PlayType, + e.LastMediaCDNServer = t.LastMediaCDNServer, + e.MaxVideoQltyIndex = t.MaxVideoQltyIndex, + e.MaxReWd = t.MaxReWd, + e.MaxReHt = t.MaxReHt, + e.IsGapless = t.IsGapless, + e.IsAudioOnly = t.IsAudioOnly, + e.IsFirstItem = t.IsFirstItem, + e.ItemID = t.ItemID, + e.ServerInfo = t.ServerInfo + } + _computeVariantInfo(e) { + const i = {}; + let r = 0 + , n = 0 + , s = 0 + , a = 0; + const o = this._getMaxNormalizedPeak(e); + e.forEach(e=>{ + if (e.attrs) { + const r = this._getVideoFourCC(e.attrs.CODECS) + , n = this._getVideoQualityIndex(r, e.attrs["VIDEO-RANGE"]) || 0 + , s = { + codecs: e.attrs.CODECS, + width: e.width, + height: e.height, + bandwidth: e.attrs.BANDWIDTH, + avgBandwidth: e.attrs["AVERAGE-BANDWIDTH"], + framerate: e.attrs["FRAME-RATE"], + iframes: e.iframes, + brRnk: this._getBitrateRank(e.attrs.BANDWIDTH, r, o), + qltyIndex: n, + targetduration: 0, + playTime: 0 + }; + a = n > a ? n : a, + i[e.url] = s + } + var t = e.width * e.height; + t > s && (s = t, + r = e.width, + n = e.height) + } + ); + e = 0 < Object.keys(i).length ? Object.values(i).map(e=>e.bandwidth + ":" + e.avgBandwidth).join(",") : void 0; + return { + variantList: i, + varListString: e, + maxVideoQltyIndex: a, + maxWidth: r, + maxHeight: n + } + } + _getMaxNormalizedPeak(e) { + let n = 0; + return e.forEach(e=>{ + e = e.attrs; + if (e) { + const t = e.BANDWIDTH || 0 + , i = this._getNormalizedPeak(t, this._getVideoFourCC(e.CODECS)) + , r = Math.max(t, i); + n = r > n ? r : n + } + } + ), + n + } + _getNormalizedPeak(e, t) { + return "object" == typeof Ly[t] ? 1.5 * e : +e + } + _getVideoFourCC(e) { + return e && e.split(",").map(e=>e.split(".")[0].trim()).find(e=>!!Ly[e]) + } + _getVideoQualityIndex(e, t) { + return "object" == typeof Ly[e] ? Ly[e][t] : Ly[e] + } + _getBitrateRank(e, t, i) { + t = Math.max(1, this._getNormalizedPeak(e, t)); + return Math.ceil(100 * t / i) + } + _findTimeWeightedValues(o, d, l) { + const e = { + twBRnk: 0, + twIBR: 0, + twIABR: 0 + }; + if (d) { + let i = 0 + , r = 0 + , n = 0 + , s = 0 + , a = 0; + Object.values(d).forEach(e=>{ + let t = e.playTime; + e === d[l] && (t += o || 0), + t && (r += e.bandwidth * t, + i += e.brRnk * t, + n += t, + e.avgBandwidth && (s += e.avgBandwidth * t, + a += t)) + } + ), + n && (e.twBRnk = i / n, + e.twIBR = r / n), + s && a && (e.twIABR = s / a) + } + return e + } + _computeMediaStats(e) { + const t = e.bufferAppendInfo; + let i = []; + const r = []; + t && t.forEach && t.forEach(e=>{ + i.push(e.latency), + r.push(e.size) + } + ); + var n = this._computeStats(i) + , s = this._computeStats(r) + , a = e.seekInfo; + i = [], + a && a.forEach && e.seekInfo.forEach(e=>i.push(e.latency)); + var o = this._computeStats(i) + , a = e.playInfo; + return i = [], + a && a.forEach && e.playInfo.forEach(e=>i.push(e.latency)), + { + bufLatencyInfo: n, + bufSizeInfo: s, + seekLatencyInfo: o, + playLatencyInfo: this._computeStats(i) + } + } + _computeStats(e) { + let t, i; + if (e) { + const r = e.filter(e=>0 < e); + if (0 < r.length) { + t = r.reduce((e,t)=>Math.max(e, t)); + const e = r.length + , n = r.sort((e,t)=>e - t) + , s = Math.ceil(e / 2); + i = e % 2 == 0 ? (n[s] + n[s - 1]) / 2 : n[s - 1] + } + } + return { + max: t, + median: i + } + } + _getVariantInfo(e, t) { + return e && t.manifestData && t.manifestData.variantList && t.manifestData.variantList[e] ? t.manifestData.variantList[e] : {} + } + _setTargetDuration(e, t, i) { + e && i.manifestData && i.manifestData.variantList && i.manifestData.variantList[e] && (i.manifestData.variantList[e].targetduration = t) + } + _isBadSw(e, t, i, r, n, s, a) { + let o = n - s < 1e4 && t !== e && r === i && !a ? !0 : !1; + return o + } + _aggregateTimes(e) { + this.update(e, ({sessionControlRecord: t, playLikelyToKeepUpRecord: i, playStalledRecord: r, mediaEngineStalledRecord: n, switchCompleteRecord: s, playRateChangedRecord: a, variantEndedRecord: o, playErrorRecord: d, nwErrorRecord: l, periodicRecord: u, playEndedRecord: c})=>{ + var h = Date.now() - t.eventStartTime; + switch (t.state) { + case "RTC_STATE_INIT": + i.StartupTime = (i.StartupTime || 0) + h, + u.InitTime = (u.InitTime || 0) + h, + c.InitTime = (c.InitTime || 0) + h; + break; + case "RTC_STATE_CANPLAY": + a.StartupTime = (a.StartupTime || 0) + h, + u.InitTime = (u.InitTime || 0) + h, + c.InitTime = (c.InitTime || 0) + h; + break; + case "RTC_STATE_PAUSE": + u.PauseTime = (u.PauseTime || 0) + h, + c.PauseTime = (c.PauseTime || 0) + h, + a.LastPause = (a.LastPause || 0) + h, + c.LastPause = (c.LastPause || 0) + h, + d.LastPause = (d.LastPause || 0) + h, + l.LastPause = (l.LastPause || 0) + h; + break; + case "RTC_STATE_STALL": + o.StallTime = (o.StallTime || 0) + h, + u.StallTime = (u.StallTime || 0) + h, + c.StallTime = (c.StallTime || 0) + h, + a.LastStall = (a.LastStall || 0) + h, + d.LastStall = (d.LastStall || 0) + h, + c.LastStall = (c.LastStall || 0) + h; + break; + case "RTC_STATE_MEDIAENGINESTALL": + o.MediaEngineStallTime = (o.MediaEngineStallTime || 0) + h, + u.MediaEngineStallTime = (u.MediaEngineStallTime || 0) + h, + c.MediaEngineStallTime = (c.MediaEngineStallTime || 0) + h, + a.LastMediaEngineStall = (a.LastMediaEngineStall || 0) + h, + d.LastMediaEngineStall = (d.LastMediaEngineStall || 0) + h, + c.LastMediaEngineStall = (c.LastMediaEngineStall || 0) + h; + break; + case "RTC_STATE_NWERROR": + c.NwErrTime = (c.NwErrTime || 0) + h, + u.NwErrTime = (u.NwErrTime || 0) + h; + break; + case "RTC_STATE_PLAYERROR": + u.PlayErrTime = (u.PlayErrTime || 0) + h, + c.PlayErrTime = (c.PlayErrTime || 0) + h; + break; + case "RTC_STATE_PLAY": + { + a.RateChangePlayTime = (a.RateChangePlayTime || 0) + h, + s.PlayTime = (s.PlayTime || 0) + h, + s.PlayTimeLastSW = (s.PlayTimeLastSW || 0) + h * (t.oldRate / 100), + r.LastResume = (r.LastResume || 0) + h, + n.LastResume = (n.LastResume || 0) + h, + d.LastResume = (d.LastResume || 0) + h, + l.LastResume = (l.LastResume || 0) + h, + o.VarPlayTimeWC = (o.VarPlayTimeWC || 0) + h, + o.VarPlayTime = (o.VarPlayTime || 0) + h * (t.oldRate / 100), + u.PlayTimeWC = (u.PlayTimeWC || 0) + h, + u.PlayTime = (u.PlayTime || 0) + h * (t.oldRate / 100), + c.PlayTimeWC = (c.PlayTimeWC || 0) + h, + c.PlayTime = (c.PlayTime || 0) + h * (t.oldRate / 100), + n.PlayTime = c.PlayTime, + r.PlayTime = c.PlayTime; + const i = t.curLevelUrl; + let e = t.intervalVariantList[i]; + e.playTime = (e.playTime || 0) + h, + e = t.sessionVariantList[i], + e.playTime = (e.playTime || 0) + h; + break + } + } + } + ) + } + } + const By = { + name: "rtc-service" + }; + class Uy { + constructor(e, t, i, r) { + this.hls = e, + this.config = t, + this.accessLog = i, + this.logger = r, + this.destroy$ = new zt, + this.isSeeking = !1, + this.seekStart = null, + this.periodicInterval = t.rtcIntervalTimeout || 3e5, + this.intervalFunc = null, + this.rtcStore = new Fy(this.logger), + this.rtcQuery = new Ny(this.rtcStore,this.logger), + this.rtcComponent = new _y(this.rtcQuery,this.logger), + i.setRTCQuery(this.rtcQuery), + this.subscribeAndUpdateStore(), + this.registerForEvents() + } + destroy() { + this.destroy$.next(), + this.clearPeriodic(), + this.rtcStore.reset() + } + detachMedia() { + this.clearPeriodic(); + var e; + try { + e = this.hls.realCurrentTime, + this.rtcStore.updateVariantEnd(this.rtcEventItemId(!0), { + currentTime: e + }), + this.sendAndFinalize(this.rtcEventItemId(!0), Ry.VariantEnded), + this.rtcStore.updatePeriodic(this.rtcEventItemId(!0), !0), + this.sendAndFinalize(this.rtcEventItemId(!0), Ry.Periodic), + this.rtcStore.updateEnded(this.rtcEventItemId(!0)), + this.sendAndFinalize(this.rtcEventItemId(!0), Ry.PlayEnded) + } catch (e) { + this.logger.warn(By, e) + } + } + handleError(e) { + var t = e instanceof p ? e : new V(!0,e.message,$.InternalError); + t instanceof nu && !t.fatal ? (this.rtcStore.updateLevelLoadError(this.rtcEventItemId(), { + url: t.url, + mediaDur: this.hls.bufferedDuration, + isSeeking: this.isSeeking + }), + this.sendAndFinalize(this.rtcEventItemId(), Ry.SwitchComplete)) : t.type === o ? (this.rtcStore.updateNwError(this.rtcEventItemId(), { + fatal: t.fatal, + details: t.details, + code: null === (e = t.response) || void 0 === e ? void 0 : e.code + }), + this.sendAndFinalize(this.rtcEventItemId(), Ry.NwError)) : (this.rtcStore.updateMediaError(this.rtcEventItemId(), { + fatal: t.fatal, + details: t.details, + code: null === (t = t.response) || void 0 === t ? void 0 : t.code + }), + this.sendAndFinalize(this.rtcEventItemId(), Ry.PlayError)) + } + handleMediaElementError(e) { + this.rtcStore.updateMediaElementError(this.rtcEventItemId(), e), + this.sendAndFinalize(this.rtcEventItemId(), Ry.PlayError) + } + handleFragLoaded(e, t) { + var i, r, n; + this.checkMediaOptionType(e.mediaOptionType) && (e.itemId !== this.rtcEventItemId() && this.logger.warn(By, `Frag id does not match current item id. Frag Id=${e.itemId}, playing id=${this.rtcEventItemId(!0)}, loading id=${null === (n = this.hls.loadingItem) || void 0 === n ? void 0 : n.itemId}`), + i = t.tload - t.trequest, + r = t.tload - t.tfirst, + n = this.serverInfoInstance || {}, + this.rtcStore.updateFragLoaded(e.itemId, { + fragType: e.mediaOptionType, + bytes: t.loaded, + duration: e.duration, + adt: i, + processTime: r, + contentType: t.contentType, + cdnServer: t.cdnServer, + serverInfo: n + }), + this.accessLog.updateFragLoaded(e.itemId, this.isSeeking, { + fragType: e.mediaOptionType, + bytes: t.loaded, + duration: e.duration, + adt: i, + processTime: r, + startPTS: e.start, + endPTS: e.start + e.duration + })) + } + handleFragBuffered(e) { + var t; + this.checkMediaOptionType(e.fragmentType) && (t = e.endDataAppend - e.startDataAppend, + this.rtcStore.updateFragBuffered(this.rtcEventItemId(), { + fragType: e.fragmentType, + bytes: e.dataBytesAppend, + parseTime: t + })) + } + handleLevelLoaded(e, t) { + var i; + e ? (e.itemId !== this.rtcEventItemId() && this.logger.warn(By, `media option id does not match current item id. media Id=${e.itemId}, current id=${this.rtcEventItemId}`), + e.mediaOptionType === ul.Variant && (i = t.tload - t.trequest, + this.rtcStore.updateLevelLoaded(this.rtcEventItemId(), { + url: e.url, + targetduration: e.targetduration, + adt: i, + contentType: t.contentType, + playType: e.type + }))) : this.logger.warn(`handleLevelLoaded called with mediaOptionDetails as ${e}`) + } + handleLevelSwitched(e) { + var t = { + url: e.url, + isSeeking: this.isSeeking, + mediaDur: this.hls.bufferedDuration, + currentTime: this.hls.realCurrentTime + }; + e.oldVariant && (this.rtcStore.updateVariantEnd(this.rtcEventItemId(), { + currentTime: this.hls.realCurrentTime + }), + this.sendAndFinalize(this.rtcEventItemId(), Ry.VariantEnded)), + this.rtcStore.updateLevelSwitched(this.rtcEventItemId(), t), + this.sendAndFinalize(this.rtcEventItemId(), Ry.SwitchComplete) + } + handleLevelSwitching(e) { + this.levelSwitchingUrl = e + } + handleLevelsChanged(e) { + this.rtcStore.updateLevelsChanged(this.rtcEventItemId(), { + levels: e + }) + } + handleManifestParsed(e) { + var t = e.stats.tload - e.stats.trequest; + this.rtcStore.updateManifestParsed(this.rtcEventItemId(), { + levels: e.levels, + adt: t, + contentType: e.stats.contentType, + isAudioOnly: this.hls.inGaplessMode, + isGapless: this.hls.inGaplessMode, + isFirstItem: this.hls.isFirstItem, + itemID: ((null === (e = this.hls.reportingAgent) || void 0 === e ? void 0 : e.SessionID) || Jd()) + "-" + this.rtcEventItemId() + }) + } + handleSeek(e) { + if ("SEEKING" === e) + this.isSeeking = !0, + this.seekStart = Date.now(); + else if ("SEEKED" === e) { + this.isSeeking = !1; + let e = 0; + this.seekStart && (e = Date.now() - this.seekStart), + this.seekStart = null, + this.rtcStore.updateSeeked(this.rtcEventItemId(!0), { + latency: e + }) + } + } + handleDesiredRateChanged(e, t) { + 0 === t || 1 < Math.abs(e) && 1 < Math.abs(t) ? (this.rtcStore.updateRateChanged(this.rtcEventItemId(!0), { + rate: t, + latency: 0, + mediaDur: this.hls.bufferedDuration, + currentTime: this.hls.realCurrentTime, + url: this.levelSwitchingUrl + }), + this.sendAndFinalize(this.rtcEventItemId(!0), Ry.PlayRateChanged)) : 1 !== e && 1 === t && (this.playStart = Date.now()), + this.oldRate = e, + this.newRate = t + } + handleVariantBufferAppended(e, t) { + let i = 0; + e && (i = Date.now() - e), + this.rtcStore.updateBufferAppended(this.rtcEventItemId(), { + latency: i, + size: t + }) + } + handleStalled(e, t) { + var i = { + type: e.type, + stallDurationMs: e.stallDurationMs, + bufferLen: t, + mediaDur: this.hls.bufferedDuration + } + , t = this.rtcQuery.getEntity(this.rtcEventItemId(!0)).sessionControlRecord.state; + e.type === Op.LowBuffer || e.type === Op.Seek && e.isLowBufferStall ? "RTC_STATE_PLAY" === t && (this.rtcStore.updateBufferStalled(this.rtcEventItemId(!0), i), + this.sendAndFinalize(this.rtcEventItemId(!0), Ry.PlayStalled)) : "RTC_STATE_PLAY" === t && (this.rtcStore.updateMediaEngineStalled(this.rtcEventItemId(!0), i), + this.sendAndFinalize(this.rtcEventItemId(!0), Ry.MediaEngineStalled)) + } + handlePlaybackInfo(e, t) { + this.rtcStore.updatePlaybackInfo(this.rtcEventItemId(!0), { + droppedVideoFrames: e, + decodedFrameCount: t + }), + this.accessLog.updatePlaybackInfo(this.rtcEventItemId(!0), { + droppedVideoFrames: e, + decodedFrameCount: t + }) + } + checkMediaOptionType(e) { + return e === ul.Variant || e === ul.AltAudio || (this.logger.error(By, 'Should not have media option type = "%s" in RTC', Cl[e]), + !1) + } + rtcEventItemId(e=!1) { + return (this.hls.isPreloading ? e ? this.hls.playingItem : this.hls.loadingItem : this.hls.currentItem).itemId + } + subscribeAndUpdateStore() { + this.hls.publicQueries$.pipe(Ra(([,e])=>this.mediaElementQueryListener(e)), $a(this.destroy$)).subscribe(), + this.hls.itemQueue.activeItemById$.pipe(Ja(t=>{ + if (t) { + let e = !1; + if (this.hls.userInfo ? this.hls.userInfo.internalBuild ? e = !0 : this.hls.userInfo.diagnosticsAndUsage && (e = this.config.enableRtcReporting) : e = this.config.enableRtcReporting, + e) { + const i = this.hls.reportingAgent; + i ? this.rtcComponent.setReportingAgent(i) : this.logger.warn(By, "[RTCA] - Reporting is enabled but reportingAgent is null") + } else + this.rtcComponent.setReportingAgent(null); + this.serverInfoInstance = null; + t = t.itemId; + this.rtcStore.createEntity(t), + !this.hls.isFirstItem && this.hls.inGaplessMode || this.setPeriodic(t) + } + } + ), $a(this.destroy$)).subscribe() + } + itemTransitioned(e, t) { + this.rtcStore.updateVariantEnd(e, { + currentTime: this.hls.realCurrentTime + }), + this.sendAndFinalize(e, Ry.VariantEnded), + this.rtcStore.updatePeriodic(e, !0), + this.sendAndFinalize(e, Ry.Periodic), + this.rtcStore.updateEnded(e), + this.sendAndFinalize(e, Ry.PlayEnded), + this.setPeriodic(t) + } + mediaElementQueryListener(e) { + return e.gotPlaying$.pipe(Ja(e=>{ + if (e) { + const e = this.oldRate + , t = this.newRate || 1; + 1 < Math.abs(e) && 1 < Math.abs(t) || (this.rtcStore.updateCanPlay(this.rtcEventItemId(!0), { + mediaDur: this.hls.bufferedDuration + }), + this.sendAndFinalize(this.rtcEventItemId(!0), Ry.PlayLikelyToKeepUp), + this.rtcStore.updateRateChanged(this.rtcEventItemId(!0), { + rate: t, + latency: ne(this.playStart) ? Date.now() - this.playStart : 0, + mediaDur: this.hls.bufferedDuration, + currentTime: this.hls.realCurrentTime, + url: this.levelSwitchingUrl + }), + this.sendAndFinalize(this.rtcEventItemId(!0), Ry.PlayRateChanged)) + } + } + )) + } + registerForEvents() { + const e = wc(this.hls, this); + nn(e.event(P.KEY_REQUEST_STARTED, this.keyRequestStarted, this), e.event(P.KEY_LOADED, this.keyLoaded, this)).pipe($a(this.destroy$)).subscribe() + } + keyRequestStarted(e) { + e.timestamp = Date.now(), + this.rtcStore.updateLicenseChallengeRequested(this.rtcEventItemId(), e) + } + keyLoaded(e) { + e.timestamp = Date.now(), + e.currentTime = this.hls.realCurrentTime, + this.rtcStore.updateSegmentKeyLoaded(this.rtcEventItemId(), e) + } + licenseChallengeReceived(e) { + this.rtcStore.updateLicenseChallengeReceived(this.rtcEventItemId(), { + timestamp: Date.now(), + keyuri: e.keyuri + }) + } + licenseChallengeSubmitted(e) { + this.rtcStore.updateLicenseChallengeSubmitted(this.rtcEventItemId(), { + timestamp: Date.now(), + keyFormat: e.keyFormat, + keyuri: e.keyuri + }) + } + licenseChallengeCreated(e) { + this.rtcStore.updateLicenseChallengeCreated(this.rtcEventItemId(), { + timestamp: Date.now(), + cdmVersion: e.cdmVersion, + keyuri: e.keyuri + }), + this.rtcStore.updateLicenseResponseRequested(this.rtcEventItemId(), { + timestamp: Date.now(), + keyuri: e.keyuri + }) + } + licenseResponseSubmitted(e) { + this.rtcStore.updateLicenseResponseReceived(this.rtcEventItemId(), { + timestamp: Date.now(), + keyuri: e.keyuri + }), + this.rtcStore.updateLicenseResponseSubmitted(this.rtcEventItemId(), { + timestamp: Date.now(), + keyuri: e.keyuri + }) + } + licenseResponseProcessed(e) { + this.rtcStore.updateLicenseResponseProcessed(this.rtcEventItemId(), { + timestamp: Date.now(), + keyuri: e.keyuri, + currentTime: this.hls.realCurrentTime + }), + this.sendAndFinalize(this.rtcEventItemId(), Ry.KeySessionComplete) + } + licenseChallengeError(e) { + this.rtcStore.updateLicenseChallengeError(this.rtcEventItemId(), { + timestamp: Date.now(), + keyuri: e.keyuri + }), + this.sendAndFinalize(this.rtcEventItemId(), Ry.KeySessionComplete) + } + licenseResponseError(e) { + this.rtcStore.updateLicenseResponseError(this.rtcEventItemId(), { + timestamp: Date.now(), + keyuri: e.keyuri + }), + this.sendAndFinalize(this.rtcEventItemId(), Ry.KeySessionComplete) + } + keyAborted(e) { + var t; + null != (null === (t = this.rtcQuery.getEntity(this.rtcEventItemId())) || void 0 === t ? void 0 : t.sessionControlRecord.activeKeySessions[e.keyuri]) ? (this.rtcStore.updateKeyAborted(this.rtcEventItemId(), { + timestamp: Date.now(), + keyuri: e.keyuri + }), + this.sendAndFinalize(this.rtcEventItemId(), Ry.KeySessionComplete)) : this.logger.warn(`keyAbort called without active key session ${oe(e.keyuri)}`) + } + setPeriodic(e) { + this.clearPeriodic(), + this.intervalFunc = setInterval(this.handlePeriodic.bind(this, e), this.periodicInterval) + } + handlePeriodic(e) { + this.rtcStore.updatePeriodic(e, !1), + this.sendAndFinalize(e, Ry.Periodic) + } + clearPeriodic() { + this.intervalFunc && clearInterval(this.intervalFunc), + this.intervalFunc = null + } + sendAndFinalize(e, t) { + switch (this.accessLog.addPlayTime(e), + t) { + case Ry.PlayEnded: + this.rtcComponent.sendPlayEnded(e); + break; + case Ry.Periodic: + this.rtcComponent.sendPeriodic(e); + break; + case Ry.PlayStalled: + this.accessLog.updateStallCount(e), + this.rtcComponent.sendPlayStalled(e); + break; + case Ry.KeySessionComplete: + this.rtcComponent.sendKeySessionComplete(e); + break; + case Ry.PlayLikelyToKeepUp: + this.accessLog.updateCanPlay(e), + this.rtcComponent.sendPlayLikelyToKeepUp(e); + break; + case Ry.PlayRateChanged: + this.rtcComponent.sendPlayRateChange(e); + break; + case Ry.PlayError: + this.accessLog.addToErrorLog(e, "mediaError"), + this.rtcComponent.sendPlayError(e); + break; + case Ry.MediaEngineStalled: + this.accessLog.updateMediaEngineStallCount(e), + this.rtcComponent.sendMediaEngineStalled(e); + break; + case Ry.SwitchComplete: + this.accessLog.addToAccessLog(e), + this.rtcComponent.sendSwitchComplete(e); + break; + case Ry.VariantEnded: + this.rtcComponent.sendVariantEnded(e); + break; + case Ry.NwError: + this.accessLog.addToErrorLog(e, "networkError"), + this.rtcComponent.sendNwError(e); + break; + default: + return void this.logger.error(By, `Unknown rtc event eventGroupId:${e}`) + } + this.rtcStore.finalize(e, t) + } + } + function $y(t, o, d, l, u, c, h) { + return e=>e.pipe(Up(), Ra(e=>{ + return e ? Cr([Bi(e).pipe(xy(t.manifestLoadPolicy, d, t, l, null, u, c)), (n = t, + s = o, + a = h.mux, + new Ut(e=>{ + const t = new ay(n,s,a); + return e.next(t), + ()=>{ + t.destroy() + } + } + )), (i = t.trickPlaybackConfig, + r = o, + new Ut(e=>{ + var t = new ql(i,r); + return e.next(t), + ()=>{} + } + ))]).pipe(ur(([e,t,i])=>({ + rootPlaylistQuery: e, + mediaParser: t, + iframeMachine: i + }))) : Bi(null); + var i, r, n, s, a + } + )) + } + Ec; + return class Vy extends Ec { + constructor(e={}, t) { + var i; + if (super(), + this.destroy$ = new zt, + this.mediaElement$ = new gi(null), + this.encryptedMediaElement$ = new gi(null), + this.publicQueriesInternal$ = new gi(null), + this.mediaElementAdapter = null, + this.rpcService = null, + this.rpcClients = null, + this.platformService = bf(), + this.keySystemAdapter = null, + this.legibleSystemAdapter = null, + this.sessionID = Jd(), + this.statsService = (Bf = Bf || new Nf(Ff), + Bf), + this.gaplessCapable = !0, + this.teardownWorker$ = new Hf, + this.itemQueue = new jg, + (e.liveSyncDurationCount || e.liveMaxLatencyDurationCount) && (e.liveSyncDuration || e.liveMaxLatencyDuration)) + throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration"); + const f = Object.assign(Object.assign({}, Al), e); + i = (this.hlsConfig = f).buildType, + ae = "production" === i; + const r = this.sessionID; + let n = "silent"; + e.debug && (n = f.debugLevel), + this.logger = null !== (i = this.logger) && void 0 !== i ? i : ([D,c={}] = [r, (u = { + sendLogs: e.sendLogs, + level: "log" === n ? "debug" : n, + consoleOverride: "boolean" != typeof e.debug ? e.debug : void 0, + buildType: f.buildType + }, + M = u.consoleOverride, + Object.assign({ + name: "hls", + timestamp: u.sendLogs ? Ae.stdTimeFunctions.epochTime : Ae.stdTimeFunctions.isoTime, + browser: { + asObject: !0, + serialize: !0, + transmit: { + send: (e,t)=>{} + }, + write: { + debug: Ke.bind(null, Ve(M || console, "debug"), "debug"), + info: Ke.bind(null, Ve(M || console, "info"), "info"), + warn: Ke.bind(null, Ve(M || console, "warn"), "warn"), + error: Ke.bind(null, Ve(M || console, "error"), "error"), + fatal: Ke.bind(null, Ve(M || console, "error"), "fatal") + } + } + }, u))], + Be && Be.sessionId === D ? Be.warn("Logger Singleton already setup, returning existing singleton") : (Be = Ae(Ue(c)).child({ + sessionId: D, + name: "hls" + }), + Be.qe = e=>Be.info(e), + Be.sessionId = D), + Be), + Lo = !1, + Ro && (delete window.$$stores, + delete window.$$queries), + this.hlsConfig.audioPrimingDelay = 0, + this.rootPlaylistService = (M = this.logger, + Oy = new wy(Ay,M), + Oy), + this.customUrlLoader = Mc(), + this.sessionDataLoader = new _p(f,Oc,this.customUrlLoader.load,this.logger); + var s, a, o, d, l, u = f.liveMaxLatencyDurationCount, c = f.liveSyncDurationCount; + if (ne(u) && ne(c) && u <= c) + throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"'); + if (ne(f.liveMaxLatencyDuration) && (f.liveMaxLatencyDuration <= f.liveSyncDuration || !ne(f.liveSyncDuration))) + throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"'); + const h = Xm(); + h.setHlsEntity({ + id: r, + config: f + }); + const p = hg() + , m = new gf(vf) + , g = (Ph = Ph || new Dh(Mh), + Ph); + this.accessLogInstance = new jf(this,r), + this.rtcService = new Uy(this,f,this.accessLogInstance,this.logger), + this.playerEvents = new bg(this,this.logger,this.rtcService); + const y = (D = this.platformService, + l = D, + (()=>{ + if ("function" == typeof matchMedia) { + var e = matchMedia("(dynamic-range: high)") + , t = matchMedia("bad query"); + if (e.media !== t.media) + return nn(Bi(e), en(e, "change")).pipe(ur(e=>e.matches)) + } + return Bi(!0) + } + )().pipe(Ja(e=>{ + l.updateSupportsHdr(e) + } + )).pipe(Ua(Ti))) + , v = this.mediaElement$.pipe((s = f, + o = (a = this).logger, + d = this.teardownWorker$, + e=>e.pipe(Ql.tag("playback.mediaElementServiceEpic.in"), Ra(e=>{ + if (!e) + return Bi(null); + const t = new hf(e,mf,s,a,o,d); + return t.openMediaSource(new MediaSource), + nn(Bi(t), t) + } + ), Ql.tag("playback.mediaElementServiceEpic.emit"))), wa()) + , S = this.itemQueue.activeItemById$.pipe(Ra(e=>e ? Vf(f, this.statsService, e, this.logger) : Ti)); + this.rpcService = (()=>{ + let e = f.createRPCService; + return f.enableWorker && null == e && (e = Cf), + null == e && (e = Of), + e(this.logger) + } + )(), + this.rpcClients = (M = this.rpcService, + { + crypto: new Ef(M), + mux: new If(M) + }); + var b, T, E, I, w, A, O, k, C, u = Cr([this.itemQueue.activeItemById$.pipe($y(f, this.logger, this.rootPlaylistService, m, this.statsService, this.playerEvents, this.rpcClients), Ja(e=>{ + var t = null == e ? void 0 : e.rootPlaylistQuery; + this.publicQueriesInternal$.next([t, null]), + this.iframeMachine = null == e ? void 0 : e.iframeMachine, + t && this.playerEvents.triggerManifestParsed(t) + } + )), v.pipe((E = this.itemQueue.removedItems$, + I = g, + w = f, + A = m, + k = (O = this).rtcService, + C = this.logger, + e=>Cr([((n,s,a,o,d,l,u)=>e.pipe(Ql.tag("[Keys] playback.keySystemServiceEpic.in"), Ra(r=>r ? new Ut(e=>{ + let t = new kh(n,r,a,o,d,l,u); + const i = nn(Bi(t), s.pipe(Kr(e=>t.removeKeysForItems(e)), Ua(Ti))).subscribe(e); + return function() { + u.warn("[Keys] playback.keySystemServiceEpic.unsubscribe"), + i.unsubscribe(), + t.destroy().subscribe(), + t = void 0 + } + } + ) : Bi(null)), Ql.tag("[Keys] playback.keySystemServiceEpic.emit")))(I, E, w, A, O, k, C), ((t,i,r)=>e.pipe(Ql.tag("playback.legibleServiceEpic.in"), Ra(e=>e ? nn(Bi(e = new Rp(e,t,i,r)), e) : Bi(null)), Ql.tag("playback.legibleServiceEpic.emit")))(w, O, C), e]).pipe(ur(([e,t,i])=>({ + keySystemAdapter: e, + legibleSystemAdapter: t, + mediaSink: i + })))), Ja(({keySystemAdapter: e, legibleSystemAdapter: t, mediaSink: i})=>{ + this.keySystemAdapter = e, + this.legibleSystemAdapter = t, + this.mediaElementAdapter = i + } + ))]).pipe(ur(([e,t])=>{ + var {keySystemAdapter: i, legibleSystemAdapter: r, mediaSink: n} = t; + if (!(e && i && r && n)) + return null; + var {rootPlaylistQuery: s, iframeMachine: t, mediaParser: e} = e; + return { + logger: this.logger, + config: f, + platformService: this.platformService, + statsService: this.statsService, + rtcService: this.rtcService, + rpcClients: this.rpcClients, + rootPlaylistService: this.rootPlaylistService, + rootPlaylistQuery: s, + mediaLibraryService: p, + keySystemAdapter: i, + legibleSystemAdapter: r, + mediaSink: n, + mediaParser: e, + iframeMachine: t, + customUrlLoader: this.customUrlLoader, + gaplessInstance: this + } + } + ), wa()).pipe(Ra(a=>{ + if (!a) + return Ti; + const {rootPlaylistQuery: t, mediaSink: e, mediaLibraryService: i} = a; + this.publicQueriesInternal$.next([t, e.mediaQuery]); + const n = e.mediaQuery + , r = Bi(a).pipe(ry()) + , s = t.rootPlaylistEntity$.pipe(Up(), Cs(1), Ja(()=>{ + this.commitEarlySelection(a.logger) + } + )) + , o = $l(Cr([n.haveEnough$, t.sessionData$]), ([e])=>!0 === e, 1).pipe(Ra(([,e])=>this.sessionDataLoader.loadSessionData(e)), Ja(e=>{ + this.rootPlaylistService.setSessionData(t.itemId, e) + } + ), Un(e=>(this.logger.error(e.message), + Ti))) + , d = Uf(t.itemId) + , l = function(l, e, u, r, t) { + const a = u.mediaQuery + , i = Zd([a.seekTo$, a.bufferedSegmentsByType$(cl.Variant)]).pipe(ur(([e,t])=>{ + const i = ne(null == e ? void 0 : e.pos) ? e.pos : a.currentTime + , r = t.find(e=>e.startPTS <= i && e.endPTS > i) + , n = a.getBufferInfo(i, l.maxBufferHole) + , s = a.getCombinedBufferInfo(i, l.maxBufferHole); + return { + pos: i, + sbTuple: n, + combined: s, + playingFrag: null !== (t = null == r ? void 0 : r.frag) && void 0 !== t ? t : null + } + } + )) + , n = Zd([e.getInFlightFragByType$(ul.Variant), e.enabledMediaOptionByType$(ul.Variant)]).pipe(Ra(([e,t])=>{ + var i = r.getQueryForOption(t); + return bn(Bi(e), Bi(t), i.mediaOptionDetails$) + } + ), ur(([e,t,i])=>[e, { + variant: t, + details: i + }])) + , s = Zd([t.bandwidthEstimate$, t.fragEstimate$, t.bufferEstimate$]); + return Zd([a.readyState$, n, i, a.desiredRate$, s]).pipe(Hi(Zi), ur(([,e,t,i,r])=>{ + var [n,s] = e + , [a,e,r] = r; + let o = e + , d = r; + return e && (o = { + maxDurationSec: ne(e.maxDurationSec) ? e.maxDurationSec : l.defaultTargetDuration, + avgParseTimeMs: ne(e.avgParseTimeMs) ? e.avgParseTimeMs : l.statDefaults.fragParseTimeMs + }), + r && (d = { + avgBufferCreateMs: ne(r.avgBufferCreateMs) ? r.avgBufferCreateMs : l.statDefaults.fragBufferCreationDelayMs, + avgInitFragAppendMs: ne(r.avgInitFragAppendMs) ? r.avgInitFragAppendMs : l.statDefaults.initFragAppendMs, + avgDataFragAppendMs: ne(r.avgDataFragAppendMs) ? r.avgDataFragAppendMs : l.statDefaults.dataFragAppendMs + }), + a = function(e, t, i, h, p, r, n, s) { + let a = function(e, t, i) { + const {pos: r, combined: n, playingFrag: s} = h; + if (0 === n.len) + return !1; + var a = 0 != p && 1 != p + , o = t.details + , d = o.fragments + , t = oy(o) + , i = Math.max(1, t * i); + let l = a || n.len >= t || n.len >= i; + a = d[o.fragments.length - 1], + i = d[0].start + o.totalduration; + let u = !1; + if (s) { + const c = _l.search(d, e=>s.discoSeqNum - e.discoSeqNum); + u = e && s.discoSeqNum !== e.discoSeqNum || null == c || Fp(c, s) + } + return l && o.liveOrEvent ? l = r <= i - a.duration : o.liveOrEvent || (l = l || i - t <= r), + l = l || u, + l + }(t, i, e.startTargetDurationFactor); + var o = h.combined; + if (!a && 0 < o.len) { + const p = oy(i.details); + a = function(n, e, t, i, r, s, a) { + var o = null === (o = h.sbTuple[ul.Variant]) || void 0 === o ? void 0 : o.buffered; + if ((null == o ? void 0 : o.len) >= t) + return 0; + if (!o || !n || !(n.start + n.duration > o.end && (n.start - o.end <= a || n.start <= o.end))) + return 1 / 0; + o = n.state; + let d = n.tstart + , l = 0; + switch (o) { + case "loading": + l += function(e, t) { + var {bwSample: i, duration: r} = n; + return i ? (r = ne(i.total) ? 8 * i.total : Math.ceil(r * e), + e = 8 * i.loaded, + r -= e, + i = e / (performance.now() - i.tfirst) * 1e3, + t = t.avgBandwidth, + r / (ne(i) ? Math.min(t, i) : t)) : 1 / 0 + }(e, i), + d = n.tstart + 1e3 * l; + case "loaded": + case "parsing": + l += function(e, t) { + return t = ne(r.avgParseTimeMs) ? t.avgParseTimeMs : 0, + performance.now() < e ? t / 1e3 : Math.max(0, t - (performance.now() - e)) / 1e3 + }(d, r), + d = n.tstart + 1e3 * l; + case "parsed": + case "appending": + l += function(e, t) { + return t = ne(s.avgDataFragAppendMs) ? t.avgDataFragAppendMs : 0, + performance.now() < e ? t / 1e3 : Math.max(0, t - (performance.now() - e)) / 1e3 + }(d, s); + break; + case "appended": + l = 0; + break; + default: + l = 1 / 0 + } + return l + }(t, i.variant.bitrate, p, r, n, s, e.maxBufferHole) <= o.len + } + return a + }(l, n, s, t, i, a, o, d), + u.haveEnough = a + } + ), ca(), Ra(([e,t])=>e !== t ? Bi(t) : Bi(t).pipe(ss(200))), Ja(e=>{} + ), Ua(Ti)) + }(f, (this.logger, + t), e, i, d) + , u = function() { + const {config: e, mediaSink: t, rootPlaylistQuery: i, mediaLibraryService: r, gaplessInstance: n} = a + , s = t.mediaQuery; + return Zd([i.enabledAVOptions$.pipe(Ra(e=>bn(...e.map(e=>kl(e) ? r.getQueryForOption(e).mediaOptionDetails$ : Bi(null))))), s.msReadyState$, s.updating$, s.isIframeRate$, s.isBufferedToEnd$(e.maxBufferHole, !n.inGaplessMode)]).pipe(Ql.tag("checkForEndOfStream"), an(([,e,t,i,r])=>"open" === e && !1 === t && !i && r), Ja(([e])=>{ + null != e[0] && e.every(e=>null == e || !1 === e.liveOrEvent && !1 === e.iframesOnly) && !n.inGaplessMode && t.endStream() + } + ), Ua(Ti)) + }() + , c = function() { + const {config: o, iframeMachine: d, mediaSink: t} = a + , l = t.mediaQuery; + return l.desiredRate$.pipe(Ra(a=>jp(a) ? vn(0, Math.abs(1e3 / a)).pipe(ur(()=>{ + let e = null; + const t = l.seekable; + if (!d.isStarted || t.length < 1) + return e; + var i = d.iframeClockTimeSeconds + , r = o.leftMediaTimeToAutoPause + , n = t.start(0) + , s = t.end(t.length - 1); + return 1 < a && s - i < r ? e = { + newRate: 0, + autoPausedRestartTime: s - r + } : a < 0 && i - n < a / -2 && (e = { + newRate: 1, + autoPausedRestartTime: n + }), + e + } + ), Up(), Ja(e=>{ + t.desiredRate = e.newRate, + t.autoPausedRestartTime = e.autoPausedRestartTime + } + ), Ua(Ti)) : Ti)) + }() + , h = (t=>{ + const {mediaSink: e, config: i} = t + , r = e.mediaQuery; + return !0 !== i.enableIFramePreloading ? Ti : r.desiredRate$.pipe(ur(jp), Es(), Ra(e=>e ? Ti : function(r) { + const {mediaSink: e, rootPlaylistQuery: n, mediaLibraryService: s, logger: a, config: o} = r + , d = e.mediaQuery; + return d.waterLevelChangedForType$(cl.Variant).pipe(an(e=>e === kp.AboveHighWater), Ls(()=>n.enabledMediaOptionByType$(ul.Variant).pipe(Ra(e=>{ + var t = n.mediaOptionListQueries[ul.Variant].hasIframes + , i = null !== (i = null === (i = s.getQuery().getEntity(n.itemId)) || void 0 === i ? void 0 : i.liveOrEvent) && void 0 !== i && i; + return !t || i ? Ti : (i = Uf(n.itemId), + e = pg(e), + i = Dg(!0, o, n, e, d, i, a), + i = n.variantMediaOptionById(i.variantMediaOption), + fg(r, i)) + } + ), Ra(e=>{ + var t = og(d.currentTime, n.discoSeqNum, 0, e, []); + return null !== (e = null == t ? void 0 : t.foundFrag) && void 0 !== e && e.mediaFragment ? (t = t.foundFrag.mediaFragment, + nn(Sg(r, t.keyTagInfo, { + itemId: t.itemId, + mediaOptionId: t.mediaOptionId + }), mg(r, t))) : (a.warn(Vg, "Unable to find fragment for iframe prefetch"), + Ti) + } + ), Cs(1), Ua(Ti), Un(e=>(a.error(Vg, `got error ${e.message} in prefetch`), + Ti)), $s(()=>{} + )))) + }(t))) + } + )(a) + , p = [s, r, o, l, $l(Zd([n.gotPlaying$, n.gotLoadStart$, n.readyState$]), ([e,t,i])=>!0 === e || !0 === t || 1 <= i).pipe(Ra(()=>n.ended$), Ra(e=>vn(0, e ? void 0 : 1e3)), Ja(()=>{ + this.playbackInfo(f, n) + } + )), c, h, n.timeupdate$.pipe(ur(e=>{ + if (this.inGaplessMode && this.isPreloading && ne(this.loadingItem.itemStartOffset) && e >= this.loadingItem.itemStartOffset) { + const e = this.itemQueue.playingItem.itemId + , t = this.itemQueue.loadingItem.itemId + , i = { + prevItemId: e, + nextItemId: t, + nextStartTime: this.loadingItem.itemStartOffset, + nextDuration: n.msDuration - this.loadingItem.itemStartOffset + }; + this.itemQueue.updatePlayingItemId(), + this.trigger(P.ITEM_TRANSITIONED, i), + this.rtcService.itemTransitioned(e, t) + } + } + )), this.updateLiveSeekableRange(t, e), u]; + if (f.enablePerformanceLogging) { + const a = bn(...Ml.map(r=>t.getInFlightFragByType$(r).pipe(Up(), Es((e,t)=>e.state === t.state), So(n.bufferedRangeTuple$), Ja(([e,t])=>{ + const i = Object.assign(Object.assign({}, e), { + name: Cl[r], + buffered: void 0 + }); + "appended" === e.state && (i.buffered = t) + } + )))); + p.push(a) + } + return nn(...p) + } + )), c = this.itemQueue.removedItems$.pipe(od(e=>{ + var t; + t = e, + hg().remove(t), + this.rootPlaylistService.removeItems(e) + } + )), D = h.getQuery().userSeek$.pipe((b = this.itemQueue, + T = this.rootPlaylistService, + e=>e.pipe(Up(), Ra(e=>Jr([Bi(e), b.activeItemById$.pipe(Up(), Ra(e=>T.getQueryForId(e.itemId).rootPlaylistEntity$), Cs(1))])), ur(([e,t])=>(T.setPendingSeek(t.itemId, e), + e))))), M = h.getQuery().selectEntityAction(To.Add).pipe(Ja(()=>{ + this.logger.warn(`new Hls instance added while old one still active sessionId:${r}`) + } + )); + nn(v.pipe(Un(e=>{ + var t; + return e instanceof MediaError && (null === (t = this.rtcService) || void 0 === t || t.handleMediaElementError(e)), + Ti + } + )), nn(y, D, S, c, u, this.teardownWorker$).pipe(Un(e=>this._handleError(e)))).pipe($s(()=>{ + var e, t; + try { + this.detachMedia(), + this.trigger(P.DESTROYING), + this.playerEvents.destroy(), + null === (e = this.accessLogInstance) || void 0 === e || e.destroy(), + null === (t = this.rtcService) || void 0 === t || t.destroy(), + hg().clear(), + this.rootPlaylistService.removeAll(), + this.itemQueue.clearQueue(), + h.removeEntity(this.sessionID) + } catch (e) { + this.logger.error(`Got error in finalize ${e.message}`) + } + } + ), $a(hn(this.destroy$, M))).subscribe() + } + get publicQueries$() { + return this.publicQueriesInternal$.pipe(an(e=>Boolean(e) && Boolean(e[0]) && Boolean(e[1]))) + } + get _activeRootQuery() { + var e = this.publicQueriesInternal$.value; + return null !== (e = null == e ? void 0 : e[0]) && void 0 !== e ? e : null + } + get _mediaElementQuery() { + var e = this.publicQueriesInternal$.value; + return null !== (e = null == e ? void 0 : e[1]) && void 0 !== e ? e : null + } + static get version() { + return "2.141.0" + } + static get Events() { + return P + } + get Events() { + return Vy.Events + } + static get DefaultConfig() { + return de(Al) + } + get DefaultConfig() { + return Vy.DefaultConfig + } + static isSupported() { + try { + const e = window.MediaSource || window.WebKitMediaSource + , t = window.SourceBuffer || window.WebKitSourceBuffer + , i = e && "function" == typeof e.isTypeSupported && e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"') + , r = !t || t.prototype && "function" == typeof t.prototype.appendBuffer && "function" == typeof t.prototype.remove; + return !!i && !!r + } catch (e) { + return !1 + } + } + commitEarlySelection(e) { + var t = this.itemQueue.earlyAudioSelection; + ne(t) && (this.audioSelectedPersistentID = t, + this.itemQueue.earlyAudioSelection = null), + ne(t = this.itemQueue.earlySubtitleSelection) && (this.subtitleSelectedPersistentID = t, + this.itemQueue.earlySubtitleSelection = null) + } + _handleError(i) { + var r; + try { + let t, e = i.message; + if (this.logger.error(`Got unhandled or fatal error ${e}`, i), + null === (r = this.rtcService) || void 0 === r || r.handleError(i), + t = i instanceof p ? i : new V(!0,i.message,$.InternalError), + t.fatal && this.isPreloading && (this.logger.warn("Fatal error seen while preloading, calling dequeueSource"), + this.dequeueSource("FatalErrorWhileLoading")), + t.fatal) { + let e = Ul; + if (this.mediaElementAdapter) { + const r = this.mediaElementAdapter.mediaQuery + , n = r.getCombinedBufferInfo(r.currentTime, 0); + 0 < (null == n ? void 0 : n.len) && (e = $l(this.mediaElementAdapter.mediaQuery.stallInfo$, e=>null != e).pipe(ur(()=>{} + ))) + } + return e.pipe(Ra(()=>(this.trigger(P.ERROR, t), + Ti))) + } + this.trigger(P.ERROR, t) + } catch (i) { + throw this.logger.error(`Error thrown inside _handleError ${i.message}`, i), + i + } + return Ti + } + updateLiveSeekableRange(e, t) { + return e.enabledMediaOptionByType$(ul.Variant).pipe(Ra(e=>{ + const t = pg(e); + let i = 0; + return t.mediaOptionDetailsEntity$.pipe(Up(), an(e=>{ + var t = null !== e.stats && !1 === e.detailsLoading && e.lastUpdateMillis > i; + return i = null !== (e = e.lastUpdateMillis) && void 0 !== e ? e : 0, + t + } + )) + } + ), Ra(e=>(0 === e.unchangedCount && (e.mediaOptionDetails.liveOrEvent ? t.updateLiveSeekableRange(e.mediaOptionDetails) : t.clearLiveSeekableRange()), + Ti))) + } + playbackInfo(i, r) { + const n = this.mediaElement$.getValue(); + if (n) { + const s = n.readyState >= n.HAVE_FUTURE_DATA + , a = { + readyToPlay: s, + playbackLikelyToKeepUp: r.haveEnough && s, + rate: n.playbackRate, + paused: n.paused, + position: n.currentTime, + duration: n.duration, + seekableTimeRanges: Kf.timeRangeToArray(n.seekable), + loadedTimeRanges: Kf.timeRangeToArray(n.buffered) + }; + let e = 0 + , t = 0; + if (Kf.isHtmlVideoElement(n)) { + const o = n.getVideoPlaybackQuality; + if (o && typeof o == typeof Function) { + const o = n.getVideoPlaybackQuality(); + e = a.droppedVideoFrames = o.droppedVideoFrames, + a.corruptedVideoFrames = o.corruptedVideoFrames, + a.totalVideoFrames = o.totalVideoFrames, + t = a.totalVideoFrames - e + } + } else + Kf.isWebkitMediaElement(n) && (e = a.droppedVideoFrames = n.webkitDroppedFrameCount, + t = a.decodedFrameCount = n.webkitDecodedFrameCount); + i.enablePerformanceLogging && r.getCombinedMediaSourceBufferInfo(i.maxBufferHole), + null === (i = this.rtcService) || void 0 === i || i.handlePlaybackInfo(e, t) + } + } + get currentItem() { + return this.isPreloading ? this.playingItem : this.itemQueue.activeItem + } + get realCurrentTime() { + var e, t = this._mediaElementQuery; + if (this.iframeMachine && this.iframeMachine.isStarted) { + const r = t.mediaElementDuration + , e = this.iframeMachine.iframeClockTimeSeconds; + return e > r ? r : e + } + let i = null !== (e = null == t ? void 0 : t.currentTime) && void 0 !== e ? e : NaN; + return ne(i) && ne(null === (e = this.playingItem) || void 0 === e ? void 0 : e.itemStartOffset) && (i -= this.playingItem.itemStartOffset), + i + } + set realCurrentTime(e) { + var t; + ne(null === (t = this.playingItem) || void 0 === t ? void 0 : t.itemStartOffset) && (e += this.playingItem.itemStartOffset), + this.seekTo = e + } + get bufferedDuration() { + var e; + const t = this._mediaElementQuery; + return null !== (e = null == t ? void 0 : t.getBufferedDuration()) && void 0 !== e ? e : 0 + } + get sessionData() { + var e = this._activeRootQuery; + return null == e ? void 0 : e.sessionData + } + get supportedFrameRates() { + const e = this.hlsConfig.trickPlaybackConfig.enabled + , t = [0, 1] + , i = this._activeRootQuery + , r = hg().getQuery(); + return e && i && r.getEntity(i.itemId) && !1 === r.getEntity(i.itemId).liveOrEvent && t.push(8, 24, 48, 96), + t + } + loadSource(e, i, t) { + var r; + if ("playready" === this.config.keySystemPreference && !this.config.enablePlayReadyKeySystem) + throw new V(!0,"Playready key system is not supported now",$.UnsupportedKeySystemError); + if (!e || !e.trim().length) + throw new V(!0,"Empty loadSource url",$.EmptyLoadSourceError); + e = fl.buildAbsoluteURL(window.location.href, e, { + alwaysNormalize: !0 + }), + i && Object.keys(i).filter(e=>0 <= ["itemId", "streamID"].indexOf(e)).reduce((e,t)=>t in i ? Object.assign(e, { + [t]: i[t] + }) : e, {}), + null !== (r = null == i ? void 0 : i.appData) && void 0 !== r && r.reportingAgent && (this.reportingAgent = i.appData.reportingAgent), + null != i && i.userInfo && (this.userInfo = i.userInfo), + null === (r = this.accessLogInstance) || void 0 === r || r.setupReporter(i.appData), + null != i && i.platformInfo && this.platformService.updatePlatformInfo(i.platformInfo), + this.itemQueue.setQueueItem(`item:${null !== (r = null == i ? void 0 : i.itemId) && void 0 !== r ? r : Jd()}`, e, t, null == i ? void 0 : i.platformInfo, null === (t = null == i ? void 0 : i.appData) || void 0 === t ? void 0 : t.serviceName), + Xm().setStartTime(void 0) + } + queueSource(e, t, i) { + var r; + null != t && t.userInfo && (this.userInfo = t.userInfo); + var n = null === (r = this._mediaElementQuery) || void 0 === r ? void 0 : r.getCombinedBufferInfo(null === (n = this._mediaElementQuery) || void 0 === n ? void 0 : n.currentTime, 0); + let s = 0; + n && (s = n.end), + this.itemQueue.addQueueItem(`item:${null !== (n = null == t ? void 0 : t.itemId) && void 0 !== n ? n : Jd()}`, e, i, null == t ? void 0 : t.platformInfo, s, null === (t = null == t ? void 0 : t.appData) || void 0 === t ? void 0 : t.serviceName) + } + dequeueSource(e="ApplicationInitiated") { + if (!this.isPreloading && "InvalidFormat" === e && this.isFirstItem) + return this.logger.error("First item has invalid format for gapless. Probably video. Disabling gapless."), + void (this.gaplessCapable = !1); + var t, i; + this.isPreloading ? (t = this.loadingItem.url, + i = this.loadingItem.itemId, + this.mediaElementAdapter.flushData(cl.Variant, this.loadingItem.itemStartOffset, 1 / 0), + this.mediaElementAdapter.msDuration = this.loadingItem.itemStartOffset, + this.itemQueue.resetLoadingItem(), + "InvalidFormat" !== e && "FatalErrorWhileLoading" !== e || (this.gaplessCapable = !1), + this.triggerItemEvicted({ + url: t, + itemId: i + }, e)) : this.logger.warn(`Nothing to dequeue, no item is preloading dequeue reason: ${e}`) + } + triggerItemEvicted(e, t) { + null !== e ? (t = { + url: e.url, + evictedItemId: e.itemId, + reason: t + }, + Object.assign(Object.assign({}, t), { + url: oe(e.url) + }), + this.trigger(P.ITEM_EVICTED, t)) : this.logger.error("dequeueSource called with no playing or loading item") + } + endSource() { + this.gaplessCapable = !1, + this.isPreloading && (this.logger.warn("EndSource called during preloading. Loading item will be removed"), + this.mediaElementAdapter.flushData(cl.Variant, this.loadingItem.itemStartOffset, 1 / 0), + this.mediaElementAdapter.msDuration = this.loadingItem.itemStartOffset, + this.itemQueue.resetLoadingItem()) + } + get inGaplessMode() { + return this.config.gapless && this.gaplessCapable + } + get isPreloading() { + return this.itemQueue.isPreloading() + } + get isFirstItem() { + return this.itemQueue.isFirstItem + } + get loadingItem() { + return this.itemQueue.loadingItem + } + get playingItem() { + return this.itemQueue.playingItem + } + get url() { + return this.playingItem ? this.playingItem.url : this.loadingItem ? this.loadingItem.url : void 0 + } + destroy() { + var e; + return this.destroy$.next(), + null != this.rpcService && this.rpcService.teardown(), + null !== (e = this.encryptedMediaElement$.getValue()) && void 0 !== e && e.updating ? this.encryptedMediaElement$.getValue().done$.pipe(an(e=>e), Cs(2), Ra(e=>(this.encryptedMediaElement$.next(null), + this.teardownWorker$.complete(), + this.teardownWorker$))) : (this.encryptedMediaElement$.next(null), + this.teardownWorker$.complete(), + this.teardownWorker$) + } + attachMedia(e) { + this.trigger(P.MEDIA_ATTACHING, { + media: e + }), + this.mediaElement$.next(e), + this.encryptedMediaElement$.next(e), + this.trigger(P.MEDIA_ATTACHED, { + media: e + }) + } + detachMedia() { + var e; + this.mediaElement$.getValue() && (this.trigger(P.MEDIA_DETACHING), + null === (e = this.rtcService) || void 0 === e || e.detachMedia(), + this.mediaElement$.next(null), + this.trigger(P.MEDIA_DETACHED)) + } + handleResolvedUri(e, t) { + this.customUrlLoader.setCustomUrlResponse(e, { + uri: t.uri, + response: t + }) + } + get variantOptions$() { + return this.publicQueries$.pipe(Ra(e=>{ + const [t,i] = e; + return Cr([t.preferredMediaOptions$, i.desiredRate$]).pipe(ur(([e])=>{ + const t = i.isIframeRate; + return e[ul.Variant].filter(e=>(null !== (e = e.iframes) && void 0 !== e && e) === t).map(e=>e.mediaOptionId) + } + )) + } + )) + } + get altAudioOptions$() { + return this.publicQueries$.pipe(Ra(e=>{ + var [e] = e; + return Bi(e.audioMediaSelectionOptions) + } + )) + } + get subtitleOptions$() { + return this.publicQueries$.pipe(Ra(e=>{ + var [e] = e; + return Bi([{ + MediaSelectionOptionsName: "Disable subtitle", + MediaSelectionOptionsPersistentID: -1 + }].concat(e.subtitleMediaSelectionOptions)) + } + )) + } + get levels() { + var e; + return null !== (e = null === (e = this._activeRootQuery) || void 0 === e ? void 0 : e.preferredMediaOptions[ul.Variant]) && void 0 !== e ? e : [] + } + get audioTracks() { + var e; + return null !== (e = null === (e = this._activeRootQuery) || void 0 === e ? void 0 : e.preferredMediaOptions[ul.AltAudio]) && void 0 !== e ? e : [] + } + get audioMediaOptions() { + var e; + return null !== (e = null === (e = this._activeRootQuery) || void 0 === e ? void 0 : e.audioMediaSelectionOptions) && void 0 !== e ? e : [] + } + get subtitleMediaOptions() { + var e; + return null !== (e = null === (e = this._activeRootQuery) || void 0 === e ? void 0 : e.subtitleMediaSelectionOptions) && void 0 !== e ? e : [] + } + get playbackLikelyToKeepUp() { + var e; + return null !== (e = null === (e = this._mediaElementQuery) || void 0 === e ? void 0 : e.playbackLikelyToKeepUp) && void 0 !== e && e + } + get duration$() { + return this.publicQueries$.pipe(Ra(e=>{ + var [,e] = e; + return e.mediaElementDuration$ + } + )) + } + get timeupdate$() { + return this.publicQueries$.pipe(Ra(e=>{ + var [,e] = e; + return e.timeupdate$ + } + )) + } + get playing$() { + return this.publicQueries$.pipe(Ra(e=>{ + var [,e] = e; + return e.gotPlaying$ + } + )) + } + get desiredRate$() { + return this.publicQueries$.pipe(Ra(e=>{ + var [,e] = e; + return e.desiredRate$ + } + )) + } + set desiredRate(e) { + null != e && this.setRate(e) + } + get desiredRate() { + var e; + return null !== (e = null === (e = this._mediaElementQuery) || void 0 === e ? void 0 : e.desiredRate) && void 0 !== e ? e : 0 + } + get effectiveRate() { + var e; + return null !== (e = null === (e = this._mediaElementQuery) || void 0 === e ? void 0 : e.effectiveRate) && void 0 !== e ? e : 0 + } + get iframeMode() { + var e; + return null !== (e = null === (e = this._mediaElementQuery) || void 0 === e ? void 0 : e.isIframeRate) && void 0 !== e && e + } + get accessLog() { + return this.accessLogInstance && this._activeRootQuery ? this.accessLogInstance.getAccessLog(this._activeRootQuery.itemId) : [] + } + get errorLog() { + return this.accessLogInstance ? this.accessLogInstance.errorLog : [] + } + setRate(e) { + const t = this.logger.child({ + name: "iframes" + }); + if (e === this.desiredRate) + return -2; + if (!this.mediaElementAdapter || isNaN(e)) + return t.warn("unable to switch to rate, missing adapter or newRate isNaN"), + -1; + e = Number(e); + const i = Math.abs(e); + if (!this.supportedFrameRates.some(e=>e === i)) + return t.warn(`unsupported rate(${e})`), + -3; + if (jp(e)) { + const e = this._activeRootQuery; + if (null == e || !e.mediaOptionListQueries[ul.Variant].hasIframes) + return t.warn("no iframe variants available"), + -1 + } + return this.mediaElementAdapter.desiredRate = e, + 0 + } + get sessionData$() { + return this.publicQueries$.pipe(Ra(([e])=>e.sessionData$)) + } + set skip(e) { + this.mediaElementAdapter.skip = e + } + gaplessSeekTo(e) { + e < this.playingItem.itemStartOffset && (this.logger.warn(`[Gapless] Seeking past track boundary oldSeek=${e}, adjustedSeek=${this.playingItem.itemStartOffset}`), + e = this.playingItem.itemStartOffset), + this.isPreloading && (e > this.loadingItem.itemStartOffset && (this.logger.warn(`[Gapless] Seeking past track boundary oldSeek=${e}, adjustedSeek=${this.loadingItem.itemStartOffset}`), + e = this.loadingItem.itemStartOffset), + e < this._mediaElementQuery.getBufferInfo(this._mediaElementQuery.currentTime, this.config.maxBufferHole)[0].buffered.start && this.dequeueSource("SeekToUnbufferedTimeRanges")), + Xm().setUserSeek(e) + } + set seekTo(e) { + var t = Number(e); + ne(t) ? this.inGaplessMode ? this.gaplessSeekTo(t) : Xm().setUserSeek(t) : this.logger.error(`[seek] got invalid seek value ${e}`) + } + seekToDate(e) { + Xm().setUserSeek(e) + } + get availableProgramDateTime() { + return new Map(this._currentDateToMediaTimeTuple) + } + get _currentDateToMediaTimeTuple() { + if (!this._activeRootQuery) + return []; + var e = this._activeRootQuery.enabledMediaOptionKeys[ul.Variant]; + return kl(e) && null !== (e = null === (e = hg().getQueryForOption(e).mediaOptionDetails) || void 0 === e ? void 0 : e.dateMediaTimePairs) && void 0 !== e ? e : [] + } + get playingDate() { + return Gg(this._currentDateToMediaTimeTuple, this.realCurrentTime) + } + set variantId(e) {} + set audioSelectedPersistentID(e) { + var t = this._activeRootQuery; + null != t && t.preferredMediaOptions[ul.AltAudio] ? (t = t.itemId, + this.rootPlaylistService.setEnabledMediaOptionTupleWithMatchedGroups(t, ul.AltAudio, e, { + userInitiated: !0 + })) : !ne(e) || e < 0 || (this.logger.warn(`[audio] no active item, defer audio track selection: persistentId ${e}`), + this.itemQueue.earlyAudioSelection = e) + } + get audioSelectedPersistentID() { + var e; + return this._activeRootQuery ? null === (e = this._activeRootQuery.enabledAlternateMediaOptionByType(ul.AltAudio)) || void 0 === e ? void 0 : e.persistentID : this.itemQueue.earlyAudioSelection + } + set subtitleSelectedPersistentID(e) { + var t = this._activeRootQuery + , i = null == t ? void 0 : t.preferredMediaOptions[ul.Subtitle]; + i ? (t = t.itemId, + 0 === i.length && (!ne(e) || e < 0) || (ne(e) && -1 !== e ? this.rootPlaylistService.setEnabledMediaOptionTupleWithMatchedGroups(t, ul.Subtitle, e) : this.rootPlaylistService.setEnabledMediaOptionByType(t, ul.Subtitle, Ol))) : !ne(e) || e < 0 || (this.logger.warn(`[subtitle] no active item, defer subtitle track selection: persistentId ${e}`), + this.itemQueue.earlySubtitleSelection = e) + } + get subtitleSelectedPersistentID() { + var e; + return this._activeRootQuery ? null === (e = this._activeRootQuery.enabledAlternateMediaOptionByType(ul.Subtitle)) || void 0 === e ? void 0 : e.persistentID : this.itemQueue.earlySubtitleSelection + } + get selectedMediaArray() { + const e = this._activeRootQuery; + if (!e) + return []; + const t = [] + , i = e.enabledAlternateMediaOptionByType(ul.AltAudio) + , r = e.enabledAlternateMediaOptionByType(ul.Subtitle) + , n = i ? e.audioMediaSelectionOptions.find(e=>e.MediaSelectionOptionsPersistentID === i.persistentID) : void 0 + , s = r ? e.subtitleMediaSelectionOptions.find(e=>e.MediaSelectionOptionsPersistentID === r.persistentID) : void 0; + if (n) { + const e = { + MediaSelectionGroupMediaType: pl.AUDIO, + MediaSelectionOptionsPersistentID: n.MediaSelectionOptionsPersistentID + }; + t.push(e) + } + if (s) { + let e = hl.NO; + s.MediaSelectionOptionsDisplaysNonForcedSubtitles && (e = s.MediaSelectionOptionsDisplaysNonForcedSubtitles); + const i = { + MediaSelectionGroupMediaType: pl.SUBTITLE, + MediaSelectionOptionsDisplaysNonForcedSubtitles: e, + MediaSelectionOptionsPersistentID: s.MediaSelectionOptionsPersistentID + }; + t.push(i) + } + return t + } + set selectedMediaArray(e) { + this._activeRootQuery ? e.forEach(e=>{ + e.MediaSelectionGroupMediaType === pl.AUDIO || e.MediaSelectionOptionsMediaType === pl.AUDIO ? this.audioSelectedPersistentID = e.MediaSelectionOptionsPersistentID : e.MediaSelectionGroupMediaType !== pl.SUBTITLE && e.MediaSelectionOptionsMediaType !== pl.SUBTITLE && e.MediaSelectionOptionsMediaType !== pl.CLOSEDCAPTION || (this.subtitleSelectedPersistentID = e.MediaSelectionOptionsPersistentID) + } + ) : this.logger.warn("selectedMediaArray: no active item") + } + getHTMLTextTrack(e) { + return this.legibleSystemAdapter.getExistingHTMLTextTrackWithSubtitleTrackId(e) + } + get keysystems() { + return this.keySystemAdapter.availableKeySystems + } + setProtectionData(e) { + this.keySystemAdapter.initialize(e) + } + generateKeyRequest(e, t) { + this.keySystemAdapter.generateRequest(e, t), + this.rtcService.licenseChallengeReceived({ + keyuri: e + }) + } + setLicenseResponse(e, t) { + this.keySystemAdapter.setLicenseResponse(e, t) + } + get bufferInfo$() { + return this.publicQueries$.pipe(Ra(e=>{ + const [,t] = e + , i = Xm().getQuery().currentConfig; + return nn(t.timeupdate$, t.bufferedRangeTuple$).pipe(so(1e3), ur(()=>{ + var e = t.currentTime; + return { + combined: t.getCombinedBufferInfo(e, i.maxBufferHole), + sbTuple: t.getBufferInfo(e, i.maxBufferHole) + } + } + )) + } + )) + } + bufferInfoByType$(t) { + return this.bufferInfo$.pipe(ur(e=>null === (e = null == e ? void 0 : e.sbTuple) || void 0 === e ? void 0 : e[t])) + } + levelWithPersistentId(e) { + this.logger.warn("levelWithPersistentId is deprecated") + } + startLoad(e) { + this.logger.warn("startLoad is deprecated"), + ne(e) && (this.logger.warn(`[seek] Seeking to ${null == e ? void 0 : e.toFixed(3)} via deprecated "startLoad" method. Use loadSource(url, options, startTime) instead.`), + this.seekTo = e) + } + stopLoad() {} + get config() { + return Object.assign(Object.assign({}, de(Ym())), { + set startPosition(e) { + qe().warn(`Setting start position ${null == e ? void 0 : e.toFixed(3)} using deprecated method`), + Xm().setStartTime(e) + } + }) + } + get media() { + return null != this.mediaElement$.value + } + set subtitleDisplay(e) { + this.logger.warn(`set subtitleDisplay ${e} is deprecated`) + } + } + } + , + "object" == typeof exports && "undefined" != typeof module ? module.exports = t() : "function" == typeof define && define.amd ? define(t) : (e = "undefined" != typeof globalThis ? globalThis : e || jy).Hls = t() +}(!1); +//# sourceMappingURL=hls.js.map + diff --git a/resources/cider-ui-tests/index.js b/resources/cider-ui-tests/index.js index 9647d122..715d0e0b 100644 --- a/resources/cider-ui-tests/index.js +++ b/resources/cider-ui-tests/index.js @@ -263,16 +263,17 @@ const app = new Vue({ let type = (self.mk.nowPlayingItem != null) ? self.mk.nowPlayingItem["type"] ?? '' : ''; if (type.includes("musicVideo") || type.includes("uploadedVideo")) { - document.getElementById("apple-music-video-container").style.display = "block"; - // app.chrome.topChromeVisible = false + document.getElementById("apple-music-video-container").style.display = "block"; + // app.chrome.topChromeVisible = false } else { document.getElementById("apple-music-video-container").style.display = "none"; - // app.chrome.topChromeVisible = true + // app.chrome.topChromeVisible = true + self.chrome.artworkReady = false + + app.getNowPlayingArtwork(42); + app.getNowPlayingArtworkBG(32); } - self.chrome.artworkReady = false self.lyrics = [] - app.getNowPlayingArtwork(42); - app.getNowPlayingArtworkBG(32); app.loadLyrics() }) @@ -499,7 +500,7 @@ const app = new Vue({ }, exitMV() { - MusicKit.getInstance().stop() + MusicKit.getInstance().stop(); document.getElementById("apple-music-video-container").style.display = "none"; }, getArtistInfo(id, isLibrary) { diff --git a/resources/cider-ui-tests/musickit.js b/resources/cider-ui-tests/musickit.js new file mode 100644 index 00000000..c701809a --- /dev/null +++ b/resources/cider-ui-tests/musickit.js @@ -0,0 +1,19293 @@ +!function(e, s) { + "object" == typeof exports && "undefined" != typeof module ? s(exports) : "function" == typeof define && define.amd ? define(["exports"], s) : s((e = "undefined" != typeof globalThis ? globalThis : e || self).MusicKit = {}) +}(this, (function(e) { + "use strict"; + var s = void 0 !== typeof self ? self : this; + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + function __decorate$2(e, s, n, d) { + var h, p = arguments.length, y = p < 3 ? s : null === d ? d = Object.getOwnPropertyDescriptor(s, n) : d; + if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) + y = Reflect.decorate(e, s, n, d); + else + for (var m = e.length - 1; m >= 0; m--) + (h = e[m]) && (y = (p < 3 ? h(y) : p > 3 ? h(s, n, y) : h(s, n)) || y); + return p > 3 && y && Object.defineProperty(s, n, y), + y + } + function __metadata$2(e, s) { + if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) + return Reflect.metadata(e, s) + } + function __awaiter$3(e, s, n, d) { + return new (n || (n = Promise))((function(h, p) { + function fulfilled(e) { + try { + step(d.next(e)) + } catch (bt) { + p(bt) + } + } + function rejected(e) { + try { + step(d.throw(e)) + } catch (bt) { + p(bt) + } + } + function step(e) { + var s; + e.done ? h(e.value) : (s = e.value, + s instanceof n ? s : new n((function(e) { + e(s) + } + ))).then(fulfilled, rejected) + } + step((d = d.apply(e, s || [])).next()) + } + )) + } + function formatArtworkURL(e, s, n) { + return s = s || e.height || 100, + n = n || e.width || 100, + window.devicePixelRatio >= 1.5 && (n *= 2, + s *= 2), + e.url.replace("{h}", "" + s).replace("{w}", "" + n).replace("{f}", "jpeg") + } + const K = ()=>{} + , asAsync = e=>{ + e.then(K, K) + } + , n = K; + function isLive(e) { + return !!e && !!e.attributes && !!e.attributes.isLive + } + function isStream$1(e) { + var s, n; + return "stream" === (null === (n = null === (s = null == e ? void 0 : e.attributes) || void 0 === s ? void 0 : s.playParams) || void 0 === n ? void 0 : n.format) + } + function isLiveRadioStation(e) { + return isLive(e) && isStream$1(e) + } + function isLiveRadioKind(e, s) { + var n; + return isLiveRadioStation(e) && (null === (n = e.attributes) || void 0 === n ? void 0 : n.mediaKind) === s + } + function isBroadcastRadio(e) { + return isLive(e) && isStream$1(e) && void 0 !== e.attributes.stationProviderName && "Shoutcast" === e.attributes.streamingRadioSubType + } + function getFilterFromFlags(e) { + const s = e.includes("radio-live") + , n = e.includes("radio-aod") + , d = e.includes("radio-broadcast"); + return e=>(!s || s && !isLiveRadioStation(e)) && (!n || n && !function(e) { + return !isLive(e) && isStream$1(e) && "Episode" === e.attributes.streamingRadioSubType + }(e)) && (!d || d && !isBroadcastRadio(e)) + } + const d = { + album: "albums", + albums: "albums", + artist: "artists", + artists: "artists", + song: "songs", + songs: "songs" + }; + function normalizeContentType(e) { + let s = d[e]; + return s || (s = e.replace(/_|[A-Z]/g, (e,s)=>"_" === e ? "-" : (e = e.toLowerCase(), + 0 === s ? e : "-" + e)), + e.endsWith("y") ? s = s.substring(0, s.length - 1) + "ies" : s.endsWith("s") || (s += "s"), + d[e] = s, + s) + } + const h = { + 400: "REQUEST_ERROR", + 401: "UNAUTHORIZED_ERROR", + 403: "ACCESS_DENIED", + 404: "NOT_FOUND", + 405: "NOT_FOUND", + 413: "REQUEST_ERROR", + 414: "REQUEST_ERROR", + 429: "QUOTA_EXCEEDED", + 500: "SERVER_ERROR", + 501: "NOT_FOUND", + 503: "SERVICE_UNAVAILABLE" + } + , p = { + "-1004": "DEVICE_LIMIT", + 1010: h[404], + 2002: "AUTHORIZATION_ERROR", + 2034: "TOKEN_EXPIRED", + 3059: "DEVICE_LIMIT", + 3063: "SUBSCRIPTION_ERROR", + 3076: "CONTENT_UNAVAILABLE", + 3082: "CONTENT_RESTRICTED", + 3084: "STREAM_UPSELL", + 5002: h[500], + 180202: "PLAYREADY_CBC_ENCRYPTION_ERROR", + 190121: "WIDEVINE_CDM_EXPIRED" + } + , y = [] + , m = new Set(["UNSUPPORTED_ERROR", "CONTENT_EQUIVALENT", "CONTENT_UNAVAILABLE", "CONTENT_UNSUPPORTED", "SERVER_ERROR", "SUBSCRIPTION_ERROR"]); + class MKError extends Error { + constructor(e, s) { + super(), + this.errorCode = "UNKNOWN_ERROR", + e && m.has(e) ? (this.name = this.errorCode = e, + this.message = this.description = s || e) : s || "string" != typeof e ? (this.name = this.errorCode = e || "UNKNOWN_ERROR", + s && (this.message = this.description = s)) : (this.name = this.errorCode = "UNKNOWN_ERROR", + this.message = this.description = e), + y.push(this), + Error.captureStackTrace && Error.captureStackTrace(this, MKError) + } + static get errors() { + return y + } + static playActivityError(e) { + return new this("PLAY_ACTIVITY",e) + } + static parseError(e) { + return new this("PARSE_ERROR",e) + } + static responseError(e) { + const {status: s, statusText: n} = e + , d = new this(h[s] || "NETWORK_ERROR",n || "" + s); + return d.data = e, + d + } + static serverError(e) { + let {status: s, dialog: n, failureType: d, customerMessage: h, errorMessage: y, message: m} = e; + n && (m = n.message || n.customerMessage || n.errorMessage, + n.message = m); + const g = p[d] || p[s] || "UNKNOWN_ERROR" + , v = new this(g,m || h || y); + return "STREAM_UPSELL" === g && n && n.okButtonAction && n.okButtonAction.url && (n.okButtonAction.url = n.okButtonAction.url.replace(/\&(?:challenge|key-system|uri|user-initiated)=[^\&]+/gim, "")), + v.dialog = n, + v + } + static internalError(e) { + return new this(MKError.INTERNAL_ERROR,e) + } + } + MKError.ACCESS_DENIED = h[403], + MKError.AGE_VERIFICATION = "AGE_VERIFICATION", + MKError.AUTHORIZATION_ERROR = p[2002], + MKError.CONFIGURATION_ERROR = "CONFIGURATION_ERROR", + MKError.CONTENT_EQUIVALENT = "CONTENT_EQUIVALENT", + MKError.CONTENT_RESTRICTED = p[3082], + MKError.CONTENT_UNAVAILABLE = p[3076], + MKError.CONTENT_UNSUPPORTED = "CONTENT_UNSUPPORTED", + MKError.DEVICE_LIMIT = p[3059], + MKError.INVALID_ARGUMENTS = "INVALID_ARGUMENTS", + MKError.PLAYREADY_CBC_ENCRYPTION_ERROR = "PLAYREADY_CBC_ENCRYPTION_ERROR", + MKError.MEDIA_CERTIFICATE = "MEDIA_CERTIFICATE", + MKError.MEDIA_DESCRIPTOR = "MEDIA_DESCRIPTOR", + MKError.MEDIA_LICENSE = "MEDIA_LICENSE", + MKError.MEDIA_KEY = "MEDIA_KEY", + MKError.MEDIA_PLAYBACK = "MEDIA_PLAYBACK", + MKError.MEDIA_SESSION = "MEDIA_SESSION", + MKError.NETWORK_ERROR = "NETWORK_ERROR", + MKError.NOT_FOUND = p[1010], + MKError.PARSE_ERROR = "PARSE_ERROR", + MKError.PLAY_ACTIVITY = "PLAY_ACTIVITY", + MKError.QUOTA_EXCEEDED = h[429], + MKError.REQUEST_ERROR = h[400], + MKError.SERVER_ERROR = p[5002], + MKError.SERVICE_UNAVAILABLE = h[503], + MKError.STREAM_UPSELL = p[3084], + MKError.SUBSCRIPTION_ERROR = p[3063], + MKError.TOKEN_EXPIRED = p[2034], + MKError.UNAUTHORIZED_ERROR = h[401], + MKError.UNKNOWN_ERROR = "UNKNOWN_ERROR", + MKError.UNSUPPORTED_ERROR = "UNSUPPORTED_ERROR", + MKError.INTERNAL_ERROR = "INTERNAL_ERROR", + MKError.OUTPUT_RESTRICTED = "OUTPUT_RESTRICTED", + MKError.WIDEVINE_CDM_EXPIRED = "WIDEVINE_CDM_EXPIRED"; + class Notifications { + constructor(e=[], s) { + this._eventRegistry = {}, + e.forEach(e=>{ + this._eventRegistry[e] = [] + } + ), + s && s.namespace && (this.dispatchNamespace = "com.apple." + s.namespace), + this.shouldStorageDispatch && (this._handleGlobalStorageEvent = this._handleGlobalStorageEvent.bind(this), + window.addEventListener("storage", this._handleGlobalStorageEvent)) + } + get shouldStorageDispatch() { + return "undefined" != typeof window && "undefined" != typeof sessionStorage && this.dispatchNamespace + } + addEventListener(e, s) { + Array.isArray(this._eventRegistry[e]) && this._eventRegistry[e].push(s) + } + dispatchEvent(e, s) { + Array.isArray(this._eventRegistry[e]) && this._eventRegistry[e].forEach(e=>e(s)) + } + dispatchDistributedEvent(e, s) { + if (this.dispatchEvent(e, s), + this.shouldStorageDispatch) { + const n = `${this.dispatchNamespace}:${e}`; + sessionStorage.setItem(n, JSON.stringify(s)) + } + } + removeEventListener(e, s) { + if (Array.isArray(this._eventRegistry[e])) { + const n = this._eventRegistry[e].indexOf(s); + this._eventRegistry[e].splice(n, 1) + } + } + _handleGlobalStorageEvent(e) { + var s; + if (this.dispatchNamespace && (null === (s = e.key) || void 0 === s ? void 0 : s.startsWith(this.dispatchNamespace + ":"))) { + const s = e.key.substring(this.dispatchNamespace.length + 1); + this.dispatchEvent(s, JSON.parse(e.newValue)) + } + } + } + var g = "undefined" != typeof FastBoot ? FastBoot.require("buffer").Buffer : "undefined" != typeof process && null !== process.versions && null !== process.versions.node ? Buffer : window.Buffer; + function memoize(e) { + return function(...s) { + let n = "" + , d = s.length; + for (e._memoized = e._memoized || {}; d--; ) { + const e = s[d]; + n += e === Object(e) ? JSON.stringify(e) : e + } + return n in e._memoized ? e._memoized[n] : e._memoized[n] = e(...s) + } + } + function isObject(e) { + return !!e && "object" == typeof e && !Array.isArray(e) + } + function generateUUID() { + let e = strRandomizer() + strRandomizer(); + for (; e.length < 16; ) + e += strRandomizer(); + return e.slice(0, 16) + } + function strRandomizer() { + return Math.random().toString(16).substring(2) + } + const v = memoize(e=>/^[a|i|l|p]{1}\.[a-zA-Z0-9]+$/.test(e)) + , _ = memoize(e=>/^(a\.)?[a-zA-Z0-9]+$/.test(e)); + function isNodeEnvironment$1(e) { + const isDefined = e=>null != e; + return 0 === arguments.length && "undefined" != typeof process && (e = process), + isDefined(e) && isDefined(e.versions) && isDefined(e.versions.node) || "undefined" != typeof FastBoot + } + const b = memoize(isNodeEnvironment$1() ? e=>g.from(e, "base64").toString("binary") : e=>window.atob(e)); + memoize(isNodeEnvironment$1() ? e=>g.from(e).toString("base64") : e=>window.btoa(e)); + const debounce = (e,s=250,n={ + isImmediate: !1 + })=>{ + let d; + return function(...h) { + const p = this + , y = n.isImmediate && void 0 === d; + void 0 !== d && clearTimeout(d), + d = setTimeout((function() { + d = void 0, + n.isImmediate || e.apply(p, h) + } + ), s), + y && e.apply(p, h) + } + } + , exceptFields = (e,...s)=>{ + const n = {}; + return Object.keys(e).forEach(d=>{ + s.includes(d) || (n[d] = e[d]) + } + ), + n + } + , arrayEquals = (e,s)=>!!e && !!s && [].every.call(e, (e,n)=>e === s[n]); + function hasOwn(e, s) { + return Object.prototype.hasOwnProperty.call(Object(e), s) + } + function isEmpty(e) { + if ("object" != typeof e) + throw new TypeError("Source is not an Object"); + for (const s in e) + if (hasOwn(e, s)) + return !1; + return !0 + } + function transform$9(e, s, n=!1) { + return n && (e = Object.keys(e).reduce((s,n)=>(s[e[n]] = n, + s), {})), + Object.keys(e).reduce((n,d)=>{ + const h = e[d] + , p = "function" == typeof h ? h() : function(e, s) { + return s.split(".").reduce((e,s)=>{ + if (void 0 !== e) + return e[s] + } + , e) + }(s, h); + return p && function(e, s, n) { + s.split(".").reduce((s,d,h,p)=>{ + const y = h === p.length - 1 + , m = hasOwn(s, d) + , g = s[d]instanceof Object + , v = null === s[d]; + if (!y && m && (!g || v)) + throw new TypeError(`Value at ${p.slice(0, h + 1).join(".")} in keypath is not an Object.`); + return y ? (s[d] = n, + e) : m ? s[d] : s[d] = {} + } + , e) + }(n, d, p), + n + } + , {}) + } + function transformKeys(e, s) { + return Object.keys(e).reduce((n,d)=>(n[s(d)] = e[d], + n), {}) + } + const T = ["contributors", "Episode", "modalities", "Movie", "musicVideo", "podcast-episodes", "radioStation", "Show", "song", "uploaded-audios", "uploadedAudio", "uploaded-videos", "uploadedVideo", "Vod", "workouts", "workout-programs"] + , E = { + "uploaded-videos": !0, + uploadedVideo: !0, + "uploaded-audios": !0, + uploadedAudio: !0, + "podcast-episodes": !0 + } + , k = { + mediaItemStateDidChange: "mediaItemStateDidChange", + mediaItemStateWillChange: "mediaItemStateWillChange" + } + , S = ["trace", "debug", "info", "warn", "error"]; + class Nonsole { + } + S.forEach(e=>{ + Nonsole.prototype[e] = ()=>{} + } + ); + const P = new Nonsole + , getConsole = ()=>"undefined" == typeof console ? P : console + , I = {} + , createLocalStorageFlag = e=>{ + const s = "undefined" == typeof localStorage ? void 0 : localStorage + , n = e.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (e,s)=>s.toUpperCase()); + let d; + return I.hasOwnProperty(n) ? d = I[n] : (d = { + get: ()=>null == s ? void 0 : s.getItem(e), + json: ()=>{ + const n = null == s ? void 0 : s.getItem(e); + try { + return n ? JSON.parse(n) : void 0 + } catch (bt) { + return + } + } + , + setJson: n=>{ + try { + const d = JSON.stringify(n); + null == s || s.setItem(e, d) + } catch (bt) {} + } + , + remove: ()=>null == s ? void 0 : s.removeItem(e), + set: n=>null == s ? void 0 : s.setItem(e, n) + }, + I[n] = d), + d + } + ; + createLocalStorageFlag("mk-debug"), + createLocalStorageFlag("mk-debug-topic"); + const A = "undefined" == typeof localStorage ? void 0 : localStorage + , getConfiguredLevel = (e="mk-debug",s=S.length)=>parseInt(w(e, s), 10) + , w = memoize((e,s)=>{ + var n, d; + return null !== (d = null === (n = null == A ? void 0 : A.getItem) || void 0 === n ? void 0 : n.call(A, e)) && void 0 !== d ? d : "" + s + } + ) + , getAllowedLevels = e=>isNaN(e) || e < 0 ? [] : S.slice(e) + , canLogTopic = (e,s)=>{ + const n = ((e="mk-debug-topic",s="*")=>w(e, s))(s); + return R(n).some(s=>s.test(e)) + } + , R = memoize(e=>e.split(/[\s,]+/).map(e=>{ + const s = e.replace(/\*/g, ".*?"); + return new RegExp("^" + s + "$") + } + )) + , trace = (e,...s)=>logMessage(Object.assign({ + level: "trace" + }, e), ...s) + , debug = (e,...s)=>logMessage(Object.assign({ + level: "debug" + }, e), ...s) + , info = (e,...s)=>logMessage(Object.assign({ + level: "info" + }, e), ...s) + , warn = (e,...s)=>logMessage(Object.assign({ + level: "warn" + }, e), ...s) + , error$1 = (e,...s)=>logMessage(Object.assign({ + level: "error" + }, e), ...s) + , log = (e,...s)=>logMessage(e, ...s) + , logMessage = (e,...s)=>{ + let {level: n, levelKey: d, topic: h, topicKey: p} = e; + if (n = null != n ? n : "debug", + !((e,s)=>-1 !== getAllowedLevels(getConfiguredLevel(s)).indexOf(e))(n, d)) + return; + if (!canLogTopic(h, p)) + return; + const y = getConsole(); + if ("function" != typeof y[n]) + return; + let[m,...g] = s; + void 0 !== h && (m = `${h}: ${m}`), + y[n](m, ...g) + } + ; + class Logger { + constructor(e) { + var s, n, d, h; + this._levelFilterKey = "mk-debug", + "string" == typeof e ? (this._levelFilterKey = e, + this.level = getConfiguredLevel(this._levelFilterKey, 5)) : "object" == typeof e ? (this._levelFilterKey = null !== (s = e.levelFilterStorageKey) && void 0 !== s ? s : this._levelFilterKey, + this._topicFilterKey = null !== (n = e.topicFilterStorageKey) && void 0 !== n ? n : this.generateDefaultTopicFilterStorageKey(this._levelFilterKey), + this.topic = e.topic, + this.level = null !== (d = e.level) && void 0 !== d ? d : getConfiguredLevel(this._levelFilterKey, 5)) : this.level = null != e ? e : getConfiguredLevel(this._levelFilterKey, 5), + this._topicFilterKey = null !== (h = this._topicFilterKey) && void 0 !== h ? h : this.generateDefaultTopicFilterStorageKey(this._levelFilterKey) + } + get enabled() { + return this.level < 5 + } + set enabled(e) { + this.level = e ? 1 : 5 + } + debug(e, ...s) { + this.callLogMethod(debug, e, ...s) + } + error(e, ...s) { + this.callLogMethod(error$1, e, ...s) + } + log(e, ...s) { + this.callLogMethod(log, e, ...s) + } + info(e, ...s) { + this.callLogMethod(info, e, ...s) + } + trace(e, ...s) { + this.callLogMethod(trace, e, ...s) + } + warn(e, ...s) { + this.callLogMethod(warn, e, ...s) + } + callLogMethod(e, s, ...n) { + var d, h; + const p = { + levelKey: this._levelFilterKey, + topicKey: this._topicFilterKey, + topic: this.topic + }; + let y = s; + var m; + "object" == typeof (m = s) && null !== m && "string" == typeof m.topic && (p.topic = null !== (d = s.topic) && void 0 !== d ? d : p.topic, + y = null !== (h = s.message) && void 0 !== h ? h : n.shift()), + e(p, y, ...n) + } + generateDefaultTopicFilterStorageKey(e) { + return e + "-topic" + } + } + const O = new Logger + , C = new Logger; + var M, D; + e.PlaybackType = void 0, + (M = e.PlaybackType || (e.PlaybackType = {}))[M.none = 0] = "none", + M[M.preview = 1] = "preview", + M[M.unencryptedFull = 2] = "unencryptedFull", + M[M.encryptedFull = 3] = "encryptedFull", + function(e) { + e[e.none = 0] = "none", + e[e.loading = 1] = "loading", + e[e.ready = 2] = "ready", + e[e.playing = 3] = "playing", + e[e.ended = 4] = "ended", + e[e.unavailable = 5] = "unavailable", + e[e.restricted = 6] = "restricted", + e[e.error = 7] = "error", + e[e.unsupported = 8] = "unsupported" + }(D || (D = {})); + const {none: N, loading: L, ready: x, playing: U, ended: $, unavailable: j, restricted: B, error: F, unsupported: V} = D + , H = { + [N]: { + allowed: [L], + unknown: [$, j, B, F, V] + }, + [L]: { + allowed: [x, B, F, V], + unknown: [] + }, + [x]: { + allowed: [U], + unknown: [F] + }, + [U]: { + allowed: [$, F], + unknown: [j, B, V] + }, + [$]: { + allowed: [], + unknown: [] + }, + [j]: { + allowed: [], + unknown: [] + }, + [B]: { + allowed: [], + unknown: [] + }, + [F]: { + allowed: [], + unknown: [] + }, + [V]: { + allowed: [], + unknown: [] + } + } + , toName = e=>D[e] + , createMediaItemStateGuard = (e=N)=>{ + const s = { + current: e, + set(e) { + const {current: n} = s; + if (!((e,s)=>H[e].allowed.includes(s))(n, e)) { + const s = ((e,s)=>H[e].unknown.includes(s))(n, e); + C.debug(`MediaItem.state was changed from ${toName(n)} to ${toName(e)}`, s ? "but it is unknown whether it should be allowed or not." : "and it should not be happening") + } + s.current = e + } + }; + return s + } + ; + function isStringNotEmpty(e) { + return !function(e) { + return void 0 === e || "" === e.trim() + }(e) + } + function transform$8(e) { + return transform$9({ + "attributes.albumName": "metadata.playlistName", + "attributes.artistName": "metadata.artistName", + "attributes.artwork"() { + const s = null == e ? void 0 : e.artworkURL; + if (s) + return function(e) { + const s = e.split("/").pop() + , [n,d] = !!s && s.match(/\d+/g) || ["100", "100"]; + return { + width: parseInt(n, 10), + height: parseInt(d, 10), + url: e.replace(`${n}x${d}`, "{w}x{h}") + } + }(s) + }, + "attributes.composerName": "metadata.composerName", + "attributes.contentRating"() { + var s; + if (1 === (null === (s = null == e ? void 0 : e.metadata) || void 0 === s ? void 0 : s.explicit)) + return "explicit" + }, + "attributes.discNumber"() { + var s; + return (null === (s = null == e ? void 0 : e.metadata) || void 0 === s ? void 0 : s.discNumber) || 1 + }, + "attributes.durationInMillis": "metadata.duration", + "attributes.genreNames"() { + var s; + return [null === (s = null == e ? void 0 : e.metadata) || void 0 === s ? void 0 : s.genre] + }, + "attributes.isrc"() { + var s; + const n = null === (s = null == e ? void 0 : e.metadata) || void 0 === s ? void 0 : s.xid; + if (n) + return n.replace(/^([^:]+):isrc:/, "$1") + }, + "attributes.name": "metadata.itemName", + "attributes.playParams.id": "metadata.itemId", + "attributes.playParams.kind": "metadata.kind", + "attributes.previews": ()=>[{ + url: null == e ? void 0 : e.previewURL + }], + "attributes.releaseDate": "metadata.releaseDate", + "attributes.trackNumber": "metadata.trackNumber", + assetURL: "URL", + cloudId: "metadata.cloud-id", + id() { + var s; + return "" + (null === (s = null == e ? void 0 : e.metadata) || void 0 === s ? void 0 : s.itemId) + }, + flavor: "flavor", + type: "metadata.kind" + }, e) + } + const {mediaItemStateDidChange: z, mediaItemStateWillChange: q} = k + , W = { + isEntitledToPlay: !0 + }; + class MediaItem extends Notifications { + constructor(s={}) { + super([z, q]), + this.bingeWatching = !1, + this.hlsMetadata = {}, + this.playbackType = e.PlaybackType.none, + this._assets = [], + this._state = createMediaItemStateGuard(), + C.debug("media-item: creating Media Item with options:", s); + s.id && s.attributes ? (Object.keys(s).forEach(e=>{ + hasOwn(W, e) || (this[e] = s[e]) + } + ), + this.type = this.playParams && this.playParams.kind ? this.playParams.kind : this.type || "song") : (this.id = s.id || generateUUID(), + this.type = s.type || "song", + this.attributes = { + playParams: { + id: this.id, + kind: this.type + } + }), + this._context = s.context || {}, + s.container ? this._container = s.container : s.containerId && s.containerType && (this._container = { + id: s.containerId, + type: s.containerType + }) + } + get albumInfo() { + const {albumName: e, artistName: s} = this + , n = []; + return s && n.push(s), + e && n.push(e), + n.join(" - ") + } + get albumName() { + return this.attributes.albumName + } + get artistName() { + return this.attributes.genreNames && this.attributes.genreNames.indexOf("Classical") > -1 && this.attributes.composerName ? this.attributes.composerName : this.attributes.artistName + } + get artwork() { + var e, s; + return null !== (e = this.attributes.artwork) && void 0 !== e ? e : null === (s = this.attributes.images) || void 0 === s ? void 0 : s.coverArt16X9 + } + get artworkURL() { + if (this.artwork && this.artwork.url) + return this.artwork.url + } + get assets() { + return this._assets + } + get canPlay() { + return this.isPlayable && this.isReady + } + get container() { + return this._container + } + set container(e) { + this._container = e + } + get contentRating() { + return this.attributes.contentRating + } + get context() { + return this._context + } + set context(e) { + this._context = e + } + get discNumber() { + return this.attributes.discNumber + } + get hasContainerArtwork() { + return this.container && this.container.attributes && this.container.attributes.artwork && this.container.attributes.artwork.url + } + get hasPlaylistContainer() { + return this.container && "playlists" === this.container.type && this.container.attributes + } + get isEntitledToPlay() { + var e, s; + const {attributes: n, playables: d} = this; + return null !== (s = n.isEntitledToPlay || (null === (e = null == d ? void 0 : d[0]) || void 0 === e ? void 0 : e.isEntitledToPlay)) && void 0 !== s && s + } + get isLiveRadioStation() { + return isLiveRadioStation(this) + } + get isLiveAudioStation() { + return isLiveRadioKind(this, "audio") + } + get isLiveVideoStation() { + return isLiveRadioKind(this, "video") + } + get isSong() { + return "song" === this.type + } + get info() { + return `${this.title} - ${this.albumInfo}` + } + get isCloudItem() { + return this.playParams && this.playParams.isLibrary || v(this.id) + } + get isCloudUpload() { + return -1 === this._songId + } + get isExplicitItem() { + return "explicit" === this.contentRating + } + get isLoading() { + return this.state === D.loading + } + get isPlayableMediaType() { + return -1 !== T.indexOf(this.type) + } + get isPlayable() { + var e; + return !!this.isPlayableMediaType && (!(!this.isLiveRadioStation && !this.hasOffersHlsUrl) || (this.needsPlayParams ? !!this.playParams : this.isUTS ? this.isEntitledToPlay : !!this.attributes.assetUrl || !!(null === (e = this.attributes.previews) || void 0 === e ? void 0 : e.length))) + } + get isPlaying() { + return this.state === D.playing + } + get isPreparedToPlay() { + if ("song" === this.type) + return !!this._assets && !!this.keyURLs && !!this._songId; + if (this.isUTS) { + const e = isStringNotEmpty(this.assetURL) + , s = !!(this.keyURLs && isStringNotEmpty(this.keyURLs["hls-key-cert-url"]) && isStringNotEmpty(this.keyURLs["hls-key-server-url"]) && isStringNotEmpty(this.keyURLs["widevine-cert-url"])); + return e && s + } + return !!isStringNotEmpty(this.assetURL) || this.playRawAssetURL && !!isStringNotEmpty(this.attributes.assetUrl) + } + get isrc() { + return this.attributes.isrc + } + get isReady() { + return this.state === D.ready + } + get isRestricted() { + return this.state === D.restricted + } + get isUTS() { + return ["Episode", "Movie", "MusicMovie", "Show", "Vod"].includes(this.type) + } + get isUnavailable() { + return this.state === D.unavailable + } + get needsPlayParams() { + return ["musicVideo", "song"].includes(this.type) + } + get normalizedType() { + return normalizeContentType(this.type) + } + get offers() { + return this.attributes.offers + } + get offersHlsUrl() { + const {offers: e} = this + , s = null == e ? void 0 : e.find(e=>{ + var s; + return !!(null === (s = e.hlsUrl) || void 0 === s ? void 0 : s.length) + } + ); + return null == s ? void 0 : s.hlsUrl + } + get hasOffersHlsUrl() { + return isStringNotEmpty(this.offersHlsUrl) + } + set playbackData(e) { + if (void 0 === e) + return; + this.previewURL && (e.previewURL = this.previewURL); + const s = transform$8(e); + this.artwork && s.artwork && delete s.artwork, + s.id !== this.id && delete s.id, + this.playParams && s.attributes.playParams && (s.attributes.playParams = this.playParams), + Object.assign(this, s), + C.debug("media-item: item merged with playbackData", this), + this.state = D.ready + } + get playbackDuration() { + return this.attributes.durationInMillis || this.attributes.durationInMilliseconds + } + get playlistArtworkURL() { + var e, s, n; + return this.hasPlaylistContainer && this.hasContainerArtwork ? null === (n = null === (s = null === (e = this.container) || void 0 === e ? void 0 : e.attributes) || void 0 === s ? void 0 : s.artwork) || void 0 === n ? void 0 : n.url : this.artworkURL + } + get playlistName() { + var e, s; + return this.hasPlaylistContainer ? null === (s = null === (e = this.container) || void 0 === e ? void 0 : e.attributes) || void 0 === s ? void 0 : s.name : this.albumName + } + get playParams() { + return this.attributes.playParams + } + get playRawAssetURL() { + return this.offers ? this.offers.some(e=>"STDQ" === e.type) : !(!this.isCloudUpload && !E[this.type]) + } + get previewURL() { + var e, s, n, d, h, p, y, m, g, v, _, b, T, E, k; + return (null === (n = null === (s = null === (e = this.attributes) || void 0 === e ? void 0 : e.previews) || void 0 === s ? void 0 : s[0]) || void 0 === n ? void 0 : n.url) || (null === (p = null === (h = null === (d = this.attributes) || void 0 === d ? void 0 : d.previews) || void 0 === h ? void 0 : h[0]) || void 0 === p ? void 0 : p.hlsUrl) || (null === (v = null === (g = null === (m = null === (y = this.attributes) || void 0 === y ? void 0 : y.trailers) || void 0 === m ? void 0 : m[0]) || void 0 === g ? void 0 : g.assets) || void 0 === v ? void 0 : v.hlsUrl) || (null === (T = null === (b = null === (_ = this.attributes) || void 0 === _ ? void 0 : _.movieClips) || void 0 === b ? void 0 : b[0]) || void 0 === T ? void 0 : T.hlsUrl) || (null === (k = null === (E = this.attributes) || void 0 === E ? void 0 : E.video) || void 0 === k ? void 0 : k.hlsUrl) + } + get rating() { + return this.attributes.rating + } + get releaseDate() { + if (this._releaseDate) + return this._releaseDate; + if (this.attributes && (this.attributes.releaseDate || this.attributes.releaseDateTime)) { + const e = this.attributes.releaseDate || this.attributes.releaseDateTime; + return this._releaseDate = /^\d{4}-\d{1,2}-\d{1,2}/.test(e) ? new Date(e) : void 0, + this._releaseDate + } + } + get songId() { + return this._songId && -1 !== this._songId ? this._songId : this.id + } + get state() { + return this._state.current + } + set state(e) { + const s = { + oldState: this._state.current, + state: e + }; + this._stateWillChange && this._stateWillChange(this), + this.dispatchEvent(q, s), + this._state.set(e), + this._stateDidChange && this._stateDidChange(this), + this.dispatchEvent(z, s) + } + get title() { + return this.attributes.name || this.attributes.title + } + get trackNumber() { + return this.attributes.trackNumber + } + beginMonitoringStateDidChange(e) { + this._stateDidChange = e + } + beginMonitoringStateWillChange(e) { + this._stateWillChange = e + } + endMonitoringStateDidChange() { + this._stateDidChange = void 0 + } + endMonitoringStateWillChange() { + this._stateWillChange = void 0 + } + isEqual(e) { + return this.id === e.id && this.type === e.type && this.attributes === e.attributes + } + resetState() { + this.endMonitoringStateWillChange(), + this.endMonitoringStateDidChange(), + this.state = D.none + } + restrict() { + this.isExplicitItem && (this.state = D.restricted, + this._removePlayableData()) + } + notSupported() { + this.state = D.unsupported, + this._removePlayableData() + } + updateFromLoadError(e) { + switch (e.errorCode) { + case MKError.CONTENT_RESTRICTED: + this.state = D.restricted; + break; + case MKError.CONTENT_UNAVAILABLE: + this.state = D.unavailable; + break; + default: + this.state = D.error + } + } + updateFromSongList(e) { + "musicVideo" === this.type ? this.updateWithLoadedAssets(void 0, e["hls-playlist-url"]) : this.updateWithLoadedAssets(e.assets), + this._songId = e.songId, + this.updateWithLoadedKeys({ + "hls-key-cert-url": e["hls-key-cert-url"], + "hls-key-server-url": e["hls-key-server-url"], + "widevine-cert-url": e["widevine-cert-url"] + }) + } + updateWithLoadedKeys(e, s) { + this.keyURLs = e, + s && (this.keyServerQueryParameters = s) + } + updateWithLoadedAssets(e, s) { + e && (this._assets = e), + s && (this.assetURL = s) + } + _removePlayableData() { + var e, s, n; + null === (e = this.attributes) || void 0 === e || delete e.playParams, + null === (s = this.attributes) || void 0 === s || delete s.previews, + null === (n = this.attributes) || void 0 === n || delete n.trailers + } + } + var Y = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : void 0 !== s ? s : "undefined" != typeof self ? self : {}; + function unwrapExports(e) { + return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e + } + function createCommonjsModule(e, s) { + return e(s = { + exports: {} + }, s.exports), + s.exports + } + var G = createCommonjsModule((function(e) { + var s = e.exports = "undefined" != typeof window && window.Math == Math ? window : "undefined" != typeof self && self.Math == Math ? self : Function("return this")(); + "number" == typeof __g && (__g = s) + } + )) + , Q = createCommonjsModule((function(e) { + var s = e.exports = { + version: "2.6.12" + }; + "number" == typeof __e && (__e = s) + } + )); + Q.version; + var _isObject = function(e) { + return "object" == typeof e ? null !== e : "function" == typeof e + } + , _anObject = function(e) { + if (!_isObject(e)) + throw TypeError(e + " is not an object!"); + return e + } + , _fails = function(e) { + try { + return !!e() + } catch (bt) { + return !0 + } + } + , J = !_fails((function() { + return 7 != Object.defineProperty({}, "a", { + get: function() { + return 7 + } + }).a + } + )) + , X = G.document + , Z = _isObject(X) && _isObject(X.createElement) + , ee = !J && !_fails((function() { + return 7 != Object.defineProperty((e = "div", + Z ? X.createElement(e) : {}), "a", { + get: function() { + return 7 + } + }).a; + var e + } + )) + , te = Object.defineProperty + , ie = { + f: J ? Object.defineProperty : function(e, s, n) { + if (_anObject(e), + s = function(e, s) { + if (!_isObject(e)) + return e; + var n, d; + if (s && "function" == typeof (n = e.toString) && !_isObject(d = n.call(e))) + return d; + if ("function" == typeof (n = e.valueOf) && !_isObject(d = n.call(e))) + return d; + if (!s && "function" == typeof (n = e.toString) && !_isObject(d = n.call(e))) + return d; + throw TypeError("Can't convert object to primitive value") + }(s, !0), + _anObject(n), + ee) + try { + return te(e, s, n) + } catch (bt) {} + if ("get"in n || "set"in n) + throw TypeError("Accessors not supported!"); + return "value"in n && (e[s] = n.value), + e + } + } + , se = J ? function(e, s, n) { + return ie.f(e, s, function(e, s) { + return { + enumerable: !(1 & e), + configurable: !(2 & e), + writable: !(4 & e), + value: s + } + }(1, n)) + } + : function(e, s, n) { + return e[s] = n, + e + } + , re = {}.hasOwnProperty + , _has = function(e, s) { + return re.call(e, s) + } + , ne = 0 + , ae = Math.random() + , _uid = function(e) { + return "Symbol(".concat(void 0 === e ? "" : e, ")_", (++ne + ae).toString(36)) + } + , oe = createCommonjsModule((function(e) { + var s = G["__core-js_shared__"] || (G["__core-js_shared__"] = {}); + (e.exports = function(e, n) { + return s[e] || (s[e] = void 0 !== n ? n : {}) + } + )("versions", []).push({ + version: Q.version, + mode: "global", + copyright: "© 2020 Denis Pushkarev (zloirock.ru)" + }) + } + )) + , de = oe("native-function-to-string", Function.toString) + , le = createCommonjsModule((function(e) { + var s = _uid("src") + , n = ("" + de).split("toString"); + Q.inspectSource = function(e) { + return de.call(e) + } + , + (e.exports = function(e, d, h, p) { + var y = "function" == typeof h; + y && (_has(h, "name") || se(h, "name", d)), + e[d] !== h && (y && (_has(h, s) || se(h, s, e[d] ? "" + e[d] : n.join(String(d)))), + e === G ? e[d] = h : p ? e[d] ? e[d] = h : se(e, d, h) : (delete e[d], + se(e, d, h))) + } + )(Function.prototype, "toString", (function() { + return "function" == typeof this && this[s] || de.call(this) + } + )) + } + )) + , _ctx = function(e, s, n) { + if (function(e) { + if ("function" != typeof e) + throw TypeError(e + " is not a function!") + }(e), + void 0 === s) + return e; + switch (n) { + case 1: + return function(n) { + return e.call(s, n) + } + ; + case 2: + return function(n, d) { + return e.call(s, n, d) + } + ; + case 3: + return function(n, d, h) { + return e.call(s, n, d, h) + } + } + return function() { + return e.apply(s, arguments) + } + } + , $export = function(e, s, n) { + var d, h, p, y, m = e & $export.F, g = e & $export.G, v = e & $export.S, _ = e & $export.P, b = e & $export.B, T = g ? G : v ? G[s] || (G[s] = {}) : (G[s] || {}).prototype, E = g ? Q : Q[s] || (Q[s] = {}), k = E.prototype || (E.prototype = {}); + for (d in g && (n = s), + n) + p = ((h = !m && T && void 0 !== T[d]) ? T : n)[d], + y = b && h ? _ctx(p, G) : _ && "function" == typeof p ? _ctx(Function.call, p) : p, + T && le(T, d, p, e & $export.U), + E[d] != p && se(E, d, y), + _ && k[d] != p && (k[d] = p) + }; + G.core = Q, + $export.F = 1, + $export.G = 2, + $export.S = 4, + $export.P = 8, + $export.B = 16, + $export.W = 32, + $export.U = 64, + $export.R = 128; + var ce, ue, he = $export, pe = {}.toString, ye = Object("z").propertyIsEnumerable(0) ? Object : function(e) { + return "String" == function(e) { + return pe.call(e).slice(8, -1) + }(e) ? e.split("") : Object(e) + } + , _defined = function(e) { + if (null == e) + throw TypeError("Can't call method on " + e); + return e + }, _toIobject = function(e) { + return ye(_defined(e)) + }, me = Math.ceil, ge = Math.floor, _toInteger = function(e) { + return isNaN(e = +e) ? 0 : (e > 0 ? ge : me)(e) + }, fe = Math.min, ve = Math.max, _e = Math.min, be = oe("keys"), Te = (ce = !1, + function(e, s, n) { + var d, h, p = _toIobject(e), y = (d = p.length) > 0 ? fe(_toInteger(d), 9007199254740991) : 0, m = function(e, s) { + return (e = _toInteger(e)) < 0 ? ve(e + s, 0) : _e(e, s) + }(n, y); + if (ce && s != s) { + for (; y > m; ) + if ((h = p[m++]) != h) + return !0 + } else + for (; y > m; m++) + if ((ce || m in p) && p[m] === s) + return ce || m || 0; + return !ce && -1 + } + ), Ee = be[ue = "IE_PROTO"] || (be[ue] = _uid(ue)), ke = "constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","), Se = Object.keys || function(e) { + return function(e, s) { + var n, d = _toIobject(e), h = 0, p = []; + for (n in d) + n != Ee && _has(d, n) && p.push(n); + for (; s.length > h; ) + _has(d, n = s[h++]) && (~Te(p, n) || p.push(n)); + return p + }(e, ke) + } + , Pe = { + f: Object.getOwnPropertySymbols + }, Ie = { + f: {}.propertyIsEnumerable + }, _toObject = function(e) { + return Object(_defined(e)) + }, Ae = Object.assign, we = !Ae || _fails((function() { + var e = {} + , s = {} + , n = Symbol() + , d = "abcdefghijklmnopqrst"; + return e[n] = 7, + d.split("").forEach((function(e) { + s[e] = e + } + )), + 7 != Ae({}, e)[n] || Object.keys(Ae({}, s)).join("") != d + } + )) ? function(e, s) { + for (var n = _toObject(e), d = arguments.length, h = 1, p = Pe.f, y = Ie.f; d > h; ) + for (var m, g = ye(arguments[h++]), v = p ? Se(g).concat(p(g)) : Se(g), _ = v.length, b = 0; _ > b; ) + m = v[b++], + J && !y.call(g, m) || (n[m] = g[m]); + return n + } + : Ae; + he(he.S + he.F, "Object", { + assign: we + }), + Q.Object.assign; + var Re = "undefined" != typeof globalThis && globalThis || "undefined" != typeof self && self || void 0 !== Re && Re + , Oe = "URLSearchParams"in Re + , Ce = "Symbol"in Re && "iterator"in Symbol + , Me = "FileReader"in Re && "Blob"in Re && function() { + try { + return new Blob, + !0 + } catch (bt) { + return !1 + } + }() + , De = "FormData"in Re + , Ne = "ArrayBuffer"in Re; + if (Ne) + var Le = ["[object Int8Array]", "[object Uint8Array]", "[object Uint8ClampedArray]", "[object Int16Array]", "[object Uint16Array]", "[object Int32Array]", "[object Uint32Array]", "[object Float32Array]", "[object Float64Array]"] + , xe = ArrayBuffer.isView || function(e) { + return e && Le.indexOf(Object.prototype.toString.call(e)) > -1 + } + ; + function normalizeName(e) { + if ("string" != typeof e && (e = String(e)), + /[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e) || "" === e) + throw new TypeError('Invalid character in header field name: "' + e + '"'); + return e.toLowerCase() + } + function normalizeValue(e) { + return "string" != typeof e && (e = String(e)), + e + } + function iteratorFor(e) { + var s = { + next: function() { + var s = e.shift(); + return { + done: void 0 === s, + value: s + } + } + }; + return Ce && (s[Symbol.iterator] = function() { + return s + } + ), + s + } + function Headers$1(e) { + this.map = {}, + e instanceof Headers$1 ? e.forEach((function(e, s) { + this.append(s, e) + } + ), this) : Array.isArray(e) ? e.forEach((function(e) { + this.append(e[0], e[1]) + } + ), this) : e && Object.getOwnPropertyNames(e).forEach((function(s) { + this.append(s, e[s]) + } + ), this) + } + function consumed(e) { + if (e.bodyUsed) + return Promise.reject(new TypeError("Already read")); + e.bodyUsed = !0 + } + function fileReaderReady(e) { + return new Promise((function(s, n) { + e.onload = function() { + s(e.result) + } + , + e.onerror = function() { + n(e.error) + } + } + )) + } + function readBlobAsArrayBuffer(e) { + var s = new FileReader + , n = fileReaderReady(s); + return s.readAsArrayBuffer(e), + n + } + function bufferClone(e) { + if (e.slice) + return e.slice(0); + var s = new Uint8Array(e.byteLength); + return s.set(new Uint8Array(e)), + s.buffer + } + function Body() { + return this.bodyUsed = !1, + this._initBody = function(e) { + var s; + this.bodyUsed = this.bodyUsed, + this._bodyInit = e, + e ? "string" == typeof e ? this._bodyText = e : Me && Blob.prototype.isPrototypeOf(e) ? this._bodyBlob = e : De && FormData.prototype.isPrototypeOf(e) ? this._bodyFormData = e : Oe && URLSearchParams.prototype.isPrototypeOf(e) ? this._bodyText = e.toString() : Ne && Me && ((s = e) && DataView.prototype.isPrototypeOf(s)) ? (this._bodyArrayBuffer = bufferClone(e.buffer), + this._bodyInit = new Blob([this._bodyArrayBuffer])) : Ne && (ArrayBuffer.prototype.isPrototypeOf(e) || xe(e)) ? this._bodyArrayBuffer = bufferClone(e) : this._bodyText = e = Object.prototype.toString.call(e) : this._bodyText = "", + this.headers.get("content-type") || ("string" == typeof e ? this.headers.set("content-type", "text/plain;charset=UTF-8") : this._bodyBlob && this._bodyBlob.type ? this.headers.set("content-type", this._bodyBlob.type) : Oe && URLSearchParams.prototype.isPrototypeOf(e) && this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8")) + } + , + Me && (this.blob = function() { + var e = consumed(this); + if (e) + return e; + if (this._bodyBlob) + return Promise.resolve(this._bodyBlob); + if (this._bodyArrayBuffer) + return Promise.resolve(new Blob([this._bodyArrayBuffer])); + if (this._bodyFormData) + throw new Error("could not read FormData body as blob"); + return Promise.resolve(new Blob([this._bodyText])) + } + , + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + var e = consumed(this); + return e || (ArrayBuffer.isView(this._bodyArrayBuffer) ? Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset, this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength)) : Promise.resolve(this._bodyArrayBuffer)) + } + return this.blob().then(readBlobAsArrayBuffer) + } + ), + this.text = function() { + var e, s, n, d = consumed(this); + if (d) + return d; + if (this._bodyBlob) + return e = this._bodyBlob, + s = new FileReader, + n = fileReaderReady(s), + s.readAsText(e), + n; + if (this._bodyArrayBuffer) + return Promise.resolve(function(e) { + for (var s = new Uint8Array(e), n = new Array(s.length), d = 0; d < s.length; d++) + n[d] = String.fromCharCode(s[d]); + return n.join("") + }(this._bodyArrayBuffer)); + if (this._bodyFormData) + throw new Error("could not read FormData body as text"); + return Promise.resolve(this._bodyText) + } + , + De && (this.formData = function() { + return this.text().then(decode) + } + ), + this.json = function() { + return this.text().then(JSON.parse) + } + , + this + } + Headers$1.prototype.append = function(e, s) { + e = normalizeName(e), + s = normalizeValue(s); + var n = this.map[e]; + this.map[e] = n ? n + ", " + s : s + } + , + Headers$1.prototype.delete = function(e) { + delete this.map[normalizeName(e)] + } + , + Headers$1.prototype.get = function(e) { + return e = normalizeName(e), + this.has(e) ? this.map[e] : null + } + , + Headers$1.prototype.has = function(e) { + return this.map.hasOwnProperty(normalizeName(e)) + } + , + Headers$1.prototype.set = function(e, s) { + this.map[normalizeName(e)] = normalizeValue(s) + } + , + Headers$1.prototype.forEach = function(e, s) { + for (var n in this.map) + this.map.hasOwnProperty(n) && e.call(s, this.map[n], n, this) + } + , + Headers$1.prototype.keys = function() { + var e = []; + return this.forEach((function(s, n) { + e.push(n) + } + )), + iteratorFor(e) + } + , + Headers$1.prototype.values = function() { + var e = []; + return this.forEach((function(s) { + e.push(s) + } + )), + iteratorFor(e) + } + , + Headers$1.prototype.entries = function() { + var e = []; + return this.forEach((function(s, n) { + e.push([n, s]) + } + )), + iteratorFor(e) + } + , + Ce && (Headers$1.prototype[Symbol.iterator] = Headers$1.prototype.entries); + var Ue = ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]; + function Request(e, s) { + if (!(this instanceof Request)) + throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.'); + var n, d, h = (s = s || {}).body; + if (e instanceof Request) { + if (e.bodyUsed) + throw new TypeError("Already read"); + this.url = e.url, + this.credentials = e.credentials, + s.headers || (this.headers = new Headers$1(e.headers)), + this.method = e.method, + this.mode = e.mode, + this.signal = e.signal, + h || null == e._bodyInit || (h = e._bodyInit, + e.bodyUsed = !0) + } else + this.url = String(e); + if (this.credentials = s.credentials || this.credentials || "same-origin", + !s.headers && this.headers || (this.headers = new Headers$1(s.headers)), + this.method = (n = s.method || this.method || "GET", + d = n.toUpperCase(), + Ue.indexOf(d) > -1 ? d : n), + this.mode = s.mode || this.mode || null, + this.signal = s.signal || this.signal, + this.referrer = null, + ("GET" === this.method || "HEAD" === this.method) && h) + throw new TypeError("Body not allowed for GET or HEAD requests"); + if (this._initBody(h), + !("GET" !== this.method && "HEAD" !== this.method || "no-store" !== s.cache && "no-cache" !== s.cache)) { + var p = /([?&])_=[^&]*/; + if (p.test(this.url)) + this.url = this.url.replace(p, "$1_=" + (new Date).getTime()); + else { + this.url += (/\?/.test(this.url) ? "&" : "?") + "_=" + (new Date).getTime() + } + } + } + function decode(e) { + var s = new FormData; + return e.trim().split("&").forEach((function(e) { + if (e) { + var n = e.split("=") + , d = n.shift().replace(/\+/g, " ") + , h = n.join("=").replace(/\+/g, " "); + s.append(decodeURIComponent(d), decodeURIComponent(h)) + } + } + )), + s + } + function Response(e, s) { + if (!(this instanceof Response)) + throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.'); + s || (s = {}), + this.type = "default", + this.status = void 0 === s.status ? 200 : s.status, + this.ok = this.status >= 200 && this.status < 300, + this.statusText = void 0 === s.statusText ? "" : "" + s.statusText, + this.headers = new Headers$1(s.headers), + this.url = s.url || "", + this._initBody(e) + } + Request.prototype.clone = function() { + return new Request(this,{ + body: this._bodyInit + }) + } + , + Body.call(Request.prototype), + Body.call(Response.prototype), + Response.prototype.clone = function() { + return new Response(this._bodyInit,{ + status: this.status, + statusText: this.statusText, + headers: new Headers$1(this.headers), + url: this.url + }) + } + , + Response.error = function() { + var e = new Response(null,{ + status: 0, + statusText: "" + }); + return e.type = "error", + e + } + ; + var $e = [301, 302, 303, 307, 308]; + Response.redirect = function(e, s) { + if (-1 === $e.indexOf(s)) + throw new RangeError("Invalid status code"); + return new Response(null,{ + status: s, + headers: { + location: e + } + }) + } + ; + var je = Re.DOMException; + try { + new je + } catch (Ra) { + (je = function(e, s) { + this.message = e, + this.name = s; + var n = Error(e); + this.stack = n.stack + } + ).prototype = Object.create(Error.prototype), + je.prototype.constructor = je + } + function fetch$1(e, s) { + return new Promise((function(n, d) { + var h = new Request(e,s); + if (h.signal && h.signal.aborted) + return d(new je("Aborted","AbortError")); + var p = new XMLHttpRequest; + function abortXhr() { + p.abort() + } + p.onload = function() { + var e, s, d = { + status: p.status, + statusText: p.statusText, + headers: (e = p.getAllResponseHeaders() || "", + s = new Headers$1, + e.replace(/\r?\n[\t ]+/g, " ").split("\r").map((function(e) { + return 0 === e.indexOf("\n") ? e.substr(1, e.length) : e + } + )).forEach((function(e) { + var n = e.split(":") + , d = n.shift().trim(); + if (d) { + var h = n.join(":").trim(); + s.append(d, h) + } + } + )), + s) + }; + d.url = "responseURL"in p ? p.responseURL : d.headers.get("X-Request-URL"); + var h = "response"in p ? p.response : p.responseText; + setTimeout((function() { + n(new Response(h,d)) + } + ), 0) + } + , + p.onerror = function() { + setTimeout((function() { + d(new TypeError("Network request failed")) + } + ), 0) + } + , + p.ontimeout = function() { + setTimeout((function() { + d(new TypeError("Network request failed")) + } + ), 0) + } + , + p.onabort = function() { + setTimeout((function() { + d(new je("Aborted","AbortError")) + } + ), 0) + } + , + p.open(h.method, function(e) { + try { + return "" === e && Re.location.href ? Re.location.href : e + } catch (bt) { + return e + } + }(h.url), !0), + "include" === h.credentials ? p.withCredentials = !0 : "omit" === h.credentials && (p.withCredentials = !1), + "responseType"in p && (Me ? p.responseType = "blob" : Ne && h.headers.get("Content-Type") && -1 !== h.headers.get("Content-Type").indexOf("application/octet-stream") && (p.responseType = "arraybuffer")), + !s || "object" != typeof s.headers || s.headers instanceof Headers$1 ? h.headers.forEach((function(e, s) { + p.setRequestHeader(s, e) + } + )) : Object.getOwnPropertyNames(s.headers).forEach((function(e) { + p.setRequestHeader(e, normalizeValue(s.headers[e])) + } + )), + h.signal && (h.signal.addEventListener("abort", abortXhr), + p.onreadystatechange = function() { + 4 === p.readyState && h.signal.removeEventListener("abort", abortXhr) + } + ), + p.send(void 0 === h._bodyInit ? null : h._bodyInit) + } + )) + } + fetch$1.polyfill = !0, + Re.fetch || (Re.fetch = fetch$1, + Re.Headers = Headers$1, + Re.Request = Request, + Re.Response = Response); + const addPathToURL = (e,s)=>void 0 === e || "" === e ? s || "" : void 0 === s ? e : (e.endsWith("/") && (e = e.slice(0, -1)), + s.startsWith("/") && (s = s.slice(1)), + `${e}/${s}`) + , addQueryParamsToURL = (e,s)=>{ + const n = urlEncodeParameters(s); + return "" === n ? e : e.endsWith("&") || e.endsWith("?") ? `${e}${n}` : e.includes("?") ? `${e}&${n}` : `${e}?${n}` + } + , Be = "undefined" != typeof Headers + , headersToDict = e=>{ + let s = {}; + var n; + return n = e, + Be && n instanceof Headers ? e.forEach((e,n)=>s[n] = e) : Array.isArray(e) ? e.forEach(([e,n])=>s[e] = n) : s = e, + s + } + , mergeFetchHeaders = (e={},s={})=>Object.assign(Object.assign({}, headersToDict(e)), headersToDict(s)) + , mergeFetchOptions = (e,s)=>{ + if (e || s) + return (null == e ? void 0 : e.headers) && (null == s ? void 0 : s.headers) ? Object.assign(Object.assign(Object.assign({}, e), s), { + headers: mergeFetchHeaders(e.headers, s.headers) + }) : Object.assign(Object.assign({}, e), s) + } + ; + function parseQueryParams(e) { + var s; + if (!e || e.startsWith("http") && !e.includes("?")) + return {}; + try { + return parseParams(null !== (s = e.split("?")[1]) && void 0 !== s ? s : e, "&", decodeURIComponent) + } catch (n) { + return {} + } + } + function parseParams(e, s="&", n=(e=>e)) { + return "string" != typeof e ? {} : e.split(s).map(e=>e.trim().split("=", 2)).reduce((e,s)=>{ + const [d,h] = s; + return "" === d && void 0 === h || (e[n(d)] = n(h), + void 0 === h && (e[n(d)] = void 0)), + e + } + , {}) + } + function getMaxAgeFromHeaders(e) { + const s = function(e, s) { + if (void 0 !== s) + return Be && s instanceof Headers ? s.get(e) : s[e] + }("cache-control", e); + if (s) { + return (e=>{ + const s = Number(e); + if (Number.isFinite(s)) + return s + } + )(parseParams(s, ",")["max-age"]) + } + } + function rewriteLastUrlPath(e, s) { + const n = e.split("/"); + return n.pop(), + n.push(s), + n.join("/") + } + const recursiveEncodeParameters = (e,s)=>Object.keys(e).reduce((n,d)=>{ + const h = e[d] + , p = s ? `${s}[${encodeURIComponent(d)}]` : encodeURIComponent(d); + return `${n}${n ? "&" : ""}${isObject(h) ? recursiveEncodeParameters(h, p) : `${p}=${encodeURIComponent("" + h)}`}` + } + , ""); + function urlEncodeParameters(e) { + return e ? recursiveEncodeParameters(e) : "" + } + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. All rights reserved. + Licensed under the Apache License, Version 2.0 (the "License"); you may not use + this file except in compliance with the License. You may obtain a copy of the + License at http://www.apache.org/licenses/LICENSE-2.0 + + THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED + WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, + MERCHANTABLITY OR NON-INFRINGEMENT. + + See the Apache Version 2.0 License for specific language governing permissions + and limitations under the License. + ***************************************************************************** */ + function __awaiter$2(e, s, n, d) { + return new (n || (n = Promise))((function(h, p) { + function fulfilled(e) { + try { + step(d.next(e)) + } catch (bt) { + p(bt) + } + } + function rejected(e) { + try { + step(d.throw(e)) + } catch (bt) { + p(bt) + } + } + function step(e) { + e.done ? h(e.value) : new n((function(s) { + s(e.value) + } + )).then(fulfilled, rejected) + } + step((d = d.apply(e, s || [])).next()) + } + )) + } + const AsyncDebounce = (e=100,s)=>(n,d,h)=>{ + const p = h.value + , y = asyncDebounce(p, e, s); + h.value = y + } + , asyncDebounce = (e,s=250,n={ + isImmediate: !1 + })=>{ + let d, h; + function fulfill(e) { + return hasOwn(n, "cancelledValue") ? null == e ? void 0 : e.resolve(n.cancelledValue) : null == e ? void 0 : e.reject(new Error("cancelled")) + } + const clearLastPromise = ()=>{ + d && (d.resolved || (fulfill(d), + d.timeoutId && clearTimeout(d.timeoutId)), + d = void 0) + } + , invokeFn = (s,n,h,p)=>{ + e.apply(s, p).then(e=>{ + n(e), + d && (d.resolved = !0) + } + ).catch(h) + } + ; + return n.isImmediate ? function(...e) { + const n = Date.now() + , p = this; + return h && n >= h && clearLastPromise(), + h = Date.now() + s, + d ? fulfill(Promise) : new Promise((s,n)=>{ + d = { + resolve: s, + reject: n + }, + invokeFn(p, s, n, e) + } + ) + } + : function(...e) { + const n = this; + return d && clearLastPromise(), + new Promise((function(h, p) { + const y = setTimeout(invokeFn.bind(void 0, n, h, p, e), s); + d = { + resolve: h, + reject: p, + timeoutId: y + } + } + )) + } + } + , Ke = isNodeEnvironment$1(); + class Browser { + constructor(e) { + var s; + e || (e = "undefined" != typeof window && (null === (s = null === window || void 0 === window ? void 0 : window.navigator) || void 0 === s ? void 0 : s.userAgent) ? window.navigator.userAgent : ""); + const n = e.toLowerCase(); + this.isEdge = /\sedge\//.test(n), + this.isChrome = !this.isEdge && /chrome/.test(n), + this.isSafari = !this.isEdge && !this.isChrome && /safari/.test(n), + this.isFirefox = !this.isEdge && !this.isChrome && !this.isSafari && /firefox/.test(n), + this.isIE = !this.isEdge && !this.isChrome && !this.isSafari && !this.isFirefox && /trident|msie/.test(n), + this.isMobile = /mobile/.test(n), + this.isAndroid = this.isMobile && /android/.test(n), + this.isiOS = this.isMobile && /iphone|ipad|ipod/.test(n), + this.isWebView = /(webview|(iphone|ipod|ipad)(?!.*safari\/)|android.*(wv|\.0\.0\.0)|\bfb[\w_]+\/(?:messenger)?|\binstagram|\btwitter)/.test(n), + this.isEdge ? this.engineVersion = n.match(/(?:edge).(\d+)/) : (this.version = n.match(/(?:chrome|version|firefox|msie|rv).(\d+)\.(\d+)/), + this.engineVersion = n.match(/(?:applewebkit|gecko|trident).(\d+)/)), + this.version && (this.majorVersion = parseInt(this.version[1], 10), + this.minorVersion = parseInt(this.version[2], 10)), + this.engineVersion && (this.engineMajorVersion = parseInt(this.engineVersion[1], 10)) + } + static supportsEs6() { + if ("undefined" == typeof Symbol) + return !1; + try { + new Function('"use strict";class Foo {}')(), + new Function('"use strict";var bar = (x) => x+1')() + } catch (bt) { + return !1 + } + return !0 + } + } + const Fe = new Browser + , Ve = { + AFG: "143610", + AGO: "143564", + AIA: "143538", + ALB: "143575", + AND: "143611", + ARE: "143481", + ARG: "143505", + ARM: "143524", + ATG: "143540", + AUS: "143460", + AUT: "143445", + AZE: "143568", + BEL: "143446", + BEN: "143576", + BFA: "143578", + BGD: "143490", + BGR: "143526", + BHR: "143559", + BHS: "143539", + BIH: "143612", + BLR: "143565", + BLZ: "143555", + BMU: "143542", + BOL: "143556", + BRA: "143503", + BRB: "143541", + BRN: "143560", + BTN: "143577", + BWA: "143525", + CAF: "143623", + CAN: "143455", + CHE: "143459", + CHL: "143483", + CHN: "143465", + CIV: "143527", + CMR: "143574", + COD: "143613", + COG: "143582", + COL: "143501", + CPV: "143580", + CRI: "143495", + CYM: "143544", + CYP: "143557", + CZE: "143489", + DEU: "143443", + DMA: "143545", + DNK: "143458", + DOM: "143508", + DZA: "143563", + ECU: "143509", + EGY: "143516", + ESP: "143454", + EST: "143518", + ETH: "143569", + FIN: "143447", + FJI: "143583", + FRA: "143442", + FSM: "143591", + GAB: "143614", + GBR: "143444", + GEO: "143615", + GHA: "143573", + GIN: "143616", + GMB: "143584", + GNB: "143585", + GRC: "143448", + GRD: "143546", + GTM: "143504", + GUY: "143553", + HKG: "143463", + HND: "143510", + HRV: "143494", + HUN: "143482", + IDN: "143476", + IND: "143467", + IRL: "143449", + IRQ: "143617", + ISL: "143558", + ISR: "143491", + ITA: "143450", + JAM: "143511", + JOR: "143528", + JPN: "143462", + KAZ: "143517", + KEN: "143529", + KGZ: "143586", + KHM: "143579", + KNA: "143548", + KOR: "143466", + KWT: "143493", + LAO: "143587", + LBN: "143497", + LBR: "143588", + LBY: "143567", + LCA: "143549", + LIE: "143522", + LKA: "143486", + LTU: "143520", + LUX: "143451", + LVA: "143519", + MAC: "143515", + MAR: "143620", + MCO: "143618", + MDA: "143523", + MDG: "143531", + MDV: "143488", + MEX: "143468", + MKD: "143530", + MLI: "143532", + MLT: "143521", + MMR: "143570", + MNE: "143619", + MNG: "143592", + MOZ: "143593", + MRT: "143590", + MSR: "143547", + MUS: "143533", + MWI: "143589", + MYS: "143473", + NAM: "143594", + NER: "143534", + NGA: "143561", + NIC: "143512", + NLD: "143452", + NOR: "143457", + NPL: "143484", + NRU: "143606", + NZL: "143461", + OMN: "143562", + PAK: "143477", + PAN: "143485", + PER: "143507", + PHL: "143474", + PLW: "143595", + PNG: "143597", + POL: "143478", + PRT: "143453", + PRY: "143513", + PSE: "143596", + QAT: "143498", + ROU: "143487", + RUS: "143469", + RWA: "143621", + SAU: "143479", + SEN: "143535", + SGP: "143464", + SLB: "143601", + SLE: "143600", + SLV: "143506", + SRB: "143500", + STP: "143598", + SUR: "143554", + SVK: "143496", + SVN: "143499", + SWE: "143456", + SWZ: "143602", + SYC: "143599", + TCA: "143552", + TCD: "143581", + THA: "143475", + TJK: "143603", + TKM: "143604", + TON: "143608", + TTO: "143551", + TUN: "143536", + TUR: "143480", + TWN: "143470", + TZA: "143572", + UGA: "143537", + UKR: "143492", + URY: "143514", + USA: "143441", + UZB: "143566", + VCT: "143550", + VEN: "143502", + VGB: "143543", + VNM: "143471", + VUT: "143609", + WSM: "143607", + XKX: "143624", + YEM: "143571", + ZAF: "143472", + ZMB: "143622", + ZWE: "143605" + } + , He = memoize(e=>{ + const s = new Uint16Array(e) + , n = s.length; + let d = ""; + for (let h = 0; h < n; h++) + d += String.fromCharCode(s[h]); + return d + } + ) + , ze = memoize(e=>{ + const s = b(e); + return qe(s) + } + ); + function ensureArray(e=[]) { + return Array.isArray(e) ? e : [e] + } + const qe = memoize(e=>{ + const s = e.length + , n = new ArrayBuffer(s) + , d = new Uint8Array(n); + for (let h = 0; h < s; h++) + d[h] = e.charCodeAt(h); + return d + } + ) + , We = memoize(e=>{ + const s = e.length + , n = new ArrayBuffer(2 * s) + , d = new Uint16Array(n); + for (let h = 0; h < s; h++) + d[h] = e.charCodeAt(h); + return d + } + ) + , Ye = memoize(e=>{ + let s, n, d, h, p, y, m, g = 0; + const v = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + let _ = ""; + for (; g < e.length; ) + s = e[g++], + n = g < e.length ? e[g++] : Number.NaN, + d = g < e.length ? e[g++] : Number.NaN, + h = s >> 2, + p = (3 & s) << 4 | n >> 4, + y = (15 & n) << 2 | d >> 6, + m = 63 & d, + isNaN(n) ? y = m = 64 : isNaN(d) && (m = 64), + _ += v.charAt(h) + v.charAt(p) + v.charAt(y) + v.charAt(m); + return _ + } + ); + let isMergeableObject = function(e) { + return function(e) { + return !!e && "object" == typeof e + }(e) && !function(e) { + let s = Object.prototype.toString.call(e); + return "[object RegExp]" === s || "[object Date]" === s || function(e) { + return e.$$typeof === Ge + }(e) + }(e) + }; + let Ge = "function" == typeof Symbol && Symbol.for ? Symbol.for("react.element") : 60103; + function cloneUnlessOtherwiseSpecified(e, s) { + return !1 !== s.clone && s.isMergeableObject(e) ? deepmerge((n = e, + Array.isArray(n) ? [] : {}), e, s) : e; + var n + } + function defaultArrayMerge(e, s, n) { + return e.concat(s).map((function(e) { + return cloneUnlessOtherwiseSpecified(e, n) + } + )) + } + function getKeys(e) { + return Object.keys(e).concat(function(e) { + return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(e).filter((function(s) { + return e.propertyIsEnumerable(s) + } + )) : [] + }(e)) + } + function mergeObject(e, s, n) { + let d = {}; + return n.isMergeableObject(e) && getKeys(e).forEach((function(s) { + d[s] = cloneUnlessOtherwiseSpecified(e[s], n) + } + )), + getKeys(s).forEach((function(h) { + n.isMergeableObject(s[h]) && e[h] ? d[h] = function(e, s) { + if (!s.customMerge) + return deepmerge; + let n = s.customMerge(e); + return "function" == typeof n ? n : deepmerge + }(h, n)(e[h], s[h], n) : d[h] = cloneUnlessOtherwiseSpecified(s[h], n) + } + )), + d + } + function deepmerge(e, s, n) { + (n = n || {}).arrayMerge = n.arrayMerge || defaultArrayMerge, + n.isMergeableObject = n.isMergeableObject || isMergeableObject; + let d = Array.isArray(s); + return d === Array.isArray(e) ? d ? n.arrayMerge(e, s, n) : mergeObject(e, s, n) : cloneUnlessOtherwiseSpecified(s, n) + } + var Qe; + deepmerge.all = function(e, s) { + if (!Array.isArray(e)) + throw new Error("first argument should be an array"); + return e.reduce((function(e, n) { + return deepmerge(e, n, s) + } + ), {}) + } + , + function(e) { + e.dataRecordDidDelete = "dataRecordDidDelete", + e.dataRecordWillDelete = "dataRecordWillDelete", + e.dataRecordDidMaterialize = "dataRecordDidMaterialize", + e.dataRecordDidPopulate = "dataRecordDidPopulate", + e.dataRecordWillPopulate = "dataRecordWillPopulate" + }(Qe || (Qe = {})); + const isDataRecord = e=>!(!e || "function" != typeof e.hasAttributes || "function" != typeof e.hasRelationships || "function" != typeof e.hasViews || "function" != typeof e.serialize); + class DataRecord { + constructor(e, s, n={}) { + this.type = e, + this.id = s, + this._mjs = { + attributes: [], + relationships: [], + views: [] + }, + this._meta = {}, + this._mjs = Object.assign(Object.assign({}, this._mjs), n) + } + hasProperties(e) { + return !e || (e.attributes || e.relationships || e.views ? !(e.attributes && !this.hasAttributes(e.attributes)) && (!(e.relationships && !this.hasRelationships(e.relationships)) && !(e.views && !this.hasViews(e.views))) : this.hasAttributes() || this.hasRelationships() || this.hasViews()) + } + hasAttributes(e) { + return this._hasProperties(this._mjs.attributes, e) + } + hasRelationships(e) { + return this._hasProperties(this._mjs.relationships, e) + } + hasViews(e) { + return this._hasProperties(this._mjs.views, e) + } + meta(e) { + return e ? this._meta[e] : this._meta + } + serialize(e=!0, s={}, n={}) { + const d = { + id: this.id, + type: this.type + }; + return s[`${this.type}-${this.id}`] && !n.allowFullDuplicateSerializations ? d : (s[`${this.type}-${this.id}`] = !0, + this.hasAttributes() && (d.attributes = this._mjs.attributes.reduce((e,s)=>(e[s] = this[s], + e), {})), + this._mjs.relationships.length > 0 && (d.relationships = this._serializeRelatedData(this._mjs.relationships, s, n)), + this._mjs.views.length > 0 && (d.views = this._serializeRelatedData(this._mjs.views, s, n)), + e ? { + data: d + } : d) + } + setProperty(e, s, n="attributes", d={}) { + function isMergeableObject(e) { + return !(!e || "object" != typeof e || e instanceof DataRecord) + } + hasOwn(this, e) || (this._mjs[n] || (this._mjs[n] = []), + this._mjs[n].push(e)); + const setDescriptor = e=>({ + value: e, + writable: !0, + configurable: !0, + enumerable: !0 + }); + this[e] && s && "object" == typeof this[e] && "object" == typeof s ? "attributes" === n ? Object.defineProperty(this, e, setDescriptor(deepmerge(this[e], s, { + arrayMerge: function(e, s, n) { + return s + }, + isMergeableObject: isMergeableObject + }))) : "relationships" === n && Array.isArray(this[e]) && d.extendRelationships ? Object.defineProperty(this, e, setDescriptor(deepmerge(this[e], s, { + isMergeableObject: isMergeableObject + }))) : Object.defineProperty(this, e, setDescriptor(s)) : Object.defineProperty(this, e, setDescriptor(s)) + } + removeRelative(e, s) { + this[e] && (Array.isArray(this[e]) ? this[e] = this[e].filter(e=>e.id !== s) : delete this[e]) + } + setParent(e) { + const s = this._mjs.parents + , n = s && s.length > 0; + this._mjs.parents = n ? s.concat(e) : e + } + _hasProperties(e, s) { + return !!e && (s ? ensureArray(s).every(s=>e.includes(s)) : e.length > 0) + } + _serializeRelatedData(e, s={}, n={}) { + return e.reduce((e,d)=>{ + if (n.excludeRelationships && n.excludeRelationships.has(d)) + return e; + if (n.includeRelationships && !n.includeRelationships.has(d)) + return e; + const h = this[d]; + return Array.isArray(h) ? e[d] = { + data: h.map(e=>"function" == typeof e.serialize ? e.serialize(!1, s, n) : e) + } : e[d] = h && "function" == typeof h.serialize ? h.serialize(!1, s, n) : h, + e + } + , {}) + } + } + class DataStore extends Notifications { + constructor(e={}) { + super([Qe.dataRecordDidDelete, Qe.dataRecordWillDelete, Qe.dataRecordDidMaterialize, Qe.dataRecordWillPopulate, Qe.dataRecordDidPopulate]), + this._removeOnExpiration = !1, + this._shouldDisableRecordReuse = !0, + this._records = {}, + this._expiryRecords = new Set, + this._removeOnExpiration = !!e.removeOnExpiration, + this._mapping = e.mapping, + this._shouldDisableRecordReuse = !!e.shouldDisableRecordReuse, + this.filter = e.filter + } + get mapping() { + return this._mapping + } + set mapping(e) { + this._mapping = e + } + clear() { + this._records = {}, + this._expiryRecords = new Set + } + peek(e, s, n) { + if (this._checkForExpiredRecords(), + !this._records[e]) + return s ? null : []; + if (!s) + return Object.values(this._records[e]); + if (Array.isArray(s)) + return s.map(s=>{ + const d = this._records[e][s]; + if (d && d.hasProperties(n)) + return d + } + ); + const d = this._records[e][s]; + return d && d.hasProperties(n) ? d : null + } + populateDataRecords(e, s={}, n={}) { + if (!e.data) + return []; + if (!Array.isArray(e.data)) + return this.populateDataRecord(e.data, s, n); + const d = []; + return e.data.forEach((e,h)=>{ + const p = Object.assign(Object.assign({}, n), { + parents: n.parents ? [Object.assign(Object.assign({}, n.parents[0]), { + position: h + })] : [] + }); + n.parents && (n.parents[0].position = h); + const y = this.populateDataRecord(e, s, p); + d.push(y) + } + ), + d + } + populateDataRecord(e, s={}, n) { + const d = n.filter || this.filter + , h = n.mapping || this.mapping; + if (d && !d(e)) + return; + if (h) { + let s = "function" == typeof h ? h(e) : transform$9(h, e); + Object.assign(e, s) + } + this._shouldDisableRecordReuse && (s = {}); + const p = this._materializeRecord(s, Object.assign({ + id: e.id, + type: e.type + }, n)); + return e.meta && (p._meta = e.meta), + e.attributes && e.attributes.cachingPolicy && e.attributes.cachingPolicy.maxAge && (p._mjs.expiration = Date.now() + 1e3 * e.attributes.cachingPolicy.maxAge, + this._removeOnExpiration && this._expiryRecords.add(p)), + this._populateDataAttributes(e, p), + "object" == typeof e.relationships && Object.keys(e.relationships).forEach(d=>{ + let y = e.relationships[d]; + y && "data"in y && (y = this.populateDataRecords(y, s, { + mapping: h, + parents: [{ + relationshipName: d, + parentType: p.type, + parentId: p.id + }] + }), + p.setProperty(d, y, "relationships", n)) + } + ), + "object" == typeof e.views && Object.keys(e.views).forEach(n=>{ + const d = e.views[n]; + if (d.attributes || d.data) { + const e = new DataRecord("view",n); + if (this._populateDataAttributes(d, e), + d.data) { + const n = this.populateDataRecords(d, s, h); + e.setProperty("data", n, "relationships") + } + p.setProperty(n, e, "views") + } + } + ), + p + } + query(e, s) { + this._checkForExpiredRecords(); + let includeRecord = e=>!1; + return "string" == typeof e && s ? includeRecord = n=>(null == n ? void 0 : n[e]) === s : "function" == typeof e ? includeRecord = s=>{ + try { + return e(s) + } catch (bt) { + return !1 + } + } + : "object" == typeof e && (includeRecord = s=>{ + const n = Object.keys(e); + let d = 0; + return n.forEach(n=>{ + (null == s ? void 0 : s[n]) === e[n] && d++ + } + ), + n.length === d + } + ), + Object.values(this._records).reduce((e,s)=>(Object.values(s).forEach(s=>{ + includeRecord(s) && e.push(s) + } + ), + e), []) + } + remove(e, s) { + setTimeout(this._checkForExpiredRecords.bind(this), 0); + if (!hasOwn(this._records, e)) + return; + const n = this.peek(e, s); + n && (this.dispatchEvent(Qe.dataRecordWillDelete, [e, s]), + n._mjs.parents && n._mjs.parents.length > 0 && n._mjs.parents.forEach(({relationshipName: e, parentType: s, parentId: d})=>{ + this.peek(s, d).removeRelative(e, n.id) + } + ), + delete this._records[e][s], + this.dispatchEvent(Qe.dataRecordDidDelete, [e, s])) + } + save(e, s={}) { + return setTimeout(this._checkForExpiredRecords.bind(this), 0), + this.populateDataRecords(e, this._records, s) + } + _populateDataAttributes(e, s) { + "object" == typeof e.attributes && (this.dispatchEvent(Qe.dataRecordWillPopulate, [s.type, s.id]), + Object.keys(e.attributes).forEach(n=>{ + s.setProperty(n, e.attributes[n], "attributes") + } + ), + this.dispatchEvent(Qe.dataRecordDidPopulate, [s.type, s.id])) + } + _materializeRecord(e, s) { + const {type: n, id: d} = s + , h = function(e, s) { + var n = {}; + for (var d in e) + Object.prototype.hasOwnProperty.call(e, d) && s.indexOf(d) < 0 && (n[d] = e[d]); + if (null != e && "function" == typeof Object.getOwnPropertySymbols) { + var h = 0; + for (d = Object.getOwnPropertySymbols(e); h < d.length; h++) + s.indexOf(d[h]) < 0 && (n[d[h]] = e[d[h]]) + } + return n + }(s, ["type", "id"]); + return e[n] = e[n] || {}, + e[n][d] ? e[n][d].setParent(h.parents || []) : e[n][d] = new DataRecord(n,d,h), + this.dispatchEvent(Qe.dataRecordDidMaterialize, [n, d]), + e[n][d] + } + _checkForExpiredRecords() { + const e = []; + this._expiryRecords.forEach(s=>{ + Date.now() > s._mjs.expiration && (e.push([s.type, s.id]), + this._expiryRecords.delete(s)) + } + ), + e.forEach(e=>{ + this.remove(...e) + } + ) + } + } + const logDeprecation = (e,s={})=>{ + if (O && O.enabled) { + const n = []; + n.push("Deprecation warning:"), + n.push(s.message || e + " has been deprecated."), + void 0 !== s.until && n.push(`${e} will be removed in version ${s.until}.`), + O.warn(n.join(" ")) + } + } + ; + const Je = { + AW: "ABW", + AF: "AFG", + AO: "AGO", + AI: "AIA", + AX: "ALA", + AL: "ALB", + AD: "AND", + AE: "ARE", + AR: "ARG", + AM: "ARM", + AS: "ASM", + AQ: "ATA", + TF: "ATF", + AG: "ATG", + AU: "AUS", + AT: "AUT", + AZ: "AZE", + BI: "BDI", + BE: "BEL", + BJ: "BEN", + BQ: "BES", + BF: "BFA", + BD: "BGD", + BG: "BGR", + BH: "BHR", + BS: "BHS", + BA: "BIH", + BL: "BLM", + BY: "BLR", + BZ: "BLZ", + BM: "BMU", + BO: "BOL", + BR: "BRA", + BB: "BRB", + BN: "BRN", + BT: "BTN", + BV: "BVT", + BW: "BWA", + CF: "CAF", + CA: "CAN", + CC: "CCK", + CH: "CHE", + CL: "CHL", + CN: "CHN", + CI: "CIV", + CM: "CMR", + CD: "COD", + CG: "COG", + CK: "COK", + CO: "COL", + KM: "COM", + CV: "CPV", + CR: "CRI", + CU: "CUB", + CW: "CUW", + CX: "CXR", + KY: "CYM", + CY: "CYP", + CZ: "CZE", + DE: "DEU", + DJ: "DJI", + DM: "DMA", + DK: "DNK", + DO: "DOM", + DZ: "DZA", + EC: "ECU", + EG: "EGY", + ER: "ERI", + EH: "ESH", + ES: "ESP", + EE: "EST", + ET: "ETH", + FI: "FIN", + FJ: "FJI", + FK: "FLK", + FR: "FRA", + FO: "FRO", + FM: "FSM", + GA: "GAB", + GB: "GBR", + GE: "GEO", + GG: "GGY", + GH: "GHA", + GI: "GIB", + GN: "GIN", + GP: "GLP", + GM: "GMB", + GW: "GNB", + GQ: "GNQ", + GR: "GRC", + GD: "GRD", + GL: "GRL", + GT: "GTM", + GF: "GUF", + GU: "GUM", + GY: "GUY", + HK: "HKG", + HM: "HMD", + HN: "HND", + HR: "HRV", + HT: "HTI", + HU: "HUN", + ID: "IDN", + IM: "IMN", + IN: "IND", + IO: "IOT", + IE: "IRL", + IR: "IRN", + IQ: "IRQ", + IS: "ISL", + IL: "ISR", + IT: "ITA", + JM: "JAM", + JE: "JEY", + JO: "JOR", + JP: "JPN", + KZ: "KAZ", + KE: "KEN", + KG: "KGZ", + KH: "KHM", + KI: "KIR", + KN: "KNA", + KR: "KOR", + KW: "KWT", + LA: "LAO", + LB: "LBN", + LR: "LBR", + LY: "LBY", + LC: "LCA", + LI: "LIE", + LK: "LKA", + LS: "LSO", + LT: "LTU", + LU: "LUX", + LV: "LVA", + MO: "MAC", + MF: "MAF", + MA: "MAR", + MC: "MCO", + MD: "MDA", + MG: "MDG", + MV: "MDV", + MX: "MEX", + MH: "MHL", + MK: "MKD", + ML: "MLI", + MT: "MLT", + MM: "MMR", + ME: "MNE", + MN: "MNG", + MP: "MNP", + MZ: "MOZ", + MR: "MRT", + MS: "MSR", + MQ: "MTQ", + MU: "MUS", + MW: "MWI", + MY: "MYS", + YT: "MYT", + NA: "NAM", + NC: "NCL", + NE: "NER", + NF: "NFK", + NG: "NGA", + NI: "NIC", + NU: "NIU", + NL: "NLD", + NO: "NOR", + NP: "NPL", + NR: "NRU", + NZ: "NZL", + OM: "OMN", + PK: "PAK", + PA: "PAN", + PN: "PCN", + PE: "PER", + PH: "PHL", + PW: "PLW", + PG: "PNG", + PL: "POL", + PR: "PRI", + KP: "PRK", + PT: "PRT", + PY: "PRY", + PS: "PSE", + PF: "PYF", + QA: "QAT", + RE: "REU", + RO: "ROU", + RU: "RUS", + RW: "RWA", + SA: "SAU", + SD: "SDN", + SN: "SEN", + SG: "SGP", + GS: "SGS", + SH: "SHN", + SJ: "SJM", + SB: "SLB", + SL: "SLE", + SV: "SLV", + SM: "SMR", + SO: "SOM", + PM: "SPM", + RS: "SRB", + SS: "SSD", + ST: "STP", + SR: "SUR", + SK: "SVK", + SI: "SVN", + SE: "SWE", + SZ: "SWZ", + SX: "SXM", + SC: "SYC", + SY: "SYR", + TC: "TCA", + TD: "TCD", + TG: "TGO", + TH: "THA", + TJ: "TJK", + TK: "TKL", + TM: "TKM", + TL: "TLS", + TO: "TON", + TT: "TTO", + TN: "TUN", + TR: "TUR", + TV: "TUV", + TW: "TWN", + TZ: "TZA", + UG: "UGA", + UA: "UKR", + UM: "UMI", + UY: "URY", + US: "USA", + UZ: "UZB", + VA: "VAT", + VC: "VCT", + VE: "VEN", + VG: "VGB", + VI: "VIR", + VN: "VNM", + VU: "VUT", + WF: "WLF", + WS: "WSM", + XK: "XKX", + YE: "YEM", + ZA: "ZAF", + ZM: "ZMB", + ZW: "ZWE" + }; + class PubSub { + constructor() { + this.events = {} + } + publish(e, s) { + const n = this.getSubscribersForType(e); + void 0 !== n && n.forEach(n=>{ + n(e, s) + } + ) + } + subscribe(e, s) { + this.getSubscribersForType(e, !0).push(s) + } + subscribeOnce(e, s) { + const onceCallback = (e,n)=>{ + this.unsubscribe(e, onceCallback), + s(e, n) + } + ; + this.subscribe(e, onceCallback) + } + unsubscribe(e, s) { + const n = this.getSubscribersForType(e); + if (void 0 !== n) + for (const d in n) + if (n[d] === s) { + delete n[d]; + break + } + } + clear(e) { + void 0 === e ? this.events = {} : delete this.events[e] + } + getSubscribersForType(e, s=!1) { + return !this.events.hasOwnProperty(e) && s && (this.events[e] = []), + this.events[e] + } + } + const Xe = {} + , SerialAsync = e=>{ + let s = Promise.resolve(); + return (n,d,h)=>{ + const p = h.value; + return h.value = function(...n) { + return __awaiter$2(this, void 0, void 0, (function*() { + return e && (s = (e=>{ + let s = Xe[e]; + return s || (s = Promise.resolve(), + Xe[e] = s), + s + } + )(e)), + s = s.catch(()=>{} + ).then(()=>p.apply(this, n)), + e && (Xe[e] = s), + s + } + )) + } + , + h + } + } + ; + var Ze, et, tt, it, st, rt, nt, at, ot; + e.PlaybackBitrate = void 0, + (Ze = e.PlaybackBitrate || (e.PlaybackBitrate = {}))[Ze.STANDARD = 64] = "STANDARD", + Ze[Ze.HIGH = 256] = "HIGH", + function(e) { + e.apiStorefrontChanged = "apiStorefrontChanged", + e.hlsLevelUpdated = "hlsLevelUpdated", + e.mediaContentComplete = "mediaContentComplete", + e.playbackPause = "playbackPause", + e.playbackPlay = "playbackPlay", + e.playbackScrub = "playbackScrub", + e.playbackSeek = "playbackSeek", + e.playbackSkip = "playbackSkip", + e.playbackStop = "playbackStop", + e.playerActivate = "playerActivate", + e.playerExit = "playerExit", + e.queueModified = "queueModified", + e.userActivityIntent = "userActivityIntent", + e.applicationActivityIntent = "applicationActivityIntent" + }(et || (et = {})), + function(e) { + e.MUSICKIT = "music_kit-integration", + e.OTHER = "other", + e.MINI = "mini", + e.SONG = "song", + e.ALBUM = "album", + e.ALBUM_CLASSICAL = "album-classical", + e.ARTIST = "artist", + e.COMPILATION = "compilation", + e.COMPILATION_CLASSICAL = "compilation-classical", + e.PLAYLIST = "playlist", + e.PLAYLIST_CLASSICAL = "playlist-classical", + e.RADIO = "radio", + e.SEARCH = "search", + e.STATION = "station" + }(tt || (tt = {})), + function(e) { + e[e.UNKNOWN = 0] = "UNKNOWN", + e[e.RADIO = 1] = "RADIO", + e[e.PLAYLIST = 2] = "PLAYLIST", + e[e.ALBUM = 3] = "ALBUM", + e[e.ARTIST = 4] = "ARTIST" + }(it || (it = {})), + e.PlayActivityEndReasonType = void 0, + (st = e.PlayActivityEndReasonType || (e.PlayActivityEndReasonType = {}))[st.NOT_APPLICABLE = 0] = "NOT_APPLICABLE", + st[st.OTHER = 1] = "OTHER", + st[st.TRACK_SKIPPED_FORWARDS = 2] = "TRACK_SKIPPED_FORWARDS", + st[st.PLAYBACK_MANUALLY_PAUSED = 3] = "PLAYBACK_MANUALLY_PAUSED", + st[st.PLAYBACK_SUSPENDED = 4] = "PLAYBACK_SUSPENDED", + st[st.MANUALLY_SELECTED_PLAYBACK_OF_A_DIFF_ITEM = 5] = "MANUALLY_SELECTED_PLAYBACK_OF_A_DIFF_ITEM", + st[st.PLAYBACK_PAUSED_DUE_TO_INACTIVITY = 6] = "PLAYBACK_PAUSED_DUE_TO_INACTIVITY", + st[st.NATURAL_END_OF_TRACK = 7] = "NATURAL_END_OF_TRACK", + st[st.PLAYBACK_STOPPED_DUE_TO_SESSION_TIMEOUT = 8] = "PLAYBACK_STOPPED_DUE_TO_SESSION_TIMEOUT", + st[st.TRACK_BANNED = 9] = "TRACK_BANNED", + st[st.FAILED_TO_LOAD = 10] = "FAILED_TO_LOAD", + st[st.PAUSED_ON_TIMEOUT = 11] = "PAUSED_ON_TIMEOUT", + st[st.SCRUB_BEGIN = 12] = "SCRUB_BEGIN", + st[st.SCRUB_END = 13] = "SCRUB_END", + st[st.TRACK_SKIPPED_BACKWARDS = 14] = "TRACK_SKIPPED_BACKWARDS", + st[st.NOT_SUPPORTED_BY_CLIENT = 15] = "NOT_SUPPORTED_BY_CLIENT", + st[st.QUICK_PLAY = 16] = "QUICK_PLAY", + st[st.EXITED_APPLICATION = 17] = "EXITED_APPLICATION", + function(e) { + e[e.Manual = 0] = "Manual", + e[e.Interval = 1] = "Interval", + e[e.SkipIntro = 2] = "SkipIntro" + }(rt || (rt = {})), + function(e) { + e[e.UNKNOWN = 0] = "UNKNOWN", + e[e.NO_RIGHTS = 1] = "NO_RIGHTS", + e[e.PURCHASED = 2] = "PURCHASED", + e[e.UPLOADED = 3] = "UPLOADED", + e[e.MATCHED = 4] = "MATCHED", + e[e.ADDED = 5] = "ADDED", + e[e.SUBSCRIBED = 6] = "SUBSCRIBED", + e[e.NOT_SUPPORTED = 7] = "NOT_SUPPORTED" + }(nt || (nt = {})), + function(e) { + e[e.NO_SELECTION_PLAY = 0] = "NO_SELECTION_PLAY", + e[e.RESUME_LAST_PLAYED_SONG = 1] = "RESUME_LAST_PLAYED_SONG", + e[e.RESUME_CURRENT_DEVICE_POSITION = 2] = "RESUME_CURRENT_DEVICE_POSITION" + }(at || (at = {})), + function(e) { + e[e.NOT_APPLICABLE = 0] = "NOT_APPLICABLE", + e[e.SIMILARITIES = 1] = "SIMILARITIES", + e[e.ESSENTIALS = 2] = "ESSENTIALS", + e[e.USER_LIBRARY = 3] = "USER_LIBRARY", + e[e.ALGO_HEATSEEKER = 4] = "ALGO_HEATSEEKER", + e[e.SEED_TRACK = 5] = "SEED_TRACK", + e[e.GN_1M_TEMPORARY = 6] = "GN_1M_TEMPORARY", + e[e.VECTOR = 8] = "VECTOR", + e[e.ARTIST_SIMILARITIES = 9] = "ARTIST_SIMILARITIES", + e[e.STORY_ALBUM_LISTENERS_ALSO_BOUGHT = 10] = "STORY_ALBUM_LISTENERS_ALSO_BOUGHT", + e[e.STORY_ALBUM_SALES_LEADER = 11] = "STORY_ALBUM_SALES_LEADER", + e[e.STORY_BILLBOARD = 12] = "STORY_BILLBOARD", + e[e.STORY_COMPLETE_MY_ALBUM = 13] = "STORY_COMPLETE_MY_ALBUM", + e[e.STORY_CRITICAL_PICK = 14] = "STORY_CRITICAL_PICK", + e[e.STORY_ITUNES_ESSENTIAL = 15] = "STORY_ITUNES_ESSENTIAL", + e[e.STORY_HEATSEEKER = 16] = "STORY_HEATSEEKER", + e[e.STORY_IDENTITY = 17] = "STORY_IDENTITY", + e[e.STORY_POWER_SONG = 18] = "STORY_POWER_SONG", + e[e.STORY_SONG_SALES_LEADER = 20] = "STORY_SONG_SALES_LEADER", + e[e.GENRE_SIMILARITIES = 21] = "GENRE_SIMILARITIES", + e[e.STORY_IMIX = 22] = "STORY_IMIX", + e[e.STORY_OTHER_MIX = 23] = "STORY_OTHER_MIX", + e[e.EDITORIAL = 24] = "EDITORIAL", + e[e.TOP_SONGS = 25] = "TOP_SONGS", + e[e.SUBFORMAT_SONGS = 26] = "SUBFORMAT_SONGS", + e[e.CRITICAL_PICKS = 27] = "CRITICAL_PICKS", + e[e.US_ARTIST_SIMS = 28] = "US_ARTIST_SIMS", + e[e.HEAVY_ROTATION = 29] = "HEAVY_ROTATION", + e[e.STORY_FORMAT_STATION_HEAVY_ROTATION = 30] = "STORY_FORMAT_STATION_HEAVY_ROTATION", + e[e.ARTIST_BASED_CORE_SIMILAR_ARTISTS = 31] = "ARTIST_BASED_CORE_SIMILAR_ARTISTS", + e[e.ARTIST_BASED_FAMILIAR_SIMILAR_ARTISTS = 32] = "ARTIST_BASED_FAMILIAR_SIMILAR_ARTISTS", + e[e.ARTIST_BASED_DISCOVERIES = 33] = "ARTIST_BASED_DISCOVERIES", + e[e.ARTIST_BASED_HOT_SONGS = 34] = "ARTIST_BASED_HOT_SONGS", + e[e.ARTIST_BASED_SEED_ARTIST = 35] = "ARTIST_BASED_SEED_ARTIST", + e[e.ARTIST_BASED_COMPOSER = 36] = "ARTIST_BASED_COMPOSER", + e[e.EDITORIAL_STATION_INTRO = 37] = "EDITORIAL_STATION_INTRO", + e[e.EDITORIAL_RELATIVE_REPEAT = 38] = "EDITORIAL_RELATIVE_REPEAT", + e[e.EDITORIAL_ABSOLUTE_REPEAT = 39] = "EDITORIAL_ABSOLUTE_REPEAT", + e[e.EDITORIAL_SCHEDULED = 40] = "EDITORIAL_SCHEDULED", + e[e.EDITORIAL_SUGGESTED_ARTIST = 41] = "EDITORIAL_SUGGESTED_ARTIST", + e[e.FOR_YOU_FAMILIAR = 42] = "FOR_YOU_FAMILIAR", + e[e.FOR_YOU_RECOMMENDED = 43] = "FOR_YOU_RECOMMENDED", + e[e.FOR_YOU_FAVORITE_ARTIST = 44] = "FOR_YOU_FAVORITE_ARTIST", + e[e.FOR_YOU_RECOMMENDED_ARTIST = 45] = "FOR_YOU_RECOMMENDED_ARTIST", + e[e.EDITORIAL_POSITIONAL = 46] = "EDITORIAL_POSITIONAL", + e[e.SIMILAR_SONGS = 47] = "SIMILAR_SONGS", + e[e.SONG_ATTRIBUTE_FAVORITE_ARTIST = 48] = "SONG_ATTRIBUTE_FAVORITE_ARTIST", + e[e.SONG_ATTRIBUTE_FAVORITE_ARTIST_DERIVED = 49] = "SONG_ATTRIBUTE_FAVORITE_ARTIST_DERIVED", + e[e.SONG_ATTRIBUTE_FAVORITE_ARTIST_EDITORIAL = 50] = "SONG_ATTRIBUTE_FAVORITE_ARTIST_EDITORIAL", + e[e.SONG_ATTRIBUTE_RECOMMENDED = 51] = "SONG_ATTRIBUTE_RECOMMENDED", + e[e.SONG_ATTRIBUTE_RECOMMENDED_DERIVED = 52] = "SONG_ATTRIBUTE_RECOMMENDED_DERIVED", + e[e.SONG_ATTRIBUTE_RECOMMENDED_EDITORIAL = 53] = "SONG_ATTRIBUTE_RECOMMENDED_EDITORIAL", + e[e.SONG_ATTRIBUTE_NON_PERSONALIZED = 54] = "SONG_ATTRIBUTE_NON_PERSONALIZED", + e[e.SONG_ATTRIBUTE_NON_PERSONALIZED_DERIVED = 55] = "SONG_ATTRIBUTE_NON_PERSONALIZED_DERIVED", + e[e.SONG_ATTRIBUTE_NON_PERSONALIZED_EDITORIAL = 56] = "SONG_ATTRIBUTE_NON_PERSONALIZED_EDITORIAL", + e[e.PERSONAL_STATION = 57] = "PERSONAL_STATION", + e[e.PERSONAL_STATION_FAVORITE_ARTIST = 58] = "PERSONAL_STATION_FAVORITE_ARTIST", + e[e.PERSONAL_STATION_RECOMMENDED = 59] = "PERSONAL_STATION_RECOMMENDED", + e[e.NEW_MUSIC_STATION = 60] = "NEW_MUSIC_STATION", + e[e.NEW_MUSIC_STATION_FAVORITE_ARTIST = 61] = "NEW_MUSIC_STATION_FAVORITE_ARTIST", + e[e.NEW_MUSIC_STATION_RECOMMENDED = 62] = "NEW_MUSIC_STATION_RECOMMENDED" + }(ot || (ot = {})); + var dt, lt, ct, ut, ht, pt, yt, mt, gt, ft, vt, _t; + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + function __rest$1(e, s) { + var n = {}; + for (var d in e) + Object.prototype.hasOwnProperty.call(e, d) && s.indexOf(d) < 0 && (n[d] = e[d]); + if (null != e && "function" == typeof Object.getOwnPropertySymbols) { + var h = 0; + for (d = Object.getOwnPropertySymbols(e); h < d.length; h++) + s.indexOf(d[h]) < 0 && Object.prototype.propertyIsEnumerable.call(e, d[h]) && (n[d[h]] = e[d[h]]) + } + return n + } + function __metadata$1(e, s) { + if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) + return Reflect.metadata(e, s) + } + function __awaiter$1(e, s, n, d) { + return new (n || (n = Promise))((function(h, p) { + function fulfilled(e) { + try { + step(d.next(e)) + } catch (bt) { + p(bt) + } + } + function rejected(e) { + try { + step(d.throw(e)) + } catch (bt) { + p(bt) + } + } + function step(e) { + var s; + e.done ? h(e.value) : (s = e.value, + s instanceof n ? s : new n((function(e) { + e(s) + } + ))).then(fulfilled, rejected) + } + step((d = d.apply(e, s || [])).next()) + } + )) + } + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + function t(e, s) { + var n = "function" == typeof Symbol && e[Symbol.iterator]; + if (!n) + return e; + var d, h, p = n.call(e), y = []; + try { + for (; (void 0 === s || s-- > 0) && !(d = p.next()).done; ) + y.push(d.value) + } catch (e) { + h = { + error: e + } + } finally { + try { + d && !d.done && (n = p.return) && n.call(p) + } finally { + if (h) + throw h.error + } + } + return y + } + !function(e) { + e[e.UNSPECIFIED = 0] = "UNSPECIFIED", + e[e.STATIC = 1] = "STATIC", + e[e.TIME_SYNCED = 2] = "TIME_SYNCED" + }(dt || (dt = {})), + function(e) { + e[e.REPEAT_UNKNOWN = 0] = "REPEAT_UNKNOWN", + e[e.REPEAT_OFF = 1] = "REPEAT_OFF", + e[e.REPEAT_ONE = 2] = "REPEAT_ONE", + e[e.REPEAT_ALL = 3] = "REPEAT_ALL" + }(lt || (lt = {})), + function(e) { + e[e.SHUFFLE_UNKNOWN = 0] = "SHUFFLE_UNKNOWN", + e[e.SHUFFLE_OFF = 1] = "SHUFFLE_OFF", + e[e.SHUFFLE_ON = 2] = "SHUFFLE_ON" + }(ct || (ct = {})), + function(e) { + e[e.AUTO_UNKNOWN = 0] = "AUTO_UNKNOWN", + e[e.AUTO_OFF = 1] = "AUTO_OFF", + e[e.AUTO_ON = 2] = "AUTO_ON", + e[e.AUTO_ON_CONTENT_UNSUPPORTED = 3] = "AUTO_ON_CONTENT_UNSUPPORTED" + }(ut || (ut = {})), + function(e) { + e[e.NOT_SPECIFIED = 0] = "NOT_SPECIFIED", + e[e.CONTAINER_CHANGED = 1] = "CONTAINER_CHANGED" + }(ht || (ht = {})), + function(e) { + e[e.PLAY_END = 0] = "PLAY_END", + e[e.PLAY_START = 1] = "PLAY_START", + e[e.LYRIC_DISPLAY = 2] = "LYRIC_DISPLAY" + }(pt || (pt = {})), + function(e) { + e[e.INVALID = 0] = "INVALID", + e[e.ITUNES_STORE_CONTENT = 1] = "ITUNES_STORE_CONTENT", + e[e.NON_SONG_CLIP = 2] = "NON_SONG_CLIP", + e[e.AD = 3] = "AD", + e[e.STREAM = 4] = "STREAM", + e[e.AUDIO_AD = 5] = "AUDIO_AD", + e[e.VIDEO_AD = 6] = "VIDEO_AD", + e[e.TIMED_METADATA_PING = 7] = "TIMED_METADATA_PING", + e[e.ARTIST_UPLOADED_CONTENT = 8] = "ARTIST_UPLOADED_CONTENT", + e[e.AGGREGATE_NON_CATALOG_PLAY_TIME = 9] = "AGGREGATE_NON_CATALOG_PLAY_TIME", + e[e.ORIGINAL_CONTENT_MOVIES = 10] = "ORIGINAL_CONTENT_MOVIES", + e[e.ORIGINAL_CONTENT_SHOWS = 11] = "ORIGINAL_CONTENT_SHOWS" + }(yt || (yt = {})), + function(e) { + e[e.AUDIO = 0] = "AUDIO", + e[e.VIDEO = 1] = "VIDEO" + }(mt || (mt = {})), + function(e) { + e[e.AUTO = 0] = "AUTO", + e[e.MANUAL = 1] = "MANUAL" + }(gt || (gt = {})), + function(e) { + e[e.ORIGINATING_DEVICE = 0] = "ORIGINATING_DEVICE", + e[e.PAIRED_WATCH = 1] = "PAIRED_WATCH", + e[e.SONOS = 2] = "SONOS", + e[e.CAR_PLAY = 3] = "CAR_PLAY", + e[e.WEB_AUC = 4] = "WEB_AUC", + e[e.TWITTER_AUC = 5] = "TWITTER_AUC", + e[e.MUSIC_SDK = 6] = "MUSIC_SDK", + e[e.ATV_REMOTE = 7] = "ATV_REMOTE", + e[e.WEBPLAYER = 8] = "WEBPLAYER", + e[e.WHOLE_HOUSE_AUDIO = 9] = "WHOLE_HOUSE_AUDIO", + e[e.MUSICKIT = 10] = "MUSICKIT", + e[e.VW = 11] = "VW", + e[e.UNKNOWN_SOURCE_TYPE = 12] = "UNKNOWN_SOURCE_TYPE", + e[e.AMAZON = 13] = "AMAZON", + e[e.PORSCHE = 14] = "PORSCHE", + e[e.CHROMECAST = 15] = "CHROMECAST", + e[e.WEB_APP = 16] = "WEB_APP", + e[e.MERCEDES_BENZ = 17] = "MERCEDES_BENZ", + e[e.THIRD_PARTY_TV = 18] = "THIRD_PARTY_TV", + e[e.SEAT = 19] = "SEAT", + e[e.CUPRA = 20] = "CUPRA" + }(ft || (ft = {})), + function(e) { + e[e.EPISODE = 1] = "EPISODE", + e[e.SHOUTCAST = 2] = "SHOUTCAST" + }(vt || (vt = {})), + function(e) { + e[e.NotStarted = 0] = "NotStarted", + e[e.Running = 1] = "Running", + e[e.Stopped = 2] = "Stopped" + }(_t || (_t = {})); + var bt = { + type: "xstate.init" + }; + function r(e) { + return void 0 === e ? [] : [].concat(e) + } + function o(e) { + return { + type: "xstate.assign", + assignment: e + } + } + function i(e, s) { + return "string" == typeof (e = "string" == typeof e && s && s[e] ? s[e] : e) ? { + type: e + } : "function" == typeof e ? { + type: e.name, + exec: e + } : e + } + function a(e) { + return function(s) { + return e === s + } + } + function u(e) { + return "string" == typeof e ? { + type: e + } : e + } + function c(e, s) { + return { + value: e, + context: s, + actions: [], + changed: !1, + matches: a(e) + } + } + function f(e, s, n) { + var d = s + , h = !1; + return [e.filter((function(e) { + if ("xstate.assign" === e.type) { + h = !0; + var s = Object.assign({}, d); + return "function" == typeof e.assignment ? s = e.assignment(d, n) : Object.keys(e.assignment).forEach((function(h) { + s[h] = "function" == typeof e.assignment[h] ? e.assignment[h](d, n) : e.assignment[h] + } + )), + d = s, + !1 + } + return !0 + } + )), d, h] + } + var l = function(e, s) { + return e.actions.forEach((function(n) { + var d = n.exec; + return d && d(e.context, s) + } + )) + }; + function invoke(e) { + return void 0 === e || (e=>"function" != typeof e)(e) ? e : e() + } + const Tt = /(?:st|ra)\.([0-9]+)/ + , Et = /st\.([0-9]+)/ + , toTimeMeasuredData = e=>{ + var {timestamp: s} = e + , n = __rest$1(e, ["timestamp"]); + return Object.assign(Object.assign({}, n), { + "milliseconds-since-play": Date.now() - s + }) + } + ; + class PlayActivitySender { + constructor(e) { + var s, n, d, h; + this.mode = gt.AUTO, + this._isQA = !1, + this._logInfo = !1, + this._preferDSID = !1, + this._accessToken = e.accessToken, + this._clientId = e.clientId, + this._eventType = e.eventType, + this._fetch = null !== (s = e.fetch) && void 0 !== s ? s : fetch, + this._fetchOptions = null !== (n = e.fetchOptions) && void 0 !== n ? n : {}, + this._headersClass = null !== (d = e.headersClass) && void 0 !== d ? d : Headers, + this._isQA = null !== (h = e.isQA) && void 0 !== h && h, + this._logInfo = e.logInfo || this._isQA, + this._musicUserToken = e.musicUserToken, + this._preferDSID = e.preferDSID, + this._sourceType = e.sourceType, + this._traceTag = e.traceTag + } + get accessToken() { + return invoke(this._accessToken) + } + get musicUserToken() { + return invoke(this._musicUserToken) + } + get url() { + return this._isQA ? "https://universal-activity-service.itunes.apple.com/qa/play" : "https://universal-activity-service.itunes.apple.com/play" + } + send(e) { + return __awaiter$1(this, void 0, void 0, (function*() { + const s = { + client_id: this._clientId, + event_type: this._eventType, + data: ensureArray(e).map(toTimeMeasuredData) + }; + if (0 === s.data.length) + throw new Error("send() called without any data"); + const n = this._generateFetchOptions({ + method: "POST", + body: JSON.stringify(s), + headers: this.headers() + }) + , d = yield this._fetch(this.url, n); + return yield d.text(), + this._logInfo && console.info("play activity:", this._sourceType === ft.AMAZON ? JSON.stringify(s) : s), + s + } + )) + } + baseHeaders() { + var e, s; + const n = null !== (s = null === (e = this._fetchOptions) || void 0 === e ? void 0 : e.headers) && void 0 !== s ? s : {}; + return n instanceof this._headersClass ? new this._headersClass(Array.from(n.entries())) : new this._headersClass(n) + } + headers() { + const e = this._preferDSID ? "X-Dsid" : "media-user-token" + , s = this.baseHeaders(); + return s.set("Authorization", "Bearer " + this.accessToken), + s.set("Content-Type", "application/json"), + s.set(e, "" + this.musicUserToken), + this._isQA && void 0 !== this._traceTag && s.set("Data-Trace-Tag", this._traceTag), + s + } + _generateFetchOptions(e) { + return Object.assign(Object.assign({}, this._fetchOptions), e) + } + } + const fullAppId = (e,s)=>{ + if (void 0 === (null == s ? void 0 : s.name)) + return "MusicKitApp/1.0"; + if (void 0 !== e) + return e; + return `${function(e) { + return e.toLowerCase().replace(/[-_]+/g, " ").replace(/[^\w\s]/g, "").replace(/\b./g, e=>e.toUpperCase()).replace(/\s/g, "") + }(s.name)}/${(null == s ? void 0 : s.version) || "1.0"}` + } + , os = e=>{ + var s, n, d; + const h = e.toLowerCase(); + let p, y = "Unidentified OS"; + const m = /mobile/.test(h); + m && /android|adr/.test(h) ? (y = "Android", + p = h.match(/(?:android|adr)\ ((\d+[._])+\d+)/)) : m && /iphone|ipad|ipod/.test(h) ? (y = "iOS", + p = h.match(/os\ ((\d+[._])+\d+)\ like\ mac\ os\ x/)) : /tizen/.test(h) ? (y = "Tizen", + p = h.match(/tizen (.*)/)) : /web0s|webos/.test(h) ? (y = "WebOS", + p = h.match(/[web0s|webos] (.*)/)) : !m && /cros/.test(h) ? y = "ChromeOS" : !m && /macintosh/.test(h) ? (y = "macOS", + p = h.match(/os\ x\ ((\d+[._])+\d+)\b/)) : !m && /linux/.test(h) ? y = "Linux" : !m && /windows/.test(h) && (y = "Windows", + p = h.match(/windows ([^\)]*)/)); + return `${y}/${null !== (d = null === (n = null === (s = null == p ? void 0 : p[1]) || void 0 === s ? void 0 : s.replace) || void 0 === n ? void 0 : n.call(s, /_/g, ".")) && void 0 !== d ? d : "0.0"}` + } + , model = e=>"model/" + ((null == e ? void 0 : e.platform) || "Unavailable") + , build = e=>{ + const s = null == e ? void 0 : e.build; + return void 0 === s || "" === s ? "build/0.0.0" : "build/" + s + } + , kt = { + platform: "", + userAgent: "" + }; + class DeveloperToken { + constructor(e) { + if (this.token = e, + !e || !/^[a-z0-9\-\_]{16,}\.[a-z0-9\-\_]{16,}\.[a-z0-9\-\_]{16,}/i.test(e)) + throw new Error("Invalid token."); + const [s,n] = e.split(".") + , {exp: d, iss: h} = this._decode(n); + if (this.expiration = 1e3 * d, + this.isExpired) + throw new Error("Initialized with an expired token."); + this.teamId = h; + const {kid: p} = this._decode(s); + this.keyId = p + } + get isExpired() { + return this.expiration < Date.now() + } + _decode(e) { + return JSON.parse(b(e)) + } + } + class GenericStorage { + constructor(e={}) { + this.data = e + } + get data() { + return this._data + } + set data(e) { + this._data = e + } + get length() { + return this.keys.length + } + get keys() { + return Object.keys(this.data) + } + getItem(e) { + return this.data[e] || null + } + setItem(e, s) { + this.data[e] = s + } + removeItem(e) { + delete this.data[e] + } + clear() { + this.keys.forEach(e=>this.removeItem(e)) + } + key(e) { + return this.keys[e] || null + } + } + function getCookie(e="", s=document.cookie) { + const n = s.match(new RegExp(`(?:^|;\\s*)${e}=([^;]*)`)); + if (n) + return n[1] + } + function setCookie(e, s, n="", d=14, h, p) { + const y = new Date; + h = null != h ? h : window; + const m = (p = null != p ? p : /\./.test(h.location.hostname) ? h.location.hostname : "").length > 0 ? `domain=${p}; ` : ""; + y.setTime(y.getTime() + 24 * d * 60 * 60 * 1e3); + let g = ""; + "https:" === h.location.protocol && (g = "; secure"), + h.document.cookie = `${e}=${s}; expires=${y.toUTCString()}; ${m}path=${n}${g}` + } + function removeCookie(e, s, n) { + setCookie(e, "", "/", 0, s, n) + } + const DEFAULT_CACHE_KEY_FUNCTION = (e,s)=>`${s}${e}`; + class NetworkCache { + constructor(e={}) { + this.storage = e.storage || new GenericStorage, + this.prefix = e.prefix || "", + this.ttl = e.ttl || 3e5, + this.cacheKeyFunction = e.cacheKeyFunction || DEFAULT_CACHE_KEY_FUNCTION + } + getItem(e) { + const s = this.cacheKeyForPath(e) + , n = this.storage.getItem(s); + if (null !== n) { + const {x: e, d: d} = JSON.parse(n); + if (e > Date.now()) + return d; + this.storage.removeItem(s) + } + } + setItem(e, s, n=this.ttl) { + const d = this.cacheKeyForPath(e); + this.storage.setItem(d, JSON.stringify({ + x: Date.now() + n, + d: s + })) + } + removeItem(e) { + const s = this.cacheKeyForPath(e); + this.storage.removeItem(s) + } + removeItemsMatching(e, s=!0) { + const n = this.cacheKeyForPath(e); + this.removeItemsMatchingCacheKey(n, s) + } + clear() { + this.removeItemsMatchingCacheKey(this.prefix, !1) + } + removeItemsMatchingCacheKey(e, s) { + const n = new RegExp(`^${e}${s ? "$" : ""}`); + (this.storage instanceof GenericStorage ? this.storage.keys : Object.keys(this.storage)).forEach(e=>{ + e && n.test(e) && this.storage.removeItem(e) + } + ) + } + cacheKeyForPath(e) { + return this.cacheKeyFunction(e, this.prefix) + } + } + var St; + !function(e) { + e.JSON = "application/json", + e.FORM = "application/x-www-form-urlencoded" + }(St || (St = {})); + class TokenSession extends class { + constructor(e, s) { + var n; + if (this.prefix = "", + this.method = "GET", + this.url = e, + (s = s || {}).storage && s.underlyingStorage) + throw new Error("only pass storage OR underlyingStorage in sessionOptions to URLSession"); + const d = s.underlyingStorage || {}; + if (this.storage = s.storage || new GenericStorage(d), + this.networkCache = new NetworkCache({ + storage: this.storage, + prefix: this.prefix, + cacheKeyFunction: this._key.bind(this) + }), + this.ttl = s.ttl || 3e5, + this._fetchOptions = Object.assign({}, s.fetchOptions), + "function" != typeof s.fetch && "function" != typeof fetch) + throw new Error("window.fetch is not defined"); + this._fetchFunction = null !== (n = s.fetch) && void 0 !== n ? n : fetch.bind(window), + this.headers = this._fetchOptions.headers || new Headers, + delete this._fetchOptions.headers + } + clearCacheForRequest(e, s) { + "object" == typeof e && (s = e, + e = void 0); + const n = this.constructURL(e, s); + this.networkCache.removeItemsMatching(n) + } + request(e, s, n) { + var d; + return __awaiter$2(this, void 0, void 0, (function*() { + n || "object" != typeof e || (n = s || {}, + s = e, + e = void 0); + let h = {}; + "object" == typeof (n = Object.assign(Object.assign({ + method: this.method, + headers: this.headers, + reload: !1 + }, this._fetchOptions), n)).queryParameters ? (h = n.queryParameters, + delete n.queryParameters) : "GET" !== n.method && "DELETE" !== n.method || (h = s); + const p = this.constructURL(e, h) + , {method: y, reload: m=!1, useRawResponse: g} = n; + if (n.headers = this.buildHeaders(n), + delete n.reload, + delete n.useRawResponse, + "GET" === y && !m) { + const e = this.getCacheItem(p); + if (e) + return Promise.resolve(e) + } + s && Object.keys(s).length && ("POST" === y || "PUT" === y) && (n.body = n.body || s, + n.contentType === St.FORM ? (n.body = urlEncodeParameters(n.body), + n.headers.set("Content-Type", St.FORM)) : (n.body = JSON.stringify(n.body), + n.headers.set("Content-Type", St.JSON))); + const v = yield this._fetchFunction(p, n); + if (!v.ok) + return Promise.reject(v); + let _; + try { + _ = yield v.json() + } catch (T) { + _ = {} + } + if (_.errors) + return Promise.reject(_.errors); + const b = g ? _ : _.results || _.data || _; + if ("GET" === y) { + const e = null !== (d = getMaxAgeFromHeaders(v.headers)) && void 0 !== d ? d : this.ttl; + this.setCacheItem(p, b, e) + } + return b + } + )) + } + buildHeaders({headers: e, reload: s=!1}={}) { + void 0 === e && (e = this.headers); + const n = (e=>new e.constructor(e))(e); + return s && n.set("Cache-Control", "no-cache"), + n + } + constructURL(e, s) { + return ((e,s,n)=>addQueryParamsToURL(addPathToURL(e, s), n))(this.url, e, s) + } + getCacheItem(e) { + const s = this.networkCache.storage + , n = `${this.prefix}${this.prefix}cache-mut` + , d = s.getItem(n) || null + , h = this.headers.get("Music-User-Token") || this.headers.get("Media-User-Token") || null; + return h !== d && (this.networkCache.clear(), + null === h ? s.removeItem(n) : s.setItem(n, h)), + this.networkCache.getItem(e) + } + setCacheItem(e, s, n=this.ttl) { + this.networkCache.setItem(e, s, n) + } + clearNetworkCache() { + this.networkCache.clear() + } + _key(e, s) { + const n = function(e) { + try { + const [s,n] = e.split("?", 2); + if (void 0 === n) + return s; + const d = n.split("&").map(e=>e.split("=", 2)) + , h = [...Array(d.length).keys()]; + h.sort((e,s)=>{ + const n = d[e] + , h = d[s]; + return n < h ? -1 : n > h ? 1 : e - s + } + ); + const p = h.map(e=>d[e]); + return `${s}?${p.map(([e,s])=>void 0 !== s ? `${e}=${s}` : e).join("&")}` + } catch (s) { + return e + } + }(e).toLowerCase().replace(this.url, ""); + return `${this.prefix}${n.replace(/[^-_0-9a-z]{1,}/g, ".")}` + } + } + { + constructor(e, s, n) { + super(e, n), + this._developerToken = new DeveloperToken(s), + this.headers.set("Authorization", "Bearer " + this.developerToken), + n = n || {}, + this.userToken = n.userToken, + this.userToken && this.headers.set("Media-User-Token", this.userToken) + } + get developerToken() { + return this._developerToken.token + } + } + Date.now(); + isNodeEnvironment$1(); + const formatByte = e=>("0" + (255 & e).toString(16)).slice(-2) + , createHelper = (e,s)=>(n,d,h)=>{ + const {helpers: p} = h.cache; + return e in p || (p[e] = s(n, d, h)), + p[e] + } + ; + const returnAsField = (e,s)=>(...n)=>function(e, s) { + if (void 0 !== s) + return { + [e]: s + } + }(e, s(...n)) + , createFieldFn = (e,s)=>(n,d,h)=>{ + const {fields: p} = h.cache; + var y; + return e in p || (h.cache.fields = Object.assign(Object.assign({}, p), { + [e]: (y = s(n, d, h), + null == y ? void 0 : { + [e]: y + }) + })), + h.cache.fields[e] + } + , createClientFieldFn = (e,s)=>createFieldFn(e, (e,n,{client: d})=>d[s]) + , Pt = createClientFieldFn("build-version", "buildVersion") + , It = ["play", "playbackstarted"] + , At = createFieldFn("event-type", (e,s,n)=>{ + const d = e.eventType; + if (void 0 === d) + return pt.PLAY_START; + if (e.itemType === yt.TIMED_METADATA_PING && void 0 !== e.timedMetadata) + return pt.PLAY_END; + if ("string" != typeof d) + return null != d ? d : pt.PLAY_START; + const h = d.toLowerCase(); + return It.includes(h) ? pt.PLAY_START : pt.PLAY_END + } + ) + , wt = ["uploadedVideo", "uploadedAudio", "uploaded-videos", "uploaded-audios"] + , Rt = createHelper("is-auc", ({kind: e})=>void 0 !== e && wt.includes(e)) + , Ot = createHelper("should-send-timed-metadata", ({endReasonType: s, eventType: n, itemType: d, timedMetadata: h})=>void 0 !== h && (d === yt.TIMED_METADATA_PING || n === pt.PLAY_START || s === e.PlayActivityEndReasonType.PLAYBACK_MANUALLY_PAUSED)) + , Ct = createFieldFn("type", (e,s,n)=>{ + var d; + const {id: h, reporting: p} = e; + if ("-1" === h || !p) + switch (null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) { + case pt.PLAY_END: + return yt.AGGREGATE_NON_CATALOG_PLAY_TIME; + case pt.PLAY_START: + if ("-1" === h) + return yt.INVALID + } + const {format: y, itemType: m} = e; + return Ot(e, s, n) ? m === yt.TIMED_METADATA_PING ? m : yt.STREAM : "stream" === y ? yt.STREAM : Rt(e, s, n) ? yt.ARTIST_UPLOADED_CONTENT : null != m ? m : yt.ITUNES_STORE_CONTENT + } + ) + , Mt = createFieldFn("container-type", (e,s,n)=>{ + var d, h; + if ((null === (d = Ct(e, s, n)) || void 0 === d ? void 0 : d.type) === yt.AGGREGATE_NON_CATALOG_PLAY_TIME) + return; + const {container: p} = e; + if (void 0 === p) + return it.UNKNOWN; + const y = null !== (h = p.type) && void 0 !== h ? h : p.kind; + if ("number" == typeof y) + return y; + switch (y) { + case "album": + case "albums": + case "library-albums": + return it.ALBUM; + case "artist": + case "artists": + case "library-artists": + return it.ARTIST; + case "playlist": + case "playlists": + case "library-playlists": + return it.PLAYLIST; + case "radio": + case "radioStation": + case "station": + case "stations": + return it.RADIO; + default: + return it.UNKNOWN + } + } + ) + , Dt = [returnAsField("album-adam-id", (e,s,n)=>{ + var d; + if ((null === (d = Mt(e, s, n)) || void 0 === d ? void 0 : d["container-type"]) !== it.ALBUM) + return; + const {container: h} = e + , p = null == h ? void 0 : h.id; + return void 0 === p || v(p) ? void 0 : p + } + ), returnAsField("cloud-album-id", (e,s,n)=>{ + var d; + if ((null === (d = Mt(e, s, n)) || void 0 === d ? void 0 : d["container-type"]) !== it.ALBUM) + return; + const {container: h} = e + , p = null == h ? void 0 : h.id; + return void 0 !== p && v(p) ? p : void 0 + } + ), returnAsField("global-playlist-id", (e,s,n)=>{ + var d, h; + if ((null === (d = Mt(e, s, n)) || void 0 === d ? void 0 : d["container-type"]) !== it.PLAYLIST) + return; + const {container: p} = e + , y = null !== (h = null == p ? void 0 : p.catalogId) && void 0 !== h ? h : null == p ? void 0 : p.globalId; + return (null == p ? void 0 : p.isLibrary) && y ? y : v(null == p ? void 0 : p.id) || null == p ? void 0 : p.id + } + ), returnAsField("playlist-version-hash", (e,s,n)=>{ + var d; + if ((null === (d = Mt(e, s, n)) || void 0 === d ? void 0 : d["container-type"]) !== it.PLAYLIST) + return; + const {container: h} = e + , p = null == h ? void 0 : h.versionHash; + return void 0 !== p && "" !== p ? p : void 0 + } + ), returnAsField("station-hash", (e,s,n)=>{ + var d, h; + if ((null === (d = Mt(e, s, n)) || void 0 === d ? void 0 : d["container-type"]) !== it.RADIO) + return; + const p = null === (h = e.container) || void 0 === h ? void 0 : h.stationHash; + return void 0 !== p && "" !== p ? p : void 0 + } + ), returnAsField("station-id", (e,s,n)=>{ + var d, h; + if ((null === (d = Mt(e, s, n)) || void 0 === d ? void 0 : d["container-type"]) === it.RADIO) + return null === (h = e.container) || void 0 === h ? void 0 : h.id + } + ), returnAsField("station-personalized-id", (e,s,n)=>{ + var d, h; + if ((null === (d = Mt(e, s, n)) || void 0 === d ? void 0 : d["container-type"]) !== it.RADIO) + return; + const p = null === (h = e.container) || void 0 === h ? void 0 : h.id; + return void 0 !== p && Et.test(p) ? parseInt(p.replace(Et, "$1"), 10) : void 0 + } + ), returnAsField("universal-library-id", (e,s,n)=>{ + var d, h; + if ((null === (d = Mt(e, s, n)) || void 0 === d ? void 0 : d["container-type"]) !== it.PLAYLIST) + return; + const {container: p} = e + , y = null !== (h = null == p ? void 0 : p.catalogId) && void 0 !== h ? h : null == p ? void 0 : p.globalId + , m = null == p ? void 0 : p.id; + if (void 0 !== m) + if ((null == p ? void 0 : p.isLibrary) && y) { + if ("" !== m) + return m + } else if (v(m)) + return m + } + )] + , Nt = createFieldFn("container-ids", (e,s,n)=>{ + var d; + if ((null === (d = Ct(e, s, n)) || void 0 === d ? void 0 : d.type) === yt.AGGREGATE_NON_CATALOG_PLAY_TIME) + return; + const h = Dt.reduce((d,h)=>Object.assign(Object.assign({}, d), h(e, s, n)), Object.create(null)); + return isEmpty(h) ? void 0 : h + } + ) + , Lt = createClientFieldFn("developer-token", "accessToken") + , xt = createClientFieldFn("device-name", "deviceName") + , Ut = createHelper("initial-start-position-in-milliseconds", ({position: e=0, startPositionInMilliseconds: s})=>s || Math.round(1e3 * e)) + , $t = createFieldFn("end-position-in-milliseconds", (e,s,n)=>{ + var d; + switch (null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) { + case pt.LYRIC_DISPLAY: + return e.duration; + case pt.PLAY_START: + return; + default: + if (s && void 0 === s.position) + return; + return e.endPositionInMilliseconds || Ut(e, s, n) + } + } + ) + , jt = createHelper("is-private", ({id: e, reporting: s})=>"-1" === e || !s) + , Bt = e.PlayActivityEndReasonType + , Kt = { + exit: Bt.EXITED_APPLICATION, + next: Bt.TRACK_SKIPPED_FORWARDS, + pause: Bt.PLAYBACK_MANUALLY_PAUSED, + playbackfinished: Bt.NATURAL_END_OF_TRACK, + playbackstopped: Bt.PLAYBACK_MANUALLY_PAUSED, + previous: Bt.TRACK_SKIPPED_BACKWARDS, + scrub_begin: Bt.SCRUB_BEGIN, + scrub_end: Bt.SCRUB_END, + stop: Bt.NATURAL_END_OF_TRACK + } + , Ft = createFieldFn("end-reason-type", (s,n,d)=>{ + var h; + const {eventType: p, endReasonType: y, timedMetadata: m} = s; + if (n && void 0 === n.position) + return; + if ((null === (h = Ct(s, n, d)) || void 0 === h ? void 0 : h.type) === yt.TIMED_METADATA_PING && void 0 !== m) + return e.PlayActivityEndReasonType.NOT_APPLICABLE; + if (jt(s, n, d) && p === pt.PLAY_END) + return e.PlayActivityEndReasonType.NOT_APPLICABLE; + if (void 0 !== y || "string" != typeof p) + return y; + const g = p.toLowerCase(); + return Kt[g] + } + ) + , {CONTAINER_CHANGED: Vt, NOT_SPECIFIED: Ht} = ht + , zt = createFieldFn("event-reason-hint-type", (e,s,n)=>{ + var d, h; + if ((null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) !== pt.PLAY_START) + return; + const p = e.container; + return void 0 === p ? Ht : !1 === s ? n.isAlexa ? Ht : Vt : (null === (h = null == s ? void 0 : s.container) || void 0 === h ? void 0 : h.id) !== p.id ? Vt : Ht + } + ) + , qt = createFieldFn("feature-name", (e,s,n)=>{ + var d, h, p, y; + if ((null === (d = Ct(e, s, n)) || void 0 === d ? void 0 : d.type) === yt.AGGREGATE_NON_CATALOG_PLAY_TIME) + return; + if ((null === (h = At(e, s, n)) || void 0 === h ? void 0 : h["event-type"]) === pt.LYRIC_DISPLAY) + return "now_playing"; + const m = null !== (y = null === (p = e.container) || void 0 === p ? void 0 : p.name) && void 0 !== y ? y : tt.MUSICKIT; + return "string" == typeof m ? m : "" + m + } + ) + , Wt = createClientFieldFn("guid", "guid") + , Yt = createHelper("should-have-auc-adam-id", Rt) + , Gt = createHelper("should-have-radio-adam-id", ({id: e, container: s})=>Tt.test(e) || "radioStation" === (null == s ? void 0 : s.kind)) + , Qt = createHelper("is-library-item-or-library-type", ({id: e, isLibrary: s},n,d)=>s || v(e)) + , Jt = createHelper("catalog-id", ({catalogId: e, container: s})=>null != e ? e : null == s ? void 0 : s.catalogId) + , Xt = createHelper("is-library-item-with-catalog-id", (e,s,n)=>e.isLibrary && !!Jt(e, s, n)) + , Zt = [returnAsField("auc-adam-id", (e,s,n)=>{ + var d; + if ((null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) !== pt.LYRIC_DISPLAY && !jt(e, s, n) && !Gt(e, s, n)) + return Yt(e, s, n) ? e.id : void 0 + } + ), returnAsField("cloud-id", (e,s,n)=>{ + var d, h; + if ((null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) === pt.LYRIC_DISPLAY) + return e.cloudId; + const {id: p} = e + , y = void 0 !== p && "" !== p; + return jt(e, s, n) && (null === (h = At(e, s, n)) || void 0 === h ? void 0 : h["event-type"]) === pt.PLAY_START && y && "-1" !== p ? p : Gt(e, s, n) || Yt(e, s, n) ? e.cloudId : Xt(e, s, n) && y || Qt(e, s, n) ? p : e.cloudId + } + ), returnAsField("lyric-id", (e,s,n)=>{ + var d, h; + if ((null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) === pt.LYRIC_DISPLAY) + return null === (h = e.lyricDescriptor) || void 0 === h ? void 0 : h.id + } + ), returnAsField("purchased-adam-id", (e,s,n)=>{ + var d; + if ((null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) !== pt.LYRIC_DISPLAY) + return e.purchasedId + } + ), returnAsField("radio-adam-id", (e,s,n)=>{ + var d; + if ((null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) === pt.LYRIC_DISPLAY || jt(e, s, n)) + return; + const {container: h, id: p} = e; + return Tt.test(p) || "radioStation" === (null == h ? void 0 : h.kind) ? parseInt(("" + p).replace(Tt, "$1"), 10) : void 0 + } + ), returnAsField("subscription-adam-id", (e,s,n)=>{ + var d; + if (!((null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) === pt.LYRIC_DISPLAY || jt(e, s, n) || Gt(e, s, n) || Yt(e, s, n))) { + if (Xt(e, s, n)) + return Jt(e, s, n); + if (!Qt(e, s, n)) + return e.id + } + } + )] + , ei = createFieldFn("ids", (e,s,n)=>{ + var d; + if ((null === (d = Ct(e, s, n)) || void 0 === d ? void 0 : d.type) === yt.AGGREGATE_NON_CATALOG_PLAY_TIME) + return; + const h = Zt.reduce((d,h)=>Object.assign(Object.assign({}, d), h(e, s, n)), Object.create(null)); + return isEmpty(h) ? void 0 : h + } + ) + , ti = createClientFieldFn("internal-build", "internalBuild") + , ii = createHelper("has-episode-streaming-kind", ({streamingKind: e},s,n)=>e === vt.EPISODE) + , si = createHelper("is-stream", (e,s,n)=>{ + var d; + return (null === (d = Ct(e, s, n)) || void 0 === d ? void 0 : d.type) === yt.STREAM + } + ) + , ri = createHelper("is-live-stream", (e,s,n)=>si(e, s, n) && !ii(e, s, n)) + , ni = createFieldFn("media-duration-in-milliseconds", (e,s,n)=>{ + var d, h, p; + const y = null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]; + if (y === pt.LYRIC_DISPLAY) + return 0; + if (ri(e, s, n)) + return 0; + const m = Math.round(1e3 * e.duration); + if (y === pt.PLAY_START) + return m; + const g = null !== (h = e.startPositionInMilliseconds) && void 0 !== h ? h : Math.round(1e3 * (null !== (p = e.position) && void 0 !== p ? p : 0)); + return g > 1e3 * e.duration ? g : m + } + ) + , {AUDIO: ai, VIDEO: oi} = mt + , di = createFieldFn("media-type", (e,s,n)=>{ + var d; + if ((null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) === pt.LYRIC_DISPLAY) + return ai; + const {kind: h, mediaType: p} = e; + if ("number" == typeof p) + return p; + const y = "string" == typeof p ? p : h; + return y && /video/i.test(y) ? oi : ai + } + ) + , li = createClientFieldFn("metrics-client-id", "metricsClientId") + , ci = createFieldFn("offline", ()=>!1) + , ui = createFieldFn("persistent-id", ()=>generateUUID()) + , hi = createFieldFn("play-mode", (e,s,n)=>{ + var d, h, p, y, m, g, v, _; + if ((null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) === pt.LYRIC_DISPLAY || (null === (h = Ct(e, s, n)) || void 0 === h ? void 0 : h.type) === yt.AGGREGATE_NON_CATALOG_PLAY_TIME) + return { + "auto-play-mode": null !== (p = hi.autoplayMode) && void 0 !== p ? p : 0, + "repeat-play-mode": null !== (y = hi.repeatPlayMode) && void 0 !== y ? y : 0, + "shuffle-play-mode": null !== (m = hi.shufflePlayMode) && void 0 !== m ? m : 0 + }; + const b = invoke(e.playMode); + return void 0 !== b ? { + "auto-play-mode": null !== (g = b.autoplayMode) && void 0 !== g ? g : 0, + "repeat-play-mode": null !== (v = b.repeatPlayMode) && void 0 !== v ? v : 0, + "shuffle-play-mode": null !== (_ = b.shufflePlayMode) && void 0 !== _ ? _ : 0 + } : void 0 + } + ) + , pi = createClientFieldFn("private-enabled", "privateEnabled") + , yi = createFieldFn("reco-data", (e,s,n)=>{ + var d, h; + if ((null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]) !== pt.LYRIC_DISPLAY && (null === (h = Ct(e, s, n)) || void 0 === h ? void 0 : h.type) !== yt.AGGREGATE_NON_CATALOG_PLAY_TIME) + return e.recoData + } + ) + , mi = createClientFieldFn("sb-enabled", "userIsSubscribed") + , gi = createClientFieldFn("siri-initiated", "siriInitiated") + , fi = createClientFieldFn("source-type", "sourceType") + , vi = createFieldFn("start-position-in-milliseconds", (e,s,n)=>{ + var d, h, p, y; + const m = null === (d = At(e, s, n)) || void 0 === d ? void 0 : d["event-type"]; + return m === pt.LYRIC_DISPLAY || (null === (h = Ct(e, s, n)) || void 0 === h ? void 0 : h.type) === yt.AGGREGATE_NON_CATALOG_PLAY_TIME || ri(e, s, n) ? 0 : m === pt.PLAY_START ? Ut(e, s, n) : null !== (y = null !== (p = e.startPositionInMilliseconds) && void 0 !== p ? p : previousPosition(s)) && void 0 !== y ? y : 0 + } + ) + , previousPosition = e=>e && void 0 !== e.position ? Math.round(1e3 * e.position) : 0 + , _i = createClientFieldFn("store-front", "storefrontId") + , bi = createFieldFn("timed-metadata", (e,s,n)=>{ + const d = e.timedMetadata; + if (void 0 !== d && shouldSendTimedMetadata(e, s, n)) + return ((e,s=8)=>{ + if (!(e instanceof Uint8Array)) + return ""; + const n = Array.prototype.map.call(e, formatByte).join(""); + return 0 === s ? n : n.replace(new RegExp(`(.{1,${s}})`,"g"), "$1 ").trim() + } + )(d, 0) + } + ) + , shouldSendTimedMetadata = (e,s,n)=>{ + var d, h; + return (null === (d = Ct(e, s, n)) || void 0 === d ? void 0 : d.type) === yt.TIMED_METADATA_PING || (null === (h = At(e, s, n)) || void 0 === h ? void 0 : h["event-type"]) !== pt.LYRIC_DISPLAY + } + , Ti = createFieldFn("timestamp", ({timestamp: e},s,n)=>null != e ? e : Date.now()) + , Ei = createClientFieldFn("user-agent", "userAgent") + , ki = createFieldFn("user-token", (e,s,{client: n})=>{ + if (!n.preferDSID) + return n.musicUserToken + } + ) + , Si = createFieldFn("utc-offset-in-seconds", (e,s,n)=>{ + var d; + return (null === (d = Ct(e, s, n)) || void 0 === d ? void 0 : d.type) === yt.AGGREGATE_NON_CATALOG_PLAY_TIME ? 0 : n.client.utcOffsetInSeconds + } + ) + , Pi = { + "build-version": Pt, + "container-ids": Nt, + "container-type": Mt, + "developer-token": Lt, + "device-name": xt, + "end-position-in-milliseconds": $t, + "end-reason-type": Ft, + "event-reason-hint-type": zt, + "event-type": At, + "feature-name": qt, + guid: Wt, + ids: ei, + "internal-build": ti, + "media-duration-in-milliseconds": ni, + "media-type": di, + "metrics-client-id": li, + offline: ci, + "persistent-id": ui, + "play-mode": hi, + "private-enabled": pi, + "reco-data": yi, + "sb-enabled": mi, + "siri-initiated": gi, + "source-type": fi, + "start-position-in-milliseconds": vi, + "store-front": _i, + "timed-metadata": bi, + timestamp: Ti, + type: Ct, + "user-agent": Ei, + "user-token": ki, + "utc-offset-in-seconds": Si + }; + let Ii = 0; + const buildPlayActivityData = (e,s,n,d=!1)=>{ + if (void 0 === s) + throw new Error("called without a play activity descriptor"); + const h = ((e,...s)=>Object.assign(Object.assign(Object.assign({}, e), Object.assign({}, ...s)), { + cache: { + fields: Object.assign({}, ...s.map(e=>{ + var s; + return null === (s = null == e ? void 0 : e.cache) || void 0 === s ? void 0 : s.fields + } + )), + helpers: Object.assign({}, ...s.map(e=>{ + var s; + return null === (s = null == e ? void 0 : e.cache) || void 0 === s ? void 0 : s.helpers + } + )) + } + }))("boolean" == typeof d ? ((e={},s)=>Object.assign({ + id: (Ii++).toFixed(0), + client: s, + isAlexa: !1 + }, e))({ + isAlexa: d + }, e) : Object.assign(Object.assign({}, d), { + client: e + })); + return Object.assign(s, (e=>{ + var s, n; + return { + eventType: null !== (s = e.eventType) && void 0 !== s ? s : pt.PLAY_START, + reporting: null === (n = e.reporting) || void 0 === n || n + } + } + )(s)), + Object.assign(Object.create(null), ...Object.values(Pi).map(e=>null == e ? void 0 : e(s, n, h))) + } + ; + var Ai; + !function(e) { + e[e.ALEXA = 13] = "ALEXA" + }(Ai || (Ai = {})); + const createCookieJar = e=>{ + switch (void 0 === e && (e = "browser"), + e) { + case "browser": + return { + get: getCookie, + set: setCookie + }; + case "memory": + return ((e={})=>({ + get(s) { + if (void 0 !== s) + return e[s] + }, + set(s, n) { + e[s] = n + } + }))(); + default: + return e + } + } + , empty = (e,s)=>write(e, s, [], "/", 0) + , read = (e,s)=>{ + const n = e.get(s); + if (void 0 === n || "" === n) + return []; + return ensureArray(JSON.parse(atob(n))) + } + , write = (e,s,n,d,h,p)=>e.set(s, btoa(JSON.stringify(n)), d, h, p) + , {AUTO: wi} = gt; + class PlayActivityBatchableSender { + constructor(e, s) { + this.sender = e, + this.jar = s, + this.mode = wi + } + flush() { + return __awaiter$1(this, void 0, void 0, (function*() { + const e = read(this.jar, "amupaee"); + if (void 0 !== e && 0 !== e.length) + try { + yield this.sender.send(e), + empty(this.jar, "amupaee") + } catch ({message: s}) { + throw new Error("flush: " + s) + } + } + )) + } + send(s) { + return __awaiter$1(this, void 0, void 0, (function*() { + if (this.mode === wi && (Array.isArray(s) || s["end-reason-type"] !== e.PlayActivityEndReasonType.EXITED_APPLICATION)) + return this.sender.send(s); + ((e,s,n,d,h,p)=>{ + write(e, s, [...read(e, s), n], d, h, p) + } + )(this.jar, "amupaee", s, "/") + } + )) + } + } + class Timeline { + constructor() { + this._events = {}, + this._keys = [] + } + get events() { + return this._events + } + get first() { + return this.at(0) + } + get keys() { + return this._keys + } + get last() { + return this.at(this.length - 1) + } + get length() { + return this._keys.length + } + get second() { + return this.at(1) + } + at(e) { + if (e > this.length - 1) + throw new Error("Invalid timeline index"); + const s = this._keys[e]; + return this._events[s] + } + before(e) { + if ("number" != typeof e) { + const s = []; + for (const e in this._events) + hasOwn(this._events, e) && s.push(this._events[e]); + e = this._keys[s.indexOf(e)] + } + const s = this._keys.indexOf(e); + if (-1 === s) + throw new Error("Key not found"); + if (s > 0) + return this._events[this._keys[s - 1]] + } + drain() { + const e = this._keys.map(e=>this._events[e]); + return this.reset(), + e + } + reset() { + this._events = {}, + this._keys = [] + } + pop() { + return __awaiter$1(this, void 0, void 0, (function*() { + const e = this._keys.pop(); + if (void 0 === e) + return Promise.reject("TIMELINE IS EMPTY"); + const s = this._events[e]; + return delete this._events[e], + Promise.resolve(s) + } + )) + } + add(e, s) { + return __awaiter$1(this, void 0, void 0, (function*() { + return this.push(e, s) + } + )) + } + push(e, s=Date.now()) { + return __awaiter$1(this, void 0, void 0, (function*() { + for (; -1 !== this._keys.indexOf(s); ) + s++; + return this._events[s] = e, + this._keys.push(s), + Promise.resolve(s) + } + )) + } + shift() { + return __awaiter$1(this, void 0, void 0, (function*() { + const e = this._keys.shift(); + if (void 0 === e) + return Promise.reject("TIMELINE IS EMPTY"); + const s = this._events[e]; + return delete this._events[e], + Promise.resolve(s) + } + )) + } + unshift(e, s=Date.now()) { + return __awaiter$1(this, void 0, void 0, (function*() { + for (; -1 !== this._keys.indexOf(s); ) + s++; + return this._events[s] = e, + this._keys.unshift(s), + Promise.resolve(s) + } + )) + } + } + const Ri = new Logger; + class TimedMetadataTracker { + constructor(e, s) { + this.client = e, + this._currentValue = s + } + get currentValue() { + return this._currentValue + } + clear() { + this._currentValue = void 0 + } + ping(e, s) { + return __awaiter$1(this, void 0, void 0, (function*() { + this.timedMetadataChanged(e) && (void 0 !== this._currentValue && (yield this.client.pingTimedMetadata(s, this._currentValue)), + this._currentValue = void 0 === e ? void 0 : e.slice(0)) + } + )) + } + timedMetadataChanged(e) { + const {_currentValue: s} = this; + return void 0 === s ? void 0 !== e : void 0 === e || (e.length !== s.length || s.some((s,n)=>s !== e[n])) + } + } + const fieldGetter = (e,s)=>n=>s in n ? n[s] : n[e] + , Oi = fieldGetter("eventType", "event-type") + , Ci = fieldGetter("endReasonType", "end-reason-type") + , Mi = fieldGetter("itemType", "type") + , createMPAFMachine = ()=>function(e, s) { + void 0 === s && (s = {}); + var n = t(f(r(e.states[e.initial].entry).map((function(e) { + return i(e, s.actions) + } + )), e.context, bt), 2) + , d = n[0] + , h = n[1] + , p = { + config: e, + _options: s, + initialState: { + value: e.initial, + actions: d, + context: h, + matches: a(e.initial) + }, + transition: function(s, n) { + var d, h, y = "string" == typeof s ? { + value: s, + context: e.context + } : s, m = y.value, g = y.context, v = u(n), _ = e.states[m]; + if (_.on) { + var b = r(_.on[v.type]); + try { + for (var T = function(e) { + var s = "function" == typeof Symbol && Symbol.iterator + , n = s && e[s] + , d = 0; + if (n) + return n.call(e); + if (e && "number" == typeof e.length) + return { + next: function() { + return e && d >= e.length && (e = void 0), + { + value: e && e[d++], + done: !e + } + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.") + }(b), E = T.next(); !E.done; E = T.next()) { + var k = E.value; + if (void 0 === k) + return c(m, g); + var S = "string" == typeof k ? { + target: k + } : k + , P = S.target + , I = S.actions + , A = void 0 === I ? [] : I + , w = S.cond + , R = void 0 === w ? function() { + return !0 + } + : w + , O = void 0 === P + , C = null != P ? P : m + , M = e.states[C]; + if (R(g, v)) { + var D = t(f((O ? r(A) : [].concat(_.exit, A, M.entry).filter((function(e) { + return e + } + ))).map((function(e) { + return i(e, p._options.actions) + } + )), g, v), 3) + , N = D[0] + , L = D[1] + , x = D[2] + , U = null != P ? P : m; + return { + value: U, + context: L, + actions: N, + changed: P !== m || N.length > 0 || x, + matches: a(U) + } + } + } + } catch (t) { + d = { + error: t + } + } finally { + try { + E && !E.done && (h = T.return) && h.call(T) + } finally { + if (d) + throw d.error + } + } + } + return c(m, g) + } + }; + return p + }({ + id: "mpaf", + initial: "idle", + context: {}, + states: { + error: {}, + idle: { + on: { + play: "playing", + scrubBegin: { + target: "scrubbing", + actions: o(e=>Object.assign(Object.assign({}, e), { + stateBeforeScrub: "idle" + })) + }, + scrubEnd: { + target: "error", + actions: ["clearStateBeforeScrub", "setScrubEndError"] + } + } + }, + playing: { + on: { + scrubBegin: { + target: "scrubbing", + actions: o(e=>Object.assign(Object.assign({}, e), { + stateBeforeScrub: "playing" + })) + }, + stop: "idle", + scrubEnd: { + target: "error", + actions: ["clearStateBeforeScrub", "setScrubEndError"] + } + } + }, + scrubbing: { + on: { + scrubEnd: [{ + target: "idle", + cond: ({stateBeforeScrub: e})=>"idle" === e, + actions: ["clearStateBeforeScrub"] + }, { + target: "playing", + actions: ["clearStateBeforeScrub"] + }] + } + } + } + }, { + actions: { + clearStateBeforeScrub: o(e=>__rest$1(e, ["stateBeforeScrub"])), + setScrubEndError: o(e=>Object.assign(Object.assign({}, e), { + errorMessage: "The scrub() method was called with the SCRUB_END action without a previous SCRUB_START descriptor" + })) + } + }); + class MPAFStateMachine { + constructor() { + this.machine = createMPAFMachine(), + this.machineService = function(e) { + var s = e.initialState + , n = _t.NotStarted + , d = new Set + , h = { + _machine: e, + send: function(h) { + n === _t.Running && (s = e.transition(s, h), + l(s, u(h)), + d.forEach((function(e) { + return e(s) + } + ))) + }, + subscribe: function(e) { + return d.add(e), + e(s), + { + unsubscribe: function() { + return d.delete(e) + } + } + }, + start: function(d) { + if (d) { + var p = "object" == typeof d ? d : { + context: e.config.context, + value: d + }; + s = { + value: p.value, + actions: [], + context: p.context, + matches: a(p.value) + } + } + return n = _t.Running, + l(s, bt), + h + }, + stop: function() { + return n = _t.Stopped, + d.clear(), + h + }, + get state() { + return s + }, + get status() { + return n + } + }; + return h + }(this.machine).start() + } + canSendEvent(e) { + var s; + return null !== (s = this.machine.transition(this.machineService.state, e).changed) && void 0 !== s && s + } + matches(e) { + return this.machineService.state.matches(e) + } + send(s) { + const n = (s=>{ + const n = Oi(s) + , d = Ci(s); + if (Mi(s) === yt.TIMED_METADATA_PING) + return !1; + switch (n) { + case pt.PLAY_START: + return "play"; + case pt.PLAY_END: + switch (d) { + case e.PlayActivityEndReasonType.SCRUB_BEGIN: + return "scrubBegin"; + case e.PlayActivityEndReasonType.SCRUB_END: + return "scrubEnd"; + case e.PlayActivityEndReasonType.EXITED_APPLICATION: + case e.PlayActivityEndReasonType.NOT_APPLICABLE: + return !1; + default: + return "stop" + } + default: + return "stop" + } + } + )(s); + if (!1 !== n && (this.canSendEvent({ + type: n + }) && this.machineService.send({ + type: n + }), + this.matches("error"))) + throw new Error(this.machineService.state.context.errorMessage) + } + } + class StatelessPlayActivity extends class { + constructor(e, s, n, d) { + var h, p, y; + this._accessToken = e, + this._musicUserToken = s, + this._storefrontId = n, + this.privateEnabled = !1, + this.siriInitiated = !1, + this.clientId = "JSCLIENT", + this.eventType = "JSPLAY", + this.internalBuild = !1, + this.preferDSID = !1, + this.sourceType = ft.MUSICKIT, + this._utcOffset = (new Date).getTimezoneOffset(), + this._userIsSubscribed = !0, + d && (this._appInfo = d.app, + this._navigator = d.navigator, + this._userAgent = d.userAgent, + hasOwn(d, "utcOffset") && isNaN(d.utcOffset) ? this._utcOffsetInSeconds = -1 : hasOwn(d, "utcOffset") && (this._utcOffset = d.utcOffset), + this.clientId = d.clientId || "JSCLIENT", + this._deviceName = d.deviceName, + this.guid = d.guid, + this.metricsClientId = d.metricsClientId, + this.preferDSID = null !== (h = d.preferDSID) && void 0 !== h && h, + this.sourceType = void 0 !== d.sourceType && "number" == typeof d.sourceType ? d.sourceType : ft.MUSICKIT, + this._userIsSubscribed = null === (p = d.userIsSubscribed) || void 0 === p || p), + this.buildVersion = ((e,s,n,d)=>[fullAppId(e, s), os(d), model(n), build(s)].join(" "))(this._appId, this._appInfo, this.navigator, this.userAgent), + this.sender = new PlayActivitySender({ + accessToken: this._accessToken, + clientId: this.clientId, + eventType: this.eventType, + fetch: null == d ? void 0 : d.fetch, + fetchOptions: null == d ? void 0 : d.fetchOptions, + headersClass: null === (y = null == d ? void 0 : d.fetch) || void 0 === y ? void 0 : y.Headers, + isQA: null == d ? void 0 : d.isQA, + logInfo: null == d ? void 0 : d.logInfo, + musicUserToken: this._musicUserToken, + preferDSID: this.preferDSID, + sourceType: this.sourceType, + traceTag: null == d ? void 0 : d.traceTag + }) + } + get accessToken() { + return invoke(this._accessToken) + } + get appID() { + return void 0 === this._appId && (this._appId = fullAppId(this._appId, this._appInfo)), + this._appId + } + get deviceName() { + return this._deviceName + } + get musicUserToken() { + return invoke(this._musicUserToken) + } + get navigator() { + var e; + return null !== (e = this._navigator) && void 0 !== e ? e : "undefined" == typeof navigator ? kt : navigator + } + get storefrontId() { + return invoke(this._storefrontId) + } + get userAgent() { + var e; + return null !== (e = this._userAgent) && void 0 !== e ? e : this.navigator.userAgent + } + get userIsSubscribed() { + return invoke(this._userIsSubscribed) + } + get utcOffsetInSeconds() { + if (void 0 === this._utcOffsetInSeconds && void 0 !== this._utcOffset && !isNaN(this._utcOffset)) { + const e = 60 * this._utcOffset; + this._utcOffsetInSeconds = e <= 0 ? Math.abs(e) : -e + } + return void 0 === this._utcOffsetInSeconds || isNaN(this._utcOffsetInSeconds) ? -1 : this._utcOffsetInSeconds + } + send(e) { + return __awaiter$1(this, void 0, void 0, (function*() { + return this.sender.send(e) + } + )) + } + buildDescriptorForPlayParams(e, s, n, d, h) { + const p = "stream" === e.format ? yt.STREAM : yt.ITUNES_STORE_CONTENT; + return Object.assign(Object.assign(Object.assign({}, e), { + container: n, + duration: null != d ? d : 0, + eventType: s, + itemType: p + }), h) + } + buildForPlayParams(e, s, n, d=0, h={}, p=!1) { + return this.build(this.buildDescriptorForPlayParams(e, s, n, d, h), p) + } + } + { + constructor(e, s, n, d) { + super(e, s, n, d) + } + build(e, s) { + return buildPlayActivityData(this, e, s, "JSCLIENT" !== this.clientId) + } + } + class PlayActivity { + constructor(e, s, n, d) { + this.timeline = new Timeline, + this._paf = new StatelessPlayActivity(e,s,n,d), + this._cookieJar = createCookieJar(null == d ? void 0 : d.cookieJar), + this.sender = new PlayActivityBatchableSender(this._paf.sender,this._cookieJar), + this._machine = new MPAFStateMachine, + this._timedMetadataTracker = new TimedMetadataTracker(this) + } + get mode() { + return this.sender.mode + } + set mode(e) { + this.sender.mode = e + } + get privateEnabled() { + return this._paf.privateEnabled + } + set privateEnabled(e) { + this._paf.privateEnabled = e + } + get timedMetadata() { + return this._timedMetadataTracker.currentValue + } + clearTimedMetadata() { + return this._timedMetadataTracker.clear() + } + setTimedMetadata(e, s) { + return this._timedMetadataTracker.ping(e, s) + } + activate(s=!1) { + return __awaiter$1(this, void 0, void 0, (function*() { + if (s) + try { + yield this.flush() + } catch (d) { + if (!(e=>(e=>{ + switch (typeof e) { + case "string": + return e; + case "object": + return e.message ? "string" != typeof e.message ? "" : e.message : ""; + default: + return "" + } + } + )(e).includes("send() called without any data"))(d)) + throw d + } + const n = this.timeline.last; + if (n && n.endReasonType === e.PlayActivityEndReasonType.EXITED_APPLICATION) + return this.timeline.pop() + } + )) + } + exit(s=0) { + return __awaiter$1(this, void 0, void 0, (function*() { + return this.stop(s, e.PlayActivityEndReasonType.EXITED_APPLICATION) + } + )) + } + pause(s=0) { + return __awaiter$1(this, void 0, void 0, (function*() { + return this.stop(s, e.PlayActivityEndReasonType.PLAYBACK_MANUALLY_PAUSED) + } + )) + } + pingTimedMetadata(s, n, d=this._previousDescriptor()) { + return __awaiter$1(this, void 0, void 0, (function*() { + yield this._addToTimeline(Object.assign(Object.assign({}, d), { + position: s, + endReasonType: e.PlayActivityEndReasonType.NOT_APPLICABLE, + eventType: pt.PLAY_END, + itemType: yt.TIMED_METADATA_PING, + timedMetadata: n + })) + } + )) + } + play(e, s=0) { + return __awaiter$1(this, void 0, void 0, (function*() { + const n = this.timeline.length > 0; + if (void 0 === e) { + if (!n) + return; + const e = this._previousDescriptor(); + e.eventType === pt.PLAY_END && delete e.endReasonType; + const s = Object.assign(Object.assign({}, this.sanitizePreviousDescriptor(e)), { + eventType: pt.PLAY_START + }); + return this._addToTimeline(s) + } + if (n) { + const e = this._previousDescriptor(); + if (this._machine.matches("playing") && !(({id: e, reporting: s=!0, eventType: n})=>("-1" === e || !s) && n === pt.PLAY_END)(e)) + return Promise.reject(new Error("The play() method was called without a previous stop() or pause() call.")) + } + const d = Object.assign(Object.assign({}, e), { + eventType: pt.PLAY_START, + position: s + }); + return this._addToTimeline(d) + } + )) + } + scrub(s=0, n=e.PlayActivityEndReasonType.SCRUB_BEGIN) { + return __awaiter$1(this, void 0, void 0, (function*() { + const e = this._previousDescriptor() + , d = Object.assign(Object.assign({}, this.sanitizePreviousDescriptor(e)), { + eventType: pt.PLAY_END, + endReasonType: n, + position: s + }); + return this._addToTimeline(d) + } + )) + } + skip(s, n=e.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS, d=0) { + return __awaiter$1(this, void 0, void 0, (function*() { + return yield this.stop(d, n), + this.play(s) + } + )) + } + stop(s=0, n=e.PlayActivityEndReasonType.NATURAL_END_OF_TRACK) { + return __awaiter$1(this, void 0, void 0, (function*() { + let d = this._previousDescriptor(); + if (d.endReasonType === e.PlayActivityEndReasonType.EXITED_APPLICATION && (yield this.timeline.pop(), + empty(this._cookieJar, "amupaee"), + d = this._previousDescriptor()), + this._machine.matches("playing")) { + const e = Object.assign(Object.assign({}, this.sanitizePreviousDescriptor(d)), { + eventType: pt.PLAY_END, + endReasonType: n, + position: s, + timedMetadata: this._timedMetadataTracker.currentValue + }); + return this._addToTimeline(e) + } + return Promise.reject(new Error("A play stop() method was called without a previous play() descriptor")) + } + )) + } + build(e, s) { + if (void 0 === e && void 0 === s && Ri.warn("You are calling build() from a stateful PAF client. Please, use a stateless client or exit(), pause(), play(), scrub(), skip() or stop() instead."), + void 0 === e) { + if (0 === this.timeline.length) + throw new Error("build() called without a play activity descriptor"); + e = this.timeline.last + } + if (void 0 === s) { + if (void 0 === (s = this.timeline.before(e)) && e.eventType === pt.PLAY_END) + throw new Error("Cannot build() for PLAY_END descriptors without previous descriptors"); + s = null != s && s + } + return this._paf.build(Object.assign(Object.assign({}, e), { + timedMetadata: this.timedMetadata + }), s) + } + addForPlayParams(e, s, n, d=0, h={}) { + const p = this.buildDescriptorForPlayParams(e, s, n, d, h); + return this._addToTimeline(p) + } + buildDescriptorForPlayParams(e, s, n, d=0, h={}) { + const p = "stream" === e.format ? yt.STREAM : yt.ITUNES_STORE_CONTENT; + return Object.assign(Object.assign(Object.assign({}, e), { + container: n, + duration: d, + eventType: s, + itemType: p + }), h) + } + flush() { + return this.sender.flush() + } + _addToTimeline(e) { + return __awaiter$1(this, void 0, void 0, (function*() { + const s = Object.assign(Object.assign({}, e), { + timestamp: Date.now() + }) + , n = this.timeline.length > 0 && this.timeline.last; + yield this.timeline.add(s); + const d = this.build(s, n); + yield this.send(d) + } + )) + } + _previousDescriptor() { + const e = this.timeline.last; + if (void 0 === e) + throw new Error("A method was called without a previous descriptor"); + return exceptFields(e, "timestamp") + } + buildForPlayParams(e, s, n, d=0, h={}, p=!1) { + return Ri.warn("You are using buildsForPlayParams from a stateful PlayActivity. Please, use StatelessPlayActivity instead"), + this._paf.buildForPlayParams(e, s, n, d, h, p) + } + send(e) { + const s = ensureArray(e); + return s.forEach(e=>this._machine.send(e)), + this.sender.send(s) + } + sanitizePreviousDescriptor(e) { + let s = function deepClone(e) { + if ("object" != typeof e || null === e) + throw new TypeError("Source is not an Object"); + const s = Array.isArray(e) ? [] : {}; + for (const n in e) + hasOwn(e, n) && ("object" == typeof e[n] && null !== e[n] ? s[n] = deepClone(e[n]) : s[n] = e[n]); + return s + }(e); + return s.itemType === yt.TIMED_METADATA_PING && (s = exceptFields(s, "itemType")), + s + } + } + e.version = "2.2150.6"; + const Di = e.version.split(".") + , Ni = Di[0] + , Li = Di[Di.length - 1]; + Di[0] = "3", + Di[Di.length - 1] = Li + "-prerelease", + Di[0] = Ni, + Di[Di.length - 1] = Li, + e.version = Di.join("."); + const Bind = ()=>(e,s,n)=>{ + if (void 0 === n || "function" != typeof n.value) + throw new TypeError(`Only methods can be decorated with @Bind, but ${s} is not a method.`); + return { + configurable: !0, + get() { + const e = n.value.bind(this); + return Object.defineProperty(this, s, { + value: e, + configurable: !0, + writable: !0 + }), + e + } + } + } + ; + const xi = { + af: 48, + sq: 1, + ar: 34, + eu: 1, + bg: 49, + be: 1, + ca: 42, + zh: 19, + "zh-tw": 18, + "zh-cn": 19, + "zh-hk": 45, + "zh-sg": 19, + hr: 41, + cs: 22, + da: 11, + nl: 10, + "nl-be": 65, + en: 1, + "en-us": 1, + "en-eg": 26, + "en-au": 27, + "en-gb": 2, + "en-ca": 6, + "en-nz": 27, + "en-ie": 26, + "en-za": 26, + "en-jm": 26, + "en-bz": 26, + "en-tt": 26, + "en-001": 26, + et: 30, + fo: 1, + fa: 59, + fi: 12, + fr: 3, + "fr-ca": 5, + gd: 2, + de: 4, + "de-ch": 57, + el: 23, + he: 36, + hi: 50, + hu: 21, + is: 31, + id: 37, + it: 7, + ja: 9, + ko: 13, + lv: 33, + lt: 32, + mk: 1, + mt: 1, + no: 14, + nb: 14, + nn: 14, + pl: 20, + "pt-br": 15, + pt: 24, + rm: 1, + ro: 39, + ru: 16, + sr: 1, + sk: 40, + sl: 52, + es: 8, + "es-mx": 28, + "es-419": 44, + sv: 17, + th: 35, + ts: 1, + tn: 1, + tr: 25, + uk: 29, + ur: 55, + ve: 1, + vi: 43, + xh: 1, + yi: 1, + zu: 56, + ms: 38, + iw: 36, + lo: 46, + tl: 47, + kk: 51, + ta: 53, + te: 54, + bn: 58, + ga: 60, + ht: 61, + la: 62, + pa: 63, + sa: 64 + }; + function getLanguages() { + if ("undefined" == typeof navigator) + return []; + if (navigator.languages) + return navigator.languages; + const e = navigator.language || navigator.userLanguage; + return e ? [e] : [] + } + const Ui = new RegExp("^https://([a-z0-9]+-)?" + ("js-cdn.music.apple.com" + "/musickit/v3/".replace(/v3/, "(v2|v3)")).replace(/[\.\/]/g, "\\$&"),"i") + , $i = /^([a-z]+:)?\/\//; + function findScript(e) { + return isNodeEnvironment$1() || !e ? null : document.querySelector(`script[src*="${e}"]`) + } + function determineCdnBasePrefix() { + for (const e of "undefined" != typeof document && document.querySelectorAll ? Array.from(document.querySelectorAll("script[src]")) : []) { + const s = Ui.exec(e.src); + if (s) + return s[1] || "" + } + return "" + } + function determineCdnBaseHost() { + if (isNodeEnvironment$1()) + return ""; + return `//${determineCdnBasePrefix()}js-cdn.music.apple.com` + } + function getHlsJsCdnConfig() { + const e = { + hls: "", + rtc: "" + }; + if (isNodeEnvironment$1()) + return e; + const s = determineCdnBaseHost(); + let n = "2.141.0"; + return n = createLocalStorageFlag("mk-hlsjs-version").get() || n, + e.hls = `http://localhost:9000/apple-hls.js`, + e.rtc = `https:${s}/hls.js/${n}/rtc.js/rtc.min.js`, + e + } + function cdnBaseURL(e, s=window) { + if (isNodeEnvironment$1()) + return ""; + if (s.localStorage.mkCDNBaseURLOverride) + return s.localStorage.mkCDNBaseURLOverride; + const n = findScript(e); + return n ? n.getAttribute("src").replace(new RegExp(e + "$"), "") : determineCdnBaseHost() + "/musickit/v3/" + } + function loadScript(e, s) { + return new Promise((n,d)=>{ + isNodeEnvironment$1() && d("Dynamic script loading is unsupported in Node environments."); + if (findScript(e)) + return n(); + const h = document.createElement("script"); + let p; + if (s && Object.keys(s).forEach(e=>{ + h.setAttribute(e, s[e]) + } + ), + h.onload = ()=>{ + n() + } + , + h.onerror = e=>{ + d(e) + } + , + $i.test(e)) + p = e; + else { + p = `${cdnBaseURL(e)}${e}` + } + h.src = p, + document.head.appendChild(h) + } + ) + } + const ji = new Logger("sk-debug"); + class AuthBridgeApp extends class { + constructor() { + this._targetOrigin = "*" + } + init(e, s) { + var n; + this._receiveWindow = e, + this._sendWindow = s, + this.handleMessage = this.handleMessage.bind(this), + null === (n = this._receiveWindow) || void 0 === n || n.addEventListener("message", this.handleMessage) + } + sendMessage(e, s) { + const n = { + action: "mediakit:" + e, + data: s + }; + this._sendWindow && this._sendWindow.postMessage(JSON.stringify(n), this._targetOrigin) + } + handleMessage(e) { + if (!this._isOriginAllowed(e.origin)) + return; + let s; + try { + s = JSON.parse(e.data) + } catch (bt) {} + if (!s || !this._isNamespacedData(s)) + return; + "*" === this._targetOrigin && (this._targetOrigin = e.origin), + ji.debug("auth-bridge: handleMessage", s); + const n = s.action.replace("mediakit:", ""); + this[n] ? this[n](s.data) : ji.debug("auth-bridge: unsupported method", n) + } + _isOriginAllowed(e) { + if (!e) + return !1; + const [s,n] = e.split("://"); + let d = ""; + return n && (d = n.split(":")[0]), + "https" === s && !!d && d.endsWith(".apple.com") + } + _isNamespacedData(e) { + return e.action && -1 !== e.action.indexOf("mediakit:") + } + } + { + constructor() { + super(), + this.whenFrameInited = new Promise(e=>this._frameInitResolve = e), + this.whenAuthCompleted = new Promise(e=>this._authUpdateResolve = e), + this.frame = document.createElement("iframe"), + this.frame.src = this._getIframeSrc(), + this.frame.style.display = "none", + document.body.appendChild(this.frame), + this.init(window, this.frame.contentWindow) + } + requestAuthUpdate() { + this.whenFrameInited.then(()=>this.sendMessage("requestAuthUpdate")) + } + setCookieItem(e, s) { + this.whenFrameInited.then(()=>this.sendMessage("setCookieItem", { + name: e, + value: s + })) + } + clearAuth() { + this.whenFrameInited.then(()=>this.sendMessage("clearAuth")) + } + frameInit() { + var e; + null === (e = this._frameInitResolve) || void 0 === e || e.call(this), + this.requestAuthUpdate() + } + updateAuth(e) { + if ((null == e ? void 0 : e.enabled) && (null == e ? void 0 : e.cookies)) { + const s = e.cookies; + Object.keys(s).forEach(e=>{ + var n; + const d = null !== (n = s[e]) && void 0 !== n ? n : ""; + d ? setCookie(e, d, "/", 7) : removeCookie(e) + } + ) + } + this._authUpdateResolve && (this._authUpdateResolve(), + this._authUpdateResolve = void 0) + } + authClearedFromOtherFrame() { + ji.warn("Override auth-bridge/app's authClearedFromOtherFrame to trigger app-specific sign out behavior") + } + _getIframeSrc() { + let e = determineCdnBasePrefix(); + return e && (e = "?env=" + e.substring(0, e.length - 1)), + "https://mediaauth.apple.com/auth-bridge/" + e + } + } + const Bi = new Set(["apps", "books", "music", "podcasts", "tv"]) + , Ki = /\.apple\.com$/; + function getCommerceHostname(e, s) { + !s && "undefined" != typeof location && location.hostname && (s = location); + let n = e + ".itunes.apple.com"; + if (!s) + return n; + const d = function(e) { + if (!e || !Ki.test(e)) + return; + const s = e.split("."); + let n = s[s.length - 3]; + const d = n; + if (n && n.includes("-")) { + const e = n.split("-"); + n = e[e.length - 1] + } + return Bi.has(n) ? d : void 0 + }(s.hostname); + return d && (n = `${e}.${d}.apple.com`), + n + } + var Fi; + function buildQueryParams(e={ + app: Fi.APP, + p: Fi.P + }) { + return void 0 === e.app && (e.app = Fi.APP), + void 0 === e.p && (e.p = Fi.P), + Object.keys(e).map(s=>`${encodeURIComponent(s)}=${encodeURIComponent(e[s])}`).join("&") + } + !function(e) { + e.APP = "music", + e.P = "subscribe" + }(Fi || (Fi = {})); + const Vi = { + 2: "com.apple.onboarding.tvapp", + 0: "com.apple.onboarding.applemusic" + } + , Hi = { + 2: "pltvcid", + 0: "pldfltcid" + } + , zi = { + "com.apple.onboarding.tvapp": 5, + "com.apple.onboarding.applemusic": 3 + }; + var qi; + !function(e) { + e[e.ParseError = -32700] = "ParseError", + e[e.InvalidRequest = -32600] = "InvalidRequest", + e[e.MethodNotFound = -32601] = "MethodNotFound", + e[e.InvalidParams = -32602] = "InvalidParams", + e[e.InternalError = -32603] = "InternalError" + }(qi || (qi = {})); + class Dispatch { + constructor(e={}) { + this._registry = {}, + this._sequence = 0, + this.handle = e=>{ + e.data && "2.0" === e.data.jsonrpc && ("*" !== this.origin && this.origin !== e.origin || (e.data.method && this.destination ? this.handleRequest(e.data).then(e=>{ + this.send(this.destination, e) + } + ) : (hasOwn(e.data, "result") || e.data.error) && this.handleResponse(e.data))) + } + , + this.destination = e.destination, + this.methods = e.methods || {}, + this.origin = e.origin || "*", + e.source && (this.source = e.source) + } + get source() { + return this._source + } + set source(e) { + if (!e && this._source) + return this._source.removeEventListener("message", this.handle), + void (this._source = void 0); + e.addEventListener("message", this.handle), + this._source = e + } + apply(e, s) { + if (!this.destination) + throw new Error("No destination"); + const n = this._sequence++ + , d = new Promise((e,s)=>{ + this._registry[n] = { + resolve: e, + reject: s + } + } + ); + return this.send(this.destination, { + jsonrpc: "2.0", + id: n, + method: e, + params: s + }), + d + } + call(e, ...s) { + return this.apply(e, s) + } + handleRequest(e) { + return __awaiter$2(this, void 0, void 0, (function*() { + const s = { + jsonrpc: "2.0", + id: e.id + } + , n = this.methods[e.method]; + if (!n) + return Object.assign(s, { + error: { + code: qi.MethodNotFound, + message: "Method not found" + } + }); + try { + const d = yield n.apply(void 0, ensureArray(e.params)); + return Object.assign(s, { + result: d + }) + } catch (F) { + return Object.assign(s, { + error: { + code: F.code || qi.InternalError, + message: F.message + } + }) + } + } + )) + } + handleResponse(e) { + const s = this._registry[e.id]; + delete this._registry[e.id], + s && (e.error ? s.reject(Object.assign(Error(), e.error)) : s.resolve(e.result)) + } + send(e, s) { + e.postMessage(s, e.window === e ? this.origin : void 0) + } + } + var Wi; + function validateToken(e) { + var s; + if ("string" != typeof e) + return !1; + const n = e.match(/[a-zA-Z0-9=\/+]{32,}==$/); + return null !== (s = n && n.length > 0) && void 0 !== s && s + } + !function(e) { + e[e.UNAVAILABLE = -1] = "UNAVAILABLE", + e[e.NOT_DETERMINED = 0] = "NOT_DETERMINED", + e[e.DENIED = 1] = "DENIED", + e[e.RESTRICTED = 2] = "RESTRICTED", + e[e.AUTHORIZED = 3] = "AUTHORIZED" + }(Wi || (Wi = {})); + const Yi = `https://${getCommerceHostname("buy")}/commerce/account/authenticateMusicKitRequest` + , Gi = "https://authorize.music.apple.com" + , Qi = /^https?:\/\/(.+\.)*(apple\.com|apps\.mzstatic\.com)(\/[\w\d]+)*$/; + var Ji, Xi, Zi, es; + !function(e) { + e[e.AUTHORIZE = 0] = "AUTHORIZE", + e[e.SUBSCRIBE = 1] = "SUBSCRIBE" + }(Ji || (Ji = {})); + class ServiceSetupView { + constructor(e, s={}) { + var n; + if (this.developerToken = e, + this.authenticateMethod = "GET", + this.target = "apple-music-service-view", + this.deeplinkParameters = s && s.deeplinkParameters || {}, + this.iconURL = s && s.iconURL, + this.authenticateMethod = s && s.authenticateMethod || "GET", + this.isServiceView && window.opener !== window) { + const e = "undefined" != typeof sessionStorage ? sessionStorage.getItem("ac") : void 0 + , s = null != e ? new URL(e).origin : void 0; + s && (this.dispatch = new Dispatch({ + destination: null !== (n = window.opener) && void 0 !== n ? n : void 0, + origin: s, + source: window + })) + } + } + get isServiceView() { + return /(authorize\.(.+\.)*apple\.com)/i.test(window.location.hostname) || window && window.name === this.target || !1 + } + focus() { + this._window && window.focus && this._window.focus() + } + load(e={ + action: Ji.AUTHORIZE + }) { + return __awaiter$1(this, void 0, void 0, (function*() { + return e.action === Ji.SUBSCRIBE ? this._subscribeAction(e.parameters) : this._authorizeAction(e.parameters) + } + )) + } + present(e="", s) { + const {height: n, left: d, top: h, width: p} = this._calculateClientDimensions() + , y = { + height: 650, + menubar: "no", + resizable: "no", + scrollbars: "no", + status: "no", + toolbar: "no", + width: 650 + } + , m = Object.assign(Object.assign(Object.assign({}, y), { + left: p / 2 - y.width / 2 + d, + top: n / 2 - y.height / 2 + h + }), s) + , g = Object.keys(m).map(e=>`${e}=${m[e]}`).join(","); + return /trident|msie/i.test(navigator.userAgent) ? (this._window = window.open(window.location.href, this.target, g) || void 0, + this._window.location.href = e) : this._window = window.open(e, this.target, g) || void 0, + /\bedge\b/i.test(navigator.userAgent) && (this._window.opener = self), + this.focus(), + this._window + } + _authorizeAction(e={}) { + var s; + return __awaiter$1(this, void 0, void 0, (function*() { + let n, d; + const h = (null === (s = window.location) || void 0 === s ? void 0 : s.href) || ""; + return "GET" === this.authenticateMethod ? d = `${Gi}/woa?${buildQueryParams(Object.assign(Object.assign({}, this.deeplinkParameters), { + a: btoa(this._thirdPartyInfo()), + referrer: h + }))}` : (n = this._buildFormElement(Yi), + document.body.appendChild(n)), + new Promise((s,h)=>{ + const p = this.present(d); + this.dispatch = new Dispatch({ + methods: { + authorize(e, n, d) { + validateToken(e) ? s({ + restricted: n && "1" === n, + userToken: e, + cid: d + }) : h(Wi.NOT_DETERMINED) + }, + close() {}, + decline() { + h(Wi.DENIED) + }, + switchUserId() { + h(Wi.NOT_DETERMINED) + }, + thirdPartyInfo: ()=>this._thirdPartyInfo(this.developerToken, Object.assign(Object.assign({}, this.deeplinkParameters), e)), + unavailable() { + h(Wi.UNAVAILABLE) + } + }, + origin: Gi, + source: window, + destination: p + }), + n && n.submit() + } + ) + } + )) + } + _buildFormElement(e, s=this.target, n=this.developerToken) { + const d = document.createElement("form"); + d.setAttribute("method", "post"), + d.setAttribute("action", e), + d.setAttribute("target", s), + d.style.display = "none"; + const h = document.createElement("input"); + h.setAttribute("name", "jwtToken"), + h.setAttribute("value", n), + d.appendChild(h); + const p = document.createElement("input"); + p.setAttribute("name", "isWebPlayer"), + p.setAttribute("value", "true"), + d.appendChild(p); + const y = document.createElement("input"); + return y.setAttribute("name", "LogoURL"), + y.setAttribute("value", ""), + d.appendChild(y), + d + } + _calculateClientDimensions(e=window) { + return { + height: e.innerHeight ? e.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height, + left: e.screenLeft ? e.screenLeft : screen.availLeft || screen.left, + top: e.screenTop ? e.screenTop : screen.availTop || screen.top, + width: e.innerWidth ? e.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width + } + } + _subscribeAction(e={}) { + return __awaiter$1(this, void 0, void 0, (function*() { + return Object.assign(e, this.deeplinkParameters), + new Promise((s,n)=>{ + const d = "https://authorize.music.apple.com/upsell?" + buildQueryParams(e); + this.present(d), + window.addEventListener("message", ({data: e, origin: d, source: h})=>{ + const {closeWindow: p, launchClient: y} = "string" == typeof e ? JSON.parse(e) : e; + d && !Qi.test(d) || (y ? 0 === y.supported ? n("Unable to subscribe on this platform.") : s(y) : n("Subscribe action error.")) + } + ) + } + ) + } + )) + } + _thirdPartyInfo(e=this.developerToken, s) { + var n; + let d = this.iconURL; + const h = window.location.host || document.referrer + , p = [...[].slice.call(document.querySelectorAll('link[rel="apple-music-app-icon"]')), ...[].slice.call(document.querySelectorAll('link[rel="apple-touch-icon-precomposed"]')), ...[].slice.call(document.querySelectorAll('link[rel="apple-touch-icon"]'))]; + if (p && p[0] && p[0].href) { + const e = p.find(e=>!!e.sizes && "120x120" === e.sizes.value); + d = null !== (n = null == e ? void 0 : e.href) && void 0 !== n ? n : p[0].href + } + return JSON.stringify({ + thirdPartyIconURL: d, + thirdPartyName: h, + thirdPartyParameters: s, + thirdPartyToken: e + }) + } + } + !function(e) { + e.ID = "us", + e.LANGUAGE_TAG = "en-gb" + }(Xi || (Xi = {})); + class Storefront { + constructor(e, s, n) { + this.id = e, + this.attributes = s, + this.type = "storefronts", + this.href = n || `/v1/${this.type}/${e}` + } + static inferFromLanguages(e, s=getLanguages()) { + return __awaiter$1(this, void 0, void 0, (function*() { + const n = yield function(e, s="https://api.music.apple.com/v1") { + return __awaiter$1(this, void 0, void 0, (function*() { + const n = new Headers({ + Authorization: "Bearer " + e + }) + , d = yield fetch(s + "/storefronts", { + headers: n + }) + , h = yield d.json(); + return h.errors ? Promise.reject(h.errors) : h.data + } + )) + }(e) + , d = n.map(e=>e.id) + , h = s[0] || "en-US" + , [p,y] = h.toLowerCase().split(/-|_/) + , m = d.includes(y) ? y : "us"; + return n.find(e=>e.id === m) + } + )) + } + } + !function(e) { + e.DEFAULT_CID = "pldfltcid", + e.TV_CID = "pltvcid", + e.RESTRICTIONS_ENABLED = "itre", + e.STOREFRONT_COUNTRY_CODE = "itua", + e.USER_TOKEN = "media-user-token" + }(Zi || (Zi = {})), + function(e) { + e.authorizationStatusDidChange = "authorizationStatusDidChange", + e.authorizationStatusWillChange = "authorizationStatusWillChange", + e.eligibleForSubscribeView = "eligibleForSubscribeView", + e.needsGDPRDidChange = "needsGDPRDidChange", + e.storefrontCountryCodeDidChange = "storefrontCountryCodeDidChange", + e.storefrontIdentifierDidChange = "storefrontIdentifierDidChange", + e.userTokenDidChange = "userTokenDidChange" + }(es || (es = {})), + Zi.DEFAULT_CID; + let ts = !1; + ts = !0; + const is = "https://" + getCommerceHostname("buy") + , ss = `https://${getCommerceHostname("play")}/WebObjects/MZPlay.woa/wa`; + class StoreKit extends Notifications { + constructor(e, s) { + super([es.authorizationStatusDidChange, es.authorizationStatusWillChange, es.eligibleForSubscribeView, es.needsGDPRDidChange, es.storefrontCountryCodeDidChange, es.userTokenDidChange, es.storefrontIdentifierDidChange]), + this.developerToken = e, + this.apiBase = "https://api.music.apple.com/v1", + this.iTunesBuyBase = is, + this.meParameters = {}, + this.persist = "localstorage", + this.playBase = ss, + this.prefix = "music", + this.realm = 0, + this.storage = window.localStorage, + this._authorizationStatus = Wi.NOT_DETERMINED, + this._dispatchedSubscribeView = !1, + this._me = null, + this._cids = {}, + this._gdprVersion = -1, + this._needsGDPR = void 0, + this._dynamicUserToken = getCookie(Zi.USER_TOKEN), + s && (s.apiBase && (this.apiBase = s.apiBase), + s.deeplink && (this.deeplinkParameters = s.deeplink), + s.meParameters && (this.meParameters = s.meParameters), + s.persist && (this.persist = s.persist), + s.prefix && (this.prefix = s.prefix), + void 0 !== s.realm && (this.realm = s.realm), + this.bundleId = Vi[this.realm]), + this.cidNamespace = Hi[this.realm], + this._developerToken = new DeveloperToken(e), + this._serviceSetupView = new ServiceSetupView(e,{ + authenticateMethod: s && s.authenticateMethod, + iconURL: s && s.iconURL, + deeplinkParameters: this.deeplinkParameters + }), + this.storagePrefix = `${this.prefix}.${this._developerToken.teamId}`.toLocaleLowerCase(); + const n = this._getStorageItem(Zi.USER_TOKEN); + this.userToken = n || void 0, + this.developerToken && this.userTokenIsValid && (this._restrictedEnabled = this.restrictedEnabled, + this.shouldDisplayPrivacyLink(this.bundleId).catch(()=>{} + )), + this._storefrontCountryCode = this.storefrontCountryCode, + this.whenAuthCompleted = Promise.resolve(), + isNodeEnvironment$1() || (this._processLocationHash(window.location.hash), + "cookie" !== this.persist || (null == s ? void 0 : s.disableAuthBridge) || (this.authBridgeApp = new AuthBridgeApp, + this.authBridgeApp.authClearedFromOtherFrame = this.revokeUserToken.bind(this), + this.whenAuthCompleted = this.authBridgeApp.whenAuthCompleted.then(()=>{ + this.userToken = this._getStorageItem(Zi.USER_TOKEN) || void 0 + } + ))) + } + get authorizationStatus() { + return this._authorizationStatus + } + set authorizationStatus(e) { + this._authorizationStatus !== e && (this._getIsActiveSubscription.updateCache(void 0), + this.dispatchEvent(es.authorizationStatusWillChange, { + authorizationStatus: this._authorizationStatus, + newAuthorizationStatus: e + }), + this._authorizationStatus = e, + this.dispatchEvent(es.authorizationStatusDidChange, { + authorizationStatus: e + })) + } + get cid() { + if (!this._cids[this.cidNamespace]) { + const e = this._getStorageItem(this.cidNamespace); + this._cids[this.cidNamespace] = e || void 0 + } + return this._cids[this.cidNamespace] + } + set cid(e) { + e ? this._setStorageItem(this.cidNamespace, e) : this._removeStorageItem(this.cidNamespace), + this._cids[this.cidNamespace] = e + } + eligibleForSubscribeView() { + return __awaiter$1(this, void 0, void 0, (function*() { + const e = yield this.hasMusicSubscription(); + return (!this.hasAuthorized || this.hasAuthorized && !e) && !this._dispatchedSubscribeView + } + )) + } + get hasAuthorized() { + return this.authorizationStatus > Wi.DENIED + } + get logoutURL() { + return this.iTunesBuyBase + "/account/web/logout" + } + get parentalControls() { + return this._parentalControls + } + set parentalControls(e) { + this._parentalControls = e, + e && (0 === this.realm ? this.restrictedEnabled = e.musicParentalControlsEnabled : 2 === this.realm && e.videoContentRestrictions && (this.authorizationStatus = Wi.RESTRICTED)) + } + get _pldfltcid() { + return this._cids[Zi.DEFAULT_CID] + } + set _pldfltcid(e) { + this._cids[Zi.DEFAULT_CID] = e + } + get privacyAcknowledgements() { + return this._privacyAcknowledgements + } + set privacyAcknowledgements(e) { + if (this._privacyAcknowledgements = e, + !e) + return this._gdprVersion = -1, + void (this._needsGDPR = void 0); + this.bundleId && (this._gdprVersion = e[this.bundleId] || 0, + this._needsGDPR = this._gdprVersion < (zi[this.bundleId] || 0), + this._needsGDPR && this.dispatchEvent(es.needsGDPRDidChange, { + GDPRVersion: this._gdprVersion, + needsGDPR: this._needsGDPR + })) + } + get restrictedEnabled() { + if (this.userToken && "boolean" != typeof this._restrictedEnabled) { + const e = this._getStorageItem(Zi.RESTRICTIONS_ENABLED); + if (e) + this._restrictedEnabled = "0" !== e; + else if (this._storefrontCountryCode) { + const e = ["br", "ch", "gt", "hu", "id", "in", "it", "kr", "la", "lt", "my", "ru", "sg", "tr"]; + this._restrictedEnabled = -1 !== e.indexOf(this._storefrontCountryCode) || void 0 + } + } + return this._restrictedEnabled + } + set restrictedEnabled(e) { + this.userToken && void 0 !== e && this._setStorageItem(Zi.RESTRICTIONS_ENABLED, e ? "1" : "0"), + this._restrictedEnabled = e, + e && (this.authorizationStatus = Wi.RESTRICTED) + } + get storefrontCountryCode() { + if (!this._storefrontCountryCode) { + const e = this._getStorageItem(Zi.STOREFRONT_COUNTRY_CODE); + this._storefrontCountryCode = (null == e ? void 0 : e.toLowerCase()) || Xi.ID + } + return this._storefrontCountryCode + } + set storefrontCountryCode(e) { + e && this.userToken ? this._setStorageItem(Zi.STOREFRONT_COUNTRY_CODE, e) : this._removeStorageItem(Zi.STOREFRONT_COUNTRY_CODE), + this._storefrontCountryCode = e, + this.dispatchEvent(es.storefrontCountryCodeDidChange, { + storefrontCountryCode: e + }) + } + get storefrontIdentifier() { + return this._storefrontIdentifier + } + set storefrontIdentifier(e) { + this._storefrontIdentifier = e, + this.dispatchEvent(es.storefrontIdentifierDidChange, { + storefrontIdentifier: e + }) + } + runTokenValidations(e, s=!0) { + e && validateToken(e) ? (s && this._setStorageItem(Zi.USER_TOKEN, e), + this.authorizationStatus = this.restrictedEnabled ? Wi.RESTRICTED : Wi.AUTHORIZED) : (this._removeStorageItem(Zi.USER_TOKEN), + this.authorizationStatus = Wi.NOT_DETERMINED) + } + wrapDynamicUserTokenForChanges(e, s=invoke(e)) { + if ("function" != typeof e) + return e; + let n = s; + return ()=>{ + const s = invoke(e); + return n !== s && (n = s, + this.runTokenValidations(s, !1), + this.dispatchEvent(es.userTokenDidChange, { + userToken: s + })), + s || "" + } + } + get dynamicUserToken() { + return this._dynamicUserToken + } + set dynamicUserToken(e) { + const s = invoke(e); + this._dynamicUserToken = this.wrapDynamicUserTokenForChanges(e, s), + this.runTokenValidations(s, "function" != typeof e), + this.dispatchEvent(es.userTokenDidChange, { + userToken: s + }) + } + get userToken() { + return invoke(this.dynamicUserToken) + } + set userToken(e) { + this.dynamicUserToken = e + } + get userTokenIsValid() { + return validateToken(this.userToken) + } + deeplinkURL(e={}) { + return "https://finance-app.itunes.apple.com/deeplink?" + buildQueryParams(e = Object.assign(Object.assign({}, this.deeplinkParameters || {}), e)) + } + itunesDeeplinkURL(e={ + p: "browse" + }) { + return "https://itunes.apple.com/deeplink?" + buildQueryParams(e = Object.assign(Object.assign({}, this.deeplinkParameters || {}), e)) + } + pldfltcid() { + return __awaiter$1(this, void 0, void 0, (function*() { + if (!this._cids[Zi.DEFAULT_CID]) + try { + yield this.infoRefresh() + } catch (e) { + return + } + return this._cids[Zi.DEFAULT_CID] + } + )) + } + renewUserToken() { + return __awaiter$1(this, void 0, void 0, (function*() { + if (!this.userToken) + return this.requestUserToken(); + const e = new Headers({ + Authorization: "Bearer " + this.developerToken, + Accept: "application/json", + "Content-Type": "application/json", + "X-Apple-Music-User-Token": "" + this.userToken + }) + , s = yield fetch(this.playBase + "/renewMusicToken", { + method: "POST", + headers: e + }); + if (401 === s.status) + return yield this.revokeUserToken(), + Promise.reject(new Error("Renew token")); + const n = yield s.json(); + return n["music-token"] && (this.userToken = n["music-token"]), + this.userToken + } + )) + } + requestStorefrontCountryCode() { + return __awaiter$1(this, void 0, void 0, (function*() { + if (this.authorizationStatus <= Wi.DENIED) + return Promise.reject("Not authorized: " + this.authorizationStatus); + const e = new Headers({ + Authorization: "Bearer " + this.developerToken, + "Music-User-Token": this.userToken || "" + }) + , s = yield fetch(this.apiBase + "/me/storefront", { + headers: e + }); + if (s && !s.ok) + return this._reset(), + Promise.reject("Storefront Country Code error."); + const n = yield s.json(); + if (n.errors) + return Promise.reject(n.errors); + const [d] = n.data; + return d && d.id ? (this.storefrontCountryCode = d.id, + this.storefrontCountryCode) : Promise.reject("Storefront Country Code error.") + } + )) + } + requestStorefrontIdentifier() { + return __awaiter$1(this, void 0, void 0, (function*() { + if (!this.storefrontIdentifier) { + const e = yield Storefront.inferFromLanguages(this.developerToken); + this.storefrontIdentifier = e.id + } + return this.storefrontIdentifier + } + )) + } + requestUserToken() { + return __awaiter$1(this, void 0, void 0, (function*() { + if (this._serviceSetupView.isServiceView) + return this.userToken || ""; + try { + const e = yield this._serviceSetupView.load({ + action: Ji.AUTHORIZE + }); + this.cid = e.cid, + this.userToken = e.userToken, + this.restrictedEnabled = e.restricted + } catch (e) { + return this._reset(), + this.authorizationStatus = e, + Promise.reject(e) + } + return this.userToken + } + )) + } + revokeUserToken() { + var e; + return __awaiter$1(this, void 0, void 0, (function*() { + try { + yield this._webPlayerLogout() + } catch (s) {} + null === (e = this.authBridgeApp) || void 0 === e || e.clearAuth(), + this.dispatchEvent(es.authorizationStatusWillChange, { + authorizationStatus: this.authorizationStatus, + newAuthorizationStatus: Wi.NOT_DETERMINED + }), + this._reset(), + this.dispatchEvent(es.authorizationStatusDidChange, { + authorizationStatus: this.authorizationStatus + }), + this.dispatchEvent(es.userTokenDidChange, { + userToken: this.userToken + }) + } + )) + } + setCids(e) { + this._cids = Object.assign(Object.assign({}, this._cids), e), + Object.keys(this._cids).forEach(e=>{ + this._setStorageItem(e, this._cids[e]) + } + ) + } + shouldDisplayPrivacyLink(e) { + return __awaiter$1(this, void 0, void 0, (function*() { + return void 0 !== this._needsGDPR || (yield this.me()), + this._needsGDPR + } + )) + } + hasMusicSubscription() { + return __awaiter$1(this, void 0, void 0, (function*() { + return !!this.hasAuthorized && this._getIsActiveSubscription() + } + )) + } + _getIsActiveSubscription() { + var e; + return __awaiter$1(this, void 0, void 0, (function*() { + const s = yield this.me(); + return !!(null === (e = s.subscription) || void 0 === e ? void 0 : e.active) + } + )) + } + resetSubscribeViewEligibility() { + this._dispatchedSubscribeView = !1 + } + presentSubscribeViewForEligibleUsers(e={}, s=!0) { + return __awaiter$1(this, void 0, void 0, (function*() { + const n = yield this.eligibleForSubscribeView(); + if (!this._serviceSetupView.isServiceView && n) { + if (!s) + return this.dispatchEvent(es.eligibleForSubscribeView, e), + void (this._dispatchedSubscribeView = !0); + try { + const e = yield this._serviceSetupView.load({ + action: Ji.SUBSCRIBE + }); + return this._dispatchedSubscribeView = !0, + e + } catch (d) { + return this.revokeUserToken() + } + } + } + )) + } + infoRefresh() { + return __awaiter$1(this, void 0, void 0, (function*() { + if (this.authorizationStatus <= Wi.DENIED) + return Promise.reject("Not authorized: " + this.authorizationStatus); + const e = new Headers({ + Authorization: "Bearer " + this.developerToken, + "Music-User-Token": this.userToken || "" + }); + try { + const s = yield fetch(this.iTunesBuyBase + "/account/web/infoRefresh", { + credentials: "include", + headers: e + }) + , n = yield s.json(); + this.setCids(n) + } catch (s) {} + } + )) + } + me() { + return this.authorizationStatus <= Wi.DENIED ? Promise.reject("Not authorized: " + this.authorizationStatus) : (this._me || (this._me = new Promise((e,s)=>__awaiter$1(this, void 0, void 0, (function*() { + const n = new Headers({ + Authorization: "Bearer " + this.developerToken, + "Music-User-Token": this.userToken || "" + }) + , d = addQueryParamsToURL(this.apiBase + "/me/account", Object.assign({ + meta: "subscription" + }, this.meParameters)) + , h = yield fetch(d, { + headers: n + }); + if (h && !h.ok) + return 2 !== this.realm && this._reset(), + s("Account error."); + let p = yield h.json(); + if (p.errors) + return s(p.errors); + const {data: y, meta: m} = p; + if (!m || !m.subscription) + return s("Account error."); + this.storefrontCountryCode = m.subscription.storefront; + const g = { + meta: m, + subscription: m.subscription + }; + y && y.length && (g.attributes = y[0].attributes); + try { + let s = yield fetch(this.iTunesBuyBase + "/account/web/info", { + credentials: "include", + headers: n + }); + if (p = yield s.json(), + this.parentalControls = p.parentalControlsData, + this.privacyAcknowledgements = p.privacyAcknowledgement, + isEmpty(this.privacyAcknowledgements || {})) { + try { + yield this.infoRefresh() + } catch (v) { + e(g) + } + s = yield fetch(this.iTunesBuyBase + "/account/web/info", { + credentials: "include", + headers: n + }), + p = yield s.json(), + this.parentalControls = p.parentalControlsData, + this.privacyAcknowledgements = p.privacyAcknowledgement + } + g.info = p + } catch (bt) { + console.warn("Failed to fetch privacyAcknowledgements", bt) + } + return e(g) + } + ))).then(e=>{ + var s; + return this._getIsActiveSubscription.updateCache((null === (s = e.subscription) || void 0 === s ? void 0 : s.active) || !1), + this._me = null, + e + } + ).catch(e=>(this._me = null, + Promise.reject(e)))), + this._me) + } + musicSubscriptionOffers(e, s=getLanguages()) { + return __awaiter$1(this, void 0, void 0, (function*() { + let n; + if (this.hasAuthorized) { + n = (yield this.me()).info.storeFrontISO3A + } else { + if (!e) { + const n = yield Storefront.inferFromLanguages(this.developerToken, s); + e = null == n ? void 0 : n.id + } + n = e && Je[e.toUpperCase()] || "USA" + } + const d = function(e="en-US") { + const s = xi[e.toLowerCase()]; + if (s) + return s; + if (e.includes("-")) { + const s = e.split("-")[0] + , n = xi[s.toLowerCase()]; + if (n) + return n + } + return xi["en-us"] + }(s[0]) + , h = Ve[n]; + if (!d || !h) + return []; + const p = new Headers({ + "X-Apple-Store-Front": `${h}-${d},8` + }); + this.userToken && (p.set("Authorization", "Bearer " + this.developerToken), + p.set("Music-User-Token", this.userToken)); + const y = yield fetch(this.iTunesBuyBase + "/commerce/web/subscription/offers/music", { + headers: p + }); + if (!y.ok) + return Promise.reject(y.status); + return (yield y.json()).offers + } + )) + } + _getStorageItem(e) { + if (e) + return "cookie" === this.persist ? getCookie(e) : "localstorage" === this.persist ? this.storage.getItem(`${this.storagePrefix}.${e}`) : void 0 + } + _processLocationHash(e) { + const s = /^\#([a-zA-Z0-9+\/]{200,}={0,2})$/; + if (s.test(e)) { + const d = e.replace(s, "$1"); + try { + const {itre: e, musicUserToken: s, cid: n} = JSON.parse(atob(d)); + this.restrictedEnabled = e && "1" === e, + this.userToken = s, + this.cid = n + } catch (n) {} + history.replaceState(null, document.title, " ") + } + } + _removeStorageItem(e) { + if ("cookie" === this.persist) + this._removeCookieFromDomains(e); + else if ("localstorage" === this.persist) + return this.storage.removeItem(`${this.storagePrefix}.${e}`) + } + _removeCookieFromDomains(e, s=window) { + removeCookie(e); + const {hostname: n} = s.location + , d = n.split("."); + if (d.length && (d.shift(), + d.length > 2)) + for (let h = d.length; h > 2; h--) { + const n = d.join("."); + d.shift(), + removeCookie(e, s, n) + } + } + _reset(e=Wi.NOT_DETERMINED) { + this._authorizationStatus = e, + this._cids = {}, + this._dispatchedSubscribeView = !1, + this._restrictedEnabled = void 0, + this._storefrontCountryCode = void 0, + this._getIsActiveSubscription.updateCache(void 0), + Object.keys(Hi).forEach(e=>{ + this._removeStorageItem(Hi[e]) + } + ), + this._removeStorageItem(Zi.RESTRICTIONS_ENABLED), + this._removeStorageItem(Zi.USER_TOKEN), + this._removeStorageItem(Zi.STOREFRONT_COUNTRY_CODE), + this._dynamicUserToken = void 0, + this._me = null, + this.privacyAcknowledgements = void 0 + } + _setStorageItem(e, s) { + var n; + return "cookie" === this.persist ? (null === (n = this.authBridgeApp) || void 0 === n || n.setCookieItem(e, s), + setCookie(e, s, "/", 180)) : "localstorage" === this.persist ? this.storage.setItem(`${this.storagePrefix}.${e}`, s) : void 0 + } + _webPlayerLogout() { + return __awaiter$1(this, void 0, void 0, (function*() { + const e = new Headers({ + Authorization: "Bearer " + this.developerToken, + Accept: "application/json", + "Content-Type": "application/json", + "X-Apple-Music-User-Token": "" + this.userToken + }); + e.delete("X-Apple-Music-User-Token"), + e.append("Music-User-Token", this.userToken || ""); + const s = yield fetch(this.logoutURL, { + method: "POST", + headers: e, + credentials: "include" + }); + return s && !s.ok ? Promise.reject(s.status) : s.json() + } + )) + } + } + !function(e, s, n, d) { + var h, p = arguments.length, y = p < 3 ? s : null === d ? d = Object.getOwnPropertyDescriptor(s, n) : d; + if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) + y = Reflect.decorate(e, s, n, d); + else + for (var m = e.length - 1; m >= 0; m--) + (h = e[m]) && (y = (p < 3 ? h(y) : p > 3 ? h(s, n, y) : h(s, n)) || y); + p > 3 && y && Object.defineProperty(s, n, y) + }([((e=300)=>(s,n,d)=>{ + if (void 0 === d || "function" != typeof d.value) + throw new TypeError(`Only methods can be decorated with @CachedResult, but ${n} is not a method.`); + return { + configurable: !0, + get() { + const s = d.value + , h = 1e3 * e; + let p, y = -1; + function cachedResultMethod(...e) { + return __awaiter$2(this, void 0, void 0, (function*() { + const n = Date.now(); + return (void 0 === p || -1 === y || y > 0 && n > y + h) && (y = n, + p = yield s.apply(this, e)), + p + } + )) + } + return cachedResultMethod.updateCache = function(e) { + y = Date.now(), + p = e + } + , + cachedResultMethod.getCachedValue = ()=>p, + Object.defineProperty(this, n, { + value: cachedResultMethod, + configurable: !0, + writable: !0 + }), + cachedResultMethod + } + } + } + )(900), __metadata$1("design:type", Function), __metadata$1("design:paramtypes", []), __metadata$1("design:returntype", Promise)], StoreKit.prototype, "_getIsActiveSubscription", null); + const rs = { + audioTrackAdded: "audioTrackAdded", + audioTrackChanged: "audioTrackChanged", + audioTrackRemoved: "audioTrackRemoved", + bufferedProgressDidChange: "bufferedProgressDidChange", + drmUnsupported: "drmUnsupported", + forcedTextTrackChanged: "forcedTextTrackChanged", + mediaCanPlay: "mediaCanPlay", + mediaElementCreated: "mediaElementCreated", + mediaPlaybackError: "mediaPlaybackError", + nowPlayingItemDidChange: "nowPlayingItemDidChange", + nowPlayingItemWillChange: "nowPlayingItemWillChange", + metadataDidChange: "metadataDidChange", + playbackBitrateDidChange: "playbackBitrateDidChange", + playbackDurationDidChange: "playbackDurationDidChange", + playbackProgressDidChange: "playbackProgressDidChange", + playbackRateDidChange: "playbackRateDidChange", + playbackStateDidChange: "playbackStateDidChange", + playbackStateWillChange: "playbackStateWillChange", + playbackTargetAvailableDidChange: "playbackTargetAvailableDidChange", + playbackTargetIsWirelessDidChange: "playbackTargetIsWirelessDidChange", + playbackTimeDidChange: "playbackTimeDidChange", + playbackVolumeDidChange: "playbackVolumeDidChange", + playerTypeDidChange: "playerTypeDidChange", + presentationModeDidChange: "presentationModeDidChange", + primaryPlayerDidChange: "primaryPlayerDidChange", + textTrackAdded: "textTrackAdded", + textTrackChanged: "textTrackChanged", + textTrackRemoved: "textTrackRemoved", + timedMetadataDidChange: "timedMetadataDidChange" + } + , ns = { + configured: "musickitconfigured", + loaded: "musickitloaded", + audioTrackAdded: rs.audioTrackAdded, + audioTrackChanged: rs.audioTrackChanged, + audioTrackRemoved: rs.audioTrackRemoved, + authorizationStatusDidChange: es.authorizationStatusDidChange, + authorizationStatusWillChange: es.authorizationStatusWillChange, + bufferedProgressDidChange: rs.bufferedProgressDidChange, + capabilitiesChanged: "capabilitiesChanged", + autoplayEnabledDidChange: "autoplayEnabledDidChange", + drmUnsupported: rs.drmUnsupported, + eligibleForSubscribeView: es.eligibleForSubscribeView, + forcedTextTrackChanged: rs.forcedTextTrackChanged, + mediaCanPlay: rs.mediaCanPlay, + mediaElementCreated: rs.mediaElementCreated, + mediaItemStateDidChange: k.mediaItemStateDidChange, + mediaItemStateWillChange: k.mediaItemStateWillChange, + mediaPlaybackError: rs.mediaPlaybackError, + mediaSkipAvailable: "mediaSkipAvailable", + mediaRollEntered: "mediaRollEntered", + mediaUpNext: "mediaUpNext", + metadataDidChange: rs.metadataDidChange, + needsGDPRDidChange: "needsGDPRDidChange", + nowPlayingItemDidChange: rs.nowPlayingItemDidChange, + nowPlayingItemWillChange: rs.nowPlayingItemWillChange, + playbackBitrateDidChange: rs.playbackBitrateDidChange, + playbackDurationDidChange: rs.playbackDurationDidChange, + playbackProgressDidChange: rs.playbackProgressDidChange, + playbackRateDidChange: rs.playbackRateDidChange, + playbackStateDidChange: rs.playbackStateDidChange, + playbackStateWillChange: rs.playbackStateWillChange, + playbackTargetAvailableDidChange: rs.playbackTargetAvailableDidChange, + playbackTargetIsWirelessDidChange: rs.playbackTargetIsWirelessDidChange, + playbackTimeDidChange: rs.playbackTimeDidChange, + playbackVolumeDidChange: rs.playbackVolumeDidChange, + playerTypeDidChange: rs.playerTypeDidChange, + presentationModeDidChange: rs.presentationModeDidChange, + primaryPlayerDidChange: rs.primaryPlayerDidChange, + queueIsReady: "queueIsReady", + queueItemsDidChange: "queueItemsDidChange", + queueItemForStartPosition: "queueItemForStartPosition", + queuePositionDidChange: "queuePositionDidChange", + shuffleModeDidChange: "shuffleModeDidChange", + repeatModeDidChange: "repeatModeDidChange", + storefrontCountryCodeDidChange: es.storefrontCountryCodeDidChange, + storefrontIdentifierDidChange: es.storefrontIdentifierDidChange, + textTrackAdded: rs.textTrackAdded, + textTrackChanged: rs.textTrackChanged, + textTrackRemoved: rs.textTrackRemoved, + timedMetadataDidChange: rs.timedMetadataDidChange, + userTokenDidChange: es.userTokenDidChange, + webComponentsLoaded: "musickitwebcomponentsloaded" + }; + var as, ds; + function formattedSeconds(e) { + return { + hours: Math.floor(e / 3600), + minutes: Math.floor(e % 3600 / 60) + } + } + e.PlaybackStates = void 0, + (as = e.PlaybackStates || (e.PlaybackStates = {}))[as.none = 0] = "none", + as[as.loading = 1] = "loading", + as[as.playing = 2] = "playing", + as[as.paused = 3] = "paused", + as[as.stopped = 4] = "stopped", + as[as.ended = 5] = "ended", + as[as.seeking = 6] = "seeking", + as[as.waiting = 8] = "waiting", + as[as.stalled = 9] = "stalled", + as[as.completed = 10] = "completed", + e.PresentationMode = void 0, + (ds = e.PresentationMode || (e.PresentationMode = {}))[ds.pictureinpicture = 0] = "pictureinpicture", + ds[ds.inline = 1] = "inline"; + const ls = "mk-player-tsid" + , cs = ["exitFullscreen", "webkitExitFullscreen", "mozCancelFullScreen", "msExitFullscreen"] + , us = ["fullscreenElement", "webkitFullscreenElement", "mozFullScreenElement", "msFullscreenElement"] + , hs = ["requestFullscreen", "webkitRequestFullscreen", "mozRequestFullScreen", "msRequestFullscreen"] + , noop = ()=>Promise.resolve() + , ps = (e=>{ + if (void 0 === e) + return noop; + const s = cs.find(s=>"function" == typeof e.prototype[s]); + return "string" != typeof s ? noop : (e=self.document)=>{ + var n; + return null === (n = null == e ? void 0 : e[s]) || void 0 === n ? void 0 : n.call(e) + } + } + )(HTMLDocument) + , ys = (e=>{ + if (void 0 === e) + return ()=>!1; + const s = us.find(s=>s in e.prototype); + return "string" != typeof s ? ()=>!1 : (e=self.document)=>!!e[s] + } + )(HTMLDocument) + , ms = (e=>{ + if (void 0 === e) + return noop; + const s = hs.find(s=>"function" == typeof e.prototype[s]); + return "string" != typeof s ? noop : e=>null == e ? void 0 : e[s]() + } + )(HTMLElement); + class Fullscreen { + constructor(e) { + this.player = e + } + exit() { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this.isInFullscreen()) + return this.stopDispatchingEvents(()=>this.exitFullscreen()) + } + )) + } + request(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (void 0 !== e) + return this.stopDispatchingEvents(()=>this.requestFullscreenForElement(e)) + } + )) + } + stopDispatchingEvents(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return this.player.windowHandlers.stopListeningToVisibilityChanges(e) + } + )) + } + exitFullscreen() { + return ps() + } + isInFullscreen() { + return ys() + } + requestFullscreenForElement(e) { + return ms(e) + } + } + class UnsupportedSeeker { + constructor() { + this.ended = !1 + } + start() { + O.warn("seeker.start is not supported in this playback method") + } + end() { + O.warn("seeker.end is not supported in this playback method") + } + seekToTime(e) { + return O.warn("seekToTime is not supported in this playback method"), + Promise.resolve() + } + } + class PlayerSeeker { + constructor(e) { + this._ended = !1, + this._lastSeekedTime = -1, + this._startTime = -1, + O.debug("seeker: new"), + this._player = e + } + get ended() { + return this._ended + } + get isEngagedInPlayback() { + return this._player.isEngagedInPlayback + } + get stillPlayingSameItem() { + return this._currentItem === this._player.nowPlayingItem + } + end() { + O.debug("seeker: end"), + -1 !== this._startTime ? this._ended ? O.warn("seeker: Cannot end the same seeker twice.") : (this.dispatchStartEvent(), + this.dispatchEndEvent()) : O.warn("seeker: Cannot end a seeker before starting it.") + } + seekToTime(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + var s; + if (O.debug("seeker: seekToTime", e), + !this.ended) + return this.stillPlayingSameItem || (this._currentItem = this._player.nowPlayingItem, + this._startTime = 0), + this._lastSeekedTime = e, + s = this._player.seekToTime(e), + __awaiter$2(void 0, void 0, void 0, (function*() { + try { + return yield s + } catch (bt) { + if ("cancelled" !== bt.message) + throw bt + } + } + )); + O.warn("seeker: Cannot seek once the seeker has ended") + } + )) + } + start() { + O.debug("seeker: start"), + -1 === this._startTime ? (this._currentItem = this._player.nowPlayingItem, + this._startTime = this._player.currentPlaybackTime, + this._lastSeekedTime = this._startTime) : O.warn("seeker: Cannot start same seeker twice") + } + dispatch(e, s) { + this.isEngagedInPlayback ? (O.debug("seeker: dispatch", e), + this._player.dispatch(e, s)) : O.debug("seeker: do not dispatch because isEngagedInPlayback", this.isEngagedInPlayback) + } + dispatchStartEvent() { + this.stillPlayingSameItem || (this._startTime = 0, + this._lastSeekedTime = 0), + this.dispatch(et.playbackScrub, { + position: this._startTime + }) + } + dispatchEndEvent() { + this._ended = !0, + this.dispatch(et.playbackScrub, { + position: this._lastSeekedTime, + endReasonType: e.PlayActivityEndReasonType.SCRUB_END + }) + } + } + const {visibilityChangeEvent: gs, visibilityState: fs, unloadEventName: vs} = (()=>{ + let e = "visibilitychange" + , s = "visibilityState"; + void 0 !== document.mozHidden ? (e = "mozvisibilitychange", + s = "mozVisibilityState") : void 0 !== document.msHidden ? (e = "msvisibilitychange", + s = "msVisibilityState") : document.webkitHidden && (e = "webkitvisibilitychange", + s = "webkitVisibilityState"); + return { + visibilityChangeEvent: e, + visibilityState: s, + unloadEventName: "onpagehide"in window ? "pagehide" : "unload" + } + } + )(); + class WindowHandlers { + constructor(e, s=Fe) { + this.browser = s, + this.dispatchVisibilityChanges = !0, + this.player = e + } + activate(e=self, s=self.document) { + s.addEventListener(gs, this.visibilityChanged), + e.addEventListener("storage", this.storage, !1), + e.addEventListener(vs, this.windowUnloaded) + } + deactivate() { + document.removeEventListener(gs, this.visibilityChanged), + window.removeEventListener("storage", this.storage), + window.addEventListener(vs, this.windowUnloaded) + } + stopListeningToVisibilityChanges(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + this.dispatchVisibilityChanges = !1; + const s = yield e(); + return this.dispatchVisibilityChanges = !0, + s + } + )) + } + dispatch(e, s={}) { + this.player.dispatch(e, s) + } + storage({key: e, newValue: s}) { + e === ls && this.player.tsidChanged(s) + } + visibilityChanged(e) { + const s = e.target[fs]; + O.log("dc visibilityState", s, e, ys()), + this.browser.isiOS && this.dispatchVisibilityChanges && ("hidden" === s ? this.dispatch(et.playerExit, { + position: this.player.currentPlaybackTime + }) : "visible" === s && this.dispatch(et.playerActivate)) + } + windowUnloaded() { + this.player.isPlaying && this.dispatch(et.playerExit, { + position: this.player.currentPlaybackTime + }) + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object]), __metadata$2("design:returntype", void 0)], WindowHandlers.prototype, "storage", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Event]), __metadata$2("design:returntype", void 0)], WindowHandlers.prototype, "visibilityChanged", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", void 0)], WindowHandlers.prototype, "windowUnloaded", null); + const {bufferedProgressDidChange: _s, mediaCanPlay: bs, mediaElementCreated: Ts, mediaPlaybackError: Es, nowPlayingItemDidChange: ks, nowPlayingItemWillChange: Ss, metadataDidChange: Ps, primaryPlayerDidChange: Is, playbackDurationDidChange: As, playbackProgressDidChange: ws, playbackStateDidChange: Rs, playbackRateDidChange: Os, playbackStateWillChange: Cs, playbackTargetAvailableDidChange: Ms, playbackTargetIsWirelessDidChange: Ds, playbackTimeDidChange: Ns, playbackVolumeDidChange: Ls} = rs + , xs = ["canplay", "durationchange", "ended", "error", "loadedmetadata", "loadstart", "pause", "play", "playing", "progress", "ratechange", "seeked", "seeking", "timeupdate", "volumechange", "waiting"] + , {ended: Us, loading: $s, paused: js, playing: Bs, seeking: Ks, stopped: Fs, waiting: Vs} = e.PlaybackStates; + class BasePlayer { + constructor(s) { + this.privateEnabled = !1, + this.siriInitiated = !1, + this.previewOnly = !1, + this._currentBufferedProgress = 0, + this._paused = !1, + this._playbackState = e.PlaybackStates.none, + this._stopped = !1, + this._playbackDidStart = !1, + this._currentPlaybackProgress = 0, + this._hasSmartPlayed = !1, + this._isPrimaryPlayer = !0, + this._playbackTargetAvailable = !1, + this._playbackTargetIsWireless = !1, + this._serial = Date.now().toString(), + this._isDestroyed = !1, + this._dispatcher = s.services.dispatcher, + this._timing = s.services.timing, + this._context = s.context || {}, + this.privateEnabled = s.privateEnabled || !1, + this.siriInitiated = s.siriInitiated || !1, + this._bitrateCalculator = s.services.bitrateCalculator, + this.windowHandlers = new WindowHandlers(this), + this.fullscreen = new Fullscreen(this), + localStorage.setItem(ls, this._serial) + } + get bitrate() { + return this._bitrateCalculator.bitrate + } + get currentBufferedProgress() { + return this._currentBufferedProgress + } + set currentBufferedProgress(e) { + this._currentBufferedProgress !== e && (this._currentBufferedProgress = e, + this._dispatcher.publish(_s, { + progress: e + })) + } + get _currentDuration() { + return this._targetElement.duration + } + get _currentTime() { + var e; + const s = this._targetElement.currentTime + , n = this._buffer; + return s - (null !== (e = null == n ? void 0 : n.currentTimestampOffset) && void 0 !== e ? e : 0) + } + get currentPlaybackDuration() { + const s = this.nowPlayingItem + , n = (null == s ? void 0 : s.playbackType) === e.PlaybackType.encryptedFull || (null == s ? void 0 : s.playbackType) === e.PlaybackType.unencryptedFull + , d = null == s ? void 0 : s.playbackDuration; + return n && d ? this._timing.time(d / 1e3) : this._timing.time(this._currentDuration) + } + get currentPlaybackTime() { + const e = void 0 === this.nowPlayingItem || void 0 === this.nowPlayingItem.playEvent || this._hasSmartPlayed ? this._currentTime : this.nowPlayingItem.playEvent.playCursorInSeconds; + return this._timing.time(e) + } + get currentPlaybackTimeRemaining() { + return this.currentPlaybackDuration - this.currentPlaybackTime + } + get currentPlaybackProgress() { + return this._currentPlaybackProgress || 0 + } + set currentPlaybackProgress(e) { + this._currentPlaybackProgress !== e && (this._currentPlaybackProgress = e, + this._dispatcher.publish(ws, { + progress: e + })) + } + get formattedCurrentPlaybackDuration() { + return formattedSeconds(this.currentPlaybackDuration) + } + get hasMediaElement() { + return this._targetElement instanceof HTMLElement && null !== this._targetElement.parentNode + } + get isEngagedInPlayback() { + return !this._stopped && !this.isPaused() + } + get isPlaying() { + return this.playbackState === Bs + } + get isPrimaryPlayer() { + return this._isPrimaryPlayer + } + set isPrimaryPlayer(e) { + e !== this._isPrimaryPlayer && (this._isPrimaryPlayer = e, + this._isPrimaryPlayer ? localStorage.setItem(ls, this._serial) : (this._dispatcher.publish(Is, { + target: this + }), + this.pause({ + userInitiated: !1 + }))) + } + get isReady() { + return 0 !== this._targetElement.readyState + } + get nowPlayingItem() { + return this._nowPlayingItem + } + set nowPlayingItem(e) { + this._hasSmartPlayed = !1; + const s = this._dispatcher; + if (void 0 === e) + return this._nowPlayingItem = e, + void s.publish(ks, { + item: e + }); + const n = this._nowPlayingItem + , d = this._buffer; + (null == n ? void 0 : n.isEqual(e)) || (s.publish(Ss, { + item: e + }), + this.isPlaying && (null == d ? void 0 : d.currentItem) !== e && this._pauseMedia(), + n && (O.debug("setting state to ended on ", n.title), + n.state = D.ended, + n.endMonitoringStateDidChange(), + n.endMonitoringStateWillChange()), + this._nowPlayingItem = e, + O.debug("setting state to playing on ", e.title), + e.state = D.playing, + e && e.info && this._setTargetElementTitle(e.info), + s.publish(ks, { + item: e + }), + s.publish(As, { + currentTarget: this._targetElement, + duration: this.currentPlaybackDuration, + target: this._targetElement, + type: "durationchange" + })) + } + get playbackRate() { + return this._targetElement.playbackRate + } + set playbackRate(e) { + this._targetElement.playbackRate = e + } + get playbackState() { + return this._playbackState + } + set playbackState(e) { + const s = this._playbackState; + if (e === s) + return; + const n = { + oldState: s, + state: e, + nowPlayingItem: this.nowPlayingItem ? { + id: this.nowPlayingItem.id, + type: this.nowPlayingItem.type + } : void 0 + }; + O.debug("BasePlayer.playbackState is changing", n), + this._dispatcher.publish(Cs, n), + this._playbackState = e, + this._dispatcher.publish(Rs, n) + } + get playbackTargetAvailable() { + return void 0 !== window.WebKitPlaybackTargetAvailabilityEvent && this._playbackTargetAvailable + } + set playbackTargetAvailable(e) { + e !== this._playbackTargetAvailable && (this._playbackTargetAvailable = e, + this._dispatcher.publish(Ms, { + available: e + })) + } + get playbackTargetIsWireless() { + return void 0 !== window.WebKitPlaybackTargetAvailabilityEvent && this._playbackTargetIsWireless + } + set playbackTargetIsWireless(e) { + e !== this._playbackTargetIsWireless && (this._playbackTargetIsWireless = e, + this._dispatcher.publish(Ds, { + playing: e + })) + } + get volume() { + return this._targetElement.volume + } + set volume(e) { + this._targetElement.volume = e + } + get isDestroyed() { + return this._isDestroyed + } + clearNextManifest() { + var e; + null === (e = this._buffer) || void 0 === e || e.clearNextManifest() + } + initialize() { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("BasePlayer.initialize"), + this.isPlayerSupported() ? (yield this.initializeMediaElement(), + yield this.initializeExtension(), + this.initializeEventHandlers(), + this._dispatcher.publish(Ts, this._targetElement)) : O.warn("{this.constructor.name} not supported") + } + )) + } + initializeEventHandlers() { + if (this.windowHandlers.activate(), + !this.hasMediaElement) + return; + const e = this._targetElement; + window.WebKitPlaybackTargetAvailabilityEvent && (e.addEventListener("webkitplaybacktargetavailabilitychanged", e=>{ + this.playbackTargetAvailable = "available" === e.availability + } + ), + e.addEventListener("webkitcurrentplaybacktargetiswirelesschanged", e=>{ + this.playbackTargetIsWireless = e.target === this._targetElement && !this.playbackTargetIsWireless + } + )), + xs.forEach(s=>e.addEventListener(s, this)), + this.dispatch(et.playerActivate, { + isPlaying: this.isPlaying + }) + } + removeEventHandlers() { + xs.forEach(e=>this._targetElement.removeEventListener(e, this)), + this.windowHandlers.deactivate() + } + isPaused() { + return this._paused + } + exitFullscreen() { + return this.fullscreen.exit() + } + requestFullscreen(e) { + return this.fullscreen.request(e) + } + seekToTime(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const s = this._buffer; + if (s) { + O.debug("Doing buffer seek to", e); + if (!(yield s.seek(e))) + return + } else + O.debug("Doing media element seek to", e), + this._targetElement.currentTime = e + } + )) + } + newSeeker() { + var e; + return null === (e = this._seeker) || void 0 === e || e.end(), + this._seeker = new PlayerSeeker(this), + this._seeker + } + stop(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("BasePlayer.stop", e), + yield this._waitForPendingPlay(), + this.isPlaying && this.dispatch(et.playbackStop, Object.assign({ + position: this.currentPlaybackTime, + startPosition: this._initialBufferPosition || 0 + }, e)), + yield this.stopMediaAndCleanup() + } + )) + } + stopMediaAndCleanup(e=Fs) { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("stopMediaAndCleanup"), + yield this._stopMediaElement(), + this._stopped = !0, + this._paused = !1, + this.nowPlayingItem = void 0, + this._initialBufferPosition = void 0, + this.playbackState = e + } + )) + } + _calculatePlaybackProgress() { + this.currentPlaybackProgress = Math.round(100 * (this.currentPlaybackTime / this.currentPlaybackDuration || 0)) / 100 + } + destroy() { + var e, s; + if (O.debug("BasePlayer.destroy"), + this._isDestroyed = !0, + !this.hasMediaElement) + return; + const n = this._targetElement; + null === (e = this.extension) || void 0 === e || e.destroy(n), + this.removeEventHandlers(), + this.cleanupElement(), + null === (s = n.parentNode) || void 0 === s || s.removeChild(n) + } + handleEvent(s) { + return __awaiter$3(this, void 0, void 0, (function*() { + switch ("timeupdate" !== s.type && O.debug("BasePlayer.handleEvent: ", s.type, s, this.isPaused(), this._stopped), + s.type) { + case "canplay": + this._dispatcher.publish(bs, s), + this.handleSmartPlay(), + this._playbackState !== e.PlaybackStates.waiting || this._targetElement.paused || (this.playbackState = e.PlaybackStates.playing); + break; + case "durationchange": + this._targetElement.duration !== 1 / 0 && (s.duration = this.currentPlaybackDuration, + this._dispatcher.publish(As, s), + this._calculatePlaybackProgress()); + break; + case "ended": + { + if (O.debug('media element "ended" event'), + this.isElementCleaned()) { + O.debug('media element already cleaned, ignoring "ended" event'); + break + } + const s = this._targetElement.currentTime; + yield this.stopMediaAndCleanup(Us), + this.dispatch(et.playbackStop, { + position: s, + endReasonType: e.PlayActivityEndReasonType.NATURAL_END_OF_TRACK + }); + break + } + case "error": + O.error("Playback Error", s), + this._dispatcher.publish(Es, new MKError(MKError.MEDIA_PLAYBACK,"Playback Error")); + break; + case "loadedmetadata": + this._dispatcher.publish(Ps, s); + break; + case "loadstart": + this.playbackState = $s; + break; + case "pause": + this.playbackState = this._stopped ? Fs : js; + break; + case "play": + case "playing": + this._paused = !1, + this._stopped = !1, + this.isPrimaryPlayer = !0, + this.playbackState = Bs; + break; + case "progress": + { + const e = this._targetElement.buffered; + this.handleBufferStart(), + 1 === e.length && 0 === e.start(0) && (this.currentBufferedProgress = Math.round(e.end(0) / this.currentPlaybackDuration * 100)); + break + } + case "ratechange": + this._dispatcher.publish(Os, s); + break; + case "seeked": + this._stopped ? this.playbackState = Fs : this._paused ? this.playbackState = js : this.playbackState !== Us && (this.playbackState = Bs); + break; + case "seeking": + this.playbackState === js ? this._paused = !0 : this.playbackState === Fs && (this._stopped = !0), + this.playbackState !== Us && (this.playbackState = Ks); + break; + case "timeupdate": + { + this._dispatcher.publish(Ns, { + currentPlaybackDuration: this.currentPlaybackDuration, + currentPlaybackTime: this.currentPlaybackTime, + currentPlaybackTimeRemaining: this.currentPlaybackTimeRemaining + }), + this._calculatePlaybackProgress(); + const e = this._buffer; + e && (e.currentTime = this.currentPlaybackTime); + break + } + case "volumechange": + this._dispatcher.publish(Ls, s); + break; + case "waiting": + this.playbackState = Vs + } + } + )) + } + handleBufferStart() { + const {_targetElement: e} = this; + void 0 !== this._initialBufferPosition || e.paused || 0 === e.buffered.length || (this._initialBufferPosition = e.buffered.start(0), + O.debug("BasePlayer.handleBufferStart: setting initial buffer position ", this._initialBufferPosition)) + } + handleSmartPlay() { + if (!this._targetElement || !this.nowPlayingItem) + return; + const e = this.nowPlayingItem; + e && e.playEvent && !e.playEvent.isDone && !this._hasSmartPlayed && (O.debug("BasePlayer.handleSmartPlay is resuming playCursor"), + this._targetElement.currentTime = e.playEvent.playCursorInSeconds), + this._hasSmartPlayed = !0 + } + pause(e={}) { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this._waitForPendingPlay(), + this.isPlaying && (yield this._pauseMedia(), + this._paused = !0, + this.dispatch(et.playbackPause, Object.assign({ + position: this.currentPlaybackTime + }, e))) + } + )) + } + play(e=!0) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (O.debug("BasePlayer.play()"), + this.nowPlayingItem) + try { + const afterPlay = ()=>{ + O.debug("BasePlayer.play dispatching playbackPlay"), + this.dispatch(et.playbackPlay, { + userInitiated: e, + position: this.currentPlaybackTime + }) + } + ; + yield this._playMedia(afterPlay) + } catch (bt) { + return void ("NotAllowedError" !== bt.name && "NotSupportedError" !== bt.name || O.error("BasePlayer.play() rejected due to", bt)) + } + } + )) + } + preload() { + return this._loadMedia() + } + showPlaybackTargetPicker() { + this.playbackTargetAvailable && this._targetElement.webkitShowPlaybackTargetPicker() + } + dispatch(e, s={}) { + void 0 === s.item && (s.item = this.nowPlayingItem), + void 0 === s.position && (s.position = this.currentPlaybackTime), + s.isPlaying = this.isPlaying, + this._dispatcher.publish(e, s) + } + tsidChanged(e) { + void 0 !== e && "" !== e && (this.isPrimaryPlayer = e === this._serial) + } + _waitForPendingPlay() { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this._playPromise) + try { + yield this._playPromise + } catch (bt) { + O.error("BasePlayer._waitForPendingPlay playPromise rejected", bt) + } finally { + this._playPromise = void 0 + } + } + )) + } + _loadMedia() { + return O.debug("BasePlayer._loadMedia", this._targetElement), + this._targetElement.load(), + Promise.resolve() + } + _pauseMedia() { + return this._targetElement.pause(), + Promise.resolve() + } + _playAssetURL(e, s) { + O.debug("BasePlayer._playAssetURL", e), + this._targetElement.src = e; + const n = this._loadMedia(); + return s ? (O.debug("BasePlayer.loadOnly"), + n) : this._playMedia() + } + playItemFromUnencryptedSource(e, s, n) { + return (null == n ? void 0 : n.startTime) && (e += "#t=" + n.startTime), + this._playAssetURL(e, s) + } + _playMedia(e=n) { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("BasePlayer._playMedia", this._targetElement, this.extension); + const s = this._targetElement.play().then(e=>(this._playbackDidStart = !0, + e)); + this._playPromise = s.then(e), + yield s + } + )) + } + _setTargetElementTitle(e) { + this.hasMediaElement && (this._targetElement.title = e) + } + _licenseError() { + this._playPromise = void 0 + } + _stopMediaElement() { + return __awaiter$3(this, void 0, void 0, (function*() { + this.hasMediaElement && (this._targetElement.pause(), + this.cleanupElement()) + } + )) + } + cleanupElement() { + const e = this._targetElement; + e && !this.isElementCleaned() && (e.currentTime = 0, + e.removeAttribute("src"), + e.removeAttribute("title")) + } + isElementCleaned() { + const e = this._targetElement; + return !e || 0 === e.currentTime && "" === e.src && "" === e.title + } + } + __decorate$2([AsyncDebounce(250), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Number]), __metadata$2("design:returntype", Promise)], BasePlayer.prototype, "seekToTime", null); + const Hs = { + app: {}, + features: {}, + urls: {} + }; + var zs, qs, Ws; + function restoreSelectedTrack(e, s) { + O.debug("MEDIA_TRACKS restoreSelectedTrack"); + const n = e.getPersistedTrack() + , d = e.fields + , h = s.currentTrack; + if (!n) + return void O.debug("MEDIA_TRACKS no persisted track"); + if (h && trackEquals(h, n, d)) + return void O.debug("MEDIA_TRACKS persisted track is equal to current track, not setting"); + const p = s.tracks; + if (p && p.length) + for (let y = 0; y < p.length; y++) { + const e = p[y]; + if (O.debug(`MEDIA_TRACKS testing track ${e.label} against persisted track ${JSON.stringify(n)}`), + trackEquals(e, n, d)) { + O.debug("MEDIA_TRACKS found matching track " + e.label), + s.currentTrack = e; + break + } + } + } + function trackEquals(e, s, n) { + let d = !0; + for (let h = 0; h < n.length; h++) { + const p = n[h]; + if (e[p] !== s[p]) { + d = !1; + break + } + } + return d + } + !function(e) { + e.playbackLicenseError = "playbackLicenseError", + e.playbackSessionError = "playbackSessionError", + e.manifestParsed = "manifestParsed", + e.audioCodecIdentified = "audioCodecIdentified", + e.audioTracksSwitched = "audioTracksSwitched", + e.audioTracksUpdated = "audioTracksUpdated", + e.textTracksSwitched = "textTracksSwitched", + e.textTracksUpdated = "textTracksUpdated", + e.levelUpdated = "levelUpdated" + }(zs || (zs = {})), + function(e) { + e.MP4 = "audio/mp4", + e.AVC1 = "video/mp4" + }(qs || (qs = {})), + function(e) { + e.WIDEVINE = "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed", + e.PLAYREADY = "com.microsoft.playready", + e.FAIRPLAY = "com.apple.streamingkeydelivery" + }(Ws || (Ws = {})); + class TrackPersistence { + constructor(e, s) { + this.storageKey = e, + this.fields = s + } + getPersistedTrack() { + if (!window || !window.localStorage) + return !1; + const e = window.localStorage.getItem(this.storageKey) || ""; + try { + return JSON.parse(e) + } catch (bt) { + return O.warn("MEDIA_TRACK could not parse persisted value " + e), + !1 + } + } + setPersistedTrack(e) { + if (!window || !window.localStorage) + return; + if (O.debug(`MEDIA_TRACK setPersistedTrack ${e.language},${e.label},${e.kind} with keys ${this.fields}`), + !e) + return void window.localStorage.setItem(this.storageKey, ""); + const s = JSON.stringify(this.extractFieldValuesFromTrack(e)); + O.debug("MEDIA_TRACK Extracted values " + s), + window.localStorage.setItem(this.storageKey, s) + } + extractFieldValuesFromTrack(e) { + const s = {}; + return this.fields.forEach(n=>{ + const d = e[n]; + null == d && O.warn(`MEDIA_TRACK No value for field ${n} on track ${JSON.stringify(e)}`), + s[n] = d + } + ), + s + } + } + const {audioTrackAdded: Ys, audioTrackChanged: Gs, audioTrackRemoved: Qs} = rs + , {audioTracksSwitched: Js, audioTracksUpdated: Xs} = zs; + class AudioTrackManager { + constructor(e, s, n) { + if (this.mediaElement = e, + this.dispatcher = s, + this.extensionTracks = n, + this._extensionTracks = [], + this.trackPersistence = new TrackPersistence("mk-audio-track",["label", "language", "kind"]), + this.extensionTracks) { + O.debug("MEDIA_TRACK Initializing audio track manager for hls track events"), + this.onExtensionAudioTracksUpdated = this.onExtensionAudioTracksUpdated.bind(this), + this.onExtensionAudioTrackSwitched = this.onExtensionAudioTrackSwitched.bind(this); + const e = this.extensionTracks; + e.addEventListener(Xs, this.onExtensionAudioTracksUpdated), + e.addEventListener(Js, this.onExtensionAudioTrackSwitched) + } else { + if (!e.audioTracks) + return; + O.debug("MEDIA_TRACK Initializing audio track manager for native track events"), + this.onAudioTrackAdded = this.onAudioTrackAdded.bind(this), + this.onAudioTrackChanged = this.onAudioTrackChanged.bind(this), + this.onAudioTrackRemoved = this.onAudioTrackRemoved.bind(this), + e.audioTracks.addEventListener("addtrack", this.onAudioTrackAdded), + e.audioTracks.addEventListener("change", this.onAudioTrackChanged), + e.audioTracks.addEventListener("removetrack", this.onAudioTrackRemoved) + } + } + get currentTrack() { + return this.tracks.find(e=>e.enabled) + } + set currentTrack(e) { + e && (O.debug("MEDIA_TRACK Setting audio track " + e.label), + this.extensionTracks ? (O.debug(`MEDIA_TRACK Setting track on extension ${e.id}-${e.label}`), + this.extensionTracks.audioTrack = e) : (O.debug("MEDIA_TRACK disabling all audio tracks"), + Array.from(this.mediaElement.audioTracks).forEach(s=>{ + s !== e && (s.enabled = !1) + } + ), + O.debug("MEDIA_TRACK enabling", e), + e.enabled = !0), + this.trackPersistence.setPersistedTrack(e)) + } + get tracks() { + return this.extensionTracks ? this._extensionTracks || this.extensionTracks.audioTracks || [] : Array.from(this.mediaElement.audioTracks) + } + destroy() { + if (this.extensionTracks) { + const e = this.extensionTracks; + e.removeEventListener(Xs, this.onExtensionAudioTracksUpdated), + e.removeEventListener(Js, this.onExtensionAudioTrackSwitched) + } else { + if (!this.mediaElement.audioTracks) + return; + this.mediaElement.audioTracks.removeEventListener("addtrack", this.onAudioTrackAdded), + this.mediaElement.audioTracks.removeEventListener("change", this.onAudioTrackChanged), + this.mediaElement.audioTracks.removeEventListener("removetrack", this.onAudioTrackRemoved) + } + } + restoreSelectedTrack() { + return restoreSelectedTrack(this.trackPersistence, this) + } + onExtensionAudioTracksUpdated(e) { + O.debug("MEDIA_TRACK Extension audio tracks updated " + JSON.stringify(e)), + this._extensionTracks = e, + this.restoreSelectedTrack(), + this.dispatcher.publish(Ys, e) + } + onExtensionAudioTrackSwitched(e) { + if (O.debug("MEDIA_TRACK Extension audio track switched " + JSON.stringify(e)), + this._extensionTracks) { + const preserveSelectedTrack = s=>{ + s.enabled = e.selectedId === s.id + } + ; + this._extensionTracks.forEach(preserveSelectedTrack) + } + this.dispatcher.publish(Gs, e) + } + onAudioTrackAdded(e) { + !function(e, s, n) { + const d = s.getPersistedTrack(); + d && trackEquals(e, d, s.fields) && (O.debug("MEDIA_TRACK onTrackAdded with track that matches persisted track " + e.label), + n.currentTrack = e) + }(e.track, this.trackPersistence, this), + this.dispatcher.publish(Ys, e) + } + onAudioTrackChanged(e) { + this.dispatcher.publish(Gs, e) + } + onAudioTrackRemoved(e) { + this.dispatcher.publish(Qs, e) + } + } + const Zs = document.createElement("video") + , er = [] + , tr = []; + function deferPlayback() { + fillAvailableElements("audio", tr), + fillAvailableElements("video", er), + O.debug(`dom-helpers: defer playback called. There are ${er.length} available video elements and ${tr.length} available audio elements.`) + } + function fillAvailableElements(e, s) { + let n = 100 - s.length; + for (; n > 0; ) { + const d = document.createElement(e); + d.load(), + s.push(d), + n-- + } + } + var ir = createCommonjsModule((function(e, s) { + Object.defineProperty(s, "__esModule", { + value: !0 + }), + s.isValidPercentValue = function(e) { + return "number" == typeof e && e >= 0 && e <= 100 + } + , + s.isValidAlignSetting = function(e) { + return "string" == typeof e && ["start", "center", "end", "left", "right", "middle"].includes(e) + } + , + s.isValidDirectionSetting = function(e) { + return "string" == typeof e && ["", "rl", "lr"].includes(e) + } + , + s.isValidLineAndPositionSetting = function(e) { + return "number" == typeof e || "auto" === e + } + , + s.isValidLineAlignSetting = function(e) { + return "string" == typeof e && ["start", "center", "end"].includes(e) + } + , + s.isValidPositionAlignSetting = function(e) { + return "string" == typeof e && ["line-left", "center", "line-right", "auto", "left", "start", "middle", "end", "right"].includes(e) + } + , + s.isValidScrollSetting = function(e) { + return ["", "up"].includes(e) + } + } + )); + unwrapExports(ir), + ir.isValidPercentValue, + ir.isValidAlignSetting, + ir.isValidDirectionSetting, + ir.isValidLineAndPositionSetting, + ir.isValidLineAlignSetting, + ir.isValidPositionAlignSetting, + ir.isValidScrollSetting; + var sr = createCommonjsModule((function(e, s) { + Object.defineProperty(s, "__esModule", { + value: !0 + }); + const n = { + "&": "&", + "<": "<", + ">": ">", + "‎": "‎", + "‏": "‏", + " ": " " + } + , d = { + c: "span", + i: "i", + b: "b", + u: "u", + ruby: "ruby", + rt: "rt", + v: "span", + lang: "span" + } + , h = { + v: "title", + lang: "lang" + } + , p = { + rt: "ruby" + } + , y = { + "text-combine-upright": "-webkit-text-combine:horizontal; text-orientation: mixed;" + }; + class ParserUtility { + static parseTimeStamp(e) { + function computeSeconds(e) { + const [s,n,d,h] = e.map(e=>e ? parseInt("" + e) : 0); + return 3600 * s + 60 * n + d + h / 1e3 + } + const s = /^(\d+):(\d{2})(:\d{2})?\.(\d{3})/.exec(e); + return s ? s[3] ? computeSeconds([s[1], s[2], s[3].substring(1), s[4]]) : parseInt(s[1]) > 59 ? computeSeconds([s[1], s[2], null, s[4]]) : computeSeconds([null, s[1], s[2], s[4]]) : null + } + static parseContent(e, s, m) { + let g = s.text; + function nextToken() { + if (!g) + return null; + const e = /^([^<]*)(<[^>]+>?)?/.exec(g); + return s = e[1] ? e[1] : e[2], + g = g.substr(s.length), + s; + var s + } + function unescape1(e) { + return n[e] + } + function unescape(e) { + return e.replace(/&(amp|lt|gt|lrm|rlm|nbsp);/g, unescape1) + } + function shouldAdd(e, s) { + return !p[s.dataset.localName] || p[s.dataset.localName] === e.dataset.localName + } + function createElement(s, n, p) { + const g = d[s]; + if (!g) + return null; + const v = e.document.createElement(g); + v.dataset.localName = g; + const _ = h[s]; + if (_ && p && (v[_] = p.trim()), + n) + if (m[n]) { + const e = function(e) { + let s = ""; + for (const n in e) + s += y[n] ? y[n] : n + ":" + e[n] + ";"; + return s + }(m[n]); + v.setAttribute("style", e) + } else + console.info(`WebVTT: parseContent: Style referenced, but no style defined for '${n}'!`); + return v + } + const v = e.document.createElement("div") + , _ = []; + let b, T, E = v; + for (; null !== (b = nextToken()); ) + if ("<" !== b[0]) + E.appendChild(e.document.createTextNode(unescape(b))); + else { + if ("/" === b[1]) { + _.length && _[_.length - 1] === b.substr(2).replace(">", "") && (_.pop(), + E = E.parentNode); + continue + } + const s = ParserUtility.parseTimeStamp(b.substr(1, b.length - 2)); + let n; + if (s) { + n = e.document.createProcessingInstruction("timestamp", s.toString()), + E.appendChild(n); + continue + } + if (T = /^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/.exec(b), + !T) + continue; + if (n = createElement(T[1], T[2], T[3]), + !n) + continue; + if (!shouldAdd(E, n)) + continue; + T[2], + _.push(T[1]), + E.appendChild(n), + E = n + } + return v + } + } + s.default = ParserUtility + } + )); + unwrapExports(sr); + var rr = createCommonjsModule((function(e, s) { + var n = Y && Y.__decorate || function(e, s, n, d) { + var h, p = arguments.length, y = p < 3 ? s : null === d ? d = Object.getOwnPropertyDescriptor(s, n) : d; + if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) + y = Reflect.decorate(e, s, n, d); + else + for (var m = e.length - 1; m >= 0; m--) + (h = e[m]) && (y = (p < 3 ? h(y) : p > 3 ? h(s, n, y) : h(s, n)) || y); + return p > 3 && y && Object.defineProperty(s, n, y), + y + } + ; + Object.defineProperty(s, "__esModule", { + value: !0 + }); + let d = class { + constructor(e, s, n) { + this._id = "", + this._pauseOnExit = !1, + this._region = null, + this._vertical = "", + this._snapToLines = !0, + this._line = "auto", + this._lineAlign = "start", + this._position = "auto", + this._positionAlign = "auto", + this._size = 100, + this._align = "center", + this.hasBeenReset = !1, + this._startTime = e, + this._endTime = s, + this._text = n + } + get id() { + return this._id + } + set id(e) { + this._id = "" + e + } + get pauseOnExit() { + return this._pauseOnExit + } + set pauseOnExit(e) { + this._pauseOnExit = !!e + } + get startTime() { + return this._startTime + } + set startTime(e) { + if ("number" != typeof e) + throw new TypeError("Start time must be set to a number: " + e); + this._startTime = e, + this.hasBeenReset = !0 + } + get endTime() { + return this._endTime + } + set endTime(e) { + if ("number" != typeof e) + throw new TypeError("End time must be set to a number: " + e); + this._endTime = e, + this.hasBeenReset = !0 + } + get text() { + return this._text + } + set text(e) { + this._text = "" + e, + this.hasBeenReset = !0 + } + get region() { + return this._region + } + set region(e) { + this._region = e, + this.hasBeenReset = !0 + } + get vertical() { + return this._vertical + } + set vertical(e) { + if (!ir.isValidDirectionSetting(e)) + throw new SyntaxError("An invalid or illegal string was specified for vertical: " + e); + this._vertical = e, + this.hasBeenReset = !0 + } + get snapToLines() { + return this._snapToLines + } + set snapToLines(e) { + this._snapToLines = !!e, + this.hasBeenReset = !0 + } + get line() { + return this._line + } + set line(e) { + if (!ir.isValidLineAndPositionSetting(e)) + throw new SyntaxError("An invalid number or illegal string was specified for line: " + e); + this._line = e, + this.hasBeenReset = !0 + } + get lineAlign() { + return this._lineAlign + } + set lineAlign(e) { + if (!ir.isValidLineAlignSetting(e)) + throw new SyntaxError("An invalid or illegal string was specified for lineAlign: " + e); + this._lineAlign = e, + this.hasBeenReset = !0 + } + get position() { + return this._position + } + set position(e) { + if (!ir.isValidLineAndPositionSetting(e)) + throw new Error("Position must be between 0 and 100 or auto: " + e); + this._position = e, + this.hasBeenReset = !0 + } + get positionAlign() { + return this._positionAlign + } + set positionAlign(e) { + if (!ir.isValidPositionAlignSetting(e)) + throw new SyntaxError("An invalid or illegal string was specified for positionAlign: " + e); + this._positionAlign = e, + this.hasBeenReset = !0 + } + get size() { + return this._size + } + set size(e) { + if (e < 0 || e > 100) + throw new Error("Size must be between 0 and 100: " + e); + this._size = e, + this.hasBeenReset = !0 + } + get align() { + return this._align + } + set align(e) { + if (!ir.isValidAlignSetting(e)) + throw new SyntaxError("An invalid or illegal string was specified for align: " + e); + this._align = e, + this.hasBeenReset = !0 + } + getCueAsHTML() { + return sr.default.parseContent(window, this, {}) + } + static create(e) { + if (!e.hasOwnProperty("startTime") || !e.hasOwnProperty("endTime") || !e.hasOwnProperty("text")) + throw new Error("You must at least have start time, end time, and text."); + const s = new this(e.startTime,e.endTime,e.text); + return Object.keys(e).forEach(n=>{ + s.hasOwnProperty(n) && (s[n] = e[n]) + } + ), + s + } + static fromJSON(e) { + return this.create(JSON.parse(e)) + } + toJSON() { + const e = {}; + return Object.keys(this).forEach(s=>{ + this.hasOwnProperty(s) && "getCueAsHTML" !== s && "hasBeenReset" !== s && "displayState" !== s && (e[s] = this[s]) + } + ), + e + } + } + ; + d = n([function(e) { + let s = e; + "undefined" != typeof window && null != window.VTTCue && (s = window.VTTCue, + s.create = e.create, + s.fromJSON = e.fromJSON, + s.prototype.toJSON = e.prototype.toJSON); + return s + } + ], d), + s.VTTCue = d + } + )); + unwrapExports(rr), + rr.VTTCue; + var nr = createCommonjsModule((function(e, s) { + var n = Y && Y.__decorate || function(e, s, n, d) { + var h, p = arguments.length, y = p < 3 ? s : null === d ? d = Object.getOwnPropertyDescriptor(s, n) : d; + if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) + y = Reflect.decorate(e, s, n, d); + else + for (var m = e.length - 1; m >= 0; m--) + (h = e[m]) && (y = (p < 3 ? h(y) : p > 3 ? h(s, n, y) : h(s, n)) || y); + return p > 3 && y && Object.defineProperty(s, n, y), + y + } + ; + Object.defineProperty(s, "__esModule", { + value: !0 + }); + let d = class { + constructor() { + this._id = "", + this._lines = 3, + this._regionAnchorX = 0, + this._regionAnchorY = 100, + this._scroll = "", + this._viewportAnchorX = 0, + this._viewportAnchorY = 100, + this._width = 100 + } + get id() { + return this._id + } + set id(e) { + if ("string" != typeof e) + throw new Error("ID must be a string."); + this._id = e + } + get lines() { + return this._lines + } + set lines(e) { + if ("number" != typeof e) + throw new TypeError("Lines must be set to a number."); + this._lines = e + } + get regionAnchorX() { + return this._regionAnchorX + } + set regionAnchorX(e) { + if (!ir.isValidPercentValue(e)) + throw new TypeError("RegionAnchorX must be between 0 and 100."); + this._regionAnchorX = e + } + get regionAnchorY() { + return this._regionAnchorY + } + set regionAnchorY(e) { + if (!ir.isValidPercentValue(e)) + throw new TypeError("RegionAnchorY must be between 0 and 100."); + this._regionAnchorY = e + } + get scroll() { + return this._scroll + } + set scroll(e) { + if ("string" == typeof e) { + const s = e.toLowerCase(); + if (ir.isValidScrollSetting(s)) + return void (this._scroll = s) + } + throw new SyntaxError("An invalid or illegal string was specified.") + } + get viewportAnchorX() { + return this._viewportAnchorX + } + set viewportAnchorX(e) { + if (!ir.isValidPercentValue(e)) + throw new TypeError("ViewportAnchorX must be between 0 and 100."); + this._viewportAnchorX = e + } + get viewportAnchorY() { + return this._viewportAnchorY + } + set viewportAnchorY(e) { + if (!ir.isValidPercentValue(e)) + throw new TypeError("ViewportAnchorY must be between 0 and 100."); + this._viewportAnchorY = e + } + get width() { + return this._width + } + set width(e) { + if (!ir.isValidPercentValue(e)) + throw new TypeError("Width must be between 0 and 100."); + this._lines = e + } + toJSON() { + const e = {}; + return Object.keys(this).forEach(s=>{ + this.hasOwnProperty(s) && (e[s] = this[s]) + } + ), + e + } + static create(e) { + const s = new this; + return Object.keys(e).forEach(n=>{ + s.hasOwnProperty(n) && (s[n] = e[n]) + } + ), + s + } + static fromJSON(e) { + return this.create(JSON.parse(e)) + } + } + ; + d = n([function(e) { + let s = e; + "undefined" != typeof window && null != window.VTTRegion && (s = window.VTTRegion, + s.create = e.create, + s.fromJSON = e.fromJSON, + s.prototype.toJSON = e.prototype.toJSON); + return s + } + ], d), + s.VTTRegion = d + } + )); + unwrapExports(nr), + nr.VTTRegion; + var ar = createCommonjsModule((function(e, s) { + Object.defineProperty(s, "__esModule", { + value: !0 + }), + s.VTTCue = rr.VTTCue, + s.VTTRegion = nr.VTTRegion; + class ParsingError extends Error { + constructor(e, s) { + super(), + this.name = "ParsingError", + this.code = "number" == typeof e ? e : e.code, + s ? this.message = s : e instanceof ParsingError && (this.message = e.message) + } + } + s.ParsingError = ParsingError, + ParsingError.Errors = { + BadSignature: new ParsingError(0,"Malformed WebVTT signature."), + BadTimeStamp: new ParsingError(1,"Malformed time stamp.") + }; + class Settings { + constructor() { + this.values = {} + } + set(e, s) { + this.get(e) || "" === s || (this.values[e] = s) + } + get(e, s, n) { + return "object" == typeof s && "string" == typeof n ? this.has(e) ? this.values[e] : s[n] : this.has(e) ? this.values[e] : s + } + has(e) { + return e in this.values + } + alt(e, s, n) { + for (let d = 0; d < n.length; ++d) + if (s === n[d]) { + this.set(e, s); + break + } + } + integer(e, s) { + /^-?\d+$/.test(s) && this.set(e, parseInt(s, 10)) + } + percent(e, s) { + if (s.match(/^([\d]{1,3})(\.[\d]*)?%$/)) + try { + const n = parseFloat(s); + if (n >= 0 && n <= 100) + return this.set(e, n), + !0 + } catch (Ra) { + return !1 + } + return !1 + } + } + class WebVTTParser { + constructor(e, s, n) { + this.window = e, + this.state = "INITIAL", + this.styleCollector = "", + this.buffer = "", + this.decoder = s || new TextDecoder("utf8"), + this.regionList = [], + this.onStylesParsedCallback = n, + this._styles = {} + } + static StringDecoder() { + return { + decode: e=>{ + if (!e) + return ""; + if ("string" != typeof e) + throw new Error("Error - expected string data."); + return decodeURIComponent(encodeURIComponent(e)) + } + } + } + reportOrThrowError(e) { + if (!(e instanceof ParsingError && "function" == typeof this.onparsingerror)) + throw e; + this.onparsingerror(e) + } + parseOptions(e, s, n, d) { + const h = d ? e.split(d) : [e]; + for (const p of h) { + if ("string" != typeof p) + continue; + const e = p.split(n); + if (2 !== e.length) + continue; + s(e[0], e[1]) + } + } + parseCue(e, s, n) { + const d = e + , consumeTimeStamp = ()=>{ + const s = sr.default.parseTimeStamp(e); + if (null === s) + throw new ParsingError(ParsingError.Errors.BadTimeStamp,"Malformed timestamp: " + d); + return e = e.replace(/^[^\sa-zA-Z-]+/, ""), + s + } + , skipWhitespace = ()=>{ + e = e.replace(/^\s+/, "") + } + ; + if (skipWhitespace(), + s.startTime = consumeTimeStamp(), + skipWhitespace(), + "--\x3e" !== e.substr(0, 3)) + throw new ParsingError(ParsingError.Errors.BadTimeStamp,"Malformed time stamp (time stamps must be separated by '--\x3e'): " + d); + e = e.substr(3), + skipWhitespace(), + s.endTime = consumeTimeStamp(), + skipWhitespace(), + ((e,s)=>{ + const d = new Settings; + this.parseOptions(e, (e,s)=>{ + let h, p; + switch (e) { + case "region": + for (let h = n.length - 1; h >= 0; h--) + if (n[h].id === s) { + d.set(e, n[h].region); + break + } + break; + case "vertical": + d.alt(e, s, ["rl", "lr"]); + break; + case "line": + h = s.split(","), + p = h[0], + d.integer(e, p), + d.percent(e, p) && d.set("snapToLines", !1), + d.alt(e, p, ["auto"]), + 2 === h.length && d.alt("lineAlign", h[1], ["start", "center", "end"]); + break; + case "position": + if (h = s.split(","), + d.percent(e, h[0]), + 2 === h.length) { + let e = ["line-left", "line-right", "center", "auto", "left", "start", "middle", "end", "right"]; + d.alt("positionAlign", h[1], e) + } + break; + case "size": + d.percent(e, s); + break; + case "align": + let y = ["start", "center", "end", "left", "right", "middle"]; + d.alt(e, s, y) + } + } + , /:/, /\s/), + s.region = d.get("region", null), + s.vertical = d.get("vertical", ""), + s.line = d.get("line", void 0 === s.line ? "auto" : s.line), + s.lineAlign = d.get("lineAlign", "start"), + s.snapToLines = d.get("snapToLines", !0), + s.size = d.get("size", 100); + let h = d.get("align", "center"); + s.align = "middle" === h ? "center" : h, + s.position = d.get("position", "auto"); + let p = d.get("positionAlign", { + start: "start", + left: "start", + center: "center", + right: "end", + end: "end" + }, s.align); + s.positionAlign = { + start: "start", + "line-left": "start", + left: "start", + center: "center", + middle: "center", + "line-right": "end", + right: "end", + end: "end" + }[p] + } + )(e, s) + } + parseRegion(e) { + const s = new Settings; + if (this.parseOptions(e, (e,n)=>{ + switch (e) { + case "id": + s.set(e, n); + break; + case "width": + s.percent(e, n); + break; + case "lines": + s.integer(e, n); + break; + case "regionanchor": + case "viewportanchor": + { + const d = n.split(","); + if (2 !== d.length) + break; + const h = new Settings; + if (h.percent("x", d[0]), + h.percent("y", d[1]), + !h.has("x") || !h.has("y")) + break; + s.set(e + "X", h.get("x")), + s.set(e + "Y", h.get("y")); + break + } + case "scroll": + s.alt(e, n, ["up"]) + } + } + , /=/, /\s/), + s.has("id")) { + const e = new nr.VTTRegion; + e.width = s.get("width", 100), + e.lines = s.get("lines", 3), + e.regionAnchorX = s.get("regionanchorX", 0), + e.regionAnchorY = s.get("regionanchorY", 100), + e.viewportAnchorX = s.get("viewportanchorX", 0), + e.viewportAnchorY = s.get("viewportanchorY", 100), + e.scroll = s.get("scroll", ""), + this.onregion && this.onregion(e), + this.regionList.push({ + id: s.get("id"), + region: e + }) + } + } + parseStyle(e) { + const parseStyles = e=>{ + const s = {} + , n = e.split(";"); + for (let d = 0; d < n.length; d++) + if (n[d].includes(":")) { + const e = n[d].split(":", 2) + , h = e[0].trim() + , p = e[1].trim(); + "" !== h && "" !== p && (s[h] = p) + } + return s + } + , s = e.split("}"); + s.pop(); + for (const n of s) { + let e = null + , s = null; + const d = n.split("{"); + d[0] && (e = d[0].trim()), + d[1] && (s = parseStyles(d[1])), + e && s && (this._styles[e] = s) + } + this.onStylesParsedCallback && this.onStylesParsedCallback(this._styles) + } + parseHeader(e) { + this.parseOptions(e, (function(e, s) { + switch (e) { + case "Region": + this.parseRegion(s) + } + } + ), /:/) + } + parse(e) { + e && (this.buffer += this.decoder.decode(e, { + stream: !0 + })); + const collectNextLine = ()=>{ + const e = this.buffer; + let s = 0; + const calculateBreakPosition = (e,s)=>{ + const n = { + start: -1, + length: -1 + }; + if ("\r" === e[s]) + n.start = s, + n.length = 1; + else if ("\n" === e[s]) + n.start = s, + n.length = 1; + else if ("<" === e[s] && s + 1 < e.length && "b" === e[s + 1] && s + 2 < e.length && "r" === e[s + 2]) { + let d = s + 2; + for (; d < e.length && ">" !== e[d++]; ) + ; + n.start = s, + n.length = d - s + } + return n + } + ; + let n = { + start: e.length, + length: 0 + }; + for (; s < e.length; ) { + const d = calculateBreakPosition(e, s); + if (d.length > 0) { + n = d; + break + } + ++s + } + const d = e.substr(0, n.start); + return this.buffer = e.substr(n.start + n.length), + d + } + ; + try { + let e; + if ("INITIAL" === this.state) { + if (!/\r\n|\n/.test(this.buffer)) + return this; + e = collectNextLine(); + const s = /^()?WEBVTT([ \t].*)?$/.exec(e); + if (!s || !s[0]) + throw new ParsingError(ParsingError.Errors.BadSignature); + this.state = "HEADER" + } + let s = !1; + for (; this.buffer; ) { + if (!/\r\n|\n/.test(this.buffer)) + return this; + switch (s ? s = !1 : e = collectNextLine(), + this.state) { + case "HEADER": + e.includes(":") ? this.parseHeader(e) : e || (this.state = "ID"); + continue; + case "NOTE": + e || (this.state = "ID"); + continue; + case "STYLE": + e ? this.styleCollector += e : (this.parseStyle(this.styleCollector), + this.state = "ID", + this.styleCollector = ""); + continue; + case "ID": + if (/^NOTE($|[ \t])/.test(e)) { + this.state = "NOTE"; + break + } + if (/^STYLE($|[ \t])/.test(e)) { + this.state = "STYLE"; + break + } + if (!e) + continue; + if (this.cue = new rr.VTTCue(0,0,""), + this.state = "CUE", + !e.includes("--\x3e")) { + this.cue.id = e; + continue + } + case "CUE": + try { + this.parseCue(e, this.cue, this.regionList) + } catch (bt) { + this.reportOrThrowError(bt), + this.cue = null, + this.state = "BADCUE"; + continue + } + this.state = "CUETEXT"; + continue; + case "CUETEXT": + { + const n = e.includes("--\x3e"); + if (!e || n) { + s = !0, + this.oncue && this.oncue(this.cue), + this.cue = null, + this.state = "ID"; + continue + } + this.cue.text && (this.cue.text += "\n"), + this.cue.text += e; + continue + } + case "BADCUE": + e || (this.state = "ID"); + continue + } + } + } catch (bt) { + this.reportOrThrowError(bt), + "CUETEXT" === this.state && this.cue && this.oncue && this.oncue(this.cue), + this.cue = null, + this.state = "INITIAL" === this.state ? "BADWEBVTT" : "BADCUE" + } + return this + } + flush() { + try { + if (this.buffer += this.decoder.decode(), + (this.cue || "HEADER" === this.state) && (this.buffer += "\n\n", + this.parse()), + "INITIAL" === this.state) + throw new ParsingError(ParsingError.Errors.BadSignature) + } catch (bt) { + this.reportOrThrowError(bt) + } + return this.onflush && this.onflush(), + this + } + styles() { + return this._styles + } + } + s.default = WebVTTParser, + s.WebVTTParser = WebVTTParser + } + )); + unwrapExports(ar), + ar.VTTCue, + ar.VTTRegion, + ar.ParsingError, + ar.WebVTTParser; + var or = createCommonjsModule((function(e, s) { + Object.defineProperty(s, "__esModule", { + value: !0 + }), + s.VTTCue = rr.VTTCue; + const n = [/^(::cue\()(\..*)(\))/, /^(::cue\()(#.*)(\))/, /^(::cue\()(c|i|b|u|ruby|rt|v|lang)(\))/] + , d = [[1470, 1470], [1472, 1472], [1475, 1475], [1478, 1478], [1488, 1514], [1520, 1524], [1544, 1544], [1547, 1547], [1549, 1549], [1563, 1563], [1566, 1610], [1645, 1647], [1649, 1749], [1765, 1766], [1774, 1775], [1786, 1805], [1807, 1808], [1810, 1839], [1869, 1957], [1969, 1969], [1984, 2026], [2036, 2037], [2042, 2042], [2048, 2069], [2074, 2074], [2084, 2084], [2088, 2088], [2096, 2110], [2112, 2136], [2142, 2142], [2208, 2208], [2210, 2220], [8207, 8207], [64285, 64285], [64287, 64296], [64298, 64310], [64312, 64316], [64318, 64318], [64320, 64321], [64323, 64324], [64326, 64449], [64467, 64829], [64848, 64911], [64914, 64967], [65008, 65020], [65136, 65140], [65142, 65276], [67584, 67589], [67592, 67592], [67594, 67637], [67639, 67640], [67644, 67644], [67647, 67669], [67671, 67679], [67840, 67867], [67872, 67897], [67903, 67903], [67968, 68023], [68030, 68031], [68096, 68096], [68112, 68115], [68117, 68119], [68121, 68147], [68160, 68167], [68176, 68184], [68192, 68223], [68352, 68405], [68416, 68437], [68440, 68466], [68472, 68479], [68608, 68680], [126464, 126467], [126469, 126495], [126497, 126498], [126500, 126500], [126503, 126503], [126505, 126514], [126516, 126519], [126521, 126521], [126523, 126523], [126530, 126530], [126535, 126535], [126537, 126537], [126539, 126539], [126541, 126543], [126545, 126546], [126548, 126548], [126551, 126551], [126553, 126553], [126555, 126555], [126557, 126557], [126559, 126559], [126561, 126562], [126564, 126564], [126567, 126570], [126572, 126578], [126580, 126583], [126585, 126588], [126590, 126590], [126592, 126601], [126603, 126619], [126625, 126627], [126629, 126633], [126635, 126651], [1114109, 1114109]]; + class StyleBox { + applyStyles(e, s) { + s = s || this.div; + for (const n in e) + e.hasOwnProperty(n) && (s.style[n] = e[n]) + } + formatStyle(e, s) { + return 0 === e ? "0" : e + s + } + } + s.StyleBox = StyleBox; + class CueStyleBox extends StyleBox { + constructor(e, s, n, d, h) { + super(), + this.cue = s; + let p = { + textAlign: { + start: "left", + "line-left": "left", + left: "left", + center: "center", + middle: "center", + "line-right": "right", + right: "right", + end: "right" + }[s.positionAlign] || s.align, + whiteSpace: "pre-line", + position: "absolute" + }; + p.direction = this.determineBidi(this.cueDiv), + p.writingMode = this.directionSettingToWritingMode(s.vertical), + p.unicodeBidi = "plaintext", + this.div = e.document.createElement("div"), + this.applyStyles(p), + p = { + backgroundColor: d.backgroundColor, + display: "inline-block" + }, + this.parseOpacity(p.backgroundColor) && (p.padding = "5px", + p.borderRadius = "5px"), + this.backgroundDiv = e.document.createElement("div"), + this.applyStyles(p, this.backgroundDiv), + p = { + color: n.color, + backgroundColor: n.backgroundColor, + textShadow: n.textShadow, + fontSize: n.fontSize, + fontFamily: n.fontFamily, + position: "relative", + left: "0", + right: "0", + top: "0", + bottom: "0", + display: "inline-block", + textOrientation: "upright" + }, + p.writingMode = this.directionSettingToWritingMode(s.vertical), + p.unicodeBidi = "plaintext", + this.cueDiv = sr.default.parseContent(e, s, h), + this.applyStyles(p, this.cueDiv), + this.backgroundDiv.appendChild(this.cueDiv), + this.div.appendChild(this.backgroundDiv); + let y = 0; + if ("number" == typeof s.position) { + let e = s.positionAlign || s.align; + if (e) + switch (e) { + case "start": + case "left": + y = s.position; + break; + case "center": + case "middle": + y = s.position - s.size / 2; + break; + case "end": + case "right": + y = s.position - s.size + } + } + "" === s.vertical ? this.applyStyles({ + left: this.formatStyle(y, "%"), + width: this.formatStyle(s.size, "%") + }) : this.applyStyles({ + top: this.formatStyle(y, "%"), + height: this.formatStyle(s.size, "%") + }) + } + determineBidi(e) { + let s, n = [], h = ""; + if (!e || !e.childNodes) + return "ltr"; + function pushNodes(e, s) { + for (let n = s.childNodes.length - 1; n >= 0; n--) + e.push(s.childNodes[n]) + } + function nextTextNode(e) { + if (!e || !e.length) + return null; + let s = e.pop() + , n = s.textContent || s.innerText; + if (n) { + const s = /^.*(\n|\r)/.exec(n); + return s ? (e.length = 0, + s[0]) : n + } + return "ruby" === s.tagName ? nextTextNode(e) : s.childNodes ? (pushNodes(e, s), + nextTextNode(e)) : void 0 + } + function isContainedInCharacterList(e, s) { + for (const n of s) + if (e >= n[0] && e <= n[1]) + return !0; + return !1 + } + for (pushNodes(n, e); h = nextTextNode(n); ) + for (let e = 0; e < h.length; e++) + if (s = h.charCodeAt(e), + isContainedInCharacterList(s, d)) + return "rtl"; + return "ltr" + } + parseOpacity(e) { + if (!e || "string" != typeof e) + return null; + const s = (e = e.replace(/ /g, "").replace("rgba(", "").replace(")", "")).split(","); + return s && s.length >= 4 ? s[3] : null + } + directionSettingToWritingMode(e) { + return "" === e ? "horizontal-tb" : "lr" === e ? "vertical-lr" : "vertical-rl" + } + move(e) { + this.applyStyles({ + top: this.formatStyle(e.top, "px"), + bottom: this.formatStyle(e.bottom, "px"), + left: this.formatStyle(e.left, "px"), + right: this.formatStyle(e.right, "px"), + height: this.formatStyle(e.height, "px"), + width: this.formatStyle(e.width, "px") + }) + } + } + s.CueStyleBox = CueStyleBox; + class BoxPosition { + constructor(e) { + var s; + let n, d, h, p, y, m; + if (e instanceof CueStyleBox && e.cue ? (s = e.cue) && "" !== s.vertical ? this.property = "width" : this.property = "height" : e instanceof BoxPosition && (this.property = e.property || "height"), + e instanceof CueStyleBox && e.div) { + h = e.div.offsetHeight, + p = e.div.offsetWidth, + y = e.div.offsetTop; + const s = e.div.firstChild; + if (m = s ? s.getBoundingClientRect() : e.div.getBoundingClientRect(), + n = m && m[this.property] || null, + s && s.firstChild) { + const e = s.firstChild; + if (e && "string" == typeof e.textContent) { + d = n / this.calculateNewLines(e.textContent) + } + } + } else + e instanceof BoxPosition && (m = e); + this.left = m.left, + this.right = m.right, + this.top = m.top || y, + this.height = m.height || h, + this.bottom = m.bottom || y + (m.height || h), + this.width = m.width || p, + this.lineHeight = null !== n ? n : m.lineHeight, + this.singleLineHeight = null !== d ? d : m.singleLineHeight, + this.singleLineHeight || (this.singleLineHeight = 41) + } + calculateNewLines(e) { + let s = 1; + for (let n = 0; n < e.length; n++) + "\n" === e[n] && s++; + return s + } + move(e, s) { + switch (s = void 0 !== s ? s : this.singleLineHeight, + e) { + case "+x": + this.left += s, + this.right += s; + break; + case "-x": + this.left -= s, + this.right -= s; + break; + case "+y": + this.top += s, + this.bottom += s; + break; + case "-y": + this.top -= s, + this.bottom -= s + } + } + overlaps(e) { + return this.left < e.right && this.right > e.left && this.top < e.bottom && this.bottom > e.top + } + overlapsAny(e) { + for (const s of e) + if (this.overlaps(s)) + return !0; + return !1 + } + within(e) { + return this.top >= e.top && this.bottom <= e.bottom && this.left >= e.left && this.right <= e.right + } + moveIfOutOfBounds(e, s) { + switch (s) { + case "+x": + this.left < e.left && (this.left = e.left, + this.right = this.left + this.width); + break; + case "-x": + this.right > e.right && (this.right = e.right, + this.left = this.right - this.width); + break; + case "+y": + this.top < e.top && (this.top = e.top, + this.bottom = this.top + this.height); + break; + case "-y": + this.bottom > e.bottom && (this.bottom = e.bottom, + this.top = this.bottom - this.height) + } + } + toCSSCompatValues(e) { + return { + top: this.top - e.top, + bottom: e.bottom - this.bottom, + left: this.left - e.left, + right: e.right - this.right, + height: this.height, + width: this.width + } + } + static getSimpleBoxPosition(e) { + let s = null; + e instanceof StyleBox && e.div ? s = e.div : e instanceof HTMLElement && (s = e); + let n = s.offsetHeight || 0 + , d = s.offsetWidth || 0 + , h = s.offsetTop || 0 + , p = h + n + , y = s.getBoundingClientRect(); + const {left: m, right: g} = y; + return y.top && (h = y.top), + y.height && (n = y.height), + y.width && (d = y.width), + y.bottom && (p = y.bottom), + { + left: m, + right: g, + top: h, + height: n, + bottom: p, + width: d + } + } + static getBoxPosition(e, s) { + if (e && e.length > 0) { + let n = 0 + , d = e[0][s]; + for (let h = 0; h < e.length; h++) + s in ["top", "right"] ? e[h][s] > d && (n = h, + d = e[h][s]) : s in ["bottom", "left"] && e[h][s] < d && (n = h, + d = e[h][s]); + return e[n] + } + return null + } + static moveToMinimumDistancePlacement(e, s, n) { + "height" === e.property ? "+y" === s ? (e.top = n.topMostBoxPosition.bottom + 0, + e.bottom = e.top + e.height) : "-y" === s && (e.bottom = n.bottomMostBoxPosition.top - 0, + e.top = e.bottom - e.height) : "width" === e.property && ("+x" === s ? (e.left = n.rightMostBoxPosition.right + 0, + e.right = e.left + e.width) : "-x" === s && (e.right = n.leftMostBoxPosition.left - 0, + e.left = e.right - e.width)) + } + static moveBoxToLinePosition(e, s, n) { + const d = e.cue; + let h, p = new BoxPosition(e), y = function(e) { + if ("number" == typeof e.line && (e.snapToLines || e.line >= 0 && e.line <= 100)) + return e.line; + if (!e.track || !e.track.textTrackList || !e.track.textTrackList.mediaElement) + return -1; + let s = 0; + const n = e.track + , d = n.textTrackList; + for (let h = 0; h < d.length && d[h] !== n; h++) + "showing" === d[h].mode && s++; + return -1 * ++s + }(d), m = []; + if (d.snapToLines) { + let e = 0; + switch (d.vertical) { + case "": + m = ["+y", "-y"], + h = "height"; + break; + case "rl": + m = ["+x", "-x"], + h = "width"; + break; + case "lr": + m = ["-x", "+x"], + h = "width" + } + const n = p.lineHeight + , g = s[h] + n + , v = m[0]; + if (y < 0) { + let h = 0; + switch (d.vertical) { + case "": + h = s.height - n - .05 * s.height; + break; + case "rl": + case "lr": + h = -s.width + n + .05 * s.width + } + e = h, + m = m.reverse() + } else { + switch (d.vertical) { + case "": + e = n * Math.round(y); + break; + case "rl": + e = s.width - n * Math.round(y); + break; + case "lr": + e = n * Math.round(y) + } + Math.abs(e) > g && (e = e < 0 ? -1 : 1, + e *= Math.ceil(g / n) * n) + } + p.move(v, e) + } else { + const n = "" === d.vertical ? s.height : s.width + , h = p.lineHeight / n * 100; + switch (d.lineAlign) { + case "center": + y -= h / 2; + break; + case "end": + y -= h + } + switch (d.vertical) { + case "": + e.applyStyles({ + top: e.formatStyle(y, "%") + }); + break; + case "rl": + e.applyStyles({ + right: e.formatStyle(y, "%") + }); + break; + case "lr": + e.applyStyles({ + left: e.formatStyle(y, "%") + }) + } + m = ["+y", "-y", "+x", "-x"], + "+y" === d.axis ? m = ["+y", "-y", "+x", "-x"] : "-y" === d.axis && (m = ["-y", "+y", "+x", "-x"]), + p = new BoxPosition(e) + } + const g = function(e, d) { + let h; + for (let p = 0; p < d.length; p++) { + e.moveIfOutOfBounds(s, d[p]); + let y = 0 + , m = !1; + for (; e.overlapsAny(n) && !(y > 9); ) + m ? e.move(d[p]) : (n && n.length > 0 && (h || (h = { + topMostBoxPosition: BoxPosition.getBoxPosition(n, "top"), + bottomMostBoxPosition: BoxPosition.getBoxPosition(n, "bottom"), + leftMostBoxPosition: BoxPosition.getBoxPosition(n, "left"), + rightMostBoxPosition: BoxPosition.getBoxPosition(n, "right") + }), + BoxPosition.moveToMinimumDistancePlacement(e, d[p], h)), + m = !0), + y++ + } + return e + }(p, m); + e.move(g.toCSSCompatValues(s)) + } + } + s.BoxPosition = BoxPosition; + class WebVTTRenderer { + constructor(e, s, n=!0) { + if (!e) + return null; + this.window = e, + this.overlay = s, + this.loggingEnabled = n, + this.foregroundStyleOptions = { + fontFamily: "Helvetica", + fontSize: "36px", + color: "rgba(255, 255, 255, 1)", + textShadow: "", + backgroundColor: "rgba(0, 0, 0, 0)" + }, + this.backgroundStyleOptions = { + backgroundColor: "rgba(0, 0, 0, 0.5)" + }, + this.globalStyleCollection = {}; + const d = e.document.createElement("div"); + d.style.position = "absolute", + d.style.left = "0", + d.style.right = "0", + d.style.top = "0", + d.style.bottom = "0", + d.style.margin = "1.5%", + this.paddedOverlay = d, + s.appendChild(this.paddedOverlay), + this.initSubtitleCSS() + } + initSubtitleCSS() { + const e = [new rr.VTTCue(0,0,"String to init CSS - Won't be visible to user")]; + this.paddedOverlay.style.opacity = "0", + this.processCues(e), + this.processCues([]), + this.paddedOverlay.style.opacity = "1" + } + convertCueToDOMTree(e) { + return e ? sr.default.parseContent(this.window, e, this.globalStyleCollection) : null + } + setStyles(e) { + function applyStyles(e, s, n) { + for (const d in s) + s.hasOwnProperty(d) && (!0 === n && void 0 !== e[d] || !1 === n) && (e[d] = s[d]) + } + for (const s in e) { + let d = !1 + , h = null; + "::cue" === s ? (h = this.foregroundStyleOptions, + d = !0) : "::-webkit-media-text-track-display" === s && (h = this.backgroundStyleOptions, + d = !0); + const p = e[s]; + if (!0 === d) + applyStyles(h, p, d); + else + for (let e = 0; e < n.length; e++) { + const h = n[e].exec(s); + if (h && 4 === h.length) { + const e = h[2] + , s = {}; + applyStyles(s, p, d), + this.globalStyleCollection[e] = s + } + } + } + this.initSubtitleCSS(), + this.loggingEnabled && (console.log("WebVTTRenderer setStyles foregroundStyleOptions: " + JSON.stringify(this.foregroundStyleOptions)), + console.log("WebVTTRenderer setStyles backgroundStyleOptions: " + JSON.stringify(this.backgroundStyleOptions)), + console.log("WebVTTRenderer setStyles globalStyleCollection: " + JSON.stringify(this.globalStyleCollection))) + } + processCues(e) { + if (!e) + return; + for (; this.paddedOverlay.firstChild; ) + this.paddedOverlay.removeChild(this.paddedOverlay.firstChild); + if (!function(e) { + for (let s = 0; s < e.length; s++) + if (e[s].hasBeenReset || !e[s].displayState) + return !0; + return !1 + }(e)) { + for (let s = 0; s < e.length; s++) + this.paddedOverlay.appendChild(e[s].displayState); + return + } + const s = [] + , n = BoxPosition.getSimpleBoxPosition(this.paddedOverlay); + e.length > 1 && (e = function(e) { + const s = []; + let n = 0; + for (let d = 0; d < e.length; d++) { + let h = e[d]; + if ("number" != typeof h.line) + return e; + n += h.line, + s.push(h) + } + return n /= e.length, + n > 50 ? (s.forEach((function(e) { + e.axis = "-y" + } + )), + s.sort((e,s)=>s.line - e.line)) : (s.forEach((function(e) { + e.axis = "+y" + } + )), + s.sort((e,s)=>e.line - s.line)), + s + }(e)); + for (let d = 0; d < e.length; d++) { + let h = e[d] + , p = new CueStyleBox(this.window,h,this.foregroundStyleOptions,this.backgroundStyleOptions,this.globalStyleCollection); + this.paddedOverlay.appendChild(p.div), + BoxPosition.moveBoxToLinePosition(p, n, s), + h.displayState = p.div, + s.push(BoxPosition.getSimpleBoxPosition(p)) + } + } + setSize(e, s) { + e && (this.overlay.style.width = e + "px"), + s && (this.overlay.style.height = s + "px") + } + getOverlay() { + return this.overlay + } + } + s.default = WebVTTRenderer, + s.WebVTTRenderer = WebVTTRenderer + } + )); + unwrapExports(or), + or.VTTCue, + or.StyleBox, + or.CueStyleBox, + or.BoxPosition, + or.WebVTTRenderer; + var dr = createCommonjsModule((function(e, s) { + function __export(e) { + for (var n in e) + s.hasOwnProperty(n) || (s[n] = e[n]) + } + Object.defineProperty(s, "__esModule", { + value: !0 + }), + __export(ar), + __export(or) + } + )); + unwrapExports(dr); + var lr = dr.WebVTTRenderer; + class TrackManagerStub { + get currentTrack() { + return {} + } + set currentTrack(e) {} + get tracks() { + return [] + } + destroy() {} + restoreSelectedTrack() {} + } + const {audioTrackAdded: cr, audioTrackChanged: ur, forcedTextTrackChanged: hr, textTrackAdded: pr, textTrackChanged: yr, textTrackRemoved: mr} = rs + , {textTracksSwitched: gr, textTracksUpdated: fr} = zs; + class TextTrackManager { + constructor(e, s, n) { + this.mediaElement = e, + this.dispatcher = s, + this.extensionTracks = n, + this._tracks = [], + this.trackPersistence = new TrackPersistence("mk-text-track",["label", "language", "kind"]); + const d = this.trackPersistence.getPersistedTrack(); + if (this._tracks.push({ + id: -2, + label: "Off", + language: "", + kind: "subtitles", + mode: !d || this.isTrackOff(d) ? "showing" : "disabled" + }), + this.extensionTracks) { + O.debug("MEDIA_TRACK Initializing text track manager for HLS.js track events"); + const s = e.parentElement; + this.renderer = new lr(window,s,!1), + this.renderer.setStyles({ + "::cue": { + fontSize: "calc(1vw + 1em)" + } + }), + this.onExtensionTextTracksAdded = this.onExtensionTextTracksAdded.bind(this), + this.onExtensionTextTrackSwitched = this.onExtensionTextTrackSwitched.bind(this), + this.onCueChange = this.onCueChange.bind(this); + const n = this.extensionTracks; + n.addEventListener(fr, this.onExtensionTextTracksAdded), + n.addEventListener(gr, this.onExtensionTextTrackSwitched) + } else + O.debug("MEDIA_TRACK Initializing text track manager for native track events"), + this.onTextTrackAdded = this.onTextTrackAdded.bind(this), + this.onTextTrackChanged = this.onTextTrackChanged.bind(this), + this.onTextTrackRemoved = this.onTextTrackRemoved.bind(this), + this.onPlayStart = this.onPlayStart.bind(this), + e.textTracks.addEventListener("addtrack", this.onTextTrackAdded), + e.textTracks.addEventListener("change", this.onTextTrackChanged), + e.textTracks.addEventListener("removetrack", this.onTextTrackRemoved), + e.addEventListener("playing", this.onPlayStart); + this.onAudioTrackAddedOrChanged = debounce(this.onAudioTrackAddedOrChanged.bind(this)), + s.subscribe(ur, this.onAudioTrackAddedOrChanged), + s.subscribe(cr, this.onAudioTrackAddedOrChanged) + } + get currentTrack() { + return this.tracks.find(e=>"showing" === e.mode) + } + set currentTrack(e) { + if (!e) + return; + let s; + this.trackPersistence.setPersistedTrack(e), + this.extensionTracks ? (O.debug("MEDIA_TRACK Setting track on extension " + e.label), + "Off" === e.label ? (this.clearCurrentlyPlayingTrack(), + s = this.extensionTracks.selectForcedTrack(), + void 0 === s && this.onExtensionTextTrackSwitched({ + track: e + })) : this.extensionTracks.textTrack = e) : (O.debug("MEDIA_TRACK Setting track on element " + e.label), + this._tracks.forEach(s=>{ + s !== e && "showing" === s.mode && (s.mode = "disabled") + } + ), + e && (O.debug("MEDIA_TRACK setting track mode to showing for " + e.label), + this.isTrackOff(e) ? (this._tracks[0].mode = "showing", + s = this.selectNativeForcedTrack(this.mediaElement.audioTracks)) : e.mode = "showing")), + this.dispatcher.publish(rs.forcedTextTrackChanged, s) + } + get tracks() { + return this._tracks + } + destroy() { + if (this.clearCurrentlyPlayingTrack(), + this.extensionTracks) { + const e = this.extensionTracks; + e.removeEventListener(fr, this.onExtensionTextTracksAdded), + e.removeEventListener(gr, this.onExtensionTextTrackSwitched) + } else + this.mediaElement.textTracks.removeEventListener("addtrack", this.onTextTrackAdded), + this.mediaElement.textTracks.removeEventListener("change", this.onTextTrackChanged), + this.mediaElement.textTracks.removeEventListener("removetrack", this.onTextTrackRemoved), + this.mediaElement.removeEventListener("playing", this.onPlayStart); + this.dispatcher.unsubscribe(ur, this.onAudioTrackAddedOrChanged), + this.dispatcher.unsubscribe(cr, this.onAudioTrackAddedOrChanged) + } + restoreSelectedTrack() { + return restoreSelectedTrack(this.trackPersistence, this) + } + onExtensionTextTracksAdded(e) { + O.debug("MEDIA_TRACK Extension text tracks updated " + JSON.stringify(e)), + this._tracks.push(...e), + this.restoreSelectedTrack(), + this.dispatcher.publish(pr, e) + } + onExtensionTextTrackSwitched(e) { + O.debug("MEDIA_TRACKS Extension text track switched " + e), + this.handleVTT(e); + const s = e.track; + if (this._tracks) { + const preserveSelectedTrack = n=>{ + e.track ? s.forced && "Off" === n.label || "Off" === s.label && "Off" === n.label ? n.mode = "showing" : n.mode = e.track.persistentID === n.id ? "showing" : "disabled" : n.mode = "Off" === n.label ? "showing" : "disabled" + } + ; + this._tracks.forEach(preserveSelectedTrack) + } + this.dispatcher.publish(yr, e) + } + handleVTT(e) { + const s = e && e.track && e.track.id; + if (void 0 !== s && s >= 0) { + const e = this.filterSelectableTextTracks(this.mediaElement.textTracks)[s]; + this.onNativeTrackChange(e) + } else + this.clearCurrentlyPlayingTrack() + } + onAudioTrackAddedOrChanged(e, s) { + if (O.debug("MEDIA_TRACKS text track manager detects audio track change"), + this.shouldForceSubtitle()) + if (this.extensionTracks) { + O.debug("MEDIA_TRACKS selecting forced text track via extension"); + const e = this.extensionTracks.selectForcedTrack(); + e ? this.dispatcher.publish(hr, e) : this.clearCurrentlyPlayingTrack() + } else + O.debug("MEDIA_TRACKS selecting forced text track natively"), + this.currentTrack = this._tracks[0] + } + onTextTrackAdded(e) { + this._tracks.push(e.track), + this.dispatcher.publish(pr, e) + } + onPlayStart() { + this.restoreSelectedTrack() + } + onTextTrackRemoved(e) { + this.dispatcher.publish(mr, e) + } + onTextTrackChanged(e) { + const s = this.findNativeSelectedTextTrack(); + let n = this.trackPersistence.getPersistedTrack(); + if (n || (n = this._tracks[0]), + s && !trackEquals(s, n, this.trackPersistence.fields)) + if (this.isTrackOff(n) && "forced" !== s.kind) + this.currentTrack = n; + else { + const e = this.findNativeTrack(n); + e && (this.currentTrack = e) + } + else + this.dispatcher.publish(yr, e) + } + findNativeSelectedTextTrack() { + for (let e = 0; e < this.mediaElement.textTracks.length; e++) { + const s = this.mediaElement.textTracks[e]; + if ("showing" === s.mode) + return s + } + } + findNativeTrack(e) { + for (let s = 0; s < this.mediaElement.textTracks.length; s++) { + const n = this.mediaElement.textTracks[s]; + if (trackEquals(n, e, this.trackPersistence.fields)) + return n + } + } + selectNativeForcedTrack(e) { + for (let s = 0; s < e.length; s++) { + const n = e[s]; + if (n.enabled) { + const e = this.findNativeForcedTrack(n); + return e && "showing" !== e.mode && (e.mode = "showing"), + e + } + } + } + findNativeForcedTrack(e) { + const s = this.mediaElement.textTracks; + for (let n = 0; n < s.length; n++) { + const d = s[n]; + if ("forced" === d.kind && d.language === e.language) + return d + } + } + onNativeTrackChange(e) { + this.clearCurrentlyPlayingTrack(), + this._currentlyPlayingTrack = e, + e.addEventListener("cuechange", this.onCueChange) + } + clearCurrentlyPlayingTrack() { + var e; + void 0 !== this._currentlyPlayingTrack && ("string" == typeof (e = this._currentlyPlayingTrack).id && "removeEventListener"in e) && (this._currentlyPlayingTrack.removeEventListener("cuechange", this.onCueChange), + this.renderer.processCues({}), + delete this._currentlyPlayingTrack) + } + onCueChange(e) { + const s = e && e.target && e.target.activeCues; + s && this.renderer.processCues(s) + } + filterSelectableTextTracks(e) { + const s = []; + for (let n = 0; n < e.length; n++) { + const d = e[n]; + ("captions" === d.kind || "subtitles" === d.kind || "metadata" === d.kind && d.customTextTrackCueRenderer) && s.push(d) + } + return s + } + shouldForceSubtitle() { + O.debug("MEDIA_TRACKS Determining whether to select forced text track"); + const e = this.trackPersistence.getPersistedTrack(); + return !e || this.isTrackOff(e) + } + isTrackOff(e) { + return "Off" === e.label || "Auto" === e.label + } + } + const vr = { + "picture-in-picture": e.PresentationMode.pictureinpicture, + inline: e.PresentationMode.inline + } + , _r = {}; + _r[e.PresentationMode.pictureinpicture] = "picture-in-picture", + _r[e.PresentationMode.inline] = "inline"; + const {presentationModeDidChange: br} = rs + , {playbackLicenseError: Tr} = zs + , {stopped: Er} = e.PlaybackStates; + class VideoPlayer extends BasePlayer { + constructor(e) { + super(e), + this.mediaPlayerType = "video", + this._textTrackManager = new TrackManagerStub, + this._audioTrackManager = new TrackManagerStub, + this.userInitiated = !1, + this.restrictPlatforms = !("restrict-platforms"in Hs.features) || Hs.features["restrict-platforms"], + this.pipEventHandler = this.pipEventHandler.bind(this) + } + get audioTracks() { + return this._audioTrackManager.tracks + } + get containerElement() { + return this._context.videoContainerElement ? this._context.videoContainerElement : document.getElementById("apple-music-video-container") + } + get currentAudioTrack() { + return this._audioTrackManager.currentTrack + } + set currentAudioTrack(e) { + this._audioTrackManager.currentTrack = e + } + get currentTextTrack() { + return this._textTrackManager.currentTrack + } + set currentTextTrack(e) { + this._textTrackManager.currentTrack = e + } + get _targetElement() { + return this.video || Object.assign({}, document.createElement("video")) + } + get textTracks() { + return this._textTrackManager.tracks + } + initializeExtension() { + return __awaiter$3(this, void 0, void 0, (function*() { + this.restrictPlatforms && Fe.isAndroid ? O.warn("videoPlayer.initializeExtension Not supported on the current platform") : this.video || O.warn("videoPlayer.initializeExtension No video element, not initializing extension") + } + )) + } + onPlaybackLicenseError(e) { + this._licenseError(), + this._dispatcher.publish(Tr, e) + } + setupTrackManagers(e) { + var s, n, d, h; + null === (n = null === (s = this._textTrackManager) || void 0 === s ? void 0 : s.destroy) || void 0 === n || n.call(s), + this._textTrackManager = new TextTrackManager(this._targetElement,this._dispatcher,e), + null === (h = null === (d = this._audioTrackManager) || void 0 === d ? void 0 : d.destroy) || void 0 === h || h.call(d), + this._audioTrackManager = new AudioTrackManager(this._targetElement,this._dispatcher,e) + } + destroy() { + this._textTrackManager.destroy(), + this._audioTrackManager.destroy(), + super.destroy() + } + initializeEventHandlers() { + const e = Object.create(null, { + initializeEventHandlers: { + get: ()=>super.initializeEventHandlers + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + e.initializeEventHandlers.call(this), + this.hasMediaElement && (this._targetElement.addEventListener("webkitpresentationmodechanged", this.pipEventHandler), + this._targetElement.addEventListener("enterpictureinpicture", this.pipEventHandler), + this._targetElement.addEventListener("leavepictureinpicture", this.pipEventHandler)) + } + )) + } + removeEventHandlers() { + if (super.removeEventHandlers(), + !this.hasMediaElement) + return; + const {_targetElement: e} = this; + e.removeEventListener("webkitpresentationmodechanged", this.pipEventHandler), + e.removeEventListener("enterpictureinpicture", this.pipEventHandler), + e.removeEventListener("leavepictureinpicture", this.pipEventHandler) + } + initializeMediaElement() { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("videoPlayer.initializeMediaElement Initializing media element"); + const e = this.containerElement; + e ? (this.video = function() { + let e = er.pop(); + return e ? O.debug(`dom-helpers: retrieving video tag, ${er.length} remain`) : (O.debug("dom-helpers: no available video tags, creating one"), + e = document.createElement("video")), + e + }(), + this.video.autoplay = !1, + this.video.controls = !1, + this.video.playsInline = !0, + this.video.id = "apple-music-video-player", + e.appendChild(this.video)) : O.warn("videoPlayer.initializeMediaElement No video element; no container defined") + } + )) + } + isPlayerSupported() { + return Browser.supportsEs6() + } + _stopMediaElement() { + const e = Object.create(null, { + _stopMediaElement: { + get: ()=>super._stopMediaElement + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + yield e._stopMediaElement.call(this), + this.destroy() + } + )) + } + pipEventHandler(s) { + switch (s.type) { + case "enterpictureinpicture": + this._dispatcher.publish(br, { + mode: e.PresentationMode.pictureinpicture + }); + break; + case "leavepictureinpicture": + this._dispatcher.publish(br, { + mode: e.PresentationMode.inline + }); + break; + case "webkitpresentationmodechanged": + { + const e = this._targetElement; + this._dispatcher.publish(br, { + mode: this._translateStringToPresentationMode(e.webkitPresentationMode) + }); + break + } + } + } + playItemFromEncryptedSource(s, n=!1, d) { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("videoPlayer.playItemFromEncryptedSource", s, n), + this.playbackState !== Er ? (s.playbackType = e.PlaybackType.encryptedFull, + this.nowPlayingItem = s, + s.state = D.loading, + this.userInitiated = n, + this.playHlsStream(s.assetURL, s)) : O.debug("video-player.playItemFromEncryptedSource aborting playback because player is stopped") + } + )) + } + playItemFromUnencryptedSource(e, s, n) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (O.debug("videoPlayer.playItemFromUnencryptedSource", e, s), + this.playbackState === Er) + return void O.debug("videoPlayer.playItemFromUnencryptedSource aborting playback because player is stopped"); + const [n] = e.split("?"); + return n.endsWith("m3u") || n.endsWith("m3u8") ? void this.playHlsStream(e) : this._playAssetURL(e, s) + } + )) + } + setPresentationMode(s) { + return __awaiter$3(this, void 0, void 0, (function*() { + const n = this._targetElement; + if (n.webkitSupportsPresentationMode && "function" == typeof n.webkitSetPresentationMode) + return n.webkitSetPresentationMode(this._translatePresentationModeToString(s)); + if (n.requestPictureInPicture && document.exitPictureInPicture) { + if (s === e.PresentationMode.pictureinpicture) + return n.requestPictureInPicture(); + if (s === e.PresentationMode.inline) + return document.exitPictureInPicture() + } + } + )) + } + _translateStringToPresentationMode(s) { + let n = vr[s]; + return void 0 === n && (O.warn(`videoPlayer._translateStringToPresentationMode ${s} is not a valid presentation mode, setting to inline`), + n = e.PresentationMode.inline), + n + } + _translatePresentationModeToString(e) { + let s = _r[e]; + return void 0 === s && (O.warn(`videoPlayer._translatePresentationModeToString ${e} is not a valid presentation mode, setting to inline`), + s = "inline"), + s + } + setNextSeamlessItem(e) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + } + var kr; + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object]), __metadata$2("design:returntype", void 0)], VideoPlayer.prototype, "onPlaybackLicenseError", null), + function(e) { + e.NONE = "none", + e.FAIRPLAY = "com.apple.fps", + e.PLAYREADY = "com.microsoft.playready", + e.WIDEVINE = "com.widevine.alpha" + }(kr || (kr = {})); + const hasSessionStorage = ()=>"undefined" != typeof window && window.sessionStorage; + function findMediaKeySystemAccess(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + for (let d = 0; d < e.length; d++) + try { + const n = e[d]; + return [n, yield navigator.requestMediaKeySystemAccess(n, s)] + } catch (n) {} + return [] + } + )) + } + let Sr; + const {NONE: Pr, FAIRPLAY: Ir, WIDEVINE: Ar, PLAYREADY: wr} = kr; + function supportsDrm() { + if (!Sr) + throw new Error("findKeySystemPreference has not been invoked"); + return Sr !== Pr + } + function potentialKeySystemsForAccess() { + return hasSessionStorage() && "true" === window.sessionStorage.getItem("mk-playready-cbcs-unsupported") ? [Ar] : Hs.features["prefer-playready"] ? [wr, Ar] : [Ar, wr] + } + function findKeySystemPreference() { + var e, s; + return __awaiter$3(this, void 0, void 0, (function*() { + if (!Ke) { + if (null === (e = window.WebKitMediaKeys) || void 0 === e ? void 0 : e.isTypeSupported(Ir + ".1_0", qs.AVC1)) + Sr = Ir; + else if (null === (s = window.MSMediaKeys) || void 0 === s ? void 0 : s.isTypeSupported(wr, qs.AVC1)) + Sr = wr; + else { + const e = Zs; + if (hasMediaKeySupport() && e.canPlayType('video/mp4;codecs="avc1.42E01E"') && e.canPlayType('audio/mp4;codecs="mp4a.40.2"')) { + const e = [{ + videoCapabilities: [{ + contentType: 'video/mp4;codecs="avc1.42E01E"', + robustness: "SW_SECURE_CRYPTO" + }], + audioCapabilities: [{ + contentType: 'audio/mp4;codecs="mp4a.40.2"' + }] + }] + , s = potentialKeySystemsForAccess() + , [n] = yield findMediaKeySystemAccess(s, e); + Sr = n + } + } + return Sr = null != Sr ? Sr : Pr, + Sr + } + Sr = Pr + } + )) + } + function hasMediaKeySupport() { + return !!(navigator && navigator.requestMediaKeySystemAccess && window.MediaKeys && window.MediaKeySystemAccess) + } + let Rr = { + developerToken: "developerTokenNotSet", + musicUserToken: "musicUserTokenNotSet" + }; + function createHlsOffersLicenseChallengeBody(e) { + return { + "adam-id": e.id, + id: 1 + } + } + function createLicenseChallengeBody(e, s, n, d, h) { + let p; + const y = { + challenge: n.challenge || Ye(n.licenseChallenge), + "key-system": d, + uri: n.keyuri + }; + return p = s.isUTS ? Object.assign(Object.assign({}, y), function(e, s="start") { + return { + "extra-server-parameters": e.keyServerQueryParameters, + "license-action": s + } + }(s, e)) : s.isLiveRadioStation ? Object.assign(Object.assign({}, y), { + event: "beats1" + }) : s.hasOffersHlsUrl ? { + "license-requests": [Object.assign(Object.assign({}, y), createHlsOffersLicenseChallengeBody(s))] + } : Object.assign(Object.assign({}, y), function(e, s=!1) { + return { + adamId: e.songId, + isLibrary: e.isCloudItem, + "user-initiated": s + } + }(s, h)), + p + } + class License { + fetch(e) { + const s = { + Authorization: "Bearer " + Rr.developerToken, + Accept: "application/json", + "Content-Type": "application/json", + "X-Apple-Music-User-Token": "" + Rr.musicUserToken + }; + this.keySystem === kr.WIDEVINE && (s["X-Apple-Renewal"] = !0); + const n = new Headers(s); + return fetch(this.licenseUrl, { + method: "POST", + body: JSON.stringify(e), + headers: n + }) + } + reset() { + this.licenseUrl = void 0, + this.playableItem = void 0, + this.data = void 0, + this.initiated = void 0, + this.keySystem = void 0, + this.startResponse = void 0 + } + start(e, s, n, d, h=!1) { + var p, y; + return __awaiter$3(this, void 0, void 0, (function*() { + this.licenseUrl = e, + this.playableItem = s, + this.data = n, + this.keySystem = d, + this.initiated = h; + const m = n.isRenewalRequest ? "renew" : "start" + , g = createLicenseChallengeBody(m, s, n, d, h); + s.hasOffersHlsUrl && (this.licenseUrl += "/" + m), + this.startResponse = this.fetch(g); + try { + const e = yield this.startResponse; + if (!e.ok) { + let s; + try { + s = yield e.json() + } catch (bt) {} + this.processJsonError(s) + } + const s = yield e.json() + , n = (null === (p = s["license-responses"]) || void 0 === p ? void 0 : p.length) ? s["license-responses"][0] : s; + return n.status = null !== (y = n.status) && void 0 !== y ? y : n.errorCode, + 0 !== n.status && this.processJsonError(n), + n + } catch (F) { + throw this.startResponse = void 0, + F + } + } + )) + } + processJsonError(e) { + let s = new MKError(MKError.MEDIA_LICENSE,"Error acquiring license"); + if ((null == e ? void 0 : e.errorCode) && (e.status = e.errorCode), + e && 0 !== e.status) { + if (!e.message) + switch (e.status) { + case -1004: + e.message = MKError.DEVICE_LIMIT; + break; + default: + e.message = MKError.MEDIA_LICENSE + } + s = MKError.serverError(e), + s.data = e, + s.errorCode === MKError.PLAYREADY_CBC_ENCRYPTION_ERROR && hasSessionStorage() && window.sessionStorage.setItem("mk-playready-cbcs-unsupported", "true") + } + throw s + } + stop() { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this.startResponse) + try { + yield this.startResponse + } catch (F) {} + if (!this.playableItem || !this.data) + return; + if (!this.playableItem.isUTS) + return; + const e = createLicenseChallengeBody("stop", this.playableItem, this.data, this.keySystem, this.initiated) + , s = this.fetch(e); + this.reset(); + try { + yield s + } catch (F) { + O.warn("license.stop request error", F) + } + } + )) + } + } + const Or = /max-age=(\d+)/i; + class KeySession extends Notifications { + constructor() { + super([zs.playbackLicenseError, zs.playbackSessionError]), + this.initiated = !0, + this.isLibrary = !1, + this.keySystem = kr.FAIRPLAY, + this.mediaKeySessions = {}, + this._storage = window.sessionStorage, + this.boundDispatchKeyError = this.dispatchKeyError.bind(this), + this.boundDispatchSessionError = this.dispatchSessionError.bind(this), + this.boundHandleSessionCreation = this.handleSessionCreation.bind(this), + this.boundStartLicenseSession = this.startLicenseSession.bind(this), + this.license = new License + } + get extID() { + if (this.extURI) + return this.extURI.replace("data:;base64,", "") + } + get isFairplay() { + return this.keySystem === kr.FAIRPLAY + } + get isPlayReady() { + return this.keySystem === kr.PLAYREADY + } + get isWidevine() { + return this.keySystem === kr.WIDEVINE + } + acquirePlaybackLicense(e, s, n, d) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (!this.keyServerURL || !this.developerToken || !this.userToken) + return; + const {keyServerURL: n, keySystem: h} = this; + try { + return yield this.license.start(n, d.item, { + challenge: s, + keyuri: e + }, h, this.initiated) + } catch (bt) { + this.dispatchEvent(zs.playbackLicenseError, bt) + } + } + )) + } + startLicenseSession(e) { + let s; + O.debug("Starting License Session", e); + const {message: n, target: d, messageType: h} = e; + if (this.keySystem !== kr.FAIRPLAY && "license-request" !== h) + return void O.debug("not making license request for", h); + if (this.isPlayReady) { + const e = String.fromCharCode.apply(null, new Uint16Array(n.buffer || n)); + s = (new DOMParser).parseFromString(e, "application/xml").getElementsByTagName("Challenge")[0].childNodes[0].nodeValue + } else + s = Ye(new Uint8Array(n)); + const p = d.extURI || this.extURI + , y = this.mediaKeySessions[p]; + if (y) + return this.acquirePlaybackLicense(p, s, this.initiated, y).then(e=>this.handleLicenseJson(e, d, p)); + O.debug("no key session info, aborting license request") + } + setKeyURLs(e) { + this.keyCertURL = e[this.isFairplay ? "hls-key-cert-url" : "widevine-cert-url"], + this.keyServerURL = e["hls-key-server-url"] + } + dispatchKeyError(e) { + console.error(MKError.MEDIA_KEY + " error in dispatchKeyError:", e), + this.dispatchEvent(zs.playbackSessionError, new MKError(MKError.MEDIA_KEY,e)) + } + dispatchSessionError(e) { + this.dispatchEvent(zs.playbackSessionError, new MKError(MKError.MEDIA_SESSION,e)) + } + loadCertificateBuffer() { + return __awaiter$3(this, void 0, void 0, (function*() { + if (!this.keyCertURL) + return Promise.reject(new MKError(MKError.MEDIA_SESSION,"No certificate URL")); + const e = document.createElement("a"); + e.href = this.keyCertURL; + const s = Date.now() + , n = `${e.hostname}${e.pathname}`.replace(/[^a-z0-9.]/gi, ".") + , d = this._storage.getItem(n) + , h = parseInt(this._storage.getItem("com.ai.mk.vmcc.exp") || "", 10); + if (d && h && h > s) { + const e = new Uint8Array(d.length); + for (let s = d.length; s--; ) + e[s] = d.charCodeAt(s); + return e.buffer + } + const p = yield fetch(`${this.keyCertURL}?t=${Date.now()}`) + , y = p.headers.get("cache-control"); + let m = 86400; + if (y && Or.test(y)) { + const e = y.match(Or); + e && e[1] && (m = parseInt(e[1], 10)) + } + const g = yield p.arrayBuffer() + , v = String.fromCharCode.apply(String, new Uint8Array(g)); + return /^\<\?xml/.test(v) ? Promise.reject(new MKError(MKError.MEDIA_CERTIFICATE,"Invalid certificate.")) : (this._storage.setItem(n, v), + this._storage.setItem("com.ai.mk.vmcc.exp", (s + 1e3 * m).toString()), + g) + } + )) + } + handleSessionCreation(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return this.createSession(e).catch(e=>{ + this.dispatchSessionError(e) + } + ) + } + )) + } + handleLicenseJson(e, s, n) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (O.debug(`updating session ${s.sessionId} with license response`, e), + null == e ? void 0 : e.license) { + const n = ze(e.license); + try { + yield s.update(n) + } catch (bt) { + O.error("Failed to updated media keys", bt), + this.dispatchKeyError(bt) + } + } + } + )) + } + addMediaKeySessionInfo(e, s, n) { + const d = this.mediaKeySessions[e]; + d ? (O.debug(`keySession info exists for ${n.title}, making existing session ${d.session.sessionId} the old session`), + d.oldSession = d.session, + d.session = s) : (O.debug("creating key session info for " + n.title), + this.mediaKeySessions[e] = { + session: s, + item: n + }) + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object]), __metadata$2("design:returntype", void 0)], KeySession.prototype, "startLicenseSession", null); + class FairplayEncryptedSession extends KeySession { + constructor() { + super(...arguments), + this._mediaKeySessions = {}, + this._mediaKeySessionRenewals = {} + } + attachMedia(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + this.keySystem = s.keySystem, + this._keySystemAccess = s, + e.addEventListener("encrypted", this.boundHandleSessionCreation, !1) + } + )) + } + detachMedia(e) { + e.removeEventListener("encrypted", this.boundHandleSessionCreation); + const s = this._mediaKeySessions + , n = this._mediaKeySessionRenewals; + Object.values(s).forEach(e=>{ + e.removeEventListener("message", this.boundStartLicenseSession), + asAsync(e.close()) + } + ), + this._mediaKeySessions = {}, + Object.values(n).forEach(e=>clearTimeout(e)), + this._mediaKeySessionRenewals = {} + } + createSession(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("Encrypted createSession", e); + const s = this._keySystemAccess; + if (!s) + return; + const {initData: n, target: d, initDataType: h} = e; + this._mediaKeysPromise || (this._mediaKeysPromise = new Promise((e,n)=>__awaiter$3(this, void 0, void 0, (function*() { + const n = yield s.createMediaKeys() + , h = yield this.loadCertificateBuffer(); + yield n.setServerCertificate(h), + yield d.setMediaKeys(n), + e(n) + } + )))); + const p = yield this._mediaKeysPromise + , y = new Uint8Array(n) + , m = String.fromCharCode.apply(void 0, Array.from(y)) + , g = p.createSession(); + g.extURI = this.extURI || m, + yield g.generateRequest(h, n), + this._mediaKeySessions[g.sessionId] = g, + g.addEventListener("message", this.boundStartLicenseSession) + } + )) + } + handleLicenseJson(e, s, n) { + const d = Object.create(null, { + handleLicenseJson: { + get: ()=>super.handleLicenseJson + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + if (!e) + return; + yield d.handleLicenseJson.call(this, e, s, n); + const h = e["renew-after"]; + if (e.license && h) { + const e = this._mediaKeySessionRenewals + , n = e[s.sessionId]; + n && clearTimeout(n); + const d = setTimeout(()=>s.update(qe("renew")), 1e3 * h); + e[s.sessionId] = d + } + } + )) + } + loadKeys(e) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + clearSessions() { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + } + const Cr = /^(?:.*)(skd:\/\/.+)$/i; + class WebKitSession extends KeySession { + attachMedia(e, s) { + return this.target = e, + e.addEventListener("webkitneedkey", this.boundHandleSessionCreation, !1), + e.addEventListener("webkitkeyerror", this.boundDispatchKeyError), + e + } + detachMedia(e) { + e && (e.removeEventListener("webkitneedkey", this.boundHandleSessionCreation, !1), + e.removeEventListener("webkitkeyerror", this.boundDispatchKeyError)) + } + destroy() { + O.debug("FPS destroy"), + this.detachMedia(this.target), + this.session && (this.session.removeEventListener("webkitkeyerror", this.boundDispatchKeyError), + this.session.removeEventListener("webkitkeymessage", this.boundStartLicenseSession)) + } + createSession(e) { + O.debug("FPS createSession", e); + const {initData: s, target: n} = e + , {item: d} = this; + if (!d) + return O.error("Cannot createSession without item"), + Promise.resolve(); + const h = this._extractAssetId(s); + if (O.debug("extURI", h), + !n.webkitKeys) { + const e = new window.WebKitMediaKeys(this.keySystem); + n.webkitSetMediaKeys(e) + } + return this.loadCertificateBuffer().then(e=>{ + const p = this._concatInitDataIdAndCertificate(s, h, e) + , y = "VIDEO" === n.tagName ? qs.AVC1 : qs.MP4 + , m = n.webkitKeys.createSession(y, p); + this.addMediaKeySessionInfo(h, m, d), + this.session = m, + m.extURI = h, + m.addEventListener("webkitkeyerror", this.boundDispatchKeyError), + m.addEventListener("webkitkeymessage", this.boundStartLicenseSession) + } + ) + } + _extractAssetId(e) { + let s = String.fromCharCode.apply(null, new Uint16Array(e.buffer || e)); + const n = s.match(Cr); + return n && n.length >= 2 && (s = n[1]), + O.debug("Extracted assetId from EXT-X-KEY URI", s), + s + } + _concatInitDataIdAndCertificate(e, s, n) { + "string" == typeof s && (s = We(s)), + n = new Uint8Array(n); + let d = 0; + const h = new ArrayBuffer(e.byteLength + 4 + s.byteLength + 4 + n.byteLength) + , p = new DataView(h); + new Uint8Array(h,d,e.byteLength).set(e), + d += e.byteLength, + p.setUint32(d, s.byteLength, !0), + d += 4; + const y = new Uint8Array(h,d,s.byteLength); + y.set(s), + d += y.byteLength, + p.setUint32(d, n.byteLength, !0), + d += 4; + return new Uint8Array(h,d,n.byteLength).set(n), + new Uint8Array(h,0,h.byteLength) + } + loadKeys(e) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + clearSessions() { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + } + class MSSession extends KeySession { + attachMedia(e, s) { + return this.keySystem = s.keySystem, + e.addEventListener("msneedkey", this.boundHandleSessionCreation, !1), + e.addEventListener("mskeyerror", this.boundDispatchKeyError), + e + } + detachMedia(e) { + e.removeEventListener("msneedkey", this.boundHandleSessionCreation, !1), + e.removeEventListener("mskeyerror", this.boundDispatchKeyError) + } + createSession(e) { + const {initData: s, target: n} = e; + if (!n.msKeys) { + const e = new MSMediaKeys(this.keySystem); + n.msSetMediaKeys(e) + } + const d = n.msKeys.createSession(qs.MP4, s); + return d.addEventListener("mskeyerror", this.dispatchKeyError), + d.addEventListener("mskeymessage", this.startLicenseSession.bind(this)), + d + } + loadKeys(e) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + clearSessions() { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + } + const Mr = new Logger + , Dr = { + [kr.WIDEVINE]: Ws.WIDEVINE, + [kr.FAIRPLAY]: Ws.FAIRPLAY, + [kr.PLAYREADY]: Ws.PLAYREADY + } + , Nr = [0, 0, 1, 222, 112, 115, 115, 104, 0, 0, 0, 0, 154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, 91, 224, 136, 95, 149, 0, 0, 1, 190] + , Lr = [190, 1, 0, 0, 1, 0, 1, 0, 180, 1]; + function concatenate(e, ...s) { + let n = 0; + for (const p of s) + n += p.length; + const d = new e(n); + let h = 0; + for (const p of s) + d.set(p, h), + h += p.length; + return d + } + const {WIDEVINE: xr, PLAYREADY: Ur} = kr + , $r = {}; + $r[xr] = e=>{ + Mr.debug("generating Widevine pssh for keyId"); + const s = new Uint8Array([0, 0, 0, 52, 112, 115, 115, 104, 0, 0, 0, 0, 237, 239, 139, 169, 121, 214, 74, 206, 163, 200, 39, 220, 213, 29, 33, 237, 0, 0, 0, 20, 8, 1, 18, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + for (let n = 0; n < e.length; n++) + s[s.length - 16 + n] = e[n]; + return Mr.debug("generatePSSH", s), + s + } + , + $r[Ur] = e=>{ + Mr.debug("generating Playready pssh for keyId"), + (e=>{ + const swap = (e,s,n)=>{ + const d = e[s]; + e[s] = e[n], + e[n] = d + } + ; + swap(e, 0, 3), + swap(e, 1, 2), + swap(e, 4, 5), + swap(e, 6, 7) + } + )(e); + const s = Ye(e) + , n = ''.replace("[KEYID]", s) + , d = We(n) + , h = new Uint8Array(d.buffer,d.byteOffset,d.byteLength); + return concatenate(Uint8Array, Nr, Lr, h) + } + ; + class PreloadingEncryptedSession extends KeySession { + constructor() { + super(...arguments), + this._sessionRemovalTimeouts = {}, + this._mediaKeySessionRenewals = {} + } + attachMedia(e, s) { + this.keySystem = s.keySystem, + this._keySystemAccess = s, + this._target = e + } + detachMedia() { + asAsync(this.clearSessions()) + } + createSession(e) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + _mediaKeysSetup() { + return __awaiter$3(this, void 0, void 0, (function*() { + const e = this._keySystemAccess; + e && (this._mediaKeysPromise || (this._mediaKeysPromise = new Promise((s,n)=>__awaiter$3(this, void 0, void 0, (function*() { + var d; + const h = yield e.createMediaKeys(); + try { + yield null === (d = this._target) || void 0 === d ? void 0 : d.setMediaKeys(h), + this._mediaKeys = h + } catch (F) { + this.dispatchKeyError(F), + n(F) + } + if (this.isWidevine) { + const e = yield this.loadCertificateBuffer(); + yield h.setServerCertificate(e) + } + s(h) + } + )))), + yield this._mediaKeysPromise) + } + )) + } + createSessionAndGenerateRequest(e, s, n=!1) { + var d; + return __awaiter$3(this, void 0, void 0, (function*() { + if (!n && this.mediaKeySessions[e]) + return; + Mr.debug(`createSessionAndGenerateRequest for item ${s.title}, isRenewal ${n}`); + const h = null === (d = this._mediaKeys) || void 0 === d ? void 0 : d.createSession() + , {keySystem: p} = this; + if (!h) + return; + this.addMediaKeySessionInfo(e, h, s); + const y = (e=>{ + if (e.includes("data")) { + const [s,n] = e.split(","); + return n + } + return e + } + )(e) + , m = ze(y) + , g = this.isWidevine && s.isSong || 16 === m.length; + let v; + var _; + return Mr.debug("extracted uri", e), + this.isPlayReady && !g ? (Mr.debug("handling Playready object"), + h.extURI = e, + _ = m, + v = concatenate(Uint8Array, new Uint8Array(Nr), _)) : g ? (Mr.debug("handling keyId only initData"), + h.extURI = "data:;base64," + Ye(m), + v = ((e,s)=>{ + const n = $r[s]; + if (!n) + return Mr.warn("No pssh generator for ", s), + e; + return n(Uint8Array.from(e)) + } + )(m, p)) : (Mr.debug("handling pssh initData"), + h.extURI = e, + v = m), + h.addEventListener("message", this.startLicenseSession), + h.generateRequest("cenc", v).catch(e=>{ + if (e.message.match(/generateRequest.*\(75\)/)) + return h.generateRequest("cenc", v); + throw e + } + ) + } + )) + } + handleLicenseJson(e, s, n) { + const d = Object.create(null, { + handleLicenseJson: { + get: ()=>super.handleLicenseJson + } + }); + var h; + return __awaiter$3(this, void 0, void 0, (function*() { + if (!e) + return; + const p = this.mediaKeySessions[n]; + if (!p) + return void Mr.debug("media key session does not exist, not updating"); + const y = e["renew-after"]; + if (e.license && y) { + Mr.debug("Got renew after value", y, n); + const e = this._mediaKeySessionRenewals + , d = e[s.sessionId]; + d && clearTimeout(d), + e[s.sessionId] = setTimeout(()=>this._renewMediaKeySession(p, n), 1e3 * y) + } + yield d.handleLicenseJson.call(this, e, s, n); + const m = null === (h = this.mediaKeySessions[n]) || void 0 === h ? void 0 : h.oldSession; + m && (Mr.debug("removing old key session after updating", n), + yield this._removeAndCloseSession(m), + delete this.mediaKeySessions[n].oldSession, + delete this._mediaKeySessionRenewals[m.sessionId]) + } + )) + } + _renewMediaKeySession(e, s) { + delete this._mediaKeySessionRenewals[e.session.sessionId], + asAsync(this.createSessionAndGenerateRequest(s, e.item, !0)) + } + loadKeys(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this._mediaKeysSetup(); + const n = this.filterKeyValues(e); + for (const e of n) { + const {dataUri: n} = e; + yield this.createSessionAndGenerateRequest(n, s) + } + if (null == s ? void 0 : s.isLiveAudioStation) { + const e = Object.keys(this.mediaKeySessions) + , s = n.reduce((e,s)=>(e[s.dataUri] = !0, + e), {}); + for (const n of e) + s[n] || (yield this._scheduleRemoveSession(n)) + } + } + )) + } + filterKeyValues(e) { + let s; + if (1 === e.length) + s = e; + else { + const n = Dr[this.keySystem]; + s = e.filter(e=>e.keyFormat === n) + } + return s + } + clearSessions(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const s = this.mediaKeySessions; + if (null == e ? void 0 : e.length) { + const s = this.filterKeyValues(e); + for (const e of s) { + const s = e.dataUri; + clearTimeout(this._sessionRemovalTimeouts[s]), + yield this._removeSessionImmediately(s) + } + } else { + Object.values(this._sessionRemovalTimeouts).forEach(e=>clearTimeout(e)), + Mr.debug("clearing key sessions", s); + for (const e of Object.keys(s)) + yield this._removeSessionImmediately(e) + } + } + )) + } + _scheduleRemoveSession(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (!this.mediaKeySessions[e]) + return void Mr.warn("no session for dataUri, not scheduling remove", e); + if (this._sessionRemovalTimeouts[e]) + return; + const s = setTimeout(()=>{ + asAsync(this._removeSessionImmediately(e)) + } + , 6e4); + Mr.debug("deferring removal of keysession for dataUri", e), + this._sessionRemovalTimeouts[e] = s + } + )) + } + _removeSessionImmediately(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const s = this.mediaKeySessions[e]; + if (!s) + return void Mr.warn("no session for dataUri, not removing", e); + Mr.debug("removing keysession for", e); + const {session: n, oldSession: d} = s; + this._clearSessionRenewal(n), + delete this.mediaKeySessions[e], + yield this._removeAndCloseSession(n), + d && (yield this._removeAndCloseSession(d)) + } + )) + } + _removeAndCloseSession(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + e.removeEventListener("message", this.startLicenseSession), + Mr.debug("tearing down session", e.sessionId); + try { + yield e.remove() + } catch (bt) { + Mr.warn("Error invoking session.remove()", bt) + } finally { + try { + yield e.close() + } catch (bt) { + Mr.warn("Error invoking session.close()", bt) + } + } + } + )) + } + _clearSessionRenewal(e) { + const s = this._mediaKeySessionRenewals[e.sessionId]; + s && (Mr.debug("clearing scheduled license renewal for session", e.sessionId), + clearTimeout(s), + delete this._mediaKeySessionRenewals[e.sessionId]) + } + } + const jr = createLocalStorageFlag("mk-safari-modern-eme"); + class MediaExtension extends Notifications { + constructor(e, s) { + super([zs.playbackLicenseError, zs.playbackSessionError]), + this.audio = e, + this.contentType = s, + Fe.isIE || Fe.isSafari && Fe.engineMajorVersion + } + get hasMediaKeySupport() { + return hasMediaKeySupport() + } + get hasMediaSession() { + return void 0 !== this._session + } + get isFairplay() { + return this._session.isFairplay + } + set extURI(e) { + this._session.extURI = e + } + set initiated(e) { + this._session.initiated = e + } + get session() { + return this._session + } + clearSessions(e) { + var s; + return __awaiter$3(this, void 0, void 0, (function*() { + return null === (s = this.session) || void 0 === s ? void 0 : s.clearSessions(e) + } + )) + } + initializeKeySystem() { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this._attachSession(); + const {_session: e} = this; + e && [zs.playbackLicenseError, zs.playbackSessionError].forEach(s=>{ + e.addEventListener(s, e=>{ + this.dispatchEvent(s, e) + } + ) + } + ) + } + )) + } + _attachSession() { + var e, s, n; + return __awaiter$3(this, void 0, void 0, (function*() { + const {audio: d, contentType: h} = this; + if (null === (e = window.WebKitMediaKeys) || void 0 === e ? void 0 : e.isTypeSupported(kr.FAIRPLAY + ".1_0", qs.MP4)) { + let e; + if (!!jr.json() && this.hasMediaKeySupport) { + const s = [{ + initDataTypes: ["skd"], + audioCapabilities: [{ + contentType: h, + robustness: "" + }], + distinctiveIdentifier: "not-allowed", + persistentState: "not-allowed", + sessionTypes: ["temporary"] + }] + , [,n] = yield findMediaKeySystemAccess([kr.FAIRPLAY], s); + e = n + } + e ? (O.warn("media-extension: Using Fairplay modern EME"), + this._session = new FairplayEncryptedSession, + this._session.attachMedia(d, e)) : (O.warn("media-extension: Using Fairplay legacy EME"), + this._session = new WebKitSession, + this._session.attachMedia(d, { + keySystem: kr.FAIRPLAY + })) + } else if (null === (s = window.MSMediaKeys) || void 0 === s ? void 0 : s.isTypeSupported(kr.PLAYREADY, qs.MP4)) + this._session = new MSSession, + this._session.attachMedia(d, { + keySystem: kr.PLAYREADY + }); + else if (this.hasMediaKeySupport && d.canPlayType(h)) { + this._session = new PreloadingEncryptedSession; + const e = [{ + initDataTypes: ["cenc", "keyids"], + audioCapabilities: [{ + contentType: h + }], + distinctiveIdentifier: "optional", + persistentState: "required" + }] + , s = potentialKeySystemsForAccess() + , [,p] = yield findMediaKeySystemAccess(s, e); + p ? null === (n = this._session) || void 0 === n || n.attachMedia(d, p) : O.warn("media-extension: No keysystem detected!") + } + } + )) + } + setMediaItem(e) { + !function(e, s) { + s.keyURLs && (e.developerToken = Rr.developerToken, + e.userToken = Rr.musicUserToken, + e.item = s, + e.adamId = s.songId, + e.isLibrary = s.isCloudItem, + e.setKeyURLs(s.keyURLs)) + }(this._session, e) + } + destroy(e) { + this._session && this._session.detachMedia(e) + } + } + const Br = createLocalStorageFlag("mk-force-audio-mse") + , shouldForceAudioMse = ()=>!!Br.json(); + class ByteRangeSegment { + constructor({url: e, startByte: s, length: n, isInitSegment: d=!1}) { + this.url = e, + this.isInitSegment = d, + this.startByte = parseInt(s, 10), + this.length = parseInt(n, 10), + this.endByte = this.startByte + this.length - 1, + this.range = `bytes=${this.startByte}-${this.endByte}` + } + load() { + return __awaiter$3(this, void 0, void 0, (function*() { + const {url: e, range: s} = this; + if (!e) + return new Uint8Array; + const n = new Headers; + n.append("Range", s); + const d = yield fetch(e, { + headers: n + }) + , h = yield d.arrayBuffer(); + return new Uint8Array(h) + } + )) + } + } + class ContinuousSegment { + constructor(e, s=!1) { + this.url = e, + this.isInitSegment = s + } + load() { + return __awaiter$3(this, void 0, void 0, (function*() { + const {url: e} = this; + if (!e) + return new Uint8Array; + O.debug("radio-segment: loading", e); + const s = yield fetch(e) + , n = yield s.arrayBuffer(); + return new Uint8Array(n) + } + )) + } + } + const Kr = /^#EXT-X-BYTERANGE:([^\n]+)\n/gim + , Fr = /^#EXT-X-MAP:([^\n]+)\n/im + , Vr = /#EXTINF:\d*\.\d*\,[\n](.+)|^#EXT-X-MAP:URI="([^"]*)"/gim + , Hr = /#EXTINF:\d*\.\d*,\s*#EXT-X-BITRATE:\d{1,3}[\n](.+)|^#EXT-X-MAP:URI="([^"]*)"/gim; + class SegmentList { + constructor() { + this._segments = [], + this._addedSegments = {} + } + get segments() { + return this._segments + } + addSegment(e, s) { + this._addedSegments[s] || (O.debug("Adding segment", s), + this._segments.push(e), + this._addedSegments[s] = !0) + } + extractLiveRadioSegments(e, s) { + this._extractContinuousSegments(Vr, e, s) + } + extractHlsOffersSegments(e, s) { + this._extractContinuousSegments(Hr, e, s) + } + _extractContinuousSegments(e, s, n) { + if (!s || !e.test(s)) + return; + let d; + for (e.lastIndex = 0; d = e.exec(s); ) { + const e = d[0].startsWith("#EXT-X-MAP") ? d[2] : d[1] + , s = rewriteLastUrlPath(n, e) + , h = d[0].startsWith("#EXT-X-MAP"); + this.addSegment(new ContinuousSegment(s,h), e) + } + } + extractByteRangeSegments(e, s) { + var n, d; + if (!e || !Kr.test(e)) + return; + const h = function(e) { + if (!e || !Fr.test(e)) + return; + const [,s] = e.match(Fr); + return s.split(",").reduce((e,s)=>{ + const [n,d] = s.split("="); + return e[n.toLowerCase()] = d.replace(/\"/gi, ""), + e + } + , {}) + }(e) + , p = null !== (n = s.split("/").pop()) && void 0 !== n ? n : "" + , y = s.replace(p, h.uri) + , [m,g] = h.byterange.split("@") + , v = new ByteRangeSegment({ + url: y, + startByte: g, + length: m + }); + this.addSegment(v, v.range), + (null !== (d = e.match(Kr)) && void 0 !== d ? d : []).forEach(e=>{ + const [,s,n] = e.match(/^#EXT-X-BYTERANGE:(\d+)@(\d+)\n/) + , d = new ByteRangeSegment({ + url: y, + startByte: n, + length: s + }); + this.addSegment(d, d.range) + } + ) + } + } + var zr; + !function(e) { + e.keysParsed = "keysParsed" + }(zr || (zr = {})); + const qr = /^#EXT-X-TARGETDURATION:(\d+)/im + , Wr = /^#EXT-X-KEY:[^\n]+URI="([^"]+)"/im + , Yr = /^#EXT-X-KEY:[^\n]+URI="([^"]+)",KEYFORMAT="([^"]+)"/gim; + function loadManifestData(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return (yield fetch(e)).text() + } + )) + } + class Manifest extends Notifications { + constructor(e, s) { + super([zs.manifestParsed, zr.keysParsed]), + this._downlink = 0, + this._segmentList = new SegmentList, + this._data = e, + this._item = s, + this._url = s.assetURL + } + parse() { + const e = this._item + , s = this._data; + if (Sr !== kr.FAIRPLAY || shouldForceAudioMse()) + if (this._detectKeyTags(), + e.hasOffersHlsUrl) + this._segmentList.extractHlsOffersSegments(s, e.assetURL); + else if (e.isLiveRadioStation) { + this._segmentList.extractLiveRadioSegments(s, e.assetURL); + const [,n] = this._data.match(qr); + O.debug(`manifest: setting up manifest refresh interval at ${n} seconds`); + const d = 1e3 * parseInt(n, 10); + this._manifestRefreshInterval = setInterval(this.liveRadioRefresh, d) + } else + this._segmentList.extractByteRangeSegments(s, e.assetURL) + } + static load(e, s=!0) { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("loading manifest for item", e.title); + const n = e.assetURL; + let d; + const h = !!window.sessionStorage && s; + if (h && (d = window.sessionStorage.getItem(n), + d)) + return new this(d,e); + const p = (new Date).getTime(); + d = yield loadManifestData(n); + const y = new this(d,e); + return y.downlink = function(e, s) { + return 8 * s.length / (((new Date).getTime() - e) / 1e3) / 1024 + }(p, d), + h && window.sessionStorage.setItem(n, d), + Promise.resolve(y) + } + )) + } + get downlink() { + return this._downlink + } + set downlink(e) { + this._downlink = e + } + get mediaItem() { + return this._item + } + liveRadioRefresh() { + return __awaiter$3(this, void 0, void 0, (function*() { + const e = yield loadManifestData(this._url); + this._data = e, + this._detectKeyTags(), + this._segmentList.extractLiveRadioSegments(e, this._url), + this.dispatchEvent(zs.manifestParsed) + } + )) + } + segmentsForTimeRange(e) { + const s = Math.floor(e.start / 10) + 1 + , n = Math.floor(e.end / 10) + 1 + , {segments: d} = this; + return [d[0], ...d.slice(s, n + 1)] + } + get segments() { + return this._segmentList.segments + } + get extURI() { + if (!this._extURI) { + const e = this._data.match(Wr); + O.debug("manifest: EXT_X_KEY_URI matches", e), + this._extURI = e && e[1] || void 0 + } + return this._extURI + } + get keyValues() { + let e = this._modernKeys; + return e.length || (e = this._legacyKeys), + e + } + _detectKeyTags() { + const e = this.keyValues; + e.length && this.dispatchEvent(zr.keysParsed, { + item: this.mediaItem, + keys: e + }) + } + get _legacyKeys() { + const e = this._data.match(Wr); + O.debug("manifest: EXT_X_KEY_URI matches", e); + const s = e && e[1] || void 0; + this._extURI = s; + const n = []; + return s && n.push({ + keyFormat: Ws.WIDEVINE, + dataUri: s + }), + n + } + get _modernKeys() { + let e; + Yr.lastIndex = 0; + const s = []; + for (; e = Yr.exec(this._data); ) { + const [n,d,h] = e; + s.push({ + keyFormat: h, + dataUri: d + }) + } + return s + } + stop() { + this._manifestRefreshInterval && clearInterval(this._manifestRefreshInterval) + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", Promise)], Manifest.prototype, "liveRadioRefresh", null); + const Gr = "seamlessAudioTransition" + , Qr = "bufferTimedMetadataDidChange" + , Jr = isNodeEnvironment$1() ? require("util").TextDecoder : self.TextDecoder; + function encodedArrayToString(e, s="utf-8") { + if ("iso-8859-1" === s) + return String.fromCharCode(...e); + return new Jr(s).decode(e) + } + function readNullTerminatedString(e, s=0, n) { + const d = []; + n = null != n ? n : e.length; + for (let h = s; h < n; h++) { + const s = e[h]; + if ("\0" === String.fromCharCode(s)) + break; + d.push(String.fromCharCode(s)) + } + return [d.join(""), d.length] + } + function isBitAtPositionOn(e, s) { + return 0 != (e & 1 << s) + } + class BaseMp4Box { + constructor(e, s, n, d) { + this.id = e, + this.data = s, + this.start = n, + this.end = d + } + get size() { + return this.end - this.start + } + get rawBytes() { + return this.data.slice(this.start, this.end) + } + } + const Xr = [237, 239, 139, 169, 121, 214, 74, 206, 163, 200, 39, 220, 213, 29, 33, 237]; + class PsshBox extends BaseMp4Box { + constructor(e, s, n) { + super("pssh", e, s, n), + this.view = new DataView(e.buffer,s) + } + get systemId() { + const {data: e, start: s} = this + , n = s + 12; + return e.slice(n, n + 16) + } + get dataSize() { + return this.view.getUint32(28) + } + get psshData() { + const {data: e, start: s, dataSize: n} = this + , d = s + 32; + return e.slice(d, d + n) + } + get keyBytes() { + const {psshData: e} = this; + return e.slice(2, 18) + } + get isWidevine() { + return arrayEquals(this.systemId, Xr) + } + } + class TencBox extends BaseMp4Box { + constructor(e, s, n) { + super("tenc", e, s, n), + this.data = e, + this.start = s, + this.end = n + } + get isProtected() { + const {data: e, start: s} = this; + return e[s + 14] + } + get defaultKeyId() { + const {data: e, start: s} = this; + return e.slice(s + 16, s + 32) + } + set defaultKeyId(e) { + const {data: s, start: n} = this; + for (let d = 0; d < e.length; d++) + s[d + n + 16] = e[d] + } + } + function findBox(e, s, n=[]) { + for (let d = s; d < e.length; ) { + if (0 === n.length) + return; + const s = new DataView(e.buffer,d).getUint32(0) + , h = encodedArrayToString(e.subarray(d + 4, d + 8)) + , p = d + s; + if (1 === n.length && h === n[0]) + return new BaseMp4Box(h,e,d,p); + if (h === n[0]) + return findBox(e, d + 8, n.slice(1)); + d += s + } + } + const rewriteDefaultKid = e=>{ + const [s] = function(e) { + const s = findBox(e, 0, ["moov", "trak", "mdia", "minf", "stbl", "stsd"]) + , n = []; + if (!s) + return n; + for (let d = s.start + 16; d < s.end; ) { + let h = findBox(e, d, ["enca"]) + , p = 36; + if (h || (h = findBox(e, d, ["encv"]), + p = 86), + !h) + return n; + const y = findBox(e, h.start + p, ["sinf", "schi", "tenc"]); + y ? (n.push(new TencBox(y.data,y.start,y.end)), + d = y.end) : d = s.end + } + return n + }(e); + if (!s) + return; + const n = function(e) { + const s = findBox(e, 0, ["moov"]) + , n = []; + if (!s) + return n; + const d = new DataView(e.buffer,0); + for (let h = s.start + 8; h < s.size; ) { + const s = d.getUint32(h); + "pssh" === encodedArrayToString(e.subarray(h + 4, h + 8)) && n.push(new PsshBox(e,h,h + s)), + h += s + } + return n + }(e).find(e=>e.isWidevine); + n && (s.defaultKeyId = n.keyBytes) + } + ; + function readSynchSafeUint32(e) { + return 2097152 * (127 & e[0]) + 16384 * (127 & e[1]) + 128 * (127 & e[2]) + (127 & e[3]) + } + const Zr = { + 0: "iso-8859-1", + 1: "utf-16", + 2: "utf-16be", + 3: "utf-8" + } + , en = { + TPE1: !0, + TIT2: !0, + WXXX: !0, + PRIV: !0, + TALB: !0, + CHAP: !0 + }; + class ID3 { + constructor(e) { + this.frames = [], + this.unsynchronized = !1, + this.hasExtendedHeader = !1, + this.hasFooter = !1, + this.isExperimental = !1; + let s = 0; + const n = He(e.subarray(s, s + 3)); + if (s += 3, + "ID3" !== n) + return; + this.minor = e[s++], + this.revision = e[s++]; + const d = e[s++]; + this._parseID3Flags(d); + const h = readSynchSafeUint32(e.subarray(s, s + 4)); + s += 4, + this.frameLength = h; + const p = s + h; + if (this.endPos = p, + this.hasExtendedHeader) { + s += readSynchSafeUint32(e.subarray(s, s + 4)) + } + this.minor > 2 && this._parseID3Frames(this, e, s, p) + } + _parseID3Flags(e) { + this.unsynchronized = isBitAtPositionOn(e, 7), + this.hasExtendedHeader = isBitAtPositionOn(e, 6), + this.isExperimental = isBitAtPositionOn(e, 5), + this.hasFooter = isBitAtPositionOn(e, 4) + } + _parseID3Frames(e, s, n, d) { + const h = new DataView(s.buffer,0,d) + , {minor: p} = this; + for (; n + 8 <= d; ) { + const y = He(s.subarray(n, n + 4)); + n += 4; + const m = 4 === p ? readSynchSafeUint32(s.subarray(n, n + 4)) : h.getUint32(n); + if (n += 4, + s[n++], + s[n++], + en[y]) { + const h = n + , p = this._extractID3FramePayload(s, y, m, h, d); + if (p) { + const s = this.decodeID3Frame(p); + s && e.frames.push(s) + } + n += m + } else + n += m + } + } + _extractID3FramePayload(e, s, n, d, h) { + const p = d + n; + let y; + return p <= h && (y = { + type: s, + size: n, + data: e.slice(d, p) + }), + y + } + decodeID3Frame(e) { + if ("TXXX" !== e.type) + return "WXXX" === e.type ? this.decodeWxxxFrame(e) : "PRIV" === e.type ? this.decodePrivFrame(e) : "CHAP" === e.type ? this.decodeChapFrame(e) : "T" === e.type[0] ? this.decodeTextFrame(e) : { + key: e.type, + data: e.data + } + } + decodeChapFrame(e) { + const {data: s} = e + , n = new DataView(s.buffer) + , d = { + key: "CHAP", + frames: [] + }; + let[h,p] = readNullTerminatedString(s, 0, s.length); + return d.id = h, + p++, + d.startTime = n.getUint32(p), + p += 4, + d.endTime = n.getUint32(p), + p += 4, + p += 4, + p += 4, + this._parseID3Frames(d, s, p, s.length), + d + } + decodeTextFrame(e) { + const {data: s} = e + , n = Zr[s[0]] + , d = encodedArrayToString(s.subarray(1), n); + return { + key: e.type, + text: d + } + } + decodeWxxxFrame(e) { + const {data: s} = e + , n = Zr[s[0]]; + let d = 1; + const h = encodedArrayToString(s.subarray(d), n); + d += h.length + 1; + return { + key: "WXXX", + description: h, + text: encodedArrayToString(s.subarray(d)) + } + } + decodePrivFrame(e) { + const s = encodedArrayToString(e.data); + if (!s) + return; + return { + key: "PRIV", + info: s, + data: e.data.slice(s.length + 1) + } + } + } + function checkBoxName(e, s, n) { + return !(s + 4 > e.length) && (e[s] === n[0] && e[s + 1] === n[1] && e[s + 2] === n[2] && e[s + 3] === n[3]) + } + function findEmsgs(e) { + const s = e.length + , n = []; + if (function(e) { + return (null == e ? void 0 : e.length) >= 8 && checkBoxName(e, 4, [102, 116, 121, 112]) + }(e)) + return n; + for (let d = 0; d < s; d++) { + if (checkBoxName(e, d, [109, 111, 111, 102])) + return n; + if (checkBoxName(e, d, [101, 109, 115, 103])) { + const s = d - 4 + , h = new DataView(e.buffer,s).getUint32(0) + , p = e.subarray(s, s + h); + d = d + h - 1, + n.push(p) + } + } + return n + } + const tn = { + TALB: "album", + TIT2: "title", + TPE1: "performer" + } + , sn = ["performer", "title", "album"]; + class TimedMetadata { + constructor(e) { + this.links = [], + this.storefrontToIds = {}, + e.forEach(e=>{ + var s, n; + const {key: d} = e + , h = tn[d]; + if (h) + this[h] = null === (s = e.text) || void 0 === s ? void 0 : s.replace(/\0/g, ""); + else if ("WXXX" === e.key) { + if (e.description) { + const [s,n] = e.description.split("\0"); + this.links.push({ + description: s, + url: n + }) + } + } else if ("PRIV" === e.key) { + const s = null === (n = e.info) || void 0 === n ? void 0 : n.split("\0"); + if (s && s.length && s[0].startsWith("com.apple.radio.adamid")) { + s[1].split(",").forEach(e=>{ + const [s,n] = e.split(":"); + s && n && "0" !== n && !hasOwn(this.storefrontToIds, s) && (this.storefrontToIds[s] = n) + } + ) + } + } + } + ) + } + resolveAdamIdFromStorefront(e) { + const s = this.storefrontToIds[e]; + this._adamId = s + } + get adamId() { + return this._adamId + } + equals(e) { + if (!sn.every(s=>this[s] === e[s])) + return !1; + const {links: s} = this + , n = e.links; + if (s.length !== n.length) + return !1; + for (let d = 0; d < s.length; d++) { + const e = s[d].description === n[d].description + , h = s[d].url === n[d].url; + if (!e || !h) + return !1 + } + return !0 + } + } + class Emsg { + constructor(e) { + this.data = e; + const s = new DataView(e.buffer); + let n = 8; + if (1 !== e[n]) + return; + n += 4, + this.timeScale = s.getUint32(n), + n += 4; + const d = s.getUint32(n); + n += 4; + const h = s.getUint32(n); + if (n += 4, + this.presentationTime = Math.pow(2, 32) * d + h, + !Number.isSafeInteger(this.presentationTime)) + throw this.presentationTime = Number.MAX_SAFE_INTEGER, + new Error("Failed to create 64 bit integer"); + this.eventDuration = s.getUint32(n), + n += 4, + this.id = s.getUint32(n), + n += 4; + const [p,y] = readNullTerminatedString(e, n); + n += y + 1, + this.schemeIdUri = p; + const [m,g] = readNullTerminatedString(e, n); + n += g + 1, + this.payload = e.subarray(n, e.byteLength), + this.id3 = new ID3(this.payload) + } + get length() { + return this.data.length + } + get elementPresentationTime() { + const {presentationTime: e, timeScale: s} = this; + return e && s ? Math.round(e / s) : NaN + } + get timedMetadata() { + var e; + if (this._timedMetadata) + return this._timedMetadata; + const s = null === (e = this.id3) || void 0 === e ? void 0 : e.frames; + return s ? (this._timedMetadata = new TimedMetadata(s), + this._timedMetadata) : void 0 + } + } + class TimedMetadataManager { + constructor(e, s) { + this._currentTime = e, + this._onDidChange = s, + this._emsgLookup = {}, + this._getCurrentEmsg = this._getCurrentEmsg.bind(this) + } + processEmsgs(e) { + const s = findEmsgs(e); + s.length && (this._currentEmsgInterval || (this._currentEmsgInterval = setInterval(this._getCurrentEmsg, 1e3)), + s.forEach(e=>{ + const s = new Emsg(e); + this._emsgLookup[s.elementPresentationTime] = s + } + )) + } + stop() { + const {_currentEmsgInterval: e} = this; + e && clearInterval(e) + } + _getCurrentEmsg() { + const {_currentTime: e, _emsgLookup: s} = this + , n = Math.round(e()) + , d = [] + , h = Object.keys(s); + for (let y = 0; y < h.length; y++) { + const e = parseInt(h[y], 10); + if (!(e < n)) + break; + d.push(e) + } + const p = d.pop(); + if (p) { + const e = s[p]; + if (!e) + return; + const {_currentEmsg: n, _onDidChange: d} = this + , h = null == n ? void 0 : n.payload + , y = e.payload; + h && arrayEquals(h, y) || (this._currentEmsg = e, + d(e)), + this._cleanupEmsgs(p) + } + } + _cleanupEmsgs(e) { + const {_emsgLookup: s} = this; + Object.keys(s).forEach(n=>{ + parseInt(n, 10) < e && delete s[n] + } + ) + } + } + class SegmentProcessor { + constructor(e, s, n) { + this._item = e, + this._timedMetadataManager = new TimedMetadataManager(()=>s.currentTime,e=>{ + n.publish(Qr, e.timedMetadata) + } + ) + } + process(e, s) { + const {_item: n} = this; + try { + n.isLiveRadioStation ? this._processLiveRadioSegment(s) : n.hasOffersHlsUrl && this._processHlsOffersSegment(e, s) + } catch (bt) { + O.error("Error processing segment", bt) + } + } + stop() { + this._timedMetadataManager.stop() + } + _processHlsOffersSegment(e, s) { + e.isInitSegment && rewriteDefaultKid(s) + } + _processLiveRadioSegment(e) { + this._timedMetadataManager.processEmsgs(e) + } + } + const rn = new Logger({ + levelFilterStorageKey: "mk-mse-buffer", + topic: "mse-buffer" + }) + , nn = createLocalStorageFlag("mk-mse-buffer").get() + , {manifestParsed: an} = zs; + class MseBuffer { + constructor({dispatcher: e, element: s, manifest: n, currentTime: d, duration: h, clip: p}) { + this.firstSegmentLoadPromise = Promise.resolve(), + this.hasKickstarted = !1, + this.segmentIndexToFetch = -1, + this.timeToTrim = 10, + this.isAtEndOfStream = !1, + this.isFullyBuffered = !1, + this.deferredRemoves = [], + this.currentTimestampOffset = 0, + this.dispatcher = e, + this.clip = p, + this.element = s, + this.mediaSource = new MediaSource, + this.mediaSource.addEventListener("sourceopen", this.onSourceOpen), + this.segmentProcessor = new SegmentProcessor(n.mediaItem,s,e), + this.playbackTimeline = { + current: { + manifest: n + } + }, + n.addEventListener(an, this.onManifestParsed), + this._currentTime = d || 0, + this.duration = h, + window.mseBuffer = this + } + onSourceOpen() { + rn.debug("mediaSource open handler"); + const {mediaSource: e} = this; + if (e.activeSourceBuffers.length > 0) + return void rn.debug("not adding new source buffer"); + rn.debug("adding new source buffer"); + const s = e.addSourceBuffer('audio/mp4;codecs="mp4a.40.2"'); + this.sourceBuffer = s, + s.addEventListener("updateend", this.updateEndHandler); + const {clip: n, hasAppendWindowSupport: d} = this; + n && (d ? (rn.debug("appendWindowStart/End", n.start, n.end), + s.appendWindowStart = n.start, + s.appendWindowEnd = n.end) : (rn.debug("seeking for clip", n.start), + asAsync(this.seek(n.start)))), + this.updateSegmentToFetch(0, !0) + } + setNextManifest(e) { + rn.debug("setting next manifest for ", e.mediaItem.title), + this.nextSeamlessTransition ? (rn.debug("abandoning transition scheduled for " + this.nextSeamlessTransition), + this.revertSeamlessTransition(!0), + this.playbackTimeline.next = { + manifest: e + }) : (this.playbackTimeline.next = { + manifest: e + }, + this.isFullyBuffered && (rn.debug("current song is fully buffered, beginning transition to next"), + this.transitionToNextManifest())) + } + isItemPlaying(e) { + var s, n; + const {playbackTimeline: d} = this + , h = this.nextSeamlessTransition ? null === (s = d.previous) || void 0 === s ? void 0 : s.manifest.mediaItem : null === (n = d.current) || void 0 === n ? void 0 : n.manifest.mediaItem; + return !!h && (rn.debug(`isItemPlaying ${e.title}, ${h.title}, ${e.id === h.id}`), + e.id === h.id) + } + get currentItem() { + return this.manifest.mediaItem + } + get playableUrl() { + let e = this._playableUrl; + return e || (e = window.URL.createObjectURL(this.mediaSource), + rn.debug("created url", e), + this._playableUrl = e, + e) + } + get segments() { + const {manifest: e, clip: s} = this; + return s ? e.segmentsForTimeRange(s) : e.segments || [] + } + get currentTime() { + return this._currentTime + } + set currentTime(e) { + var s, n; + if (e += this.currentTimestampOffset, + this._currentTime === e) + return; + const {nextSeamlessTransition: d} = this; + if (d && e >= d) { + rn.debug("setting offset to", d), + this.currentTimestampOffset = d || 0, + this.nextSeamlessTransition = void 0, + this.duration = this.manifest.mediaItem.playbackDuration / 1e3, + rn.debug("buffer setting duration to", this.duration); + const e = { + previous: null === (n = null === (s = this.playbackTimeline.previous) || void 0 === s ? void 0 : s.manifest) || void 0 === n ? void 0 : n.mediaItem, + current: this.manifest.mediaItem + }; + rn.debug("dispatching seamless audio transition", e), + this.dispatcher.publish(Gr, e) + } + this._currentTime = e; + const {isOverBufferLimit: h, timeToTrim: p} = this + , y = e > this.timeToTrim; + h && y && (rn.debug("buffer over limit, trimming to ", p), + this.removeToTime(p), + this.timeToTrim += 10) + } + get hasAppendWindowSupport() { + var e; + return void 0 !== (null === (e = this.sourceBuffer) || void 0 === e ? void 0 : e.appendWindowStart) + } + seek(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const {duration: s, seekWhenUpdated: n, sourceBuffer: d} = this; + if (this.resolveSeekPromise(!1), + rn.debug("seek to ", e), + (e = +e) > s && (rn.debug("rounding seek time to duration", e, s), + e = s), + !d) + return !1; + if (this.revertSeamlessTransition(), + d.updating) + return rn.debug("sourcebuffer updating, deferring seek"), + new Promise(s=>{ + n && n.resolve(!1), + this.seekWhenUpdated = { + seek: this.seek.bind(this, e), + resolve: s + } + } + ); + this.currentlyLoadingSegmentIndex = void 0, + this.updateSegmentToFetch(0, !0), + this.removeToTime(e), + this.timeToTrim = 10 * Math.floor(e / 10); + const h = this.getSegmentForTime(e); + 0 !== h && (yield this.firstSegmentLoadPromise), + rn.debug("seeking to", e, "segment", h), + this.updateSegmentToFetch(h, !0); + const p = new Promise(s=>{ + this.seekResolver = { + time: e, + resolve: s + } + } + ); + return this.checkSeekBuffered(), + p + } + )) + } + clearNextManifest() { + this.revertSeamlessTransition(!0), + this.playbackTimeline.next = void 0 + } + revertSeamlessTransition(e=!1) { + const {playbackTimeline: s, nextSeamlessTransition: n} = this; + if (!n || !s.previous) + return void rn.debug("no need to revert, no transition"); + this.isAtEndOfStream = e, + rn.debug("reverting seamless transition with discardNextManifest", e), + e ? this.clearBufferToEnd(n) : this.clearBuffer(), + rn.debug("abandoning transition to " + this.manifest.mediaItem.title), + s.next = e ? void 0 : s.current, + s.current = s.previous, + s.previous = void 0; + const d = this.manifest.mediaItem; + rn.debug("current item reverted to " + d.title), + this.nextSeamlessTransition = void 0, + this.duration = d.playbackDuration / 1e3, + rn.debug("reverted duration to " + this.duration), + e || (this.currentTimestampOffset = 0, + this.timestampOffsetAdjustment = 0, + rn.debug("reverted currentTimestampOffset and timestampOffsetAdjustment to 0")), + this.printInfo(), + this.segmentIndexToFetch = -1 + } + get streamHasEnding() { + return !this.manifest.mediaItem.isLiveRadioStation + } + stop() { + this.segmentProcessor.stop(), + this.setEndOfStream(), + this.remove() + } + remove() { + var e; + rn.debug("removing sourceBuffer and mediaSource"); + const {sourceBuffer: s, mediaSource: n} = this; + null === (e = this.seekResolver) || void 0 === e || e.resolve(!1), + this.manifest.removeEventListener(an, this.onManifestParsed); + const d = this._playableUrl; + d && (rn.debug("revoking url", d), + window.URL.revokeObjectURL(d)), + n.removeEventListener("sourceopen", this.onSourceOpen), + s && (s.removeEventListener("updateend", this.updateEndHandler), + this.sourceBuffer = void 0) + } + onManifestParsed() { + const e = this.segmentIndexToFetch + 1; + rn.debug("manifestParsed, loading segment", e), + this.updateSegmentToFetch(e, !0) + } + updateEndHandler() { + if (this.kickstartBuffer(), + this.clearDeferredRemove()) + return; + if (rn.debug("update end", this.seekWhenUpdated), + this.seekWhenUpdated) { + rn.debug("updateEndHandler resolving seekWhenUpdated"); + const {seekWhenUpdated: e} = this; + return asAsync(e.seek().then(e.resolve)), + void (this.seekWhenUpdated = void 0) + } + this.checkSeekBuffered(); + const {clip: e, sourceBuffer: s, hasAppendWindowSupport: n} = this; + if (e && s && !n) { + const {buffered: n} = s; + if (this.isTimeBuffered(e.end + 1)) { + const d = n.end(n.length - 1); + return rn.debug("clipping sourcebuffer to", e.end, d), + void s.remove(e.end, d) + } + } + if (this.isAtEndOfStream) + return rn.debug("buffer is at end of stream"), + this.streamHasEnding && (rn.debug("isAtEndOfStream, not fetching any more segments"), + this.playbackTimeline.next || this.setEndOfStream(), + this.transitionToNextManifest()), + void (this.isAtEndOfStream = !1); + rn.debug("updateEndHandler invoking loadSegment"), + asAsync(this.loadSegment()) + } + clearDeferredRemove() { + var e; + if (0 === this.deferredRemoves.length) + return !1; + const s = this.deferredRemoves.shift(); + return null === (e = this.sourceBuffer) || void 0 === e || e.remove(s.start, s.end), + !0 + } + transitionToNextManifest() { + var e; + rn.debug("beginning transition to next manifest"); + const {playbackTimeline: s, sourceBuffer: n} = this; + if (!s.next || !n) + return void rn.debug("no next manifest"); + const d = this.endOfBufferTime || this.currentTimestampOffset; + rn.debug("setting seamless transition at", d), + this.nextSeamlessTransition = d, + this.timestampOffsetAdjustment = d, + this.playbackTimeline.current.endTime = d, + s.previous = s.current, + rn.debug("previous manifest set to", null === (e = s.previous) || void 0 === e ? void 0 : e.manifest.mediaItem.title), + s.current = s.next, + rn.debug("current manifest set to", s.current.manifest.mediaItem.title), + s.next = void 0, + this.updateSegmentToFetch(0, !0), + this.printInfo() + } + updateSegmentToFetch(e, s=!1) { + this.segments.length && e < this.segments.length && e !== this.segmentIndexToFetch && (this.segmentIndexToFetch = e, + s && (rn.debug("updateSegmentToFetch invoking loadSegment"), + asAsync(this.loadSegment()))) + } + loadSegment() { + return __awaiter$3(this, void 0, void 0, (function*() { + const e = this.segmentIndexToFetch + , s = this.segments[e]; + if (e !== this.currentlyLoadingSegmentIndex) { + if (s) + try { + rn.debug("begin loadSegment " + e), + this.currentlyLoadingSegmentIndex = e; + const d = s.load(); + 0 === e && (this.firstSegmentLoadPromise = d); + const h = yield d; + if (0 !== e && e !== this.segmentIndexToFetch) + return void rn.debug("load segment index to fetch changed, not processing bytes for segment", e); + this.segmentProcessor.process(s, h), + rn.debug("loadSegment processed: " + e); + const {sourceBuffer: p, timestampOffsetAdjustment: y} = this; + if (!p) + return; + try { + "number" == typeof y && (rn.debug("adjusting timestampOffset of sourcebuffer to", y), + p.timestampOffset = y, + this.timestampOffsetAdjustment = void 0), + p.appendBuffer(h), + this.isFullyBuffered = !1, + this.isOverBufferLimit = !1, + rn.debug("appended to buffer", h.length), + this.printBufferTimes(), + e === this.segments.length - 1 ? this.isAtEndOfStream = !0 : e === this.segmentIndexToFetch && (rn.debug("loadSegment bumping segment index to fetch to ", e + 1), + this.updateSegmentToFetch(e + 1)) + } catch (n) { + "QuotaExceededError" === n.name ? (this.isOverBufferLimit = !0, + rn.debug("reached buffer limit")) : rn.warn("Error appending to source buffer", n) + } + } catch (bt) { + rn.error("Error loading segment", bt) + } finally { + this.currentlyLoadingSegmentIndex = void 0 + } + } else + rn.debug(`segment ${e} is currently loading, not loading it again`) + } + )) + } + setEndOfStream() { + const {sourceBuffer: e, mediaSource: s} = this; + e && "ended" !== s.readyState && (e.updating || "open" !== s.readyState ? rn.error("Could not end of stream (updating, readyState)", e.updating, s.readyState) : (rn.debug("mediaSource.endOfStream"), + s.endOfStream(), + this.isFullyBuffered = !0)) + } + removeToTime(e) { + rn.debug("removing to time", e), + e > 0 && (this.isTimeBuffered(e) || this.isOverBufferLimit) && this.safeSourceBufferRemove(0, e) + } + safeSourceBufferRemove(e, s) { + const {sourceBuffer: n} = this; + n && (n.updating ? this.deferredRemoves.push({ + start: e, + end: s + }) : n.remove(e, s)) + } + get previousOffset() { + var e, s; + return (null === (s = null === (e = this.playbackTimeline) || void 0 === e ? void 0 : e.previous) || void 0 === s ? void 0 : s.endTime) || 0 + } + get manifest() { + var e; + return null === (e = this.playbackTimeline.current) || void 0 === e ? void 0 : e.manifest + } + checkSeekBuffered() { + const {seekResolver: e, currentTimestampOffset: s} = this; + if (!e) + return; + const {time: n} = e + , d = n + s + , h = this.isTimeBuffered(d); + rn.debug("resolving seek for time, adjustedTime, isBuffered", n, d, h), + this.printBufferTimes(), + h && (rn.debug("resolving seek to true for time:", d), + this.element.currentTime = d, + this.resolveSeekPromise(!0)) + } + resolveSeekPromise(e) { + this.seekResolver && (this.seekResolver.resolve(e), + this.seekResolver = void 0) + } + get endOfBufferTime() { + var e; + const s = null === (e = this.sourceBuffer) || void 0 === e ? void 0 : e.buffered; + return !(!s || !s.length) && s.end(s.length - 1) + } + isTimeBuffered(e) { + var s; + const n = null === (s = this.sourceBuffer) || void 0 === s ? void 0 : s.buffered; + if (!n) + return !1; + for (let d = 0; d < n.length; d++) + if (rn.debug("isTimeBuffered", n.start(d), e, n.end(d)), + e >= n.start(d) && e <= n.end(d)) + return !0; + return !1 + } + clearBufferToEnd(e) { + const {sourceBuffer: s} = this; + if (!s || !s.buffered) + return; + const n = s.buffered.end(s.buffered.length - 1); + this.safeSourceBufferRemove(e, n) + } + clearBuffer() { + const {sourceBuffer: e} = this; + if (!e || !e.buffered) + return; + const s = e.buffered; + for (let n = 0; n < s.length; n++) + this.safeSourceBufferRemove(s.start(n), s.end(n)) + } + get bufferTimesString() { + var e; + const s = null === (e = this.sourceBuffer) || void 0 === e ? void 0 : e.buffered; + if (!s) + return ""; + const n = []; + for (let d = 0; d < s.length; d++) + n.push(`start ${s.start(d)} end: ${s.end(d)}`); + return n.join(",") + } + printBufferTimes() { + nn && rn.debug("buffer times", this.bufferTimesString) + } + getSegmentForTime(e) { + return Math.floor(e / 10) + 1 + } + kickstartBuffer() { + const {hasKickstarted: e, element: s, clip: n} = this + , {buffered: d} = s; + e || (this.manifest.mediaItem.isSong ? n && this.isTimeBuffered(n.start) && (s.currentTime = n.start, + this.hasKickstarted = !0) : d.length && (s.currentTime = d.start(0), + this.hasKickstarted = !0)) + } + printInfo() { + var e, s; + const {playbackTimeline: n} = this; + rn.info("---- Buffer Info ----"), + rn.info("currently buffering item", n.current.manifest.mediaItem.title), + rn.info("next item to buffer", null === (e = n.next) || void 0 === e ? void 0 : e.manifest.mediaItem.title), + rn.info("previously buffered item", null === (s = n.previous) || void 0 === s ? void 0 : s.manifest.mediaItem.title), + rn.info("currentTimestampOffset", this.currentTimestampOffset), + rn.info("currentTime", this.currentTime), + rn.info("duration", this.duration), + rn.info("nextSeamlessTransition", this.nextSeamlessTransition), + rn.info("timestampOffsetAdjustment", this.timestampOffsetAdjustment), + rn.info("buffered times", this.bufferTimesString), + rn.info("isAtEndOfStream", this.isAtEndOfStream), + rn.info("isFullyBuffered", this.isFullyBuffered), + rn.info("segmentIndexToFetch", this.segmentIndexToFetch), + rn.info("segments.length", this.segments.length), + rn.info("---- End Buffer Info ----") + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", void 0)], MseBuffer.prototype, "onSourceOpen", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", void 0)], MseBuffer.prototype, "onManifestParsed", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", void 0)], MseBuffer.prototype, "updateEndHandler", null); + const {mediaPlaybackError: on} = rs; + class AudioPlayer extends BasePlayer { + constructor(e) { + var s; + super(e), + this.currentAudioTrack = void 0, + this.currentTextTrack = void 0, + this.textTracks = [], + this.audioTracks = [], + this.isSeamlessAudioTransitionsEnabled = !1, + this.mediaPlayerType = "audio", + this.isSeamlessAudioTransitionsEnabled = !!(null === (s = null == e ? void 0 : e.bag) || void 0 === s ? void 0 : s.features["seamless-audio-transitions"]), + window.audioPlayer = this + } + get _targetElement() { + return this.audio + } + initializeExtension() { + return __awaiter$3(this, void 0, void 0, (function*() { + this.extension = new MediaExtension(this.audio,'audio/mp4;codecs="mp4a.40.2"'), + yield this.extension.initializeKeySystem(), + this.extension.addEventListener(zs.playbackLicenseError, e=>{ + this._licenseError(), + this._dispatcher.publish(on, e) + } + ), + this.extension.addEventListener(zs.playbackSessionError, e=>{ + this._dispatcher.publish(on, new MKError(MKError.MEDIA_SESSION,e)) + } + ) + } + )) + } + initializeMediaElement() { + return __awaiter$3(this, void 0, void 0, (function*() { + const e = function() { + let e = tr.pop(); + return e ? O.debug(`dom-helpers: retrieving audio tag, ${tr.length} remain`) : (O.debug("dom-helpers: no available audio tags, creating one"), + e = document.createElement("audio")), + e + }(); + e.autoplay = !1, + e.id = "apple-music-player", + e.controls = !1, + e.muted = !1, + e.playbackRate = 1, + e.preload = "metadata", + e.volume = 1, + this.audio = e, + document.body.appendChild(e), + O.debug("initializedMediaElement", e) + } + )) + } + removeEventHandlers() { + this._targetElement.removeEventListener("timeupdate", this.onTimeUpdate), + super.removeEventHandlers() + } + isPlayerSupported() { + return !0 + } + _stopMediaElement() { + const e = Object.create(null, { + _stopMediaElement: { + get: ()=>super._stopMediaElement + } + }); + var s; + return __awaiter$3(this, void 0, void 0, (function*() { + yield e._stopMediaElement.call(this), + yield this.tearDownManifests(), + null === (s = this._buffer) || void 0 === s || s.stop(), + this._buffer = void 0 + } + )) + } + setNextSeamlessItem(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const {extension: s, nextManifest: n} = this + , d = this._buffer; + if (!d || !s) + return; + if ((null == n ? void 0 : n.mediaItem.id) === e.id) + return void O.debug("already have next manifest for ", e.title); + this._targetElement.removeEventListener("timeupdate", this.onTimeUpdate), + this._targetElement.addEventListener("timeupdate", this.onTimeUpdate), + O.debug("player preparing next manifest for", e.title); + const h = yield this.loadAndParseManifest(e, !1); + d.setNextManifest(h), + s.setMediaItem(e), + s.extURI = h.extURI, + this.nextManifest = h + } + )) + } + playItemFromEncryptedSource(s, n=!1, d) { + return __awaiter$3(this, void 0, void 0, (function*() { + const h = this._paused && !n; + if (O.debug("playItemFromEncryptedSource", s.title), + s.playRawAssetURL) + return s.playbackType = e.PlaybackType.unencryptedFull, + this.nowPlayingItem = s, + this._playAssetURL(s.assetURL, h); + const {extension: p} = this; + if (!p) + return; + p.initiated = n, + p.setMediaItem(s), + s.playbackType = e.PlaybackType.encryptedFull, + this.nowPlayingItem = s, + s.state = D.loading; + const y = yield this.getManifestForItem(s); + this.manifest = y; + const m = shouldForceAudioMse(); + if ((s.isSong || p.isFairplay && m) && (p.extURI = y.extURI), + s.state = D.ready, + p.isFairplay && !m) { + let e = s.assetURL; + return (null == d ? void 0 : d.startTime) && (e += "#t=" + d.startTime), + this._playAssetURL(e, h) + } + { + const e = this._buffer; + if (!(e && this.isSeamlessAudioTransitionsEnabled && e.isItemPlaying(y.mediaItem))) + return this.beginNewBufferForItem(h, y, d); + O.debug("already have buffer, continuing playback") + } + } + )) + } + getManifestForItem(e) { + var s, n; + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("reconciling item to play against playing item"); + const {nextManifest: d, manifest: h, isSeamlessAudioTransitionsEnabled: p} = this + , y = this._buffer; + if (!y || !h) + return O.debug("no buffer or manifest, creating manifest [title, buffer, manifest]", e.title, !!y, !!h), + this.loadAndParseManifest(e); + if (!p) + return O.debug("seamless transitions disabled, stopping and creating manifest for", e.title), + yield this.tearDownManifests(), + this.loadAndParseManifest(e); + const m = !y.isItemPlaying(e); + let g; + return O.debug("itemMismatch", m), + d && !m ? (O.debug(`replacing manifest for ${h.mediaItem.title} with next manifest ${d.mediaItem.title}`), + g = d, + this.nextManifest = void 0, + O.debug("cease listening for keys on manifest for", h.mediaItem.title), + yield this.tearDownManifest(h)) : m ? (null == d ? void 0 : d.mediaItem.id) !== e.id ? (O.debug(`item to play ${e.title} does not match playing or next items, tearing down all manifests`), + yield this.tearDownManifests(), + g = yield this.loadAndParseManifest(e)) : (O.debug(`item to play ${e.title} matches next item, tearing down current manifest`), + yield this.tearDownManifest(h), + g = d) : (O.debug("item is already playing, returning existing manifest"), + g = h), + O.debug("getManifestForItem loading keys for", h.mediaItem.title), + null === (n = null === (s = this.extension) || void 0 === s ? void 0 : s.session) || void 0 === n || n.loadKeys(g.keyValues, g.mediaItem), + g + } + )) + } + seekToTime(e) { + const s = Object.create(null, { + seekToTime: { + get: ()=>super.seekToTime + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + const n = yield s.seekToTime.call(this, e); + return this.isSeamlessAudioTransitionsEnabled && this.onTimeUpdate(), + n + } + )) + } + tearDownManifests() { + return __awaiter$3(this, void 0, void 0, (function*() { + this.manifest = yield this.tearDownManifest(this.manifest), + this.nextManifest = yield this.tearDownManifest(this.nextManifest) + } + )) + } + tearDownManifest(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const {extension: s} = this; + e && (O.debug("tearing down manifest for", e.mediaItem.title), + e.stop(), + s && (yield s.clearSessions(e.keyValues)), + e.removeEventListener(zr.keysParsed, this.loadKeysHandler)) + } + )) + } + loadAndParseManifest(e, s=!0) { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug(`will load and parse manifest for ${e.title}, loadKeys ${s}`); + const n = yield Manifest.load(e, !1); + return s && n.addEventListener(zr.keysParsed, this.loadKeysHandler), + n.parse(), + n + } + )) + } + onTimeUpdate() { + var e, s; + if (!this._buffer) + return; + const {currentPlaybackTimeRemaining: n, nextManifest: d} = this; + d && n < 15 && (O.debug("player loading keys for", d.mediaItem.title), + null === (s = null === (e = this.extension) || void 0 === e ? void 0 : e.session) || void 0 === s || s.loadKeys(d.keyValues, d.mediaItem), + this._targetElement.removeEventListener("timeupdate", this.onTimeUpdate)) + } + loadKeysHandler(e) { + var s, n; + null === (n = null === (s = this.extension) || void 0 === s ? void 0 : s.session) || void 0 === n || n.loadKeys(e.keys, e.item) + } + beginNewBufferForItem(e, s, n) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (O.debug("creating new MseBuffer for item", s.mediaItem.title, e), + this._buffer && (O.debug("stopping old buffer"), + this._buffer.stop()), + this._buffer = new MseBuffer({ + dispatcher: this._dispatcher, + element: this._targetElement, + duration: s.mediaItem.playbackDuration / 1e3, + manifest: s + }), + yield this._playAssetURL(this._buffer.playableUrl, !0), + !e) { + let e = Promise.resolve(); + return (null == n ? void 0 : n.startTime) && (e = this.seekToTime(n.startTime)), + e.then(()=>this._playMedia()) + } + } + )) + } + setPresentationMode(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return Promise.resolve() + } + )) + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", void 0)], AudioPlayer.prototype, "onTimeUpdate", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object]), __metadata$2("design:returntype", void 0)], AudioPlayer.prototype, "loadKeysHandler", null); + class EncryptedSession extends KeySession { + attachMedia(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + this.keySystem = s.keySystem, + this._keySystemAccess = s, + e.addEventListener("encrypted", this.boundHandleSessionCreation, !1) + } + )) + } + detachMedia(e) { + e.removeEventListener("encrypted", this.boundHandleSessionCreation) + } + createSession(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("Encrypted createSession", e); + const s = this._keySystemAccess; + if (!s) + return; + const {initData: n, initDataType: d, target: h} = e; + return this._mediaKeysPromise || (this._mediaKeysPromise = new Promise((e,n)=>__awaiter$3(this, void 0, void 0, (function*() { + const d = yield s.createMediaKeys(); + try { + yield h.setMediaKeys(d) + } catch (F) { + this.dispatchKeyError(F), + n(F) + } + const p = yield this.loadCertificateBuffer(); + yield d.setServerCertificate(p), + this._mediaKeysServerCertificate = p, + e(d) + } + )))), + yield this._mediaKeysPromise, + this._mediaKeysServerCertificate ? this._createSession(h, n, d) : void 0 + } + )) + } + generatePSSH(e) { + const s = new Uint8Array([0, 0, 0, 52, 112, 115, 115, 104, 0, 0, 0, 0, 237, 239, 139, 169, 121, 214, 74, 206, 163, 200, 39, 220, 213, 29, 33, 237, 0, 0, 0, 20, 8, 1, 18, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + , n = ze(e); + for (let d = 0; d < n.length; d++) + s[s.length - 16 + d] = n[d]; + return O.debug("generatePSSH", s), + s + } + _createSession(e, s, n) { + const d = e.mediaKeys.createSession() + , {item: h} = this; + if (!h) + return; + this._teardownCurrentSession(), + O.debug("creating media key session", d); + let p; + if (this.isWidevine && h.isSong) + p = this.generatePSSH(this.extID); + else { + const e = function(e) { + const s = [] + , n = new DataView(e.buffer); + for (let d = 0; d < e.length; ) { + const h = n.getUint32(d); + s.push(new PsshBox(e,d,d + h)), + d += h + } + return s + }(new Uint8Array(s)).find(e=>e.isWidevine) + , n = null == e ? void 0 : e.rawBytes + , h = Ye(n); + O.debug("extracted uri", h), + d.extURI = h, + p = s + } + return d.addEventListener("message", this.startLicenseSession), + this._currentSession = d, + d.generateRequest(n, p).catch(e=>{ + if (e.message.match(/generateRequest.*\(75\)/)) + return d.generateRequest(n, p); + throw e + } + ) + } + _teardownCurrentSession() { + this._currentSession && (O.debug("tearing down media key session", this._currentSession), + this._currentSession.removeEventListener("message", this.startLicenseSession), + this._currentSession = void 0) + } + loadKeys(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + clearSessions() { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + } + class MediaExtensionStub extends Notifications { + constructor(e) { + super(e), + this.audioTracks = [], + this.textTracks = [], + this.extURI = "", + this.hasMediaKeySupport = !0, + this.initiated = !0, + this.isFairplay = !0, + this.hasMediaKeySupport = !0, + this.hasMediaSession = !0 + } + destroy(e) {} + setMediaItem(e) {} + initializeKeySystem() { + return __awaiter$3(this, void 0, void 0, (function*() { + this.session = new EncryptedSession + } + )) + } + clearSessions() { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + } + class PlayerStub { + constructor(s) { + this.bitrate = e.PlaybackBitrate.STANDARD, + this.audioTracks = [], + this.currentBufferedProgress = 0, + this.currentPlaybackDuration = 0, + this.currentPlaybackProgress = 0, + this.currentPlaybackTime = 0, + this.currentPlaybackTimeRemaining = 0, + this.formattedCurrentPlaybackDuration = { + hours: 0, + minutes: 0 + }, + this.isPlaying = !1, + this.isPrimaryPlayer = !0, + this.isReady = !1, + this.paused = !1, + this.playbackState = e.PlaybackStates.none, + this.playbackTargetAvailable = !1, + this.playbackTargetIsWireless = !1, + this.previewOnly = !1, + this.textTracks = [], + this.extension = new MediaExtensionStub([]), + this.hasAuthorization = !0, + this.isDestroyed = !1, + this._volume = 1, + this._playbackRate = 1, + this._dispatcher = s.services.dispatcher, + this.windowHandlers = new WindowHandlers(this) + } + get hasMediaElement() { + return !0 + } + get isEngagedInPlayback() { + return !this.paused + } + get playbackRate() { + return this._playbackRate + } + set playbackRate(e) { + this._playbackRate = e, + this._dispatcher.publish(rs.playbackRateDidChange, new Event("ratechange")) + } + get volume() { + return this._volume + } + set volume(e) { + this._volume = e, + this._dispatcher.publish(rs.playbackVolumeDidChange, new Event("volumeChange")) + } + destroy() {} + dispatch() {} + exitFullscreen() { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + initialize() { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + isPaused() { + return this.paused + } + clearNextManifest() {} + mute() {} + newSeeker() { + return new PlayerSeeker(this) + } + pause(e) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + play() { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + playItemFromEncryptedSource(e, s, n) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + playItemFromUnencryptedSource(e, s, n) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + preload() { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + prepareToPlay(e, s, n) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + seekToTime(e) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + requestFullscreen() { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + setPresentationMode(e) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + showPlaybackTargetPicker() {} + stop(e) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + stopMediaAndCleanup() { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + supportsPictureInPicture() { + return !1 + } + tsidChanged() {} + setNextSeamlessItem(e) { + return __awaiter$3(this, void 0, void 0, (function*() {} + )) + } + } + class SpanWatcher { + constructor(e, s, n, d, h=!1) { + this.dispatcher = e, + this.callback = s, + this.start = n, + this.stop = d, + this.allowMultiple = h, + this.inWatchSpan = !1 + } + startMonitor() { + this.dispatcher.unsubscribe(ns.playbackTimeDidChange, this.handleTimeChange), + this.dispatcher.subscribe(ns.playbackTimeDidChange, this.handleTimeChange) + } + stopMonitor() { + this.dispatcher.unsubscribe(ns.playbackTimeDidChange, this.handleTimeChange) + } + handleTimeChange(e, {currentPlaybackTime: s}) { + return __awaiter$3(this, void 0, void 0, (function*() { + !Number.isFinite(s) || s < this.start || s > this.stop ? this.inWatchSpan = !1 : this.inWatchSpan || (this.allowMultiple || this.stopMonitor(), + this.inWatchSpan = !0, + yield this.callback(s, this)) + } + )) + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", Promise)], SpanWatcher.prototype, "handleTimeChange", null); + class PlaybackMonitor { + constructor(e) { + this.isActive = !1, + this.isMonitoring = !1, + this.watchers = [], + this.handlePlaybackThreshold = this.handlePlaybackThreshold.bind(this), + this.playbackController = e.controller, + this.dispatcher = e.services.dispatcher, + this.dispatcher.subscribe(ns.nowPlayingItemDidChange, this.handleMediaItemChange), + this.apiManager = e.services.apiManager + } + activate() { + this.isActive = !0, + this.startMonitor() + } + deactivate() { + this.isActive = !1, + this.clearMonitor() + } + clearMonitor() { + this.isMonitoring && (this.watchers.forEach(e=>e.stopMonitor()), + this.isMonitoring = !1) + } + shouldMonitor() { + return this.isActive + } + startMonitor() { + this.shouldMonitor() && (this.watchers.forEach(e=>e.startMonitor()), + this.isMonitoring = !0) + } + handleMediaItemChange() { + this.isActive && (this.clearMonitor(), + this.shouldMonitor() && this.startMonitor()) + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", void 0)], PlaybackMonitor.prototype, "handleMediaItemChange", null); + class RollMonitor extends PlaybackMonitor { + constructor(e) { + super(e), + this.rollMap = new Map + } + handlePlaybackThreshold(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (!this.rollMap.has(s)) + return; + const e = this.rollMap.get(s); + this.dispatcher.publish(ns.mediaRollEntered, e), + this.rollMap.delete(s) + } + )) + } + shouldMonitor() { + if (!super.shouldMonitor()) + return !1; + return this.getRollMetadata().length > 0 + } + startMonitor() { + this.setupWatchers(this.getRollMetadata()), + super.startMonitor() + } + getRollMetadata() { + const e = this.playbackController.nowPlayingItem; + return void 0 === e ? [] : ((e,s=["pre-roll", "mid-roll", "post-roll"])=>{ + if (void 0 === e.hlsMetadata) + return []; + const n = []; + return s.forEach(s=>{ + const d = parseInt(e.hlsMetadata[s + ".count"], 10); + if (!isNaN(d)) + for (let h = 0; h < d; h++) { + const d = `${s}.${h}`; + n.push({ + index: h, + type: s, + skippable: "true" === e.hlsMetadata[d + ".skippable"], + "adam-id": e.hlsMetadata[d + ".adam-id"], + start: Math.round(parseFloat(e.hlsMetadata[d + ".start"])), + duration: Math.round(parseFloat(e.hlsMetadata[d + ".duration"])) + }) + } + } + ), + n + } + )(e, ["pre-roll", "post-roll"]) + } + setupWatchers(e) { + const s = []; + e.forEach(e=>{ + const {start: n, duration: d} = e + , h = new SpanWatcher(this.dispatcher,this.handlePlaybackThreshold,n,n + d); + s.push(h), + this.rollMap.set(h, e) + } + ), + this.watchers = s + } + } + class SkipAvailable extends PlaybackMonitor { + constructor(e) { + super(e), + this.skipMap = new Map + } + handlePlaybackThreshold(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (!this.skipMap.has(s)) + return; + const e = this.skipMap.get(s); + this.dispatcher.publish(ns.mediaSkipAvailable, e), + this.skipMap.delete(s) + } + )) + } + shouldMonitor() { + if (!super.shouldMonitor()) + return !1; + return this.getNowPlayingMetadata().length > 0 + } + startMonitor() { + this.setupWatchers(this.getNowPlayingMetadata()), + super.startMonitor() + } + getNowPlayingMetadata() { + const e = this.playbackController.nowPlayingItem; + return void 0 === e ? [] : (e=>{ + const s = parseInt(e.hlsMetadata["skip.count"], 10) + , n = []; + if (isNaN(s) || 0 === s) + return n; + for (let d = 0; d < s; d++) + n.push({ + start: parseFloat(e.hlsMetadata[`skip.${d}.start`]), + duration: parseFloat(e.hlsMetadata[`skip.${d}.duration`]), + target: parseFloat(e.hlsMetadata[`skip.${d}.target`]), + label: e.hlsMetadata[`skip.${d}.label`] + }); + return n + } + )(e) + } + setupWatchers(e) { + const s = []; + e.forEach(e=>{ + const {start: n, duration: d} = e + , h = new SpanWatcher(this.dispatcher,this.handlePlaybackThreshold,n,n + d); + s.push(h), + this.skipMap.set(h, e) + } + ), + this.watchers = s + } + } + const getUpNextStart = e=>parseFloat(e.hlsMetadata["up-next.start"]) + , getWatchedTime = e=>parseFloat(e.hlsMetadata["watched.time"]) + , fetchHLSMetadata = e=>__awaiter$3(void 0, void 0, void 0, (function*() { + if (e.isUTS && e.assetURL) + try { + const s = (yield fetch(e.assetURL).then(e=>e.text())).match(/^(?:#EXT-X-SESSION-DATA:?)DATA\-ID="([^"]+)".+VALUE="([^"]+)".*$/gm); + s && s.forEach(s=>{ + const n = s.split(",")[0].split("com.apple.hls.")[1].replace(/"/g, "") + , d = s.split(",")[1].split("VALUE=")[1].replace(/"/g, ""); + e.hlsMetadata[n] = d + } + ) + } catch (Ra) { + Mr.log(Ra) + } + } + )); + class UpNextMonitor extends PlaybackMonitor { + constructor(e) { + super(e); + const s = this.handlePlaybackThreshold; + this.watchers = [{ + startMonitor: ()=>{ + this.dispatcher.unsubscribe(et.mediaContentComplete, s), + this.dispatcher.subscribe(et.mediaContentComplete, s) + } + , + stopMonitor: ()=>{ + this.dispatcher.unsubscribe(et.mediaContentComplete, s) + } + }] + } + handlePlaybackThreshold() { + var e, s, n, d; + return __awaiter$3(this, void 0, void 0, (function*() { + const h = this.playbackController.nowPlayingItem; + if ("Episode" === (null == h ? void 0 : h.type)) { + let n; + try { + n = yield null === (e = this.apiManager.utsAPI) || void 0 === e ? void 0 : e.showEpisodeNextepisode({ + showId: null === (s = null == h ? void 0 : h.attributes) || void 0 === s ? void 0 : s.showId, + episodeId: null == h ? void 0 : h.id + }) + } catch (m) {} + if (n && this.isAppleOriginal(n)) + return void this.dispatcher.publish(ns.mediaUpNext, { + item: n, + isNextEpisode: !0 + }) + } + let p = yield null === (n = this.apiManager.utsAPI) || void 0 === n ? void 0 : n.getPostPlayShelf(null == h ? void 0 : h.id); + if ((null == p ? void 0 : p.items) || (p = yield null === (d = this.apiManager.utsAPI) || void 0 === d ? void 0 : d.watchlistContinueWatching()), + !(null == p ? void 0 : p.items) || !Array.isArray(p.items)) + return; + const y = p.items.find(e=>this.isAppleOriginal(e) && "Show" !== e.type); + y && this.dispatcher.publish(ns.mediaUpNext, { + item: y + }) + } + )) + } + shouldMonitor() { + return !!super.shouldMonitor() && (void 0 !== this.playbackController.nowPlayingItem && (e = this.playbackController.nowPlayingItem, + !isNaN(getUpNextStart(e)) && !isNaN(getWatchedTime(e)))); + var e + } + isAppleOriginal(e) { + var s; + return e.isAppleOriginal || (null === (s = e.content) || void 0 === s ? void 0 : s.isAppleOriginal) + } + } + const dn = getHlsJsCdnConfig() + , ln = { + app: {}, + autoplay: { + maxQueueSizeForAutoplay: 50, + maxQueueSizeInRequest: 10, + maxUpcomingTracksToMaintain: 10 + }, + features: { + xtrick: !0, + isWeb: !0, + bookmarking: !1, + "seamless-audio-transitions": !0 + }, + urls: { + hls: dn.hls, + rtc: dn.rtc, + mediaApi: "https://amp-api.music.apple.com/v1", + webPlayback: `https://${getCommerceHostname("play")}/WebObjects/MZPlay.woa/wa/webPlayback` + } + } + , cn = createLocalStorageFlag("mk-offers-key-urls").json(); + let un; + cn && (ln.urls.hlsOffersKeyUrls = cn); + class Store { + constructor(e, s={}) { + this._hasAuthorized = !1, + this._providedRequestUserToken = !1, + this._dispatcher = s.services.dispatcher, + s.precache && (this.precache = s.precache), + s.storefrontId && (this.storefrontId = s.storefrontId), + this._defaultStorefrontCountryCode = s.storefrontCountryCode, + (s.affiliateToken || s.campaignToken) && (s.linkParameters = Object.assign(Object.assign({}, s.linkParameters || {}), { + at: s.affiliateToken, + ct: s.campaignToken + })), + this.storekit = new StoreKit(e,{ + apiBase: ln.urls.mediaApi, + authenticateMethod: ln.features["legacy-authenticate-method"] ? "POST" : "GET", + deeplink: s.linkParameters, + disableAuthBridge: s.disableAuthBridge, + iconURL: ln.app.icon, + meParameters: s.meParameters, + persist: s.persist, + realm: s.realm || 0 + }), + this.storekit.addEventListener(ns.authorizationStatusDidChange, e=>{ + const {authorizationStatus: s} = e; + this._hasAuthorized = [Wi.AUTHORIZED, Wi.RESTRICTED].includes(s) + } + ) + } + get authorizationStatus() { + return this.storekit.authorizationStatus + } + get cid() { + return this.storekit.cid + } + get developerToken() { + return this.storekit.developerToken + } + get hasAuthorized() { + return this._hasAuthorized + } + get isAuthorized() { + return this.storekit.hasAuthorized + } + get isRestricted() { + return this.storekit.authorizationStatus === Wi.RESTRICTED + } + get metricsClientId() { + return this._metricsClientId + } + set metricsClientId(e) { + this._metricsClientId = e + } + get musicUserToken() { + return this.storekit.userToken + } + set musicUserToken(e) { + this.storekit.userToken = e + } + set dynamicMusicUserToken(e) { + this.storekit.dynamicUserToken = e + } + get needsGDPR() { + Mr.error("needsGDPR has been deprecated. Plesae migrate to shouldDisplayPrivacyLink()") + } + get realm() { + return this.storekit.realm + } + set requestUserToken(e) { + this._providedRequestUserToken = !0, + this.storekit.requestUserToken = e + } + get restrictedEnabled() { + return this.storekit.restrictedEnabled + } + get storefrontCountryCode() { + var e; + return this.isAuthorized ? this.storekit.storefrontCountryCode : null !== (e = this._defaultStorefrontCountryCode) && void 0 !== e ? e : this.storekit.storefrontCountryCode + } + get storefrontId() { + return this._apiStorefrontId || this.storekit.storefrontCountryCode + } + set storefrontId(e) { + e && (e = e.toLowerCase()), + e !== this._apiStorefrontId && (this._apiStorefrontId = e, + this._dispatcher.publish(et.apiStorefrontChanged, { + storefrontId: e + })) + } + get subscribeURL() { + return this.storekit.deeplinkURL({ + p: "subscribe" + }) + } + get subscribeFamilyURL() { + return this.storekit.deeplinkURL({ + p: "subscribe-family" + }) + } + get subscribeIndividualURL() { + return this.storekit.deeplinkURL({ + p: "subscribe-individual" + }) + } + get subscribeStudentURL() { + return this.storekit.deeplinkURL({ + p: "subscribe-student" + }) + } + get userToken() { + return this.musicUserToken + } + authorize() { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this.storekit.userTokenIsValid) + return this.storekit.userToken; + let e; + try { + e = yield this.storekit.requestUserToken() + } catch (F) { + try { + yield this.unauthorize() + } catch (bt) {} + throw new MKError(MKError.AUTHORIZATION_ERROR,"Unauthorized") + } + return this._providedRequestUserToken && (this.storekit.userToken = e), + this.storekit.userTokenIsValid ? (yield this.storekit.requestStorefrontCountryCode().catch(e=>__awaiter$3(this, void 0, void 0, (function*() { + return yield this.unauthorize(), + Promise.reject(e) + } + ))), + e) : void 0 + } + )) + } + shouldDisplayPrivacyLink(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return this.storekit.shouldDisplayPrivacyLink(e) + } + )) + } + unauthorize() { + return __awaiter$3(this, void 0, void 0, (function*() { + return this.storekit.revokeUserToken() + } + )) + } + validateAgeVerification(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (2 !== this.storekit.realm) + return; + const s = yield this.storekit.me(); + if (s.info) { + if (s.info.webAgeVerificationData && !s.info.webAgeVerificationData.isVerified) + return Promise.reject(new MKError(MKError.AGE_VERIFICATION,"Age verification required")); + if (e.rating && s.info.parentalControlsData && s.info.parentalControlsData.videoContentRestrictions) { + const n = e.rating.system.replace(/[^a-z0-9]+/i, "-"); + if (s.info.parentalControlsData.videoContentRestrictions[n] < e.rating.value) + return Promise.reject(new MKError(MKError.CONTENT_RESTRICTED,"Content restricted")) + } + } + } + )) + } + } + const hn = /\/([a-z]{2})\/(album|artist|episode|movie|music-video|playlist|podcast|post|show|song|station)\/(?:[^\/]*\/)?(?:id)?(\d+|[a-z]{2}\.[a-z0-9\-]+|umc.cmc.[a-zA-Z0-9]+)(?:.*(?:[\?|\&]i=(\d+)).*)?.*$/i; + function formattedMediaURL(e) { + if (!hn.test(e)) + throw new TypeError("Invalid Media URL: " + e); + let[,s,n,d,h] = e.match(hn); + return "music-video" === n && (n = "musicVideo"), + -1 !== ["album", "playlist"].indexOf(n) && h ? (n = "song", + d = h) : "podcast" === n && h && (n = "episode", + d = h), + { + storefrontId: s, + kind: n, + contentId: d, + isUTS: !!d && d.startsWith("umc.") + } + } + function hasAuthorization(e) { + return void 0 === e && (e = un && un.storekit), + void 0 !== e && e.hasAuthorized && e.userTokenIsValid + } + function hasMusicSubscription(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return void 0 === e && (e = un && un.storekit), + e.hasMusicSubscription() + } + )) + } + class MediaSessionManager { + constructor(e, s) { + this.capabilities = e, + this.dispatcher = s, + this.session = navigator.mediaSession, + this.session && (this.dispatcher.subscribe(ns.nowPlayingItemDidChange, this.onNowPlayingItemDidChange), + this.dispatcher.subscribe(ns.capabilitiesChanged, this.onCapabilitiesChanged), + this._setMediaSessionHandlers()) + } + onCapabilitiesChanged() { + this._resetHandlers(), + this._setMediaSessionHandlers() + } + onNowPlayingItemDidChange(e, {item: s}) { + this._setMediaSessionMetadata(s) + } + _setMediaSessionMetadata(e) { + var s, n; + this.session && "MediaMetadata"in window && e && (this.session.metadata = new window.MediaMetadata({ + title: e.title, + artist: null !== (s = e.artistName) && void 0 !== s ? s : null === (n = e.attributes) || void 0 === n ? void 0 : n.showTitle, + album: e.albumName, + artwork: e.artwork ? [96, 128, 192, 256, 384, 512].map(s=>({ + src: formatArtworkURL(e.artwork, s, s), + sizes: `${s}x${s}`, + type: "image/jpeg" + })) : [] + })) + } + _setMediaSessionHandlers() { + this.session && (this._resetHandlers(), + this.session.setActionHandler("play", ()=>{ + var e; + return null === (e = this.controller) || void 0 === e ? void 0 : e.play() + } + ), + this.capabilities.canPause ? this.session.setActionHandler("pause", ()=>{ + var e; + return null === (e = this.controller) || void 0 === e ? void 0 : e.pause() + } + ) : this.session.setActionHandler("pause", ()=>{ + var e; + return null === (e = this.controller) || void 0 === e ? void 0 : e.stop() + } + ), + this.capabilities.canSeek && (this.session.setActionHandler("seekforward", ()=>{ + var e; + return null === (e = this.controller) || void 0 === e ? void 0 : e.seekForward() + } + ), + this.session.setActionHandler("seekbackward", ()=>{ + var e; + return null === (e = this.controller) || void 0 === e ? void 0 : e.seekBackward() + } + )), + this.capabilities.canSkipToNextItem && this.session.setActionHandler("nexttrack", ()=>{ + var e; + return null === (e = this.controller) || void 0 === e ? void 0 : e.skipToNextItem() + } + ), + this.capabilities.canSkipToPreviousItem && this.session.setActionHandler("previoustrack", ()=>{ + var e; + return null === (e = this.controller) || void 0 === e ? void 0 : e.skipToPreviousItem() + } + )) + } + _resetHandlers() { + this.session && (this.session.setActionHandler("play", void 0), + this.session.setActionHandler("pause", void 0), + this.session.setActionHandler("seekforward", void 0), + this.session.setActionHandler("seekbackward", void 0), + this.session.setActionHandler("nexttrack", void 0), + this.session.setActionHandler("previoustrack", void 0)) + } + } + var pn; + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", void 0)], MediaSessionManager.prototype, "onCapabilitiesChanged", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", void 0)], MediaSessionManager.prototype, "onNowPlayingItemDidChange", null), + function(e) { + e[e.PAUSE = 0] = "PAUSE", + e[e.EDIT_QUEUE = 1] = "EDIT_QUEUE", + e[e.SEEK = 2] = "SEEK", + e[e.REPEAT = 3] = "REPEAT", + e[e.SHUFFLE = 4] = "SHUFFLE", + e[e.SKIP_NEXT = 5] = "SKIP_NEXT", + e[e.SKIP_PREVIOUS = 6] = "SKIP_PREVIOUS", + e[e.SKIP_TO_ITEM = 7] = "SKIP_TO_ITEM" + }(pn || (pn = {})); + class Capabilities { + constructor(e) { + this._dispatcher = e, + this._checkCapability = e=>!1, + this._mediaSession = new MediaSessionManager(this,e) + } + set controller(e) { + this._mediaSession.controller = e + } + updateChecker(e) { + this._checkCapability !== e && (this._checkCapability = e, + this._dispatcher.publish(ns.capabilitiesChanged)) + } + get canEditPlaybackQueue() { + return this._checkCapability(pn.EDIT_QUEUE) + } + get canPause() { + return this._checkCapability(pn.PAUSE) + } + get canSeek() { + return this._checkCapability(pn.SEEK) + } + get canSetRepeatMode() { + return this._checkCapability(pn.REPEAT) + } + get canSetShuffleMode() { + return this._checkCapability(pn.SHUFFLE) + } + get canSkipToNextItem() { + return this._checkCapability(pn.SKIP_NEXT) + } + get canSkipToMediaItem() { + return this._checkCapability(pn.SKIP_TO_ITEM) + } + get canSkipToPreviousItem() { + return this._checkCapability(pn.SKIP_PREVIOUS) + } + } + const yn = { + condition: ()=>!0, + toOptions: (e,s,n)=>[Object.assign(Object.assign({}, e), { + context: n + })] + } + , mn = { + condition: e=>{ + var s; + return "stations" === e.type && (null === (s = e.attributes) || void 0 === s ? void 0 : s.isLive) + } + , + toOptions: (e,s,n)=>[Object.assign(Object.assign({}, e), { + context: n, + container: { + attributes: e.attributes, + id: e.id, + type: e.type, + name: null == n ? void 0 : n.featureName + } + })] + } + , hasRelationship = e=>s=>{ + var n, d; + return !!(null === (d = null === (n = s.relationships) || void 0 === n ? void 0 : n[e]) || void 0 === d ? void 0 : d.data) + } + , typeIs = (...e)=>({type: s})=>e.includes(s) + , withBagPrefix = e=>{ + if (void 0 === e || "" === e) + return; + const {prefix: s} = Hs; + return s ? `${s}:${e}` : e + } + , getContainerName$1 = (e,s)=>{ + var n, d; + return null !== (d = null != s ? s : null === (n = null == e ? void 0 : e.container) || void 0 === n ? void 0 : n.name) && void 0 !== d ? d : tt.SONG + } + , gn = { + toOptions: (e,s,n)=>{ + const d = Object.assign(Object.assign({ + id: e.id + }, s), { + name: withBagPrefix(getContainerName$1(e, null == n ? void 0 : n.featureName)) + }); + return [{ + relationships: e.relationships, + attributes: e.attributes, + id: e.id, + type: e.type, + container: d, + context: n + }] + } + , + condition: typeIs("songs", "library-songs", "music-videos") + } + , parseAssets = ({type: e, attributes: {assetTokens: s}})=>e.includes("udio") ? (e=>{ + if (void 0 === e) + return; + const [s] = Object.keys(e); + return e[s] + } + )(s) : (e=>{ + if (void 0 === e) + return; + const s = Object.keys(e); + return e[s[s.length - 1]] + } + )(s) + , fn = { + condition: typeIs("uploaded-audios", "uploadedAudio", "uploaded-videos", "uploadedVideo"), + toOptions: (e,s,n)=>{ + var d, h; + const p = Object.assign(Object.assign({}, e), { + context: n, + attributes: Object.assign(Object.assign({}, e.attributes), { + assetUrl: parseAssets(e), + playParams: null !== (h = null === (d = null == e ? void 0 : e.attributes) || void 0 === d ? void 0 : d.playParams) && void 0 !== h ? h : { + id: e.id, + kind: e.type + } + }) + }); + return void 0 !== s && (p.container = s), + void 0 !== (null == n ? void 0 : n.featureName) && (p.container = Object.assign(Object.assign({}, p.container), { + name: null == n ? void 0 : n.featureName + })), + [p] + } + } + , vn = { + toOptions: (e,s,n)=>e.relationships.episodes.data.map(e=>Object.assign(Object.assign({}, e), { + context: n + })), + condition: hasRelationship("episodes"), + requiredRelationships: ["episodes"] + }; + function __decorate(e, s, n, d) { + var h, p = arguments.length, y = p < 3 ? s : null === d ? d = Object.getOwnPropertyDescriptor(s, n) : d; + if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) + y = Reflect.decorate(e, s, n, d); + else + for (var m = e.length - 1; m >= 0; m--) + (h = e[m]) && (y = (p < 3 ? h(y) : p > 3 ? h(s, n, y) : h(s, n)) || y); + return p > 3 && y && Object.defineProperty(s, n, y), + y + } + function __metadata(e, s) { + if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) + return Reflect.metadata(e, s) + } + function __awaiter(e, s, n, d) { + return new (n || (n = Promise))((function(h, p) { + function fulfilled(e) { + try { + step(d.next(e)) + } catch (bt) { + p(bt) + } + } + function rejected(e) { + try { + step(d.throw(e)) + } catch (bt) { + p(bt) + } + } + function step(e) { + var s; + e.done ? h(e.value) : (s = e.value, + s instanceof n ? s : new n((function(e) { + e(s) + } + ))).then(fulfilled, rejected) + } + step((d = d.apply(e, s || [])).next()) + } + )) + } + function formatRatingsContentType(e, s) { + return v(s) && _(s) ? e.replace(/^library-/, "") : v(s) && !/^library-/.test(e) ? "library-" + e : e + } + function normalizeAdamId(e) { + return e.replace(/^a\./, "") + } + function makeRequest(e, s, n, d={}) { + return __awaiter(this, void 0, void 0, (function*() { + let h, p = s; + const y = n && n.ids; + d = Object.assign({}, d); + const {shouldCacheResults: m=!0, returnRawJSONApiRecords: g=!1, includePagination: v=e.defaultIncludePaginationMetadata, includeResponseMeta: _=!1} = d; + delete d.shouldCacheResults, + delete d.returnRawJSONApiRecords, + delete d.includePagination, + delete d.includeResponseMeta, + "string" == typeof y && (p = `${s}/${encodeURIComponent(y)}`, + n && delete n.ids); + try { + (v || _) && (d.useRawResponse = !0), + h = yield e.request(p, n, d) + } catch (b) { + return "status"in b ? 404 === b.status ? Promise.reject(new MKError(MKError.CONTENT_UNAVAILABLE,"The requested content is not available.")) : Promise.reject(MKError.responseError(b)) : Promise.reject(MKError.internalError(b)) + } + try { + const s = h.results || h.data || h; + if ("object" == typeof h && "results"in h && "meta"in h && (s.meta = h.meta), + 0 === s.length) + return Promise.reject(new MKError(MKError.CONTENT_UNAVAILABLE,"The requested content is not available.")); + const p = g ? s : e.parseResultData(m, s); + if (!v && !_) + return p; + if ("results"in h) { + for (const s in h.results) + "meta" !== s && (p[s] = paginateResultSet(h.results[s], p[s], e, n, d)); + return p + } + return paginateResultSet(h, p, e, n, d) + } catch (F) { + return Promise.reject(MKError.parseError(F)) + } + } + )) + } + function paginateResultSet(e, s, n, d, h={}) { + let p, y; + h.includePagination = !0; + const m = Object.assign({}, h); + return delete m.offset, + e.next && (p = ()=>makeRequest(n, formatPaginatedUrl(n.url, e.next), d, m)), + e.previous && (y = ()=>makeRequest(n, formatPaginatedUrl(n.url, e.previous), d, m)), + { + data: s, + next: p, + previous: y, + meta: e.meta + } + } + function mapRequestResult(e, s) { + return "data"in e ? (e.data = s(e.data), + e) : s(e) + } + function formatPaginatedUrl(e, s) { + if ("function" != typeof URL) + throw new Error("formatPaginatedUrl requires an implementation of URL"); + const {pathname: n} = new URL(e) + , d = new RegExp(`^${n}/`); + return s.replace(d, "") + } + const getFeatureName = (e,s)=>{ + if (s) + return s; + const n = function(e=[]) { + return 0 !== e.length && e.filter(({attributes: e})=>!!e && (e.workName || e.movementName || e.movementCount || e.movementNumber)).length > 0 + }(e.relationships.tracks.data); + return "albums" === e.type || "library-albums" === e.type ? n ? tt.ALBUM_CLASSICAL : tt.ALBUM : "playlists" === e.type || "library-playlists" === e.type ? n ? tt.PLAYLIST_CLASSICAL : tt.PLAYLIST : void 0 + } + , _n = [{ + toOptions: (e,s,n)=>{ + const d = { + attributes: e.attributes, + id: e.id, + type: e.type, + name: withBagPrefix(getFeatureName(e, null == n ? void 0 : n.featureName)) + }; + return e.relationships.tracks.data.map(e=>({ + attributes: e.attributes, + id: e.id, + type: e.type, + container: d, + context: n + })) + } + , + condition: hasRelationship("tracks"), + requiredRelationships: ["tracks"] + }, vn, gn, mn, fn] + , bn = _n.reduce((e,s)=>{ + const n = s.requiredRelationships; + return n && e.push(...n), + e + } + , []) + , Tn = new Set(bn) + , isArrayOf = (e,s)=>Array.isArray(e) && (0 === e.length || s(e[0])) + , isMediaAPIResource = e=>e && void 0 !== e.id && void 0 !== e.type + , isMediaItem = e=>e && void 0 !== e.id + , isMPMediaItem = e=>e && void 0 !== e.contentId && void 0 !== e.metadata && void 0 !== e.metadata.itemId && void 0 !== e.metadata.itemType + , isQueueItems = e=>e && e.items && Array.isArray(e.items) + , isQueueLoaded = e=>e && e.loaded + , isQueueURLOption = e=>e && e.url + , descriptorToMediaItems = e=>{ + if (!isQueueItems(e) && !isQueueLoaded(e)) + return []; + const s = isQueueLoaded(e) ? loadedDescriptorToMediaItem(e) : unloadedDescriptorToMediaItem(e); + return s.forEach(s=>s.context = Object.assign(Object.assign({}, e.context), s.context)), + s + } + , unloadedDescriptorToMediaItem = ({items: e})=>isArrayOf(e, isMPMediaItem) ? e.map(e=>new MediaItem(function(e) { + const s = transform$9({ + id: "metadata.itemId", + type: "metadata.itemType", + "attributes.contentRating"() { + var s; + if (1 === (null === (s = null == e ? void 0 : e.metadata) || void 0 === s ? void 0 : s.isExplicit)) + return "explicit" + }, + "attributes.playParams"() { + var s, n, d; + return 0 !== (null === (s = null == e ? void 0 : e.metadata) || void 0 === s ? void 0 : s.isPlayable) && { + id: null === (n = null == e ? void 0 : e.metadata) || void 0 === n ? void 0 : n.itemId, + kind: null === (d = null == e ? void 0 : e.metadata) || void 0 === d ? void 0 : d.itemType + } + }, + "container.id": "metadata.containerId", + "container.name": "metadata.containerName", + "container.type": "metadata.containerType" + }, e); + return Object.assign({ + attributes: {} + }, s) + }(e))) : isArrayOf(e, isMediaItem) ? e.map(e=>new MediaItem(e)) : [] + , loadedDescriptorToMediaItem = e=>{ + const s = [] + , {loaded: n, container: d, context: h} = e; + return void 0 === n ? [] : isArrayOf(n, isDataRecord) ? (n.forEach(e=>{ + s.push(...dataRecordToMediaItems(e, d, h)) + } + ), + s) : isArrayOf(n, isMediaAPIResource) ? (n.forEach(e=>{ + s.push(...resourceToMediaItem(e, d, h)) + } + ), + s) : isDataRecord(n) ? dataRecordToMediaItems(n, d, h) : isMediaAPIResource(n) ? resourceToMediaItem(n, d, h) : [] + } + , dataRecordToMediaItems = (e,s,n={})=>{ + const {data: d} = e.serialize(!0, void 0, { + includeRelationships: Tn, + allowFullDuplicateSerializations: !0 + }); + return resourceToMediaItem(d, s, n) + } + , resourceToMediaItem = (e,s,n={})=>(O.debug("_resourceToMediaItem", e), + ((e,s,n={})=>{ + var d, h, p, y; + s = null !== (p = null === (h = null === (d = s) || void 0 === d ? void 0 : d.serialize) || void 0 === h ? void 0 : h.call(d).data) && void 0 !== p ? p : s; + return (null !== (y = _n.find(d=>d.condition(e, s, n))) && void 0 !== y ? y : yn).toOptions(e, s, n).map(e=>new MediaItem(e)) + } + )(e, s, n)); + class BaseModifiableQueue { + constructor() { + this.canModifyQueue = !1 + } + append(e) { + Mr.warn("Append is not supported for this type of playback") + } + clear() { + Mr.warn("Clear is not supported for this type of playback") + } + insertAt(e, s) { + Mr.warn("InsertAt is not supported for this type of playback") + } + prepend(e, s=!1) { + Mr.warn("Prepend is not supported for this type of playback") + } + } + class ModifiableQueue { + constructor(e, s) { + this.canModifyQueue = !0, + this.queue = e, + this._mediaItemPlayback = s + } + append(e) { + const s = descriptorToMediaItems(e); + this.queue.splice(this.queue.appendTargetIndex, 0, s) + } + clear() { + this.queue.length && (this.queue.splice(0, this.queue.length), + this.queue.reset()) + } + insertAt(e, s) { + const n = descriptorToMediaItems(s); + this.queue.splice(e, 0, n) + } + prepend(e, s=!1) { + const n = descriptorToMediaItems(e) + , d = this.prependIndex(); + s && this.queue.splice(d, this.queue.length), + this.queue.splice(d, 0, n) + } + prependIndex() { + const {_mediaItemPlayback: e} = this + , {position: s} = this.queue; + return void 0 === e.nowPlayingItem && 0 === s || s < 0 ? 0 : s + 1 + } + } + var En; + e.PlayerRepeatMode = void 0, + (En = e.PlayerRepeatMode || (e.PlayerRepeatMode = {}))[En.none = 0] = "none", + En[En.one = 1] = "one", + En[En.all = 2] = "all"; + class BaseRepeatable { + constructor() { + this.canSetRepeatMode = !1 + } + get repeatMode() { + return e.PlayerRepeatMode.none + } + set repeatMode(e) { + e !== this.repeatMode && Mr.warn("setting repeatMode is not supported in this playback method") + } + } + class Repeatable { + constructor(s) { + this.dispatcher = s, + this.canSetRepeatMode = !0, + this._mode = e.PlayerRepeatMode.none + } + get repeatMode() { + return this._mode + } + set repeatMode(s) { + s in e.PlayerRepeatMode && s !== this._mode && (this._mode = s, + this.dispatcher.publish(ns.repeatModeDidChange, this._mode)) + } + } + Object.assign(Object.assign({}, { + NEXT_ITEM: "NEXT" + }), e.PlayActivityEndReasonType); + const asyncNoop = ()=>__awaiter$3(void 0, void 0, void 0, (function*() {} + )); + class BaseSeekable { + constructor(e) { + this.mediaItemPlayback = e, + this.canSeek = !1 + } + getSeekSeconds(e) { + return Mr.warn("Seeking by predetermined amounts are not supported in this playback method"), + { + BACK: 0, + FORWARD: 0 + } + } + seekBackward(e=asyncNoop) { + Mr.warn("seekBackward is not supported in this playback method") + } + seekForward(e=asyncNoop) { + Mr.warn("seekForward is not supported in this playback method") + } + seekToTime(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + Mr.warn("seekToTime is not supported in this playback method") + } + )) + } + } + class Seekable { + constructor(e, s) { + this._dispatcher = e, + this.mediaItemPlayback = s, + this.canSeek = !0 + } + getSeekSeconds(e) { + return (e=>{ + switch (e.type) { + case "EditorialVideoClip": + case "uploaded-videos": + case "uploadedVideo": + case "musicVideo": + return { + FORWARD: 10, + BACK: 10 + }; + default: + return { + FORWARD: 30, + BACK: 15 + } + } + } + )(e) + } + seekBackward(e=this._seekToBeginning) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (void 0 === this.mediaItemPlayback.nowPlayingItem) + return void Mr.warn("Cannot seekBackward when nowPlayingItem is not yet set."); + const s = this.mediaItemPlayback.currentPlaybackTime - this.getSeekSeconds(this.mediaItemPlayback.nowPlayingItem).BACK; + s < 0 ? yield e.call(this) : yield this.seekToTime(s, rt.Interval) + } + )) + } + seekForward(e=this._seekToEnd) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (void 0 === this.mediaItemPlayback.nowPlayingItem) + return void Mr.warn("Cannot seekForward when nowPlayingItem is not yet set."); + const s = this.mediaItemPlayback.currentPlaybackTime + this.getSeekSeconds(this.mediaItemPlayback.nowPlayingItem).FORWARD; + s > this.mediaItemPlayback.currentPlaybackDuration ? yield e.call(this) : yield this.seekToTime(s, rt.Interval) + } + )) + } + seekToTime(e, s=rt.Manual) { + return __awaiter$3(this, void 0, void 0, (function*() { + const n = this.mediaItemPlayback.currentPlaybackTime + , d = Math.min(Math.max(0, e), this.mediaItemPlayback.currentPlaybackDuration - 1); + yield this.mediaItemPlayback.seekToTime(d, s), + this._dispatcher.publish(et.playbackSeek, { + startPosition: n, + position: d, + seekReasonType: s + }) + } + )) + } + _seekToBeginning() { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this.seekToTime(0, rt.Interval) + } + )) + } + _seekToEnd() { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this.seekToTime(this.mediaItemPlayback.currentPlaybackDuration, rt.Interval) + } + )) + } + } + const shuffleCollection = e=>{ + const s = [...e] + , {length: n} = s; + for (let d = 0; d < n; ++d) { + const e = d + Math.floor(Math.random() * (n - d)) + , h = s[e]; + s[e] = s[d], + s[d] = h + } + return s + } + ; + class QueueItem { + constructor(e, s) { + var n; + this.isAutoplay = !1, + this.item = e, + this.isAutoplay = null !== (n = null == s ? void 0 : s.isAutoplay) && void 0 !== n && n + } + restrict() { + return this.item.restrict() + } + } + function toQueueItems(e, s) { + return e.map(e=>new QueueItem(e,s)) + } + function toMediaItems(e) { + return e.map(e=>e.item) + } + const parseQueueURLOption = e=>{ + if (!isQueueURLOption(e)) + return e; + const {url: s} = e + , n = function(e, s) { + var n = {}; + for (var d in e) + Object.prototype.hasOwnProperty.call(e, d) && s.indexOf(d) < 0 && (n[d] = e[d]); + if (null != e && "function" == typeof Object.getOwnPropertySymbols) { + var h = 0; + for (d = Object.getOwnPropertySymbols(e); h < d.length; h++) + s.indexOf(d[h]) < 0 && Object.prototype.propertyIsEnumerable.call(e, d[h]) && (n[d[h]] = e[d[h]]) + } + return n + }(e, ["url"]) + , {contentId: d, kind: h, storefrontId: p} = formattedMediaURL(s); + return n[h] = d, + un.storefrontId = p, + O.debug("parseQueueURLOption", n), + n + } + , {queueItemsDidChange: kn, queuePositionDidChange: Sn} = ns; + class Queue { + constructor(e) { + if (this.hasAutoplayStation = !1, + this._itemIDs = [], + this._queueItems = [], + this._isRestricted = !1, + this._nextPlayableItemIndex = -1, + this._position = -1, + this._dispatcher = e.services.dispatcher, + !e.descriptor) + return; + const s = descriptorToMediaItems(e.descriptor).filter(e=>this._isItemPlayable(e)); + this._queueItems = toQueueItems(s), + this._reindex(), + this.position = this._getStartItemPosition(e.descriptor.startWith) + } + get isEmpty() { + return 0 === this.length + } + set isRestricted(e) { + this._isRestricted = false, + this._isRestricted && this._queueItems && this._queueItems.forEach(e=>{ + e.restrict() + } + ) + } + get isRestricted() { + return this._isRestricted + } + get appendTargetIndex() { + let e = this.length; + const s = this._queueItems.findIndex(e=>e.isAutoplay); + return -1 !== s && this.position < s && (e = s), + e + } + get items() { + return toMediaItems(this._queueItems) + } + get autoplayItems() { + return toMediaItems(this._queueItems.filter(e=>e.isAutoplay)) + } + get unplayedAutoplayItems() { + return toMediaItems(this._unplayedQueueItems.filter(e=>e.isAutoplay)) + } + get userAddedItems() { + return toMediaItems(this._queueItems.filter(e=>!e.isAutoplay)) + } + get unplayedUserItems() { + return toMediaItems(this._unplayedQueueItems.filter(e=>!e.isAutoplay)) + } + get length() { + return this._queueItems.length + } + get nextPlayableItem() { + if (-1 !== this.nextPlayableItemIndex) + return this.item(this.nextPlayableItemIndex) + } + get nextPlayableItemIndex() { + return this._nextPlayableItemIndex = this._getNextPlayableItemIndex(), + this._nextPlayableItemIndex + } + get position() { + return this._position + } + set position(e) { + this._updatePosition(e) + } + get previousPlayableItem() { + if (void 0 !== this.previousPlayableItemIndex) + return this.item(this.previousPlayableItemIndex) + } + get previousPlayableItemIndex() { + if (void 0 === this._previousPlayableItemIndex) { + let e = this.position - 1; + for (; e > -1; ) { + const s = this.item(e); + if (this._isItemPlayable(s)) { + this._previousPlayableItemIndex = e; + break + } + e-- + } + } + return this._previousPlayableItemIndex + } + removeQueueItems(e) { + for (let s = this.length - 1; s >= 0; s--) + e(this.queueItem(s), s) && this.spliceQueueItems(s, 1) + } + indexForItem(e) { + return ("string" == typeof e ? this._itemIDs : this.items).indexOf(e) + } + item(e) { + var s; + return null === (s = this.queueItem(e)) || void 0 === s ? void 0 : s.item + } + get currentItem() { + return this.item(this.position) + } + queueItem(e) { + var s; + return null === (s = this._queueItems) || void 0 === s ? void 0 : s[e] + } + get currentQueueItem() { + return this.queueItem(this.position) + } + remove(e) { + if (logDeprecation("remove", { + message: "The queue remove function has been deprecated" + }), + e === this.position) + throw new MKError(MKError.INVALID_ARGUMENTS); + this.splice(e, 1) + } + append(e=[]) { + return this.appendQueueItems(toQueueItems(e)) + } + appendQueueItems(e=[]) { + return this.spliceQueueItems(this.appendTargetIndex, 0, e) + } + splice(e, s, n=[]) { + return toMediaItems(this.spliceQueueItems(e, s, toQueueItems(n))) + } + spliceQueueItems(e, s, n=[], d=!0) { + n = n.filter(e=>this._isItemPlayable(null == e ? void 0 : e.item)); + const h = this._queueItems.splice(e, s, ...n); + return this._itemIDs.splice(e, s, ...n.map(e=>e.item.id)), + d && (this._dispatcher.publish(et.queueModified, { + start: e, + added: toMediaItems(n), + removed: toMediaItems(h) + }), + this._dispatcher.publish(kn, this.items)), + h + } + reset() { + const e = this.position; + this._position = -1, + this._dispatcher.publish(Sn, { + oldPosition: e, + position: this.position + }) + } + _isSameItems(e) { + if (e.length !== this.length) + return !1; + const s = e.map(e=>e.id).sort() + , n = [...this._itemIDs].sort(); + let d, h; + try { + d = JSON.stringify(s), + h = JSON.stringify(n) + } catch (bt) { + return !1 + } + return d === h + } + _reindex() { + this._queueItems && (this._itemIDs = this._queueItems.map(e=>e.item.id)) + } + _updatePosition(e) { + if (e === this._position) + return; + const s = this._position; + this._position = this._getNextPlayableItemIndex(e), + this._previousPlayableItemIndex = void 0, + this._dispatcher.publish(Sn, { + oldPosition: s, + position: this._position + }) + } + _getNextPlayableItemIndex(s=this.position + 1) { + var n; + let d = s; + for (; d < this.length; ) { + const e = this.item(d); + if (this._isItemPlayable(e)) + return d; + d++ + } + if ((null === (n = this.repeatable) || void 0 === n ? void 0 : n.repeatMode) === e.PlayerRepeatMode.all) + for (d = 0; d <= s; ) { + const e = this.item(d); + if (this._isItemPlayable(e)) + return d; + d++ + } + return -1 + } + get _unplayedQueueItems() { + const e = this.position < 0 ? 0 : this.position; + return this._queueItems.slice(e) + } + _getStartItemPosition(e) { + if (void 0 === e) + return -1; + if ("object" == typeof e && "id"in e && (e = e.id), + "string" == typeof e) + return this.indexForItem(e); + const s = parseInt("" + e, 10); + return s >= 0 && s < this.length ? s : -1 + } + _isItemPlayable(e) { + return (null == e ? void 0 : e.isPlayable) || (null == e ? void 0 : e.previewURL) + } + } + var Pn; + !function(e) { + e[e.off = 0] = "off", + e[e.songs = 1] = "songs" + }(Pn || (Pn = {})); + const In = "Shuffling is not supported in this playback method."; + class BaseShuffler { + constructor() { + this.canSetShuffleMode = !1 + } + set shuffle(e) { + Mr.warn(In) + } + get shuffleMode() { + return Pn.off + } + set shuffleMode(e) { + Mr.warn(In) + } + checkAndReshuffle(e) { + Mr.warn(In) + } + } + class Shuffler { + constructor(e, {dispatcher: s}) { + this.controller = e, + this.canSetShuffleMode = !0, + this.mode = Pn.off, + this._unshuffledIDs = [], + this._isSpliceFromShuffle = !1, + this.dispatcher = s, + this.dispatcher.subscribe(et.queueModified, this.queueModifiedHandler), + this._queue = e.queue + } + get queue() { + return this._queue + } + set queue(e) { + this._queue = e, + this._unshuffledIDs = e.userAddedItems.map(e=>e.id), + this.checkAndReshuffle(!1) + } + queueModifiedHandler(e, s) { + if (this._isSpliceFromShuffle) + return void (this._isSpliceFromShuffle = !1); + const {start: n, added: d, removed: h} = s; + if (h.length > 0) { + const e = h.map(e=>e.id); + this._unshuffledIDs = this._unshuffledIDs.filter(s=>!e.includes(s)) + } + d.length > 0 && this._unshuffledIDs.splice(n, 0, ...d.map(e=>e.id)) + } + set shuffle(e) { + this.shuffleMode = e ? Pn.songs : Pn.off + } + get shuffleMode() { + return this.mode + } + set shuffleMode(e) { + e !== this.shuffleMode && e in Pn && (Mr.debug(`mk: set shuffleMode from ${this.shuffleMode} to ${e}`), + this.mode = e, + this.mode === Pn.songs ? this.shuffleQueue() : this.unshuffleQueue(), + this.controller.nowPlayingItem && (this._queue.position = this._queue.indexForItem(this.controller.nowPlayingItem.id)), + this.dispatcher.publish(ns.shuffleModeDidChange, this.shuffleMode)) + } + checkAndReshuffle(e=!1) { + this.shuffleMode === Pn.songs && this.shuffleQueue(e) + } + shuffleQueue(e=!0) { + const {userAddedItems: s} = this._queue; + if (s.length <= 1) + return s; + const n = s.slice(0) + , d = this._queue.position > -1 ? n.splice(this._queue.position, 1) : []; + let h = []; + do { + h = shuffleCollection(n) + } while (arrayEquals(h, n)); + const p = [...d, ...h]; + this._isSpliceFromShuffle = !0, + this._queue.spliceQueueItems(0, p.length, toQueueItems(p), e) + } + unshuffleQueue(e=!0) { + let s = []; + const n = this._unshuffledIDs.reduce((e,s,n)=>(e[s] = n, + e), {}) + , d = []; + let h = 0; + const p = this._queue.item(this._queue.position); + this._queue.userAddedItems.forEach(e=>{ + const y = n[e.id]; + void 0 === y && d.push(e), + s[y] = e, + e.id === (null == p ? void 0 : p.id) && (h = y) + } + ), + s = s.filter(Boolean); + const y = s.concat(d); + this._isSpliceFromShuffle = !0, + this._queue.spliceQueueItems(0, y.length, toQueueItems(y), e), + this._queue.position = h + } + } + var An; + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [String, Object]), __metadata$2("design:returntype", void 0)], Shuffler.prototype, "queueModifiedHandler", null), + function(e) { + e.continuous = "continuous", + e.serial = "serial" + }(An || (An = {})); + const {queueItemsDidChange: wn} = ns; + class PlaybackController { + constructor(e) { + var s; + this._context = {}, + this.onPlaybackStateDidChange = this.onPlaybackStateDidChange.bind(this), + this._autoplayEnabled = null !== (s = null == e ? void 0 : e.autoplayEnabled) && void 0 !== s && s, + this._services = e.services, + this._playerOptions = e, + this.storekit = e.storekit, + this._skipIntro = new SkipAvailable({ + controller: this, + services: e.services + }), + this._upNext = new UpNextMonitor({ + controller: this, + services: e.services + }), + this._rollMonitor = new RollMonitor({ + controller: this, + services: e.services + }), + this._queueModifier = new BaseModifiableQueue, + this._shuffler = new BaseShuffler, + this._seekable = new BaseSeekable(this._mediaItemPlayback), + this._repeatable = new BaseRepeatable, + this._dispatcher.subscribe(ns.autoplayEnabledDidChange, this.updateAutoplay) + } + updateAutoplay(e, s) { + this.autoplayEnabled = s + } + constructContext(e, s) { + var n; + const d = Object.assign(Object.assign({}, s), e.context); + return void 0 !== e.featureName && void 0 === (null === (n = e.context) || void 0 === n ? void 0 : n.featureName) && (Mr.warn("featureName is deprecated, pass it inside context"), + d.featureName = e.featureName), + d + } + get context() { + return this._context + } + get continuous() { + return this._continuous || this.hasAuthorization + } + set continuous(e) { + this._continuous = e + } + get autoplayEnabled() { + return this._autoplayEnabled + } + set autoplayEnabled(e) { + this._autoplayEnabled = e + } + get currentBufferedProgress() { + return this._mediaItemPlayback.currentBufferedProgress + } + set currentBufferedProgress(e) { + this._mediaItemPlayback.currentBufferedProgress = e + } + set currentPlaybackProgress(e) { + this._mediaItemPlayback.currentPlaybackProgress = e + } + get _dispatcher() { + return this._services.dispatcher + } + get formattedCurrentPlaybackDuration() { + return this._mediaItemPlayback.formattedCurrentPlaybackDuration + } + get hasAuthorization() { + return hasAuthorization(this.storekit) + } + get isPlaying() { + return this._mediaItemPlayback.isPlaying + } + get isPrimaryPlayer() { + return this._mediaItemPlayback.isPrimaryPlayer + } + set isPrimaryPlayer(e) { + this._mediaItemPlayback.isPrimaryPlayer = e + } + get isReady() { + return this._mediaItemPlayback.isReady + } + get _mediaItemPlayback() { + return this._services.mediaItemPlayback + } + get nowPlayingItem() { + return this._mediaItemPlayback.nowPlayingItem + } + get nowPlayingItemIndex() { + return this.queue ? this.queue.position : -1 + } + get queue() { + return this._queue + } + set queue(e) { + this._prepareQueue(e), + this._queue = e, + this._shuffler.queue = this._queue, + this._queueModifier.queue = this._queue, + this._dispatcher.publish(wn, e.items) + } + get repeatMode() { + return this._repeatable.repeatMode + } + set repeatMode(e) { + this._repeatable.repeatMode = e + } + get seekSeconds() { + const {nowPlayingItem: e} = this; + if (void 0 !== e) + return this._seekable.getSeekSeconds(e) + } + set shuffle(e) { + this._shuffler.shuffle = e + } + get shuffleMode() { + return this._shuffler.shuffleMode + } + set shuffleMode(e) { + this._shuffler.shuffleMode = e + } + get storekit() { + return this._storekit + } + set storekit(s) { + s && (s.addEventListener(es.authorizationStatusWillChange, ({authorizationStatus: s, newAuthorizationStatus: n})=>__awaiter$3(this, void 0, void 0, (function*() { + this.isPlaying && (s > Wi.DENIED && n < Wi.RESTRICTED ? yield this.stop({ + endReasonType: e.PlayActivityEndReasonType.PLAYBACK_SUSPENDED, + userInitiated: !1 + }) : yield this.stop({ + userInitiated: !1 + })) + } + ))), + this._storekit = s) + } + append(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const s = yield this._dataForQueueOptions(e); + return this._queueModifier.append(s), + this.queue + } + )) + } + insertAt(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + const n = yield this._dataForQueueOptions(s); + return this._queueModifier.insertAt(e, n), + this.queue + } + )) + } + _dataForQueueOptions(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const s = this.constructContext(e, this.context); + return Object.assign(Object.assign({}, e), { + context: s + }) + } + )) + } + clear() { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._queueModifier.clear(), + this.queue + } + )) + } + changeToMediaAtIndex(e=0) { + var s, n, d; + return __awaiter$3(this, void 0, void 0, (function*() { + yield this.stop(); + const h = null === (s = this.queue.item(e)) || void 0 === s ? void 0 : s.id + , p = null === (d = null === (n = this._mediaItemPlayback) || void 0 === n ? void 0 : n.playOptions) || void 0 === d ? void 0 : d.get(h); + let y = (null == p ? void 0 : p.startTime) || 0; + const m = yield this._changeToMediaAtIndex(e, !0); + m && (m.id !== h && (y = 0), + this._dispatcher.publish(et.playbackPlay, { + item: m, + position: y + })) + } + )) + } + changeToMediaItem(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const s = this.queue.indexForItem(e); + return -1 === s ? Promise.reject(new MKError(MKError.MEDIA_DESCRIPTOR)) : this.changeToMediaAtIndex(s) + } + )) + } + activate() { + Mr.debug("mk: base controller - activate"), + this._dispatcher.unsubscribe(ns.playbackStateDidChange, this.onPlaybackStateDidChange), + this._dispatcher.subscribe(ns.playbackStateDidChange, this.onPlaybackStateDidChange), + this._skipIntro.activate(), + this._upNext.activate(), + this._rollMonitor.activate() + } + deactivate() { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this.stop(), + this._dispatcher.unsubscribe(ns.playbackStateDidChange, this.onPlaybackStateDidChange), + this._skipIntro.deactivate(), + this._upNext.deactivate(), + this._rollMonitor.deactivate() + } + )) + } + destroy() { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this.deactivate(), + this._dispatcher.unsubscribe(ns.autoplayEnabledDidChange, this.updateAutoplay) + } + )) + } + hasCapabilities(e) { + switch (e) { + case pn.SEEK: + return this._seekable.canSeek; + case pn.REPEAT: + return this._repeatable.canSetRepeatMode; + case pn.SHUFFLE: + return this._shuffler.canSetShuffleMode; + case pn.EDIT_QUEUE: + return this._queueModifier.canModifyQueue; + case pn.PAUSE: + case pn.SKIP_NEXT: + case pn.SKIP_TO_ITEM: + return !0; + case pn.SKIP_PREVIOUS: + default: + return !1 + } + } + pause(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._mediaItemPlayback.pause(e) + } + )) + } + play() { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this.nowPlayingItem) + return this._mediaItemPlayback.play(); + if (!this._queue || this._queue.isEmpty) + return; + if (this.nowPlayingItemIndex >= 0) + return this.changeToMediaAtIndex(this.nowPlayingItemIndex); + const {queue: e} = this; + if (-1 !== e.nextPlayableItemIndex) + return this.changeToMediaAtIndex(e.nextPlayableItemIndex); + e.isRestricted && e.items.every(e=>e.isRestricted) && this._dispatcher.publish(ns.mediaPlaybackError, new MKError(MKError.CONTENT_RESTRICTED,"Content restricted")) + } + )) + } + playSingleMediaItem(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + yield fetchHLSMetadata(e), + this._dispatcher.publish(ns.queueItemsDidChange, [e]); + const s = yield this._mediaItemPlayback.startMediaItemPlayback(e, !0); + s && this._dispatcher.publish(et.playbackPlay, { + item: s, + position: 0, + userInitiated: !0 + }) + } + )) + } + onPlaybackStateDidChange(s, n) { + return __awaiter$3(this, void 0, void 0, (function*() { + n.state === e.PlaybackStates.ended && (this.continuous || this.repeatMode === e.PlayerRepeatMode.one) && (Mr.debug("controller detected track ended event, moving to next item."), + this._dispatcher.publish(et.applicationActivityIntent, { + endReasonType: e.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS, + userInitiated: !1 + }), + yield this._next()) + } + )) + } + preload() { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._mediaItemPlayback.preload() + } + )) + } + prepend(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + const n = yield this._dataForQueueOptions(e); + return this._queueModifier.prepend(n, s), + this.queue + } + )) + } + prepareToPlay(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._mediaItemPlayback.prepareToPlay(e) + } + )) + } + showPlaybackTargetPicker() { + this._mediaItemPlayback.showPlaybackTargetPicker() + } + seekBackward() { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._seekable.seekBackward() + } + )) + } + seekForward() { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._seekable.seekForward(this.skipToNextItem.bind(this)) + } + )) + } + skipToNextItem() { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._next(!0) + } + )) + } + getNewSeeker() { + return this._mediaItemPlayback.getNewSeeker() + } + seekToTime(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this._seekable.seekToTime(e, s) + } + )) + } + setQueue(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return yield this.extractGlobalValues(e), + yield this._mediaItemPlayback.stop(), + this.returnQueueForOptions(e) + } + )) + } + extractGlobalValues(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + this._context = this.constructContext(e, this._context), + void 0 !== e.featureName && e.context && (Mr.warn("featureName is deprecated, pass it inside context"), + e.context.featureName = e.featureName) + } + )) + } + stop(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this._mediaItemPlayback.stop(e) + } + )) + } + _changeToMediaAtIndex(e=0, s=!1) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this.queue.isEmpty) + return; + this.queue.position = e; + const n = this.queue.item(this.queue.position); + if (!n) + return; + const d = yield this._mediaItemPlayback.startMediaItemPlayback(n, s); + if (d || n.state !== D.unsupported) + return d; + yield this.skipToNextItem() + } + )) + } + _next(e=!1, s=!1) { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._nextAtIndex(this.queue.nextPlayableItemIndex, e, s) + } + )) + } + _nextAtIndex(s, n=!1, d=!1) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this.queue.isEmpty) + return; + const {_mediaItemPlayback: h} = this; + if (s < 0) + return Mr.debug("controller/index._next no next item available, stopping playback"), + yield this.stop({ + userInitiated: n + }), + void (h.playbackState = e.PlaybackStates.completed); + const p = this.isPlaying + , y = h.currentPlaybackTime + , m = yield this._changeToMediaAtIndex(s, n); + return this._notifySkip(p, m, d, { + userInitiated: n, + position: y, + direction: e.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS + }), + m + } + )) + } + _notifySkip(s, n, d, h) { + const {userInitiated: p, direction: y, position: m} = h + , g = this._dispatcher; + d ? (Mr.debug("seamlessAudioTransition transition, PAF play"), + g.publish(et.playbackPlay, { + item: n, + position: 0, + endReasonType: e.PlayActivityEndReasonType.NATURAL_END_OF_TRACK + })) : s ? n ? g.publish(et.playbackSkip, { + item: n, + userInitiated: p, + direction: y, + position: m + }) : g.publish(et.playbackStop, { + userInitiated: p, + position: m + }) : n && g.publish(et.playbackPlay, Object.assign({ + item: n, + position: 0 + }, p ? { + endReasonType: e.PlayActivityEndReasonType.MANUALLY_SELECTED_PLAYBACK_OF_A_DIFF_ITEM + } : {})) + } + _prepareQueue(e) { + Mr.debug("mk: _prepareQueue"), + this.hasAuthorization && (e.isRestricted = this.storekit.restrictedEnabled || !1), + e.repeatable = this._repeatable + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [String, Boolean]), __metadata$2("design:returntype", void 0)], PlaybackController.prototype, "updateAutoplay", null); + function rejectOnLast() { + return Promise.reject("The last middleware in the stack should not call next") + } + function processMiddleware(e, ...s) { + return e.length ? function createNextFunction([e,...s]) { + return (...n)=>e(createNextFunction(s), ...n) + }([...e, rejectOnLast])(...s) : Promise.reject("processMiddleware requires at mimimum one middleware function") + } + function parameterizeString(e, s) { + return function(e) { + try { + return function recursiveTokenizeParameterizedString(e, s=[]) { + if (e.startsWith("{{")) { + const n = e.indexOf("}}"); + if (-1 === n) + throw new Error("UNCLOSED_PARAMETER"); + const d = { + type: Rn.Parameter, + value: e.slice(2, n) + }; + return n + 2 < e.length ? recursiveTokenizeParameterizedString(e.slice(n + 2), [...s, d]) : [...s, d] + } + { + const n = e.indexOf("{{"); + return -1 === n ? [...s, { + type: Rn.Static, + value: e + }] : recursiveTokenizeParameterizedString(e.slice(n), [...s, { + type: Rn.Static, + value: e.slice(0, n) + }]) + } + }(e) + } catch (F) { + if ("UNCLOSED_PARAMETER" === F.message) + throw new Error(`Unclosed parameter in path: "${e}"`); + throw F + } + }(e).map(e=>{ + switch (e.type) { + case Rn.Parameter: + return e.value in s ? encodeURIComponent("" + s[e.value]) : `{{${e.value}}}`; + case Rn.Static: + default: + return e.value + } + } + ).join("") + } + var Rn; + function constructUrlMiddleware(e, s) { + let n = s.url; + return n || (n = addPathToURL(s.baseUrl, s.path)), + s.urlParameters && (n = parameterizeString(n, s.urlParameters)), + s.queryParameters && (n = addQueryParamsToURL(n, s.queryParameters)), + e(Object.assign(Object.assign({}, s), { + url: n + })) + } + function unwrapJSONFromResponse(e) { + return __awaiter$2(this, void 0, void 0, (function*() { + try { + return yield e.json() + } catch (F) { + return + } + } + )) + } + function fetchMiddlewareFactory(e) { + return function(s, n) { + return __awaiter$2(this, void 0, void 0, (function*() { + const s = yield e(n.url, n.fetchOptions) + , d = { + request: n, + response: s, + data: yield unwrapJSONFromResponse(s) + }; + if (!s.ok) + throw MKError.responseError(s); + return d + } + )) + } + } + !function(e) { + e[e.Static = 0] = "Static", + e[e.Parameter = 1] = "Parameter" + }(Rn || (Rn = {})); + const On = fetchMiddlewareFactory("undefined" != typeof fetch ? fetch : ()=>{ + throw new Error("window.fetch is not defined") + } + ); + var Cn; + !function(e) { + e.Replace = "REPLACE", + e.Merge = "MERGE" + }(Cn || (Cn = {})); + const Mn = ["url"]; + class APISession { + constructor(e) { + this.reconfigure(e) + } + get config() { + return this._config + } + request(e, s={}, n={}) { + var d; + return processMiddleware(this.middlewareStack, Object.assign(Object.assign(Object.assign({}, this.config.defaultOptions), n), { + baseUrl: this.config.url, + path: e, + fetchOptions: mergeFetchOptions(null === (d = this.config.defaultOptions) || void 0 === d ? void 0 : d.fetchOptions, n.fetchOptions), + queryParameters: Object.assign(Object.assign({}, this.config.defaultQueryParameters), s), + urlParameters: Object.assign(Object.assign({}, this.config.defaultUrlParameters), n.urlParameters) + })) + } + reconfigure(e, s=Cn.Replace) { + s === Cn.Merge && (e = deepmerge(this.config, e)), + Mn.forEach(s=>{ + if (void 0 === e[s]) + throw new Error(`Session requires a valid SessionConfig, missing "${s}"`) + } + ), + this._config = e, + this.middlewareStack = this.createMiddlewareStack() + } + createMiddlewareStack() { + return Array.isArray(this.config.middleware) ? [constructUrlMiddleware, ...this.config.middleware, this.makeFetchMiddleware()] : [constructUrlMiddleware, this.makeFetchMiddleware()] + } + makeFetchMiddleware() { + return "function" == typeof this.config.fetchFunction ? fetchMiddlewareFactory(this.config.fetchFunction) : On + } + } + const Dn = { + music: { + url: "https://api.music.apple.com" + }, + apps: { + url: "https://amp-api.apps.apple.com" + }, + books: { + url: "https://amp-api.books.apple.com" + }, + fitness: { + url: "https://amp-api.fitness.apple.com" + } + }; + Dn.music = { + url: "https://amp-api.music.apple.com" + }, + Dn.videos = { + url: "https://amp-api.videos.apple.com" + }, + Dn.podcasts = { + url: "https://amp-api.podcasts.apple.com" + }; + class MediaAPIV3 { + constructor(e) { + const {realmConfig: s} = e + , n = /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + function(e, s) { + var n = {}; + for (var d in e) + Object.prototype.hasOwnProperty.call(e, d) && s.indexOf(d) < 0 && (n[d] = e[d]); + if (null != e && "function" == typeof Object.getOwnPropertySymbols) { + var h = 0; + for (d = Object.getOwnPropertySymbols(e); h < d.length; h++) + s.indexOf(d[h]) < 0 && Object.prototype.propertyIsEnumerable.call(e, d[h]) && (n[d[h]] = e[d[h]]) + } + return n + }(e, ["realmConfig"]); + for (const d in Dn) { + let e = deepmerge(Dn[d], n); + const h = null == s ? void 0 : s[d]; + h && (e = deepmerge(e, h)), + this.configure(d, e) + } + } + configure(e, s, n=Cn.Merge) { + var d; + this.storefrontId = s.storefrontId; + const h = function(e) { + let s = {}; + e.url && (s.url = e.url); + e.storefrontId && (s.defaultUrlParameters = { + storefrontId: e.storefrontId + }); + e.mediaUserToken && (s.defaultOptions = { + fetchOptions: { + headers: { + "Media-User-Token": e.mediaUserToken + } + } + }); + e.developerToken && (s = deepmerge(s, { + defaultOptions: { + fetchOptions: { + headers: { + Authorization: "Bearer " + e.developerToken + } + } + } + })); + e.options && (s = deepmerge(s, e.options)); + return s + }(s); + if (this[e]) + this[e].session.reconfigure(h, n); + else { + const s = new APISession(h) + , n = s.request.bind(s); + n.session = s; + const p = "undefined" != typeof process && "test" === (null === (d = process.env) || void 0 === d ? void 0 : d.NODE_ENV); + Object.defineProperty(this, e, { + value: n, + writable: p, + enumerable: !0 + }) + } + } + } + class StationTrackLoader { + constructor(e, s, {dispatcher: n, logger: d, apiManager: h}, p={}) { + this.queue = e, + this.station = s, + this.context = p, + this.isActive = !1, + this.dispatcher = n, + this.logger = d, + this.apiManager = h + } + activate() { + this.dispatcher.unsubscribe(ns.queuePositionDidChange, this.checkLoadMore), + this.dispatcher.subscribe(ns.queuePositionDidChange, this.checkLoadMore), + this.isActive = !0 + } + deactivate() { + this.dispatcher.unsubscribe(ns.queuePositionDidChange, this.checkLoadMore), + this.isActive = !1 + } + start() { + return this.isActive || this.activate(), + this.loadNextTracks() + } + checkLoadMore() { + if (!(this.queue.isEmpty || this.queue.nextPlayableItemIndex >= 0)) + return this.loadNextTracks() + } + loadNextTracks() { + var e, s, n; + return __awaiter$3(this, void 0, void 0, (function*() { + let d = []; + const {apiManager: h} = this; + if ((null == h ? void 0 : h.api)instanceof MediaAPIV3) { + const s = yield h.api.music("v1/me/stations/next-tracks/" + this.station.id, void 0, { + fetchOptions: { + method: "POST" + } + }); + d = null === (e = null == s ? void 0 : s.data) || void 0 === e ? void 0 : e.data + } else + d = null !== (n = yield null === (s = h.mediaAPI) || void 0 === s ? void 0 : s.nextStationTracks(this.station.id)) && void 0 !== n ? n : []; + if (0 === d.length) + throw this.logger.warn("No track data is available for the current station", { + stationId: this.station.id + }), + new MKError(MKError.CONTENT_UNAVAILABLE,"No track data is available for the current station."); + const p = descriptorToMediaItems({ + context: this.context, + loaded: d, + container: this.station + }); + this.queue.splice(this.queue.length, 0, p) + } + )) + } + } + var Nn; + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", void 0)], StationTrackLoader.prototype, "checkLoadMore", null), + function(e) { + e.artist = "artist", + e.song = "song", + e.station = "station", + e.radioStation = "radioStation" + }(Nn || (Nn = {})); + const isIdentityQueue = e=>e && void 0 !== e.identity + , {queueIsReady: Ln} = ns; + class ContinuousPlaybackController extends PlaybackController { + constructor(e) { + super(e), + this.type = An.continuous, + this._isLive = !1, + this._continuous = !0 + } + get continuous() { + return !0 + } + set continuous(e) { + if (!0 !== e) + throw new MKError(MKError.UNSUPPORTED_ERROR,"Continuous playback cannot be disabled for station queues.") + } + get context() { + return Object.assign({ + featureName: tt.STATION + }, this._context) + } + get isLive() { + return this._isLive + } + set isLive(e) { + e !== this._isLive && (this._isLive = e, + this._dispatcher.publish(ns.capabilitiesChanged)) + } + changeToMediaItem(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + this.generateMethodNotAvailable("changeToMediaItem") + } + )) + } + hasCapabilities(e) { + switch (e) { + case pn.PAUSE: + case pn.SKIP_NEXT: + return !this.isLive; + case pn.SKIP_PREVIOUS: + case pn.SKIP_TO_ITEM: + return !1; + default: + return super.hasCapabilities(e) + } + } + pause(e) { + const s = Object.create(null, { + pause: { + get: ()=>super.pause + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + if (!this.isLive) + return s.pause.call(this, e); + this.generateMethodNotAvailable("pause") + } + )) + } + skipToPreviousItem() { + return __awaiter$3(this, void 0, void 0, (function*() { + this.generateMethodNotAvailable("skipToPreviousItem") + } + )) + } + _dataForQueueOptions(e) { + const s = Object.create(null, { + _dataForQueueOptions: { + get: ()=>super._dataForQueueOptions + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + const n = yield s._dataForQueueOptions.call(this, e); + return this.isLive && (n.loaded = this.station), + n + } + )) + } + returnQueueForOptions(e) { + var s; + return __awaiter$3(this, void 0, void 0, (function*() { + const n = isIdentityQueue(e) ? yield this.loadStationByIdentity(e.identity) : yield this.loadStationByStationId(this.generateStationId(e)); + if (void 0 === n) + return Promise.reject(new MKError(MKError.UNSUPPORTED_ERROR,"Cannot load requested station")); + this.station = n, + this.isLive = isIdentityQueue(e) || !!(null == n ? void 0 : n.isLive) || !!(null === (s = null == n ? void 0 : n.attributes) || void 0 === s ? void 0 : s.isLive); + const d = { + services: { + dispatcher: this._dispatcher + }, + descriptor: yield this._dataForQueueOptions(e) + }; + return this.queue = new Queue(d), + this.isLive || (this.trackLoader = new StationTrackLoader(this.queue,n,{ + dispatcher: this._dispatcher, + logger: Mr, + apiManager: this._services.apiManager + },this.context), + yield this.trackLoader.start()), + this._seekable = this.isLive ? new BaseSeekable(this._mediaItemPlayback) : new Seekable(this._dispatcher,this._mediaItemPlayback), + this._dispatcher.publish(Ln, this.queue.items), + this.queue + } + )) + } + getNewSeeker() { + return this.hasCapabilities(pn.SEEK) ? super.getNewSeeker() : new UnsupportedSeeker + } + skipToNextItem() { + const e = Object.create(null, { + skipToNextItem: { + get: ()=>super.skipToNextItem + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + if (!this.isLive) + return e.skipToNextItem.call(this); + this.generateMethodNotAvailable("skipToNextItem") + } + )) + } + generateMethodNotAvailable(e) { + Mr.warn(e + " is not supported for this type of playback") + } + generateStationId(e) { + let s; + if (isQueueURLOption(e)) { + const {contentId: n, kind: d, storefrontId: h} = formattedMediaURL(e.url); + e[d] = n, + un.storefrontId = h, + s = d + } + const n = e; + if (n.artist) + return "ra." + n.artist; + if (n.song) + return "ra." + n.song; + if (n.station) + return n.station; + if (n.radioStation) + return n.radioStation; + throw new MKError(MKError.UNSUPPORTED_ERROR,s ? s + " is not a supported option. Use setQueue instead." : "Unsupported options specified for setStationQueue. You may want setQueue instead.") + } + loadStationByIdentity(e) { + var s, n, d; + return __awaiter$3(this, void 0, void 0, (function*() { + const {apiManager: h} = this._services; + if ((null == h ? void 0 : h.api)instanceof MediaAPIV3) { + const d = yield h.api.music("v1/catalog/{{storefrontId}}/stations", { + filter: { + identity: e + } + }); + return null === (n = null === (s = null == d ? void 0 : d.data) || void 0 === s ? void 0 : s.data) || void 0 === n ? void 0 : n[0] + } + const p = yield null === (d = null == h ? void 0 : h.mediaAPI) || void 0 === d ? void 0 : d.stations(void 0, { + filter: { + identity: e + } + }); + return p && p[0] + } + )) + } + loadStationByStationId(e) { + var s, n, d; + return __awaiter$3(this, void 0, void 0, (function*() { + const {apiManager: h} = this._services; + if ((null == h ? void 0 : h.api)instanceof MediaAPIV3) { + const d = yield h.api.music("v1/catalog/{{storefrontId}}/stations/" + e); + return null === (n = null === (s = null == d ? void 0 : d.data) || void 0 === s ? void 0 : s.data) || void 0 === n ? void 0 : n[0] + } + return null === (d = null == h ? void 0 : h.mediaAPI) || void 0 === d ? void 0 : d.station(e) + } + )) + } + activate() { + super.activate(), + this.trackLoader && this.trackLoader.activate() + } + deactivate() { + const e = Object.create(null, { + deactivate: { + get: ()=>super.deactivate + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + yield e.deactivate.call(this), + this.trackLoader && this.trackLoader.deactivate() + } + )) + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Number]), __metadata$2("design:returntype", Boolean)], ContinuousPlaybackController.prototype, "hasCapabilities", null); + class PercentageWatcher { + constructor(e, s, n) { + this.dispatcher = e, + this.callback = s, + this.percentage = n, + this.threshold = -1 + } + startMonitor() { + this.dispatcher.unsubscribe(ns.playbackDurationDidChange, this.updateThreshold), + this.dispatcher.unsubscribe(ns.playbackTimeDidChange, this.handleTimeChange), + this.dispatcher.subscribe(ns.playbackDurationDidChange, this.updateThreshold), + this.dispatcher.subscribe(ns.playbackTimeDidChange, this.handleTimeChange) + } + stopMonitor() { + this.dispatcher.unsubscribe(ns.playbackDurationDidChange, this.updateThreshold), + this.dispatcher.unsubscribe(ns.playbackTimeDidChange, this.handleTimeChange), + this.threshold = -1 + } + handleTimeChange(e, {currentPlaybackDuration: s, currentPlaybackTime: n}) { + return __awaiter$3(this, void 0, void 0, (function*() { + this.threshold < 0 && this.updateThreshold(e, { + duration: s + }), + n < this.threshold || (this.stopMonitor(), + yield this.callback(n, this)) + } + )) + } + updateThreshold(e, {duration: s}) { + this.threshold = s * this.percentage + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", Promise)], PercentageWatcher.prototype, "handleTimeChange", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", void 0)], PercentageWatcher.prototype, "updateThreshold", null); + class Preloader extends PlaybackMonitor { + constructor(e) { + super(e), + this.isSeamlessAudioTransitionsEnabled = !1, + this.watchers = [new PercentageWatcher(this.dispatcher,this.handlePlaybackThreshold,.3)], + this.isSeamlessAudioTransitionsEnabled = ln.features["seamless-audio-transitions"] + } + handlePlaybackThreshold() { + return __awaiter$3(this, void 0, void 0, (function*() { + const e = this.getNextPlayableItem(); + e && (yield this.playbackController.prepareToPlay(e, !0)) + } + )) + } + shouldMonitor() { + if (!super.shouldMonitor()) + return !1; + if (!this.playbackController.hasAuthorization) + return !1; + const e = this.getNextPlayableItem() + , s = void 0 !== e; + return this.isSeamlessAudioTransitionsEnabled ? s : s && !(null == e ? void 0 : e.isPreparedToPlay) + } + getNextPlayableItem() { + return this.playbackController.queue.nextPlayableItem + } + } + function dasherize(e) { + return e.replace(/([A-Z])/g, "-$1").replace(/[-_\s]+/g, "-").toLowerCase() + } + const recursiveRelationshipLoad = (e,s,n)=>__awaiter$3(void 0, void 0, void 0, (function*() { + const [d,h,p] = s + , y = n.length; + if (y > 0 && y < p.limit + p.offset) + return n; + const m = Object.assign({}, p); + let g; + m.offset = y; + try { + g = yield e(d, h, m) + } catch (bt) { + return n + } + return n.push(...g), + g.length < m.limit ? n : recursiveRelationshipLoad(e, s, n) + } + )) + , getNamedQueueOptions = (e,s)=>{ + const n = [] + , d = e.namedQueueOptions; + for (const h in s) + Object.keys(d).includes(h) && n.push([h, d[h]]); + return n + } + , loadSelectedQueueValue = (e,s,n,d)=>__awaiter$3(void 0, void 0, void 0, (function*() { + const [h,p] = n + , y = Array.isArray(d) + , m = y ? "" + d[0] : "" + d + , g = yield e.getAPIForItem(m); + if (g instanceof MediaAPIV3) { + let e = dasherize(h); + e.endsWith("s") || (e += "s"); + const s = (v(m) ? "v1/me/library/" : "v1/catalog/{{storefrontId}}/") + e + (y ? "" : "/{{id}}") + , n = {}; + y && (n.ids = d); + const p = yield g.music(s, n, { + urlParameters: { + id: d + } + }); + return y ? p.data.data : p.data.data[0] + } + const _ = yield g[p.apiMethod](d, s.parameters); + return y || (yield function(e, s, n, d={}) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (void 0 === s) + return n; + void 0 === d.limit && (d.limit = 100), + void 0 === d.offset && (d.offset = 0); + const {relationship: h, method: p} = s + , y = e[p].bind(e); + let m; + return isDataRecord(n) ? (void 0 === n[h] && n.setProperty(h, [], "relationships"), + m = n[h]) : (n.relationships = n.relationships || {}, + void 0 === n.relationships[h] && Object.defineProperty(n.relationships, h, { + value: { + data: [] + }, + enumerable: !0 + }), + m = n.relationships[h].data), + yield recursiveRelationshipLoad(y, [n.id, h, d], m), + n + } + )) + }(g, p.relationshipMethod, _)), + _ + } + )) + , xn = ["library-songs", "songs"] + , isAutoplaySupportedForType = e=>xn.includes(e) + , normalizeTypeForAutoplay = (e,s)=>(v(e) && !(null != s ? s : "").startsWith("library-") ? "library-" : "") + normalizeContentType(s); + class AutoplayTrackLoader { + constructor(e, s, {dispatcher: n, logger: d, apiManager: h}, p={}) { + this.queue = e, + this.repeatable = s, + this.context = p, + this.isActive = !1, + this.errorIds = new Set, + this.dispatcher = n, + this.logger = d, + this.apiManager = h + } + activate() { + this.isActive || (this.dispatcher.unsubscribe(ns.queuePositionDidChange, this.onQueueChanged), + this.dispatcher.subscribe(ns.queuePositionDidChange, this.onQueueChanged), + this.dispatcher.unsubscribe(ns.repeatModeDidChange, this.onRepeatableChanged), + this.dispatcher.subscribe(ns.repeatModeDidChange, this.onRepeatableChanged), + this.isActive = !0) + } + deactivate() { + this.isActive && (this.dispatcher.unsubscribe(ns.queuePositionDidChange, this.onQueueChanged), + this.dispatcher.unsubscribe(ns.repeatModeDidChange, this.onRepeatableChanged), + this.isActive = !1, + this.station = void 0, + this.queue.hasAutoplayStation = !1) + } + start() { + if (!this.isActive) + return this.activate(), + this.loadNextTracks() + } + stop() { + this.isActive && (this.deactivate(), + this.cleanupQueue()) + } + onRepeatableChanged() { + this.repeatable.repeatMode === e.PlayerRepeatMode.none ? this.checkLoadMore() : this.cleanupQueue() + } + onQueueChanged() { + if (!(this.queue.nextPlayableItemIndex >= 0)) + return this.checkLoadMore() + } + checkLoadMore() { + var e; + const s = null !== (e = this.queue.unplayedAutoplayItems.length) && void 0 !== e ? e : 0 + , n = ln.autoplay.maxUpcomingTracksToMaintain; + if (!(this.queue.isEmpty || this.queue.unplayedUserItems.length > ln.autoplay.maxQueueSizeForAutoplay)) + return s < n ? this.loadNextTracks(n - s) : this.loadNextTracks() + } + cleanupQueue() { + this.queue.removeQueueItems((e,s)=>!(s <= this.queue.position) && !!e.isAutoplay) + } + loadNextTracks(s=ln.autoplay.maxUpcomingTracksToMaintain) { + var n, d, h; + return __awaiter$3(this, void 0, void 0, (function*() { + if (this.repeatable.repeatMode !== e.PlayerRepeatMode.none) + return; + let p, {station: y} = this; + if (this.station) { + try { + p = yield null === (n = this.apiManager.mediaAPI) || void 0 === n ? void 0 : n.nextStationTracks(this.station.id, { + limit: s + }) + } catch (bt) { + return + } + if (!this.isActive) + return + } else { + const e = yield this.startStation(s); + if (!e || !this.isActive) + return void (this.queue.hasAutoplayStation = !1); + y = this.station = e.station, + this.queue.hasAutoplayStation = !0, + p = e.tracks, + (null === (d = null == e ? void 0 : e.tracks) || void 0 === d ? void 0 : d.length) || this.logger.warn("No track data is available for the current station", { + stationId: null == y ? void 0 : y.id + }) + } + const m = descriptorToMediaItems({ + context: Object.assign(Object.assign({}, this.context), { + featureName: "now_playing", + reco_id: (null === (h = this.context.featureName) || void 0 === h ? void 0 : h.startsWith("listen-now")) ? void 0 : this.context.reco_id + }), + loaded: p, + container: y + }); + this.queue.appendQueueItems(toQueueItems(m, { + isAutoplay: !0 + })) + } + )) + } + startStation(e) { + var s, n; + return __awaiter$3(this, void 0, void 0, (function*() { + const {userAddedItems: d} = this.queue + , h = null !== (s = d[d.length - 2]) && void 0 !== s ? s : d[d.length - 1] + , p = null == h ? void 0 : h.container + , y = p ? { + container: { + id: p.id, + type: p.type + } + } : void 0 + , m = this.queue.items.slice(-1 * ln.autoplay.maxQueueSizeInRequest).reduce((e,{id: s, type: n})=>{ + const d = normalizeTypeForAutoplay(s, n); + return isAutoplaySupportedForType(d) && !this.errorIds.has(s) && e.push({ + id: s, + type: d, + meta: y + }), + e + } + , []); + if (0 === m.length) + return; + const g = { + data: m + }; + let v; + try { + v = yield null === (n = this.apiManager.mediaAPI) || void 0 === n ? void 0 : n.continuousStation(g, { + "limit[results:tracks]": e, + with: ["tracks"] + }) + } catch (bt) { + m.forEach(e=>this.errorIds.add(e.id)) + } + return v + } + )) + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", void 0)], AutoplayTrackLoader.prototype, "onRepeatableChanged", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", void 0)], AutoplayTrackLoader.prototype, "onQueueChanged", null), + __decorate$2([(e,s,n)=>{ + const d = n.value + , h = "_singlePromise_" + s + , p = "undefined" != typeof Symbol ? Symbol(h) : h; + return n.value = function(...e) { + if (this[p]) + return this[p]; + const s = this[p] = d.apply(this, e) + , reset = ()=>{ + this[p] = void 0 + } + ; + return s.then(reset, reset), + s + } + , + n + } + , __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Number]), __metadata$2("design:returntype", Promise)], AutoplayTrackLoader.prototype, "loadNextTracks", null); + const {queueIsReady: Un} = ns; + var $n, jn; + !function(e) { + e.album = "album", + e.musicVideo = "musicVideo", + e.playlist = "playlist", + e.song = "song", + e.episode = "episode", + e.podcast = "podcast", + e.uploadedAudio = "uploadedAudio", + e.uploadedVideo = "uploadedVideo" + }($n || ($n = {})), + function(e) { + e.albums = "albums", + e.musicVideos = "musicVideos", + e.playlists = "playlists", + e.songs = "songs", + e.episodes = "episodes", + e.podcasts = "podcasts", + e.uploadedAudio = "uploadedAudios", + e.uploadedVideo = "uploadedVideos" + }(jn || (jn = {})); + class SerialPlaybackController extends PlaybackController { + constructor(e) { + var s; + super(e), + this.type = An.serial, + this._queue = new Queue(e), + this._repeatable = new Repeatable(this._dispatcher), + this._seekable = new Seekable(this._dispatcher,this._mediaItemPlayback), + this._shuffler = new Shuffler(this,{ + dispatcher: this._dispatcher + }), + this._queueModifier = new ModifiableQueue(this._queue,this._mediaItemPlayback), + this._isSeamlessAudioTransitionsEnabled = !!(null === (s = null == e ? void 0 : e.bag) || void 0 === s ? void 0 : s.features["seamless-audio-transitions"]); + const n = { + controller: this, + services: e.services + }; + this._preloader = new Preloader(n) + } + get autoplayEnabled() { + return this._autoplayEnabled + } + set autoplayEnabled(e) { + var s; + this._autoplayEnabled = e; + const n = e ? "start" : "stop"; + null === (s = this._autoplayTrackLoader) || void 0 === s || s[n]() + } + activate() { + super.activate(), + this._preloader.activate(), + this._dispatcher.subscribe(Gr, this.onSeamlessAudioTransition) + } + deactivate() { + const e = Object.create(null, { + deactivate: { + get: ()=>super.deactivate + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + yield e.deactivate.call(this), + this._preloader.deactivate(), + this._dispatcher.unsubscribe(Gr, this.onSeamlessAudioTransition) + } + )) + } + onSeamlessAudioTransition(s, n) { + Mr.debug("controller handling seamless audio transition, PAF stop", n), + this._dispatcher.publish(et.playbackStop, { + endReasonType: e.PlayActivityEndReasonType.NATURAL_END_OF_TRACK, + position: n.previous.playbackDuration / 1e3, + isPlaying: !1 + }), + asAsync(this._next(!1, !0)) + } + hasCapabilities(e) { + var s, n; + return e === pn.SKIP_PREVIOUS || (e !== pn.REPEAT && e !== pn.SHUFFLE || !(null === (n = null === (s = this.queue) || void 0 === s ? void 0 : s.currentQueueItem) || void 0 === n ? void 0 : n.isAutoplay)) && super.hasCapabilities(e) + } + prepareToPlay(s, n=!1) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (Mr.debug("mk: SerialController - prepareToPlay - ", { + item: s, + preload: n + }), + s.isPlayable) + return this._mediaItemPlayback.prepareToPlay(s).catch(s=>{ + const d = !n && -1 === [MKError.DEVICE_LIMIT, MKError.STREAM_UPSELL].indexOf(s.errorCode); + if (this.continuous && d) + return this._dispatcher.publish(et.applicationActivityIntent, { + endReasonType: e.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS, + userInitiated: !1 + }), + this._next(); + throw s + } + ) + } + )) + } + prepend(e, s) { + const n = Object.create(null, { + prepend: { + get: ()=>super.prepend + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + const d = yield n.prepend.call(this, e, s); + if (this.shouldTransitionSeamlessly) { + const e = this.queue + , s = e.position + , n = e.item(s + 1); + Mr.debug("prepend preparing ", n.title), + yield this._mediaItemPlayback.prepareToPlay(n) + } + return d + } + )) + } + returnQueueForOptions(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + void 0 !== (e = parseQueueURLOption(e)).startPosition && (logDeprecation("startPosition", { + message: "startPosition has been deprecated in favor of startWith" + }), + void 0 === e.startWith && (e.startWith = e.startPosition)); + const s = yield this._dataForQueueOptions(e) + , n = { + services: { + dispatcher: this._dispatcher, + mediaItemPlayback: this._mediaItemPlayback + }, + descriptor: s + }; + if (void 0 !== e.shuffleMode && (this.shuffleMode = e.shuffleMode), + this.queue = new Queue(n), + "number" == typeof e.startTime) { + const s = this.queue.nextPlayableItem; + s && this._mediaItemPlayback.playOptions.set(s.id, { + startTime: e.startTime + }) + } + if (0 === this.queue.length) + throw Mr.warn("No item data is available for the current media queue", e), + new MKError(MKError.CONTENT_UNAVAILABLE,"No item data is available for the current media queue."); + return this._autoplayTrackLoader && this._autoplayTrackLoader.deactivate(), + this._autoplayTrackLoader = new AutoplayTrackLoader(this.queue,this._repeatable,{ + dispatcher: this._dispatcher, + logger: Mr, + apiManager: this._services.apiManager + },this._context), + this.autoplayEnabled && this._autoplayTrackLoader.start(), + this._dispatcher.publish(Un, this.queue.items), + this.queue + } + )) + } + skipToPreviousItem() { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._previous(!0) + } + )) + } + _dataForQueueOptions(e) { + const s = Object.create(null, { + _dataForQueueOptions: { + get: ()=>super._dataForQueueOptions + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + const n = e + , d = ((e,s)=>{ + const n = getNamedQueueOptions(e, s); + if (n.length > 1) + throw new MKError(MKError.UNSUPPORTED_ERROR,"Queues with multiple media types are not supported."); + if (0 === n.length) + return; + const [d] = n + , [h,p] = d; + if (Array.isArray(s[h]) !== p.isPlural) + throw new MKError(MKError.UNSUPPORTED_ERROR,p.isPlural ? `Queue option ${h} must be an array of id values` : `Queue option ${h} must be a single id value`); + return d + } + )(this._services.apiManager.apiService, e); + return void 0 === d || (n.loaded = yield((e,s,n)=>__awaiter$3(void 0, void 0, void 0, (function*() { + const [d,h] = n + , p = s[d]; + if (Array.isArray(p)) { + const d = new Map; + p.forEach(e=>{ + const s = e.indexOf(".") + , n = -1 === s ? "" : e.substring(0, s); + d.has(n) || d.set(n, []); + const h = d.get(n); + h && h.push(e) + } + ); + const h = (yield Promise.all([...d.values()].map(d=>loadSelectedQueueValue(e, s, n, d)))).reduce((e,s)=>{ + var n; + return (s = null !== (n = s.data) && void 0 !== n ? n : s).forEach(s=>{ + e.set(s.id, s) + } + ), + e + } + , new Map) + , y = []; + return p.forEach(e=>{ + const s = h.get(e); + s && y.push(s) + } + ), + y + } + return loadSelectedQueueValue(e, s, n, p) + } + )))(this._services.apiManager.apiService, e, d)), + Object.assign(Object.assign({}, yield s._dataForQueueOptions.call(this, e)), n) + } + )) + } + _changeToMediaAtIndex(e=0, s=!1) { + const n = Object.create(null, { + _changeToMediaAtIndex: { + get: ()=>super._changeToMediaAtIndex + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + const d = yield n._changeToMediaAtIndex.call(this, e, s) + , h = this.queue.nextPlayableItem; + return h && this.shouldTransitionSeamlessly && (yield this.prepareToPlay(h)), + d + } + )) + } + _next(s=!1, n=!1) { + return __awaiter$3(this, void 0, void 0, (function*() { + let d = this.queue.nextPlayableItemIndex; + return this.repeatMode === e.PlayerRepeatMode.one && -1 !== this.nowPlayingItemIndex && (d = this.nowPlayingItemIndex), + this._nextAtIndex(d, s, n) + } + )) + } + _previous(s=!1) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this.queue.isEmpty) + return; + const n = this.queue; + if (-1 === n.previousPlayableItemIndex) + return; + const d = this.isPlaying + , h = this._mediaItemPlayback.currentPlaybackTime + , p = yield this._changeToMediaAtIndex(n.previousPlayableItemIndex, s); + return this._notifySkip(d, p, !1, { + userInitiated: s, + direction: e.PlayActivityEndReasonType.TRACK_SKIPPED_BACKWARDS, + position: h + }), + p + } + )) + } + _prepareQueue(e) { + super._prepareQueue(e), + this._shuffler.checkAndReshuffle() + } + get shouldTransitionSeamlessly() { + return this._isSeamlessAudioTransitionsEnabled && this.hasAuthorization + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", void 0)], SerialPlaybackController.prototype, "onSeamlessAudioTransition", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Number]), __metadata$2("design:returntype", Boolean)], SerialPlaybackController.prototype, "hasCapabilities", null); + class MKDialog { + constructor(e, s="") { + this._message = e, + this._explanation = s, + this.id = "musickit-dialog", + this.scrimId = this.id + "-scrim", + this.styleId = this.id + "-style", + this._okButtonString = "OK", + [this.id, this.scrimId, this.styleId].forEach(e=>{ + try { + const s = document.getElementById(e); + s.parentElement.removeChild(s) + } catch (s) {} + } + ), + this._appendStyle("\n#musickit-dialog {\n --mk-dialog-background: rgba(255, 255, 255, 1);\n --mk-dialog-text: rgba(0, 0, 0, 0.95);\n --mk-dialog-border: rgba(0, 0, 0, 0.07);\n --mk-dialog-scrim: rgba(255, 255, 255, 0.8);\n --mk-dialog-primary: rgba(0, 122, 255, 1);\n}\n\n@media (prefers-color-scheme: dark) {\n #musickit-dialog {\n --mk-dialog-background: rgba(30, 30, 30, 1);\n --mk-dialog-text: rgba(255, 255, 255, 0.85);\n --mk-dialog-border: rgba(255, 255, 255, 0.1);\n --mk-dialog-scrim: rgba(38, 38, 38, 0.8);\n --mk-dialog-primary: rgba(8, 132, 255, 1);\n }\n}\n\n#musickit-dialog-scrim {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.35);\n}\n\n#musickit-dialog * {\n -webkit-tap-highlight-color: transparent;\n -webkit-touch-callout: none;\n -ms-touch-action: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, sans-serif;\n font-size: 15px;\n line-height: 20px;\n}\n\n#musickit-dialog *:focus { outline: 0; }\n\n#musickit-dialog {\n display: -webkit-box;\n display: -moz-box;\n display: -ms-flexbox;\n display: -webkit-flex;\n display: flex;\n -webkit-flex-direction: column;\n -moz-flex-direction: column;\n flex-direction: column;\n -webkit-justify-content: space-between;\n -moz-justify-content: space-between;\n justify-content: space-between;\n min-width: 277px;\n max-width: 290px;\n min-height: 109px;\n background: var(--mk-dialog-background);\n box-shadow: 0px 0px 9px rgba(0, 0, 0, 0.18);\n border-radius: 10px;\n color: var(--mk-dialog-text);\n position: fixed;\n top: 50%;\n left: 50%;\n margin-left: -142px;\n margin-top: -67px;\n z-index: 9999999999999999999999999;\n}\n\n#musickit-dialog #mk-dialog-body {\n display: -webkit-box;\n display: -moz-box;\n display: -ms-flexbox;\n display: -webkit-flex;\n display: flex;\n -webkit-flex-direction: column;\n -moz-flex-direction: column;\n flex-direction: column;\n flex-grow: 1;\n -webkit-justify-content: space-evenly;\n -moz-justify-content: space-evenly;\n justify-content: space-evenly;\n -webkit-align-items: stretch;\n align-items: stretch;\n padding: 10px 20px;\n min-height: 74px;\n text-align: center;\n}\n\n#musickit-dialog .mk-dialog h5 {\n font-weight: 500;\n line-height: 20px;\n margin: 7px 0 0 0;\n padding: 0;\n}\n\n#musickit-dialog .mk-dialog p {\n margin: 0 0 7px 0;\n padding: 0;\n paddin-top: 3px;\n line-height: 18px;\n font-size: 13px;\n font-weight: 300;\n}\n\n#musickit-dialog #mk-dialog-actions {\n border-top: 1px solid var(--mk-dialog-border);\n display: -webkit-box;\n display: -moz-box;\n display: -ms-flexbox;\n display: -webkit-flex;\n display: flex;\n -webkit-flex-direction: row;\n -moz-flex-direction: colrowumn;\n flex-direction: row;\n max-height: 41px;\n min-height: 34px;\n -webkit-justify-self: flex-end;\n -moz-justify-self: flex-end;\n justify-self: flex-end;\n}\n\n#musickit-dialog #mk-dialog-actions button {\n flex-grow: 1;\n border: 0;\n background: none;\n color: var(--mk-dialog-primary);\n padding: 0;\n margin: 0;\n min-height: 34px;\n height: 41px;\n text-align: center;\n}\n\n#musickit-dialog #mk-dialog-actions *:nth-child(2) {\n border-left: 1px solid var(--mk-dialog-border);\n font-weight: 500;\n}\n") + } + static presentError(e) { + const s = e.dialog; + void 0 !== s ? MKDialog.serverDialog(s).present() : new MKDialog(e.message).present() + } + static serverDialog(e) { + const s = new this(e.message,e.explanation); + return e.okButtonAction && e.okButtonAction.url && (s._okButtonActionURL = e.okButtonAction.url), + e.okButtonString && (s._okButtonString = e.okButtonString), + e.cancelButtonString && (s._cancelButtonString = e.cancelButtonString), + s + } + static clientDialog(e) { + const s = new this(e.message,e.explanation); + return e.okButtonAction && (s._okButtonAction = e.okButtonAction), + e.cancelButtonAction && (s._cancelButtonAction = e.cancelButtonAction), + e.okButtonString && (s._okButtonString = e.okButtonString), + e.cancelButtonString && (s._cancelButtonString = e.cancelButtonString), + s + } + get actions() { + return this.cancelButton ? `
${this.cancelButton}${this.okButton}
` : `
${this.okButton}
` + } + get cancelButton() { + if ("string" == typeof this._cancelButtonString) + return `` + } + set cancelButton(e) { + this._cancelButtonString = e + } + get explanation() { + return `

${this._explanation}

` + } + get hasOKButtonAction() { + return !!this._okButtonActionURL || !!this._okButtonAction + } + get message() { + return `
${this._message}
` + } + get okButton() { + return this.hasOKButtonAction && this._okButtonActionURL ? `` : `` + } + present() { + const e = document.createDocumentFragment() + , s = document.createElement("div"); + s.id = this.scrimId, + e.appendChild(s); + const n = document.createElement("div"); + n.id = this.id, + n.classList.add("mk-dialog"), + n.setAttribute("role", "alertDialog"), + n.setAttribute("aria-modal", "true"), + n.setAttribute("aria-labeledby", "mk-dialog-title"), + n.setAttribute("aria-describedby", "mk-dialog-explanation"); + let d = `\n
\n ${this.message}\n ${this.explanation}\n
`; + d = `\n ${d}\n ${this.actions}\n `, + n.innerHTML = d, + e.appendChild(n), + document.body.appendChild(e), + document.querySelector(`#${n.id} #mk-dialog-actions *:first-child`).focus(), + setTimeout(()=>{ + document.querySelector(`#${n.id} #mk-dialog-actions *:first-child`).addEventListener("click", ()=>{ + this._cancelButtonAction && this._cancelButtonAction(), + n.parentElement.removeChild(n), + s.parentElement.removeChild(s) + } + ), + this.hasOKButtonAction && (this._okButtonActionURL ? document.querySelector(`#${n.id} #mk-dialog-actions *:last-child`).addEventListener("click", e=>{ + window.open(e.target.dataset.okActionUrl, "_blank"), + n.parentElement.removeChild(n), + s.parentElement.removeChild(s) + } + ) : this._okButtonAction && document.querySelector(`#${n.id} #mk-dialog-actions *:last-child`).addEventListener("click", e=>{ + this._okButtonAction(), + n.parentElement.removeChild(n), + s.parentElement.removeChild(s) + } + )) + } + ) + } + _appendStyle(e) { + const s = document.createElement("style"); + s.id = this.styleId, + s.styleSheet ? s.styleSheet.cssText = e : s.innerHTML = e, + document.body.appendChild(s) + } + } + function getPlayerType(e) { + var s, n; + switch (null == e ? void 0 : e.type) { + case "contributors": + case "modalities": + case "movie": + case "musicVideo": + case "musicMovie": + case "trailer": + case "tvEpisode": + case "uploadedVideo": + case "uploaded-videos": + case "music-videos": + case "music-movies": + case "tv-episodes": + case "workouts": + return "video"; + case "podcast-episodes": + return "audio"; + default: + return null !== (n = null === (s = null == e ? void 0 : e.attributes) || void 0 === s ? void 0 : s.mediaKind) && void 0 !== n ? n : "audio" + } + } + const {audioTracksSwitched: Bn, audioTracksUpdated: Kn, textTracksSwitched: Fn, textTracksUpdated: Vn} = zs; + class HlsJsTracks extends Notifications { + constructor(e) { + super([Bn, Kn, Fn, Vn]), + this.session = e, + this._audioTracks = [], + this._textTracks = [], + this.session.on(window.Hls.Events.MANIFEST_LOADED, this.handleManifestLoaded.bind(this)), + this.session.on(window.Hls.Events.AUDIO_TRACK_SWITCHED, this.handleAudioTrackSwitched.bind(this)), + this.session.on(window.Hls.Events.SUBTITLE_TRACK_SWITCH, this.handleSubtitleTrackSwitch.bind(this)) + } + get audioTracks() { + return this._audioTracks + } + get textTracks() { + return this._textTracks + } + set audioTrack(e) { + this.session && e && e.id && (this.session.audioSelectedPersistentID = e.id) + } + set textTrack(e) { + var s; + this.session.subtitleSelectedPersistentID = null !== (s = null == e ? void 0 : e.id) && void 0 !== s ? s : -1 + } + selectForcedTrack() { + const {session: e} = this; + if (!(null == e ? void 0 : e.audioTracks)) + return; + const s = e.audioTracks.filter(s=>s.persistentID === e.audioSelectedPersistentID) + , n = s && s.length && s[0]; + if (!n) + return; + const d = e.subtitleMediaOptions.filter(e=>0 === e.MediaSelectionOptionsDisplaysNonForcedSubtitles && e.MediaSelectionOptionsExtendedLanguageTag === n.lang) + , h = null == d ? void 0 : d[0]; + let p; + return h ? (O.debug("hlsjsTracks: found forced track for " + h.MediaSelectionOptionsExtendedLanguageTag), + e.subtitleSelectedPersistentID = h.MediaSelectionOptionsPersistentID, + p = this.normalizeTextTrack(h)) : e.subtitleSelectedPersistentID = -1, + p + } + audioTracksUpdated(e, s) { + const n = s && s.audioMediaSelectionGroup && s.audioMediaSelectionGroup.MediaSelectionGroupOptions || []; + window.hlsSession = this.session; + const d = n.map(this.normalizeAudioTrack, this); + this._audioTracks = d, + this.dispatchEvent(Kn, d) + } + handleAudioTrackSwitched() { + this.dispatchEvent(Bn, { + selectedId: this.session.audioSelectedPersistentID + }) + } + handleManifestLoaded(e, s) { + this.audioTracksUpdated(e, s), + this.subtitleTracksUpdated(e, s) + } + handleSubtitleTrackSwitch(e, s) { + this.dispatchEvent(Fn, s) + } + subtitleTracksUpdated(e, s) { + const n = s && s.subtitleMediaSelectionGroup && s.subtitleMediaSelectionGroup.MediaSelectionGroupOptions || [] + , d = []; + n.forEach(e=>{ + 0 !== e.MediaSelectionOptionsDisplaysNonForcedSubtitles && d.push(this.normalizeTextTrack(e)) + } + ), + this._textTracks = d, + this.dispatchEvent(Vn, d) + } + normalizeAudioTrack(e) { + var s; + const n = "public.accessibility.describes-video" === (null === (s = e.MediaSelectionOptionsTaggedMediaCharacteristics) || void 0 === s ? void 0 : s[0]) ? "description" : "main"; + return Object.assign(Object.assign({}, this.normalizeSelectionOption(e)), { + enabled: !1, + kind: n + }) + } + normalizeTextTrack(e) { + var s; + let n; + return n = (null === (s = e.MediaSelectionOptionsTaggedMediaCharacteristics) || void 0 === s ? void 0 : s.includes("public.accessibility.describes-music-and-sound")) || "clcp" === e.MediaSelectionOptionsMediaType ? "captions" : "subtitles", + Object.assign(Object.assign({}, this.normalizeSelectionOption(e)), { + mode: "disabled", + kind: n + }) + } + normalizeSelectionOption(e) { + return { + id: e.MediaSelectionOptionsPersistentID, + label: e.MediaSelectionOptionsName, + language: e.MediaSelectionOptionsExtendedLanguageTag + } + } + } + const Hn = { + keySystemGenericError: "keySystemGenericError" + } + , zn = {}; + zn[kr.FAIRPLAY] = "fairplaystreaming", + zn[kr.PLAYREADY] = "playready", + zn[kr.WIDEVINE] = "widevine"; + const qn = !!createLocalStorageFlag("mk-hlsjs-debug").json(); + qn || (window.globalHlsLogConfig = qn); + const Wn = !!createLocalStorageFlag("mk-block-report-cdn-server").json(); + class HlsJsVideoPlayer extends VideoPlayer { + constructor(e) { + var s; + super(e), + this._channelsByGroup = {}, + this._rtcTracker = null === (s = null == e ? void 0 : e.playbackServices) || void 0 === s ? void 0 : s.getRTCStreamingTracker(), + this._license = new License + } + get shouldDispatchErrors() { + return !this.userInitiated || this._playbackDidStart + } + initializeExtension() { + return __awaiter$3(this, void 0, void 0, (function*() { + this._keySystem = yield findKeySystemPreference(); + try { + if (!Hs.urls.hls) + throw new Error("bag.urls.hls is not configured"); + yield loadScript(Hs.urls.hls) + } catch (bt) { + throw O.error("hlsjs-video-player failed to load script " + Hs.urls.hls, bt), + bt + } + } + )) + } + destroy() { + O.debug("hlsjs-video-player.destroy"); + const {_hls: e} = this; + e && (e.stopLoad(), + e.detachMedia(), + e.destroy()), + super.destroy(), + asAsync(this._license.stop()) + } + playHlsStream(e, s) { + O.debug("hlsjs-video-player.playHlsStream", e, s); + const {_keySystem: n} = this; + if (!n) + return; + let d, h; + this.createHlsPlayer(), + n === kr.WIDEVINE && (d = "WIDEVINE_SOFTWARE", + h = { + initDataTypes: ["cenc", "keyids"], + distinctiveIdentifier: "optional", + persistentState: "required" + }); + const p = { + platformInfo: { + requiresCDMAttachOnStart: !0, + maxSecurityLevel: d, + keySystemConfig: h + }, + appData: { + serviceName: Hs.app.name + } + } + , {_rtcTracker: y, _hls: m} = this; + if (y) { + const e = y.prepareReportingAgent(s); + void 0 !== e && (p.appData.reportingAgent = e) + } + O.debug("RTC: loadSource with load options", p), + m.loadSource(e, p), + m.attachMedia(this.video), + s && (this._licenseServerUrl = s.keyURLs["hls-key-server-url"], + n === kr.FAIRPLAY ? m.setProtectionData({ + fairplaystreaming: { + serverCertUrl: s.keyURLs["hls-key-cert-url"] + } + }) : m.setProtectionData({ + widevine: { + serverCertUrl: s.keyURLs["widevine-cert-url"] + } + })) + } + createHlsPlayer() { + const {_keySystem: e} = this + , {Hls: s} = window + , n = { + clearMediaKeysOnPromise: !1, + customTextTrackCueRenderer: !0, + debug: qn, + enablePerformanceLogging: qn, + enablePlayReadyKeySystem: !0, + enableRtcReporting: void 0 !== this._rtcTracker, + keySystemPreference: zn[e], + useMediaKeySystemAccessFilter: !0 + }; + (e=>{ + const {Hls: s} = window; + if (s && Wn) { + const n = Object.assign({}, s.DefaultConfig.fragLoadPolicy); + n.default = Object.assign({}, s.DefaultConfig.fragLoadPolicy.default), + n.customURL = Object.assign({}, s.DefaultConfig.fragLoadPolicy.customURL), + n.default.reportCDNServer = !1, + n.customURL.reportCDNServer = !1, + e.fragLoadPolicy = n + } + } + )(n); + const d = new s(n) + , {ERROR: h, INTERNAL_ERROR: p, MANIFEST_PARSED: y, KEY_REQUEST_STARTED: m, LICENSE_CHALLENGE_CREATED: g, LEVEL_SWITCHED: v} = s.Events; + d.on(h, this.handleHlsError), + d.on(p, this.handleHlsError), + d.on(y, this.handleManifestParsed), + d.on(m, this.handleKeyRequestStarted), + d.on(g, this.handleLicenseChallengeCreated), + d.on(v, this.handleLevelSwitched), + this._hls = d, + this.setupTrackManagers(new HlsJsTracks(d)) + } + handleLevelSwitched(e, s) { + var n, d; + const {level: h} = s; + if (!h) + return; + const p = null === (n = this._levels) || void 0 === n ? void 0 : n.find(e=>e.persistentId === h); + if (!p || (null === (d = this._currentLevel) || void 0 === d ? void 0 : d.persistentId) === (null == p ? void 0 : p.persistentId)) + return; + this._currentLevel = p; + const y = void 0 !== p.audioGroupId ? this._channelsByGroup[p.audioGroupId] : void 0; + this._dispatcher.publish(et.hlsLevelUpdated, { + level: p, + channels: y + }) + } + handleHlsError(e, s) { + O.warn("HLS.js error", s); + let n = new MKError(MKError.UNSUPPORTED_ERROR,s.reason); + n.data = s; + const {keySystemGenericError: d} = Hn; + if (s.details !== d) { + if ("output-restricted" === s.reason && (n = new MKError(MKError.OUTPUT_RESTRICTED,s.reason)), + s.fatal) { + if (this._hls.destroy(), + !this.shouldDispatchErrors) + throw n; + this._dispatcher.publish(rs.mediaPlaybackError, n) + } + } else + this._dispatcher.publish(d, n) + } + handleManifestParsed(e, s) { + var n, d; + this._levels = null !== (n = s.levels) && void 0 !== n ? n : [], + this.nowPlayingItem.state = D.ready, + this._channelsByGroup = (null !== (d = s.audioTracks) && void 0 !== d ? d : []).reduce((e,s)=>(e[s.groupId] = s.channels, + e), {}), + asAsync(this._playMedia()) + } + handleKeyRequestStarted(e, s) { + O.debug("hlsjs-video.handleKeyRequestStarted"), + this._hls.generateKeyRequest(s.keyuri, {}) + } + handleLicenseChallengeCreated(e, s) { + var n; + return __awaiter$3(this, void 0, void 0, (function*() { + const {_licenseServerUrl: e, nowPlayingItem: d, _keySystem: h, userInitiated: p} = this; + try { + const y = yield null === (n = this._license) || void 0 === n ? void 0 : n.start(e, d, s, h, p) + , m = { + statusCode: y.status + }; + (null == y ? void 0 : y.license) && (h === kr.FAIRPLAY ? m.ckc = ze(y.license) : m.license = ze(y.license)); + const g = y["renew-after"]; + g && (m.renewalDate = new Date(Date.now() + 1e3 * g)), + this._hls.setLicenseResponse(s.keyuri, m) + } catch (bt) { + const n = bt.data + , d = {}; + void 0 !== (null == n ? void 0 : n.status) && (d.statusCode = +n.status), + O.warn("Passing license response error to Hls.js", d), + this._hls.setLicenseResponse(s.keyuri, d), + this.onPlaybackLicenseError(bt) + } + } + )) + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", void 0)], HlsJsVideoPlayer.prototype, "handleLevelSwitched", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", void 0)], HlsJsVideoPlayer.prototype, "handleHlsError", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", void 0)], HlsJsVideoPlayer.prototype, "handleManifestParsed", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", void 0)], HlsJsVideoPlayer.prototype, "handleKeyRequestStarted", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", Promise)], HlsJsVideoPlayer.prototype, "handleLicenseChallengeCreated", null); + const {mediaPlaybackError: Yn} = rs + , {playbackLicenseError: Gn, playbackSessionError: Qn} = zs; + class NativeSafariVideoPlayer extends VideoPlayer { + initializeExtension() { + return __awaiter$3(this, void 0, void 0, (function*() { + const e = new MediaExtension(this.video,'video/mp4;codecs="avc1.42E01E"'); + this.extension = e, + yield e.initializeKeySystem(), + e.addEventListener(Gn, this.onPlaybackLicenseError), + e.addEventListener(Qn, this.onPlaybackSessionError) + } + )) + } + destroy() { + O.debug("native-safari-video-player.destroy"); + const {extension: e} = this; + e && (e.removeEventListener(Gn, this.onPlaybackLicenseError), + e.removeEventListener(Qn, this.onPlaybackSessionError), + this.video.removeEventListener("loadedmetadata", this.onMetadataLoaded), + super.destroy()) + } + playHlsStream(e) { + var s; + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("native-safari-video-player.playHlsStream", e), + this.setupTrackManagers(), + this.video.src = e; + const {nowPlayingItem: n} = this; + n && (null === (s = this.extension) || void 0 === s || s.setMediaItem(n)), + this.video.addEventListener("loadedmetadata", this.onMetadataLoaded) + } + )) + } + onPlaybackSessionError(e) { + this._dispatcher.publish(Yn, new MKError(MKError.MEDIA_SESSION,e)) + } + onMetadataLoaded() { + O.debug("native-safari-video-player.onMetadataLoaded"); + const {nowPlayingItem: e} = this; + e && (e.state = D.ready), + asAsync(this._playMedia()) + } + } + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object]), __metadata$2("design:returntype", void 0)], NativeSafariVideoPlayer.prototype, "onPlaybackSessionError", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", void 0)], NativeSafariVideoPlayer.prototype, "onMetadataLoaded", null); + class Factory { + constructor(e) { + this._playersByType = {}, + this._playerOptions = e + } + getPlayerForMediaItem(e, s, n) { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("mk: getPlayerForMediaItem", e, s); + const d = getPlayerType(e); + let h = this._playersByType[d]; + if ((null == h ? void 0 : h.isDestroyed) && (O.debug("mk: existingPlayer was previously destroyed. Removing from factory."), + h = void 0, + delete this._playersByType[d]), + h && h === n) + return n; + if (h) + return this._applyPlayerState(h, s), + h; + const {_playerOptions: p} = this; + let y; + switch (d) { + case "audio": + y = new AudioPlayer(p), + this._playersByType[d] = y; + break; + case "video": + y = (yield this._playerOptions.playbackServices.requiresHlsJs()) ? new HlsJsVideoPlayer(p) : new NativeSafariVideoPlayer(p); + break; + default: + throw new Error("Invalid player type requested: " + d) + } + return yield y.initialize(), + this._applyPlayerState(y, s), + y + } + )) + } + _applyPlayerState(e, s) { + return s ? (O.debug("_applyPlayerState", s), + Object.keys(s).forEach(n=>{ + void 0 !== e[n] && (e[n] = s[n]) + } + ), + e) : e + } + destroy() { + Object.values(this._playersByType).forEach(e=>e.destroy()) + } + } + const {mediaPlaybackError: Jn, playerTypeDidChange: Xn} = rs + , {playbackLicenseError: Zn} = zs + , {keySystemGenericError: ea} = Hn; + let ta = !1; + class MediaItemPlayback { + constructor(e) { + this.playerState = { + playbackRate: 1, + volume: 1 + }, + this.playOptions = new Map, + this._previewOnly = !1; + const {playbackServices: s} = e; + var n, d; + this.hasMusicSubscription = s.hasMusicSubscription, + this.playMediaItem = s.playMediaItem, + this.prepareForEncryptedPlayback = s.prepareForEncryptedPlayback, + n = e.tokens, + Rr = n, + e.bag && (d = e.bag, + Object.assign(Hs, d)), + this._dispatcher = e.services.dispatcher, + this._playerFactory = new Factory(e), + this._currentPlayer = new PlayerStub(e), + this._dispatcher.subscribe(Zn, this.onPlaybackLicenseError), + this._dispatcher.subscribe(ea, this.onKeySystemGenericError) + } + get currentPlaybackTime() { + return this._currentPlayer.currentPlaybackTime + } + get currentPlaybackTimeRemaining() { + return this._currentPlayer.currentPlaybackTimeRemaining + } + get audioTracks() { + return this._currentPlayer.audioTracks + } + get currentAudioTrack() { + return this._currentPlayer.currentAudioTrack + } + set currentAudioTrack(e) { + this._currentPlayer.currentAudioTrack = e + } + get currentPlaybackDuration() { + return this._currentPlayer.currentPlaybackDuration + } + get currentBufferedProgress() { + return this._currentPlayer.currentBufferedProgress + } + set currentBufferedProgress(e) { + this._currentPlayer.currentBufferedProgress = e + } + get currentPlaybackProgress() { + return this._currentPlayer.currentPlaybackProgress + } + set currentPlaybackProgress(e) { + this._currentPlayer.currentPlaybackProgress = e + } + get currentTextTrack() { + return this._currentPlayer.currentTextTrack + } + set currentTextTrack(e) { + this._currentPlayer.currentTextTrack = e + } + get previewOnly() { + return this._previewOnly + } + set previewOnly(e) { + this._previewOnly = e, + this._currentPlayer && (this._currentPlayer.previewOnly = e) + } + get formattedCurrentPlaybackDuration() { + return this._currentPlayer.formattedCurrentPlaybackDuration + } + get isPlaying() { + return this._currentPlayer.isPlaying + } + get isPrimaryPlayer() { + return this._currentPlayer.isPrimaryPlayer + } + set isPrimaryPlayer(e) { + this._currentPlayer.isPrimaryPlayer = e + } + get isReady() { + return this._currentPlayer.isReady + } + get nowPlayingItem() { + return this._currentPlayer.nowPlayingItem + } + get playbackRate() { + return this._currentPlayer.playbackRate + } + set playbackRate(e) { + this._updatePlayerState("playbackRate", e) + } + get playbackState() { + return this._currentPlayer.playbackState + } + set playbackState(e) { + this._currentPlayer.playbackState = e + } + get playbackTargetAvailable() { + return this._currentPlayer.playbackTargetAvailable + } + get playbackTargetIsWireless() { + return this._currentPlayer.playbackTargetIsWireless + } + get textTracks() { + return this._currentPlayer.textTracks + } + get volume() { + return this._currentPlayer.volume + } + set volume(e) { + this._updatePlayerState("volume", e) + } + clearNextManifest() { + this._currentPlayer.clearNextManifest() + } + destroy() { + var e, s; + this._playerFactory.destroy(), + null === (e = this._dispatcher) || void 0 === e || e.unsubscribe(Zn, this.onPlaybackLicenseError), + null === (s = this._dispatcher) || void 0 === s || s.unsubscribe(ea, this.onKeySystemGenericError) + } + exitFullscreen() { + return this._currentPlayer.exitFullscreen() + } + getNewSeeker() { + return this._currentPlayer.newSeeker() + } + mute() { + this._volumeAtMute = this.volume, + this.volume = 0 + } + pause(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._currentPlayer.pause(e) + } + )) + } + play() { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._currentPlayer.play() + } + )) + } + preload() { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._currentPlayer.preload() + } + )) + } + prepareToPlay(e) { + var s; + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("invoking prepareToPlay for ", e.title); + const n = yield this.prepareForEncryptedPlayback(e, this._currentPlayer) + , d = null === (s = this._currentPlayback) || void 0 === s ? void 0 : s.item + , h = Hs.features["seamless-audio-transitions"] + , p = "song" === (null == d ? void 0 : d.type) && "song" === e.type; + return h && p && (O.debug(`setting ${e.title} for seamless audio transition`), + yield this._currentPlayer.setNextSeamlessItem(e)), + n + } + )) + } + requestFullscreen(e) { + return this._currentPlayer.requestFullscreen(e) + } + showPlaybackTargetPicker() { + this._currentPlayer.showPlaybackTargetPicker() + } + seekToTime(e, s=rt.Manual) { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this._currentPlayer.seekToTime(e, s) + } + )) + } + setPresentationMode(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._currentPlayer.setPresentationMode(e) + } + )) + } + startMediaItemPlayback(e, s=!1) { + var n, d, h; + return __awaiter$3(this, void 0, void 0, (function*() { + if (O.debug("MediaItemPlayback: startMediaItemPlayback", e), + e.resetState(), + null === (d = null === (n = e.container) || void 0 === n ? void 0 : n.attributes) || void 0 === d ? void 0 : d.requiresSubscription) { + if (!(yield this.hasMusicSubscription())) { + const s = new MKError(MKError.SUBSCRIPTION_ERROR); + throw s.data = e, + s + } + } + const p = yield this._getPlayerForMediaItem(e); + if (yield this.setCurrentPlayer(p), + !(null === (h = this._currentPlayer) || void 0 === h ? void 0 : h.hasMediaElement)) + return O.warn(`MediaItemPlayback: Could not play media of type ${e.type}, marking item as unsupported and skipping.`), + void e.notSupported(); + try { + e.beginMonitoringStateDidChange(e=>{ + var s; + return null === (s = this._dispatcher) || void 0 === s ? void 0 : s.publish(k.mediaItemStateDidChange, e) + } + ), + e.beginMonitoringStateWillChange(e=>{ + var s; + return null === (s = this._dispatcher) || void 0 === s ? void 0 : s.publish(k.mediaItemStateWillChange, e) + } + ); + const n = this.playOptions.get(e.id); + n && this.playOptions.delete(e.id); + const d = yield this.playMediaItem(e, this._currentPlayer, s, n); + return this._currentPlayback = { + item: e, + userInitiated: s + }, + d + } catch (F) { + throw O.error(F), + F + } + } + )) + } + stop(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this._currentPlayer.stop(e) + } + )) + } + unmute() { + this.volume > 0 || (this.volume = this._volumeAtMute || 1, + this._volumeAtMute = void 0) + } + _getPlayerForMediaItem(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + O.debug("MediaItemPlayback: _getPlayerForMediaItem", e.id); + const s = yield this._playerFactory.getPlayerForMediaItem(e, this.playerState, this._currentPlayer); + return s.previewOnly = this._previewOnly, + s + } + )) + } + setCurrentPlayer(e) { + var s; + return __awaiter$3(this, void 0, void 0, (function*() { + this._currentPlayer !== e && (O.debug("MediaItemPlayback: setting currentPlayer", e), + yield this._currentPlayer.stop(), + this._currentPlayer = e, + null === (s = this._dispatcher) || void 0 === s || s.publish(Xn, { + player: e + })) + } + )) + } + onKeySystemGenericError(e, s) { + var n; + return __awaiter$3(this, void 0, void 0, (function*() { + ta ? null === (n = this._dispatcher) || void 0 === n || n.publish(Jn, s) : (ta = !0, + O.warn("Retrying playback after keysystemGenericError"), + yield this.restartPlayback()) + } + )) + } + onPlaybackLicenseError(e, s) { + var n; + return __awaiter$3(this, void 0, void 0, (function*() { + s.errorCode === MKError.PLAYREADY_CBC_ENCRYPTION_ERROR ? (O.warn("MediaItemPlayback: PLAYREADY_CBC_ENCRYPTION_ERROR...retrying with different key system"), + yield this.restartPlayback()) : null === (n = this._dispatcher) || void 0 === n || n.publish(Jn, s) + } + )) + } + restartPlayback() { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this.stop(); + const {_currentPlayback: e} = this; + if (e) { + const {item: s, userInitiated: n} = e; + s.resetState(), + yield this.startMediaItemPlayback(s, n) + } + } + )) + } + _updatePlayerState(e, s) { + this.playerState[e] = s, + this._currentPlayer[e] = s + } + } + var ia; + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", Promise)], MediaItemPlayback.prototype, "onKeySystemGenericError", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", Promise)], MediaItemPlayback.prototype, "onPlaybackLicenseError", null), + function(e) { + e.UTS = "uts-api", + e.MEDIA = "media-api" + }(ia || (ia = {})); + class APIServiceManager { + constructor(e, s) { + this.store = e, + this._dispatcher = s, + this._apisByType = {} + } + get api() { + return this.getApiByType(this._defaultAPI) + } + get apiService() { + if (void 0 !== this._defaultAPI) + return this._apisByType[this._defaultAPI]; + Mr.error("There is no API instance configured") + } + get mediaAPI() { + return this.getApiByType(ia.MEDIA) + } + get utsAPI() { + return this.getApiByType(ia.UTS) + } + getApiByType(e) { + let s; + if (void 0 !== e && (s = this._apisByType[e]), + void 0 === s || void 0 === s.api) + throw new MKError(MKError.CONFIGURATION_ERROR,"There is no API instance configured for the requested type: " + e); + return s.api + } + set defaultApiType(e) { + this._defaultAPI = e + } + registerAPIService(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const {apiType: s, configureFn: n, options: d} = e + , h = d.apiOptions || {}; + void 0 === this._defaultAPI && (this._defaultAPI = s), + this._apisByType[s] = yield n.call(this, { + apiOptions: h, + store: this.store, + dispatcher: this._dispatcher + }) + } + )) + } + } + class BitrateCalculator { + constructor(s, n=e.PlaybackBitrate.STANDARD) { + var d, h; + this._downlinkSamples = [], + this._bitrate = n, + this._dispatcher = s, + void 0 !== (null === (h = null === (d = null === window || void 0 === window ? void 0 : window.navigator) || void 0 === d ? void 0 : d.connection) || void 0 === h ? void 0 : h.downlink) && this._recalculateBitrate(100 * (window.navigator.connection.downlink || 0)) + } + get bitrate() { + return this._bitrate + } + set bitrate(e) { + this._bitrate !== e && (this._bitrate = e, + this._dispatcher.publish(ns.playbackBitrateDidChange, { + bitrate: e + })) + } + _calculateAverageDownlink() { + return 0 === this._downlinkSamples.length ? 0 : this._downlinkSamples.reduce((e,s)=>e + s, 0) / this._downlinkSamples.length || 0 + } + _recalculateBitrate(s) { + Mr.debug("_recalculateBitrate", s), + this._downlinkSamples.push(s); + this._calculateAverageDownlink() > e.PlaybackBitrate.STANDARD ? (Mr.debug("setting bitrate to", e.PlaybackBitrate.HIGH), + this.bitrate = e.PlaybackBitrate.HIGH) : (Mr.debug("setting bitrate to", e.PlaybackBitrate.STANDARD), + this.bitrate = e.PlaybackBitrate.STANDARD) + } + } + const sa = {}; + function adaptAddEventListener(e, s, n, d={}) { + const {once: h} = d + , p = function(e, s) { + const n = getCallbacksForName(e) + , wrappedCallback = (e,n)=>{ + s(n) + } + ; + return n.push([s, wrappedCallback]), + wrappedCallback + }(s, n); + !0 === h ? e.subscribeOnce(s, p) : e.subscribe(s, p) + } + function getCallbacksForName(e) { + let s = sa[e]; + return s || (s = [], + sa[e] = s), + s + } + function requiresHlsJs(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const s = null != e ? e : yield findKeySystemPreference() + , n = !("true" !== (null === localStorage || void 0 === localStorage ? void 0 : localStorage.getItem("mk-force-safari-hlsjs")) || 0 === un.realm); + return supportsDrm() && (s !== kr.FAIRPLAY || n) + } + )) + } + const getDefaultPlayable = e=>{ + if (hasPlayables(e)) + return e.playables[0] + } + , hasPlayables = e=>void 0 !== e.playables && Array.isArray(e.playables) && e.playables.length > 0; + class RTCStreamingTracker { + constructor(e) { + this.options = e + } + configure(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this.instance = e, + !ln.urls.rtc) + throw new Error("bag.urls.rtc is not configured"); + return yield loadScript(ln.urls.rtc), + this + } + )) + } + prepareReportingAgent(e) { + var s; + this.clearReportingAgent(); + const n = e || this.instance.nowPlayingItem + , d = n ? getDefaultPlayable(n) : void 0 + , {Sender: h, ClientName: p, ServiceName: y, ApplicationName: m, ReportingStoreBag: g, DeviceName: v} = window.rtc.RTCReportingAgentConfigKeys + , _ = { + firmwareVersion: this.generateBrowserVersion(), + model: this.options.browserName + }; + d && ((null === (s = d.mediaMetrics) || void 0 === s ? void 0 : s.MediaIdentifier) && (_.MediaIdentifier = d.mediaMetrics.MediaIdentifier), + d.channelId && (_.ContentProvider = d.channelId)), + void 0 === this._storeBag && (this._storeBag = this.generateStoreBag()); + const b = { + [h]: "HLSJS", + [p]: this.options.clientName, + [y]: this.options.serviceName, + [m]: this.options.applicationName, + [g]: this._storeBag, + [v]: this.options.osVersion, + userInfoDict: _ + }; + return Mr.debug("RTC: creating reporting agent with config", b), + this.reportingAgent = new window.rtc.RTCReportingAgent(b), + Mr.debug("RTC: created reporting agent", this.reportingAgent), + this.reportingAgent + } + shouldConfigure(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return requiresHlsJs() + } + )) + } + shouldTrackPlayActivity(e, s) { + return !0 + } + cleanup() { + this.clearReportingAgent() + } + clearReportingAgent() { + void 0 !== this.reportingAgent && (this.reportingAgent.destroy(), + Mr.debug("RTC: called destroy on reporting agent", this.reportingAgent), + this.reportingAgent = void 0) + } + generateBrowserVersion() { + return this.options.browserMajorVersion ? `${this.options.browserMajorVersion}.${this.options.browserMinorVersion || 0}` : "unknown" + } + generateStoreBag() { + var e; + const {storeBagURL: s, clientName: n, applicationName: d, serviceName: h, browserName: p} = this.options + , y = { + HLSJSVersion: null === (e = null === window || void 0 === window ? void 0 : window.Hls) || void 0 === e ? void 0 : e.version + } + , m = new window.rtc.RTCStorebag.RTCReportingStoreBag(s,n,h,d,p,y); + return Mr.debug("RTC: created store bag", m), + m + } + } + const ra = [et.playbackPause, et.playbackPlay, et.playbackScrub, et.playbackSeek, et.playbackSkip, et.playbackStop, et.playerActivate, et.playerExit, ns.nowPlayingItemWillChange] + , na = { + [et.playbackPause]: "pause", + [et.playbackPlay]: "play", + [et.playbackScrub]: "scrub", + [et.playbackSeek]: "seek", + [et.playbackSkip]: "skip", + [et.playbackStop]: "stop", + [et.playerActivate]: "activate", + [et.playerExit]: "exit" + }; + class PlayActivityService { + constructor(e, s) { + this.isBuffering = !1, + this.apis = Array.isArray(e) ? e : [e], + this.dispatcher = s + } + cleanup() { + this.currentItem = void 0, + this.teardownWatchers(), + this.apis.forEach(e=>e.cleanup()) + } + configure(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + const n = yield Promise.all(this.apis.map(s=>s.shouldConfigure(e))) + , d = this.apis.filter((e,s)=>n[s]); + if (0 === d.length) + return; + this.cleanup(), + this.instance = e; + const h = d.map(n=>n.configure(e, s)); + try { + yield Promise.all(h) + } catch (bt) { + Mr.error("Error configuring a play activity service", bt) + } finally { + this.setupWatchers(), + this.clearIntention() + } + } + )) + } + getTrackerByType(e) { + return this.apis.find(s=>s instanceof e) + } + handleEvent(e, s={}) { + const {item: n} = s; + void 0 !== n && (this.currentItem = n), + Mr.debug(e, s); + const d = na[e]; + if (void 0 === d) + return; + const h = this.addIntention(e, s); + switch (delete h.item, + e) { + case et.playbackPause: + case et.playbackPlay: + case et.playbackScrub: + case et.playbackSeek: + case et.playbackSkip: + case et.playbackStop: + return this.callApis(e, d, this.currentItem, h); + case et.playerActivate: + h.flush = "boolean" == typeof s.isPlaying ? !s.isPlaying : void 0; + case et.playerExit: + return this.callApis(e, d, h); + case ns.nowPlayingItemWillChange: + this.currentItem = n + } + } + addIntention(e, s) { + let n = Object.assign({}, s); + return this.shouldAddIntention(e) ? (n = Object.assign(Object.assign(Object.assign({}, this.lastUserIntent), this.lastApplicationIntent), n), + this.clearIntention(), + n) : n + } + callApis(e, s, ...n) { + return __awaiter$3(this, void 0, void 0, (function*() { + const d = this.apis.map(d=>{ + if ("function" == typeof d[s] && d.shouldTrackPlayActivity(e, this.currentItem)) + return d[s](...n) + } + ); + return Promise.all(d) + } + )) + } + clearIntention() { + this.lastUserIntent = void 0, + this.lastApplicationIntent = void 0 + } + onPlaybackStateChange(s, n) { + return __awaiter$3(this, void 0, void 0, (function*() { + const {state: s} = n + , d = { + position: this.instance.currentPlaybackTime + }; + return s === e.PlaybackStates.waiting ? (this.isBuffering = !0, + this.callApis("bufferStart", "bufferStart", this.currentItem, d)) : s === e.PlaybackStates.playing && this.isBuffering ? (this.isBuffering = !1, + this.callApis("bufferEnd", "bufferEnd", this.currentItem, d)) : void 0 + } + )) + } + recordApplicationIntent(e, s) { + this.lastApplicationIntent = s + } + recordUserIntent(e, s) { + this.lastUserIntent = s + } + shouldAddIntention(e) { + return [et.playbackPause, et.playbackStop].includes(e) + } + setupWatchers() { + ra.forEach(e=>{ + this.dispatcher.subscribe(e, this.handleEvent) + } + ), + this.dispatcher.subscribe(et.userActivityIntent, this.recordUserIntent), + this.dispatcher.subscribe(et.applicationActivityIntent, this.recordApplicationIntent), + this.dispatcher.subscribe(ns.playbackStateDidChange, this.onPlaybackStateChange) + } + teardownWatchers() { + ra.forEach(e=>{ + this.dispatcher.unsubscribe(e, this.handleEvent) + } + ), + this.dispatcher.unsubscribe(et.userActivityIntent, this.recordUserIntent), + this.dispatcher.unsubscribe(et.applicationActivityIntent, this.recordApplicationIntent), + this.dispatcher.unsubscribe(ns.playbackStateDidChange, this.onPlaybackStateChange) + } + } + var aa; + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [String, Object]), __metadata$2("design:returntype", void 0)], PlayActivityService.prototype, "handleEvent", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", Promise)], PlayActivityService.prototype, "onPlaybackStateChange", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", void 0)], PlayActivityService.prototype, "recordApplicationIntent", null), + __decorate$2([Bind(), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object, Object]), __metadata$2("design:returntype", void 0)], PlayActivityService.prototype, "recordUserIntent", null), + function(e) { + e[e.ACCURATE = 0] = "ACCURATE", + e[e.ROUND = 1] = "ROUND" + }(aa || (aa = {})); + class TimingAccuracy { + constructor(e=!1) { + this.mode = e ? aa.ACCURATE : aa.ROUND + } + time(e=0) { + return this.mode === aa.ROUND ? Math.round(e) : e + } + } + const loadLiveRadioAssets = (e,s,n)=>__awaiter$3(void 0, void 0, void 0, (function*() { + var d, h; + const p = new Headers({ + Authorization: "Bearer " + s, + Accept: "application/json", + "Content-Type": "application/json", + "X-Apple-Music-User-Token": "" + n + }) + , y = urlEncodeParameters(Object.assign(Object.assign({}, e.playParams), { + keyFormat: "web" + })) + , m = `${ln.urls.mediaApi}/play/assets?${y}` + , g = yield fetch(m, { + method: "GET", + headers: p + }); + if (500 === g.status) { + const s = new MKError(MKError.SERVER_ERROR); + throw s.data = e, + s + } + if (403 === g.status) { + let s; + try { + s = yield g.json(), + s = null === (d = null == s ? void 0 : s.errors) || void 0 === d ? void 0 : d[0] + } catch (bt) {} + const n = "40303" === (null == s ? void 0 : s.code) ? MKError.SUBSCRIPTION_ERROR : MKError.ACCESS_DENIED + , p = new MKError(n,null !== (h = null == s ? void 0 : s.title) && void 0 !== h ? h : null == s ? void 0 : s.detail); + throw p.data = e, + p + } + if (!g.ok) { + const s = new MKError(MKError.CONTENT_UNAVAILABLE); + throw s.data = e, + s + } + const v = (yield g.json()).results; + return Mr.debug(`media-item: loaded data from ${m}: ${JSON.stringify(v)}`), + v + } + )) + , oa = createLocalStorageFlag("mk-enable-live-music-video-domains") + , prepareMediaAPIItem = (e,s,n)=>__awaiter$3(void 0, void 0, void 0, (function*() { + e.hasOffersHlsUrl ? yield prepareOffersHlsUrlForEncryptedPlayback(e) : e.isLiveRadioStation ? yield prepareLiveRadioForEncryptedPlayback(e, s, n) : yield prepareItemWithMZPlay(e, s, n) + } + )) + , prepareOffersHlsUrlForEncryptedPlayback = e=>__awaiter$3(void 0, void 0, void 0, (function*() { + const s = ln.urls.hlsOffersKeyUrls; + if (!s) + throw new MKError(MKError.CONTENT_UNSUPPORTED,"HLS OFFERS"); + e.updateWithLoadedKeys(s), + yield fetchMasterManifestUrl(e, e.offersHlsUrl) + } + )) + , prepareLiveRadioForEncryptedPlayback = (e,s,n)=>__awaiter$3(void 0, void 0, void 0, (function*() { + if (!ln.features["playready-live-radio"] && Sr === kr.PLAYREADY && "video" !== e.attributes.mediaKind && !ln.features["mse-live-radio"]) + throw new MKError(MKError.CONTENT_UNSUPPORTED,"LIVE_RADIO"); + const d = (yield loadLiveRadioAssets(e, s, n)).assets[0]; + e.updateWithLoadedKeys({ + "hls-key-cert-url": d.fairPlayKeyCertificateUrl, + "hls-key-server-url": d.keyServerUrl, + "widevine-cert-url": d.widevineKeyCertificateUrl + }), + filterUnavailableLiveRadioUrls(d, e), + e.isLiveVideoStation ? e.assetURL = d.url : yield fetchMasterManifestUrl(e, d.url) + } + )) + , fetchMasterManifestUrl = (e,s)=>__awaiter$3(void 0, void 0, void 0, (function*() { + let n; + try { + n = yield fetch(s) + } catch (bt) { + throw makeContentUnavailableError(e) + } + const d = yield n.text(); + extractAssetsFromMasterManifest(d, s, e) + } + )) + , extractAssetsFromMasterManifest = (e,s,n)=>{ + const d = /^#EXT-X-STREAM-INF:.*BANDWIDTH=(\d+),CODECS="(.*)"\s*\n(.*$)/gim; + let h; + for (; h = d.exec(e); ) { + let[e,d,p,y] = h; + /^http(s)?:\/\//.test(y) || (y = rewriteLastUrlPath(s, y)), + n.assets.push({ + bandwidth: Number(d), + codec: p, + URL: y + }) + } + } + , filterUnavailableLiveRadioUrls = (e,s)=>{ + const n = new URL(e.url) + , d = !!oa.json(); + if (!(n.host.endsWith(".apple.com") || d && n.host.endsWith(".applemusic.com"))) + throw makeContentUnavailableError(s) + } + , makeContentUnavailableError = e=>{ + const s = new MKError(MKError.CONTENT_UNAVAILABLE); + return s.data = e, + s + } + , prepareItemWithMZPlay = (e,s,n)=>__awaiter$3(void 0, void 0, void 0, (function*() { + if (Mr.debug("mk: loadWithMZPlay", e.playParams), + "podcast-episodes" === e.type) + return void (e.assetURL = e.attributes.assetUrl); + if (!(yield hasMusicSubscription())) + return; + const d = e.playParams.id + , h = new Headers({ + Authorization: "Bearer " + s, + Accept: "application/json", + "Content-Type": "application/json", + "X-Apple-Music-User-Token": "" + n + }); + let p = { + salableAdamId: d + }; + if (e.isCloudItem) { + p = {}, + e.playParams.purchasedId && (p.purchaseAdamId = e.playParams.purchasedId), + e.playParams.catalogId && (p.subscriptionAdamId = e.playParams.catalogId); + const s = /^a\.(\d+)$/; + s.test(d) ? p.subscriptionAdamId = d.replace(s, "$1") : v(d) && (p.universalLibraryId = d) + } + if (!ln.urls.webPlayback) + throw new Error("bag.urls.webPlayback is not configured"); + const y = yield fetch(ln.urls.webPlayback, { + method: "POST", + body: JSON.stringify(p), + headers: h + }) + , m = yield y.text() + , g = JSON.parse(m); + if (!g || !g.songList) { + const s = MKError.serverError(g); + return e.updateFromLoadError(s), + Mr.debug("mk: prepareItemWithMZPlay - rejecting with error", s), + Promise.reject(s) + } + const [_] = g.songList; + e.updateFromSongList(_) + } + )); + function playMediaItem(s, n, d, h, p) { + return __awaiter$3(this, void 0, void 0, (function*() { + const y = d.isPaused() && !h; + Mr.debug("playMediaItem", n, y); + const m = yield function(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + return !!e.previewURL && (!!s.previewOnly || !e.playRawAssetURL && (!e.isUTS && !(yield hasMusicSubscription()) || (!hasAuthorization() || !supportsDrm() || !e.isPlayable))) + } + )) + }(n, d); + if (Mr.debug("mk: shouldPreview", m), + m) + return supportsDrm() || d.dispatch(ns.drmUnsupported, { + item: n + }), + n.playbackType = e.PlaybackType.preview, + d.nowPlayingItem = n, + yield d.playItemFromUnencryptedSource(n.previewURL, y), + n; + if (function(e) { + return !(!e.playRawAssetURL || !e.attributes.assetUrl) + }(n)) + return Mr.debug("shouldPlayRawAsset", n), + n.playbackType = e.PlaybackType.unencryptedFull, + d.nowPlayingItem = n, + yield d.playItemFromUnencryptedSource(n.attributes.assetUrl, y, p), + n; + if (isBroadcastRadio(n)) { + if (!ln.features["broadcast-radio"]) { + const e = new MKError(MKError.CONTENT_UNAVAILABLE); + throw e.data = n, + e + } + const h = yield loadLiveRadioAssets(n, s.store.developerToken, s.store.userToken) + , p = h.assets[0]; + return n.playbackType = e.PlaybackType.unencryptedFull, + n.trackInfo = h["track-info"], + d.nowPlayingItem = n, + yield d.playItemFromUnencryptedSource(p.url, y), + n + } + if (!n || !n.isPlayable) + return Promise.reject(new MKError(MKError.MEDIA_PLAYBACK,"Not Playable")); + try { + yield prepareForEncryptedPlayback(s, n, d) + } catch (F) { + return Mr.error("prepareForEncryptedPlayback Error: userInitiated " + h), + h ? Promise.reject(F) : void d.dispatch(ns.mediaPlaybackError, F) + } + return yield function(e) { + return new Promise((s,n)=>{ + const {ageGatePolicy: d} = e; + if (!d || !d.age || !d.frequencyInMinutes) + return Mr.debug("No ageGatePolicy. Resolving handleAgeGate()"), + s(void 0); + const h = window.localStorage.ageGatePolicyAge + , p = window.localStorage.ageGatePolicyExpiration; + if (h && p && parseInt(p, 10) > Date.now() && parseInt(h, 10) >= d.age) + return s(void 0); + MKDialog.clientDialog({ + okButtonString: "Yes", + okButtonAction: ()=>(localStorage.setItem("ageGatePolicyAge", d.age.toString()), + localStorage.setItem("ageGatePolicyExpiration", (Date.now() + 60 * d.frequencyInMinutes * 1e3).toString()), + s(void 0)), + cancelButtonString: "No", + cancelButtonAction: ()=>n(new MKError("AGE_GATE","Age Gate Declined")), + explanation: `This content may not be appropriate for ages younger than ${d.age}.`, + message: `Are you ${d.age} or older?` + }).present() + } + ) + }(n), + Mr.debug("About to play item as encrypted", n), + yield d.playItemFromEncryptedSource(n, h, p), + n + } + )) + } + function prepareToPlayMediaItem(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + const {developerToken: n, userToken: d} = e.store; + if (void 0 === n || void 0 === d) + return Promise.reject(new MKError(MKError.AUTHORIZATION_ERROR,"Unable to prepare media item for play.")); + s.isPreparedToPlay ? Mr.warn("media-item: item is prepared to play") : (Mr.debug("media-item: item.prepareToPlay playParams", s.playParams), + s.state = D.loading, + s.isUTS ? yield((e,s)=>__awaiter$3(void 0, void 0, void 0, (function*() { + var n, d; + const h = yield s.viewProductPersonalized({ + id: e.id, + reload: !0 + }); + if (e.playables = null !== (n = null == h ? void 0 : h.playables) && void 0 !== n ? n : null === (d = null == h ? void 0 : h.currentEpisode) || void 0 === d ? void 0 : d.playables, + e.channels = null == h ? void 0 : h.channels, + !hasPlayables(e)) + return; + const p = getDefaultPlayable(e); + void 0 !== p && (e.ageGatePolicy = p.ageGatePolicy, + e.playEvent = p.playEvent); + const y = e.playables.reduce((e,s)=>(void 0 !== s.assets && e.push(s.assets), + e), []); + if (0 === y.length) + return; + const [m] = y; + let {hlsUrl: g} = m; + ln.features.xtrick && (g = addQueryParamsToURL(g, { + xtrick: !0 + })), + ln.features.isWeb && (g = addQueryParamsToURL(g, { + webbrowser: !0 + })), + e.bingeWatching && (g = addQueryParamsToURL(g, { + bingeWatching: !0 + }), + e.bingeWatching = !1), + e.updateWithLoadedAssets(y, g), + e.updateWithLoadedKeys({ + "hls-key-cert-url": m.fpsCertificateUrl, + "hls-key-server-url": m.fpsKeyServerUrl, + "widevine-cert-url": m.wideVineCertificateUrl + }, m.fpsKeyServerQueryParameters), + yield fetchHLSMetadata(e), + e.state = D.ready + } + )))(s, e.utsAPI) : yield prepareMediaAPIItem(s, n, d)) + } + )) + } + function prepareForEncryptedPlayback(e, s, n) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (Mr.debug("prepareForEncryptedPlayback"), + !hasAuthorization()) + return n.destroy(), + Promise.reject(new MKError(MKError.AUTHORIZATION_ERROR,"Unable to prepare for playback.")); + try { + yield e.store.validateAgeVerification(s) + } catch (F) { + return F.errorCode === MKError.CONTENT_RESTRICTED && s.restrict(), + n.destroy(), + Promise.reject(F) + } + try { + yield prepareToPlayMediaItem(e, s) + } catch (F) { + if ([MKError.AUTHORIZATION_ERROR].includes(F.errorCode)) + yield e.store.storekit.revokeUserToken(); + else if (F.errorCode === MKError.TOKEN_EXPIRED) + try { + return yield e.store.storekit.renewUserToken(), + yield prepareToPlayMediaItem(e, s), + s.playbackData = _playbackDataForItem(s, n), + s + } catch (d) {} + if (F) + return n.destroy(), + Promise.reject(F) + } + return s.playbackData = _playbackDataForItem(s, n), + s + } + )) + } + function _playbackDataForItem(s, n) { + if (Mr.debug("mk: _playbackDataForItem", s), + s.isCloudUpload) + return s.assets[0]; + if ("musicVideo" !== s.type && !s.isLiveVideoStation) { + if (!s.isLiveRadioStation && !s.hasOffersHlsUrl) { + const [e] = s.assets.filter(e=>{ + var s; + if (!("flavor"in e)) + return !1; + const d = new RegExp(`\\d{1,2}\\:(c${function() { + var e; + return null === (e = window.WebKitMediaKeys) || void 0 === e ? void 0 : e.isTypeSupported(Ir + ".1_0", qs.AVC1) + }() ? "bc" : "tr"}p)(\\d{2,3})`,"i") + , h = d.test(e.flavor) + , p = null !== (s = e.flavor.match(d)) && void 0 !== s ? s : []; + return h && parseInt(p[2], 10) <= n.bitrate + } + ); + return e + } + { + const d = s.assets.reduce((e,s)=>{ + const n = s.bandwidth; + return e[n] || (e[n] = []), + e[n].push(s), + e + } + , {}) + , h = Object.keys(d).sort((e,s)=>parseInt(e, 10) - parseInt(s, 10)) + , p = n.bitrate === e.PlaybackBitrate.STANDARD ? h[0] : h[h.length - 1]; + s.assetURL = d[p][0].URL + } + } + } + const da = [MKError.AGE_VERIFICATION, MKError.CONTENT_EQUIVALENT, MKError.CONTENT_RESTRICTED, MKError.CONTENT_UNAVAILABLE, MKError.CONTENT_UNSUPPORTED, MKError.SERVER_ERROR, MKError.SUBSCRIPTION_ERROR, MKError.UNSUPPORTED_ERROR]; + var la; + e.PlaybackMode = void 0, + (la = e.PlaybackMode || (e.PlaybackMode = {}))[la.PREVIEW_ONLY = 0] = "PREVIEW_ONLY", + la[la.MIXED_CONTENT = 1] = "MIXED_CONTENT", + la[la.FULL_PLAYBACK_ONLY = 2] = "FULL_PLAYBACK_ONLY"; + const ca = createLocalStorageFlag("mk-bag-features-overrides"); + class MKInstance { + constructor(s, n={}) { + if (this._autoplayEnabled = !1, + this.privateEnabled = !1, + this.siriInitiated = !1, + this.sourceType = ft.MUSICKIT, + this.version = e.version, + this._bag = ln, + this._playbackControllers = {}, + this._playbackErrorDialog = !0, + this._playbackMode = e.PlaybackMode.MIXED_CONTENT, + this._whenConfigured = void 0, + "string" != typeof s) + throw new Error("MusicKit was initialized without an developerToken."); + Object.assign(ln.features, function(e=[]) { + const s = {}; + return e.forEach(e=>{ + "-" === e.charAt(0) ? (e = e.substr(1), + s[e] = !1) : s[e] = !0 + } + ), + s + }(n.features)); + const d = ca.json(); + d && (Mr.warn("Overriding bag.features with", d), + ln.features = Object.assign(Object.assign({}, ln.features), d)), + Object.assign(ln.autoplay, n.autoplay), + this.context = {}; + const h = new PubSub; + this.capabilities = new Capabilities(h), + n.playbackActions && (this.playbackActions = n.playbackActions); + const p = new TimingAccuracy(!!ln.features["player-accurate-timing"]) + , y = new BitrateCalculator(h,n.bitrate); + this._services = { + dispatcher: h, + timing: p, + bitrateCalculator: y + }, + void 0 !== n.playActivityAPI && (this._services.playActivity = new PlayActivityService(n.playActivityAPI,h)), + n.services = this._services, + this._configureLogger(n), + ln.app = n.app || {}, + ln.store = new DataStore({ + filter: getFilterFromFlags(n.storeFilterTypes || []), + shouldDisableRecordReuse: !!ln.features["disable-data-store-record-reuse"] + }), + Object.assign(ln.urls, n.urls || {}); + const m = function(e, s) { + return un = new Store(e,s), + un + }(s, n); + this._services.apiManager = new APIServiceManager(m,h); + const g = new MediaItemPlayback(this._createPlayerControllerOptions()); + if (this._services.mediaItemPlayback = g, + n.sourceType && (this.sourceType = n.sourceType), + this._initializeEventHandling(), + n.bitrate && (this.bitrate = n.bitrate), + n.prefix && /^(?:web|preview)$/.test(n.prefix) && (this.prefix = ln.prefix = n.prefix), + n.suppressErrorDialog && (this._playbackErrorDialog = !n.suppressErrorDialog), + void 0 !== n.playbackMode && (this.playbackMode = n.playbackMode), + this.privateEnabled = n.privateEnabled || !1, + this.siriInitiated = n.siriInitiated || !1, + this.id = generateUUID(), + Mr.log("MusicKit JS Version: " + this.version), + Mr.debug("Link Parameters", n.linkParameters), + Mr.log("InstanceId", this.id), + ln.app && Mr.debug("App", ln.app), + n.userToken) { + const {userToken: e} = n; + "function" == typeof e ? un.dynamicMusicUserToken = e : this.musicUserToken = e + } + } + get developerToken() { + return un.developerToken + } + get api() { + return this._services.apiManager.api + } + get audioTracks() { + return this._mediaItemPlayback.audioTracks + } + get authorizationStatus() { + return un.authorizationStatus + } + get bitrate() { + return this._services.bitrateCalculator.bitrate + } + set bitrate(e) { + this._services.bitrateCalculator.bitrate = e + } + get browserSupportsPictureInPicture() { + return function() { + if (Ke) + return O.warn("dom-helpers: Browser checks are not supported in Node environments"), + !1; + const e = Zs + , s = e && e.webkitSupportsPresentationMode && "function" == typeof e.webkitSetPresentationMode + , n = document.pictureInPictureEnabled; + return !(!s && !n) + }() + } + get browserSupportsVideoDrm() { + return supportsDrm() + } + get cid() { + return (2 === this.realm || this.sourceType !== ft.MUSICKIT) && un.cid + } + get continuous() { + return this._playbackController.continuous + } + set continuous(e) { + this._playbackController.continuous = e + } + get autoplayEnabled() { + return this._autoplayEnabled + } + set autoplayEnabled(e) { + 0 !== this.realm && (e = !1), + e !== this.autoplayEnabled && (this._autoplayEnabled = e, + this._services.dispatcher.publish(ns.autoplayEnabledDidChange, this.autoplayEnabled)) + } + get currentAudioTrack() { + return this._mediaItemPlayback.currentAudioTrack + } + set currentAudioTrack(e) { + this._mediaItemPlayback.currentAudioTrack = e + } + get currentPlaybackDuration() { + return this._mediaItemPlayback.currentPlaybackDuration + } + get currentPlaybackProgress() { + return this._mediaItemPlayback.currentPlaybackProgress + } + get currentPlaybackTime() { + return this._mediaItemPlayback.currentPlaybackTime + } + get currentPlaybackTimeRemaining() { + return this._mediaItemPlayback.currentPlaybackTimeRemaining + } + get currentTextTrack() { + return this._mediaItemPlayback.currentTextTrack + } + set currentTextTrack(e) { + this._mediaItemPlayback.currentTextTrack = e + } + get isAuthorized() { + return un.isAuthorized + } + get isPlaying() { + return this._playbackController.isPlaying + } + get isRestricted() { + return un.isRestricted + } + get metricsClientId() { + return un.metricsClientId + } + set metricsClientId(e) { + un.metricsClientId = e + } + get musicUserToken() { + return un.musicUserToken + } + set musicUserToken(e) { + e && un.musicUserToken === e || (un.musicUserToken = e) + } + get needsGDPR() { + return un.needsGDPR + } + get nowPlayingItem() { + return this._mediaItemPlayback.nowPlayingItem + } + get nowPlayingItemIndex() { + return this._playbackController.nowPlayingItemIndex + } + get playbackMode() { + return this._playbackMode + } + set playbackMode(s) { + if (-1 === Object.values(e.PlaybackMode).indexOf(s)) + return; + this._playbackMode = s; + const n = s === e.PlaybackMode.PREVIEW_ONLY + , d = this._services.mediaItemPlayback; + d && (d.previewOnly = n) + } + get playbackRate() { + return this._mediaItemPlayback.playbackRate + } + set playbackRate(e) { + this._mediaItemPlayback.playbackRate = e + } + get playbackState() { + return this._mediaItemPlayback.playbackState + } + get playbackTargetAvailable() { + return this._mediaItemPlayback.playbackTargetAvailable + } + get playbackTargetIsWireless() { + return this._mediaItemPlayback.playbackTargetIsWireless + } + get previewOnly() { + return this.playbackMode === e.PlaybackMode.PREVIEW_ONLY + } + set previewOnly(s) { + this.playbackMode = s ? e.PlaybackMode.PREVIEW_ONLY : e.PlaybackMode.MIXED_CONTENT + } + get queue() { + return this._playbackController.queue + } + get queueIsEmpty() { + return this._playbackController.queue.isEmpty + } + get realm() { + return un.realm + } + get repeatMode() { + return this._playbackController.repeatMode + } + set repeatMode(e) { + this._playbackController.repeatMode = e + } + set requestUserToken(e) { + un.requestUserToken = e + } + get restrictedEnabled() { + return un.restrictedEnabled + } + get seekSeconds() { + return this._playbackController.seekSeconds + } + get services() { + return this._services + } + set shuffle(e) { + this._playbackController.shuffle = e + } + get shuffleMode() { + return this._playbackController.shuffleMode + } + set shuffleMode(e) { + this._playbackController.shuffleMode = e + } + get storefrontCountryCode() { + return un.storefrontCountryCode + } + get subscribeURL() { + return un.subscribeURL + } + get subscribeFamilyURL() { + return un.subscribeFamilyURL + } + get subscribeIndividualURL() { + return un.subscribeIndividualURL + } + get subscribeStudentURL() { + return un.subscribeStudentURL + } + get textTracks() { + return this._mediaItemPlayback.textTracks + } + get videoContainerElement() { + return this.context.videoContainerElement + } + set videoContainerElement(e) { + this.context.videoContainerElement = e + } + get volume() { + return this._mediaItemPlayback.volume + } + set volume(e) { + this._mediaItemPlayback.volume = e + } + get storefrontId() { + return un.storefrontId + } + set storefrontId(e) { + un.storefrontId = e + } + get _mediaItemPlayback() { + return this._services.mediaItemPlayback + } + get _playbackController() { + if (void 0 !== this._playbackControllerInternal) + return this._playbackControllerInternal; + Mr.debug("setting _playbackController"); + const e = this._getPlaybackControllerByType(An.serial); + return this._playbackController = e, + e + } + set _playbackController(e) { + this._playbackControllerInternal = e, + this._playbackControllerInternal.autoplayEnabled = this._autoplayEnabled, + this._playbackControllerInternal.activate(), + this.capabilities.updateChecker(this._playbackControllerInternal.hasCapabilities), + this.capabilities.controller = this._playbackControllerInternal + } + addEventListener(e, s, n={}) { + adaptAddEventListener(this._services.dispatcher, e, s, n) + } + authorize() { + return __awaiter$3(this, void 0, void 0, (function*() { + return this.deferPlayback(), + un.authorize() + } + )) + } + canAuthorize() { + return supportsDrm() && !this.isAuthorized + } + canUnauthorize() { + return supportsDrm() && this.isAuthorized + } + changeToMediaAtIndex(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + this._isPlaybackSupported() && (yield this._validateAuthorization(), + this._signalChangeItemIntent(), + yield this._playbackController.changeToMediaAtIndex(e)) + } + )) + } + changeToMediaItem(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + Mr.debug("instance.changeToMediaItem", e), + this._isPlaybackSupported() && (yield this._validateAuthorization(), + this._signalChangeItemIntent(), + yield this._playbackController.changeToMediaItem(e)) + } + )) + } + changeUserStorefront(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + this.storefrontId = e + } + )) + } + cleanup() { + var s; + return __awaiter$3(this, void 0, void 0, (function*() { + null === (s = this._services.mediaItemPlayback) || void 0 === s || s.destroy(), + this._signalIntent({ + endReasonType: e.PlayActivityEndReasonType.EXITED_APPLICATION + }); + const n = Object.keys(this._playbackControllers).map(e=>this._playbackControllers[e].destroy()); + try { + yield Promise.all(n) + } catch (bt) { + Mr.error("Error cleaning up controller", bt) + } + this._services.dispatcher.clear() + } + )) + } + configure(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._whenConfigured = this._configure(e), + this._whenConfigured + } + )) + } + _configure(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + yield un.storekit.whenAuthCompleted; + const s = e.map(this._services.apiManager.registerAPIService, this._services.apiManager); + yield Promise.all(s), + yield this._configurePlayActivity() + } + )) + } + deferPlayback() { + Mr.debug("deferPlayback", this._playbackControllerInternal), + deferPlayback() + } + getApiByType(e) { + var s; + return null === (s = this._services.apiManager) || void 0 === s ? void 0 : s.getApiByType(e) + } + me() { + return __awaiter$3(this, void 0, void 0, (function*() { + try { + return yield un.storekit.me() + } catch (bt) { + return Promise.reject(new MKError(MKError.AUTHORIZATION_ERROR,"Unauthorized")) + } + } + )) + } + musicSubcriptionOffers() { + return un.storekit.musicSubscriptionOffers(this.storefrontId) + } + hasMusicSubscription() { + return hasMusicSubscription(un.storekit) + } + mute() { + return this._mediaItemPlayback.mute() + } + pause(s) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this._isPlaybackSupported()) { + try { + this._signalIntent({ + endReasonType: e.PlayActivityEndReasonType.PLAYBACK_MANUALLY_PAUSED + }), + yield this._playbackController.pause(s) + } catch (F) { + this._handlePlaybackError(F) + } + return Promise.resolve() + } + } + )) + } + play() { + return __awaiter$3(this, void 0, void 0, (function*() { + if (Mr.debug("instance.play()"), + this._isPlaybackSupported()) { + yield this._validateAuthorization(); + try { + yield this._playbackController.play() + } catch (F) { + this._handlePlaybackError(F) + } + return Promise.resolve() + } + } + )) + } + playMediaItem(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return Mr.debug("mk: playMediaItem", e), + this.deferPlayback(), + this._playbackController.playSingleMediaItem(e) + } + )) + } + playNext(e, s=!1) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this._isPlaybackSupported()) + return this._playbackController.queue ? (this.deferPlayback(), + this._playbackController.prepend(e, s)) : this.setQueue(e) + } + )) + } + playLater(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this._isPlaybackSupported()) + return this._playbackController.queue ? (this.deferPlayback(), + this._playbackController.append(e)) : this.setQueue(e) + } + )) + } + playAt(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this._isPlaybackSupported()) + return this._playbackController.queue ? (this.deferPlayback(), + this._playbackController.insertAt(e, s)) : this.setQueue(s) + } + )) + } + clearQueue() { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._mediaItemPlayback.clearNextManifest(), + this._playbackController.clear() + } + )) + } + removeEventListener(e, s) { + !function(e, s, n) { + const d = getCallbacksForName(s); + let h; + for (let p = d.length - 1; p >= 0; p--) { + const [e,s] = d[p]; + if (e === n) { + h = s, + d.splice(p, 1); + break + } + } + h && e.unsubscribe(s, h) + }(this._services.dispatcher, e, s) + } + shouldDisplayPrivacyLink(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return un.shouldDisplayPrivacyLink(e) + } + )) + } + exitFullscreen() { + return this._mediaItemPlayback.exitFullscreen() + } + requestFullscreen(e) { + return this._mediaItemPlayback.requestFullscreen(e) + } + getNewSeeker() { + return this._playbackController.getNewSeeker() + } + seekToTime(e, s=rt.Manual) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this._isPlaybackSupported()) { + yield this._validateAuthorization(); + try { + yield this._playbackController.seekToTime(e, s) + } catch (F) { + this._handlePlaybackError(F) + } + return Promise.resolve() + } + } + )) + } + setQueue(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (Mr.debug("instance.setQueue()", e), + !this._isPlaybackSupported()) + return void Mr.warn("Playback is not supported"); + if (this._isStationQueueOptions(e)) + return Mr.warn("setQueue options contained a station queue request. Changing to setStationQueue mode."), + this.setStationQueue(e); + this._signalChangeItemIntent(), + this.deferPlayback(), + yield this._updatePlaybackController(this._getPlaybackControllerByType(An.serial)); + const s = yield this._playbackController.setQueue(e); + return void 0 !== e.repeatMode && (this._playbackController.repeatMode = e.repeatMode), + void 0 !== e.autoplay && (logDeprecation("autoplay", { + message: "autoplay has been deprecated, use startPlaying instead" + }), + void 0 === e.startPlaying && (e.startPlaying = e.autoplay)), + e.startPlaying && (yield this.play()), + s + } + )) + } + setStationQueue(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (!this._isPlaybackSupported()) + return; + this.deferPlayback(), + yield this._updatePlaybackController(this._getPlaybackControllerByType(An.continuous)), + yield this._validateAuthorization(!0), + this._signalChangeItemIntent(), + e = parseQueueURLOption(e); + const s = this._playbackController.setQueue(e); + return void 0 !== e.autoplay && (logDeprecation("autoplay", { + message: "autoplay has been deprecated, use startPlaying instead" + }), + void 0 === e.startPlaying && (e.startPlaying = e.autoplay)), + e.startPlaying && (yield this.play()), + s + } + )) + } + setPresentationMode(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return this._mediaItemPlayback.setPresentationMode(e) + } + )) + } + skipToNextItem() { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this._isPlaybackSupported()) { + yield this._validateAuthorization(), + this._signalIntent({ + endReasonType: e.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS, + direction: e.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS + }); + try { + yield this._playbackController.skipToNextItem() + } catch (F) { + this._handlePlaybackError(F) + } + } + } + )) + } + skipToPreviousItem() { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this._isPlaybackSupported()) { + yield this._validateAuthorization(), + this._signalIntent({ + endReasonType: e.PlayActivityEndReasonType.TRACK_SKIPPED_BACKWARDS, + direction: e.PlayActivityEndReasonType.TRACK_SKIPPED_BACKWARDS + }); + try { + yield this._playbackController.skipToPreviousItem() + } catch (F) { + this._handlePlaybackError(F) + } + } + } + )) + } + seekForward() { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this._isPlaybackSupported()) { + yield this._validateAuthorization(); + try { + this._signalIntent({ + endReasonType: e.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS, + direction: e.PlayActivityEndReasonType.TRACK_SKIPPED_FORWARDS + }), + yield this._playbackController.seekForward() + } catch (F) { + this._handlePlaybackError(F) + } + } + } + )) + } + seekBackward() { + return __awaiter$3(this, void 0, void 0, (function*() { + if (this._isPlaybackSupported()) { + yield this._validateAuthorization(); + try { + yield this._playbackController.seekBackward() + } catch (F) { + this._handlePlaybackError(F) + } + } + } + )) + } + showPlaybackTargetPicker() { + this._playbackController.showPlaybackTargetPicker() + } + stop(e) { + var s; + return __awaiter$3(this, void 0, void 0, (function*() { + if (this._isPlaybackSupported()) { + this._signalIntent({ + endReasonType: null == e ? void 0 : e.endReasonType, + userInitiated: null === (s = null == e ? void 0 : e.userInitiated) || void 0 === s || s + }); + try { + yield this._playbackController.stop(e) + } catch (F) { + this._handlePlaybackError(F) + } + } + } + )) + } + resetSubscribeViewEligibility() { + un.storekit.resetSubscribeViewEligibility() + } + unauthorize() { + return __awaiter$3(this, void 0, void 0, (function*() { + return un.unauthorize() + } + )) + } + unmute() { + return this._mediaItemPlayback.unmute() + } + _createPlayerControllerOptions() { + return { + tokens: un, + bag: ln, + playbackServices: { + getRTCStreamingTracker: ()=>{ + var e; + return null === (e = this._services.playActivity) || void 0 === e ? void 0 : e.getTrackerByType(RTCStreamingTracker) + } + , + hasMusicSubscription: hasMusicSubscription, + playMediaItem: (e,s,n,d)=>playMediaItem(this._services.apiManager, e, s, n, d), + prepareForEncryptedPlayback: (e,s)=>prepareForEncryptedPlayback(this._services.apiManager, e, s), + requiresHlsJs: requiresHlsJs + }, + services: this._services, + context: this.context, + autoplayEnabled: this.autoplayEnabled, + privateEnabled: this.privateEnabled, + siriInitiated: this.siriInitiated, + storekit: null == un ? void 0 : un.storekit + } + } + _getPlaybackControllerByType(e) { + const s = this._playbackControllers[e]; + if (s) + return s; + let n; + switch (e) { + case An.serial: + n = new SerialPlaybackController(this._createPlayerControllerOptions()); + break; + case An.continuous: + n = new ContinuousPlaybackController(this._createPlayerControllerOptions()); + break; + default: + throw new MKError(MKError.UNSUPPORTED_ERROR,"Unsupported controller requested: " + e) + } + return this._playbackControllers[e] = n, + n + } + _handlePlaybackError(e) { + if (Mr.error("mediaPlaybackError", e), + da.includes(e.name)) + throw e; + this._playbackErrorDialog && !Ke && MKDialog.presentError(e) + } + _initializeEventHandling() { + [ns.authorizationStatusDidChange, ns.needsGDPRDidChange, ns.storefrontCountryCodeDidChange, ns.storefrontIdentifierDidChange, ns.userTokenDidChange, ns.eligibleForSubscribeView].forEach(e=>{ + un.storekit.addEventListener(e, s=>this._services.dispatcher.publish(e, s)) + } + ), + un.storekit.addEventListener(ns.userTokenDidChange, ()=>{ + this._whenConfigured && this._whenConfigured.then(()=>this._configurePlayActivity().catch()).catch() + } + ); + const s = this._services.dispatcher; + s.subscribe(ns.mediaPlaybackError, (e,s)=>this._handlePlaybackError(s)), + s.subscribe(ns.playbackStateDidChange, (s,n)=>{ + n.state === e.PlaybackStates.paused && (Mr.debug("mk: playbackStateDidChange callback - calling storekit.presentSubscribeViewForEligibleUsers"), + un.storekit.presentSubscribeViewForEligibleUsers({ + state: n.state, + item: this.nowPlayingItem + }, !1)) + } + ); + const n = Je[this.storefrontId.toUpperCase()] + , d = Ve[n]; + s.subscribe(Qr, (e,n)=>{ + n.resolveAdamIdFromStorefront(d), + s.publish(ns.timedMetadataDidChange, n) + } + ) + } + _configureLogger(e) { + e.debug && (Mr.enabled = !0, + Mr.level = parseInt(e.logLevel, 10) || 1) + } + _configurePlayActivity() { + return __awaiter$3(this, void 0, void 0, (function*() { + void 0 !== this._services.playActivity && (yield this._services.playActivity.configure(this, { + services: this._services + })) + } + )) + } + _isPlaybackSupported() { + return !Ke || (Mr.warn("Media playback is not supported in Node environments."), + !1) + } + _isStationQueueOptions(e) { + return !(!(e=>!!e && (!!isIdentityQueue(e) || (!!isQueueURLOption(e) || Object.keys(Nn).some(s=>void 0 !== e[s]))))(e = parseQueueURLOption(e)) || (e=>{ + if (!e) + return !1; + if (isQueueURLOption(e)) + return !0; + if (isQueueItems(e)) + return !0; + return Object.keys($n).concat(Object.keys(jn)).some(s=>void 0 !== e[s]) + } + )(e)) + } + _updatePlaybackController(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + Mr.debug("mk: _updatePlaybackController", e), + this._playbackControllerInternal !== e && (this._playbackControllerInternal && (yield this._playbackControllerInternal.deactivate()), + this._playbackController = e) + } + )) + } + _signalChangeItemIntent() { + this._signalIntent({ + endReasonType: e.PlayActivityEndReasonType.MANUALLY_SELECTED_PLAYBACK_OF_A_DIFF_ITEM + }) + } + _signalIntent(e) { + this.services.dispatcher.publish(et.userActivityIntent, Object.assign({ + userInitiated: !0 + }, e)) + } + _validateAuthorization(s=!1) { + return __awaiter$3(this, void 0, void 0, (function*() { + (s || this.playbackMode === e.PlaybackMode.FULL_PLAYBACK_ONLY) && (void 0 !== this._playbackControllerInternal && this._playbackControllerInternal.isReady && this._playbackControllerInternal.isPlaying || (yield this.authorize())) + } + )) + } + } + function dispatchDocumentEvent(e) { + if (Ke) + return; + const s = new Event(e,{ + bubbles: !0, + cancelable: !0 + }); + setTimeout(()=>document.dispatchEvent(s)) + } + __decorate$2([AsyncDebounce(250, { + isImmediate: !0, + cancelledValue: void 0 + }), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", [Object]), __metadata$2("design:returntype", Promise)], MKInstance.prototype, "pause", null), + __decorate$2([AsyncDebounce(250, { + isImmediate: !0, + cancelledValue: void 0 + }), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", Promise)], MKInstance.prototype, "play", null), + __decorate$2([SerialAsync("skip"), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", Promise)], MKInstance.prototype, "skipToNextItem", null), + __decorate$2([SerialAsync("skip"), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", Promise)], MKInstance.prototype, "skipToPreviousItem", null), + __decorate$2([SerialAsync("seek"), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", Promise)], MKInstance.prototype, "seekForward", null), + __decorate$2([SerialAsync("seek"), __metadata$2("design:type", Function), __metadata$2("design:paramtypes", []), __metadata$2("design:returntype", Promise)], MKInstance.prototype, "seekBackward", null); + const ua = "undefined" != typeof window && "undefined" != typeof document; + let ha = !1; + const pa = []; + function configure$2(e, s=MKInstance, n) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (!e) + throw new MKError(MKError.INVALID_ARGUMENTS,"configuration required"); + const d = {} + , {developerToken: h, mergeQueryParams: p} = e; + if (!h) + throw new MKError(MKError.CONFIGURATION_ERROR,"Missing developer token"); + p && ua && window.location && (d.linkParameters = Object.assign(Object.assign({}, e.linkParameters || {}), parseQueryParams(window.location.href))), + yield findKeySystemPreference(); + const y = new s(h,Object.assign(Object.assign({}, e), d)); + return ha || (yield function() { + return __awaiter$3(this, void 0, void 0, (function*() { + const e = pa.map(e=>e.cleanup()); + yield Promise.all(e), + pa.splice(0, pa.length) + } + )) + }()), + n && (yield n(y)), + pa.push(y), + dispatchDocumentEvent(ns.configured), + y + } + )) + } + function getInstances() { + return pa + } + function transformParameters(e, s=25) { + if (e) + return e.limit && (e.limit = e.limit > s ? s : e.limit), + e + } + function transformStoreData(e) { + const s = Object.assign({}, e) + , {href: n} = s; + return void 0 !== n && (delete s.href, + s.attributes = Object.assign(Object.assign({}, s.attributes), { + href: n + })), + s + } + ua && (asAsync(function() { + var e; + return __awaiter$3(this, void 0, void 0, (function*() { + if (Ke) + return; + const s = findScript("musickit.js"); + if ("" !== (null === (e = null == s ? void 0 : s.dataset) || void 0 === e ? void 0 : e.webComponents)) + return; + const n = "noModule"in s + , d = `components/musickit-components/musickit-components${n ? ".esm" : ""}.js` + , h = "https:" + cdnBaseURL(d) + d + , p = {}; + n && (p.type = "module"), + s.hasAttribute("async") && (p.async = ""), + s.hasAttribute("defer") && (p.defer = ""), + yield loadScript(h, p), + dispatchDocumentEvent(ns.webComponentsLoaded) + } + )) + }()), + dispatchDocumentEvent(ns.loaded)); + function transformTrackParameters(e) { + return e.map(e=>"string" == typeof e ? { + id: e, + type: "songs" + } : { + id: e.id, + type: e.type || "songs" + }) + } + const ya = ["extend", "include", "l", "platform", "views"]; + class LocalDataStore { + constructor(e={}) { + this.enableDataStore = !1; + let s = !1; + e.features && hasOwn(e.features, "api-data-store") && (this.enableDataStore = !!e.features["api-data-store"]), + e.features && hasOwn(e.features, "disable-data-store-record-reuse") && (s = !!e.features["disable-data-store-record-reuse"]), + this.enableDataStore && (this._store = e.store || new DataStore({ + shouldDisableRecordReuse: s + }), + this._store.mapping = transformStoreData) + } + get hasDataStore() { + return this.enableDataStore && void 0 !== this._store + } + delete(e, s) { + this.hasDataStore && this._store.remove(e, s) + } + read(e, s, n, d) { + d || "function" != typeof n || (d = n, + n = void 0); + const h = {}; + let p = !1; + if (n && (p = Object.keys(n).some(e=>/^(fields|extend)/.test(e)), + n.views && (h.views = n.views), + n.include && (h.relationships = n.include)), + this.hasDataStore && !p) { + let d, p = []; + if (n && (p = Object.keys(n).reduce((e,s)=>(-1 === ya.indexOf(s) && e.push([s, n[s]]), + e), p)), + d = p && 1 === p.length ? this._store.query(p[0][0], p[0][1]) : this._store.peek(e, s, h), + Array.isArray(d)) { + if (!n && d.length) + return d + } else if (d) + return d + } + if ("function" == typeof d) + return d() + } + write(e) { + return this._prepareDataForDataStore(e, e=>this._store.save(e)) + } + parse(e) { + return this._prepareDataForDataStore(e, e=>this._store.populateDataRecords(e, {})) + } + _prepareDataForDataStore(e, s) { + return this.hasDataStore ? Array.isArray(e) ? s({ + data: e + }) : Object.keys(e).reduce((n,d)=>{ + const h = e[d]; + return hasOwn(h, "data") && (n[d] = s({ + data: h.data + })), + "meta" === d && (n[d] = e[d]), + n + } + , {}) : e + } + } + const ChunkedIdApi = (e,s=100,n=1e3)=>(d,h,p)=>{ + if (void 0 === p || "function" != typeof p.value) + throw new TypeError(`Only methods can be decorated with @ChunkedIdApi, but ${h} is not a method.`); + return { + configurable: !0, + get() { + const d = p.value; + function chunkedIdApi(...h) { + return __awaiter(this, void 0, void 0, (function*() { + const p = h[e]; + if (p && Array.isArray(p)) { + const y = p[0].length || 20 + , m = Math.min(s, Math.floor(n / y)) + , g = Math.ceil(p.length / m); + if (g > 1) { + const s = h.slice(0, e) + , n = h.slice(e + 1) + , y = []; + let v = 0; + for (let e = 1; e <= g; e++) { + const h = Math.min(e * m, p.length) + , g = [...s, p.slice(v, h), ...n]; + y.push(d.apply(this, g)), + v += m + } + const _ = yield Promise.all(y); + return [].concat(..._) + } + } + return d.apply(this, h) + } + )) + } + return Object.defineProperty(this, h, { + value: chunkedIdApi, + configurable: !0, + writable: !0 + }), + chunkedIdApi + } + } + } + , formatTimezoneOffset = (e=new Date)=>{ + const s = e.getTimezoneOffset() + , n = Math.floor(Math.abs(s) / 60) + , d = Math.round(Math.abs(s) % 60); + let h = "+"; + return 0 !== s && (h = s > 0 ? "-" : "+"), + `${h}${leadingZeros(n, 2)}:${leadingZeros(d, 2)}` + } + , leadingZeros = (e,s=2)=>{ + let n = "" + e; + for (; n.length < s; ) + n = "0" + n; + return n + } + ; + class Books extends TokenSession { + constructor(e, s, n, d, h={}, p) { + super("https://api.books.apple.com/v1", e, Object.assign(Object.assign({}, p), { + userToken: s, + storage: d + })), + this.storefrontId = Xi.ID, + n && (this.storefrontId = n), + this._store = new LocalDataStore(h), + this.defaultIncludePaginationMetadata = h.features && hasOwn(h.features, "api-pagination-metadata") + } + audioBook(e, s, n) { + return this.resource("audio-books", e, s, n) + } + audioBooks(e, s, n) { + return this.collection("audio-books", e, s, n) + } + collection(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + const h = `catalog/${this.storefrontId}/${e}`; + return s && ((n = n || {}).ids = s), + makeRequest(this, h, n, d) + } + )) + } + parseResultData(e, s) { + return e ? this._store.write(s) : this._store.parse(s) + } + resource(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + if (!(null == d ? void 0 : d.reload)) { + const d = this._store.read(e, s, n); + if (d) + return d + } + const [h] = yield this.collection(e, s, n, d); + return h + } + )) + } + } + __decorate([ChunkedIdApi(1), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Object, Object, Object]), __metadata("design:returntype", Promise)], Books.prototype, "collection", null); + class Podcasts extends TokenSession { + constructor(e, s, n=Xi.ID, d, h={}, p) { + super("https://amp-api.podcasts.apple.com/v1", e, Object.assign(Object.assign({}, p), { + userToken: s, + storage: d + })), + this.storefrontId = n, + this._store = new LocalDataStore(h), + this.defaultIncludePaginationMetadata = h.features && hasOwn(h.features, "api-pagination-metadata") + } + catalogResource(e, s, n, d) { + return this.resource(e, s, n, d) + } + catalogResources(e, s, n, d) { + return this.collection(e, s, n, d) + } + catalogResourceRelationship(e, s, n, d, h) { + return this.collection(`${e}/${s}/${n}`, void 0, d, h) + } + search(e, s, n) { + return this.collection("search", void 0, Object.assign({ + term: e, + types: "podcasts" + }, s), n) + } + artist(e, s, n) { + return this.catalogResource("artists", e, s, n) + } + artists(e, s, n) { + return this.catalogResources("artists", e, s, n) + } + artistRelationship(e, s, n, d) { + return this.catalogResourceRelationship("artists", e, s, n, d) + } + charts(e, s, n) { + return this.catalogResources("charts", void 0, Object.assign({ + types: e + }, s), n) + } + podcast(e, s, n) { + return this.catalogResource("podcasts", e, Object.assign({ + include: "episodes" + }, s), n) + } + podcasts(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.catalogResources("podcasts", e, Object.assign({ + include: "episodes" + }, s), n) + } + )) + } + podcastRelationship(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + return this.catalogResourceRelationship("podcasts", e, s, n, d) + } + )) + } + episode(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource("podcast-episodes", e, s, n) + } + )) + } + episodes(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.catalogResources("podcast-episodes", e, s, n) + } + )) + } + collection(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + let h; + if (s) { + const d = {}; + d["charts" === e ? "types" : "ids"] = s, + h = Object.assign(d, n) + } else + h = n; + return makeRequest(this, `catalog/${this.storefrontId}/${e}`, h, d) + } + )) + } + parseResultData(e, s) { + return e ? this._store.write(s) : this._store.parse(s) + } + resource(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + if (!(null == d ? void 0 : d.reload)) { + const d = this._store.read(e, s, n); + if (d) + return d + } + const [h] = yield this.collection(e, s, n, d); + return h + } + )) + } + } + __decorate([ChunkedIdApi(1), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Object, Object, Object]), __metadata("design:returntype", Promise)], Podcasts.prototype, "collection", null); + const ma = new Set(["editorial-items"]); + class Fitness extends TokenSession { + constructor(e, s, n=Xi.ID, d, h={}, p) { + var y; + super("https://amp-api.fitness.apple.com/v1", e, Object.assign(Object.assign({}, p), { + userToken: s, + storage: d + })), + this.storefrontId = Xi.ID, + this.storefrontId = n, + this._store = new LocalDataStore(h), + this.defaultIncludePaginationMetadata = !!(null === (y = null == h ? void 0 : h.features) || void 0 === y ? void 0 : y["api-pagination-metadata"]) + } + workout(e, s, n) { + return this.resource("workouts", e, s, n) + } + contributor(e, s, n) { + return this.resource("contributors", e, s, n) + } + editorialItem(e, s, n) { + return this.resource("editorial-items", e, s, n) + } + modalities(e, s, n) { + return this.collection("modalities", e, s, n) + } + modality(e, s, n) { + return this.resource("modalities", e, s, n) + } + workoutProgram(e, s, n) { + return this.resource("workout-programs", e, s, n) + } + collection(e, s, n, d) { + let h; + h = s ? Object.assign({ + ids: s + }, n) : n; + let p = "catalog"; + ma.has(e) && (p = "editorial"); + return makeRequest(this, `${p}/${this.storefrontId}/${e}`, h, d) + } + parseResultData(e, s) { + return e ? this._store.write(s) : this._store.parse(s) + } + resource(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + const h = this._store.read(e, s, n); + if (h) + return h; + const [p] = yield this.collection(e, s, n, d); + return p + } + )) + } + } + __decorate([ChunkedIdApi(1), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Object, Object, Object]), __metadata("design:returntype", Promise)], Fitness.prototype, "collection", null); + class TVLibrary extends TokenSession { + constructor(e, s, n, d={}, h) { + super("https://amp-api.videos.apple.com/v1", e, Object.assign(Object.assign({}, h), { + userToken: s, + storage: n + })), + this._store = new LocalDataStore(d), + this.defaultIncludePaginationMetadata = d.features && hasOwn(d.features, "api-pagination-metadata") + } + genres(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection("genres", Object.assign({ + types: "tv-episodes,movies" + }, e), s) + } + )) + } + movies(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection("movies", e, s) + } + )) + } + purchases(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection("", Object.assign({ + types: "tv-episodes,movies" + }, e), s) + } + )) + } + tvEpisodes(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection("tv-episodes", e, s) + } + )) + } + collection(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + try { + return yield makeRequest(this, "me/purchases/" + e, s, n) + } catch (F) { + if (F.name === MKError.CONTENT_UNAVAILABLE) + return (null == n ? void 0 : n.includePagination) ? { + data: [], + meta: {} + } : []; + throw F + } + } + )) + } + parseResultData(e, s) { + return e ? this._store.write(s) : this._store.parse(s) + } + } + __decorate([ChunkedIdApi(1), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Object, Object]), __metadata("design:returntype", Promise)], TVLibrary.prototype, "collection", null); + const RecommendationUpdate = ()=>(e,s,n)=>{ + if (void 0 === n || "function" != typeof n.value) + throw new TypeError(`Only methods can be decorated with @RecommendationUpdate, but ${s} is not a method.`); + return { + configurable: !0, + get() { + const e = n.value; + function recommendationUpdate(...s) { + return __awaiter(this, void 0, void 0, (function*() { + const n = yield e.apply(this, s) + , d = new Map + , h = [] + , p = new Date; + if (!n || !Array.isArray(n)) + return n; + if (n.forEach((e,s)=>{ + var n, y; + const m = e.id + , g = null !== (n = e.nextUpdateDate) && void 0 !== n ? n : null === (y = e.attributes) || void 0 === y ? void 0 : y.nextUpdateDate; + if (!m || !g) + return; + new Date(g) < p && (h.push(m), + d.set(m, s)) + } + ), + !h.length) + return n; + let[y,m,g,...v] = s; + g = Object.assign(Object.assign({}, g), { + reload: !0 + }); + const _ = [h, m, g, ...v]; + return (yield e.apply(this, _)).forEach(e=>{ + const s = d.get(e.id); + void 0 !== s && (n[s] = e) + } + ), + n + } + )) + } + return Object.defineProperty(this, s, { + value: recommendationUpdate, + configurable: !0, + writable: !0 + }), + recommendationUpdate + } + } + } + ; + function makeAlbumKey(e) { + var s; + return (null === (s = e.artwork) || void 0 === s ? void 0 : s.url) + "" + e.artistName + "" + e.name + } + class ServerLedger { + constructor(e, s, n) { + this._data = this._initData(), + this._catalogApi = s, + this._storageKey = "mk-server-ledger:" + (e || ""), + this._sessionStorage = n || ("undefined" != typeof sessionStorage ? sessionStorage : void 0), + this.load() + } + _initData() { + return { + lastTimestamp: 0, + albums: { + added: Object.create(null), + removed: Object.create(null) + }, + playlists: { + added: Object.create(null), + removed: Object.create(null) + } + } + } + _checkTimestamp() { + const e = this._data.lastTimestamp; + e && e + 24e5 < Date.now() && (this._data = this._initData(), + this._sessionStorage && this._sessionStorage.removeItem(this._storageKey)) + } + added(e) { + this.load(); + const s = null == e ? void 0 : e.playlists + , n = null == e ? void 0 : e.albums; + return s || n ? (s && s.forEach(e=>{ + const s = Date.now(); + this._data.playlists.added[e] = s, + this._data.lastTimestamp = s + } + ), + n && n.forEach(e=>{ + const s = Date.now(); + this._data.albums.added[e] = s, + this._data.lastTimestamp = s + } + ), + this.save(), + e) : e + } + removed(e) { + this.load(); + const s = null == e ? void 0 : e.playlists; + return s ? (ensureArray(s).forEach(e=>{ + if (0 !== e.indexOf("pl.")) { + const s = Date.now(); + this._data.playlists.removed[e] = s, + this._data.lastTimestamp = s + } + } + ), + this.save(), + e) : e + } + reconcile(e, s, n, d, h) { + var p, y; + return __awaiter(this, void 0, void 0, (function*() { + this._checkTimestamp(); + const h = s.data || s; + if (!h || !Array.isArray(h) || Array.isArray(n)) + return s; + const m = this._data.albums.added + , g = this._data.playlists.removed + , v = this._data.playlists.added + , _ = [] + , b = d && !d.offset || !!n && (void 0 === n.offset || 0 === n.offset); + let T = !1; + if ("all" === e || "playlists" === e) { + for (let e = h.length - 1; e >= 0; e--) { + const s = h[e] + , n = null === (p = s.playParams) || void 0 === p ? void 0 : p.globalId; + "library-playlists" === s.type && (g[s.id] ? h.splice(e, 1) : n && v[n] && (delete v[n], + T = !0, + b || h.splice(e, 1))) + } + if (b && this._catalogApi) { + const e = Object.keys(v); + if (e.length) { + const s = yield this._catalogApi.playlists(e); + _.splice(0, 0, ...s) + } + } + } + if (this._catalogApi && ("all" === e || "albums" === e)) { + const e = Object.keys(m); + if (e.length) { + const s = yield this._catalogApi.albums(e) + , n = Object.create(null); + s.forEach((s,d)=>{ + const h = makeAlbumKey(s); + n[h] = { + catalogId: e[d], + album: s + } + } + ); + for (let e = h.length - 1; e >= 0; e--) { + const s = h[e]; + if (null === (y = s.playParams) || void 0 === y || y.globalId, + "library-albums" === s.type) { + const d = makeAlbumKey(s) + , p = n[d]; + p && (delete m[p.catalogId], + T = !0, + b ? delete n[d] : h.splice(e, 1)) + } + } + if (b) { + const e = Object.keys(n).map(e=>n[e].album); + e.length && _.splice(0, 0, ...e) + } + } + } + if (T && this.save(), + b && _.length && (_.sort((e,s)=>{ + const n = this._data.albums.added[e.id] || this._data.playlists.added[e.id] || 0; + return (this._data.albums.added[s.id] || this._data.playlists.added[s.id] || 0) - n + } + ), + h.splice(0, 0, ..._)), + !h.length) + throw new MKError(MKError.CONTENT_UNAVAILABLE,"The requested content is not available."); + const E = s.meta; + return E && void 0 === E.total && (E.total = h.length), + s + } + )) + } + load() { + if (!this._sessionStorage) + return; + const e = this._sessionStorage.getItem(this._storageKey); + if (e) + try { + this._data = JSON.parse(e), + this._data.albums && this._data.playlists || (this._data = this._initData()) + } catch (bt) { + this._data || (this._data = this._initData()) + } + else + this._data = this._initData() + } + save() { + if (!this._sessionStorage) + return; + const e = this._data + , s = 0 === Object.keys(e.albums.added).length && 0 === Object.keys(e.albums.removed).length && 0 === Object.keys(e.playlists.added).length && 0 === Object.keys(e.playlists.removed).length; + try { + if (s) + this._sessionStorage.getItem(this._storageKey) && this._sessionStorage.removeItem(this._storageKey); + else { + const e = JSON.stringify(this._data); + this._sessionStorage.setItem(this._storageKey, e) + } + } catch (bt) {} + } + } + const ga = "me/library"; + class Library extends TokenSession { + constructor(e, s, n, d={}, h, p) { + super(e, s, Object.assign(Object.assign({}, p), { + userToken: n + })), + this._last = 0, + this._store = new LocalDataStore(d), + this._serverLedger = new ServerLedger(n,h), + this.defaultIncludePaginationMetadata = d.features && hasOwn(d.features, "api-pagination-metadata") + } + add(e) { + return __awaiter(this, void 0, void 0, (function*() { + const s = transformKeys(e, dasherize) + , n = Date.now(); + if (n - this._last < 1e3) + return Promise.reject(new MKError(MKError.QUOTA_EXCEEDED)); + const d = new Headers({ + Authorization: "Bearer " + this.developerToken, + "Music-User-Token": this.userToken + }) + , h = Object.keys(s).map(e=>`ids[${e}]=${s[e].join(",")}`).join("&"); + try { + const e = yield fetch(`${this.url}/${ga}?${h}`, { + method: "POST", + headers: d + }); + return e.ok ? (this._last = n, + this._serverLedger.added(s)) : Promise.reject(MKError.responseError(e)) + } catch (p) { + return Promise.reject(MKError.responseError(p)) + } + } + )) + } + remove(e) { + return __awaiter(this, void 0, void 0, (function*() { + if (!this.developerToken || !this.userToken) + return Promise.reject("Invalid tokens"); + const s = new Headers({ + Authorization: "Bearer " + this.developerToken, + "Music-User-Token": this.userToken + }) + , n = transformKeys(e, dasherize) + , d = Object.keys(n)[0] + , h = Object.values(n)[0]; + try { + const e = yield fetch(`${this.url}/${ga}/${d}/${h}`, { + method: "DELETE", + headers: s + }); + return e.ok ? this._serverLedger.removed(n) : Promise.reject(MKError.responseError(e)) + } catch (p) { + return Promise.reject(MKError.responseError(p)) + } + } + )) + } + album(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource("albums", e, s, n) + } + )) + } + albumRelationship(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(`albums/${e}/${s}`, void 0, n, d) + } + )) + } + albums(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + let d; + try { + d = yield this.collection("albums", e, s, Object.assign(Object.assign({}, n), { + shouldCacheResults: !1 + })) + } catch (bt) { + if (bt.errorCode !== MKError.CONTENT_UNAVAILABLE) + throw bt; + d = { + data: [], + meta: {} + } + } + return this._serverLedger.reconcile("albums", d, e, s, n) + } + )) + } + artist(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource("artists", e, s, n) + } + )) + } + artistRelationship(e, s="albums", n, d) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(`artists/${e}/${s}`, void 0, n, d) + } + )) + } + artists(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection("artists", e, s, n) + } + )) + } + createPlaylist(e={}, s) { + return __awaiter(this, void 0, void 0, (function*() { + let n; + const {name: d, description: h, tracks: p=[]} = e + , y = { + attributes: { + name: d, + description: h + }, + relationships: { + tracks: { + data: transformTrackParameters(p) + } + } + } + , m = JSON.stringify(y); + try { + n = yield this.request(ga + "/playlists", s, { + body: m, + method: "POST" + }) + } catch (F) { + return Promise.reject(MKError.responseError(F)) + } + try { + const [e] = this._store.write(n); + return e + } catch (F) { + return Promise.reject(MKError.parseError(F)) + } + } + )) + } + deletePlaylist(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + let n; + const d = `${ga}/playlists/${e}`; + try { + n = yield this.request(d, s, { + method: "DELETE" + }) + } catch (F) { + return Promise.reject(MKError.responseError(F)) + } + this.purgePlaylistFromCaches(e) + } + )) + } + editPlaylist(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + let d; + const h = JSON.stringify({ + attributes: s + }); + try { + d = yield this.request(`${ga}/playlists/${e}`, n, { + body: h, + method: "PATCH" + }) + } catch (F) { + return Promise.reject(MKError.responseError(F)) + } + try { + const n = s + , d = "library-playlists"; + return this._store.write({ + data: [{ + type: d, + id: e, + attributes: n + }] + }), + s + } catch (F) { + return Promise.reject(MKError.parseError(F)) + } + } + )) + } + updatePlaylistTracklist(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + yield this.putPlaylistTracklisting(e, s, "PUT"), + this.purgePlaylistFromCaches(e) + } + )) + } + appendTracksToPlaylist(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + yield this.putPlaylistTracklisting(e, s, "POST"), + this.purgePlaylistFromCaches(e) + } + )) + } + playlistFolder(e, s, n) { + return this.resource("playlist-folders", e, s, n) + } + playlistFolders(e, s, n) { + return this.collection("playlist-folders", e, s, n) + } + playlistFoldersRoot(e, s) { + return e = Object.assign(Object.assign({}, e), { + filter: Object.assign(Object.assign({}, null == e ? void 0 : e.filter), { + identity: "playlistsroot" + }) + }), + this.playlistFolders(void 0, e, s) + } + playlistFolderChildren(e, s, n) { + const d = `playlist-folders/${e}/children`; + return this.collection(d, void 0, s, n) + } + musicVideo(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource("music-videos", e, s, n) + } + )) + } + musicVideos(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection("music-videos", e, s, n) + } + )) + } + parseResultData(e, s) { + return e ? this._store.write(s) : this._store.parse(s) + } + playlist(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return s = Object.assign({ + include: "tracks" + }, s), + this.resource("playlists", e, s, n) + } + )) + } + createCatalogPlaylist(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return n = Object.assign({ + method: "POST" + }, n), + this.resource(`playlists/${e}/catalog`, void 0, s, n) + } + )) + } + playlistRelationship(e, s="tracks", n, d) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(`playlists/${e}/${s}`, void 0, n, d) + } + )) + } + playlists(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + let d; + try { + d = e && e.length > 0 ? yield Promise.all(e.map(e=>this.playlist(e, s, n))) : yield this.collection("playlists", e, s, Object.assign(Object.assign({}, n), { + shouldCacheResults: !1 + })) + } catch (bt) { + if (bt.errorCode !== MKError.CONTENT_UNAVAILABLE) + throw bt; + d = { + data: [], + meta: {} + } + } + return this._serverLedger.reconcile("playlists", d, e, s, n) + } + )) + } + recentlyAdded(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + const n = null == e ? void 0 : e.limit; + let d; + try { + d = yield this.collection("recently-added", void 0, transformParameters(e, n || 10), Object.assign(Object.assign({}, s), { + shouldCacheResults: !1 + })) + } catch (bt) { + if (bt.errorCode !== MKError.CONTENT_UNAVAILABLE) + throw bt; + d = { + data: [], + meta: {} + } + } + return this._serverLedger.reconcile("all", d, void 0, e, s) + } + )) + } + search(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + s = this._denormalizeLibraryTypes(s); + const d = Object.assign({ + term: e, + types: "library-albums" + }, s); + return this.collection("search", void 0, d, Object.assign(Object.assign({}, n), { + shouldCacheResults: !1 + })) + } + )) + } + song(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource("songs", e, s, n) + } + )) + } + songRelationship(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(`songs/${e}/${s}`, void 0, n, d) + } + )) + } + songs(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection("songs", e, s, n) + } + )) + } + collection(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + !s || s.length || n || (n = transformParameters(s, 100), + s = void 0); + const h = s ? Object.assign({ + ids: s + }, n) : n; + return makeRequest(this, `${ga}/${e}`, h, d) + } + )) + } + resource(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + if (!(null == d ? void 0 : d.reload)) { + const d = this._store.read(e, s, n); + if (d) + return d + } + let h = `${ga}/${e}`; + s && (h = `${h}/${s}`); + const [p] = yield makeRequest(this, h, n, d); + return p + } + )) + } + purgePlaylistFromCaches(e) { + this._store.delete("library-playlists", e), + this.networkCache.removeItemsMatching(this.constructURL(`${ga}/playlists/${e}`, {}), !1) + } + putPlaylistTracklisting(e, s, n="PUT") { + return __awaiter(this, void 0, void 0, (function*() { + const d = transformTrackParameters(s) + , h = JSON.stringify({ + data: d + }); + try { + yield this.request(`${ga}/playlists/${e}/tracks`, void 0, { + body: h, + method: n + }) + } catch (F) { + return Promise.reject(MKError.responseError(F)) + } + } + )) + } + _denormalizeLibraryTypes(e={}, s="types") { + let n = e[s]; + return n ? ("string" == typeof n && (n = n.split(",")), + e[s] = n.map(e=>e.replace(/^(albums|music-videos|playlists|songs)$/, "library-$1")), + e) : e + } + } + var fa, va; + __decorate([ChunkedIdApi(1), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Object, Object, Object]), __metadata("design:returntype", Promise)], Library.prototype, "collection", null), + function(e) { + e[e.Global = 0] = "Global", + e.Lyrics = "lyrics", + e.Catalog = "catalog", + e.Personalized = "me", + e.Editorial = "editorial", + e.Engagement = "engagement", + e.Social = "social" + }(fa || (fa = {})), + function(e) { + e.songs = "songs", + e.albums = "albums", + e.playlists = "playlists", + e.stations = "stations", + e["music-videos"] = "music-videos", + e["library-music-videos"] = "library-music-videos", + e["library-playlists"] = "library-playlists", + e["library-songs"] = "library-songs" + }(va || (va = {})); + class API extends TokenSession { + constructor(e, s, n, d, h, p, y={}, m) { + super(e, s, Object.assign(Object.assign({}, m), { + userToken: d, + storage: p + })), + this.storefrontId = Xi.ID, + this.resourceRelatives = { + artists: { + albums: { + include: "tracks" + }, + playlists: { + include: "tracks" + }, + songs: null + } + }, + this.defaultIncludePaginationMetadata = y.features && hasOwn(y.features, "api-pagination-metadata"), + this._store = new LocalDataStore(y), + n && (this.storefrontId = n.toLowerCase()), + d && h && (this.userStorefrontId = h.toLowerCase()), + this._podcastsAPI = new Podcasts(s,d,n,p,y,Object.assign({}, m)), + this.fitness = new Fitness(s,d,n,p,y,Object.assign({}, m)), + this.tvLibrary = new TVLibrary(s,d,p,y,Object.assign({}, m)), + this.library = new Library(e,s,d,y,this,Object.assign({}, m)), + this.books = new Books(s,d,n,p,y,Object.assign({}, m)), + this.v3 = new MediaAPIV3({ + developerToken: s, + mediaUserToken: d, + storefrontId: n, + realmConfig: { + music: { + url: e.replace(/\/v[0-9]+(\/)?$/, "") + } + } + }) + } + get needsEquivalents() { + const {userStorefrontId: e} = this; + return void 0 !== e && "" !== e && e !== this.storefrontId + } + activity(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Catalog, "activities", e, s, n) + } + )) + } + activities(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, "activities", e, s, n) + } + )) + } + album(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Catalog, "albums", e, s, n) + } + )) + } + albumRelationship(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, `albums/${e}/${s}`, void 0, n, d) + } + )) + } + albums(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, "albums", e, s, n) + } + )) + } + appleCurator(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Catalog, "apple-curators", e, s, n) + } + )) + } + appleCurators(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, "apple-curators", e, s, n) + } + )) + } + artist(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Catalog, "artists", e, s, n) + } + )) + } + artistRelationship(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, `artists/${e}/${s}`, void 0, n, d) + } + )) + } + artistView(e, s, n, d) { + return this.collection(fa.Catalog, `artists/${e}/view/${s}`, void 0, n, d) + } + artists(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, "artists", e, s, n) + } + )) + } + audioBook(e, s, n) { + return this.books.audioBook(e, s, n) + } + audioBooks(e, s, n) { + return this.books.audioBooks(e, s, n) + } + catalogResources(e, s={}, n) { + const d = function(e) { + const s = {}; + if (!e) + return s; + for (const n of e) { + if (!n) + continue; + const {type: e, id: d} = n; + e in s || (s[e] = []), + s[e].push(d) + } + return s + }(e); + return s = Object.assign(Object.assign({}, s), { + ids: d + }), + makeRequest(this, `${fa.Catalog}/${this.storefrontId}`, s, n) + } + changeStation(e, s, n={}) { + return __awaiter(this, void 0, void 0, (function*() { + return yield makeRequest(this, "me/stations/change-station/" + e, s, Object.assign(Object.assign({}, n), { + reload: !0, + method: "POST", + shouldCacheResults: !1 + })) + } + )) + } + charts(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, "charts", e, s, Object.assign(Object.assign({}, n), { + returnRawJSONApiRecords: !0 + })) + } + )) + } + contents(e, s, n) { + return this.collection(fa.Catalog, "contents", e, s, n) + } + curator(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Catalog, "contents", e, s, n) + } + )) + } + curators(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, "contents", e, s, n) + } + )) + } + curatorRelationship(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, `curators/${e}/${s}`, void 0, n, d) + } + )) + } + episode(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this._podcastsAPI.catalogResource("podcast-episodes", e, s, n) + } + )) + } + episodes(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this._podcastsAPI.catalogResources("podcast-episodes", e, s, n) + } + )) + } + genre(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Catalog, "genres", e, s, n) + } + )) + } + genres(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, "genres", e, s, n) + } + )) + } + grouping(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + !s && isObject(e) && (s = e, + e = void 0); + const d = { + platform: "desktop" + } + , h = Object.assign(Object.assign({}, d), s); + return this.resource(fa.Editorial, "groupings", e, h, Object.assign(Object.assign({}, n), { + shouldCacheResults: !1 + })) + } + )) + } + groupings(e, s={}, n) { + return __awaiter(this, void 0, void 0, (function*() { + const d = { + platform: "desktop" + } + , h = Object.assign(Object.assign({}, d), s); + return this.collection(fa.Editorial, "groupings", e, h, Object.assign(Object.assign({}, n), { + shouldCacheResults: !1 + })) + } + )) + } + lyric(e, s, n) { + return this.resource(fa.Catalog, `songs/${e}/lyrics`, "", s, Object.assign({ + reload: !0 + }, n)) + } + lyricSnippet(e, s, n) { + return this.collection(fa.Lyrics, "snippet/songs", e, s, Object.assign(Object.assign({}, n), { + returnRawJSONApiRecords: !0 + })) + } + historyHeavyRotation(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Personalized, "history/heavy-rotation", void 0, transformParameters(e, 10), s) + } + )) + } + multiplex(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + const d = this._store.read("multiplex", e, s); + return d || (n = Object.assign({ + returnRawJSONApiRecords: !0 + }, n), + makeRequest(this, `${fa.Editorial}/${this.storefrontId}/multiplex/${e}`, s, n)) + } + )) + } + multiroom(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + const d = this._store.read("multirooms", e, s); + if (d) + return d; + const [h] = yield this.collection(fa.Editorial, "multirooms/" + e, void 0, s, n); + return h + } + )) + } + musicMovie(e, s, n) { + return this.resource(fa.Catalog, "music-movies", e, s, n) + } + musicMovies(e, s, n) { + return this.collection(fa.Catalog, "music-movies", e, s, n) + } + musicVideo(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Catalog, "music-videos", e, s, n) + } + )) + } + musicVideos(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, "music-videos", e, s, n) + } + )) + } + nextStationTracks(e, s, n={}) { + return __awaiter(this, void 0, void 0, (function*() { + const d = {}; + (null == s ? void 0 : s.clean) && (d.clean = s.clean, + delete s.clean), + (null == s ? void 0 : s.limit) && (d.limit = s.limit, + delete s.limit); + return yield makeRequest(this, "me/stations/next-tracks/" + e, s, Object.assign(Object.assign({}, n), { + reload: !0, + method: "POST", + queryParameters: d, + shouldCacheResults: !1 + })) + } + )) + } + continuousStation(e, s, n={}) { + return __awaiter(this, void 0, void 0, (function*() { + return yield makeRequest(this, "me/stations/continuous", e, Object.assign(Object.assign({}, n), { + reload: !0, + method: "POST", + queryParameters: s, + returnRawJSONApiRecords: !0, + shouldCacheResults: !1 + })) + } + )) + } + playlist(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Catalog, "playlists", e, s, n) + } + )) + } + playlistRelationship(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, `playlists/${e}/${s}`, void 0, n, d) + } + )) + } + playlists(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, "playlists", e, s, n) + } + )) + } + podcast(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this._podcastsAPI.catalogResource("podcasts", e, Object.assign({ + include: "episodes" + }, s), n) + } + )) + } + podcastRelationship(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + return this._podcastsAPI.catalogResourceRelationship("podcasts", e, s, n, d) + } + )) + } + podcasts(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this._podcastsAPI.catalogResources("podcasts", e, Object.assign({ + include: "episodes" + }, s), n) + } + )) + } + recentPlayed(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Personalized, "recent/played", void 0, transformParameters(e, 10), s) + } + )) + } + recentRadioStations(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Personalized, "recent/radio-stations", void 0, transformParameters(e, 10), s) + } + )) + } + recordLabel(e, s, n) { + return this.resource(fa.Catalog, "record-labels", e, s, n) + } + recordLabels(e, s, n) { + return this.collection(fa.Catalog, "record-labels", e, s, n) + } + recordLabelView(e, s, n, d) { + return this.collection(fa.Catalog, `record-labels/${e}/view/${s}`, void 0, n, d) + } + personalRecommendation(e, s, n, d=!0) { + return __awaiter(this, void 0, void 0, (function*() { + const h = yield this.personalRecommendations(e, s, n, d) + , [p] = h; + return p + } + )) + } + refreshPersonalRecommendation(e, s, n) { + const d = formatTimezoneOffset(); + return s = Object.assign({ + timezone: d + }, s), + n = Object.assign(Object.assign({}, n), { + method: "POST", + queryParameters: s + }), + this.resource(fa.Personalized, "recommendations", e, void 0, n) + } + personalRecommendations(e, s, n={}, d=!0) { + return __awaiter(this, void 0, void 0, (function*() { + const h = formatTimezoneOffset() + , p = yield this.collection(fa.Personalized, "recommendations", e, Object.assign({ + timezone: h + }, s), Object.assign(Object.assign({}, n), { + shouldCacheResults: d, + returnRawJSONApiRecords: !0 + })); + this._reindexRelationships(p, "recommendations"); + try { + return mapRequestResult(p, e=>this.parseResultData(!1, e)) + } catch (F) { + return Promise.reject(MKError.parseError(F)) + } + } + )) + } + personalRecommendationView(e, s, n, d={}) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Personalized, `recommendations/${e}/view/${s}`, void 0, n, d) + } + )) + } + recommendations(e, s, n={}) { + return __awaiter(this, void 0, void 0, (function*() { + const d = formatTimezoneOffset() + , h = yield this.collection(fa.Global, "recommendations/" + this.storefrontId, e, Object.assign({ + timezone: d + }, s), Object.assign(Object.assign({}, n), { + shouldCacheResults: !1, + returnRawJSONApiRecords: !0 + })); + this._reindexRelationships(h, "recommendations"); + try { + return mapRequestResult(h, e=>this.parseResultData(!1, e)) + } catch (F) { + return Promise.reject(MKError.parseError(F)) + } + } + )) + } + recommendedFriends(e, s, n={}) { + return n = Object.assign(Object.assign({}, n), { + method: "POST", + body: JSON.stringify(Object.assign({ + ids: { + socialProfiles: e + } + }, n.body)) + }), + this.collection(fa.Global, "social/recommended-friends", void 0, s, Object.assign(Object.assign({}, n), { + shouldCacheResults: !1, + returnRawJSONApiRecords: !0 + })) + } + room(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + const d = this._store.read("rooms", e, s); + if (d && d.hasAttributes("title")) + return d; + const h = yield this.collection(fa.Editorial, "rooms/" + e, void 0, s, n) + , [p] = h; + return p + } + )) + } + roomContents(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Editorial, `rooms/${e}/contents`, void 0, s, n) + } + )) + } + search(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + const d = Object.assign({ + term: e + }, s); + return n = Object.assign(Object.assign({}, n), { + useRawResponse: !0 + }), + this.collection(fa.Catalog, "search", void 0, d, Object.assign(Object.assign({}, n), { + shouldCacheResults: !1 + })) + } + )) + } + searchHints(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + const d = Object.assign({ + term: e + }, s) + , h = yield this.collection(fa.Catalog, "search/hints", void 0, d, Object.assign(Object.assign({}, n), { + returnRawJSONApiRecords: !0 + })); + return "topResults" === (null == d ? void 0 : d.with) && "topResults"in h && (h.topResults = this.parseResultData(!0, h.topResults)), + h + } + )) + } + searchQuery(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + return s = Object.assign(Object.assign({}, s), { + useRawResponse: !0 + }), + this.collection(fa.Catalog, "search/query", void 0, e, Object.assign(Object.assign({}, s), { + shouldCacheResults: !1 + })) + } + )) + } + searchSuggestions(e, s, n) { + var d; + return __awaiter(this, void 0, void 0, (function*() { + s = Object.assign({ + term: e + }, s); + const h = yield this.collection(fa.Catalog, "search/suggestions", void 0, s, Object.assign(Object.assign({}, n), { + returnRawJSONApiRecords: !0 + })); + return Array.isArray(null === (d = h) || void 0 === d ? void 0 : d.suggestions) && h.suggestions.forEach(e=>{ + "topResults" === e.kind && (e.content = this.parseResultData(!0, [e.content])[0]) + } + ), + h + } + )) + } + socialBadgingMap(e, s) { + return this.collection(fa.Global, "social/badging-map", void 0, e, Object.assign(Object.assign({}, s), { + returnRawJSONApiRecords: !0 + })) + } + socialProfile(e, s, n) { + return this.resource(fa.Social, "social-profiles", e, s, n) + } + socialProfiles(e, s, n) { + return this.collection(fa.Social, "social-profiles", e, s, n) + } + personalSocialProfile(e, s) { + return this.resource(fa.Personalized, "social-profile", void 0, e, s) + } + socialPost(e, s={}, n) { + return __awaiter(this, void 0, void 0, (function*() { + e.startsWith("sa.") ? s.filter = { + post: e + } : s.ids = e; + const [d] = yield this.collection(fa.Catalog, "contents", "", s, n); + return d + } + )) + } + socialSearch(e, s={}, n) { + return __awaiter(this, void 0, void 0, (function*() { + return s = Object.assign(Object.assign({}, s), { + term: e + }), + this.collection(fa.Social, "search", void 0, s, n) + } + )) + } + song(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Catalog, "songs", e, s, n) + } + )) + } + songRelationship(e, s, n, d) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Catalog, `songs/${e}/${s}`, void 0, n, d) + } + )) + } + songs(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return !s && isObject(e) && (s = e, + e = void 0), + this.collection(fa.Catalog, "songs", e, s, n) + } + )) + } + tastePreferences(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Personalized, "taste/taste-preferences", void 0, e, Object.assign(Object.assign({}, s), { + shouldCacheResults: !1 + })) + } + )) + } + saveTastePreferences(e) { + return __awaiter(this, void 0, void 0, (function*() { + e = e.map(e=>e instanceof DataRecord ? e.serialize().data : e); + const s = { + method: "POST", + body: JSON.stringify({ + data: e + }), + shouldCacheResults: !0 + }; + try { + return yield makeRequest(this, "me/taste/taste-preferences", void 0, s) + } catch (F) { + return F.name === MKError.CONTENT_UNAVAILABLE ? [] : Promise.reject(MKError.parseError(F)) + } + } + )) + } + tvEpisode(e, s, n) { + return this.resource(fa.Catalog, "tv-episodes", e, Object.assign({ + include: "seasons" + }, s), n) + } + tvEpisodes(e, s, n) { + return this.collection(fa.Catalog, "tv-episodes", e, Object.assign({ + include: "seasons" + }, s), n) + } + tvSeason(e, s, n) { + return this.resource(fa.Catalog, "tv-seasons", e, Object.assign({ + include: "episodes" + }, s), n) + } + tvSeasons(e, s, n) { + return this.collection(fa.Catalog, "tv-seasons", e, Object.assign({ + include: "episodes" + }, s), n) + } + tvShow(e, s, n) { + return this.resource(fa.Catalog, "tv-shows", e, s, n) + } + tvShows(e, s, n) { + return this.collection(fa.Catalog, "tv-shows", e, s, n) + } + uploadedAudio(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return s = Object.assign({ + include: "curator,artists" + }, s), + this.resource(fa.Catalog, "uploaded-audios", e, s, n) + } + )) + } + uploadedAudios(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return s = Object.assign({ + include: "curator,artists" + }, s), + this.collection(fa.Catalog, "uploaded-audios", e, s, n) + } + )) + } + uploadedVideo(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return s = Object.assign({ + include: "curator,artists" + }, s), + this.resource(fa.Catalog, "uploaded-videos", e, s, n) + } + )) + } + uploadedVideos(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return s = Object.assign({ + include: "curator,artists" + }, s), + this.collection(fa.Catalog, "uploaded-videos", e, s, n) + } + )) + } + upsellMarketingItems(e, s) { + return this.collection(fa.Engagement, "upsell/marketing-items", void 0, e, s) + } + station(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Catalog, "stations", e, s, n) + } + )) + } + stations(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return !s && isObject(e) && (s = e, + e = void 0), + this.collection(fa.Catalog, "stations", e, s, n) + } + )) + } + storefront(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Global, "storefronts", e, s, n) + } + )) + } + storefronts(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Global, "storefronts", e, s, n) + } + )) + } + musicSummary(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + return this.resource(fa.Personalized, "music-summaries", e, s, n) + } + )) + } + musicSummarySearch(e={}, s) { + return __awaiter(this, void 0, void 0, (function*() { + return this.collection(fa.Personalized, "music-summaries/search", void 0, e, s) + } + )) + } + addToLibrary(e) { + return __awaiter(this, void 0, void 0, (function*() { + return this.developerToken && this.userToken && this.library ? this.library.add(e) : Promise.reject("Invalid tokens") + } + )) + } + rating(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + const [d] = yield this.ratings(e, s, n); + return d + } + )) + } + ratings(e, s, n) { + if (!this.developerToken || !this.userToken) + return Promise.reject("Invalid tokens"); + const [d] = Object.keys(e) + , h = e[d] + , p = Array.isArray(h); + if (p && 0 === h.length) + return Promise.resolve([]); + let y = "me/ratings/" + formatRatingsContentType(d, p ? h[0] : h); + return p ? s = Object.assign(Object.assign({}, s), { + ids: h.map(normalizeAdamId) + }) : y = `${y}/${normalizeAdamId(h)}`, + makeRequest(this, y, s, Object.assign({ + shouldCacheResults: !1, + reload: !0, + includePagination: !1 + }, n)) + } + putRating(e, s, n) { + return __awaiter(this, void 0, void 0, (function*() { + if (!this.developerToken || !this.userToken) + return Promise.reject("Invalid tokens"); + const [d] = Object.keys(e) + , h = e[d] + , p = formatRatingsContentType(d, h) + , y = { + method: "PUT", + body: JSON.stringify({ + type: "rating", + attributes: { + value: s + } + }), + includePagination: !1 + } + , m = yield makeRequest(this, `me/ratings/${p}/${normalizeAdamId(h)}`, n, Object.assign({ + shouldCacheResults: !1 + }, y)) + , [g] = m; + return g + } + )) + } + deleteRating(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + if (!this.developerToken || !this.userToken) + return Promise.reject("Invalid tokens"); + const [n] = Object.keys(e) + , d = e[n] + , h = formatRatingsContentType(n, d); + if (Array.isArray(d)) + return Promise.all(d.map(e=>this.deleteRating({ + [n]: e + }, s))).then(()=>{} + ); + yield makeRequest(this, `me/ratings/${h}/${d}`, s, { + method: "DELETE", + shouldCacheResults: !1, + returnRawJSONApiRecords: !0 + }); + try { + this._store.delete(h, d) + } catch (F) { + return Promise.reject(MKError.parseError(F)) + } + } + )) + } + equivalent(e, s) { + return __awaiter(this, void 0, void 0, (function*() { + let n = `catalog/${this.userStorefrontId}/${e}` + , d = {}; + switch (e) { + case "albums": + case "songs": + d = { + "filter[equivalents]": s + }; + break; + case "artists": + case "playlists": + n = `${n}/${s}`; + break; + default: + return Promise.reject(new MKError(MKError.INVALID_ARGUMENTS,"Invalid equivalent type")) + } + return this.resource(fa.Global, n, "", d) + } + )) + } + collection(e, s, n, d, h) { + return __awaiter(this, void 0, void 0, (function*() { + let p, y, m = null == h ? void 0 : h.shouldCacheResults; + switch (p = n ? Object.assign({ + ["charts" === s ? "types" : "ids"]: n + }, d) : d, + e) { + case fa.Catalog: + case fa.Editorial: + case fa.Engagement: + case fa.Social: + case fa.Lyrics: + const n = this.storefrontId; + y = `${e}/${n}/${s}`; + break; + case fa.Global: + y = s; + break; + case fa.Personalized: + y = `${e}/${s}`, + m = !1 + } + return makeRequest(this, y, p, Object.assign(Object.assign({}, h), { + shouldCacheResults: m + })) + } + )) + } + parseResultData(e, s) { + return e ? this._store.write(s) : this._store.parse(s) + } + resource(e, s, n, d, h) { + return __awaiter(this, void 0, void 0, (function*() { + if (!(null == h ? void 0 : h.reload)) { + const e = this._store.read(s, n, d); + if (e) + return e + } + const [p] = yield this.collection(e, s, n, d, h); + return p + } + )) + } + _reindexRelationships(e, s) { + ("data"in e ? e.data : e).forEach(e=>{ + hasOwn(e, "relationships") && hasOwn(e.relationships, s) && hasOwn(e.relationships[s], "data") && Array.isArray(e.relationships[s].data) && e.relationships[s].data.forEach((e,s)=>{ + e.id = `${e.id}-${s}` + } + ) + } + ) + } + } + let _a; + __decorate([RecommendationUpdate(), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Object, Object]), __metadata("design:returntype", Promise)], API.prototype, "personalRecommendations", null), + __decorate([RecommendationUpdate(), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Object]), __metadata("design:returntype", Promise)], API.prototype, "recommendations", null), + __decorate([ChunkedIdApi(2), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, String, Object, Object, Object]), __metadata("design:returntype", Promise)], API.prototype, "collection", null); + const configure$1 = (e,s=!1)=>__awaiter$3(void 0, void 0, void 0, (function*() { + if (_a && !s) { + if (void 0 === e.storefrontId || e.storefrontId === _a.storefrontId) + return _a; + _a.clear() + } + return _a = new MediaAPIService(e.dispatcher), + _a.configure(e) + } + )) + , ba = { + album: { + isPlural: !1, + apiMethod: "album", + relationshipMethod: { + method: "albumRelationship", + relationship: "tracks" + } + }, + albums: { + isPlural: !0, + apiMethod: "albums" + }, + audioBook: { + isPlural: !1, + apiMethod: "audioBook" + }, + audioBooks: { + isPlural: !0, + apiMethod: "audioBooks" + }, + episode: { + isPlural: !1, + apiMethod: "episode" + }, + episodes: { + isPlural: !0, + apiMethod: "episodes" + }, + musicVideo: { + isPlural: !1, + apiMethod: "musicVideo" + }, + musicVideos: { + isPlural: !0, + apiMethod: "musicVideos" + }, + musicMovie: { + isPlural: !1, + apiMethod: "musicMovie" + }, + musicMovies: { + isPlural: !0, + apiMethod: "musicMovies" + }, + podcast: { + isPlural: !1, + apiMethod: "podcast" + }, + podcasts: { + isPlural: !0, + apiMethod: "podcasts" + }, + playlist: { + isPlural: !1, + apiMethod: "playlist", + relationshipMethod: { + method: "playlistRelationship", + relationship: "tracks" + } + }, + playlists: { + isPlural: !0, + apiMethod: "playlists" + }, + song: { + isPlural: !1, + apiMethod: "song" + }, + songs: { + isPlural: !0, + apiMethod: "songs" + }, + tvEpisode: { + isPlural: !1, + apiMethod: "tvEpisode" + }, + tvEpisodes: { + isPlural: !0, + apiMethod: "tvEpisodes" + }, + uploadedAudio: { + isPlural: !1, + apiMethod: "uploadedAudio" + }, + uploadedAudios: { + isPlural: !0, + apiMethod: "uploadedAudios" + }, + uploadedVideo: { + isPlural: !1, + apiMethod: "uploadedVideo" + }, + uploadedVideos: { + isPlural: !0, + apiMethod: "uploadedVideos" + } + }; + class MediaAPIService { + constructor(e) { + if (this._dispatcher = e, + !ln.urls.mediaApi) + throw new Error("bag.urls.mediaApi is not configured"); + this.url = ln.urls.mediaApi, + this.namedQueueOptions = ba, + this._dispatcher.subscribe(et.apiStorefrontChanged, (e,{storefrontId: s})=>__awaiter$3(this, void 0, void 0, (function*() { + yield this._updateStorefrontId(s) + } + ))) + } + get api() { + if (void 0 === this._api) + throw new MKError(MKError.CONFIGURATION_ERROR,"The API cannot be accessed before it is configured."); + return this._api + } + get storefrontId() { + return this.store && this.store.storefrontId + } + configure(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + if (void 0 !== e.store) + return this.store = e.store, + [ns.userTokenDidChange, ns.storefrontIdentifierDidChange].forEach(e=>{ + this.store.storekit.addEventListener(e, ()=>this.resetAPI()) + } + ), + this._initializeAPI(e), + this + } + )) + } + clear() { + this.api && this.api.clearNetworkCache && this.api.clearNetworkCache() + } + getAPIForItem(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return v(e) ? (yield this.store.authorize(), + this.api.library || this.api) : this.api + } + )) + } + resetAPI() { + return __awaiter$3(this, void 0, void 0, (function*() { + this.clear(), + this._initializeAPI() + } + )) + } + _initializeAPI(e) { + if (void 0 !== (null == e ? void 0 : e.api)) + return void (this._api = e.api); + const s = e && e.store || this.store; + if (void 0 === s) + return; + const n = ln.features["api-session-storage"] ? sessionStorage : void 0 + , d = e && e.storefrontId || s.storefrontId + , h = new API(this.url,s.developerToken,d,s.storekit.userToken,s.storekit.storefrontCountryCode,n,ln,e && e.apiOptions && e.apiOptions.sessionOptions); + this._api = h.v3, + this._api = h + } + _updateStorefrontId(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + this.api && e === this.api.storefrontId || (yield this.configure({ + dispatcher: this._dispatcher, + store: this.store, + storefrontId: e + })) + } + )) + } + } + const Ta = ["uploadedVideo", "uploadedAudio", "uploaded-videos", "uploaded-audios"] + , typeRequiresItem = e=>[et.playbackPlay, et.playbackSkip].includes(e) + , itemIsRequired = (e,s)=>void 0 !== s && typeRequiresItem(e) + , cleanContainer = e=>{ + const s = Object.assign({}, e); + return delete s.attributes, + s + } + , computeContainer = (e,s)=>{ + var n, d; + const h = ((e,s)=>{ + var n; + return itemIsRequired(e, s) && (null === (n = null == s ? void 0 : s.container) || void 0 === n ? void 0 : n.name) || null + } + )(e, s) + , p = itemIsRequired(e, s) ? Object.assign(Object.assign({}, null == s ? void 0 : s.container), null === (d = null === (n = null == s ? void 0 : s.container) || void 0 === n ? void 0 : n.attributes) || void 0 === d ? void 0 : d.playParams) : null; + if (null !== h || null !== p) + return { + container: cleanContainer(Object.assign(Object.assign({}, p), null !== h ? { + name: h + } : {})) + } + } + , Ea = { + [e.PlayerRepeatMode.all]: lt.REPEAT_ALL, + [e.PlayerRepeatMode.none]: lt.REPEAT_OFF, + [e.PlayerRepeatMode.one]: lt.REPEAT_ONE + } + , ka = { + [Pn.off]: ct.SHUFFLE_OFF, + [Pn.songs]: ct.SHUFFLE_ON + } + , descriptorFromInstance = e=>e && e.playbackActions ? { + playMode() { + var s; + let n = lt.REPEAT_UNKNOWN + , d = ct.SHUFFLE_UNKNOWN + , h = ut.AUTO_UNKNOWN; + const {playbackActions: p} = e; + var y; + return p && (p.includes("REPEAT") && (n = Ea[e.repeatMode]), + p.includes("SHUFFLE") && (d = (null === (s = e.queue.currentQueueItem) || void 0 === s ? void 0 : s.isAutoplay) ? ct.SHUFFLE_OFF : ka[e.shuffleMode]), + p.includes("AUTOPLAY") && (h = e.autoplayEnabled ? (y = e.queue).hasAutoplayStation && y.items.some(e=>{ + const {id: s, type: n, container: d} = e; + if (d && "stations" === d.type && d.name === tt.RADIO) + return !1; + const h = normalizeTypeForAutoplay(s, n); + return isAutoplaySupportedForType(h) + } + ) ? ut.AUTO_ON : ut.AUTO_ON_CONTENT_UNSUPPORTED : ut.AUTO_OFF)), + { + repeatPlayMode: n, + shufflePlayMode: d, + autoplayMode: h + } + } + } : {} + , generateItemDescriptorForPAF = (e,s,n)=>{ + const d = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, descriptorFromInstance(s)), ((e,s)=>{ + var n; + if (!typeRequiresItem(e)) + return {}; + if (void 0 === s) + return {}; + const d = null === (n = s.attributes) || void 0 === n ? void 0 : n.mediaKind; + return Object.assign(Object.assign({}, void 0 !== d ? { + mediaType: d + } : {}), s.playParams) + } + )(e, n)), ((e,s)=>{ + if (!typeRequiresItem(e) || void 0 === s) + return {}; + const {context: n={}} = s; + return { + recoData: n.reco_id + } + } + )(e, n)), ((e,s)=>{ + if (!typeRequiresItem(e) || void 0 === s) + return {}; + const n = s.playbackDuration; + return n ? { + duration: n / 1e3 + } : {} + } + )(e, n)), computeContainer(e, n)), { + trackInfo: null == n ? void 0 : n.trackInfo + }); + return Mr.trace("PAF descriptor", d), + d + } + , asCode = s=>{ + switch (typeof s) { + case "string": + return s; + case "undefined": + return "undefined"; + default: + return "PlayActivityEndReasonType." + e.PlayActivityEndReasonType[s] + } + } + ; + class PAFTrackerAPI { + get apiService() { + if (void 0 === this.service) + throw new MKError(MKError.CONFIGURATION_ERROR,"Play Activity service was called before configuration."); + return this.service + } + configure(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + return this.instance = e, + this.service = new PlayActivity(e.developerToken,e.musicUserToken,e.storefrontCountryCode,{ + app: { + build: ln.app.build, + name: ln.app.name, + version: ln.app.version + }, + fetch: !Ke && fetch.bind(window), + logInfo: Mr.enabled, + sourceType: e.sourceType, + services: s.services, + userIsSubscribed: ()=>e.isAuthorized && un.storekit._getIsActiveSubscription.getCachedValue() + }), + this + } + )) + } + cleanup() {} + shouldConfigure(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + return void 0 !== e.musicUserToken + } + )) + } + activate(e={}) { + return this.apiService.activate(e.flush) + } + exit(e={}) { + return Mr.debug("PAF debug", `client.exit(${e.position})`), + this.apiService.exit(e.position) + } + pause(e, s={}) { + return "number" == typeof s.endReasonType ? (Mr.debug("PAF debug", `client.stop(${s.position}, ${s.endReasonType})`), + this.apiService.stop(s.position, s.endReasonType)) : (Mr.debug("PAF debug", `client.pause(${s.position})`), + this.apiService.pause(s.position)) + } + play(e, s={}) { + const n = generateItemDescriptorForPAF(et.playbackPlay, this.instance, e); + return Mr.debug("PAF debug", `client.play(${JSON.stringify(n)}, ${s.position})`), + this.apiService.play(n, s.position) + } + scrub(e, s={}) { + return Mr.debug("PAF debug", `client.scrub(${s.position}, ${asCode(s.endReasonType)})`), + this.apiService.scrub(s.position, s.endReasonType) + } + seek(s, n={}) { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this.scrub(s, { + position: n.startPosition, + endReasonType: e.PlayActivityEndReasonType.SCRUB_BEGIN + }), + yield this.scrub(s, { + position: n.position, + endReasonType: e.PlayActivityEndReasonType.SCRUB_END + }) + } + )) + } + skip(e, s={}) { + return __awaiter$3(this, void 0, void 0, (function*() { + const n = generateItemDescriptorForPAF(et.playbackSkip, this.instance, e); + Mr.debug("PAF debug", `client.skip(${JSON.stringify(n)}, ${asCode(s.direction)}, ${s.position})`); + try { + yield this.apiService.skip(n, s.direction, s.position) + } catch (bt) { + if ("A play stop() method was called without a previous play() descriptor" !== bt.message) + return Promise.reject(bt); + yield this.play(e, s) + } + } + )) + } + stop(s, n={}) { + var d; + return (null == s ? void 0 : s.isLiveRadioStation) && n.position && (n.position = n.position - (n.startPosition || 0)), + (null == s ? void 0 : s.isLiveRadioStation) && (n.endReasonType = null !== (d = n.endReasonType) && void 0 !== d ? d : e.PlayActivityEndReasonType.PLAYBACK_MANUALLY_PAUSED), + Mr.debug("PAF debug", `client.stop(${n.position}, ${asCode(n.endReasonType)})`), + this.apiService.stop(n.position, n.endReasonType) + } + shouldTrackPlayActivity(s, n) { + const d = hasAuthorization() + , h = !n || n.playbackType !== e.PlaybackType.preview + , p = this.alwaysSendForActivityType(s) + , y = !n || n && this.mediaRequiresPlayActivity(n); + return !(!d || !h || !p && !y) + } + alwaysSendForActivityType(e) { + return e === et.playerActivate || e === et.playerExit + } + mediaRequiresPlayActivity(e) { + return void 0 !== (s = e.type) && Ta.includes(s) || -1 !== ["musicVideo", "song", "radioStation"].indexOf(e.type); + var s + } + } + function filterLinks(e) { + return __awaiter(this, void 0, void 0, (function*() { + const s = yield function() { + return __awaiter(this, void 0, void 0, (function*() { + const e = [{ + feature: "album-song", + regex: "http(?:s)?://(?itunes|music).apple.com/(?\\w{2})/albums?/(?:[^/]+/)?(?\\d+)$", + requiredQueryParams: { + i: "(?\\d+)" + }, + mediaAPI: { + resources: ["songs"] + } + }, { + feature: "albums", + regex: "http(?:s)?://(?itunes|music).apple.com/(?\\w{2})/albums?/(?:[^/]+/)?(?\\d+)$", + mediaAPI: { + resources: ["albums"] + } + }, { + feature: "algo-stations", + regex: "http(?:s)?://(?itunes|music).apple.com/(?\\w{2})/stations?/(?:[^/]+/)?(?(?:ra|st).\\d+)", + mediaAPI: { + resources: ["stations"] + } + }, { + feature: "artist-default-playable-content", + regex: "http(?:s)?://(?itunes|music).apple.com/(?\\w{2})/artists?/(?:[^/]+/)?(?\\d+)$", + mediaAPI: { + resources: ["artists", "default-playable-content"] + } + }, { + feature: "genre-stations", + regex: "http(?:s)?://(?itunes|music).apple.com/(?\\w{2})/genre-stations?", + mediaAPI: { + resources: ["stations"], + parameterMapping: { + genres: "filter[genres]", + eras: "filter[eras]", + tags: "filter[tags]", + moods: "filter[moods]" + } + } + }, { + feature: "library-albums", + regex: "http(?:s)?://(?itunes|music).apple.com/library/albums?/(?:[^/]+/)?(?(?:l).[a-zA-Z0-9-]+)$", + mediaAPI: { + resources: ["albums"] + } + }, { + feature: "library-album-song", + regex: "http(?:s)?://(?itunes|music).apple.com/library/albums?/(?:[^/]+/)?(?(?:l).[a-zA-Z0-9-]+)$", + requiredQueryParams: { + i: "(?i\\.[a-zA-Z0-9-]+)" + }, + mediaAPI: { + resources: ["songs"] + } + }, { + feature: "library-playlists", + regex: "http(?:s)?://(?itunes|music).apple.com/library/playlists?/(?:[^/]+/)?(?(?:p).[a-zA-Z0-9-]+)$", + mediaAPI: { + resources: ["playlists"] + } + }, { + feature: "music-videos", + regex: "http(?:s)?://(?itunes|music).apple.com/(?\\w{2})/music-videos?/(?:[^/]+/)?(?\\d+)$", + mediaAPI: { + resources: ["musicVideos"] + } + }, { + feature: "personal-general-radio", + regex: "http(?:s)?://(?itunes|music).apple.com/(?\\w{2})/stations?/me$", + mediaAPI: { + resources: ["stations"], + parameters: { + "filter[identity]": "personal" + } + } + }, { + feature: "personal-mixes", + regex: "http(?:s)?://(?itunes|music).apple.com/(?\\w{2})/(?:personal-)?mix/(?:[^/]+/)?(?mx.(?:\\d{1,2}|rp-\\d{4}))$", + mediaAPI: { + resources: ["playlists"] + } + }, { + feature: "playlists", + regex: "http(?:s)?://(?itunes|music).apple.com/(?\\w{2})/playlists?/(?:[^/]+/)?(?(?:pl).[a-zA-Z0-9-]+)$", + mediaAPI: { + resources: ["playlists"] + } + }, { + feature: "song", + regex: "http(?:s)?://(?itunes|music).apple.com/(?\\w{2})/songs?/(?:[^/]+/)?(?\\d+)$", + mediaAPI: { + resources: ["songs"] + } + }, { + feature: "steering-request", + regex: "http(?:s)?://(?itunes|music).apple.com/me/stations?/change-station/?$", + mediaAPI: { + resources: ["stations"] + } + }].map(e=>(e.regex = new RegExp(e.regex), + e.requiredQueryParams && (e.requiredQueryParams = Object.keys(e.requiredQueryParams).reduce((s,n)=>(s[n] = new RegExp(e.requiredQueryParams[n]), + s), {})), + e)); + return Promise.resolve(e) + } + )) + }() + , n = parseQueryParams(e); + return s.reduce((s,d)=>{ + if (function(e, s, n={}) { + const [d] = e.split(/\?|\#|\&/) + , h = s.regex.test(d); + return h && s.requiredQueryParams ? Object.keys(s.requiredQueryParams).every(e=>{ + const d = n[e]; + return s.requiredQueryParams[e].test(d) + } + ) : h + }(e, d, n)) { + if (s.length > 0) + if (d.requiredQueryParams) + s = s.filter(e=>e.requiredQueryParams); + else if (s.some(e=>e.requiredQueryParams)) + return s; + d.requiredQueryParams ? d.mediaAPI.parameters = Object.keys(d.requiredQueryParams).reduce((e,s)=>(e[s] = n[s], + e), {}) : d.mediaAPI.parameterMapping && (d.mediaAPI.parameters = transform$9(d.mediaAPI.parameterMapping, n, !0)), + s.push(d) + } + return s + } + , []) + } + )) + } + const Sa = /^http(?:s)?\:\/\/(?:itunes|(embed\.)?(music|podcasts|tv))\.apple\.com/i + , Pa = ["allow-forms", "allow-popups", "allow-same-origin", "allow-scripts", "allow-storage-access-by-user-activation", "allow-top-navigation-by-user-activation"] + , Ia = ["autoplay *", "encrypted-media *", "fullscreen *"] + , Aa = createLocalStorageFlag("mk-generate-swizzle"); + const wa = MKError.errors; + class MusicKitInstance extends MKInstance { + addToLibrary(e, s) { + return __awaiter$3(this, void 0, void 0, (function*() { + yield this.authorize(), + s || (s = /[a-z]{2}\.[a-z0-9\-]+/i.test(e) ? "playlists" : "albums"); + const n = {}; + let d; + return n[s] = [e], + d = this.api.addToLibrary(n), + d + } + )) + } + changeToMediaItem(e) { + const s = Object.create(null, { + changeToMediaItem: { + get: ()=>super.changeToMediaItem + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + return this._checkNeedsEquivalent(), + s.changeToMediaItem.call(this, e) + } + )) + } + play() { + const e = Object.create(null, { + play: { + get: ()=>super.play + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + return this._checkNeedsEquivalent(), + e.play.call(this) + } + )) + } + playMediaItem(e) { + const s = Object.create(null, { + playMediaItem: { + get: ()=>super.playMediaItem + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + return this._checkNeedsEquivalent(), + s.playMediaItem.call(this, e) + } + )) + } + setQueue(e) { + const s = Object.create(null, { + setQueue: { + get: ()=>super.setQueue + } + }); + return __awaiter$3(this, void 0, void 0, (function*() { + return this._checkNeedsEquivalent(), + s.setQueue.call(this, e) + } + )) + } + _checkNeedsEquivalent() { + var e; + if (!this.previewOnly && (null === (e = this.api) || void 0 === e ? void 0 : e.needsEquivalents)) + throw new MKError(MKError.CONTENT_EQUIVALENT) + } + } + function configure(e) { + return __awaiter$3(this, void 0, void 0, (function*() { + const s = new PAFTrackerAPI; + e.playActivityAPI = s; + return yield configure$2(e, MusicKitInstance, s=>__awaiter$3(this, void 0, void 0, (function*() { + const n = { + apiType: ia.MEDIA, + configureFn: configure$1, + options: {} + }; + n.options.apiOptions = e.apiOptions, + yield s.configure([n]), + e.declarativeMarkup && "undefined" != typeof console && console.warn && console.warn("The declarativeMarkup configuration option has been removed in MusicKit JS V3") + } + ))) + } + )) + } + if (ua) { + const e = function() { + function meta(e) { + if (Ke) + return; + const s = document.head.querySelector(`meta[name=${e}]`); + return (null == s ? void 0 : s.content) || void 0 + } + const e = meta("apple-music-developer-token") || meta("JWT") + , s = meta("apple-music-app-build") || meta("version") + , n = meta("apple-music-app-name") + , d = meta("apple-music-app-version"); + let h; + return (e || s || n || d) && (h = {}, + e && (h.developerToken = e), + (s || n || d) && (h.app = {}, + s && (h.app.build = s), + n && (h.app.name = n), + d && (h.app.version = d))), + h + }() + , s = /interactive|complete|loaded/.test(document.readyState); + e && e.developerToken && 0 === getInstances().length && (s ? asAsync(configure(e)) : document.addEventListener("DOMContentLoaded", ()=>configure(e))) + } + e.Events = ns, + e.MKError = MKError, + e.MediaItem = MediaItem, + e.MusicKitInstance = MusicKitInstance, + e.VideoTypes = { + movie: !0, + musicVideo: !0, + musicMovie: !0, + trailer: !0, + tvEpisode: !0, + uploadedVideo: !0, + "uploaded-videos": !0, + "music-videos": !0, + "music-movies": !0, + "tv-episodes": !0, + Episode: !0, + Movie: !0, + Show: !0, + Vod: !0, + EditorialVideoClip: !0, + RealityVideo: !0 + }, + e.__dev = I, + e.configure = configure, + e.enableMultipleInstances = function() { + ha = !0 + } + , + e.errors = wa, + e.formatArtworkURL = formatArtworkURL, + e.formatMediaTime = function(e, s=":") { + const {hours: n, minutes: d} = formattedSeconds(e); + e = Math.floor(e % 3600 % 60); + const h = []; + return n ? (h.push("" + n), + h.push(d < 10 ? "0" + d : "" + d)) : h.push("" + d), + h.push(e < 10 ? "0" + e : "" + e), + h.join(s) + } + , + e.formattedMediaURL = formattedMediaURL, + e.formattedMilliseconds = function(e) { + return formattedSeconds(e / 1e3) + } + , + e.formattedSeconds = formattedSeconds, + e.generateEmbedCode = function(e, s={ + height: "450", + width: "660" + }) { + var n, d; + if (!Sa.test(e)) + throw new Error("Invalid content url"); + let h = null !== (n = s.height) && void 0 !== n ? n : "450" + , p = null !== (d = s.width) && void 0 !== d ? d : "660"; + const {kind: y, isUTS: m} = formattedMediaURL(e); + "song" === y ? h = "150" : "episode" === y ? h = "175" : "post" === y && (h = "" + Math.round(.5625 * parseInt(p, 10))), + h = ("" + h).replace(/(\d+)px/i, "$1"), + p = ("" + p).replace(/^(\d+)(?!px)%?$/i, "$1px"); + const g = `width:100%;${p ? "max-width:" + p : ""};overflow:hidden;background:transparent;`; + let v = "https://embed.music.apple.com"; + ["podcast", "episode"].includes(y) && !m && (v = "https://embed.podcasts.apple.com"); + const _ = Aa.get() || v; + return `` + } + , + e.getHlsJsCdnConfig = getHlsJsCdnConfig, + e.getInstance = function(e) { + if (0 !== pa.length) + return void 0 === e ? pa[pa.length - 1] : pa.find(s=>s.id === e) + } + , + e.getInstances = getInstances, + e.getPlayerType = getPlayerType, + e.prepareMediaAPIItem = prepareMediaAPIItem, + e.resolveCanonical = function(e) { + return __awaiter(this, void 0, void 0, (function*() { + return { + results: { + links: yield filterLinks(e) + }, + meta: { + originalUrl: e, + originalQueryParams: parseQueryParams(e) + } + } + } + )) + } + , + Object.defineProperty(e, "__esModule", { + value: !0 + }) +} +)); diff --git a/resources/cider-ui-tests/style.less b/resources/cider-ui-tests/style.less index f99e8f66..26e89849 100644 --- a/resources/cider-ui-tests/style.less +++ b/resources/cider-ui-tests/style.less @@ -2400,4 +2400,8 @@ div#captions { .item-navigate:hover { text-decoration: underline; -} \ No newline at end of file +} + +apple-music-video-player{ + position:relative; + z-index:10000} \ No newline at end of file diff --git a/resources/cider-ui-tests/views/main.ejs b/resources/cider-ui-tests/views/main.ejs index c1fe50d2..0066ec71 100644 --- a/resources/cider-ui-tests/views/main.ejs +++ b/resources/cider-ui-tests/views/main.ejs @@ -381,8 +381,9 @@ <%- include("svg/fullscreen.svg") %> -
+
+ <%- include("components/mediaitem-artwork"); %> @@ -501,7 +502,7 @@ - + \ No newline at end of file