diff --git "a/hls.min.js" "b/hls.min.js" --- "a/hls.min.js" +++ "b/hls.min.js" @@ -1,36941 +1 @@ -!(function (e, t) { - "object" == typeof exports && "object" == typeof module - ? (module.exports = t()) - : "function" == typeof define && define.amd - ? define([], t) - : "object" == typeof exports - ? (exports.Hls = t()) - : (e.Hls = t()); -})(this, () => - (() => { - var e = { - 415: (e) => { - "use strict"; - var t, - r = "object" == typeof Reflect ? Reflect : null, - i = - r && "function" == typeof r.apply - ? r.apply - : function (e, t, r) { - return Function.prototype.apply.call(e, t, r); - }; - t = - r && "function" == typeof r.ownKeys - ? r.ownKeys - : Object.getOwnPropertySymbols - ? function (e) { - return Object.getOwnPropertyNames(e).concat( - Object.getOwnPropertySymbols(e) - ); - } - : function (e) { - return Object.getOwnPropertyNames(e); - }; - var n = - Number.isNaN || - function (e) { - return e != e; - }; - function s() { - s.init.call(this); - } - (e.exports = s), - (e.exports.once = function (e, t) { - return new Promise(function (r, i) { - function n(r) { - e.removeListener(t, s), i(r); - } - function s() { - "function" == typeof e.removeListener && - e.removeListener("error", n), - r([].slice.call(arguments)); - } - p(e, t, s, { once: !0 }), - "error" !== t && - (function (e, t, r) { - "function" == typeof e.on && p(e, "error", t, r); - })(e, n, { once: !0 }); - }); - }), - (s.EventEmitter = s), - (s.prototype._events = void 0), - (s.prototype._eventsCount = 0), - (s.prototype._maxListeners = void 0); - var a = 10; - function o(e) { - if ("function" != typeof e) - throw new TypeError( - 'The "listener" argument must be of type Function. Received type ' + - typeof e - ); - } - function l(e) { - return void 0 === e._maxListeners - ? s.defaultMaxListeners - : e._maxListeners; - } - function h(e, t, r, i) { - var n, s, a, h; - if ( - (o(r), - void 0 === (s = e._events) - ? ((s = e._events = Object.create(null)), (e._eventsCount = 0)) - : (void 0 !== s.newListener && - (e.emit("newListener", t, r.listener ? r.listener : r), - (s = e._events)), - (a = s[t])), - void 0 === a) - ) - (a = s[t] = r), ++e._eventsCount; - else if ( - ("function" == typeof a - ? (a = s[t] = i ? [r, a] : [a, r]) - : i - ? a.unshift(r) - : a.push(r), - (n = l(e)) > 0 && a.length > n && !a.warned) - ) { - a.warned = !0; - var u = new Error( - "Possible EventEmitter memory leak detected. " + - a.length + - " " + - String(t) + - " listeners added. Use emitter.setMaxListeners() to increase limit" - ); - (u.name = "MaxListenersExceededWarning"), - (u.emitter = e), - (u.type = t), - (u.count = a.length), - (h = u), - console && console.warn && console.warn(h); - } - return e; - } - function u() { - if (!this.fired) - return ( - this.target.removeListener(this.type, this.wrapFn), - (this.fired = !0), - 0 === arguments.length - ? this.listener.call(this.target) - : this.listener.apply(this.target, arguments) - ); - } - function d(e, t, r) { - var i = { - fired: !1, - wrapFn: void 0, - target: e, - type: t, - listener: r, - }, - n = u.bind(i); - return (n.listener = r), (i.wrapFn = n), n; - } - function c(e, t, r) { - var i = e._events; - if (void 0 === i) return []; - var n = i[t]; - return void 0 === n - ? [] - : "function" == typeof n - ? r - ? [n.listener || n] - : [n] - : r - ? (function (e) { - for (var t = new Array(e.length), r = 0; r < t.length; ++r) - t[r] = e[r].listener || e[r]; - return t; - })(n) - : g(n, n.length); - } - function f(e) { - var t = this._events; - if (void 0 !== t) { - var r = t[e]; - if ("function" == typeof r) return 1; - if (void 0 !== r) return r.length; - } - return 0; - } - function g(e, t) { - for (var r = new Array(t), i = 0; i < t; ++i) r[i] = e[i]; - return r; - } - function p(e, t, r, i) { - if ("function" == typeof e.on) i.once ? e.once(t, r) : e.on(t, r); - else { - if ("function" != typeof e.addEventListener) - throw new TypeError( - 'The "emitter" argument must be of type EventEmitter. Received type ' + - typeof e - ); - e.addEventListener(t, function n(s) { - i.once && e.removeEventListener(t, n), r(s); - }); - } - } - Object.defineProperty(s, "defaultMaxListeners", { - enumerable: !0, - get: function () { - return a; - }, - set: function (e) { - if ("number" != typeof e || e < 0 || n(e)) - throw new RangeError( - 'The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + - e + - "." - ); - a = e; - }, - }), - (s.init = function () { - (void 0 !== this._events && - this._events !== Object.getPrototypeOf(this)._events) || - ((this._events = Object.create(null)), (this._eventsCount = 0)), - (this._maxListeners = this._maxListeners || void 0); - }), - (s.prototype.setMaxListeners = function (e) { - if ("number" != typeof e || e < 0 || n(e)) - throw new RangeError( - 'The value of "n" is out of range. It must be a non-negative number. Received ' + - e + - "." - ); - return (this._maxListeners = e), this; - }), - (s.prototype.getMaxListeners = function () { - return l(this); - }), - (s.prototype.emit = function (e) { - for (var t = [], r = 1; r < arguments.length; r++) - t.push(arguments[r]); - var n = "error" === e, - s = this._events; - if (void 0 !== s) n = n && void 0 === s.error; - else if (!n) return !1; - if (n) { - var a; - if ((t.length > 0 && (a = t[0]), a instanceof Error)) throw a; - var o = new Error( - "Unhandled error." + (a ? " (" + a.message + ")" : "") - ); - throw ((o.context = a), o); - } - var l = s[e]; - if (void 0 === l) return !1; - if ("function" == typeof l) i(l, this, t); - else { - var h = l.length, - u = g(l, h); - for (r = 0; r < h; ++r) i(u[r], this, t); - } - return !0; - }), - (s.prototype.addListener = function (e, t) { - return h(this, e, t, !1); - }), - (s.prototype.on = s.prototype.addListener), - (s.prototype.prependListener = function (e, t) { - return h(this, e, t, !0); - }), - (s.prototype.once = function (e, t) { - return o(t), this.on(e, d(this, e, t)), this; - }), - (s.prototype.prependOnceListener = function (e, t) { - return o(t), this.prependListener(e, d(this, e, t)), this; - }), - (s.prototype.removeListener = function (e, t) { - var r, i, n, s, a; - if ((o(t), void 0 === (i = this._events))) return this; - if (void 0 === (r = i[e])) return this; - if (r === t || r.listener === t) - 0 == --this._eventsCount - ? (this._events = Object.create(null)) - : (delete i[e], - i.removeListener && - this.emit("removeListener", e, r.listener || t)); - else if ("function" != typeof r) { - for (n = -1, s = r.length - 1; s >= 0; s--) - if (r[s] === t || r[s].listener === t) { - (a = r[s].listener), (n = s); - break; - } - if (n < 0) return this; - 0 === n - ? r.shift() - : (function (e, t) { - for (; t + 1 < e.length; t++) e[t] = e[t + 1]; - e.pop(); - })(r, n), - 1 === r.length && (i[e] = r[0]), - void 0 !== i.removeListener && - this.emit("removeListener", e, a || t); - } - return this; - }), - (s.prototype.off = s.prototype.removeListener), - (s.prototype.removeAllListeners = function (e) { - var t, r, i; - if (void 0 === (r = this._events)) return this; - if (void 0 === r.removeListener) - return ( - 0 === arguments.length - ? ((this._events = Object.create(null)), - (this._eventsCount = 0)) - : void 0 !== r[e] && - (0 == --this._eventsCount - ? (this._events = Object.create(null)) - : delete r[e]), - this - ); - if (0 === arguments.length) { - var n, - s = Object.keys(r); - for (i = 0; i < s.length; ++i) - "removeListener" !== (n = s[i]) && this.removeAllListeners(n); - return ( - this.removeAllListeners("removeListener"), - (this._events = Object.create(null)), - (this._eventsCount = 0), - this - ); - } - if ("function" == typeof (t = r[e])) this.removeListener(e, t); - else if (void 0 !== t) - for (i = t.length - 1; i >= 0; i--) - this.removeListener(e, t[i]); - return this; - }), - (s.prototype.listeners = function (e) { - return c(this, e, !0); - }), - (s.prototype.rawListeners = function (e) { - return c(this, e, !1); - }), - (s.listenerCount = function (e, t) { - return "function" == typeof e.listenerCount - ? e.listenerCount(t) - : f.call(e, t); - }), - (s.prototype.listenerCount = f), - (s.prototype.eventNames = function () { - return this._eventsCount > 0 ? t(this._events) : []; - }); - }, - 558: function (e) { - !(function (t) { - var r = - /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/, - i = /^(?=([^\/?#]*))\1([^]*)$/, - n = /(?:\/|^)\.(?=\/)/g, - s = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g, - a = { - buildAbsoluteURL: function (e, t, r) { - if (((r = r || {}), (e = e.trim()), !(t = t.trim()))) { - if (!r.alwaysNormalize) return e; - var n = a.parseURL(e); - if (!n) throw new Error("Error trying to parse base URL."); - return ( - (n.path = a.normalizePath(n.path)), a.buildURLFromParts(n) - ); - } - var s = a.parseURL(t); - if (!s) - throw new Error("Error trying to parse relative URL."); - if (s.scheme) - return r.alwaysNormalize - ? ((s.path = a.normalizePath(s.path)), - a.buildURLFromParts(s)) - : t; - var o = a.parseURL(e); - if (!o) throw new Error("Error trying to parse base URL."); - if (!o.netLoc && o.path && "/" !== o.path[0]) { - var l = i.exec(o.path); - (o.netLoc = l[1]), (o.path = l[2]); - } - o.netLoc && !o.path && (o.path = "/"); - var h = { - scheme: o.scheme, - netLoc: s.netLoc, - path: null, - params: s.params, - query: s.query, - fragment: s.fragment, - }; - if (!s.netLoc && ((h.netLoc = o.netLoc), "/" !== s.path[0])) - if (s.path) { - var u = o.path, - d = u.substring(0, u.lastIndexOf("/") + 1) + s.path; - h.path = a.normalizePath(d); - } else - (h.path = o.path), - s.params || - ((h.params = o.params), - s.query || (h.query = o.query)); - return ( - null === h.path && - (h.path = r.alwaysNormalize - ? a.normalizePath(s.path) - : s.path), - a.buildURLFromParts(h) - ); - }, - parseURL: function (e) { - var t = r.exec(e); - return t - ? { - scheme: t[1] || "", - netLoc: t[2] || "", - path: t[3] || "", - params: t[4] || "", - query: t[5] || "", - fragment: t[6] || "", - } - : null; - }, - normalizePath: function (e) { - for ( - e = e.split("").reverse().join("").replace(n, ""); - e.length !== (e = e.replace(s, "")).length; - - ); - return e.split("").reverse().join(""); - }, - buildURLFromParts: function (e) { - return ( - e.scheme + - e.netLoc + - e.path + - e.params + - e.query + - e.fragment - ); - }, - }; - e.exports = a; - })(); - }, - 251: (e) => { - !(function t(r) { - var i; - (i = function () { - "use strict"; - function e(e, t) { - var r = Object.keys(e); - if (Object.getOwnPropertySymbols) { - var i = Object.getOwnPropertySymbols(e); - t && - (i = i.filter(function (t) { - return Object.getOwnPropertyDescriptor(e, t).enumerable; - })), - r.push.apply(r, i); - } - return r; - } - function i(t) { - for (var r = 1; r < arguments.length; r++) { - var i = null != arguments[r] ? arguments[r] : {}; - r % 2 - ? e(Object(i), !0).forEach(function (e) { - var r, s, a; - (r = t), - (s = e), - (a = i[e]), - (s = n(s)) in r - ? Object.defineProperty(r, s, { - value: a, - enumerable: !0, - configurable: !0, - writable: !0, - }) - : (r[s] = a); - }) - : Object.getOwnPropertyDescriptors - ? Object.defineProperties( - t, - Object.getOwnPropertyDescriptors(i) - ) - : e(Object(i)).forEach(function (e) { - Object.defineProperty( - t, - e, - Object.getOwnPropertyDescriptor(i, e) - ); - }); - } - return t; - } - function n(e) { - var t = (function (e, t) { - if ("object" != typeof e || !e) return e; - var r = e[Symbol.toPrimitive]; - if (void 0 !== r) { - var i = r.call(e, "string"); - if ("object" != typeof i) return i; - throw new TypeError( - "@@toPrimitive must return a primitive value." - ); - } - return String(e); - })(e); - return "symbol" == typeof t ? t : String(t); - } - function s(e, t) { - for (var r = 0; r < t.length; r++) { - var i = t[r]; - (i.enumerable = i.enumerable || !1), - (i.configurable = !0), - "value" in i && (i.writable = !0), - Object.defineProperty(e, n(i.key), i); - } - } - function a(e, t, r) { - return ( - t && s(e.prototype, t), - r && s(e, r), - Object.defineProperty(e, "prototype", { writable: !1 }), - e - ); - } - function o() { - return ( - (o = Object.assign - ? Object.assign.bind() - : function (e) { - for (var t = 1; t < arguments.length; t++) { - var r = arguments[t]; - for (var i in r) - Object.prototype.hasOwnProperty.call(r, i) && - (e[i] = r[i]); - } - return e; - }), - o.apply(this, arguments) - ); - } - function l(e, t) { - (e.prototype = Object.create(t.prototype)), - (e.prototype.constructor = e), - u(e, t); - } - function h(e) { - return ( - (h = Object.setPrototypeOf - ? Object.getPrototypeOf.bind() - : function (e) { - return e.__proto__ || Object.getPrototypeOf(e); - }), - h(e) - ); - } - function u(e, t) { - return ( - (u = Object.setPrototypeOf - ? Object.setPrototypeOf.bind() - : function (e, t) { - return (e.__proto__ = t), e; - }), - u(e, t) - ); - } - function d(e, t, r) { - return ( - (d = (function () { - if ("undefined" == typeof Reflect || !Reflect.construct) - return !1; - if (Reflect.construct.sham) return !1; - if ("function" == typeof Proxy) return !0; - try { - return ( - Boolean.prototype.valueOf.call( - Reflect.construct(Boolean, [], function () {}) - ), - !0 - ); - } catch (e) { - return !1; - } - })() - ? Reflect.construct.bind() - : function (e, t, r) { - var i = [null]; - i.push.apply(i, t); - var n = new (Function.bind.apply(e, i))(); - return r && u(n, r.prototype), n; - }), - d.apply(null, arguments) - ); - } - function c(e) { - var t = "function" == typeof Map ? new Map() : void 0; - return ( - (c = function (e) { - if ( - null === e || - !(function (e) { - try { - return ( - -1 !== - Function.toString.call(e).indexOf("[native code]") - ); - } catch (t) { - return "function" == typeof e; - } - })(e) - ) - return e; - if ("function" != typeof e) - throw new TypeError( - "Super expression must either be null or a function" - ); - if (void 0 !== t) { - if (t.has(e)) return t.get(e); - t.set(e, r); - } - function r() { - return d(e, arguments, h(this).constructor); - } - return ( - (r.prototype = Object.create(e.prototype, { - constructor: { - value: r, - enumerable: !1, - writable: !0, - configurable: !0, - }, - })), - u(r, e) - ); - }), - c(e) - ); - } - function f(e, t) { - (null == t || t > e.length) && (t = e.length); - for (var r = 0, i = new Array(t); r < t; r++) i[r] = e[r]; - return i; - } - var g = { exports: {} }; - !(function (e, t) { - var r, i, n, s, a; - (r = - /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/), - (i = /^(?=([^\/?#]*))\1([^]*)$/), - (n = /(?:\/|^)\.(?=\/)/g), - (s = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g), - (a = { - buildAbsoluteURL: function (e, t, r) { - if (((r = r || {}), (e = e.trim()), !(t = t.trim()))) { - if (!r.alwaysNormalize) return e; - var n = a.parseURL(e); - if (!n) - throw new Error("Error trying to parse base URL."); - return ( - (n.path = a.normalizePath(n.path)), - a.buildURLFromParts(n) - ); - } - var s = a.parseURL(t); - if (!s) - throw new Error("Error trying to parse relative URL."); - if (s.scheme) - return r.alwaysNormalize - ? ((s.path = a.normalizePath(s.path)), - a.buildURLFromParts(s)) - : t; - var o = a.parseURL(e); - if (!o) - throw new Error("Error trying to parse base URL."); - if (!o.netLoc && o.path && "/" !== o.path[0]) { - var l = i.exec(o.path); - (o.netLoc = l[1]), (o.path = l[2]); - } - o.netLoc && !o.path && (o.path = "/"); - var h = { - scheme: o.scheme, - netLoc: s.netLoc, - path: null, - params: s.params, - query: s.query, - fragment: s.fragment, - }; - if ( - !s.netLoc && - ((h.netLoc = o.netLoc), "/" !== s.path[0]) - ) - if (s.path) { - var u = o.path, - d = u.substring(0, u.lastIndexOf("/") + 1) + s.path; - h.path = a.normalizePath(d); - } else - (h.path = o.path), - s.params || - ((h.params = o.params), - s.query || (h.query = o.query)); - return ( - null === h.path && - (h.path = r.alwaysNormalize - ? a.normalizePath(s.path) - : s.path), - a.buildURLFromParts(h) - ); - }, - parseURL: function (e) { - var t = r.exec(e); - return t - ? { - scheme: t[1] || "", - netLoc: t[2] || "", - path: t[3] || "", - params: t[4] || "", - query: t[5] || "", - fragment: t[6] || "", - } - : null; - }, - normalizePath: function (e) { - for ( - e = e.split("").reverse().join("").replace(n, ""); - e.length !== (e = e.replace(s, "")).length; - - ); - return e.split("").reverse().join(""); - }, - buildURLFromParts: function (e) { - return ( - e.scheme + - e.netLoc + - e.path + - e.params + - e.query + - e.fragment - ); - }, - }), - (e.exports = a); - })(g); - var p = g.exports, - m = - Number.isFinite || - function (e) { - return "number" == typeof e && isFinite(e); - }, - v = - Number.isSafeInteger || - function (e) { - return "number" == typeof e && Math.abs(e) <= y; - }, - y = Number.MAX_SAFE_INTEGER || 9007199254740991, - E = (function (e) { - return ( - (e.MEDIA_ATTACHING = "hlsMediaAttaching"), - (e.MEDIA_ATTACHED = "hlsMediaAttached"), - (e.MEDIA_DETACHING = "hlsMediaDetaching"), - (e.MEDIA_DETACHED = "hlsMediaDetached"), - (e.BUFFER_RESET = "hlsBufferReset"), - (e.BUFFER_CODECS = "hlsBufferCodecs"), - (e.BUFFER_CREATED = "hlsBufferCreated"), - (e.BUFFER_APPENDING = "hlsBufferAppending"), - (e.BUFFER_APPENDED = "hlsBufferAppended"), - (e.BUFFER_EOS = "hlsBufferEos"), - (e.BUFFER_FLUSHING = "hlsBufferFlushing"), - (e.BUFFER_FLUSHED = "hlsBufferFlushed"), - (e.MANIFEST_LOADING = "hlsManifestLoading"), - (e.MANIFEST_LOADED = "hlsManifestLoaded"), - (e.MANIFEST_PARSED = "hlsManifestParsed"), - (e.LEVEL_SWITCHING = "hlsLevelSwitching"), - (e.LEVEL_SWITCHED = "hlsLevelSwitched"), - (e.LEVEL_LOADING = "hlsLevelLoading"), - (e.LEVEL_LOADED = "hlsLevelLoaded"), - (e.LEVEL_UPDATED = "hlsLevelUpdated"), - (e.LEVEL_PTS_UPDATED = "hlsLevelPtsUpdated"), - (e.LEVELS_UPDATED = "hlsLevelsUpdated"), - (e.AUDIO_TRACKS_UPDATED = "hlsAudioTracksUpdated"), - (e.AUDIO_TRACK_SWITCHING = "hlsAudioTrackSwitching"), - (e.AUDIO_TRACK_SWITCHED = "hlsAudioTrackSwitched"), - (e.AUDIO_TRACK_LOADING = "hlsAudioTrackLoading"), - (e.AUDIO_TRACK_LOADED = "hlsAudioTrackLoaded"), - (e.SUBTITLE_TRACKS_UPDATED = "hlsSubtitleTracksUpdated"), - (e.SUBTITLE_TRACKS_CLEARED = "hlsSubtitleTracksCleared"), - (e.SUBTITLE_TRACK_SWITCH = "hlsSubtitleTrackSwitch"), - (e.SUBTITLE_TRACK_LOADING = "hlsSubtitleTrackLoading"), - (e.SUBTITLE_TRACK_LOADED = "hlsSubtitleTrackLoaded"), - (e.SUBTITLE_FRAG_PROCESSED = "hlsSubtitleFragProcessed"), - (e.CUES_PARSED = "hlsCuesParsed"), - (e.NON_NATIVE_TEXT_TRACKS_FOUND = - "hlsNonNativeTextTracksFound"), - (e.INIT_PTS_FOUND = "hlsInitPtsFound"), - (e.FRAG_LOADING = "hlsFragLoading"), - (e.FRAG_LOAD_EMERGENCY_ABORTED = - "hlsFragLoadEmergencyAborted"), - (e.FRAG_LOADED = "hlsFragLoaded"), - (e.FRAG_DECRYPTED = "hlsFragDecrypted"), - (e.FRAG_PARSING_INIT_SEGMENT = "hlsFragParsingInitSegment"), - (e.FRAG_PARSING_USERDATA = "hlsFragParsingUserdata"), - (e.FRAG_PARSING_METADATA = "hlsFragParsingMetadata"), - (e.FRAG_PARSED = "hlsFragParsed"), - (e.FRAG_BUFFERED = "hlsFragBuffered"), - (e.FRAG_CHANGED = "hlsFragChanged"), - (e.FPS_DROP = "hlsFpsDrop"), - (e.FPS_DROP_LEVEL_CAPPING = "hlsFpsDropLevelCapping"), - (e.MAX_AUTO_LEVEL_UPDATED = "hlsMaxAutoLevelUpdated"), - (e.ERROR = "hlsError"), - (e.DESTROYING = "hlsDestroying"), - (e.KEY_LOADING = "hlsKeyLoading"), - (e.KEY_LOADED = "hlsKeyLoaded"), - (e.LIVE_BACK_BUFFER_REACHED = "hlsLiveBackBufferReached"), - (e.BACK_BUFFER_REACHED = "hlsBackBufferReached"), - (e.STEERING_MANIFEST_LOADED = "hlsSteeringManifestLoaded"), - e - ); - })({}), - S = (function (e) { - return ( - (e.NETWORK_ERROR = "networkError"), - (e.MEDIA_ERROR = "mediaError"), - (e.KEY_SYSTEM_ERROR = "keySystemError"), - (e.MUX_ERROR = "muxError"), - (e.OTHER_ERROR = "otherError"), - e - ); - })({}), - T = (function (e) { - return ( - (e.KEY_SYSTEM_NO_KEYS = "keySystemNoKeys"), - (e.KEY_SYSTEM_NO_ACCESS = "keySystemNoAccess"), - (e.KEY_SYSTEM_NO_SESSION = "keySystemNoSession"), - (e.KEY_SYSTEM_NO_CONFIGURED_LICENSE = - "keySystemNoConfiguredLicense"), - (e.KEY_SYSTEM_LICENSE_REQUEST_FAILED = - "keySystemLicenseRequestFailed"), - (e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED = - "keySystemServerCertificateRequestFailed"), - (e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED = - "keySystemServerCertificateUpdateFailed"), - (e.KEY_SYSTEM_SESSION_UPDATE_FAILED = - "keySystemSessionUpdateFailed"), - (e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED = - "keySystemStatusOutputRestricted"), - (e.KEY_SYSTEM_STATUS_INTERNAL_ERROR = - "keySystemStatusInternalError"), - (e.MANIFEST_LOAD_ERROR = "manifestLoadError"), - (e.MANIFEST_LOAD_TIMEOUT = "manifestLoadTimeOut"), - (e.MANIFEST_PARSING_ERROR = "manifestParsingError"), - (e.MANIFEST_INCOMPATIBLE_CODECS_ERROR = - "manifestIncompatibleCodecsError"), - (e.LEVEL_EMPTY_ERROR = "levelEmptyError"), - (e.LEVEL_LOAD_ERROR = "levelLoadError"), - (e.LEVEL_LOAD_TIMEOUT = "levelLoadTimeOut"), - (e.LEVEL_PARSING_ERROR = "levelParsingError"), - (e.LEVEL_SWITCH_ERROR = "levelSwitchError"), - (e.AUDIO_TRACK_LOAD_ERROR = "audioTrackLoadError"), - (e.AUDIO_TRACK_LOAD_TIMEOUT = "audioTrackLoadTimeOut"), - (e.SUBTITLE_LOAD_ERROR = "subtitleTrackLoadError"), - (e.SUBTITLE_TRACK_LOAD_TIMEOUT = - "subtitleTrackLoadTimeOut"), - (e.FRAG_LOAD_ERROR = "fragLoadError"), - (e.FRAG_LOAD_TIMEOUT = "fragLoadTimeOut"), - (e.FRAG_DECRYPT_ERROR = "fragDecryptError"), - (e.FRAG_PARSING_ERROR = "fragParsingError"), - (e.FRAG_GAP = "fragGap"), - (e.REMUX_ALLOC_ERROR = "remuxAllocError"), - (e.KEY_LOAD_ERROR = "keyLoadError"), - (e.KEY_LOAD_TIMEOUT = "keyLoadTimeOut"), - (e.BUFFER_ADD_CODEC_ERROR = "bufferAddCodecError"), - (e.BUFFER_INCOMPATIBLE_CODECS_ERROR = - "bufferIncompatibleCodecsError"), - (e.BUFFER_APPEND_ERROR = "bufferAppendError"), - (e.BUFFER_APPENDING_ERROR = "bufferAppendingError"), - (e.BUFFER_STALLED_ERROR = "bufferStalledError"), - (e.BUFFER_FULL_ERROR = "bufferFullError"), - (e.BUFFER_SEEK_OVER_HOLE = "bufferSeekOverHole"), - (e.BUFFER_NUDGE_ON_STALL = "bufferNudgeOnStall"), - (e.INTERNAL_EXCEPTION = "internalException"), - (e.INTERNAL_ABORTED = "aborted"), - (e.UNKNOWN = "unknown"), - e - ); - })({}), - _ = function () {}, - L = { trace: _, debug: _, log: _, warn: _, info: _, error: _ }, - b = L; - function R(e, t) { - if ( - ("object" == typeof console && !0 === e) || - "object" == typeof e - ) { - !(function (e) { - for ( - var t = arguments.length, - r = new Array(t > 1 ? t - 1 : 0), - i = 1; - i < t; - i++ - ) - r[i - 1] = arguments[i]; - r.forEach(function (t) { - b[t] = e[t] - ? e[t].bind(e) - : (function (e) { - var t = self.console[e]; - return t - ? t.bind(self.console, "[" + e + "] >") - : _; - })(t); - }); - })(e, "debug", "log", "info", "warn", "error"); - try { - b.log( - 'Debug logs enabled for "' + - t + - '" in hls.js version 1.5.13' - ); - } catch (e) { - b = L; - } - } else b = L; - } - var A = b, - w = /^(\d+)x(\d+)$/, - P = /(.+?)=(".*?"|.*?)(?:,|$)/g, - I = (function () { - function e(t) { - "string" == typeof t && (t = e.parseAttrList(t)), - o(this, t); - } - var t = e.prototype; - return ( - (t.decimalInteger = function (e) { - var t = parseInt(this[e], 10); - return t > Number.MAX_SAFE_INTEGER ? 1 / 0 : t; - }), - (t.hexadecimalInteger = function (e) { - if (this[e]) { - var t = (this[e] || "0x").slice(2); - t = (1 & t.length ? "0" : "") + t; - for ( - var r = new Uint8Array(t.length / 2), i = 0; - i < t.length / 2; - i++ - ) - r[i] = parseInt(t.slice(2 * i, 2 * i + 2), 16); - return r; - } - return null; - }), - (t.hexadecimalIntegerAsNumber = function (e) { - var t = parseInt(this[e], 16); - return t > Number.MAX_SAFE_INTEGER ? 1 / 0 : t; - }), - (t.decimalFloatingPoint = function (e) { - return parseFloat(this[e]); - }), - (t.optionalFloat = function (e, t) { - var r = this[e]; - return r ? parseFloat(r) : t; - }), - (t.enumeratedString = function (e) { - return this[e]; - }), - (t.bool = function (e) { - return "YES" === this[e]; - }), - (t.decimalResolution = function (e) { - var t = w.exec(this[e]); - if (null !== t) - return { - width: parseInt(t[1], 10), - height: parseInt(t[2], 10), - }; - }), - (e.parseAttrList = function (e) { - var t, - r = {}; - for (P.lastIndex = 0; null !== (t = P.exec(e)); ) { - var i = t[2]; - 0 === i.indexOf('"') && - i.lastIndexOf('"') === i.length - 1 && - (i = i.slice(1, -1)), - (r[t[1].trim()] = i); - } - return r; - }), - a(e, [ - { - key: "clientAttrs", - get: function () { - return Object.keys(this).filter(function (e) { - return "X-" === e.substring(0, 2); - }); - }, - }, - ]), - e - ); - })(); - function C(e) { - return "SCTE35-OUT" === e || "SCTE35-IN" === e; - } - var k = (function () { - function e(e, t) { - if ( - ((this.attr = void 0), - (this._startDate = void 0), - (this._endDate = void 0), - (this._badValueForSameId = void 0), - t) - ) { - var r = t.attr; - for (var i in r) - if ( - Object.prototype.hasOwnProperty.call(e, i) && - e[i] !== r[i] - ) { - A.warn( - 'DATERANGE tag attribute: "' + - i + - '" does not match for tags with ID: "' + - e.ID + - '"' - ), - (this._badValueForSameId = i); - break; - } - e = o(new I({}), r, e); - } - if ( - ((this.attr = e), - (this._startDate = new Date(e["START-DATE"])), - "END-DATE" in this.attr) - ) { - var n = new Date(this.attr["END-DATE"]); - m(n.getTime()) && (this._endDate = n); - } - } - return ( - a(e, [ - { - key: "id", - get: function () { - return this.attr.ID; - }, - }, - { - key: "class", - get: function () { - return this.attr.CLASS; - }, - }, - { - key: "startDate", - get: function () { - return this._startDate; - }, - }, - { - key: "endDate", - get: function () { - if (this._endDate) return this._endDate; - var e = this.duration; - return null !== e - ? new Date(this._startDate.getTime() + 1e3 * e) - : null; - }, - }, - { - key: "duration", - get: function () { - if ("DURATION" in this.attr) { - var e = this.attr.decimalFloatingPoint("DURATION"); - if (m(e)) return e; - } else if (this._endDate) - return ( - (this._endDate.getTime() - - this._startDate.getTime()) / - 1e3 - ); - return null; - }, - }, - { - key: "plannedDuration", - get: function () { - return "PLANNED-DURATION" in this.attr - ? this.attr.decimalFloatingPoint("PLANNED-DURATION") - : null; - }, - }, - { - key: "endOnNext", - get: function () { - return this.attr.bool("END-ON-NEXT"); - }, - }, - { - key: "isValid", - get: function () { - return ( - !!this.id && - !this._badValueForSameId && - m(this.startDate.getTime()) && - (null === this.duration || this.duration >= 0) && - (!this.endOnNext || !!this.class) - ); - }, - }, - ]), - e - ); - })(), - D = function () { - (this.aborted = !1), - (this.loaded = 0), - (this.retry = 0), - (this.total = 0), - (this.chunkCount = 0), - (this.bwEstimate = 0), - (this.loading = { start: 0, first: 0, end: 0 }), - (this.parsing = { start: 0, end: 0 }), - (this.buffering = { start: 0, first: 0, end: 0 }); - }, - M = "audio", - x = "video", - O = "audiovideo", - F = (function () { - function e(e) { - var t; - (this._byteRange = null), - (this._url = null), - (this.baseurl = void 0), - (this.relurl = void 0), - (this.elementaryStreams = - (((t = {})[M] = null), - (t[x] = null), - (t[O] = null), - t)), - (this.baseurl = e); - } - return ( - (e.prototype.setByteRange = function (e, t) { - var r, - i = e.split("@", 2); - (r = - 1 === i.length - ? (null == t ? void 0 : t.byteRangeEndOffset) || 0 - : parseInt(i[1])), - (this._byteRange = [r, parseInt(i[0]) + r]); - }), - a(e, [ - { - key: "byteRange", - get: function () { - return this._byteRange ? this._byteRange : []; - }, - }, - { - key: "byteRangeStartOffset", - get: function () { - return this.byteRange[0]; - }, - }, - { - key: "byteRangeEndOffset", - get: function () { - return this.byteRange[1]; - }, - }, - { - key: "url", - get: function () { - return ( - !this._url && - this.baseurl && - this.relurl && - (this._url = p.buildAbsoluteURL( - this.baseurl, - this.relurl, - { alwaysNormalize: !0 } - )), - this._url || "" - ); - }, - set: function (e) { - this._url = e; - }, - }, - ]), - e - ); - })(), - N = (function (e) { - function t(t, r) { - var i; - return ( - ((i = e.call(this, r) || this)._decryptdata = null), - (i.rawProgramDateTime = null), - (i.programDateTime = null), - (i.tagList = []), - (i.duration = 0), - (i.sn = 0), - (i.levelkeys = void 0), - (i.type = void 0), - (i.loader = null), - (i.keyLoader = null), - (i.level = -1), - (i.cc = 0), - (i.startPTS = void 0), - (i.endPTS = void 0), - (i.startDTS = void 0), - (i.endDTS = void 0), - (i.start = 0), - (i.deltaPTS = void 0), - (i.maxStartPTS = void 0), - (i.minEndPTS = void 0), - (i.stats = new D()), - (i.data = void 0), - (i.bitrateTest = !1), - (i.title = null), - (i.initSegment = null), - (i.endList = void 0), - (i.gap = void 0), - (i.urlId = 0), - (i.type = t), - i - ); - } - l(t, e); - var r = t.prototype; - return ( - (r.setKeyFormat = function (e) { - if (this.levelkeys) { - var t = this.levelkeys[e]; - t && - !this._decryptdata && - (this._decryptdata = t.getDecryptData(this.sn)); - } - }), - (r.abortRequests = function () { - var e, t; - null == (e = this.loader) || e.abort(), - null == (t = this.keyLoader) || t.abort(); - }), - (r.setElementaryStreamInfo = function (e, t, r, i, n, s) { - void 0 === s && (s = !1); - var a = this.elementaryStreams, - o = a[e]; - o - ? ((o.startPTS = Math.min(o.startPTS, t)), - (o.endPTS = Math.max(o.endPTS, r)), - (o.startDTS = Math.min(o.startDTS, i)), - (o.endDTS = Math.max(o.endDTS, n))) - : (a[e] = { - startPTS: t, - endPTS: r, - startDTS: i, - endDTS: n, - partial: s, - }); - }), - (r.clearElementaryStreamInfo = function () { - var e = this.elementaryStreams; - (e[M] = null), (e[x] = null), (e[O] = null); - }), - a(t, [ - { - key: "decryptdata", - get: function () { - if (!this.levelkeys && !this._decryptdata) - return null; - if ( - !this._decryptdata && - this.levelkeys && - !this.levelkeys.NONE - ) { - var e = this.levelkeys.identity; - if (e) - this._decryptdata = e.getDecryptData(this.sn); - else { - var t = Object.keys(this.levelkeys); - if (1 === t.length) - return (this._decryptdata = this.levelkeys[ - t[0] - ].getDecryptData(this.sn)); - } - } - return this._decryptdata; - }, - }, - { - key: "end", - get: function () { - return this.start + this.duration; - }, - }, - { - key: "endProgramDateTime", - get: function () { - if (null === this.programDateTime) return null; - if (!m(this.programDateTime)) return null; - var e = m(this.duration) ? this.duration : 0; - return this.programDateTime + 1e3 * e; - }, - }, - { - key: "encrypted", - get: function () { - var e; - if (null != (e = this._decryptdata) && e.encrypted) - return !0; - if (this.levelkeys) { - var t = Object.keys(this.levelkeys), - r = t.length; - if ( - r > 1 || - (1 === r && this.levelkeys[t[0]].encrypted) - ) - return !0; - } - return !1; - }, - }, - ]), - t - ); - })(F), - B = (function (e) { - function t(t, r, i, n, s) { - var a; - ((a = e.call(this, i) || this).fragOffset = 0), - (a.duration = 0), - (a.gap = !1), - (a.independent = !1), - (a.relurl = void 0), - (a.fragment = void 0), - (a.index = void 0), - (a.stats = new D()), - (a.duration = t.decimalFloatingPoint("DURATION")), - (a.gap = t.bool("GAP")), - (a.independent = t.bool("INDEPENDENT")), - (a.relurl = t.enumeratedString("URI")), - (a.fragment = r), - (a.index = n); - var o = t.enumeratedString("BYTERANGE"); - return ( - o && a.setByteRange(o, s), - s && (a.fragOffset = s.fragOffset + s.duration), - a - ); - } - return ( - l(t, e), - a(t, [ - { - key: "start", - get: function () { - return this.fragment.start + this.fragOffset; - }, - }, - { - key: "end", - get: function () { - return this.start + this.duration; - }, - }, - { - key: "loaded", - get: function () { - var e = this.elementaryStreams; - return !!(e.audio || e.video || e.audiovideo); - }, - }, - ]), - t - ); - })(F), - U = (function () { - function e(e) { - (this.PTSKnown = !1), - (this.alignedSliding = !1), - (this.averagetargetduration = void 0), - (this.endCC = 0), - (this.endSN = 0), - (this.fragments = void 0), - (this.fragmentHint = void 0), - (this.partList = null), - (this.dateRanges = void 0), - (this.live = !0), - (this.ageHeader = 0), - (this.advancedDateTime = void 0), - (this.updated = !0), - (this.advanced = !0), - (this.availabilityDelay = void 0), - (this.misses = 0), - (this.startCC = 0), - (this.startSN = 0), - (this.startTimeOffset = null), - (this.targetduration = 0), - (this.totalduration = 0), - (this.type = null), - (this.url = void 0), - (this.m3u8 = ""), - (this.version = null), - (this.canBlockReload = !1), - (this.canSkipUntil = 0), - (this.canSkipDateRanges = !1), - (this.skippedSegments = 0), - (this.recentlyRemovedDateranges = void 0), - (this.partHoldBack = 0), - (this.holdBack = 0), - (this.partTarget = 0), - (this.preloadHint = void 0), - (this.renditionReports = void 0), - (this.tuneInGoal = 0), - (this.deltaUpdateFailed = void 0), - (this.driftStartTime = 0), - (this.driftEndTime = 0), - (this.driftStart = 0), - (this.driftEnd = 0), - (this.encryptedFragments = void 0), - (this.playlistParsingError = null), - (this.variableList = null), - (this.hasVariableRefs = !1), - (this.fragments = []), - (this.encryptedFragments = []), - (this.dateRanges = {}), - (this.url = e); - } - return ( - (e.prototype.reloaded = function (e) { - if (!e) - return (this.advanced = !0), void (this.updated = !0); - var t = this.lastPartSn - e.lastPartSn, - r = this.lastPartIndex - e.lastPartIndex; - (this.updated = - this.endSN !== e.endSN || !!r || !!t || !this.live), - (this.advanced = - this.endSN > e.endSN || t > 0 || (0 === t && r > 0)), - this.updated || this.advanced - ? (this.misses = Math.floor(0.6 * e.misses)) - : (this.misses = e.misses + 1), - (this.availabilityDelay = e.availabilityDelay); - }), - a(e, [ - { - key: "hasProgramDateTime", - get: function () { - return ( - !!this.fragments.length && - m( - this.fragments[this.fragments.length - 1] - .programDateTime - ) - ); - }, - }, - { - key: "levelTargetDuration", - get: function () { - return ( - this.averagetargetduration || - this.targetduration || - 10 - ); - }, - }, - { - key: "drift", - get: function () { - var e = this.driftEndTime - this.driftStartTime; - return e > 0 - ? (1e3 * (this.driftEnd - this.driftStart)) / e - : 1; - }, - }, - { - key: "edge", - get: function () { - return this.partEnd || this.fragmentEnd; - }, - }, - { - key: "partEnd", - get: function () { - var e; - return null != (e = this.partList) && e.length - ? this.partList[this.partList.length - 1].end - : this.fragmentEnd; - }, - }, - { - key: "fragmentEnd", - get: function () { - var e; - return null != (e = this.fragments) && e.length - ? this.fragments[this.fragments.length - 1].end - : 0; - }, - }, - { - key: "age", - get: function () { - return this.advancedDateTime - ? Math.max(Date.now() - this.advancedDateTime, 0) / - 1e3 - : 0; - }, - }, - { - key: "lastPartIndex", - get: function () { - var e; - return null != (e = this.partList) && e.length - ? this.partList[this.partList.length - 1].index - : -1; - }, - }, - { - key: "lastPartSn", - get: function () { - var e; - return null != (e = this.partList) && e.length - ? this.partList[this.partList.length - 1].fragment - .sn - : this.endSN; - }, - }, - ]), - e - ); - })(); - function G(e) { - return Uint8Array.from(atob(e), function (e) { - return e.charCodeAt(0); - }); - } - function H(e) { - return Uint8Array.from( - unescape(encodeURIComponent(e)), - function (e) { - return e.charCodeAt(0); - } - ); - } - var $ = "undefined" != typeof self ? self : void 0, - K = { - CLEARKEY: "org.w3.clearkey", - FAIRPLAY: "com.apple.fps", - PLAYREADY: "com.microsoft.playready", - WIDEVINE: "com.widevine.alpha", - }, - W = "org.w3.clearkey", - V = "com.apple.streamingkeydelivery", - q = "com.microsoft.playready", - j = "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"; - function Y(e) { - switch (e) { - case V: - return K.FAIRPLAY; - case q: - return K.PLAYREADY; - case j: - return K.WIDEVINE; - case W: - return K.CLEARKEY; - } - } - var z = "edef8ba979d64acea3c827dcd51d21ed"; - function X(e) { - switch (e) { - case K.FAIRPLAY: - return V; - case K.PLAYREADY: - return q; - case K.WIDEVINE: - return j; - case K.CLEARKEY: - return W; - } - } - function Q(e) { - var t = e.drmSystems, - r = e.widevineLicenseUrl, - i = t - ? [K.FAIRPLAY, K.WIDEVINE, K.PLAYREADY, K.CLEARKEY].filter( - function (e) { - return !!t[e]; - } - ) - : []; - return !i[K.WIDEVINE] && r && i.push(K.WIDEVINE), i; - } - var J, - Z = - null != $ && - null != (J = $.navigator) && - J.requestMediaKeySystemAccess - ? self.navigator.requestMediaKeySystemAccess.bind( - self.navigator - ) - : null; - function ee(e, t, r) { - return Uint8Array.prototype.slice - ? e.slice(t, r) - : new Uint8Array(Array.prototype.slice.call(e, t, r)); - } - var te, - re = function (e, t) { - return ( - t + 10 <= e.length && - 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 - ); - }, - ie = function (e, t) { - return ( - t + 10 <= e.length && - 51 === e[t] && - 68 === e[t + 1] && - 73 === 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 - ); - }, - ne = function (e, t) { - for (var r = t, i = 0; re(e, t); ) - (i += 10), - (i += se(e, t + 6)), - ie(e, t + 10) && (i += 10), - (t += i); - if (i > 0) return e.subarray(r, r + i); - }, - se = function (e, t) { - var r = 0; - return ( - (r = (127 & e[t]) << 21), - (r |= (127 & e[t + 1]) << 14), - (r |= (127 & e[t + 2]) << 7) | (127 & e[t + 3]) - ); - }, - ae = function (e, t) { - return re(e, t) && se(e, t + 6) + 10 <= e.length - t; - }, - oe = function (e) { - for (var t = ue(e), r = 0; r < t.length; r++) { - var i = t[r]; - if (le(i)) return pe(i); - } - }, - le = function (e) { - return ( - e && - "PRIV" === e.key && - "com.apple.streaming.transportStreamTimestamp" === e.info - ); - }, - he = function (e) { - var t = String.fromCharCode(e[0], e[1], e[2], e[3]), - r = se(e, 4); - return { type: t, size: r, data: e.subarray(10, 10 + r) }; - }, - ue = function (e) { - for (var t = 0, r = []; re(e, t); ) { - for (var i = se(e, t + 6), n = (t += 10) + i; t + 8 < n; ) { - var s = he(e.subarray(t)), - a = de(s); - a && r.push(a), (t += s.size + 10); - } - ie(e, t) && (t += 10); - } - return r; - }, - de = function (e) { - return "PRIV" === e.type - ? ce(e) - : "W" === e.type[0] - ? ge(e) - : fe(e); - }, - ce = function (e) { - if (!(e.size < 2)) { - var t = me(e.data, !0), - r = new Uint8Array(e.data.subarray(t.length + 1)); - return { key: e.type, info: t, data: r.buffer }; - } - }, - fe = function (e) { - if (!(e.size < 2)) { - if ("TXXX" === e.type) { - var t = 1, - r = me(e.data.subarray(t), !0); - t += r.length + 1; - var i = me(e.data.subarray(t)); - return { key: e.type, info: r, data: i }; - } - var n = me(e.data.subarray(1)); - return { key: e.type, data: n }; - } - }, - ge = function (e) { - if ("WXXX" === e.type) { - if (e.size < 2) return; - var t = 1, - r = me(e.data.subarray(t), !0); - t += r.length + 1; - var i = me(e.data.subarray(t)); - return { key: e.type, info: r, data: i }; - } - var n = me(e.data); - return { key: e.type, data: n }; - }, - pe = function (e) { - if (8 === e.data.byteLength) { - var t = new Uint8Array(e.data), - r = 1 & t[3], - i = (t[4] << 23) + (t[5] << 15) + (t[6] << 7) + t[7]; - return (i /= 45), r && (i += 47721858.84), Math.round(i); - } - }, - me = function (e, t) { - void 0 === t && (t = !1); - var r = (function () { - if (!navigator.userAgent.includes("PlayStation 4")) - return ( - te || - void 0 === self.TextDecoder || - (te = new self.TextDecoder("utf-8")), - te - ); - })(); - if (r) { - var i = r.decode(e); - if (t) { - var n = i.indexOf("\0"); - return -1 !== n ? i.substring(0, n) : i; - } - return i.replace(/\0/g, ""); - } - for (var s, a, o, l = e.length, h = "", u = 0; u < l; ) { - if (0 === (s = e[u++]) && t) return h; - if (0 !== s && 3 !== s) - switch (s >> 4) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - h += String.fromCharCode(s); - break; - case 12: - case 13: - (a = e[u++]), - (h += String.fromCharCode( - ((31 & s) << 6) | (63 & a) - )); - break; - case 14: - (a = e[u++]), - (o = e[u++]), - (h += String.fromCharCode( - ((15 & s) << 12) | ((63 & a) << 6) | (63 & o) - )); - } - } - return h; - }; - var ve = function (e) { - for (var t = "", r = 0; r < e.length; r++) { - var i = e[r].toString(16); - i.length < 2 && (i = "0" + i), (t += i); - } - return t; - }, - ye = Math.pow(2, 32) - 1, - Ee = [].push, - Se = { video: 1, audio: 2, id3: 3, text: 4 }; - function Te(e) { - return String.fromCharCode.apply(null, e); - } - function _e(e, t) { - var r = (e[t] << 8) | e[t + 1]; - return r < 0 ? 65536 + r : r; - } - function Le(e, t) { - var r = Re(e, t); - return r < 0 ? 4294967296 + r : r; - } - function be(e, t) { - var r = Le(e, t); - return (r *= Math.pow(2, 32)) + Le(e, t + 4); - } - function Re(e, t) { - return ( - (e[t] << 24) | (e[t + 1] << 16) | (e[t + 2] << 8) | e[t + 3] - ); - } - function Ae(e, t, r) { - (e[t] = r >> 24), - (e[t + 1] = (r >> 16) & 255), - (e[t + 2] = (r >> 8) & 255), - (e[t + 3] = 255 & r); - } - function we(e, t) { - var r = []; - if (!t.length) return r; - for (var i = e.byteLength, n = 0; n < i; ) { - var s = Le(e, n), - a = s > 1 ? n + s : i; - if (Te(e.subarray(n + 4, n + 8)) === t[0]) - if (1 === t.length) r.push(e.subarray(n + 8, a)); - else { - var o = we(e.subarray(n + 8, a), t.slice(1)); - o.length && Ee.apply(r, o); - } - n = a; - } - return r; - } - function Pe(e) { - var t = [], - r = e[0], - i = 8, - n = Le(e, i); - i += 4; - var s = 0, - a = 0; - 0 === r - ? ((s = Le(e, i)), (a = Le(e, i + 4)), (i += 8)) - : ((s = be(e, i)), (a = be(e, i + 8)), (i += 16)), - (i += 2); - var o = e.length + a, - l = _e(e, i); - i += 2; - for (var h = 0; h < l; h++) { - var u = i, - d = Le(e, u); - u += 4; - var c = 2147483647 & d; - if (1 == (2147483648 & d) >>> 31) - return ( - A.warn( - "SIDX has hierarchical references (not supported)" - ), - null - ); - var f = Le(e, u); - (u += 4), - t.push({ - referenceSize: c, - subsegmentDuration: f, - info: { duration: f / n, start: o, end: o + c - 1 }, - }), - (o += c), - (i = u += 4); - } - return { - earliestPresentationTime: s, - timescale: n, - version: r, - referencesCount: l, - references: t, - }; - } - function Ie(e) { - for ( - var t = [], r = we(e, ["moov", "trak"]), n = 0; - n < r.length; - n++ - ) { - var s = r[n], - a = we(s, ["tkhd"])[0]; - if (a) { - var o = a[0], - l = Le(a, 0 === o ? 12 : 20), - h = we(s, ["mdia", "mdhd"])[0]; - if (h) { - var u = Le(h, 0 === (o = h[0]) ? 12 : 20), - d = we(s, ["mdia", "hdlr"])[0]; - if (d) { - var c = Te(d.subarray(8, 12)), - f = { soun: M, vide: x }[c]; - if (f) { - var g = Ce( - we(s, ["mdia", "minf", "stbl", "stsd"])[0] - ); - (t[l] = { timescale: u, type: f }), - (t[f] = i({ timescale: u, id: l }, g)); - } - } - } - } - } - return ( - we(e, ["moov", "mvex", "trex"]).forEach(function (e) { - var r = Le(e, 4), - i = t[r]; - i && - (i.default = { duration: Le(e, 12), flags: Le(e, 20) }); - }), - t - ); - } - function Ce(e) { - var t = e.subarray(8), - r = t.subarray(86), - i = Te(t.subarray(4, 8)), - n = i, - s = "enca" === i || "encv" === i; - if (s) { - var a = we(t, [i])[0]; - we(a.subarray("enca" === i ? 28 : 78), ["sinf"]).forEach( - function (e) { - var t = we(e, ["schm"])[0]; - if (t) { - var r = Te(t.subarray(4, 8)); - if ("cbcs" === r || "cenc" === r) { - var i = we(e, ["frma"])[0]; - i && (n = Te(i)); - } - } - } - ); - } - switch (n) { - case "avc1": - case "avc2": - case "avc3": - case "avc4": - var o = we(r, ["avcC"])[0]; - n += "." + De(o[1]) + De(o[2]) + De(o[3]); - break; - case "mp4a": - var l = we(t, [i])[0], - h = we(l.subarray(28), ["esds"])[0]; - if (h && h.length > 12) { - var u = 4; - if (3 !== h[u++]) break; - (u = ke(h, u)), (u += 2); - var d = h[u++]; - if ( - (128 & d && (u += 2), - 64 & d && (u += h[u++]), - 4 !== h[u++]) - ) - break; - u = ke(h, u); - var c = h[u++]; - if (64 !== c) break; - if (((n += "." + De(c)), (u += 12), 5 !== h[u++])) break; - u = ke(h, u); - var f = h[u++], - g = (248 & f) >> 3; - 31 === g && - (g += 1 + ((7 & f) << 3) + ((224 & h[u]) >> 5)), - (n += "." + g); - } - break; - case "hvc1": - case "hev1": - var p = we(r, ["hvcC"])[0], - m = p[1], - v = ["", "A", "B", "C"][m >> 6], - y = 31 & m, - E = Le(p, 2), - S = (32 & m) >> 5 ? "H" : "L", - T = p[12], - _ = p.subarray(6, 12); - (n += "." + v + y), - (n += "." + E.toString(16).toUpperCase()), - (n += "." + S + T); - for (var L = "", b = _.length; b--; ) { - var R = _[b]; - (R || L) && (L = "." + R.toString(16).toUpperCase() + L); - } - n += L; - break; - case "dvh1": - case "dvhe": - var A = we(r, ["dvcC"])[0], - w = (A[2] >> 1) & 127, - P = ((A[2] << 5) & 32) | ((A[3] >> 3) & 31); - n += "." + Me(w) + "." + Me(P); - break; - case "vp09": - var I = we(r, ["vpcC"])[0], - C = I[4], - k = I[5], - D = (I[6] >> 4) & 15; - n += "." + Me(C) + "." + Me(k) + "." + Me(D); - break; - case "av01": - var M = we(r, ["av1C"])[0], - x = M[1] >>> 5, - O = 31 & M[1], - F = M[2] >>> 7 ? "H" : "M", - N = (64 & M[2]) >> 6, - B = (32 & M[2]) >> 5, - U = 2 === x && N ? (B ? 12 : 10) : N ? 10 : 8, - G = (16 & M[2]) >> 4, - H = (8 & M[2]) >> 3, - $ = (4 & M[2]) >> 2, - K = 3 & M[2]; - n += - "." + - x + - "." + - Me(O) + - F + - "." + - Me(U) + - "." + - G + - "." + - H + - $ + - K + - "." + - Me(1) + - "." + - Me(1) + - "." + - Me(1) + - ".0"; - } - return { codec: n, encrypted: s }; - } - function ke(e, t) { - for (var r = t + 5; 128 & e[t++] && t < r; ); - return t; - } - function De(e) { - return ("0" + e.toString(16).toUpperCase()).slice(-2); - } - function Me(e) { - return (e < 10 ? "0" : "") + e; - } - function xe(e) { - var t = we(e, ["schm"])[0]; - if (t) { - var r = Te(t.subarray(4, 8)); - if ("cbcs" === r || "cenc" === r) - return we(e, ["schi", "tenc"])[0]; - } - return A.error("[eme] missing 'schm' box"), null; - } - function Oe(e) { - var t = Le(e, 0), - r = 8; - 1 & t && (r += 4), 4 & t && (r += 4); - for (var i = 0, n = Le(e, 4), s = 0; s < n; s++) - 256 & t && ((i += Le(e, r)), (r += 4)), - 512 & t && (r += 4), - 1024 & t && (r += 4), - 2048 & t && (r += 4); - return i; - } - function Fe(e, t) { - var r = new Uint8Array(e.length + t.length); - return r.set(e), r.set(t, e.length), r; - } - function Ne(e, t) { - var r = [], - i = t.samples, - n = t.timescale, - s = t.id, - a = !1; - return ( - we(i, ["moof"]).map(function (o) { - var l = o.byteOffset - 8; - we(o, ["traf"]).map(function (o) { - var h = we(o, ["tfdt"]).map(function (e) { - var t = e[0], - r = Le(e, 4); - return ( - 1 === t && ((r *= Math.pow(2, 32)), (r += Le(e, 8))), - r / n - ); - })[0]; - return ( - void 0 !== h && (e = h), - we(o, ["tfhd"]).map(function (h) { - var u = Le(h, 4), - d = 16777215 & Le(h, 0), - c = 0, - f = !!(16 & d), - g = 0, - p = !!(32 & d), - m = 8; - u === s && - (!!(1 & d) && (m += 8), - !!(2 & d) && (m += 4), - !!(8 & d) && ((c = Le(h, m)), (m += 4)), - f && ((g = Le(h, m)), (m += 4)), - p && (m += 4), - "video" === t.type && - (a = (function (e) { - if (!e) return !1; - var t = e.indexOf("."), - r = t < 0 ? e : e.substring(0, t); - return ( - "hvc1" === r || - "hev1" === r || - "dvh1" === r || - "dvhe" === r - ); - })(t.codec)), - we(o, ["trun"]).map(function (s) { - var o = s[0], - h = 16777215 & Le(s, 0), - u = !!(1 & h), - d = 0, - f = !!(4 & h), - p = !!(256 & h), - m = 0, - v = !!(512 & h), - y = 0, - E = !!(1024 & h), - S = !!(2048 & h), - T = 0, - _ = Le(s, 4), - L = 8; - u && ((d = Le(s, L)), (L += 4)), f && (L += 4); - for (var b = d + l, R = 0; R < _; R++) { - if ( - (p ? ((m = Le(s, L)), (L += 4)) : (m = c), - v ? ((y = Le(s, L)), (L += 4)) : (y = g), - E && (L += 4), - S && - ((T = 0 === o ? Le(s, L) : Re(s, L)), - (L += 4)), - t.type === x) - ) - for (var A = 0; A < y; ) { - var w = Le(i, b); - Be(a, i[(b += 4)]) && - Ue( - i.subarray(b, b + w), - a ? 2 : 1, - e + T / n, - r - ), - (b += w), - (A += w + 4); - } - e += m / n; - } - })); - }) - ); - }); - }), - r - ); - } - function Be(e, t) { - if (e) { - var r = (t >> 1) & 63; - return 39 === r || 40 === r; - } - return 6 == (31 & t); - } - function Ue(e, t, r, i) { - var n = Ge(e), - s = 0; - s += t; - for (var a = 0, o = 0, l = 0; s < n.length; ) { - a = 0; - do { - if (s >= n.length) break; - a += l = n[s++]; - } while (255 === l); - o = 0; - do { - if (s >= n.length) break; - o += l = n[s++]; - } while (255 === l); - var h = n.length - s, - u = s; - if (o < h) s += o; - else if (o > h) { - A.error( - "Malformed SEI payload. " + - o + - " is too small, only " + - h + - " bytes left to parse." - ); - break; - } - if (4 === a) { - if (181 === n[u++]) { - var d = _e(n, u); - if (((u += 2), 49 === d)) { - var c = Le(n, u); - if (((u += 4), 1195456820 === c)) { - var f = n[u++]; - if (3 === f) { - var g = n[u++], - p = 64 & g, - m = p ? 2 + 3 * (31 & g) : 0, - v = new Uint8Array(m); - if (p) { - v[0] = g; - for (var y = 1; y < m; y++) v[y] = n[u++]; - } - i.push({ - type: f, - payloadType: a, - pts: r, - bytes: v, - }); - } - } - } - } - } else if (5 === a && o > 16) { - for (var E = [], S = 0; S < 16; S++) { - var T = n[u++].toString(16); - E.push(1 == T.length ? "0" + T : T), - (3 !== S && 5 !== S && 7 !== S && 9 !== S) || - E.push("-"); - } - for ( - var _ = o - 16, L = new Uint8Array(_), b = 0; - b < _; - b++ - ) - L[b] = n[u++]; - i.push({ - payloadType: a, - pts: r, - uuid: E.join(""), - userData: me(L), - userDataBytes: L, - }); - } - } - } - function Ge(e) { - for (var t = e.byteLength, r = [], i = 1; i < t - 2; ) - 0 === e[i] && 0 === e[i + 1] && 3 === e[i + 2] - ? (r.push(i + 2), (i += 2)) - : i++; - if (0 === r.length) return e; - var n = t - r.length, - s = new Uint8Array(n), - a = 0; - for (i = 0; i < n; a++, i++) - a === r[0] && (a++, r.shift()), (s[i] = e[a]); - return s; - } - var He = {}, - $e = (function () { - function e(e, t, r, i, n) { - void 0 === i && (i = [1]), - void 0 === n && (n = null), - (this.uri = void 0), - (this.method = void 0), - (this.keyFormat = void 0), - (this.keyFormatVersions = void 0), - (this.encrypted = void 0), - (this.isCommonEncryption = void 0), - (this.iv = null), - (this.key = null), - (this.keyId = null), - (this.pssh = null), - (this.method = e), - (this.uri = t), - (this.keyFormat = r), - (this.keyFormatVersions = i), - (this.iv = n), - (this.encrypted = !!e && "NONE" !== e), - (this.isCommonEncryption = - this.encrypted && "AES-128" !== e); - } - e.clearKeyUriToKeyIdMap = function () { - He = {}; - }; - var t = e.prototype; - return ( - (t.isSupported = function () { - if (this.method) { - if ("AES-128" === this.method || "NONE" === this.method) - return !0; - if ("identity" === this.keyFormat) - return "SAMPLE-AES" === this.method; - switch (this.keyFormat) { - case V: - case j: - case q: - case W: - return ( - -1 !== - [ - "ISO-23001-7", - "SAMPLE-AES", - "SAMPLE-AES-CENC", - "SAMPLE-AES-CTR", - ].indexOf(this.method) - ); - } - } - return !1; - }), - (t.getDecryptData = function (t) { - if (!this.encrypted || !this.uri) return null; - if ("AES-128" === this.method && this.uri && !this.iv) { - "number" != typeof t && - ("AES-128" !== this.method || - this.iv || - A.warn( - 'missing IV for initialization segment with method="' + - this.method + - '" - compliance issue' - ), - (t = 0)); - var r = (function (e) { - for (var t = new Uint8Array(16), r = 12; r < 16; r++) - t[r] = (e >> (8 * (15 - r))) & 255; - return t; - })(t); - return new e( - this.method, - this.uri, - "identity", - this.keyFormatVersions, - r - ); - } - var i = (function (e) { - var t, - r, - i = e.split(":"), - n = null; - if ("data" === i[0] && 2 === i.length) { - var s = i[1].split(";"), - a = s[s.length - 1].split(","); - if (2 === a.length) { - var o = "base64" === a[0], - l = a[1]; - o - ? (s.splice(-1, 1), (n = G(l))) - : ((t = H(l).subarray(0, 16)), - (r = new Uint8Array(16)).set(t, 16 - t.length), - (n = r)); - } - } - return n; - })(this.uri); - if (i) - switch (this.keyFormat) { - case j: - (this.pssh = i), - i.length >= 22 && - (this.keyId = i.subarray( - i.length - 22, - i.length - 6 - )); - break; - case q: - var n = new Uint8Array([ - 154, 4, 240, 121, 152, 64, 66, 134, 171, 146, 230, - 91, 224, 136, 95, 149, - ]); - this.pssh = (function (e, t, r) { - if (16 !== e.byteLength) - throw new RangeError("Invalid system id"); - var i, n, s; - if (t) { - (i = 1), (n = new Uint8Array(16 * t.length)); - for (var a = 0; a < t.length; a++) { - var o = t[a]; - if (16 !== o.byteLength) - throw new RangeError("Invalid key"); - n.set(o, 16 * a); - } - } else (i = 0), (n = new Uint8Array()); - i > 0 - ? ((s = new Uint8Array(4)), - t.length > 0 && - new DataView(s.buffer).setUint32( - 0, - t.length, - !1 - )) - : (s = new Uint8Array()); - var l = new Uint8Array(4); - return ( - r && - r.byteLength > 0 && - new DataView(l.buffer).setUint32( - 0, - r.byteLength, - !1 - ), - (function (e) { - for ( - var t = arguments.length, - r = new Array(t > 1 ? t - 1 : 0), - i = 1; - i < t; - i++ - ) - r[i - 1] = arguments[i]; - for (var n = r.length, s = 8, a = n; a--; ) - s += r[a].byteLength; - var o = new Uint8Array(s); - for ( - o[0] = (s >> 24) & 255, - o[1] = (s >> 16) & 255, - o[2] = (s >> 8) & 255, - o[3] = 255 & s, - o.set(e, 4), - a = 0, - s = 8; - a < n; - a++ - ) - o.set(r[a], s), (s += r[a].byteLength); - return o; - })( - [112, 115, 115, 104], - new Uint8Array([i, 0, 0, 0]), - e, - s, - n, - l, - r || new Uint8Array() - ) - ); - })(n, null, i); - var s = new Uint16Array( - i.buffer, - i.byteOffset, - i.byteLength / 2 - ), - a = String.fromCharCode.apply( - null, - Array.from(s) - ), - o = a.substring(a.indexOf("<"), a.length), - l = new DOMParser() - .parseFromString(o, "text/xml") - .getElementsByTagName("KID")[0]; - if (l) { - var h = l.childNodes[0] - ? l.childNodes[0].nodeValue - : l.getAttribute("VALUE"); - if (h) { - var u = G(h).subarray(0, 16); - !(function (e) { - var t = function (e, t, r) { - var i = e[t]; - (e[t] = e[r]), (e[r] = i); - }; - t(e, 0, 3), - t(e, 1, 2), - t(e, 4, 5), - t(e, 6, 7); - })(u), - (this.keyId = u); - } - } - break; - default: - var d = i.subarray(0, 16); - if (16 !== d.length) { - var c = new Uint8Array(16); - c.set(d, 16 - d.length), (d = c); - } - this.keyId = d; - } - if (!this.keyId || 16 !== this.keyId.byteLength) { - var f = He[this.uri]; - if (!f) { - var g = - Object.keys(He).length % Number.MAX_SAFE_INTEGER; - (f = new Uint8Array(16)), - new DataView(f.buffer, 12, 4).setUint32(0, g), - (He[this.uri] = f); - } - this.keyId = f; - } - return this; - }), - e - ); - })(), - Ke = /\{\$([a-zA-Z0-9-_]+)\}/g; - function We(e) { - return Ke.test(e); - } - function Ve(e, t, r) { - if (null !== e.variableList || e.hasVariableRefs) - for (var i = r.length; i--; ) { - var n = r[i], - s = t[n]; - s && (t[n] = qe(e, s)); - } - } - function qe(e, t) { - if (null !== e.variableList || e.hasVariableRefs) { - var r = e.variableList; - return t.replace(Ke, function (t) { - var i = t.substring(2, t.length - 1), - n = null == r ? void 0 : r[i]; - return void 0 === n - ? (e.playlistParsingError || - (e.playlistParsingError = new Error( - 'Missing preceding EXT-X-DEFINE tag for Variable Reference: "' + - i + - '"' - )), - t) - : n; - }); - } - return t; - } - function je(e, t, r) { - var i, - n, - s = e.variableList; - if ((s || (e.variableList = s = {}), "QUERYPARAM" in t)) { - i = t.QUERYPARAM; - try { - var a = new self.URL(r).searchParams; - if (!a.has(i)) - throw new Error( - '"' + - i + - '" does not match any query parameter in URI: "' + - r + - '"' - ); - n = a.get(i); - } catch (t) { - e.playlistParsingError || - (e.playlistParsingError = new Error( - "EXT-X-DEFINE QUERYPARAM: " + t.message - )); - } - } else (i = t.NAME), (n = t.VALUE); - i in s - ? e.playlistParsingError || - (e.playlistParsingError = new Error( - 'EXT-X-DEFINE duplicate Variable Name declarations: "' + - i + - '"' - )) - : (s[i] = n || ""); - } - function Ye(e, t, r) { - var i = t.IMPORT; - if (r && i in r) { - var n = e.variableList; - n || (e.variableList = n = {}), (n[i] = r[i]); - } else - e.playlistParsingError || - (e.playlistParsingError = new Error( - 'EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "' + - i + - '"' - )); - } - function ze(e) { - if ((void 0 === e && (e = !0), "undefined" != typeof self)) - return ( - ((e || !self.MediaSource) && self.ManagedMediaSource) || - self.MediaSource || - self.WebKitMediaSource - ); - } - var Xe = { - audio: { - a3ds: 1, - "ac-3": 0.95, - "ac-4": 1, - alac: 0.9, - alaw: 1, - dra1: 1, - "dts+": 1, - "dts-": 1, - dtsc: 1, - dtse: 1, - dtsh: 1, - "ec-3": 0.9, - enca: 1, - fLaC: 0.9, - flac: 0.9, - FLAC: 0.9, - g719: 1, - g726: 1, - m4ae: 1, - mha1: 1, - mha2: 1, - mhm1: 1, - mhm2: 1, - mlpa: 1, - mp4a: 1, - "raw ": 1, - Opus: 1, - opus: 1, - samr: 1, - sawb: 1, - sawp: 1, - sevc: 1, - sqcp: 1, - ssmv: 1, - twos: 1, - ulaw: 1, - }, - video: { - avc1: 1, - avc2: 1, - avc3: 1, - avc4: 1, - avcp: 1, - av01: 0.8, - drac: 1, - dva1: 1, - dvav: 1, - dvh1: 0.7, - dvhe: 0.7, - encv: 1, - hev1: 0.75, - hvc1: 0.75, - mjp2: 1, - mp4v: 1, - mvc1: 1, - mvc2: 1, - mvc3: 1, - mvc4: 1, - resv: 1, - rv60: 1, - s263: 1, - svc1: 1, - svc2: 1, - "vc-1": 1, - vp08: 1, - vp09: 0.9, - }, - text: { stpp: 1, wvtt: 1 }, - }; - function Qe(e, t, r) { - return ( - void 0 === r && (r = !0), - !e.split(",").some(function (e) { - return !Je(e, t, r); - }) - ); - } - function Je(e, t, r) { - var i; - void 0 === r && (r = !0); - var n = ze(r); - return ( - null != - (i = null == n ? void 0 : n.isTypeSupported(Ze(e, t))) && i - ); - } - function Ze(e, t) { - return t + '/mp4;codecs="' + e + '"'; - } - function et(e) { - if (e) { - var t = e.substring(0, 4); - return Xe.video[t]; - } - return 2; - } - function tt(e) { - return e.split(",").reduce(function (e, t) { - var r = Xe.video[t]; - return r - ? (2 * r + e) / (e ? 3 : 2) - : (Xe.audio[t] + e) / (e ? 2 : 1); - }, 0); - } - var rt = {}, - it = /flac|opus/i; - function nt(e, t) { - return ( - void 0 === t && (t = !0), - e.replace(it, function (e) { - return (function (e, t) { - if ((void 0 === t && (t = !0), rt[e])) return rt[e]; - for ( - var r = { - flac: ["flac", "fLaC", "FLAC"], - opus: ["opus", "Opus"], - }[e], - i = 0; - i < r.length; - i++ - ) - if (Je(r[i], "audio", t)) return (rt[e] = r[i]), r[i]; - return e; - })(e.toLowerCase(), t); - }) - ); - } - function st(e, t) { - return e && "mp4a" !== e ? e : t ? t.split(",")[0] : t; - } - var at = - /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g, - ot = /#EXT-X-MEDIA:(.*)/g, - lt = /^#EXT(?:INF|-X-TARGETDURATION):/m, - ht = new RegExp( - [ - /#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, - /(?!#) *(\S[^\r\n]*)/.source, - /#EXT-X-BYTERANGE:*(.+)/.source, - /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, - /#.*/.source, - ].join("|"), - "g" - ), - ut = new RegExp( - [ - /#(EXTM3U)/.source, - /#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/ - .source, - /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/ - .source, - /#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/ - .source, - /(#)([^:]*):(.*)/.source, - /(#)(.*)(?:.*)\r?\n?/.source, - ].join("|") - ), - dt = (function () { - function e() {} - return ( - (e.findGroup = function (e, t) { - for (var r = 0; r < e.length; r++) { - var i = e[r]; - if (i.id === t) return i; - } - }), - (e.resolve = function (e, t) { - return p.buildAbsoluteURL(t, e, { alwaysNormalize: !0 }); - }), - (e.isMediaPlaylist = function (e) { - return lt.test(e); - }), - (e.parseMasterPlaylist = function (t, r) { - var i, - n = { - contentSteering: null, - levels: [], - playlistParsingError: null, - sessionData: null, - sessionKeys: null, - startTimeOffset: null, - variableList: null, - hasVariableRefs: We(t), - }, - s = []; - for (at.lastIndex = 0; null != (i = at.exec(t)); ) - if (i[1]) { - var a, - o = new I(i[1]); - Ve(n, o, [ - "CODECS", - "SUPPLEMENTAL-CODECS", - "ALLOWED-CPC", - "PATHWAY-ID", - "STABLE-VARIANT-ID", - "AUDIO", - "VIDEO", - "SUBTITLES", - "CLOSED-CAPTIONS", - "NAME", - ]); - var l = qe(n, i[2]), - h = { - attrs: o, - bitrate: - o.decimalInteger("BANDWIDTH") || - o.decimalInteger("AVERAGE-BANDWIDTH"), - name: o.NAME, - url: e.resolve(l, r), - }, - u = o.decimalResolution("RESOLUTION"); - u && ((h.width = u.width), (h.height = u.height)), - gt(o.CODECS, h), - (null != (a = h.unknownCodecs) && a.length) || - s.push(h), - n.levels.push(h); - } else if (i[3]) { - var d = i[3], - c = i[4]; - switch (d) { - case "SESSION-DATA": - var f = new I(c); - Ve(n, f, ["DATA-ID", "LANGUAGE", "VALUE", "URI"]); - var g = f["DATA-ID"]; - g && - (null === n.sessionData && (n.sessionData = {}), - (n.sessionData[g] = f)); - break; - case "SESSION-KEY": - var p = ct(c, r, n); - p.encrypted && p.isSupported() - ? (null === n.sessionKeys && - (n.sessionKeys = []), - n.sessionKeys.push(p)) - : A.warn( - '[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "' + - c + - '"' - ); - break; - case "DEFINE": - var m = new I(c); - Ve(n, m, ["NAME", "VALUE", "QUERYPARAM"]), - je(n, m, r); - break; - case "CONTENT-STEERING": - var v = new I(c); - Ve(n, v, ["SERVER-URI", "PATHWAY-ID"]), - (n.contentSteering = { - uri: e.resolve(v["SERVER-URI"], r), - pathwayId: v["PATHWAY-ID"] || ".", - }); - break; - case "START": - n.startTimeOffset = ft(c); - } - } - var y = s.length > 0 && s.length < n.levels.length; - return ( - (n.levels = y ? s : n.levels), - 0 === n.levels.length && - (n.playlistParsingError = new Error( - "no levels found in manifest" - )), - n - ); - }), - (e.parseMasterPlaylistMedia = function (t, r, i) { - var n, - s = {}, - a = i.levels, - o = { - AUDIO: a.map(function (e) { - return { - id: e.attrs.AUDIO, - audioCodec: e.audioCodec, - }; - }), - SUBTITLES: a.map(function (e) { - return { - id: e.attrs.SUBTITLES, - textCodec: e.textCodec, - }; - }), - "CLOSED-CAPTIONS": [], - }, - l = 0; - for (ot.lastIndex = 0; null !== (n = ot.exec(t)); ) { - var h = new I(n[1]), - u = h.TYPE; - if (u) { - var d = o[u], - c = s[u] || []; - (s[u] = c), - Ve(i, h, [ - "URI", - "GROUP-ID", - "LANGUAGE", - "ASSOC-LANGUAGE", - "STABLE-RENDITION-ID", - "NAME", - "INSTREAM-ID", - "CHARACTERISTICS", - "CHANNELS", - ]); - var f = h.LANGUAGE, - g = h["ASSOC-LANGUAGE"], - p = h.CHANNELS, - m = h.CHARACTERISTICS, - v = h["INSTREAM-ID"], - y = { - attrs: h, - bitrate: 0, - id: l++, - groupId: h["GROUP-ID"] || "", - name: h.NAME || f || "", - type: u, - default: h.bool("DEFAULT"), - autoselect: h.bool("AUTOSELECT"), - forced: h.bool("FORCED"), - lang: f, - url: h.URI ? e.resolve(h.URI, r) : "", - }; - if ( - (g && (y.assocLang = g), - p && (y.channels = p), - m && (y.characteristics = m), - v && (y.instreamId = v), - null != d && d.length) - ) { - var E = e.findGroup(d, y.groupId) || d[0]; - pt(y, E, "audioCodec"), pt(y, E, "textCodec"); - } - c.push(y); - } - } - return s; - }), - (e.parseLevelPlaylist = function (e, t, r, i, n, s) { - var a, - l, - h, - u = new U(t), - d = u.fragments, - c = null, - f = 0, - g = 0, - p = 0, - v = 0, - y = null, - E = new N(i, t), - S = -1, - T = !1, - _ = null; - for ( - ht.lastIndex = 0, u.m3u8 = e, u.hasVariableRefs = We(e); - null !== (a = ht.exec(e)); - - ) { - T && - ((T = !1), - ((E = new N(i, t)).start = p), - (E.sn = f), - (E.cc = v), - (E.level = r), - c && - ((E.initSegment = c), - (E.rawProgramDateTime = c.rawProgramDateTime), - (c.rawProgramDateTime = null), - _ && (E.setByteRange(_), (_ = null)))); - var L = a[1]; - if (L) { - E.duration = parseFloat(L); - var b = (" " + a[2]).slice(1); - (E.title = b || null), - E.tagList.push(b ? ["INF", L, b] : ["INF", L]); - } else if (a[3]) { - if (m(E.duration)) { - (E.start = p), - h && yt(E, h, u), - (E.sn = f), - (E.level = r), - (E.cc = v), - d.push(E); - var R = (" " + a[3]).slice(1); - (E.relurl = qe(u, R)), - mt(E, y), - (y = E), - (p += E.duration), - f++, - (g = 0), - (T = !0); - } - } else if (a[4]) { - var w = (" " + a[4]).slice(1); - y ? E.setByteRange(w, y) : E.setByteRange(w); - } else if (a[5]) - (E.rawProgramDateTime = (" " + a[5]).slice(1)), - E.tagList.push([ - "PROGRAM-DATE-TIME", - E.rawProgramDateTime, - ]), - -1 === S && (S = d.length); - else { - if (!(a = a[0].match(ut))) { - A.warn( - "No matches on slow regex match for level playlist!" - ); - continue; - } - for (l = 1; l < a.length && void 0 === a[l]; l++); - var P = (" " + a[l]).slice(1), - C = (" " + a[l + 1]).slice(1), - D = a[l + 2] ? (" " + a[l + 2]).slice(1) : ""; - switch (P) { - case "PLAYLIST-TYPE": - u.type = C.toUpperCase(); - break; - case "MEDIA-SEQUENCE": - f = u.startSN = parseInt(C); - break; - case "SKIP": - var M = new I(C); - Ve(u, M, ["RECENTLY-REMOVED-DATERANGES"]); - var x = M.decimalInteger("SKIPPED-SEGMENTS"); - if (m(x)) { - u.skippedSegments = x; - for (var O = x; O--; ) d.unshift(null); - f += x; - } - var F = M.enumeratedString( - "RECENTLY-REMOVED-DATERANGES" - ); - F && - (u.recentlyRemovedDateranges = F.split("\t")); - break; - case "TARGETDURATION": - u.targetduration = Math.max(parseInt(C), 1); - break; - case "VERSION": - u.version = parseInt(C); - break; - case "INDEPENDENT-SEGMENTS": - case "EXTM3U": - break; - case "ENDLIST": - u.live = !1; - break; - case "#": - (C || D) && E.tagList.push(D ? [C, D] : [C]); - break; - case "DISCONTINUITY": - v++, E.tagList.push(["DIS"]); - break; - case "GAP": - (E.gap = !0), E.tagList.push([P]); - break; - case "BITRATE": - E.tagList.push([P, C]); - break; - case "DATERANGE": - var G = new I(C); - Ve(u, G, [ - "ID", - "CLASS", - "START-DATE", - "END-DATE", - "SCTE35-CMD", - "SCTE35-OUT", - "SCTE35-IN", - ]), - Ve(u, G, G.clientAttrs); - var H = new k(G, u.dateRanges[G.ID]); - H.isValid || u.skippedSegments - ? (u.dateRanges[H.id] = H) - : A.warn( - 'Ignoring invalid DATERANGE tag: "' + - C + - '"' - ), - E.tagList.push(["EXT-X-DATERANGE", C]); - break; - case "DEFINE": - var $ = new I(C); - Ve(u, $, [ - "NAME", - "VALUE", - "IMPORT", - "QUERYPARAM", - ]), - "IMPORT" in $ ? Ye(u, $, s) : je(u, $, t); - break; - case "DISCONTINUITY-SEQUENCE": - v = parseInt(C); - break; - case "KEY": - var K = ct(C, t, u); - if (K.isSupported()) { - if ("NONE" === K.method) { - h = void 0; - break; - } - h || (h = {}), - h[K.keyFormat] && (h = o({}, h)), - (h[K.keyFormat] = K); - } else - A.warn( - '[Keys] Ignoring invalid EXT-X-KEY tag: "' + - C + - '"' - ); - break; - case "START": - u.startTimeOffset = ft(C); - break; - case "MAP": - var W = new I(C); - if ( - (Ve(u, W, ["BYTERANGE", "URI"]), E.duration) - ) { - var V = new N(i, t); - vt(V, W, r, h), - (c = V), - (E.initSegment = c), - c.rawProgramDateTime && - !E.rawProgramDateTime && - (E.rawProgramDateTime = - c.rawProgramDateTime); - } else { - var q = E.byteRangeEndOffset; - if (q) { - var j = E.byteRangeStartOffset; - _ = q - j + "@" + j; - } else _ = null; - vt(E, W, r, h), (c = E), (T = !0); - } - break; - case "SERVER-CONTROL": - var Y = new I(C); - (u.canBlockReload = Y.bool("CAN-BLOCK-RELOAD")), - (u.canSkipUntil = Y.optionalFloat( - "CAN-SKIP-UNTIL", - 0 - )), - (u.canSkipDateRanges = - u.canSkipUntil > 0 && - Y.bool("CAN-SKIP-DATERANGES")), - (u.partHoldBack = Y.optionalFloat( - "PART-HOLD-BACK", - 0 - )), - (u.holdBack = Y.optionalFloat("HOLD-BACK", 0)); - break; - case "PART-INF": - var z = new I(C); - u.partTarget = - z.decimalFloatingPoint("PART-TARGET"); - break; - case "PART": - var X = u.partList; - X || (X = u.partList = []); - var Q = g > 0 ? X[X.length - 1] : void 0, - J = g++, - Z = new I(C); - Ve(u, Z, ["BYTERANGE", "URI"]); - var ee = new B(Z, E, t, J, Q); - X.push(ee), (E.duration += ee.duration); - break; - case "PRELOAD-HINT": - var te = new I(C); - Ve(u, te, ["URI"]), (u.preloadHint = te); - break; - case "RENDITION-REPORT": - var re = new I(C); - Ve(u, re, ["URI"]), - (u.renditionReports = u.renditionReports || []), - u.renditionReports.push(re); - break; - default: - A.warn("line parsed but not handled: " + a); - } - } - } - y && !y.relurl - ? (d.pop(), - (p -= y.duration), - u.partList && (u.fragmentHint = y)) - : u.partList && - (mt(E, y), - (E.cc = v), - (u.fragmentHint = E), - h && yt(E, h, u)); - var ie = d.length, - ne = d[0], - se = d[ie - 1]; - if ( - (p += u.skippedSegments * u.targetduration) > 0 && - ie && - se - ) { - u.averagetargetduration = p / ie; - var ae = se.sn; - (u.endSN = "initSegment" !== ae ? ae : 0), - u.live || (se.endList = !0), - ne && (u.startCC = ne.cc); - } else (u.endSN = 0), (u.startCC = 0); - return ( - u.fragmentHint && (p += u.fragmentHint.duration), - (u.totalduration = p), - (u.endCC = v), - S > 0 && - (function (e, t) { - for (var r = e[t], i = t; i--; ) { - var n = e[i]; - if (!n) return; - (n.programDateTime = - r.programDateTime - 1e3 * n.duration), - (r = n); - } - })(d, S), - u - ); - }), - e - ); - })(); - function ct(e, t, r) { - var i, - n, - s = new I(e); - Ve(r, s, [ - "KEYFORMAT", - "KEYFORMATVERSIONS", - "URI", - "IV", - "URI", - ]); - var a = null != (i = s.METHOD) ? i : "", - o = s.URI, - l = s.hexadecimalInteger("IV"), - h = s.KEYFORMATVERSIONS, - u = null != (n = s.KEYFORMAT) ? n : "identity"; - o && s.IV && !l && A.error("Invalid IV: " + s.IV); - var d = o ? dt.resolve(o, t) : "", - c = (h || "1").split("/").map(Number).filter(Number.isFinite); - return new $e(a, d, u, c, l); - } - function ft(e) { - var t = new I(e).decimalFloatingPoint("TIME-OFFSET"); - return m(t) ? t : null; - } - function gt(e, t) { - var r = (e || "").split(/[ ,]+/).filter(function (e) { - return e; - }); - ["video", "audio", "text"].forEach(function (e) { - var i = r.filter(function (t) { - return (function (e, t) { - var r = Xe[t]; - return !!r && !!r[e.slice(0, 4)]; - })(t, e); - }); - i.length && - ((t[e + "Codec"] = i.join(",")), - (r = r.filter(function (e) { - return -1 === i.indexOf(e); - }))); - }), - (t.unknownCodecs = r); - } - function pt(e, t, r) { - var i = t[r]; - i && (e[r] = i); - } - function mt(e, t) { - e.rawProgramDateTime - ? (e.programDateTime = Date.parse(e.rawProgramDateTime)) - : null != t && - t.programDateTime && - (e.programDateTime = t.endProgramDateTime), - m(e.programDateTime) || - ((e.programDateTime = null), (e.rawProgramDateTime = null)); - } - function vt(e, t, r, i) { - (e.relurl = t.URI), - t.BYTERANGE && e.setByteRange(t.BYTERANGE), - (e.level = r), - (e.sn = "initSegment"), - i && (e.levelkeys = i), - (e.initSegment = null); - } - function yt(e, t, r) { - e.levelkeys = t; - var i = r.encryptedFragments; - (i.length && i[i.length - 1].levelkeys === t) || - !Object.keys(t).some(function (e) { - return t[e].isCommonEncryption; - }) || - i.push(e); - } - var Et = "manifest", - St = "level", - Tt = "audioTrack", - _t = "subtitleTrack", - Lt = "main", - bt = "audio", - Rt = "subtitle"; - function At(e) { - switch (e.type) { - case Tt: - return bt; - case _t: - return Rt; - default: - return Lt; - } - } - function wt(e, t) { - var r = e.url; - return ( - (void 0 !== r && 0 !== r.indexOf("data:")) || (r = t.url), r - ); - } - var Pt = (function () { - function e(e) { - (this.hls = void 0), - (this.loaders = Object.create(null)), - (this.variableList = null), - (this.hls = e), - this.registerListeners(); - } - var t = e.prototype; - return ( - (t.startLoad = function (e) {}), - (t.stopLoad = function () { - this.destroyInternalLoaders(); - }), - (t.registerListeners = function () { - var e = this.hls; - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.LEVEL_LOADING, this.onLevelLoading, this), - e.on( - E.AUDIO_TRACK_LOADING, - this.onAudioTrackLoading, - this - ), - e.on( - E.SUBTITLE_TRACK_LOADING, - this.onSubtitleTrackLoading, - this - ); - }), - (t.unregisterListeners = function () { - var e = this.hls; - e.off(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.off(E.LEVEL_LOADING, this.onLevelLoading, this), - e.off( - E.AUDIO_TRACK_LOADING, - this.onAudioTrackLoading, - this - ), - e.off( - E.SUBTITLE_TRACK_LOADING, - this.onSubtitleTrackLoading, - this - ); - }), - (t.createInternalLoader = function (e) { - var t = this.hls.config, - r = t.pLoader, - i = t.loader, - n = new (r || i)(t); - return (this.loaders[e.type] = n), n; - }), - (t.getInternalLoader = function (e) { - return this.loaders[e.type]; - }), - (t.resetInternalLoader = function (e) { - this.loaders[e] && delete this.loaders[e]; - }), - (t.destroyInternalLoaders = function () { - for (var e in this.loaders) { - var t = this.loaders[e]; - t && t.destroy(), this.resetInternalLoader(e); - } - }), - (t.destroy = function () { - (this.variableList = null), - this.unregisterListeners(), - this.destroyInternalLoaders(); - }), - (t.onManifestLoading = function (e, t) { - var r = t.url; - (this.variableList = null), - this.load({ - id: null, - level: 0, - responseType: "text", - type: Et, - url: r, - deliveryDirectives: null, - }); - }), - (t.onLevelLoading = function (e, t) { - var r = t.id, - i = t.level, - n = t.pathwayId, - s = t.url, - a = t.deliveryDirectives; - this.load({ - id: r, - level: i, - pathwayId: n, - responseType: "text", - type: St, - url: s, - deliveryDirectives: a, - }); - }), - (t.onAudioTrackLoading = function (e, t) { - var r = t.id, - i = t.groupId, - n = t.url, - s = t.deliveryDirectives; - this.load({ - id: r, - groupId: i, - level: null, - responseType: "text", - type: Tt, - url: n, - deliveryDirectives: s, - }); - }), - (t.onSubtitleTrackLoading = function (e, t) { - var r = t.id, - i = t.groupId, - n = t.url, - s = t.deliveryDirectives; - this.load({ - id: r, - groupId: i, - level: null, - responseType: "text", - type: _t, - url: n, - deliveryDirectives: s, - }); - }), - (t.load = function (e) { - var t, - r, - i, - n = this, - s = this.hls.config, - a = this.getInternalLoader(e); - if (a) { - var l = a.context; - if (l && l.url === e.url && l.level === e.level) - return void A.trace( - "[playlist-loader]: playlist request ongoing" - ); - A.log( - "[playlist-loader]: aborting previous loader for type: " + - e.type - ), - a.abort(); - } - if ( - ((r = - e.type === Et - ? s.manifestLoadPolicy.default - : o({}, s.playlistLoadPolicy.default, { - timeoutRetry: null, - errorRetry: null, - })), - (a = this.createInternalLoader(e)), - m(null == (t = e.deliveryDirectives) ? void 0 : t.part) && - (e.type === St && null !== e.level - ? (i = this.hls.levels[e.level].details) - : e.type === Tt && null !== e.id - ? (i = this.hls.audioTracks[e.id].details) - : e.type === _t && - null !== e.id && - (i = this.hls.subtitleTracks[e.id].details), - i)) - ) { - var h = i.partTarget, - u = i.targetduration; - if (h && u) { - var d = 1e3 * Math.max(3 * h, 0.8 * u); - r = o({}, r, { - maxTimeToFirstByteMs: Math.min( - d, - r.maxTimeToFirstByteMs - ), - maxLoadTimeMs: Math.min(d, r.maxTimeToFirstByteMs), - }); - } - } - var c = r.errorRetry || r.timeoutRetry || {}, - f = { - loadPolicy: r, - timeout: r.maxLoadTimeMs, - maxRetry: c.maxNumRetry || 0, - retryDelay: c.retryDelayMs || 0, - maxRetryDelay: c.maxRetryDelayMs || 0, - }, - g = { - onSuccess: function (e, t, r, i) { - var s = n.getInternalLoader(r); - n.resetInternalLoader(r.type); - var a = e.data; - 0 === a.indexOf("#EXTM3U") - ? ((t.parsing.start = performance.now()), - dt.isMediaPlaylist(a) - ? n.handleTrackOrLevelPlaylist( - e, - t, - r, - i || null, - s - ) - : n.handleMasterPlaylist(e, t, r, i)) - : n.handleManifestParsingError( - e, - r, - new Error("no EXTM3U delimiter"), - i || null, - t - ); - }, - onError: function (e, t, r, i) { - n.handleNetworkError(t, r, !1, e, i); - }, - onTimeout: function (e, t, r) { - n.handleNetworkError(t, r, !0, void 0, e); - }, - }; - a.load(e, f, g); - }), - (t.handleMasterPlaylist = function (e, t, r, i) { - var n = this.hls, - s = e.data, - a = wt(e, r), - o = dt.parseMasterPlaylist(s, a); - if (o.playlistParsingError) - this.handleManifestParsingError( - e, - r, - o.playlistParsingError, - i, - t - ); - else { - var l = o.contentSteering, - h = o.levels, - u = o.sessionData, - d = o.sessionKeys, - c = o.startTimeOffset, - f = o.variableList; - this.variableList = f; - var g = dt.parseMasterPlaylistMedia(s, a, o), - p = g.AUDIO, - m = void 0 === p ? [] : p, - v = g.SUBTITLES, - y = g["CLOSED-CAPTIONS"]; - m.length && - (m.some(function (e) { - return !e.url; - }) || - !h[0].audioCodec || - h[0].attrs.AUDIO || - (A.log( - "[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one" - ), - m.unshift({ - type: "main", - name: "main", - groupId: "main", - default: !1, - autoselect: !1, - forced: !1, - id: -1, - attrs: new I({}), - bitrate: 0, - url: "", - }))), - n.trigger(E.MANIFEST_LOADED, { - levels: h, - audioTracks: m, - subtitles: v, - captions: y, - contentSteering: l, - url: a, - stats: t, - networkDetails: i, - sessionData: u, - sessionKeys: d, - startTimeOffset: c, - variableList: f, - }); - } - }), - (t.handleTrackOrLevelPlaylist = function (e, t, r, i, n) { - var s = this.hls, - a = r.id, - o = r.level, - l = r.type, - h = wt(e, r), - u = m(o) ? o : m(a) ? a : 0, - d = At(r), - c = dt.parseLevelPlaylist( - e.data, - h, - u, - d, - 0, - this.variableList - ); - if (l === Et) { - var f = { - attrs: new I({}), - bitrate: 0, - details: c, - name: "", - url: h, - }; - s.trigger(E.MANIFEST_LOADED, { - levels: [f], - audioTracks: [], - url: h, - stats: t, - networkDetails: i, - sessionData: null, - sessionKeys: null, - contentSteering: null, - startTimeOffset: null, - variableList: null, - }); - } - (t.parsing.end = performance.now()), - (r.levelDetails = c), - this.handlePlaylistLoaded(c, e, t, r, i, n); - }), - (t.handleManifestParsingError = function (e, t, r, i, n) { - this.hls.trigger(E.ERROR, { - type: S.NETWORK_ERROR, - details: T.MANIFEST_PARSING_ERROR, - fatal: t.type === Et, - url: e.url, - err: r, - error: r, - reason: r.message, - response: e, - context: t, - networkDetails: i, - stats: n, - }); - }), - (t.handleNetworkError = function (e, t, r, n, s) { - void 0 === r && (r = !1); - var a = - "A network " + - (r - ? "timeout" - : "error" + (n ? " (status " + n.code + ")" : "")) + - " occurred while loading " + - e.type; - e.type === St - ? (a += ": " + e.level + " id: " + e.id) - : (e.type !== Tt && e.type !== _t) || - (a += - " id: " + e.id + ' group-id: "' + e.groupId + '"'); - var o = new Error(a); - A.warn("[playlist-loader]: " + a); - var l = T.UNKNOWN, - h = !1, - u = this.getInternalLoader(e); - switch (e.type) { - case Et: - (l = r - ? T.MANIFEST_LOAD_TIMEOUT - : T.MANIFEST_LOAD_ERROR), - (h = !0); - break; - case St: - (l = r ? T.LEVEL_LOAD_TIMEOUT : T.LEVEL_LOAD_ERROR), - (h = !1); - break; - case Tt: - (l = r - ? T.AUDIO_TRACK_LOAD_TIMEOUT - : T.AUDIO_TRACK_LOAD_ERROR), - (h = !1); - break; - case _t: - (l = r - ? T.SUBTITLE_TRACK_LOAD_TIMEOUT - : T.SUBTITLE_LOAD_ERROR), - (h = !1); - } - u && this.resetInternalLoader(e.type); - var d = { - type: S.NETWORK_ERROR, - details: l, - fatal: h, - url: e.url, - loader: u, - context: e, - error: o, - networkDetails: t, - stats: s, - }; - if (n) { - var c = (null == t ? void 0 : t.url) || e.url; - d.response = i({ url: c, data: void 0 }, n); - } - this.hls.trigger(E.ERROR, d); - }), - (t.handlePlaylistLoaded = function (e, t, r, i, n, s) { - var a = this.hls, - o = i.type, - l = i.level, - h = i.id, - u = i.groupId, - d = i.deliveryDirectives, - c = wt(t, i), - f = At(i), - g = "number" == typeof i.level && f === Lt ? l : void 0; - if (e.fragments.length) { - e.targetduration || - (e.playlistParsingError = new Error( - "Missing Target Duration" - )); - var p = e.playlistParsingError; - if (p) - a.trigger(E.ERROR, { - type: S.NETWORK_ERROR, - details: T.LEVEL_PARSING_ERROR, - fatal: !1, - url: c, - error: p, - reason: p.message, - response: t, - context: i, - level: g, - parent: f, - networkDetails: n, - stats: r, - }); - else - switch ( - (e.live && - s && - (s.getCacheAge && - (e.ageHeader = s.getCacheAge() || 0), - (s.getCacheAge && !isNaN(e.ageHeader)) || - (e.ageHeader = 0)), - o) - ) { - case Et: - case St: - a.trigger(E.LEVEL_LOADED, { - details: e, - level: g || 0, - id: h || 0, - stats: r, - networkDetails: n, - deliveryDirectives: d, - }); - break; - case Tt: - a.trigger(E.AUDIO_TRACK_LOADED, { - details: e, - id: h || 0, - groupId: u || "", - stats: r, - networkDetails: n, - deliveryDirectives: d, - }); - break; - case _t: - a.trigger(E.SUBTITLE_TRACK_LOADED, { - details: e, - id: h || 0, - groupId: u || "", - stats: r, - networkDetails: n, - deliveryDirectives: d, - }); - } - } else { - var m = new Error("No Segments found in Playlist"); - a.trigger(E.ERROR, { - type: S.NETWORK_ERROR, - details: T.LEVEL_EMPTY_ERROR, - fatal: !1, - url: c, - error: m, - reason: m.message, - response: t, - context: i, - level: g, - parent: f, - networkDetails: n, - stats: r, - }); - } - }), - e - ); - })(); - function It(e, t) { - var r; - try { - r = new Event("addtrack"); - } catch (e) { - (r = document.createEvent("Event")).initEvent( - "addtrack", - !1, - !1 - ); - } - (r.track = e), t.dispatchEvent(r); - } - function Ct(e, t) { - var r = e.mode; - if ( - ("disabled" === r && (e.mode = "hidden"), - e.cues && !e.cues.getCueById(t.id)) - ) - try { - if ((e.addCue(t), !e.cues.getCueById(t.id))) - throw new Error("addCue is failed for: " + t); - } catch (r) { - A.debug("[texttrack-utils]: " + r); - try { - var i = new self.TextTrackCue( - t.startTime, - t.endTime, - t.text - ); - (i.id = t.id), e.addCue(i); - } catch (e) { - A.debug( - "[texttrack-utils]: Legacy TextTrackCue fallback failed: " + - e - ); - } - } - "disabled" === r && (e.mode = r); - } - function kt(e) { - var t = e.mode; - if (("disabled" === t && (e.mode = "hidden"), e.cues)) - for (var r = e.cues.length; r--; ) e.removeCue(e.cues[r]); - "disabled" === t && (e.mode = t); - } - function Dt(e, t, r, i) { - var n = e.mode; - if ( - ("disabled" === n && (e.mode = "hidden"), - e.cues && e.cues.length > 0) - ) - for ( - var s = (function (e, t, r) { - var i = [], - n = (function (e, t) { - if (t < e[0].startTime) return 0; - var r = e.length - 1; - if (t > e[r].endTime) return -1; - for (var i = 0, n = r; i <= n; ) { - var s = Math.floor((n + i) / 2); - if (t < e[s].startTime) n = s - 1; - else { - if (!(t > e[s].startTime && i < r)) return s; - i = s + 1; - } - } - return e[i].startTime - t < t - e[n].startTime - ? i - : n; - })(e, t); - if (n > -1) - for (var s = n, a = e.length; s < a; s++) { - var o = e[s]; - if (o.startTime >= t && o.endTime <= r) i.push(o); - else if (o.startTime > r) return i; - } - return i; - })(e.cues, t, r), - a = 0; - a < s.length; - a++ - ) - (i && !i(s[a])) || e.removeCue(s[a]); - "disabled" === n && (e.mode = n); - } - function Mt(e) { - for (var t = [], r = 0; r < e.length; r++) { - var i = e[r]; - ("subtitles" !== i.kind && "captions" !== i.kind) || - !i.label || - t.push(e[r]); - } - return t; - } - var xt = "org.id3", - Ot = "https://aomedia.org/emsg/ID3"; - function Ft() { - if ("undefined" != typeof self) - return self.VTTCue || self.TextTrackCue; - } - function Nt(e, t, r, n, s) { - var a = new e(t, r, ""); - try { - (a.value = n), s && (a.type = s); - } catch (o) { - a = new e(t, r, JSON.stringify(s ? i({ type: s }, n) : n)); - } - return a; - } - var Bt = (function () { - var e = Ft(); - try { - e && new e(0, Number.POSITIVE_INFINITY, ""); - } catch (e) { - return Number.MAX_VALUE; - } - return Number.POSITIVE_INFINITY; - })(); - function Ut(e, t) { - return e.getTime() / 1e3 - t; - } - var Gt = (function () { - function e(e) { - (this.hls = void 0), - (this.id3Track = null), - (this.media = null), - (this.dateRangeCuesAppended = {}), - (this.hls = e), - this._registerListeners(); - } - var t = e.prototype; - return ( - (t.destroy = function () { - this._unregisterListeners(), - (this.id3Track = null), - (this.media = null), - (this.dateRangeCuesAppended = {}), - (this.hls = null); - }), - (t._registerListeners = function () { - var e = this.hls; - e.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on( - E.FRAG_PARSING_METADATA, - this.onFragParsingMetadata, - this - ), - e.on(E.BUFFER_FLUSHING, this.onBufferFlushing, this), - e.on(E.LEVEL_UPDATED, this.onLevelUpdated, this); - }), - (t._unregisterListeners = function () { - var e = this.hls; - e.off(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.off(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.off( - E.FRAG_PARSING_METADATA, - this.onFragParsingMetadata, - this - ), - e.off(E.BUFFER_FLUSHING, this.onBufferFlushing, this), - e.off(E.LEVEL_UPDATED, this.onLevelUpdated, this); - }), - (t.onMediaAttached = function (e, t) { - this.media = t.media; - }), - (t.onMediaDetaching = function () { - this.id3Track && - (kt(this.id3Track), - (this.id3Track = null), - (this.media = null), - (this.dateRangeCuesAppended = {})); - }), - (t.onManifestLoading = function () { - this.dateRangeCuesAppended = {}; - }), - (t.createTrack = function (e) { - var t = this.getID3Track(e.textTracks); - return (t.mode = "hidden"), t; - }), - (t.getID3Track = function (e) { - if (this.media) { - for (var t = 0; t < e.length; t++) { - var r = e[t]; - if ("metadata" === r.kind && "id3" === r.label) - return It(r, this.media), r; - } - return this.media.addTextTrack("metadata", "id3"); - } - }), - (t.onFragParsingMetadata = function (e, t) { - if (this.media) { - var r = this.hls.config, - i = r.enableEmsgMetadataCues, - n = r.enableID3MetadataCues; - if (i || n) { - var s = t.samples; - this.id3Track || - (this.id3Track = this.createTrack(this.media)); - var a = Ft(); - if (a) - for (var o = 0; o < s.length; o++) { - var l = s[o].type; - if ((l !== Ot || i) && n) { - var h = ue(s[o].data); - if (h) { - var u = s[o].pts, - d = u + s[o].duration; - d > Bt && (d = Bt), - d - u <= 0 && (d = u + 0.25); - for (var c = 0; c < h.length; c++) { - var f = h[c]; - if (!le(f)) { - this.updateId3CueEnds(u, l); - var g = Nt(a, u, d, f, l); - g && this.id3Track.addCue(g); - } - } - } - } - } - } - } - }), - (t.updateId3CueEnds = function (e, t) { - var r, - i = null == (r = this.id3Track) ? void 0 : r.cues; - if (i) - for (var n = i.length; n--; ) { - var s = i[n]; - s.type === t && - s.startTime < e && - s.endTime === Bt && - (s.endTime = e); - } - }), - (t.onBufferFlushing = function (e, t) { - var r = t.startOffset, - i = t.endOffset, - n = t.type, - s = this.id3Track, - a = this.hls; - if (a) { - var o = a.config, - l = o.enableEmsgMetadataCues, - h = o.enableID3MetadataCues; - s && - (l || h) && - Dt( - s, - r, - i, - "audio" === n - ? function (e) { - return e.type === xt && h; - } - : "video" === n - ? function (e) { - return e.type === Ot && l; - } - : function (e) { - return ( - (e.type === xt && h) || (e.type === Ot && l) - ); - } - ); - } - }), - (t.onLevelUpdated = function (e, t) { - var r = this, - i = t.details; - if ( - this.media && - i.hasProgramDateTime && - this.hls.config.enableDateRangeMetadataCues - ) { - var n = this.dateRangeCuesAppended, - s = this.id3Track, - a = i.dateRanges, - o = Object.keys(a); - if (s) - for ( - var l = Object.keys(n).filter(function (e) { - return !o.includes(e); - }), - h = function () { - var e = l[u]; - Object.keys(n[e].cues).forEach(function (t) { - s.removeCue(n[e].cues[t]); - }), - delete n[e]; - }, - u = l.length; - u--; - - ) - h(); - var d = i.fragments[i.fragments.length - 1]; - if ( - 0 !== o.length && - m(null == d ? void 0 : d.programDateTime) - ) { - this.id3Track || - (this.id3Track = this.createTrack(this.media)); - for ( - var c = d.programDateTime / 1e3 - d.start, - f = Ft(), - g = function () { - var e = o[p], - t = a[e], - i = Ut(t.startDate, c), - s = n[e], - l = (null == s ? void 0 : s.cues) || {}, - h = - (null == s ? void 0 : s.durationKnown) || - !1, - u = Bt, - d = t.endDate; - if (d) (u = Ut(d, c)), (h = !0); - else if (t.endOnNext && !h) { - var g = o.reduce(function (e, r) { - if (r !== t.id) { - var i = a[r]; - if ( - i.class === t.class && - i.startDate > t.startDate && - (!e || t.startDate < e.startDate) - ) - return i; - } - return e; - }, null); - g && ((u = Ut(g.startDate, c)), (h = !0)); - } - for ( - var m, v, y = Object.keys(t.attr), E = 0; - E < y.length; - E++ - ) { - var S = y[E]; - if ( - "ID" !== (v = S) && - "CLASS" !== v && - "START-DATE" !== v && - "DURATION" !== v && - "END-DATE" !== v && - "END-ON-NEXT" !== v - ) { - var T = l[S]; - if (T) - h && !s.durationKnown && (T.endTime = u); - else if (f) { - var _ = t.attr[S]; - C(S) && - ((m = _), - (_ = Uint8Array.from( - m - .replace(/^0x/, "") - .replace( - /([\da-fA-F]{2}) ?/g, - "0x$1 " - ) - .replace(/ +$/, "") - .split(" ") - ).buffer)); - var L = Nt( - f, - i, - u, - { key: S, data: _ }, - "com.apple.quicktime.HLS" - ); - L && - ((L.id = e), - r.id3Track.addCue(L), - (l[S] = L)); - } - } - } - n[e] = { - cues: l, - dateRange: t, - durationKnown: h, - }; - }, - p = 0; - p < o.length; - p++ - ) - g(); - } - } - }), - e - ); - })(), - Ht = (function () { - function e(e) { - var t = this; - (this.hls = void 0), - (this.config = void 0), - (this.media = null), - (this.levelDetails = null), - (this.currentTime = 0), - (this.stallCount = 0), - (this._latency = null), - (this.timeupdateHandler = function () { - return t.timeupdate(); - }), - (this.hls = e), - (this.config = e.config), - this.registerListeners(); - } - var t = e.prototype; - return ( - (t.destroy = function () { - this.unregisterListeners(), - this.onMediaDetaching(), - (this.levelDetails = null), - (this.hls = this.timeupdateHandler = null); - }), - (t.registerListeners = function () { - this.hls.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), - this.hls.on( - E.MEDIA_DETACHING, - this.onMediaDetaching, - this - ), - this.hls.on( - E.MANIFEST_LOADING, - this.onManifestLoading, - this - ), - this.hls.on(E.LEVEL_UPDATED, this.onLevelUpdated, this), - this.hls.on(E.ERROR, this.onError, this); - }), - (t.unregisterListeners = function () { - this.hls.off( - E.MEDIA_ATTACHED, - this.onMediaAttached, - this - ), - this.hls.off( - E.MEDIA_DETACHING, - this.onMediaDetaching, - this - ), - this.hls.off( - E.MANIFEST_LOADING, - this.onManifestLoading, - this - ), - this.hls.off( - E.LEVEL_UPDATED, - this.onLevelUpdated, - this - ), - this.hls.off(E.ERROR, this.onError, this); - }), - (t.onMediaAttached = function (e, t) { - (this.media = t.media), - this.media.addEventListener( - "timeupdate", - this.timeupdateHandler - ); - }), - (t.onMediaDetaching = function () { - this.media && - (this.media.removeEventListener( - "timeupdate", - this.timeupdateHandler - ), - (this.media = null)); - }), - (t.onManifestLoading = function () { - (this.levelDetails = null), - (this._latency = null), - (this.stallCount = 0); - }), - (t.onLevelUpdated = function (e, t) { - var r = t.details; - (this.levelDetails = r), - r.advanced && this.timeupdate(), - !r.live && - this.media && - this.media.removeEventListener( - "timeupdate", - this.timeupdateHandler - ); - }), - (t.onError = function (e, t) { - var r; - t.details === T.BUFFER_STALLED_ERROR && - (this.stallCount++, - null != (r = this.levelDetails) && - r.live && - A.warn( - "[playback-rate-controller]: Stall detected, adjusting target latency" - )); - }), - (t.timeupdate = function () { - var e = this.media, - t = this.levelDetails; - if (e && t) { - this.currentTime = e.currentTime; - var r = this.computeLatency(); - if (null !== r) { - this._latency = r; - var i = this.config, - n = i.lowLatencyMode, - s = i.maxLiveSyncPlaybackRate; - if (n && 1 !== s && t.live) { - var a = this.targetLatency; - if (null !== a) { - var o = r - a; - if ( - o < - Math.min( - this.maxLatency, - a + t.targetduration - ) && - o > 0.05 && - this.forwardBufferLength > 1 - ) { - var l = Math.min(2, Math.max(1, s)), - h = - Math.round( - (2 / - (1 + - Math.exp( - -0.75 * o - this.edgeStalled - ))) * - 20 - ) / 20; - e.playbackRate = Math.min(l, Math.max(1, h)); - } else - 1 !== e.playbackRate && - 0 !== e.playbackRate && - (e.playbackRate = 1); - } - } - } - } - }), - (t.estimateLiveEdge = function () { - var e = this.levelDetails; - return null === e ? null : e.edge + e.age; - }), - (t.computeLatency = function () { - var e = this.estimateLiveEdge(); - return null === e ? null : e - this.currentTime; - }), - a(e, [ - { - key: "latency", - get: function () { - return this._latency || 0; - }, - }, - { - key: "maxLatency", - get: function () { - var e = this.config, - t = this.levelDetails; - return void 0 !== e.liveMaxLatencyDuration - ? e.liveMaxLatencyDuration - : t - ? e.liveMaxLatencyDurationCount * t.targetduration - : 0; - }, - }, - { - key: "targetLatency", - get: function () { - var e = this.levelDetails; - if (null === e) return null; - var t = e.holdBack, - r = e.partHoldBack, - i = e.targetduration, - n = this.config, - s = n.liveSyncDuration, - a = n.liveSyncDurationCount, - o = n.lowLatencyMode, - l = this.hls.userConfig, - h = (o && r) || t; - (l.liveSyncDuration || - l.liveSyncDurationCount || - 0 === h) && - (h = void 0 !== s ? s : a * i); - var u = i; - return h + Math.min(1 * this.stallCount, u); - }, - }, - { - key: "liveSyncPosition", - get: function () { - var e = this.estimateLiveEdge(), - t = this.targetLatency, - r = this.levelDetails; - if (null === e || null === t || null === r) - return null; - var i = r.edge, - n = e - t - this.edgeStalled, - s = i - r.totalduration, - a = - i - - ((this.config.lowLatencyMode && r.partTarget) || - r.targetduration); - return Math.min(Math.max(s, n), a); - }, - }, - { - key: "drift", - get: function () { - var e = this.levelDetails; - return null === e ? 1 : e.drift; - }, - }, - { - key: "edgeStalled", - get: function () { - var e = this.levelDetails; - if (null === e) return 0; - var t = - 3 * - ((this.config.lowLatencyMode && e.partTarget) || - e.targetduration); - return Math.max(e.age - t, 0); - }, - }, - { - key: "forwardBufferLength", - get: function () { - var e = this.media, - t = this.levelDetails; - if (!e || !t) return 0; - var r = e.buffered.length; - return ( - (r ? e.buffered.end(r - 1) : t.edge) - - this.currentTime - ); - }, - }, - ]), - e - ); - })(), - $t = ["NONE", "TYPE-0", "TYPE-1", null], - Kt = ["SDR", "PQ", "HLG"]; - function Wt(e) { - var t = e.canSkipUntil, - r = e.canSkipDateRanges, - i = e.age; - return t && i < t / 2 ? (r ? "v2" : "YES") : ""; - } - var Vt = (function () { - function e(e, t, r) { - (this.msn = void 0), - (this.part = void 0), - (this.skip = void 0), - (this.msn = e), - (this.part = t), - (this.skip = r); - } - return ( - (e.prototype.addDirectives = function (e) { - var t = new self.URL(e); - return ( - void 0 !== this.msn && - t.searchParams.set("_HLS_msn", this.msn.toString()), - void 0 !== this.part && - t.searchParams.set("_HLS_part", this.part.toString()), - this.skip && t.searchParams.set("_HLS_skip", this.skip), - t.href - ); - }), - e - ); - })(), - qt = (function () { - function e(e) { - (this._attrs = void 0), - (this.audioCodec = void 0), - (this.bitrate = void 0), - (this.codecSet = void 0), - (this.url = void 0), - (this.frameRate = void 0), - (this.height = void 0), - (this.id = void 0), - (this.name = void 0), - (this.videoCodec = void 0), - (this.width = void 0), - (this.details = void 0), - (this.fragmentError = 0), - (this.loadError = 0), - (this.loaded = void 0), - (this.realBitrate = 0), - (this.supportedPromise = void 0), - (this.supportedResult = void 0), - (this._avgBitrate = 0), - (this._audioGroups = void 0), - (this._subtitleGroups = void 0), - (this._urlId = 0), - (this.url = [e.url]), - (this._attrs = [e.attrs]), - (this.bitrate = e.bitrate), - e.details && (this.details = e.details), - (this.id = e.id || 0), - (this.name = e.name), - (this.width = e.width || 0), - (this.height = e.height || 0), - (this.frameRate = e.attrs.optionalFloat("FRAME-RATE", 0)), - (this._avgBitrate = - e.attrs.decimalInteger("AVERAGE-BANDWIDTH")), - (this.audioCodec = e.audioCodec), - (this.videoCodec = e.videoCodec), - (this.codecSet = [e.videoCodec, e.audioCodec] - .filter(function (e) { - return !!e; - }) - .map(function (e) { - return e.substring(0, 4); - }) - .join(",")), - this.addGroupId("audio", e.attrs.AUDIO), - this.addGroupId("text", e.attrs.SUBTITLES); - } - var t = e.prototype; - return ( - (t.hasAudioGroup = function (e) { - return jt(this._audioGroups, e); - }), - (t.hasSubtitleGroup = function (e) { - return jt(this._subtitleGroups, e); - }), - (t.addGroupId = function (e, t) { - if (t) - if ("audio" === e) { - var r = this._audioGroups; - r || (r = this._audioGroups = []), - -1 === r.indexOf(t) && r.push(t); - } else if ("text" === e) { - var i = this._subtitleGroups; - i || (i = this._subtitleGroups = []), - -1 === i.indexOf(t) && i.push(t); - } - }), - (t.addFallback = function () {}), - a(e, [ - { - key: "maxBitrate", - get: function () { - return Math.max(this.realBitrate, this.bitrate); - }, - }, - { - key: "averageBitrate", - get: function () { - return ( - this._avgBitrate || this.realBitrate || this.bitrate - ); - }, - }, - { - key: "attrs", - get: function () { - return this._attrs[0]; - }, - }, - { - key: "codecs", - get: function () { - return this.attrs.CODECS || ""; - }, - }, - { - key: "pathwayId", - get: function () { - return this.attrs["PATHWAY-ID"] || "."; - }, - }, - { - key: "videoRange", - get: function () { - return this.attrs["VIDEO-RANGE"] || "SDR"; - }, - }, - { - key: "score", - get: function () { - return this.attrs.optionalFloat("SCORE", 0); - }, - }, - { - key: "uri", - get: function () { - return this.url[0] || ""; - }, - }, - { - key: "audioGroups", - get: function () { - return this._audioGroups; - }, - }, - { - key: "subtitleGroups", - get: function () { - return this._subtitleGroups; - }, - }, - { - key: "urlId", - get: function () { - return 0; - }, - set: function (e) {}, - }, - { - key: "audioGroupIds", - get: function () { - return this.audioGroups - ? [this.audioGroupId] - : void 0; - }, - }, - { - key: "textGroupIds", - get: function () { - return this.subtitleGroups - ? [this.textGroupId] - : void 0; - }, - }, - { - key: "audioGroupId", - get: function () { - var e; - return null == (e = this.audioGroups) ? void 0 : e[0]; - }, - }, - { - key: "textGroupId", - get: function () { - var e; - return null == (e = this.subtitleGroups) - ? void 0 - : e[0]; - }, - }, - ]), - e - ); - })(); - function jt(e, t) { - return !(!t || !e) && -1 !== e.indexOf(t); - } - function Yt(e, t) { - var r = t.startPTS; - if (m(r)) { - var i, - n = 0; - t.sn > e.sn - ? ((n = r - e.start), (i = e)) - : ((n = e.start - r), (i = t)), - i.duration !== n && (i.duration = n); - } else - t.sn > e.sn - ? e.cc === t.cc && e.minEndPTS - ? (t.start = e.start + (e.minEndPTS - e.start)) - : (t.start = e.start + e.duration) - : (t.start = Math.max(e.start - t.duration, 0)); - } - function zt(e, t, r, i, n, s) { - i - r <= 0 && - (A.warn("Fragment should have a positive duration", t), - (i = r + t.duration), - (s = n + t.duration)); - var a = r, - o = i, - l = t.startPTS, - h = t.endPTS; - if (m(l)) { - var u = Math.abs(l - r); - m(t.deltaPTS) - ? (t.deltaPTS = Math.max(u, t.deltaPTS)) - : (t.deltaPTS = u), - (a = Math.max(r, l)), - (r = Math.min(r, l)), - (n = Math.min(n, t.startDTS)), - (o = Math.min(i, h)), - (i = Math.max(i, h)), - (s = Math.max(s, t.endDTS)); - } - var d = r - t.start; - 0 !== t.start && (t.start = r), - (t.duration = i - t.start), - (t.startPTS = r), - (t.maxStartPTS = a), - (t.startDTS = n), - (t.endPTS = i), - (t.minEndPTS = o), - (t.endDTS = s); - var c, - f = t.sn; - if (!e || f < e.startSN || f > e.endSN) return 0; - var g = f - e.startSN, - p = e.fragments; - for (p[g] = t, c = g; c > 0; c--) Yt(p[c], p[c - 1]); - for (c = g; c < p.length - 1; c++) Yt(p[c], p[c + 1]); - return ( - e.fragmentHint && Yt(p[p.length - 1], e.fragmentHint), - (e.PTSKnown = e.alignedSliding = !0), - d - ); - } - function Xt(e, t) { - for ( - var r = null, i = e.fragments, n = i.length - 1; - n >= 0; - n-- - ) { - var s = i[n].initSegment; - if (s) { - r = s; - break; - } - } - e.fragmentHint && delete e.fragmentHint.endPTS; - var a, - l, - h, - u, - d, - c = 0; - if ( - ((function (e, t, r) { - for ( - var i = t.skippedSegments, - n = Math.max(e.startSN, t.startSN) - t.startSN, - s = - (e.fragmentHint ? 1 : 0) + - (i ? t.endSN : Math.min(e.endSN, t.endSN)) - - t.startSN, - a = t.startSN - e.startSN, - o = t.fragmentHint - ? t.fragments.concat(t.fragmentHint) - : t.fragments, - l = e.fragmentHint - ? e.fragments.concat(e.fragmentHint) - : e.fragments, - h = n; - h <= s; - h++ - ) { - var u = l[a + h], - d = o[h]; - i && !d && h < i && (d = t.fragments[h] = u), - u && d && r(u, d); - } - })(e, t, function (e, i) { - e.relurl && (c = e.cc - i.cc), - m(e.startPTS) && - m(e.endPTS) && - ((i.start = i.startPTS = e.startPTS), - (i.startDTS = e.startDTS), - (i.maxStartPTS = e.maxStartPTS), - (i.endPTS = e.endPTS), - (i.endDTS = e.endDTS), - (i.minEndPTS = e.minEndPTS), - (i.duration = e.endPTS - e.startPTS), - i.duration && (a = i), - (t.PTSKnown = t.alignedSliding = !0)), - (i.elementaryStreams = e.elementaryStreams), - (i.loader = e.loader), - (i.stats = e.stats), - e.initSegment && - ((i.initSegment = e.initSegment), (r = e.initSegment)); - }), - r && - (t.fragmentHint - ? t.fragments.concat(t.fragmentHint) - : t.fragments - ).forEach(function (e) { - var t; - !e || - (e.initSegment && - e.initSegment.relurl !== - (null == (t = r) ? void 0 : t.relurl)) || - (e.initSegment = r); - }), - t.skippedSegments) - ) - if ( - ((t.deltaUpdateFailed = t.fragments.some(function (e) { - return !e; - })), - t.deltaUpdateFailed) - ) { - A.warn( - "[level-helper] Previous playlist missing segments skipped in delta playlist" - ); - for (var f = t.skippedSegments; f--; ) t.fragments.shift(); - (t.startSN = t.fragments[0].sn), - (t.startCC = t.fragments[0].cc); - } else - t.canSkipDateRanges && - (t.dateRanges = - ((l = e.dateRanges), - (h = t.dateRanges), - (u = t.recentlyRemovedDateranges), - (d = o({}, l)), - u && - u.forEach(function (e) { - delete d[e]; - }), - Object.keys(h).forEach(function (e) { - var t = new k(h[e].attr, d[e]); - t.isValid - ? (d[e] = t) - : A.warn( - 'Ignoring invalid Playlist Delta Update DATERANGE tag: "' + - JSON.stringify(h[e].attr) + - '"' - ); - }), - d)); - var g = t.fragments; - if (c) { - A.warn( - "discontinuity sliding from playlist, take drift into account" - ); - for (var p = 0; p < g.length; p++) g[p].cc += c; - } - t.skippedSegments && (t.startCC = t.fragments[0].cc), - (function (e, t, r) { - if (e && t) - for (var i = 0, n = 0, s = e.length; n <= s; n++) { - var a = e[n], - o = t[n + i]; - a && - o && - a.index === o.index && - a.fragment.sn === o.fragment.sn - ? r(a, o) - : i--; - } - })(e.partList, t.partList, function (e, t) { - (t.elementaryStreams = e.elementaryStreams), - (t.stats = e.stats); - }), - a - ? zt(t, a, a.startPTS, a.endPTS, a.startDTS, a.endDTS) - : Qt(e, t), - g.length && (t.totalduration = t.edge - g[0].start), - (t.driftStartTime = e.driftStartTime), - (t.driftStart = e.driftStart); - var v = t.advancedDateTime; - if (t.advanced && v) { - var y = t.edge; - t.driftStart || ((t.driftStartTime = v), (t.driftStart = y)), - (t.driftEndTime = v), - (t.driftEnd = y); - } else - (t.driftEndTime = e.driftEndTime), - (t.driftEnd = e.driftEnd), - (t.advancedDateTime = e.advancedDateTime); - } - function Qt(e, t) { - var r = t.startSN + t.skippedSegments - e.startSN, - i = e.fragments; - r < 0 || r >= i.length || Jt(t, i[r].start); - } - function Jt(e, t) { - if (t) { - for ( - var r = e.fragments, i = e.skippedSegments; - i < r.length; - i++ - ) - r[i].start += t; - e.fragmentHint && (e.fragmentHint.start += t); - } - } - function Zt(e, t, r) { - var i; - return null != e && e.details - ? er(null == (i = e.details) ? void 0 : i.partList, t, r) - : null; - } - function er(e, t, r) { - if (e) - for (var i = e.length; i--; ) { - var n = e[i]; - if (n.index === r && n.fragment.sn === t) return n; - } - return null; - } - function tr(e) { - e.forEach(function (e, t) { - var r = e.details; - null != r && - r.fragments && - r.fragments.forEach(function (e) { - e.level = t; - }); - }); - } - function rr(e) { - switch (e.details) { - case T.FRAG_LOAD_TIMEOUT: - case T.KEY_LOAD_TIMEOUT: - case T.LEVEL_LOAD_TIMEOUT: - case T.MANIFEST_LOAD_TIMEOUT: - return !0; - } - return !1; - } - function ir(e, t) { - var r = rr(t); - return e.default[(r ? "timeout" : "error") + "Retry"]; - } - function nr(e, t) { - var r = "linear" === e.backoff ? 1 : Math.pow(2, t); - return Math.min(r * e.retryDelayMs, e.maxRetryDelayMs); - } - function sr(e) { - return i(i({}, e), { errorRetry: null, timeoutRetry: null }); - } - function ar(e, t, r, i) { - if (!e) return !1; - var n = null == i ? void 0 : i.code, - s = - t < e.maxNumRetry && - ((function (e) { - return ( - (0 === e && !1 === navigator.onLine) || - (!!e && (e < 400 || e > 499)) - ); - })(n) || - !!r); - return e.shouldRetry ? e.shouldRetry(e, t, r, i, s) : s; - } - var or = function (e, t) { - for ( - var r = 0, i = e.length - 1, n = null, s = null; - r <= i; - - ) { - var a = t((s = e[(n = ((r + i) / 2) | 0)])); - if (a > 0) r = n + 1; - else { - if (!(a < 0)) return s; - i = n - 1; - } - } - return null; - }; - function lr(e, t, r, i, n) { - void 0 === r && (r = 0), - void 0 === i && (i = 0), - void 0 === n && (n = 0.005); - var s = null; - if (e) { - s = t[e.sn - t[0].sn + 1] || null; - var a = e.endDTS - r; - a > 0 && a < 15e-7 && (r += 15e-7); - } else 0 === r && 0 === t[0].start && (s = t[0]); - if ( - s && - (((!e || e.level === s.level) && 0 === hr(r, i, s)) || - (function (e, t, r) { - if ( - t && - 0 === t.start && - t.level < e.level && - (t.endPTS || 0) > 0 - ) { - var i = t.tagList.reduce(function (e, t) { - return "INF" === t[0] && (e += parseFloat(t[1])), e; - }, r); - return e.start <= i; - } - return !1; - })(s, e, Math.min(n, i))) - ) - return s; - var o = or(t, hr.bind(null, r, i)); - return !o || (o === e && s) ? s : o; - } - function hr(e, t, r) { - if ( - (void 0 === e && (e = 0), - void 0 === t && (t = 0), - r.start <= e && r.start + r.duration > e) - ) - return 0; - var i = Math.min(t, r.duration + (r.deltaPTS ? r.deltaPTS : 0)); - return r.start + r.duration - i <= e - ? 1 - : r.start - i > e && r.start - ? -1 - : 0; - } - function ur(e, t, r) { - var i = - 1e3 * Math.min(t, r.duration + (r.deltaPTS ? r.deltaPTS : 0)); - return (r.endProgramDateTime || 0) - i > e; - } - var dr = (function () { - function e(e) { - (this.hls = void 0), - (this.playlistError = 0), - (this.penalizedRenditions = {}), - (this.log = void 0), - (this.warn = void 0), - (this.error = void 0), - (this.hls = e), - (this.log = A.log.bind(A, "[info]:")), - (this.warn = A.warn.bind(A, "[warning]:")), - (this.error = A.error.bind(A, "[error]:")), - this.registerListeners(); - } - var t = e.prototype; - return ( - (t.registerListeners = function () { - var e = this.hls; - e.on(E.ERROR, this.onError, this), - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.LEVEL_UPDATED, this.onLevelUpdated, this); - }), - (t.unregisterListeners = function () { - var e = this.hls; - e && - (e.off(E.ERROR, this.onError, this), - e.off(E.ERROR, this.onErrorOut, this), - e.off(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.off(E.LEVEL_UPDATED, this.onLevelUpdated, this)); - }), - (t.destroy = function () { - this.unregisterListeners(), - (this.hls = null), - (this.penalizedRenditions = {}); - }), - (t.startLoad = function (e) {}), - (t.stopLoad = function () { - this.playlistError = 0; - }), - (t.getVariantLevelIndex = function (e) { - return (null == e ? void 0 : e.type) === Lt - ? e.level - : this.hls.loadLevel; - }), - (t.onManifestLoading = function () { - (this.playlistError = 0), (this.penalizedRenditions = {}); - }), - (t.onLevelUpdated = function () { - this.playlistError = 0; - }), - (t.onError = function (e, t) { - var r, i; - if (!t.fatal) { - var n = this.hls, - s = t.context; - switch (t.details) { - case T.FRAG_LOAD_ERROR: - case T.FRAG_LOAD_TIMEOUT: - case T.KEY_LOAD_ERROR: - case T.KEY_LOAD_TIMEOUT: - return void (t.errorAction = - this.getFragRetryOrSwitchAction(t)); - case T.FRAG_PARSING_ERROR: - if (null != (r = t.frag) && r.gap) - return void (t.errorAction = { - action: 0, - flags: 0, - }); - case T.FRAG_GAP: - case T.FRAG_DECRYPT_ERROR: - return ( - (t.errorAction = - this.getFragRetryOrSwitchAction(t)), - void (t.errorAction.action = 2) - ); - case T.LEVEL_EMPTY_ERROR: - case T.LEVEL_PARSING_ERROR: - var a, - o, - l = t.parent === Lt ? t.level : n.loadLevel; - return void (t.details === T.LEVEL_EMPTY_ERROR && - null != (a = t.context) && - null != (o = a.levelDetails) && - o.live - ? (t.errorAction = - this.getPlaylistRetryOrSwitchAction(t, l)) - : ((t.levelRetry = !1), - (t.errorAction = this.getLevelSwitchAction( - t, - l - )))); - case T.LEVEL_LOAD_ERROR: - case T.LEVEL_LOAD_TIMEOUT: - return void ( - "number" == - typeof (null == s ? void 0 : s.level) && - (t.errorAction = - this.getPlaylistRetryOrSwitchAction(t, s.level)) - ); - case T.AUDIO_TRACK_LOAD_ERROR: - case T.AUDIO_TRACK_LOAD_TIMEOUT: - case T.SUBTITLE_LOAD_ERROR: - case T.SUBTITLE_TRACK_LOAD_TIMEOUT: - if (s) { - var h = n.levels[n.loadLevel]; - if ( - h && - ((s.type === Tt && - h.hasAudioGroup(s.groupId)) || - (s.type === _t && - h.hasSubtitleGroup(s.groupId))) - ) - return ( - (t.errorAction = - this.getPlaylistRetryOrSwitchAction( - t, - n.loadLevel - )), - (t.errorAction.action = 2), - void (t.errorAction.flags = 1) - ); - } - return; - case T.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED: - var u = n.levels[n.loadLevel], - d = null == u ? void 0 : u.attrs["HDCP-LEVEL"]; - return void (d - ? (t.errorAction = { - action: 2, - flags: 2, - hdcpLevel: d, - }) - : this.keySystemError(t)); - case T.BUFFER_ADD_CODEC_ERROR: - case T.REMUX_ALLOC_ERROR: - case T.BUFFER_APPEND_ERROR: - return void (t.errorAction = - this.getLevelSwitchAction( - t, - null != (i = t.level) ? i : n.loadLevel - )); - case T.INTERNAL_EXCEPTION: - case T.BUFFER_APPENDING_ERROR: - case T.BUFFER_FULL_ERROR: - case T.LEVEL_SWITCH_ERROR: - case T.BUFFER_STALLED_ERROR: - case T.BUFFER_SEEK_OVER_HOLE: - case T.BUFFER_NUDGE_ON_STALL: - return void (t.errorAction = { - action: 0, - flags: 0, - }); - } - t.type === S.KEY_SYSTEM_ERROR && this.keySystemError(t); - } - }), - (t.keySystemError = function (e) { - var t = this.getVariantLevelIndex(e.frag); - (e.levelRetry = !1), - (e.errorAction = this.getLevelSwitchAction(e, t)); - }), - (t.getPlaylistRetryOrSwitchAction = function (e, t) { - var r = ir(this.hls.config.playlistLoadPolicy, e), - i = this.playlistError++; - if (ar(r, i, rr(e), e.response)) - return { - action: 5, - flags: 0, - retryConfig: r, - retryCount: i, - }; - var n = this.getLevelSwitchAction(e, t); - return r && ((n.retryConfig = r), (n.retryCount = i)), n; - }), - (t.getFragRetryOrSwitchAction = function (e) { - var t = this.hls, - r = this.getVariantLevelIndex(e.frag), - i = t.levels[r], - n = t.config, - s = n.fragLoadPolicy, - a = n.keyLoadPolicy, - o = ir(e.details.startsWith("key") ? a : s, e), - l = t.levels.reduce(function (e, t) { - return e + t.fragmentError; - }, 0); - if ( - i && - (e.details !== T.FRAG_GAP && i.fragmentError++, - ar(o, l, rr(e), e.response)) - ) - return { - action: 5, - flags: 0, - retryConfig: o, - retryCount: l, - }; - var h = this.getLevelSwitchAction(e, r); - return o && ((h.retryConfig = o), (h.retryCount = l)), h; - }), - (t.getLevelSwitchAction = function (e, t) { - var r = this.hls; - null == t && (t = r.loadLevel); - var i = this.hls.levels[t]; - if (i) { - var n, - s, - a = e.details; - i.loadError++, - a === T.BUFFER_APPEND_ERROR && i.fragmentError++; - var o = -1, - l = r.levels, - h = r.loadLevel, - u = r.minAutoLevel, - d = r.maxAutoLevel; - r.autoLevelEnabled || (r.loadLevel = -1); - for ( - var c, - f = null == (n = e.frag) ? void 0 : n.type, - g = - ((f === bt && a === T.FRAG_PARSING_ERROR) || - ("audio" === e.sourceBufferName && - (a === T.BUFFER_ADD_CODEC_ERROR || - a === T.BUFFER_APPEND_ERROR))) && - l.some(function (e) { - var t = e.audioCodec; - return i.audioCodec !== t; - }), - p = - "video" === e.sourceBufferName && - (a === T.BUFFER_ADD_CODEC_ERROR || - a === T.BUFFER_APPEND_ERROR) && - l.some(function (e) { - var t = e.codecSet, - r = e.audioCodec; - return i.codecSet !== t && i.audioCodec === r; - }), - m = null != (s = e.context) ? s : {}, - v = m.type, - y = m.groupId, - E = function () { - var t = (S + h) % l.length; - if ( - t !== h && - t >= u && - t <= d && - 0 === l[t].loadError - ) { - var r, - n, - s = l[t]; - if (a === T.FRAG_GAP && f === Lt && e.frag) { - var c = l[t].details; - if (c) { - var m = lr( - e.frag, - c.fragments, - e.frag.start - ); - if (null != m && m.gap) return 0; - } - } else { - if ( - (v === Tt && s.hasAudioGroup(y)) || - (v === _t && s.hasSubtitleGroup(y)) - ) - return 0; - if ( - (f === bt && - null != (r = i.audioGroups) && - r.some(function (e) { - return s.hasAudioGroup(e); - })) || - (f === Rt && - null != (n = i.subtitleGroups) && - n.some(function (e) { - return s.hasSubtitleGroup(e); - })) || - (g && i.audioCodec === s.audioCodec) || - (!g && i.audioCodec !== s.audioCodec) || - (p && i.codecSet === s.codecSet) - ) - return 0; - } - return (o = t), 1; - } - }, - S = l.length; - S-- && (0 === (c = E()) || 1 !== c); - - ); - if (o > -1 && r.loadLevel !== o) - return ( - (e.levelRetry = !0), - (this.playlistError = 0), - { action: 2, flags: 0, nextAutoLevel: o } - ); - } - return { action: 2, flags: 1 }; - }), - (t.onErrorOut = function (e, t) { - var r; - switch (null == (r = t.errorAction) ? void 0 : r.action) { - case 0: - break; - case 2: - this.sendAlternateToPenaltyBox(t), - t.errorAction.resolved || t.details === T.FRAG_GAP - ? /MediaSource readyState: ended/.test( - t.error.message - ) && - (this.warn( - 'MediaSource ended after "' + - t.sourceBufferName + - '" sourceBuffer append error. Attempting to recover from media error.' - ), - this.hls.recoverMediaError()) - : (t.fatal = !0); - } - t.fatal && this.hls.stopLoad(); - }), - (t.sendAlternateToPenaltyBox = function (e) { - var t = this.hls, - r = e.errorAction; - if (r) { - var i = r.flags, - n = r.hdcpLevel, - s = r.nextAutoLevel; - switch (i) { - case 0: - this.switchLevel(e, s); - break; - case 2: - n && - ((t.maxHdcpLevel = $t[$t.indexOf(n) - 1]), - (r.resolved = !0)), - this.warn( - 'Restricting playback to HDCP-LEVEL of "' + - t.maxHdcpLevel + - '" or lower' - ); - } - r.resolved || this.switchLevel(e, s); - } - }), - (t.switchLevel = function (e, t) { - void 0 !== t && - e.errorAction && - (this.warn( - "switching to level " + t + " after " + e.details - ), - (this.hls.nextAutoLevel = t), - (e.errorAction.resolved = !0), - (this.hls.nextLoadLevel = this.hls.nextAutoLevel)); - }), - e - ); - })(), - cr = (function () { - function e(e, t) { - (this.hls = void 0), - (this.timer = -1), - (this.requestScheduled = -1), - (this.canLoad = !1), - (this.log = void 0), - (this.warn = void 0), - (this.log = A.log.bind(A, t + ":")), - (this.warn = A.warn.bind(A, t + ":")), - (this.hls = e); - } - var t = e.prototype; - return ( - (t.destroy = function () { - this.clearTimer(), - (this.hls = this.log = this.warn = null); - }), - (t.clearTimer = function () { - -1 !== this.timer && - (self.clearTimeout(this.timer), (this.timer = -1)); - }), - (t.startLoad = function () { - (this.canLoad = !0), - (this.requestScheduled = -1), - this.loadPlaylist(); - }), - (t.stopLoad = function () { - (this.canLoad = !1), this.clearTimer(); - }), - (t.switchParams = function (e, t, r) { - var i = null == t ? void 0 : t.renditionReports; - if (i) { - for (var n = -1, s = 0; s < i.length; s++) { - var a = i[s], - o = void 0; - try { - o = new self.URL(a.URI, t.url).href; - } catch (e) { - A.warn( - "Could not construct new URL for Rendition Report: " + - e - ), - (o = a.URI || ""); - } - if (o === e) { - n = s; - break; - } - o === e.substring(0, o.length) && (n = s); - } - if (-1 !== n) { - var l = i[n], - h = - parseInt(l["LAST-MSN"]) || - (null == t ? void 0 : t.lastPartSn), - u = - parseInt(l["LAST-PART"]) || - (null == t ? void 0 : t.lastPartIndex); - if (this.hls.config.lowLatencyMode) { - var d = Math.min( - t.age - t.partTarget, - t.targetduration - ); - u >= 0 && d > t.partTarget && (u += 1); - } - var c = r && Wt(r); - return new Vt(h, u >= 0 ? u : void 0, c); - } - } - }), - (t.loadPlaylist = function (e) { - -1 === this.requestScheduled && - (this.requestScheduled = self.performance.now()); - }), - (t.shouldLoadPlaylist = function (e) { - return ( - this.canLoad && - !!e && - !!e.url && - (!e.details || e.details.live) - ); - }), - (t.shouldReloadPlaylist = function (e) { - return ( - -1 === this.timer && - -1 === this.requestScheduled && - this.shouldLoadPlaylist(e) - ); - }), - (t.playlistLoaded = function (e, t, r) { - var i = this, - n = t.details, - s = t.stats, - a = self.performance.now(), - o = s.loading.first - ? Math.max(0, a - s.loading.first) - : 0; - if ( - ((n.advancedDateTime = Date.now() - o), - n.live || (null != r && r.live)) - ) { - if ( - (n.reloaded(r), - r && - this.log( - "live playlist " + - e + - " " + - (n.advanced - ? "REFRESHED " + - n.lastPartSn + - "-" + - n.lastPartIndex - : n.updated - ? "UPDATED" - : "MISSED") - ), - r && n.fragments.length > 0 && Xt(r, n), - !this.canLoad || !n.live) - ) - return; - var l, - h = void 0, - u = void 0; - if (n.canBlockReload && n.endSN && n.advanced) { - var d = this.hls.config.lowLatencyMode, - c = n.lastPartSn, - f = n.endSN, - g = n.lastPartIndex, - p = c === f; - -1 !== g - ? ((h = p ? f + 1 : c), - (u = p ? (d ? 0 : g) : g + 1)) - : (h = f + 1); - var m = n.age, - v = m + n.ageHeader, - y = Math.min( - v - n.partTarget, - 1.5 * n.targetduration - ); - if (y > 0) { - if (r && y > r.tuneInGoal) - this.warn( - "CDN Tune-in goal increased from: " + - r.tuneInGoal + - " to: " + - y + - " with playlist age: " + - n.age - ), - (y = 0); - else { - var E = Math.floor(y / n.targetduration); - (h += E), - void 0 !== u && - (u += Math.round( - (y % n.targetduration) / n.partTarget - )), - this.log( - "CDN Tune-in age: " + - n.ageHeader + - "s last advanced " + - m.toFixed(2) + - "s goal: " + - y + - " skip sn " + - E + - " to part " + - u - ); - } - n.tuneInGoal = y; - } - if ( - ((l = this.getDeliveryDirectives( - n, - t.deliveryDirectives, - h, - u - )), - d || !p) - ) - return void this.loadPlaylist(l); - } else - (n.canBlockReload || n.canSkipUntil) && - (l = this.getDeliveryDirectives( - n, - t.deliveryDirectives, - h, - u - )); - var S = this.hls.mainForwardBufferInfo, - T = S ? S.end - S.len : 0, - _ = (function (e, t) { - void 0 === t && (t = 1 / 0); - var r = 1e3 * e.targetduration; - if (e.updated) { - var i = e.fragments; - if (i.length && 4 * r > t) { - var n = 1e3 * i[i.length - 1].duration; - n < r && (r = n); - } - } else r /= 2; - return Math.round(r); - })(n, 1e3 * (n.edge - T)); - n.updated && - a > this.requestScheduled + _ && - (this.requestScheduled = s.loading.start), - void 0 !== h && n.canBlockReload - ? (this.requestScheduled = - s.loading.first + - _ - - (1e3 * n.partTarget || 1e3)) - : -1 === this.requestScheduled || - this.requestScheduled + _ < a - ? (this.requestScheduled = a) - : this.requestScheduled - a <= 0 && - (this.requestScheduled += _); - var L = this.requestScheduled - a; - (L = Math.max(0, L)), - this.log( - "reload live playlist " + - e + - " in " + - Math.round(L) + - " ms" - ), - (this.timer = self.setTimeout(function () { - return i.loadPlaylist(l); - }, L)); - } else this.clearTimer(); - }), - (t.getDeliveryDirectives = function (e, t, r, i) { - var n = Wt(e); - return ( - null != t && - t.skip && - e.deltaUpdateFailed && - ((r = t.msn), (i = t.part), (n = "")), - new Vt(r, i, n) - ); - }), - (t.checkRetry = function (e) { - var t = this, - r = e.details, - i = rr(e), - n = e.errorAction, - s = n || {}, - a = s.action, - o = s.retryCount, - l = void 0 === o ? 0 : o, - h = s.retryConfig, - u = !!n && !!h && (5 === a || (!n.resolved && 2 === a)); - if (u) { - var d; - if (((this.requestScheduled = -1), l >= h.maxNumRetry)) - return !1; - if ( - i && - null != (d = e.context) && - d.deliveryDirectives - ) - this.warn( - "Retrying playlist loading " + - (l + 1) + - "/" + - h.maxNumRetry + - ' after "' + - r + - '" without delivery-directives' - ), - this.loadPlaylist(); - else { - var c = nr(h, l); - (this.timer = self.setTimeout(function () { - return t.loadPlaylist(); - }, c)), - this.warn( - "Retrying playlist loading " + - (l + 1) + - "/" + - h.maxNumRetry + - ' after "' + - r + - '" in ' + - c + - "ms" - ); - } - (e.levelRetry = !0), (n.resolved = !0); - } - return u; - }), - e - ); - })(), - fr = (function () { - function e(e, t, r) { - void 0 === t && (t = 0), - void 0 === r && (r = 0), - (this.halfLife = void 0), - (this.alpha_ = void 0), - (this.estimate_ = void 0), - (this.totalWeight_ = void 0), - (this.halfLife = e), - (this.alpha_ = e ? Math.exp(Math.log(0.5) / e) : 0), - (this.estimate_ = t), - (this.totalWeight_ = r); - } - var t = e.prototype; - return ( - (t.sample = function (e, t) { - var r = Math.pow(this.alpha_, e); - (this.estimate_ = t * (1 - r) + r * this.estimate_), - (this.totalWeight_ += e); - }), - (t.getTotalWeight = function () { - return this.totalWeight_; - }), - (t.getEstimate = function () { - if (this.alpha_) { - var e = 1 - Math.pow(this.alpha_, this.totalWeight_); - if (e) return this.estimate_ / e; - } - return this.estimate_; - }), - e - ); - })(), - gr = (function () { - function e(e, t, r, i) { - void 0 === i && (i = 100), - (this.defaultEstimate_ = void 0), - (this.minWeight_ = void 0), - (this.minDelayMs_ = void 0), - (this.slow_ = void 0), - (this.fast_ = void 0), - (this.defaultTTFB_ = void 0), - (this.ttfb_ = void 0), - (this.defaultEstimate_ = r), - (this.minWeight_ = 0.001), - (this.minDelayMs_ = 50), - (this.slow_ = new fr(e)), - (this.fast_ = new fr(t)), - (this.defaultTTFB_ = i), - (this.ttfb_ = new fr(e)); - } - var t = e.prototype; - return ( - (t.update = function (e, t) { - var r = this.slow_, - i = this.fast_, - n = this.ttfb_; - r.halfLife !== e && - (this.slow_ = new fr( - e, - r.getEstimate(), - r.getTotalWeight() - )), - i.halfLife !== t && - (this.fast_ = new fr( - t, - i.getEstimate(), - i.getTotalWeight() - )), - n.halfLife !== e && - (this.ttfb_ = new fr( - e, - n.getEstimate(), - n.getTotalWeight() - )); - }), - (t.sample = function (e, t) { - var r = (e = Math.max(e, this.minDelayMs_)) / 1e3, - i = (8 * t) / r; - this.fast_.sample(r, i), this.slow_.sample(r, i); - }), - (t.sampleTTFB = function (e) { - var t = e / 1e3, - r = Math.sqrt(2) * Math.exp(-Math.pow(t, 2) / 2); - this.ttfb_.sample(r, Math.max(e, 5)); - }), - (t.canEstimate = function () { - return this.fast_.getTotalWeight() >= this.minWeight_; - }), - (t.getEstimate = function () { - return this.canEstimate() - ? Math.min( - this.fast_.getEstimate(), - this.slow_.getEstimate() - ) - : this.defaultEstimate_; - }), - (t.getEstimateTTFB = function () { - return this.ttfb_.getTotalWeight() >= this.minWeight_ - ? this.ttfb_.getEstimate() - : this.defaultTTFB_; - }), - (t.destroy = function () {}), - e - ); - })(), - pr = { - supported: !0, - configurations: [], - decodingInfoResults: [ - { supported: !0, powerEfficient: !0, smooth: !0 }, - ], - }, - mr = {}; - function vr(e, t, r) { - var n = e.videoCodec, - s = e.audioCodec; - if (!n || !s || !r) return Promise.resolve(pr); - var a = { - width: e.width, - height: e.height, - bitrate: Math.ceil( - Math.max(0.9 * e.bitrate, e.averageBitrate) - ), - framerate: e.frameRate || 30, - }, - o = e.videoRange; - "SDR" !== o && (a.transferFunction = o.toLowerCase()); - var l = n.split(",").map(function (e) { - return { - type: "media-source", - video: i(i({}, a), {}, { contentType: Ze(e, "video") }), - }; - }); - return ( - s && - e.audioGroups && - e.audioGroups.forEach(function (e) { - var r; - e && - (null == (r = t.groups[e]) || - r.tracks.forEach(function (t) { - if (t.groupId === e) { - var r = t.channels || "", - i = parseFloat(r); - m(i) && - i > 2 && - l.push.apply( - l, - s.split(",").map(function (e) { - return { - type: "media-source", - audio: { - contentType: Ze(e, "audio"), - channels: "" + i, - }, - }; - }) - ); - } - })); - }), - Promise.all( - l.map(function (e) { - var t = (function (e) { - var t = e.audio, - r = e.video, - i = r || t; - if (i) { - var n = i.contentType.split('"')[1]; - if (r) - return ( - "r" + - r.height + - "x" + - r.width + - "f" + - Math.ceil(r.framerate) + - (r.transferFunction || "sd") + - "_" + - n + - "_" + - Math.ceil(r.bitrate / 1e5) - ); - if (t) - return ( - "c" + - t.channels + - (t.spatialRendering ? "s" : "n") + - "_" + - n - ); - } - return ""; - })(e); - return mr[t] || (mr[t] = r.decodingInfo(e)); - }) - ) - .then(function (e) { - return { - supported: !e.some(function (e) { - return !e.supported; - }), - configurations: l, - decodingInfoResults: e, - }; - }) - .catch(function (e) { - return { - supported: !1, - configurations: l, - decodingInfoResults: [], - error: e, - }; - }) - ); - } - function yr(e, t) { - A.log( - '[abr] start candidates with "' + e + '" ignored because ' + t - ); - } - function Er(e, t, r) { - if ("attrs" in e) { - var i = t.indexOf(e); - if (-1 !== i) return i; - } - for (var n = 0; n < t.length; n++) if (Sr(e, t[n], r)) return n; - return -1; - } - function Sr(e, t, r) { - var i = e.groupId, - n = e.name, - s = e.lang, - a = e.assocLang, - o = e.characteristics, - l = e.default, - h = e.forced; - return ( - (void 0 === i || t.groupId === i) && - (void 0 === n || t.name === n) && - (void 0 === s || t.lang === s) && - (void 0 === s || t.assocLang === a) && - (void 0 === l || t.default === l) && - (void 0 === h || t.forced === h) && - (void 0 === o || - (function (e, t) { - void 0 === t && (t = ""); - var r = e.split(","), - i = t.split(","); - return ( - r.length === i.length && - !r.some(function (e) { - return -1 === i.indexOf(e); - }) - ); - })(o, t.characteristics)) && - (void 0 === r || r(e, t)) - ); - } - function Tr(e, t) { - var r = e.audioCodec, - i = e.channels; - return !( - (void 0 !== r && - (t.audioCodec || "").substring(0, 4) !== - r.substring(0, 4)) || - (void 0 !== i && i !== (t.channels || "2")) - ); - } - function _r(e, t, r) { - for (var i = t; i; i--) if (r(e[i])) return i; - for (var n = t + 1; n < e.length; n++) if (r(e[n])) return n; - return -1; - } - var Lr = (function () { - function e(e) { - var t = this; - (this.hls = void 0), - (this.lastLevelLoadSec = 0), - (this.lastLoadedFragLevel = -1), - (this.firstSelection = -1), - (this._nextAutoLevel = -1), - (this.nextAutoLevelKey = ""), - (this.audioTracksByGroup = null), - (this.codecTiers = null), - (this.timer = -1), - (this.fragCurrent = null), - (this.partCurrent = null), - (this.bitrateTestDelay = 0), - (this.bwEstimator = void 0), - (this._abandonRulesCheck = function () { - var e = t.fragCurrent, - r = t.partCurrent, - i = t.hls, - n = i.autoLevelEnabled, - s = i.media; - if (e && s) { - var a = performance.now(), - o = r ? r.stats : e.stats, - l = r ? r.duration : e.duration, - h = a - o.loading.start, - u = i.minAutoLevel; - if ( - o.aborted || - (o.loaded && o.loaded === o.total) || - e.level <= u - ) - return t.clearTimer(), void (t._nextAutoLevel = -1); - if ( - n && - !s.paused && - s.playbackRate && - s.readyState - ) { - var d = i.mainForwardBufferInfo; - if (null !== d) { - var c = t.bwEstimator.getEstimateTTFB(), - f = Math.abs(s.playbackRate); - if (!(h <= Math.max(c, (l / (2 * f)) * 1e3))) { - var g = d.len / f, - p = o.loading.first - ? o.loading.first - o.loading.start - : -1, - v = o.loaded && p > -1, - y = t.getBwEstimate(), - S = i.levels, - T = S[e.level], - _ = - o.total || - Math.max( - o.loaded, - Math.round((l * T.averageBitrate) / 8) - ), - L = v ? h - p : h; - L < 1 && - v && - (L = Math.min(h, (8 * o.loaded) / y)); - var b = v ? (1e3 * o.loaded) / L : 0, - R = b - ? (_ - o.loaded) / b - : (8 * _) / y + c / 1e3; - if (!(R <= g)) { - var w, - P = b ? 8 * b : y, - I = Number.POSITIVE_INFINITY; - for (w = e.level - 1; w > u; w--) { - var C = S[w].maxBitrate; - if ( - (I = t.getTimeToLoadFrag( - c / 1e3, - P, - l * C, - !S[w].details - )) < g - ) - break; - } - if (!(I >= R || I > 10 * l)) { - (i.nextLoadLevel = i.nextAutoLevel = w), - v - ? t.bwEstimator.sample( - h - Math.min(c, p), - o.loaded - ) - : t.bwEstimator.sampleTTFB(h); - var k = S[w].maxBitrate; - t.getBwEstimate() * - t.hls.config.abrBandWidthUpFactor > - k && t.resetEstimator(k), - t.clearTimer(), - A.warn( - "[abr] Fragment " + - e.sn + - (r ? " part " + r.index : "") + - " of level " + - e.level + - " is loading too slowly;\n Time to underbuffer: " + - g.toFixed(3) + - " s\n Estimated load time for current fragment: " + - R.toFixed(3) + - " s\n Estimated load time for down switch fragment: " + - I.toFixed(3) + - " s\n TTFB estimate: " + - (0 | p) + - " ms\n Current BW estimate: " + - (m(y) ? 0 | y : "Unknown") + - " bps\n New BW estimate: " + - (0 | t.getBwEstimate()) + - " bps\n Switching to level " + - w + - " @ " + - (0 | k) + - " bps" - ), - i.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED, { - frag: e, - part: r, - stats: o, - }); - } - } - } - } - } - } - }), - (this.hls = e), - (this.bwEstimator = this.initEstimator()), - this.registerListeners(); - } - var t = e.prototype; - return ( - (t.resetEstimator = function (e) { - e && - (A.log("setting initial bwe to " + e), - (this.hls.config.abrEwmaDefaultEstimate = e)), - (this.firstSelection = -1), - (this.bwEstimator = this.initEstimator()); - }), - (t.initEstimator = function () { - var e = this.hls.config; - return new gr( - e.abrEwmaSlowVoD, - e.abrEwmaFastVoD, - e.abrEwmaDefaultEstimate - ); - }), - (t.registerListeners = function () { - var e = this.hls; - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.FRAG_LOADING, this.onFragLoading, this), - e.on(E.FRAG_LOADED, this.onFragLoaded, this), - e.on(E.FRAG_BUFFERED, this.onFragBuffered, this), - e.on(E.LEVEL_SWITCHING, this.onLevelSwitching, this), - e.on(E.LEVEL_LOADED, this.onLevelLoaded, this), - e.on(E.LEVELS_UPDATED, this.onLevelsUpdated, this), - e.on( - E.MAX_AUTO_LEVEL_UPDATED, - this.onMaxAutoLevelUpdated, - this - ), - e.on(E.ERROR, this.onError, this); - }), - (t.unregisterListeners = function () { - var e = this.hls; - e && - (e.off( - E.MANIFEST_LOADING, - this.onManifestLoading, - this - ), - e.off(E.FRAG_LOADING, this.onFragLoading, this), - e.off(E.FRAG_LOADED, this.onFragLoaded, this), - e.off(E.FRAG_BUFFERED, this.onFragBuffered, this), - e.off(E.LEVEL_SWITCHING, this.onLevelSwitching, this), - e.off(E.LEVEL_LOADED, this.onLevelLoaded, this), - e.off(E.LEVELS_UPDATED, this.onLevelsUpdated, this), - e.off( - E.MAX_AUTO_LEVEL_UPDATED, - this.onMaxAutoLevelUpdated, - this - ), - e.off(E.ERROR, this.onError, this)); - }), - (t.destroy = function () { - this.unregisterListeners(), - this.clearTimer(), - (this.hls = this._abandonRulesCheck = null), - (this.fragCurrent = this.partCurrent = null); - }), - (t.onManifestLoading = function (e, t) { - (this.lastLoadedFragLevel = -1), - (this.firstSelection = -1), - (this.lastLevelLoadSec = 0), - (this.fragCurrent = this.partCurrent = null), - this.onLevelsUpdated(), - this.clearTimer(); - }), - (t.onLevelsUpdated = function () { - this.lastLoadedFragLevel > -1 && - this.fragCurrent && - (this.lastLoadedFragLevel = this.fragCurrent.level), - (this._nextAutoLevel = -1), - this.onMaxAutoLevelUpdated(), - (this.codecTiers = null), - (this.audioTracksByGroup = null); - }), - (t.onMaxAutoLevelUpdated = function () { - (this.firstSelection = -1), (this.nextAutoLevelKey = ""); - }), - (t.onFragLoading = function (e, t) { - var r, - i = t.frag; - this.ignoreFragment(i) || - (i.bitrateTest || - ((this.fragCurrent = i), - (this.partCurrent = null != (r = t.part) ? r : null)), - this.clearTimer(), - (this.timer = self.setInterval( - this._abandonRulesCheck, - 100 - ))); - }), - (t.onLevelSwitching = function (e, t) { - this.clearTimer(); - }), - (t.onError = function (e, t) { - if (!t.fatal) - switch (t.details) { - case T.BUFFER_ADD_CODEC_ERROR: - case T.BUFFER_APPEND_ERROR: - (this.lastLoadedFragLevel = -1), - (this.firstSelection = -1); - break; - case T.FRAG_LOAD_TIMEOUT: - var r = t.frag, - i = this.fragCurrent, - n = this.partCurrent; - if ( - r && - i && - r.sn === i.sn && - r.level === i.level - ) { - var s = performance.now(), - a = n ? n.stats : r.stats, - o = s - a.loading.start, - l = a.loading.first - ? a.loading.first - a.loading.start - : -1; - if (a.loaded && l > -1) { - var h = this.bwEstimator.getEstimateTTFB(); - this.bwEstimator.sample( - o - Math.min(h, l), - a.loaded - ); - } else this.bwEstimator.sampleTTFB(o); - } - } - }), - (t.getTimeToLoadFrag = function (e, t, r, i) { - return e + r / t + (i ? this.lastLevelLoadSec : 0); - }), - (t.onLevelLoaded = function (e, t) { - var r = this.hls.config, - i = t.stats.loading, - n = i.end - i.start; - m(n) && (this.lastLevelLoadSec = n / 1e3), - t.details.live - ? this.bwEstimator.update( - r.abrEwmaSlowLive, - r.abrEwmaFastLive - ) - : this.bwEstimator.update( - r.abrEwmaSlowVoD, - r.abrEwmaFastVoD - ); - }), - (t.onFragLoaded = function (e, t) { - var r = t.frag, - i = t.part, - n = i ? i.stats : r.stats; - if ( - (r.type === Lt && - this.bwEstimator.sampleTTFB( - n.loading.first - n.loading.start - ), - !this.ignoreFragment(r)) - ) { - if ( - (this.clearTimer(), - r.level === this._nextAutoLevel && - (this._nextAutoLevel = -1), - (this.firstSelection = -1), - this.hls.config.abrMaxWithRealBitrate) - ) { - var s = i ? i.duration : r.duration, - a = this.hls.levels[r.level], - o = (a.loaded ? a.loaded.bytes : 0) + n.loaded, - l = (a.loaded ? a.loaded.duration : 0) + s; - (a.loaded = { bytes: o, duration: l }), - (a.realBitrate = Math.round((8 * o) / l)); - } - if (r.bitrateTest) { - var h = { stats: n, frag: r, part: i, id: r.type }; - this.onFragBuffered(E.FRAG_BUFFERED, h), - (r.bitrateTest = !1); - } else this.lastLoadedFragLevel = r.level; - } - }), - (t.onFragBuffered = function (e, t) { - var r = t.frag, - i = t.part, - n = null != i && i.stats.loaded ? i.stats : r.stats; - if (!n.aborted && !this.ignoreFragment(r)) { - var s = - n.parsing.end - - n.loading.start - - Math.min( - n.loading.first - n.loading.start, - this.bwEstimator.getEstimateTTFB() - ); - this.bwEstimator.sample(s, n.loaded), - (n.bwEstimate = this.getBwEstimate()), - r.bitrateTest - ? (this.bitrateTestDelay = s / 1e3) - : (this.bitrateTestDelay = 0); - } - }), - (t.ignoreFragment = function (e) { - return e.type !== Lt || "initSegment" === e.sn; - }), - (t.clearTimer = function () { - this.timer > -1 && - (self.clearInterval(this.timer), (this.timer = -1)); - }), - (t.getAutoLevelKey = function () { - return ( - this.getBwEstimate() + - "_" + - this.getStarvationDelay().toFixed(2) - ); - }), - (t.getNextABRAutoLevel = function () { - var e = this.fragCurrent, - t = this.partCurrent, - r = this.hls, - i = r.maxAutoLevel, - n = r.config, - s = r.minAutoLevel, - a = t ? t.duration : e ? e.duration : 0, - o = this.getBwEstimate(), - l = this.getStarvationDelay(), - h = n.abrBandWidthFactor, - u = n.abrBandWidthUpFactor; - if (l) { - var d = this.findBestLevel(o, s, i, l, 0, h, u); - if (d >= 0) return d; - } - var c = a - ? Math.min(a, n.maxStarvationDelay) - : n.maxStarvationDelay; - if (!l) { - var f = this.bitrateTestDelay; - f && - ((c = - (a - ? Math.min(a, n.maxLoadingDelay) - : n.maxLoadingDelay) - f), - A.info( - "[abr] bitrate test took " + - Math.round(1e3 * f) + - "ms, set first fragment max fetchDuration to " + - Math.round(1e3 * c) + - " ms" - ), - (h = u = 1)); - } - var g = this.findBestLevel(o, s, i, l, c, h, u); - if ( - (A.info( - "[abr] " + - (l ? "rebuffering expected" : "buffer is empty") + - ", optimal quality level " + - g - ), - g > -1) - ) - return g; - var p = r.levels[s], - m = r.levels[r.loadLevel]; - return (null == p ? void 0 : p.bitrate) < - (null == m ? void 0 : m.bitrate) - ? s - : r.loadLevel; - }), - (t.getStarvationDelay = function () { - var e = this.hls, - t = e.media; - if (!t) return 1 / 0; - var r = - t && 0 !== t.playbackRate - ? Math.abs(t.playbackRate) - : 1, - i = e.mainForwardBufferInfo; - return (i ? i.len : 0) / r; - }), - (t.getBwEstimate = function () { - return this.bwEstimator.canEstimate() - ? this.bwEstimator.getEstimate() - : this.hls.config.abrEwmaDefaultEstimate; - }), - (t.findBestLevel = function (e, t, r, i, n, s, a) { - var o, - l = this, - h = i + n, - u = this.lastLoadedFragLevel, - d = -1 === u ? this.hls.firstLevel : u, - c = this.fragCurrent, - f = this.partCurrent, - g = this.hls, - p = g.levels, - v = g.allAudioTracks, - y = g.loadLevel, - E = g.config; - if (1 === p.length) return 0; - var S, - T = p[d], - _ = !(null == T || null == (o = T.details) || !o.live), - L = -1 === y || -1 === u, - b = "SDR", - R = (null == T ? void 0 : T.frameRate) || 0, - w = E.audioPreference, - P = E.videoPreference, - I = - this.audioTracksByGroup || - (this.audioTracksByGroup = (function (e) { - return e.reduce( - function (e, t) { - var r = e.groups[t.groupId]; - r || - (r = e.groups[t.groupId] = - { - tracks: [], - channels: { 2: 0 }, - hasDefault: !1, - hasAutoSelect: !1, - }), - r.tracks.push(t); - var i = t.channels || "2"; - return ( - (r.channels[i] = (r.channels[i] || 0) + 1), - (r.hasDefault = r.hasDefault || t.default), - (r.hasAutoSelect = - r.hasAutoSelect || t.autoselect), - r.hasDefault && (e.hasDefaultAudio = !0), - r.hasAutoSelect && - (e.hasAutoSelectAudio = !0), - e - ); - }, - { - hasDefaultAudio: !1, - hasAutoSelectAudio: !1, - groups: {}, - } - ); - })(v)); - if (L) { - if (-1 !== this.firstSelection) - return this.firstSelection; - var C = - this.codecTiers || - (this.codecTiers = (function (e, t, r, i) { - return e.slice(r, i + 1).reduce(function (e, r) { - if (!r.codecSet) return e; - var i = r.audioGroups, - n = e[r.codecSet]; - n || - (e[r.codecSet] = n = - { - minBitrate: 1 / 0, - minHeight: 1 / 0, - minFramerate: 1 / 0, - maxScore: 0, - videoRanges: { SDR: 0 }, - channels: { 2: 0 }, - hasDefaultAudio: !i, - fragmentError: 0, - }), - (n.minBitrate = Math.min( - n.minBitrate, - r.bitrate - )); - var s = Math.min(r.height, r.width); - return ( - (n.minHeight = Math.min(n.minHeight, s)), - (n.minFramerate = Math.min( - n.minFramerate, - r.frameRate - )), - (n.maxScore = Math.max(n.maxScore, r.score)), - (n.fragmentError += r.fragmentError), - (n.videoRanges[r.videoRange] = - (n.videoRanges[r.videoRange] || 0) + 1), - i && - i.forEach(function (e) { - if (e) { - var r = t.groups[e]; - r && - ((n.hasDefaultAudio = - n.hasDefaultAudio || - t.hasDefaultAudio - ? r.hasDefault - : r.hasAutoSelect || - (!t.hasDefaultAudio && - !t.hasAutoSelectAudio)), - Object.keys(r.channels).forEach( - function (e) { - n.channels[e] = - (n.channels[e] || 0) + - r.channels[e]; - } - )); - } - }), - e - ); - }, {}); - })(p, I, t, r)), - k = (function (e, t, r, i, n) { - for ( - var s = Object.keys(e), - a = null == i ? void 0 : i.channels, - o = null == i ? void 0 : i.audioCodec, - l = a && 2 === parseInt(a), - h = !0, - u = !1, - d = 1 / 0, - c = 1 / 0, - f = 1 / 0, - g = 0, - p = [], - v = (function (e, t) { - var r = !1, - i = []; - return ( - e && ((r = "SDR" !== e), (i = [e])), - t && - ((i = - t.allowedVideoRanges || Kt.slice(0)), - (i = (r = - void 0 !== t.preferHDR - ? t.preferHDR - : (function () { - if ( - "function" == typeof matchMedia - ) { - var e = matchMedia( - "(dynamic-range: high)" - ), - t = matchMedia("bad query"); - if (e.media !== t.media) - return !0 === e.matches; - } - return !1; - })()) - ? i.filter(function (e) { - return "SDR" !== e; - }) - : ["SDR"])), - { preferHDR: r, allowedVideoRanges: i } - ); - })(t, n), - y = v.preferHDR, - E = v.allowedVideoRanges, - S = function () { - var t = e[s[T]]; - (h = t.channels[2] > 0), - (d = Math.min(d, t.minHeight)), - (c = Math.min(c, t.minFramerate)), - (f = Math.min(f, t.minBitrate)); - var r = E.filter(function (e) { - return t.videoRanges[e] > 0; - }); - r.length > 0 && ((u = !0), (p = r)); - }, - T = s.length; - T--; - - ) - S(); - (d = m(d) ? d : 0), (c = m(c) ? c : 0); - var _ = Math.max(1080, d), - L = Math.max(30, c); - return ( - (f = m(f) ? f : r), - (r = Math.max(f, r)), - u || ((t = void 0), (p = [])), - { - codecSet: s.reduce(function (t, i) { - var n = e[i]; - if (i === t) return t; - if (n.minBitrate > r) - return ( - yr( - i, - "min bitrate of " + - n.minBitrate + - " > current estimate of " + - r - ), - t - ); - if (!n.hasDefaultAudio) - return ( - yr( - i, - "no renditions with default or auto-select sound found" - ), - t - ); - if ( - o && - i.indexOf(o.substring(0, 4)) % 5 != 0 - ) - return ( - yr( - i, - 'audio codec preference "' + - o + - '" not found' - ), - t - ); - if (a && !l) { - if (!n.channels[a]) - return ( - yr( - i, - "no renditions with " + - a + - " channel sound found (channels options: " + - Object.keys(n.channels) + - ")" - ), - t - ); - } else if ((!o || l) && h && 0 === n.channels[2]) return yr(i, "no renditions with stereo sound found"), t; - return n.minHeight > _ - ? (yr( - i, - "min resolution of " + - n.minHeight + - " > maximum of " + - _ - ), - t) - : n.minFramerate > L - ? (yr( - i, - "min framerate of " + - n.minFramerate + - " > maximum of " + - L - ), - t) - : p.some(function (e) { - return n.videoRanges[e] > 0; - }) - ? n.maxScore < g - ? (yr( - i, - "max score of " + - n.maxScore + - " < selected max of " + - g - ), - t) - : t && - (tt(i) >= tt(t) || - n.fragmentError > e[t].fragmentError) - ? t - : ((g = n.maxScore), i) - : (yr( - i, - "no variants with VIDEO-RANGE of " + - JSON.stringify(p) + - " found" - ), - t); - }, void 0), - videoRanges: p, - preferHDR: y, - minFramerate: c, - minBitrate: f, - } - ); - })(C, b, e, w, P), - D = k.codecSet, - M = k.videoRanges, - x = k.minFramerate, - O = k.minBitrate, - F = k.preferHDR; - (S = D), - (b = F ? M[M.length - 1] : M[0]), - (R = x), - (e = Math.max(e, O)), - A.log("[abr] picked start tier " + JSON.stringify(k)); - } else - (S = null == T ? void 0 : T.codecSet), - (b = null == T ? void 0 : T.videoRange); - for ( - var N, - B = f ? f.duration : c ? c.duration : 0, - U = this.bwEstimator.getEstimateTTFB() / 1e3, - G = [], - H = function () { - var t, - o = p[$], - c = $ > d; - if (!o) return 0; - if ( - E.useMediaCapabilities && - !o.supportedResult && - !o.supportedPromise - ) { - var g = navigator.mediaCapabilities; - "function" == - typeof (null == g ? void 0 : g.decodingInfo) && - (function (e, t, r, i, n, s) { - var a = e.audioCodec ? e.audioGroups : null, - o = null == s ? void 0 : s.audioCodec, - l = null == s ? void 0 : s.channels, - h = l ? parseInt(l) : o ? 1 / 0 : 2, - u = null; - if (null != a && a.length) - try { - u = - 1 === a.length && a[0] - ? t.groups[a[0]].channels - : a.reduce( - function (e, r) { - if (r) { - var i = t.groups[r]; - if (!i) - throw new Error( - "Audio track group " + - r + - " not found" - ); - Object.keys(i.channels).forEach( - function (t) { - e[t] = - (e[t] || 0) + - i.channels[t]; - } - ); - } - return e; - }, - { 2: 0 } - ); - } catch (e) { - return !0; - } - return ( - (void 0 !== e.videoCodec && - ((e.width > 1920 && e.height > 1088) || - (e.height > 1920 && e.width > 1088) || - e.frameRate > Math.max(i, 30) || - ("SDR" !== e.videoRange && - e.videoRange !== r) || - e.bitrate > Math.max(n, 8e6))) || - (!!u && - m(h) && - Object.keys(u).some(function (e) { - return parseInt(e) > h; - })) - ); - })(o, I, b, R, e, w) - ? ((o.supportedPromise = vr(o, I, g)), - o.supportedPromise.then(function (e) { - if (l.hls) { - o.supportedResult = e; - var t = l.hls.levels, - r = t.indexOf(o); - e.error - ? A.warn( - '[abr] MediaCapabilities decodingInfo error: "' + - e.error + - '" for level ' + - r + - " " + - JSON.stringify(e) - ) - : e.supported || - (A.warn( - "[abr] Unsupported MediaCapabilities decodingInfo result for level " + - r + - " " + - JSON.stringify(e) - ), - r > -1 && - t.length > 1 && - (A.log( - "[abr] Removing unsupported level " + - r - ), - l.hls.removeLevel(r))); - } - })) - : (o.supportedResult = pr); - } - if ( - (S && o.codecSet !== S) || - (b && o.videoRange !== b) || - (c && R > o.frameRate) || - (!c && R > 0 && R < o.frameRate) || - (o.supportedResult && - (null == - (t = o.supportedResult.decodingInfoResults) || - !t[0].smooth)) - ) - return G.push($), 0; - var v, - P = o.details, - C = - (f - ? null == P - ? void 0 - : P.partTarget - : null == P - ? void 0 - : P.averagetargetduration) || B; - v = c ? a * e : s * e; - var k = - B && i >= 2 * B && 0 === n - ? p[$].averageBitrate - : p[$].maxBitrate, - D = l.getTimeToLoadFrag( - U, - v, - k * C, - void 0 === P - ); - if ( - v >= k && - ($ === u || - (0 === o.loadError && 0 === o.fragmentError)) && - (D <= U || - !m(D) || - (_ && !l.bitrateTestDelay) || - D < h) - ) { - var M = l.forcedAutoLevel; - return ( - $ === y || - (-1 !== M && M === y) || - (G.length && - A.trace( - "[abr] Skipped level(s) " + - G.join(",") + - " of " + - r + - ' max with CODECS and VIDEO-RANGE:"' + - p[G[0]].codecs + - '" ' + - p[G[0]].videoRange + - '; not compatible with "' + - T.codecs + - '" ' + - b - ), - A.info( - "[abr] switch candidate:" + - d + - "->" + - $ + - " adjustedbw(" + - Math.round(v) + - ")-bitrate=" + - Math.round(v - k) + - " ttfb:" + - U.toFixed(1) + - " avgDuration:" + - C.toFixed(1) + - " maxFetchDuration:" + - h.toFixed(1) + - " fetchDuration:" + - D.toFixed(1) + - " firstSelection:" + - L + - " codecSet:" + - S + - " videoRange:" + - b + - " hls.loadLevel:" + - y - )), - L && (l.firstSelection = $), - { v: $ } - ); - } - }, - $ = r; - $ >= t; - $-- - ) - if (0 !== (N = H()) && N) return N.v; - return -1; - }), - a(e, [ - { - key: "firstAutoLevel", - get: function () { - var e = this.hls, - t = e.maxAutoLevel, - r = e.minAutoLevel, - i = this.getBwEstimate(), - n = this.hls.config.maxStarvationDelay, - s = this.findBestLevel(i, r, t, 0, n, 1, 1); - if (s > -1) return s; - var a = this.hls.firstLevel, - o = Math.min(Math.max(a, r), t); - return ( - A.warn( - "[abr] Could not find best starting auto level. Defaulting to first in playlist " + - a + - " clamped to " + - o - ), - o - ); - }, - }, - { - key: "forcedAutoLevel", - get: function () { - return this.nextAutoLevelKey - ? -1 - : this._nextAutoLevel; - }, - }, - { - key: "nextAutoLevel", - get: function () { - var e = this.forcedAutoLevel, - t = this.bwEstimator.canEstimate(), - r = this.lastLoadedFragLevel > -1; - if ( - !( - -1 === e || - (t && - r && - this.nextAutoLevelKey !== - this.getAutoLevelKey()) - ) - ) - return e; - var i = - t && r - ? this.getNextABRAutoLevel() - : this.firstAutoLevel; - if (-1 !== e) { - var n = this.hls.levels; - if ( - n.length > Math.max(e, i) && - n[e].loadError <= n[i].loadError - ) - return e; - } - return ( - (this._nextAutoLevel = i), - (this.nextAutoLevelKey = this.getAutoLevelKey()), - i - ); - }, - set: function (e) { - var t = this.hls, - r = t.maxAutoLevel, - i = t.minAutoLevel, - n = Math.min(Math.max(e, i), r); - this._nextAutoLevel !== n && - ((this.nextAutoLevelKey = ""), - (this._nextAutoLevel = n)); - }, - }, - ]), - e - ); - })(), - br = (function () { - function e() { - (this._boundTick = void 0), - (this._tickTimer = null), - (this._tickInterval = null), - (this._tickCallCount = 0), - (this._boundTick = this.tick.bind(this)); - } - var t = e.prototype; - return ( - (t.destroy = function () { - this.onHandlerDestroying(), this.onHandlerDestroyed(); - }), - (t.onHandlerDestroying = function () { - this.clearNextTick(), this.clearInterval(); - }), - (t.onHandlerDestroyed = function () {}), - (t.hasInterval = function () { - return !!this._tickInterval; - }), - (t.hasNextTick = function () { - return !!this._tickTimer; - }), - (t.setInterval = function (e) { - return ( - !this._tickInterval && - ((this._tickCallCount = 0), - (this._tickInterval = self.setInterval( - this._boundTick, - e - )), - !0) - ); - }), - (t.clearInterval = function () { - return ( - !!this._tickInterval && - (self.clearInterval(this._tickInterval), - (this._tickInterval = null), - !0) - ); - }), - (t.clearNextTick = function () { - return ( - !!this._tickTimer && - (self.clearTimeout(this._tickTimer), - (this._tickTimer = null), - !0) - ); - }), - (t.tick = function () { - this._tickCallCount++, - 1 === this._tickCallCount && - (this.doTick(), - this._tickCallCount > 1 && this.tickImmediate(), - (this._tickCallCount = 0)); - }), - (t.tickImmediate = function () { - this.clearNextTick(), - (this._tickTimer = self.setTimeout(this._boundTick, 0)); - }), - (t.doTick = function () {}), - e - ); - })(), - Rr = "NOT_LOADED", - Ar = "APPENDING", - wr = "PARTIAL", - Pr = "OK", - Ir = (function () { - function e(e) { - (this.activePartLists = Object.create(null)), - (this.endListFragments = Object.create(null)), - (this.fragments = Object.create(null)), - (this.timeRanges = Object.create(null)), - (this.bufferPadding = 0.2), - (this.hls = void 0), - (this.hasGaps = !1), - (this.hls = e), - this._registerListeners(); - } - var t = e.prototype; - return ( - (t._registerListeners = function () { - var e = this.hls; - e.on(E.BUFFER_APPENDED, this.onBufferAppended, this), - e.on(E.FRAG_BUFFERED, this.onFragBuffered, this), - e.on(E.FRAG_LOADED, this.onFragLoaded, this); - }), - (t._unregisterListeners = function () { - var e = this.hls; - e.off(E.BUFFER_APPENDED, this.onBufferAppended, this), - e.off(E.FRAG_BUFFERED, this.onFragBuffered, this), - e.off(E.FRAG_LOADED, this.onFragLoaded, this); - }), - (t.destroy = function () { - this._unregisterListeners(), - (this.fragments = - this.activePartLists = - this.endListFragments = - this.timeRanges = - null); - }), - (t.getAppendedFrag = function (e, t) { - var r = this.activePartLists[t]; - if (r) - for (var i = r.length; i--; ) { - var n = r[i]; - if (!n) break; - var s = n.end; - if (n.start <= e && null !== s && e <= s) return n; - } - return this.getBufferedFrag(e, t); - }), - (t.getBufferedFrag = function (e, t) { - for ( - var r = this.fragments, - i = Object.keys(r), - n = i.length; - n--; - - ) { - var s = r[i[n]]; - if ( - (null == s ? void 0 : s.body.type) === t && - s.buffered - ) { - var a = s.body; - if (a.start <= e && e <= a.end) return a; - } - } - return null; - }), - (t.detectEvictedFragments = function (e, t, r, i) { - var n = this; - this.timeRanges && (this.timeRanges[e] = t); - var s = (null == i ? void 0 : i.fragment.sn) || -1; - Object.keys(this.fragments).forEach(function (i) { - var a = n.fragments[i]; - if (a && !(s >= a.body.sn)) - if (a.buffered || a.loaded) { - var o = a.range[e]; - o && - o.time.some(function (e) { - var r = !n.isTimeBuffered( - e.startPTS, - e.endPTS, - t - ); - return r && n.removeFragment(a.body), r; - }); - } else a.body.type === r && n.removeFragment(a.body); - }); - }), - (t.detectPartialFragments = function (e) { - var t = this, - r = this.timeRanges, - i = e.frag, - n = e.part; - if (r && "initSegment" !== i.sn) { - var s = kr(i), - a = this.fragments[s]; - if (!(!a || (a.buffered && i.gap))) { - var o = !i.relurl; - Object.keys(r).forEach(function (e) { - var s = i.elementaryStreams[e]; - if (s) { - var l = r[e], - h = o || !0 === s.partial; - a.range[e] = t.getBufferedTimes(i, n, h, l); - } - }), - (a.loaded = null), - Object.keys(a.range).length - ? ((a.buffered = !0), - (a.body.endList = - i.endList || a.body.endList) && - (this.endListFragments[a.body.type] = a), - Cr(a) || this.removeParts(i.sn - 1, i.type)) - : this.removeFragment(a.body); - } - } - }), - (t.removeParts = function (e, t) { - var r = this.activePartLists[t]; - r && - (this.activePartLists[t] = r.filter(function (t) { - return t.fragment.sn >= e; - })); - }), - (t.fragBuffered = function (e, t) { - var r = kr(e), - i = this.fragments[r]; - !i && - t && - ((i = this.fragments[r] = - { - body: e, - appendedPTS: null, - loaded: null, - buffered: !1, - range: Object.create(null), - }), - e.gap && (this.hasGaps = !0)), - i && ((i.loaded = null), (i.buffered = !0)); - }), - (t.getBufferedTimes = function (e, t, r, i) { - for ( - var n = { time: [], partial: r }, - s = e.start, - a = e.end, - o = e.minEndPTS || a, - l = e.maxStartPTS || s, - h = 0; - h < i.length; - h++ - ) { - var u = i.start(h) - this.bufferPadding, - d = i.end(h) + this.bufferPadding; - if (l >= u && o <= d) { - n.time.push({ - startPTS: Math.max(s, i.start(h)), - endPTS: Math.min(a, i.end(h)), - }); - break; - } - if (s < d && a > u) { - var c = Math.max(s, i.start(h)), - f = Math.min(a, i.end(h)); - f > c && - ((n.partial = !0), - n.time.push({ startPTS: c, endPTS: f })); - } else if (a <= u) break; - } - return n; - }), - (t.getPartialFragment = function (e) { - var t, - r, - i, - n = null, - s = 0, - a = this.bufferPadding, - o = this.fragments; - return ( - Object.keys(o).forEach(function (l) { - var h = o[l]; - h && - Cr(h) && - ((r = h.body.start - a), - (i = h.body.end + a), - e >= r && - e <= i && - ((t = Math.min(e - r, i - e)), - s <= t && ((n = h.body), (s = t)))); - }), - n - ); - }), - (t.isEndListAppended = function (e) { - var t = this.endListFragments[e]; - return void 0 !== t && (t.buffered || Cr(t)); - }), - (t.getState = function (e) { - var t = kr(e), - r = this.fragments[t]; - return r ? (r.buffered ? (Cr(r) ? wr : Pr) : Ar) : Rr; - }), - (t.isTimeBuffered = function (e, t, r) { - for (var i, n, s = 0; s < r.length; s++) { - if ( - ((i = r.start(s) - this.bufferPadding), - (n = r.end(s) + this.bufferPadding), - e >= i && t <= n) - ) - return !0; - if (t <= i) return !1; - } - return !1; - }), - (t.onFragLoaded = function (e, t) { - var r = t.frag, - i = t.part; - if ("initSegment" !== r.sn && !r.bitrateTest) { - var n = i ? null : t, - s = kr(r); - this.fragments[s] = { - body: r, - appendedPTS: null, - loaded: n, - buffered: !1, - range: Object.create(null), - }; - } - }), - (t.onBufferAppended = function (e, t) { - var r = this, - i = t.frag, - n = t.part, - s = t.timeRanges; - if ("initSegment" !== i.sn) { - var a = i.type; - if (n) { - var o = this.activePartLists[a]; - o || (this.activePartLists[a] = o = []), o.push(n); - } - (this.timeRanges = s), - Object.keys(s).forEach(function (e) { - var t = s[e]; - r.detectEvictedFragments(e, t, a, n); - }); - } - }), - (t.onFragBuffered = function (e, t) { - this.detectPartialFragments(t); - }), - (t.hasFragment = function (e) { - var t = kr(e); - return !!this.fragments[t]; - }), - (t.hasParts = function (e) { - var t; - return !( - null == (t = this.activePartLists[e]) || !t.length - ); - }), - (t.removeFragmentsInRange = function (e, t, r, i, n) { - var s = this; - (i && !this.hasGaps) || - Object.keys(this.fragments).forEach(function (a) { - var o = s.fragments[a]; - if (o) { - var l = o.body; - l.type !== r || - (i && !l.gap) || - (l.start < t && - l.end > e && - (o.buffered || n) && - s.removeFragment(l)); - } - }); - }), - (t.removeFragment = function (e) { - var t = kr(e); - (e.stats.loaded = 0), e.clearElementaryStreamInfo(); - var r = this.activePartLists[e.type]; - if (r) { - var i = e.sn; - this.activePartLists[e.type] = r.filter(function (e) { - return e.fragment.sn !== i; - }); - } - delete this.fragments[t], - e.endList && delete this.endListFragments[e.type]; - }), - (t.removeAllFragments = function () { - (this.fragments = Object.create(null)), - (this.endListFragments = Object.create(null)), - (this.activePartLists = Object.create(null)), - (this.hasGaps = !1); - }), - e - ); - })(); - function Cr(e) { - var t, r, i; - return ( - e.buffered && - (e.body.gap || - (null == (t = e.range.video) ? void 0 : t.partial) || - (null == (r = e.range.audio) ? void 0 : r.partial) || - (null == (i = e.range.audiovideo) ? void 0 : i.partial)) - ); - } - function kr(e) { - return e.type + "_" + e.level + "_" + e.sn; - } - var Dr = { - length: 0, - start: function () { - return 0; - }, - end: function () { - return 0; - }, - }, - Mr = (function () { - function e() {} - return ( - (e.isBuffered = function (t, r) { - try { - if (t) - for ( - var i = e.getBuffered(t), n = 0; - n < i.length; - n++ - ) - if (r >= i.start(n) && r <= i.end(n)) return !0; - } catch (e) {} - return !1; - }), - (e.bufferInfo = function (t, r, i) { - try { - if (t) { - var n, - s = e.getBuffered(t), - a = []; - for (n = 0; n < s.length; n++) - a.push({ start: s.start(n), end: s.end(n) }); - return this.bufferedInfo(a, r, i); - } - } catch (e) {} - return { len: 0, start: r, end: r, nextStart: void 0 }; - }), - (e.bufferedInfo = function (e, t, r) { - (t = Math.max(0, t)), - e.sort(function (e, t) { - return e.start - t.start || t.end - e.end; - }); - var i = []; - if (r) - for (var n = 0; n < e.length; n++) { - var s = i.length; - if (s) { - var a = i[s - 1].end; - e[n].start - a < r - ? e[n].end > a && (i[s - 1].end = e[n].end) - : i.push(e[n]); - } else i.push(e[n]); - } - else i = e; - for ( - var o, l = 0, h = t, u = t, d = 0; - d < i.length; - d++ - ) { - var c = i[d].start, - f = i[d].end; - if (t + r >= c && t < f) (h = c), (l = (u = f) - t); - else if (t + r < c) { - o = c; - break; - } - } - return { - len: l, - start: h || 0, - end: u || 0, - nextStart: o, - }; - }), - (e.getBuffered = function (e) { - try { - return e.buffered; - } catch (e) { - return A.log("failed to get media.buffered", e), Dr; - } - }), - e - ); - })(), - xr = function (e, t, r, i, n, s) { - void 0 === i && (i = 0), - void 0 === n && (n = -1), - void 0 === s && (s = !1), - (this.level = void 0), - (this.sn = void 0), - (this.part = void 0), - (this.id = void 0), - (this.size = void 0), - (this.partial = void 0), - (this.transmuxing = { - start: 0, - executeStart: 0, - executeEnd: 0, - end: 0, - }), - (this.buffering = { - audio: { - start: 0, - executeStart: 0, - executeEnd: 0, - end: 0, - }, - video: { - start: 0, - executeStart: 0, - executeEnd: 0, - end: 0, - }, - audiovideo: { - start: 0, - executeStart: 0, - executeEnd: 0, - end: 0, - }, - }), - (this.level = e), - (this.sn = t), - (this.id = r), - (this.size = i), - (this.part = n), - (this.partial = s); - }; - function Or(e, t) { - for (var r = 0, i = e.length; r < i; r++) { - var n; - if ((null == (n = e[r]) ? void 0 : n.cc) === t) return e[r]; - } - return null; - } - function Fr(e, t) { - if (e) { - var r = e.start + t; - (e.start = e.startPTS = r), (e.endPTS = r + e.duration); - } - } - function Nr(e, t) { - for (var r = t.fragments, i = 0, n = r.length; i < n; i++) - Fr(r[i], e); - t.fragmentHint && Fr(t.fragmentHint, e), - (t.alignedSliding = !0); - } - function Br(e, t) { - if (e.hasProgramDateTime && t.hasProgramDateTime) { - var r = e.fragments, - i = t.fragments; - if (r.length && i.length) { - var n, - s, - a = Math.min(t.endCC, e.endCC); - t.startCC < a && - e.startCC < a && - ((n = Or(i, a)), (s = Or(r, a))), - (n && s) || - (s = - Or(r, (n = i[Math.floor(i.length / 2)]).cc) || - r[Math.floor(r.length / 2)]); - var o = n.programDateTime, - l = s.programDateTime; - o && l && Nr((l - o) / 1e3 - (s.start - n.start), e); - } - } - } - var Ur = Math.pow(2, 17), - Gr = (function () { - function e(e) { - (this.config = void 0), - (this.loader = null), - (this.partLoadTimeout = -1), - (this.config = e); - } - var t = e.prototype; - return ( - (t.destroy = function () { - this.loader && - (this.loader.destroy(), (this.loader = null)); - }), - (t.abort = function () { - this.loader && this.loader.abort(); - }), - (t.load = function (e, t) { - var r = this, - n = e.url; - if (!n) - return Promise.reject( - new Kr({ - type: S.NETWORK_ERROR, - details: T.FRAG_LOAD_ERROR, - fatal: !1, - frag: e, - error: new Error( - "Fragment does not have a " + - (n ? "part list" : "url") - ), - networkDetails: null, - }) - ); - this.abort(); - var s = this.config, - a = s.fLoader, - o = s.loader; - return new Promise(function (l, h) { - if ((r.loader && r.loader.destroy(), e.gap)) { - if ( - e.tagList.some(function (e) { - return "GAP" === e[0]; - }) - ) - return void h($r(e)); - e.gap = !1; - } - var u = (r.loader = e.loader = a ? new a(s) : new o(s)), - d = Hr(e), - c = sr(s.fragLoadPolicy.default), - f = { - loadPolicy: c, - timeout: c.maxLoadTimeMs, - maxRetry: 0, - retryDelay: 0, - maxRetryDelay: 0, - highWaterMark: "initSegment" === e.sn ? 1 / 0 : Ur, - }; - (e.stats = u.stats), - u.load(d, f, { - onSuccess: function (t, i, n, s) { - r.resetLoader(e, u); - var a = t.data; - n.resetIV && - e.decryptdata && - ((e.decryptdata.iv = new Uint8Array( - a.slice(0, 16) - )), - (a = a.slice(16))), - l({ - frag: e, - part: null, - payload: a, - networkDetails: s, - }); - }, - onError: function (t, s, a, o) { - r.resetLoader(e, u), - h( - new Kr({ - type: S.NETWORK_ERROR, - details: T.FRAG_LOAD_ERROR, - fatal: !1, - frag: e, - response: i({ url: n, data: void 0 }, t), - error: new Error( - "HTTP Error " + t.code + " " + t.text - ), - networkDetails: a, - stats: o, - }) - ); - }, - onAbort: function (t, i, n) { - r.resetLoader(e, u), - h( - new Kr({ - type: S.NETWORK_ERROR, - details: T.INTERNAL_ABORTED, - fatal: !1, - frag: e, - error: new Error("Aborted"), - networkDetails: n, - stats: t, - }) - ); - }, - onTimeout: function (t, i, n) { - r.resetLoader(e, u), - h( - new Kr({ - type: S.NETWORK_ERROR, - details: T.FRAG_LOAD_TIMEOUT, - fatal: !1, - frag: e, - error: new Error( - "Timeout after " + f.timeout + "ms" - ), - networkDetails: n, - stats: t, - }) - ); - }, - onProgress: function (r, i, n, s) { - t && - t({ - frag: e, - part: null, - payload: n, - networkDetails: s, - }); - }, - }); - }); - }), - (t.loadPart = function (e, t, r) { - var n = this; - this.abort(); - var s = this.config, - a = s.fLoader, - o = s.loader; - return new Promise(function (l, h) { - if ((n.loader && n.loader.destroy(), e.gap || t.gap)) - h($r(e, t)); - else { - var u = - (n.loader = - e.loader = - a ? new a(s) : new o(s)), - d = Hr(e, t), - c = sr(s.fragLoadPolicy.default), - f = { - loadPolicy: c, - timeout: c.maxLoadTimeMs, - maxRetry: 0, - retryDelay: 0, - maxRetryDelay: 0, - highWaterMark: Ur, - }; - (t.stats = u.stats), - u.load(d, f, { - onSuccess: function (i, s, a, o) { - n.resetLoader(e, u), - n.updateStatsFromPart(e, t); - var h = { - frag: e, - part: t, - payload: i.data, - networkDetails: o, - }; - r(h), l(h); - }, - onError: function (r, s, a, o) { - n.resetLoader(e, u), - h( - new Kr({ - type: S.NETWORK_ERROR, - details: T.FRAG_LOAD_ERROR, - fatal: !1, - frag: e, - part: t, - response: i( - { url: d.url, data: void 0 }, - r - ), - error: new Error( - "HTTP Error " + r.code + " " + r.text - ), - networkDetails: a, - stats: o, - }) - ); - }, - onAbort: function (r, i, s) { - (e.stats.aborted = t.stats.aborted), - n.resetLoader(e, u), - h( - new Kr({ - type: S.NETWORK_ERROR, - details: T.INTERNAL_ABORTED, - fatal: !1, - frag: e, - part: t, - error: new Error("Aborted"), - networkDetails: s, - stats: r, - }) - ); - }, - onTimeout: function (r, i, s) { - n.resetLoader(e, u), - h( - new Kr({ - type: S.NETWORK_ERROR, - details: T.FRAG_LOAD_TIMEOUT, - fatal: !1, - frag: e, - part: t, - error: new Error( - "Timeout after " + f.timeout + "ms" - ), - networkDetails: s, - stats: r, - }) - ); - }, - }); - } - }); - }), - (t.updateStatsFromPart = function (e, t) { - var r = e.stats, - i = t.stats, - n = i.total; - if (((r.loaded += i.loaded), n)) { - var s = Math.round(e.duration / t.duration), - a = Math.min(Math.round(r.loaded / n), s), - o = (s - a) * Math.round(r.loaded / a); - r.total = r.loaded + o; - } else r.total = Math.max(r.loaded, r.total); - var l = r.loading, - h = i.loading; - l.start - ? (l.first += h.first - h.start) - : ((l.start = h.start), (l.first = h.first)), - (l.end = h.end); - }), - (t.resetLoader = function (e, t) { - (e.loader = null), - this.loader === t && - (self.clearTimeout(this.partLoadTimeout), - (this.loader = null)), - t.destroy(); - }), - e - ); - })(); - function Hr(e, t) { - void 0 === t && (t = null); - var r = t || e, - i = { - frag: e, - part: t, - responseType: "arraybuffer", - url: r.url, - headers: {}, - rangeStart: 0, - rangeEnd: 0, - }, - n = r.byteRangeStartOffset, - s = r.byteRangeEndOffset; - if (m(n) && m(s)) { - var a, - o = n, - l = s; - if ( - "initSegment" === e.sn && - "AES-128" === - (null == (a = e.decryptdata) ? void 0 : a.method) - ) { - var h = s - n; - h % 16 && (l = s + (16 - (h % 16))), - 0 !== n && ((i.resetIV = !0), (o = n - 16)); - } - (i.rangeStart = o), (i.rangeEnd = l); - } - return i; - } - function $r(e, t) { - var r = new Error( - "GAP " + (e.gap ? "tag" : "attribute") + " found" - ), - i = { - type: S.MEDIA_ERROR, - details: T.FRAG_GAP, - fatal: !1, - frag: e, - error: r, - networkDetails: null, - }; - return ( - t && (i.part = t), ((t || e).stats.aborted = !0), new Kr(i) - ); - } - var Kr = (function (e) { - function t(t) { - var r; - return ( - ((r = e.call(this, t.error.message) || this).data = - void 0), - (r.data = t), - r - ); - } - return l(t, e), t; - })(c(Error)), - Wr = (function () { - function e(e, t) { - (this.subtle = void 0), - (this.aesIV = void 0), - (this.subtle = e), - (this.aesIV = t); - } - return ( - (e.prototype.decrypt = function (e, t) { - return this.subtle.decrypt( - { name: "AES-CBC", iv: this.aesIV }, - t, - e - ); - }), - e - ); - })(), - Vr = (function () { - function e(e, t) { - (this.subtle = void 0), - (this.key = void 0), - (this.subtle = e), - (this.key = t); - } - return ( - (e.prototype.expandKey = function () { - return this.subtle.importKey( - "raw", - this.key, - { name: "AES-CBC" }, - !1, - ["encrypt", "decrypt"] - ); - }), - e - ); - })(), - qr = (function () { - function e() { - (this.rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54]), - (this.subMix = [ - new Uint32Array(256), - new Uint32Array(256), - new Uint32Array(256), - new Uint32Array(256), - ]), - (this.invSubMix = [ - new Uint32Array(256), - new Uint32Array(256), - new Uint32Array(256), - new Uint32Array(256), - ]), - (this.sBox = new Uint32Array(256)), - (this.invSBox = new Uint32Array(256)), - (this.key = new Uint32Array(0)), - (this.ksRows = 0), - (this.keySize = 0), - (this.keySchedule = void 0), - (this.invKeySchedule = void 0), - this.initTable(); - } - var t = e.prototype; - return ( - (t.uint8ArrayToUint32Array_ = function (e) { - for ( - var t = new DataView(e), r = new Uint32Array(4), i = 0; - i < 4; - i++ - ) - r[i] = t.getUint32(4 * i); - return r; - }), - (t.initTable = function () { - var e = this.sBox, - t = this.invSBox, - r = this.subMix, - i = r[0], - n = r[1], - s = r[2], - a = r[3], - o = this.invSubMix, - l = o[0], - h = o[1], - u = o[2], - d = o[3], - c = new Uint32Array(256), - f = 0, - g = 0, - p = 0; - for (p = 0; p < 256; p++) - c[p] = p < 128 ? p << 1 : (p << 1) ^ 283; - for (p = 0; p < 256; p++) { - var m = g ^ (g << 1) ^ (g << 2) ^ (g << 3) ^ (g << 4); - (m = (m >>> 8) ^ (255 & m) ^ 99), - (e[f] = m), - (t[m] = f); - var v = c[f], - y = c[v], - E = c[y], - S = (257 * c[m]) ^ (16843008 * m); - (i[f] = (S << 24) | (S >>> 8)), - (n[f] = (S << 16) | (S >>> 16)), - (s[f] = (S << 8) | (S >>> 24)), - (a[f] = S), - (S = - (16843009 * E) ^ - (65537 * y) ^ - (257 * v) ^ - (16843008 * f)), - (l[m] = (S << 24) | (S >>> 8)), - (h[m] = (S << 16) | (S >>> 16)), - (u[m] = (S << 8) | (S >>> 24)), - (d[m] = S), - f - ? ((f = v ^ c[c[c[E ^ v]]]), (g ^= c[c[g]])) - : (f = g = 1); - } - }), - (t.expandKey = function (e) { - for ( - var t = this.uint8ArrayToUint32Array_(e), r = !0, i = 0; - i < t.length && r; - - ) - (r = t[i] === this.key[i]), i++; - if (!r) { - this.key = t; - var n = (this.keySize = t.length); - if (4 !== n && 6 !== n && 8 !== n) - throw new Error("Invalid aes key size=" + n); - var s, - a, - o, - l, - h = (this.ksRows = 4 * (n + 6 + 1)), - u = (this.keySchedule = new Uint32Array(h)), - d = (this.invKeySchedule = new Uint32Array(h)), - c = this.sBox, - f = this.rcon, - g = this.invSubMix, - p = g[0], - m = g[1], - v = g[2], - y = g[3]; - for (s = 0; s < h; s++) - s < n - ? (o = u[s] = t[s]) - : ((l = o), - s % n == 0 - ? ((l = - (c[(l = (l << 8) | (l >>> 24)) >>> 24] << - 24) | - (c[(l >>> 16) & 255] << 16) | - (c[(l >>> 8) & 255] << 8) | - c[255 & l]), - (l ^= f[(s / n) | 0] << 24)) - : n > 6 && - s % n == 4 && - (l = - (c[l >>> 24] << 24) | - (c[(l >>> 16) & 255] << 16) | - (c[(l >>> 8) & 255] << 8) | - c[255 & l]), - (u[s] = o = (u[s - n] ^ l) >>> 0)); - for (a = 0; a < h; a++) - (s = h - a), - (l = 3 & a ? u[s] : u[s - 4]), - (d[a] = - a < 4 || s <= 4 - ? l - : p[c[l >>> 24]] ^ - m[c[(l >>> 16) & 255]] ^ - v[c[(l >>> 8) & 255]] ^ - y[c[255 & l]]), - (d[a] = d[a] >>> 0); - } - }), - (t.networkToHostOrderSwap = function (e) { - return ( - (e << 24) | - ((65280 & e) << 8) | - ((16711680 & e) >> 8) | - (e >>> 24) - ); - }), - (t.decrypt = function (e, t, r) { - for ( - var i, - n, - s, - a, - o, - l, - h, - u, - d, - c, - f, - g, - p, - m, - v = this.keySize + 6, - y = this.invKeySchedule, - E = this.invSBox, - S = this.invSubMix, - T = S[0], - _ = S[1], - L = S[2], - b = S[3], - R = this.uint8ArrayToUint32Array_(r), - A = R[0], - w = R[1], - P = R[2], - I = R[3], - C = new Int32Array(e), - k = new Int32Array(C.length), - D = this.networkToHostOrderSwap; - t < C.length; - - ) { - for ( - d = D(C[t]), - c = D(C[t + 1]), - f = D(C[t + 2]), - g = D(C[t + 3]), - o = d ^ y[0], - l = g ^ y[1], - h = f ^ y[2], - u = c ^ y[3], - p = 4, - m = 1; - m < v; - m++ - ) - (i = - T[o >>> 24] ^ - _[(l >> 16) & 255] ^ - L[(h >> 8) & 255] ^ - b[255 & u] ^ - y[p]), - (n = - T[l >>> 24] ^ - _[(h >> 16) & 255] ^ - L[(u >> 8) & 255] ^ - b[255 & o] ^ - y[p + 1]), - (s = - T[h >>> 24] ^ - _[(u >> 16) & 255] ^ - L[(o >> 8) & 255] ^ - b[255 & l] ^ - y[p + 2]), - (a = - T[u >>> 24] ^ - _[(o >> 16) & 255] ^ - L[(l >> 8) & 255] ^ - b[255 & h] ^ - y[p + 3]), - (o = i), - (l = n), - (h = s), - (u = a), - (p += 4); - (i = - (E[o >>> 24] << 24) ^ - (E[(l >> 16) & 255] << 16) ^ - (E[(h >> 8) & 255] << 8) ^ - E[255 & u] ^ - y[p]), - (n = - (E[l >>> 24] << 24) ^ - (E[(h >> 16) & 255] << 16) ^ - (E[(u >> 8) & 255] << 8) ^ - E[255 & o] ^ - y[p + 1]), - (s = - (E[h >>> 24] << 24) ^ - (E[(u >> 16) & 255] << 16) ^ - (E[(o >> 8) & 255] << 8) ^ - E[255 & l] ^ - y[p + 2]), - (a = - (E[u >>> 24] << 24) ^ - (E[(o >> 16) & 255] << 16) ^ - (E[(l >> 8) & 255] << 8) ^ - E[255 & h] ^ - y[p + 3]), - (k[t] = D(i ^ A)), - (k[t + 1] = D(a ^ w)), - (k[t + 2] = D(s ^ P)), - (k[t + 3] = D(n ^ I)), - (A = d), - (w = c), - (P = f), - (I = g), - (t += 4); - } - return k.buffer; - }), - e - ); - })(), - jr = (function () { - function e(e, t) { - var r = (void 0 === t ? {} : t).removePKCS7Padding, - i = void 0 === r || r; - if ( - ((this.logEnabled = !0), - (this.removePKCS7Padding = void 0), - (this.subtle = null), - (this.softwareDecrypter = null), - (this.key = null), - (this.fastAesKey = null), - (this.remainderData = null), - (this.currentIV = null), - (this.currentResult = null), - (this.useSoftware = void 0), - (this.useSoftware = e.enableSoftwareAES), - (this.removePKCS7Padding = i), - i) - ) - try { - var n = self.crypto; - n && (this.subtle = n.subtle || n.webkitSubtle); - } catch (e) {} - this.useSoftware = !this.subtle; - } - var t = e.prototype; - return ( - (t.destroy = function () { - (this.subtle = null), - (this.softwareDecrypter = null), - (this.key = null), - (this.fastAesKey = null), - (this.remainderData = null), - (this.currentIV = null), - (this.currentResult = null); - }), - (t.isSync = function () { - return this.useSoftware; - }), - (t.flush = function () { - var e = this.currentResult, - t = this.remainderData; - if (!e || t) return this.reset(), null; - var r, - i, - n, - s = new Uint8Array(e); - return ( - this.reset(), - this.removePKCS7Padding - ? (n = - (i = (r = s).byteLength) && - new DataView(r.buffer).getUint8(i - 1)) - ? ee(r, 0, i - n) - : r - : s - ); - }), - (t.reset = function () { - (this.currentResult = null), - (this.currentIV = null), - (this.remainderData = null), - this.softwareDecrypter && - (this.softwareDecrypter = null); - }), - (t.decrypt = function (e, t, r) { - var i = this; - return this.useSoftware - ? new Promise(function (n, s) { - i.softwareDecrypt(new Uint8Array(e), t, r); - var a = i.flush(); - a - ? n(a.buffer) - : s( - new Error( - "[softwareDecrypt] Failed to decrypt data" - ) - ); - }) - : this.webCryptoDecrypt(new Uint8Array(e), t, r); - }), - (t.softwareDecrypt = function (e, t, r) { - var i = this.currentIV, - n = this.currentResult, - s = this.remainderData; - this.logOnce("JS AES decrypt"), - s && ((e = Fe(s, e)), (this.remainderData = null)); - var a = this.getValidChunk(e); - if (!a.length) return null; - i && (r = i); - var o = this.softwareDecrypter; - o || (o = this.softwareDecrypter = new qr()), - o.expandKey(t); - var l = n; - return ( - (this.currentResult = o.decrypt(a.buffer, 0, r)), - (this.currentIV = ee(a, -16).buffer), - l || null - ); - }), - (t.webCryptoDecrypt = function (e, t, r) { - var i = this; - if (this.key !== t || !this.fastAesKey) { - if (!this.subtle) - return Promise.resolve( - this.onWebCryptoError(e, t, r) - ); - (this.key = t), - (this.fastAesKey = new Vr(this.subtle, t)); - } - return this.fastAesKey - .expandKey() - .then(function (t) { - return i.subtle - ? (i.logOnce("WebCrypto AES decrypt"), - new Wr(i.subtle, new Uint8Array(r)).decrypt( - e.buffer, - t - )) - : Promise.reject( - new Error("web crypto not initialized") - ); - }) - .catch(function (n) { - return ( - A.warn( - "[decrypter]: WebCrypto Error, disable WebCrypto API, " + - n.name + - ": " + - n.message - ), - i.onWebCryptoError(e, t, r) - ); - }); - }), - (t.onWebCryptoError = function (e, t, r) { - (this.useSoftware = !0), - (this.logEnabled = !0), - this.softwareDecrypt(e, t, r); - var i = this.flush(); - if (i) return i.buffer; - throw new Error( - "WebCrypto and softwareDecrypt: failed to decrypt data" - ); - }), - (t.getValidChunk = function (e) { - var t = e, - r = e.length - (e.length % 16); - return ( - r !== e.length && - ((t = ee(e, 0, r)), (this.remainderData = ee(e, r))), - t - ); - }), - (t.logOnce = function (e) { - this.logEnabled && - (A.log("[decrypter]: " + e), (this.logEnabled = !1)); - }), - e - ); - })(), - Yr = "STOPPED", - zr = "IDLE", - Xr = "KEY_LOADING", - Qr = "FRAG_LOADING", - Jr = "FRAG_LOADING_WAITING_RETRY", - Zr = "WAITING_TRACK", - ei = "PARSING", - ti = "PARSED", - ri = "ENDED", - ii = "ERROR", - ni = "WAITING_INIT_PTS", - si = "WAITING_LEVEL", - ai = (function (e) { - function t(t, r, i, n, s) { - var a; - return ( - ((a = e.call(this) || this).hls = void 0), - (a.fragPrevious = null), - (a.fragCurrent = null), - (a.fragmentTracker = void 0), - (a.transmuxer = null), - (a._state = Yr), - (a.playlistType = void 0), - (a.media = null), - (a.mediaBuffer = null), - (a.config = void 0), - (a.bitrateTest = !1), - (a.lastCurrentTime = 0), - (a.nextLoadPosition = 0), - (a.startPosition = 0), - (a.startTimeOffset = null), - (a.loadedmetadata = !1), - (a.retryDate = 0), - (a.levels = null), - (a.fragmentLoader = void 0), - (a.keyLoader = void 0), - (a.levelLastLoaded = null), - (a.startFragRequested = !1), - (a.decrypter = void 0), - (a.initPTS = []), - (a.onvseeking = null), - (a.onvended = null), - (a.logPrefix = ""), - (a.log = void 0), - (a.warn = void 0), - (a.playlistType = s), - (a.logPrefix = n), - (a.log = A.log.bind(A, n + ":")), - (a.warn = A.warn.bind(A, n + ":")), - (a.hls = t), - (a.fragmentLoader = new Gr(t.config)), - (a.keyLoader = i), - (a.fragmentTracker = r), - (a.config = t.config), - (a.decrypter = new jr(t.config)), - t.on( - E.MANIFEST_LOADED, - a.onManifestLoaded, - (function (e) { - if (void 0 === e) - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - return e; - })(a) - ), - a - ); - } - l(t, e); - var r = t.prototype; - return ( - (r.doTick = function () { - this.onTickEnd(); - }), - (r.onTickEnd = function () {}), - (r.startLoad = function (e) {}), - (r.stopLoad = function () { - this.fragmentLoader.abort(), - this.keyLoader.abort(this.playlistType); - var e = this.fragCurrent; - null != e && - e.loader && - (e.abortRequests(), - this.fragmentTracker.removeFragment(e)), - this.resetTransmuxer(), - (this.fragCurrent = null), - (this.fragPrevious = null), - this.clearInterval(), - this.clearNextTick(), - (this.state = Yr); - }), - (r._streamEnded = function (e, t) { - if (t.live || e.nextStart || !e.end || !this.media) - return !1; - var r = t.partList; - if (null != r && r.length) { - var i = r[r.length - 1]; - return Mr.isBuffered( - this.media, - i.start + i.duration / 2 - ); - } - var n = t.fragments[t.fragments.length - 1].type; - return this.fragmentTracker.isEndListAppended(n); - }), - (r.getLevelDetails = function () { - var e; - if (this.levels && null !== this.levelLastLoaded) - return null == (e = this.levelLastLoaded) - ? void 0 - : e.details; - }), - (r.onMediaAttached = function (e, t) { - var r = (this.media = this.mediaBuffer = t.media); - (this.onvseeking = this.onMediaSeeking.bind(this)), - (this.onvended = this.onMediaEnded.bind(this)), - r.addEventListener("seeking", this.onvseeking), - r.addEventListener("ended", this.onvended); - var i = this.config; - this.levels && - i.autoStartLoad && - this.state === Yr && - this.startLoad(i.startPosition); - }), - (r.onMediaDetaching = function () { - var e = this.media; - null != e && - e.ended && - (this.log( - "MSE detaching and video ended, reset startPosition" - ), - (this.startPosition = this.lastCurrentTime = 0)), - e && - this.onvseeking && - this.onvended && - (e.removeEventListener("seeking", this.onvseeking), - e.removeEventListener("ended", this.onvended), - (this.onvseeking = this.onvended = null)), - this.keyLoader && this.keyLoader.detach(), - (this.media = this.mediaBuffer = null), - (this.loadedmetadata = !1), - this.fragmentTracker.removeAllFragments(), - this.stopLoad(); - }), - (r.onMediaSeeking = function () { - var e = this.config, - t = this.fragCurrent, - r = this.media, - i = this.mediaBuffer, - n = this.state, - s = r ? r.currentTime : 0, - a = Mr.bufferInfo(i || r, s, e.maxBufferHole); - if ( - (this.log( - "media seeking to " + - (m(s) ? s.toFixed(3) : s) + - ", state: " + - n - ), - this.state === ri) - ) - this.resetLoadingState(); - else if (t) { - var o = e.maxFragLookUpTolerance, - l = t.start - o, - h = t.start + t.duration + o; - if (!a.len || h < a.start || l > a.end) { - var u = s > h; - (s < l || u) && - (u && - t.loader && - (this.log( - "seeking outside of buffer while fragment load in progress, cancel fragment load" - ), - t.abortRequests(), - this.resetLoadingState()), - (this.fragPrevious = null)); - } - } - r && - (this.fragmentTracker.removeFragmentsInRange( - s, - 1 / 0, - this.playlistType, - !0 - ), - (this.lastCurrentTime = s)), - this.loadedmetadata || - a.len || - (this.nextLoadPosition = this.startPosition = s), - this.tickImmediate(); - }), - (r.onMediaEnded = function () { - this.startPosition = this.lastCurrentTime = 0; - }), - (r.onManifestLoaded = function (e, t) { - (this.startTimeOffset = t.startTimeOffset), - (this.initPTS = []); - }), - (r.onHandlerDestroying = function () { - this.hls.off( - E.MANIFEST_LOADED, - this.onManifestLoaded, - this - ), - this.stopLoad(), - e.prototype.onHandlerDestroying.call(this), - (this.hls = null); - }), - (r.onHandlerDestroyed = function () { - (this.state = Yr), - this.fragmentLoader && this.fragmentLoader.destroy(), - this.keyLoader && this.keyLoader.destroy(), - this.decrypter && this.decrypter.destroy(), - (this.hls = - this.log = - this.warn = - this.decrypter = - this.keyLoader = - this.fragmentLoader = - this.fragmentTracker = - null), - e.prototype.onHandlerDestroyed.call(this); - }), - (r.loadFragment = function (e, t, r) { - this._loadFragForPlayback(e, t, r); - }), - (r._loadFragForPlayback = function (e, t, r) { - var i = this; - this._doFragLoad(e, t, r, function (t) { - if (i.fragContextChanged(e)) - return ( - i.warn( - "Fragment " + - e.sn + - (t.part ? " p: " + t.part.index : "") + - " of level " + - e.level + - " was dropped during download." - ), - void i.fragmentTracker.removeFragment(e) - ); - e.stats.chunkCount++, i._handleFragmentLoadProgress(t); - }) - .then(function (t) { - if (t) { - var r = i.state; - i.fragContextChanged(e) - ? (r === Qr || (!i.fragCurrent && r === ei)) && - (i.fragmentTracker.removeFragment(e), - (i.state = zr)) - : ("payload" in t && - (i.log( - "Loaded fragment " + - e.sn + - " of level " + - e.level - ), - i.hls.trigger(E.FRAG_LOADED, t)), - i._handleFragmentLoadComplete(t)); - } - }) - .catch(function (t) { - i.state !== Yr && - i.state !== ii && - (i.warn( - "Frag error: " + - ((null == t ? void 0 : t.message) || t) - ), - i.resetFragmentLoading(e)); - }); - }), - (r.clearTrackerIfNeeded = function (e) { - var t, - r = this.fragmentTracker; - if (r.getState(e) === Ar) { - var i = e.type, - n = this.getFwdBufferInfo(this.mediaBuffer, i), - s = Math.max( - e.duration, - n ? n.len : this.config.maxBufferLength - ), - a = this.backtrackFragment; - (1 == (a ? e.sn - a.sn : 0) || - this.reduceMaxBufferLength(s, e.duration)) && - r.removeFragment(e); - } else - 0 === - (null == (t = this.mediaBuffer) - ? void 0 - : t.buffered.length) - ? r.removeAllFragments() - : r.hasParts(e.type) && - (r.detectPartialFragments({ - frag: e, - part: null, - stats: e.stats, - id: e.type, - }), - r.getState(e) === wr && r.removeFragment(e)); - }), - (r.checkLiveUpdate = function (e) { - if (e.updated && !e.live) { - var t = e.fragments[e.fragments.length - 1]; - this.fragmentTracker.detectPartialFragments({ - frag: t, - part: null, - stats: t.stats, - id: t.type, - }); - } - e.fragments[0] || (e.deltaUpdateFailed = !0); - }), - (r.flushMainBuffer = function (e, t, r) { - if ((void 0 === r && (r = null), e - t)) { - var i = { startOffset: e, endOffset: t, type: r }; - this.hls.trigger(E.BUFFER_FLUSHING, i); - } - }), - (r._loadInitSegment = function (e, t) { - var r = this; - this._doFragLoad(e, t) - .then(function (t) { - if (!t || r.fragContextChanged(e) || !r.levels) - throw new Error("init load aborted"); - return t; - }) - .then(function (t) { - var i = r.hls, - n = t.payload, - s = e.decryptdata; - if ( - n && - n.byteLength > 0 && - null != s && - s.key && - s.iv && - "AES-128" === s.method - ) { - var a = self.performance.now(); - return r.decrypter - .decrypt( - new Uint8Array(n), - s.key.buffer, - s.iv.buffer - ) - .catch(function (t) { - throw ( - (i.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.FRAG_DECRYPT_ERROR, - fatal: !1, - error: t, - reason: t.message, - frag: e, - }), - t) - ); - }) - .then(function (n) { - var s = self.performance.now(); - return ( - i.trigger(E.FRAG_DECRYPTED, { - frag: e, - payload: n, - stats: { tstart: a, tdecrypt: s }, - }), - (t.payload = n), - r.completeInitSegmentLoad(t) - ); - }); - } - return r.completeInitSegmentLoad(t); - }) - .catch(function (t) { - r.state !== Yr && - r.state !== ii && - (r.warn(t), r.resetFragmentLoading(e)); - }); - }), - (r.completeInitSegmentLoad = function (e) { - if (!this.levels) - throw new Error("init load aborted, missing levels"); - var t = e.frag.stats; - (this.state = zr), - (e.frag.data = new Uint8Array(e.payload)), - (t.parsing.start = t.buffering.start = - self.performance.now()), - (t.parsing.end = t.buffering.end = - self.performance.now()), - this.tick(); - }), - (r.fragContextChanged = function (e) { - var t = this.fragCurrent; - return !e || !t || e.sn !== t.sn || e.level !== t.level; - }), - (r.fragBufferedComplete = function (e, t) { - var r, - i, - n, - s, - a = this.mediaBuffer ? this.mediaBuffer : this.media; - if ( - (this.log( - "Buffered " + - e.type + - " sn: " + - e.sn + - (t ? " part: " + t.index : "") + - " of " + - (this.playlistType === Lt ? "level" : "track") + - " " + - e.level + - " (frag:[" + - (null != (r = e.startPTS) ? r : NaN).toFixed(3) + - "-" + - (null != (i = e.endPTS) ? i : NaN).toFixed(3) + - "] > buffer:" + - (a - ? (function (e) { - for ( - var t = "", r = e.length, i = 0; - i < r; - i++ - ) - t += - "[" + - e.start(i).toFixed(3) + - "-" + - e.end(i).toFixed(3) + - "]"; - return t; - })(Mr.getBuffered(a)) - : "(detached)") + - ")" - ), - "initSegment" !== e.sn) - ) { - var o; - if (e.type !== Rt) { - var l = e.elementaryStreams; - if ( - !Object.keys(l).some(function (e) { - return !!l[e]; - }) - ) - return void (this.state = zr); - } - var h = null == (o = this.levels) ? void 0 : o[e.level]; - null != h && - h.fragmentError && - (this.log( - "Resetting level fragment error count of " + - h.fragmentError + - " on frag buffered" - ), - (h.fragmentError = 0)); - } - (this.state = zr), - a && - (!this.loadedmetadata && - e.type == Lt && - a.buffered.length && - (null == (n = this.fragCurrent) ? void 0 : n.sn) === - (null == (s = this.fragPrevious) - ? void 0 - : s.sn) && - ((this.loadedmetadata = !0), this.seekToStartPos()), - this.tick()); - }), - (r.seekToStartPos = function () {}), - (r._handleFragmentLoadComplete = function (e) { - var t = this.transmuxer; - if (t) { - var r = e.frag, - i = e.part, - n = e.partsLoaded, - s = - !n || - 0 === n.length || - n.some(function (e) { - return !e; - }), - a = new xr( - r.level, - r.sn, - r.stats.chunkCount + 1, - 0, - i ? i.index : -1, - !s - ); - t.flush(a); - } - }), - (r._handleFragmentLoadProgress = function (e) {}), - (r._doFragLoad = function (e, t, r, i) { - var n, - s = this; - void 0 === r && (r = null); - var a = null == t ? void 0 : t.details; - if (!this.levels || !a) - throw new Error( - "frag load aborted, missing level" + - (a ? "" : " detail") + - "s" - ); - var o = null; - if ( - (!e.encrypted || (null != (n = e.decryptdata) && n.key) - ? !e.encrypted && - a.encryptedFragments.length && - this.keyLoader.loadClear(e, a.encryptedFragments) - : (this.log( - "Loading key for " + - e.sn + - " of [" + - a.startSN + - "-" + - a.endSN + - "], " + - ("[stream-controller]" === this.logPrefix - ? "level" - : "track") + - " " + - e.level - ), - (this.state = Xr), - (this.fragCurrent = e), - (o = this.keyLoader.load(e).then(function (e) { - if (!s.fragContextChanged(e.frag)) - return ( - s.hls.trigger(E.KEY_LOADED, e), - s.state === Xr && (s.state = zr), - e - ); - })), - this.hls.trigger(E.KEY_LOADING, { frag: e }), - null === this.fragCurrent && - (o = Promise.reject( - new Error( - "frag load aborted, context changed in KEY_LOADING" - ) - ))), - (r = Math.max(e.start, r || 0)), - this.config.lowLatencyMode && "initSegment" !== e.sn) - ) { - var l = a.partList; - if (l && i) { - r > e.end && a.fragmentHint && (e = a.fragmentHint); - var h = this.getNextPart(l, e, r); - if (h > -1) { - var u, - d = l[h]; - return ( - this.log( - "Loading part sn: " + - e.sn + - " p: " + - d.index + - " cc: " + - e.cc + - " of playlist [" + - a.startSN + - "-" + - a.endSN + - "] parts [0-" + - h + - "-" + - (l.length - 1) + - "] " + - ("[stream-controller]" === this.logPrefix - ? "level" - : "track") + - ": " + - e.level + - ", target: " + - parseFloat(r.toFixed(3)) - ), - (this.nextLoadPosition = d.start + d.duration), - (this.state = Qr), - (u = o - ? o - .then(function (r) { - return !r || s.fragContextChanged(r.frag) - ? null - : s.doFragPartsLoad(e, d, t, i); - }) - .catch(function (e) { - return s.handleFragLoadError(e); - }) - : this.doFragPartsLoad(e, d, t, i).catch( - function (e) { - return s.handleFragLoadError(e); - } - )), - this.hls.trigger(E.FRAG_LOADING, { - frag: e, - part: d, - targetBufferTime: r, - }), - null === this.fragCurrent - ? Promise.reject( - new Error( - "frag load aborted, context changed in FRAG_LOADING parts" - ) - ) - : u - ); - } - if (!e.url || this.loadedEndOfParts(l, r)) - return Promise.resolve(null); - } - } - this.log( - "Loading fragment " + - e.sn + - " cc: " + - e.cc + - " " + - (a ? "of [" + a.startSN + "-" + a.endSN + "] " : "") + - ("[stream-controller]" === this.logPrefix - ? "level" - : "track") + - ": " + - e.level + - ", target: " + - parseFloat(r.toFixed(3)) - ), - m(e.sn) && - !this.bitrateTest && - (this.nextLoadPosition = e.start + e.duration), - (this.state = Qr); - var c, - f = this.config.progressive; - return ( - (c = - f && o - ? o - .then(function (t) { - return !t || - s.fragContextChanged( - null == t ? void 0 : t.frag - ) - ? null - : s.fragmentLoader.load(e, i); - }) - .catch(function (e) { - return s.handleFragLoadError(e); - }) - : Promise.all([ - this.fragmentLoader.load(e, f ? i : void 0), - o, - ]) - .then(function (e) { - var t = e[0]; - return !f && t && i && i(t), t; - }) - .catch(function (e) { - return s.handleFragLoadError(e); - })), - this.hls.trigger(E.FRAG_LOADING, { - frag: e, - targetBufferTime: r, - }), - null === this.fragCurrent - ? Promise.reject( - new Error( - "frag load aborted, context changed in FRAG_LOADING" - ) - ) - : c - ); - }), - (r.doFragPartsLoad = function (e, t, r, i) { - var n = this; - return new Promise(function (s, a) { - var o, - l = [], - h = null == (o = r.details) ? void 0 : o.partList; - !(function t(o) { - n.fragmentLoader - .loadPart(e, o, i) - .then(function (i) { - l[o.index] = i; - var a = i.part; - n.hls.trigger(E.FRAG_LOADED, i); - var u = - Zt(r, e.sn, o.index + 1) || - er(h, e.sn, o.index + 1); - if (!u) - return s({ frag: e, part: a, partsLoaded: l }); - t(u); - }) - .catch(a); - })(t); - }); - }), - (r.handleFragLoadError = function (e) { - if ("data" in e) { - var t = e.data; - e.data && t.details === T.INTERNAL_ABORTED - ? this.handleFragLoadAborted(t.frag, t.part) - : this.hls.trigger(E.ERROR, t); - } else - this.hls.trigger(E.ERROR, { - type: S.OTHER_ERROR, - details: T.INTERNAL_EXCEPTION, - err: e, - error: e, - fatal: !0, - }); - return null; - }), - (r._handleTransmuxerFlush = function (e) { - var t = this.getCurrentContext(e); - if (t && this.state === ei) { - var r = t.frag, - i = t.part, - n = t.level, - s = self.performance.now(); - (r.stats.parsing.end = s), - i && (i.stats.parsing.end = s), - this.updateLevelTiming(r, i, n, e.partial); - } else - this.fragCurrent || - this.state === Yr || - this.state === ii || - (this.state = zr); - }), - (r.getCurrentContext = function (e) { - var t = this.levels, - r = this.fragCurrent, - i = e.level, - n = e.sn, - s = e.part; - if (null == t || !t[i]) - return ( - this.warn( - "Levels object was unset while buffering fragment " + - n + - " of level " + - i + - ". The current chunk will not be buffered." - ), - null - ); - var a = t[i], - o = s > -1 ? Zt(a, n, s) : null, - l = o - ? o.fragment - : (function (e, t, r) { - if (null == e || !e.details) return null; - var i = e.details, - n = i.fragments[t - i.startSN]; - return ( - n || - ((n = i.fragmentHint) && n.sn === t - ? n - : t < i.startSN && r && r.sn === t - ? r - : null) - ); - })(a, n, r); - return l - ? (r && r !== l && (l.stats = r.stats), - { frag: l, part: o, level: a }) - : null; - }), - (r.bufferFragmentData = function (e, t, r, i, n) { - var s; - if (e && this.state === ei) { - var a = e.data1, - o = e.data2, - l = a; - if ( - (a && o && (l = Fe(a, o)), - null != (s = l) && s.length) - ) { - var h = { - type: e.type, - frag: t, - part: r, - chunkMeta: i, - parent: t.type, - data: l, - }; - if ( - (this.hls.trigger(E.BUFFER_APPENDING, h), - e.dropped && e.independent && !r) - ) { - if (n) return; - this.flushBufferGap(t); - } - } - } - }), - (r.flushBufferGap = function (e) { - var t = this.media; - if (t) - if (Mr.isBuffered(t, t.currentTime)) { - var r = t.currentTime, - i = Mr.bufferInfo(t, r, 0), - n = e.duration, - s = Math.min( - 2 * this.config.maxFragLookUpTolerance, - 0.25 * n - ), - a = Math.max( - Math.min(e.start - s, i.end - s), - r + s - ); - e.start - a > s && this.flushMainBuffer(a, e.start); - } else this.flushMainBuffer(0, e.start); - }), - (r.getFwdBufferInfo = function (e, t) { - var r = this.getLoadPosition(); - return m(r) ? this.getFwdBufferInfoAtPos(e, r, t) : null; - }), - (r.getFwdBufferInfoAtPos = function (e, t, r) { - var i = this.config.maxBufferHole, - n = Mr.bufferInfo(e, t, i); - if (0 === n.len && void 0 !== n.nextStart) { - var s = this.fragmentTracker.getBufferedFrag(t, r); - if (s && n.nextStart < s.end) - return Mr.bufferInfo(e, t, Math.max(n.nextStart, i)); - } - return n; - }), - (r.getMaxBufferLength = function (e) { - var t, - r = this.config; - return ( - (t = e - ? Math.max( - (8 * r.maxBufferSize) / e, - r.maxBufferLength - ) - : r.maxBufferLength), - Math.min(t, r.maxMaxBufferLength) - ); - }), - (r.reduceMaxBufferLength = function (e, t) { - var r = this.config, - i = Math.max(Math.min(e - t, r.maxBufferLength), t), - n = Math.max(e - 3 * t, r.maxMaxBufferLength / 2, i); - return ( - n >= i && - ((r.maxMaxBufferLength = n), - this.warn("Reduce max buffer length to " + n + "s"), - !0) - ); - }), - (r.getAppendedFrag = function (e, t) { - var r = this.fragmentTracker.getAppendedFrag(e, Lt); - return r && "fragment" in r ? r.fragment : r; - }), - (r.getNextFragment = function (e, t) { - var r = t.fragments, - i = r.length; - if (!i) return null; - var n, - s = this.config, - a = r[0].start; - if (t.live) { - var o = s.initialLiveManifestSize; - if (i < o) - return ( - this.warn( - "Not enough fragments to start playback (have: " + - i + - ", need: " + - o + - ")" - ), - null - ); - ((!t.PTSKnown && - !this.startFragRequested && - -1 === this.startPosition) || - e < a) && - ((n = this.getInitialLiveFragment(t, r)), - (this.startPosition = this.nextLoadPosition = - n ? this.hls.liveSyncPosition || n.start : e)); - } else e <= a && (n = r[0]); - if (!n) { - var l = s.lowLatencyMode ? t.partEnd : t.fragmentEnd; - n = this.getFragmentAtPosition(e, l, t); - } - return this.mapToInitFragWhenRequired(n); - }), - (r.isLoopLoading = function (e, t) { - var r = this.fragmentTracker.getState(e); - return ( - (r === Pr || (r === wr && !!e.gap)) && - this.nextLoadPosition > t - ); - }), - (r.getNextFragmentLoopLoading = function (e, t, r, i, n) { - var s = e.gap, - a = this.getNextFragment(this.nextLoadPosition, t); - if (null === a) return a; - if (((e = a), s && e && !e.gap && r.nextStart)) { - var o = this.getFwdBufferInfoAtPos( - this.mediaBuffer ? this.mediaBuffer : this.media, - r.nextStart, - i - ); - if (null !== o && r.len + o.len >= n) - return ( - this.log( - 'buffer full after gaps in "' + - i + - '" playlist starting at sn: ' + - e.sn - ), - null - ); - } - return e; - }), - (r.mapToInitFragWhenRequired = function (e) { - return null == e || - !e.initSegment || - (null != e && e.initSegment.data) || - this.bitrateTest - ? e - : e.initSegment; - }), - (r.getNextPart = function (e, t, r) { - for ( - var i = -1, n = !1, s = !0, a = 0, o = e.length; - a < o; - a++ - ) { - var l = e[a]; - if (((s = s && !l.independent), i > -1 && r < l.start)) - break; - var h = l.loaded; - h - ? (i = -1) - : (n || l.independent || s) && - l.fragment === t && - (i = a), - (n = h); - } - return i; - }), - (r.loadedEndOfParts = function (e, t) { - var r = e[e.length - 1]; - return r && t > r.start && r.loaded; - }), - (r.getInitialLiveFragment = function (e, t) { - var r = this.fragPrevious, - i = null; - if (r) { - if ( - (e.hasProgramDateTime && - (this.log( - "Live playlist, switching playlist, load frag with same PDT: " + - r.programDateTime - ), - (i = (function (e, t, r) { - if ( - null === t || - !Array.isArray(e) || - !e.length || - !m(t) - ) - return null; - if (t < (e[0].programDateTime || 0)) return null; - if ( - t >= (e[e.length - 1].endProgramDateTime || 0) - ) - return null; - r = r || 0; - for (var i = 0; i < e.length; ++i) { - var n = e[i]; - if (ur(t, r, n)) return n; - } - return null; - })( - t, - r.endProgramDateTime, - this.config.maxFragLookUpTolerance - ))), - !i) - ) { - var n = r.sn + 1; - if (n >= e.startSN && n <= e.endSN) { - var s = t[n - e.startSN]; - r.cc === s.cc && - ((i = s), - this.log( - "Live playlist, switching playlist, load frag with next SN: " + - i.sn - )); - } - i || - ((i = (function (e, t) { - return or(e, function (e) { - return e.cc < t ? 1 : e.cc > t ? -1 : 0; - }); - })(t, r.cc)), - i && - this.log( - "Live playlist, switching playlist, load frag with same CC: " + - i.sn - )); - } - } else { - var a = this.hls.liveSyncPosition; - null !== a && - (i = this.getFragmentAtPosition( - a, - this.bitrateTest ? e.fragmentEnd : e.edge, - e - )); - } - return i; - }), - (r.getFragmentAtPosition = function (e, t, r) { - var i, - n = this.config, - s = this.fragPrevious, - a = r.fragments, - o = r.endSN, - l = r.fragmentHint, - h = n.maxFragLookUpTolerance, - u = r.partList, - d = !!(n.lowLatencyMode && null != u && u.length && l); - if ( - (d && - l && - !this.bitrateTest && - ((a = a.concat(l)), (o = l.sn)), - (i = - e < t - ? lr(s, a, e, e > t - h ? 0 : h) - : a[a.length - 1])) - ) { - var c = i.sn - r.startSN, - f = this.fragmentTracker.getState(i); - if ( - ((f === Pr || (f === wr && i.gap)) && (s = i), - s && - i.sn === s.sn && - (!d || u[0].fragment.sn > i.sn) && - s && - i.level === s.level) - ) { - var g = a[c + 1]; - i = - i.sn < o && this.fragmentTracker.getState(g) !== Pr - ? g - : null; - } - } - return i; - }), - (r.synchronizeToLiveEdge = function (e) { - var t = this.config, - r = this.media; - if (r) { - var i = this.hls.liveSyncPosition, - n = r.currentTime, - s = e.fragments[0].start, - a = e.edge, - o = n >= s - t.maxFragLookUpTolerance && n <= a; - if (null !== i && r.duration > i && (n < i || !o)) { - var l = - void 0 !== t.liveMaxLatencyDuration - ? t.liveMaxLatencyDuration - : t.liveMaxLatencyDurationCount * - e.targetduration; - ((!o && r.readyState < 4) || n < a - l) && - (this.loadedmetadata || (this.nextLoadPosition = i), - r.readyState && - (this.warn( - "Playback: " + - n.toFixed(3) + - " is located too far from the end of live sliding playlist: " + - a + - ", reset currentTime to : " + - i.toFixed(3) - ), - (r.currentTime = i))); - } - } - }), - (r.alignPlaylists = function (e, t, r) { - var i = e.fragments.length; - if (!i) - return this.warn("No fragments in live playlist"), 0; - var n = e.fragments[0].start, - s = !t, - a = e.alignedSliding && m(n); - if (s || (!a && !n)) { - var o = this.fragPrevious; - !(function (e, t, r) { - t && - ((function (e, t, r) { - if ( - (function (e, t, r) { - return !( - !t || - !( - r.endCC > r.startCC || - (e && e.cc < r.startCC) - ) - ); - })(e, r, t) - ) { - var i = (function (e, t) { - var r = e.fragments, - i = t.fragments; - if (i.length && r.length) { - var n = Or(r, i[0].cc); - if (n && (!n || n.startPTS)) return n; - A.log( - "No frag in previous level to align on" - ); - } else A.log("No fragments to align"); - })(r, t); - i && - m(i.start) && - (A.log( - "Adjusting PTS using last level due to CC increase within current level " + - t.url - ), - Nr(i.start, t)); - } - })(e, r, t), - !r.alignedSliding && t && Br(r, t), - r.alignedSliding || - !t || - r.skippedSegments || - Qt(t, r)); - })(o, r, e); - var l = e.fragments[0].start; - return ( - this.log( - "Live playlist sliding: " + - l.toFixed(2) + - " start-sn: " + - (t ? t.startSN : "na") + - "->" + - e.startSN + - " prev-sn: " + - (o ? o.sn : "na") + - " fragments: " + - i - ), - l - ); - } - return n; - }), - (r.waitForCdnTuneIn = function (e) { - return ( - e.live && - e.canBlockReload && - e.partTarget && - e.tuneInGoal > - Math.max(e.partHoldBack, 3 * e.partTarget) - ); - }), - (r.setStartPosition = function (e, t) { - var r = this.startPosition; - if ( - (r < t && (r = -1), - -1 === r || -1 === this.lastCurrentTime) - ) { - var i = null !== this.startTimeOffset, - n = i ? this.startTimeOffset : e.startTimeOffset; - null !== n && m(n) - ? ((r = t + n), - n < 0 && (r += e.totalduration), - (r = Math.min(Math.max(t, r), t + e.totalduration)), - this.log( - "Start time offset " + - n + - " found in " + - (i ? "multivariant" : "media") + - " playlist, adjust startPosition to " + - r - ), - (this.startPosition = r)) - : e.live - ? (r = this.hls.liveSyncPosition || t) - : (this.startPosition = r = 0), - (this.lastCurrentTime = r); - } - this.nextLoadPosition = r; - }), - (r.getLoadPosition = function () { - var e = this.media, - t = 0; - return ( - this.loadedmetadata && e - ? (t = e.currentTime) - : this.nextLoadPosition && - (t = this.nextLoadPosition), - t - ); - }), - (r.handleFragLoadAborted = function (e, t) { - this.transmuxer && - "initSegment" !== e.sn && - e.stats.aborted && - (this.warn( - "Fragment " + - e.sn + - (t ? " part " + t.index : "") + - " of level " + - e.level + - " was aborted" - ), - this.resetFragmentLoading(e)); - }), - (r.resetFragmentLoading = function (e) { - (this.fragCurrent && - (this.fragContextChanged(e) || this.state === Jr)) || - (this.state = zr); - }), - (r.onFragmentOrKeyLoadError = function (e, t) { - if (t.chunkMeta && !t.frag) { - var r = this.getCurrentContext(t.chunkMeta); - r && (t.frag = r.frag); - } - var i = t.frag; - if (i && i.type === e && this.levels) - if (this.fragContextChanged(i)) { - var n; - this.warn( - "Frag load error must match current frag to retry " + - i.url + - " > " + - (null == (n = this.fragCurrent) ? void 0 : n.url) - ); - } else { - var s = t.details === T.FRAG_GAP; - s && this.fragmentTracker.fragBuffered(i, !0); - var a = t.errorAction, - o = a || {}, - l = o.action, - h = o.retryCount, - u = void 0 === h ? 0 : h, - d = o.retryConfig; - if (a && 5 === l && d) { - this.resetStartWhenNotLoaded(this.levelLastLoaded); - var c = nr(d, u); - this.warn( - "Fragment " + - i.sn + - " of " + - e + - " " + - i.level + - " errored with " + - t.details + - ", retrying loading " + - (u + 1) + - "/" + - d.maxNumRetry + - " in " + - c + - "ms" - ), - (a.resolved = !0), - (this.retryDate = self.performance.now() + c), - (this.state = Jr); - } else if (d && a) { - if ( - (this.resetFragmentErrors(e), - !(u < d.maxNumRetry)) - ) - return void A.warn( - t.details + - " reached or exceeded max retry (" + - u + - ")" - ); - s || 3 === l || (a.resolved = !0); - } else - 2 === (null == a ? void 0 : a.action) - ? (this.state = si) - : (this.state = ii); - this.tickImmediate(); - } - }), - (r.reduceLengthAndFlushBuffer = function (e) { - if (this.state === ei || this.state === ti) { - var t = e.frag, - r = e.parent, - i = this.getFwdBufferInfo(this.mediaBuffer, r), - n = i && i.len > 0.5; - n && - this.reduceMaxBufferLength( - i.len, - (null == t ? void 0 : t.duration) || 10 - ); - var s = !n; - return ( - s && - this.warn( - "Buffer full error while media.currentTime is not buffered, flush " + - r + - " buffer" - ), - t && - (this.fragmentTracker.removeFragment(t), - (this.nextLoadPosition = t.start)), - this.resetLoadingState(), - s - ); - } - return !1; - }), - (r.resetFragmentErrors = function (e) { - e === bt && (this.fragCurrent = null), - this.loadedmetadata || (this.startFragRequested = !1), - this.state !== Yr && (this.state = zr); - }), - (r.afterBufferFlushed = function (e, t, r) { - if (e) { - var i = Mr.getBuffered(e); - this.fragmentTracker.detectEvictedFragments(t, i, r), - this.state === ri && this.resetLoadingState(); - } - }), - (r.resetLoadingState = function () { - this.log("Reset loading state"), - (this.fragCurrent = null), - (this.fragPrevious = null), - (this.state = zr); - }), - (r.resetStartWhenNotLoaded = function (e) { - if (!this.loadedmetadata) { - this.startFragRequested = !1; - var t = e ? e.details : null; - null != t && t.live - ? ((this.startPosition = -1), - this.setStartPosition(t, 0), - this.resetLoadingState()) - : (this.nextLoadPosition = this.startPosition); - } - }), - (r.resetWhenMissingContext = function (e) { - this.warn( - "The loading context changed while buffering fragment " + - e.sn + - " of level " + - e.level + - ". This chunk will not be buffered." - ), - this.removeUnbufferedFrags(), - this.resetStartWhenNotLoaded(this.levelLastLoaded), - this.resetLoadingState(); - }), - (r.removeUnbufferedFrags = function (e) { - void 0 === e && (e = 0), - this.fragmentTracker.removeFragmentsInRange( - e, - 1 / 0, - this.playlistType, - !1, - !0 - ); - }), - (r.updateLevelTiming = function (e, t, r, i) { - var n, - s = this, - a = r.details; - if (a) { - if ( - !Object.keys(e.elementaryStreams).reduce(function ( - t, - n - ) { - var o = e.elementaryStreams[n]; - if (o) { - var l = o.endPTS - o.startPTS; - if (l <= 0) - return ( - s.warn( - "Could not parse fragment " + - e.sn + - " " + - n + - " duration reliably (" + - l + - ")" - ), - t || !1 - ); - var h = i - ? 0 - : zt( - a, - e, - o.startPTS, - o.endPTS, - o.startDTS, - o.endDTS - ); - return ( - s.hls.trigger(E.LEVEL_PTS_UPDATED, { - details: a, - level: r, - drift: h, - type: n, - frag: e, - start: o.startPTS, - end: o.endPTS, - }), - !0 - ); - } - return t; - }, - !1) && - null === - (null == (n = this.transmuxer) ? void 0 : n.error) - ) { - var o = new Error( - "Found no media in fragment " + - e.sn + - " of level " + - e.level + - " resetting transmuxer to fallback to playlist timing" - ); - if ( - (0 === r.fragmentError && - (r.fragmentError++, - (e.gap = !0), - this.fragmentTracker.removeFragment(e), - this.fragmentTracker.fragBuffered(e, !0)), - this.warn(o.message), - this.hls.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.FRAG_PARSING_ERROR, - fatal: !1, - error: o, - frag: e, - reason: - "Found no media in msn " + - e.sn + - ' of level "' + - r.url + - '"', - }), - !this.hls) - ) - return; - this.resetTransmuxer(); - } - (this.state = ti), - this.hls.trigger(E.FRAG_PARSED, { frag: e, part: t }); - } else this.warn("level.details undefined"); - }), - (r.resetTransmuxer = function () { - this.transmuxer && - (this.transmuxer.destroy(), (this.transmuxer = null)); - }), - (r.recoverWorkerError = function (e) { - "demuxerWorker" === e.event && - (this.fragmentTracker.removeAllFragments(), - this.resetTransmuxer(), - this.resetStartWhenNotLoaded(this.levelLastLoaded), - this.resetLoadingState()); - }), - a(t, [ - { - key: "state", - get: function () { - return this._state; - }, - set: function (e) { - var t = this._state; - t !== e && - ((this._state = e), this.log(t + "->" + e)); - }, - }, - ]), - t - ); - })(br), - oi = (function () { - function e() { - (this.chunks = []), (this.dataLength = 0); - } - var t = e.prototype; - return ( - (t.push = function (e) { - this.chunks.push(e), (this.dataLength += e.length); - }), - (t.flush = function () { - var e, - t = this.chunks, - r = this.dataLength; - return t.length - ? ((e = - 1 === t.length - ? t[0] - : (function (e, t) { - for ( - var r = new Uint8Array(t), i = 0, n = 0; - n < e.length; - n++ - ) { - var s = e[n]; - r.set(s, i), (i += s.length); - } - return r; - })(t, r)), - this.reset(), - e) - : new Uint8Array(0); - }), - (t.reset = function () { - (this.chunks.length = 0), (this.dataLength = 0); - }), - e - ); - })(); - function li(e, t) { - return ( - void 0 === e && (e = ""), - void 0 === t && (t = 9e4), - { - type: e, - id: -1, - pid: -1, - inputTimeScale: t, - sequenceNumber: -1, - samples: [], - dropped: 0, - } - ); - } - var hi = (function () { - function e() { - (this._audioTrack = void 0), - (this._id3Track = void 0), - (this.frameIndex = 0), - (this.cachedData = null), - (this.basePTS = null), - (this.initPTS = null), - (this.lastPTS = null); - } - var t = e.prototype; - return ( - (t.resetInitSegment = function (e, t, r, i) { - this._id3Track = { - type: "id3", - id: 3, - pid: -1, - inputTimeScale: 9e4, - sequenceNumber: 0, - samples: [], - dropped: 0, - }; - }), - (t.resetTimeStamp = function (e) { - (this.initPTS = e), this.resetContiguity(); - }), - (t.resetContiguity = function () { - (this.basePTS = null), - (this.lastPTS = null), - (this.frameIndex = 0); - }), - (t.canParse = function (e, t) { - return !1; - }), - (t.appendFrame = function (e, t, r) {}), - (t.demux = function (e, t) { - this.cachedData && - ((e = Fe(this.cachedData, e)), - (this.cachedData = null)); - var r, - i = ne(e, 0), - n = i ? i.length : 0, - s = this._audioTrack, - a = this._id3Track, - o = i ? oe(i) : void 0, - l = e.length; - for ( - (null === this.basePTS || - (0 === this.frameIndex && m(o))) && - ((this.basePTS = ui(o, t, this.initPTS)), - (this.lastPTS = this.basePTS)), - null === this.lastPTS && - (this.lastPTS = this.basePTS), - i && - i.length > 0 && - a.samples.push({ - pts: this.lastPTS, - dts: this.lastPTS, - data: i, - type: xt, - duration: Number.POSITIVE_INFINITY, - }); - n < l; - - ) { - if (this.canParse(e, n)) { - var h = this.appendFrame(s, e, n); - h - ? (this.frameIndex++, - (this.lastPTS = h.sample.pts), - (r = n += h.length)) - : (n = l); - } else - ae(e, n) - ? ((i = ne(e, n)), - a.samples.push({ - pts: this.lastPTS, - dts: this.lastPTS, - data: i, - type: xt, - duration: Number.POSITIVE_INFINITY, - }), - (r = n += i.length)) - : n++; - if (n === l && r !== l) { - var u = ee(e, r); - this.cachedData - ? (this.cachedData = Fe(this.cachedData, u)) - : (this.cachedData = u); - } - } - return { - audioTrack: s, - videoTrack: li(), - id3Track: a, - textTrack: li(), - }; - }), - (t.demuxSampleAes = function (e, t, r) { - return Promise.reject( - new Error( - "[" + - this + - "] This demuxer does not support Sample-AES decryption" - ) - ); - }), - (t.flush = function (e) { - var t = this.cachedData; - return ( - t && ((this.cachedData = null), this.demux(t, 0)), - { - audioTrack: this._audioTrack, - videoTrack: li(), - id3Track: this._id3Track, - textTrack: li(), - } - ); - }), - (t.destroy = function () {}), - e - ); - })(), - ui = function (e, t, r) { - return m(e) - ? 90 * e - : 9e4 * t + (r ? (9e4 * r.baseTime) / r.timescale : 0); - }; - function di(e, t) { - return 255 === e[t] && 240 == (246 & e[t + 1]); - } - function ci(e, t) { - return 1 & e[t + 1] ? 7 : 9; - } - function fi(e, t) { - return ( - ((3 & e[t + 3]) << 11) | - (e[t + 4] << 3) | - ((224 & e[t + 5]) >>> 5) - ); - } - function gi(e, t) { - return t + 1 < e.length && di(e, t); - } - function pi(e, t) { - if (gi(e, t)) { - var r = ci(e, t); - if (t + r >= e.length) return !1; - var i = fi(e, t); - if (i <= r) return !1; - var n = t + i; - return n === e.length || gi(e, n); - } - return !1; - } - function mi(e, t, r, i, n) { - if (!e.samplerate) { - var s = (function (e, t, r, i) { - var n, - s, - a, - o, - l = navigator.userAgent.toLowerCase(), - h = i, - u = [ - 96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, - 12e3, 11025, 8e3, 7350, - ]; - n = 1 + ((192 & t[r + 2]) >>> 6); - var d = (60 & t[r + 2]) >>> 2; - if (!(d > u.length - 1)) - return ( - (a = (1 & t[r + 2]) << 2), - (a |= (192 & t[r + 3]) >>> 6), - A.log( - "manifest codec:" + - i + - ", ADTS type:" + - n + - ", samplingIndex:" + - d - ), - /firefox/i.test(l) - ? d >= 6 - ? ((n = 5), (o = new Array(4)), (s = d - 3)) - : ((n = 2), (o = new Array(2)), (s = d)) - : -1 !== l.indexOf("android") - ? ((n = 2), (o = new Array(2)), (s = d)) - : ((n = 5), - (o = new Array(4)), - (i && - (-1 !== i.indexOf("mp4a.40.29") || - -1 !== i.indexOf("mp4a.40.5"))) || - (!i && d >= 6) - ? (s = d - 3) - : (((i && - -1 !== i.indexOf("mp4a.40.2") && - ((d >= 6 && 1 === a) || - /vivaldi/i.test(l))) || - (!i && 1 === a)) && - ((n = 2), (o = new Array(2))), - (s = d))), - (o[0] = n << 3), - (o[0] |= (14 & d) >> 1), - (o[1] |= (1 & d) << 7), - (o[1] |= a << 3), - 5 === n && - ((o[1] |= (14 & s) >> 1), - (o[2] = (1 & s) << 7), - (o[2] |= 8), - (o[3] = 0)), - { - config: o, - samplerate: u[d], - channelCount: a, - codec: "mp4a.40." + n, - manifestCodec: h, - } - ); - var c = new Error("invalid ADTS sampling index:" + d); - e.emit(E.ERROR, E.ERROR, { - type: S.MEDIA_ERROR, - details: T.FRAG_PARSING_ERROR, - fatal: !0, - error: c, - reason: c.message, - }); - })(t, r, i, n); - if (!s) return; - (e.config = s.config), - (e.samplerate = s.samplerate), - (e.channelCount = s.channelCount), - (e.codec = s.codec), - (e.manifestCodec = s.manifestCodec), - A.log( - "parsed codec:" + - e.codec + - ", rate:" + - s.samplerate + - ", channels:" + - s.channelCount - ); - } - } - function vi(e) { - return 9216e4 / e; - } - function yi(e, t, r, i, n) { - var s, - a = i + n * vi(e.samplerate), - o = (function (e, t) { - var r = ci(e, t); - if (t + r <= e.length) { - var i = fi(e, t) - r; - if (i > 0) return { headerLength: r, frameLength: i }; - } - })(t, r); - if (o) { - var l = o.frameLength, - h = o.headerLength, - u = h + l, - d = Math.max(0, r + u - t.length); - d - ? (s = new Uint8Array(u - h)).set( - t.subarray(r + h, t.length), - 0 - ) - : (s = t.subarray(r + h, r + u)); - var c = { unit: s, pts: a }; - return ( - d || e.samples.push(c), { sample: c, length: u, missing: d } - ); - } - var f = t.length - r; - return ( - (s = new Uint8Array(f)).set(t.subarray(r, t.length), 0), - { sample: { unit: s, pts: a }, length: f, missing: -1 } - ); - } - var Ei = null, - Si = [ - 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, - ], - Ti = [44100, 48e3, 32e3, 22050, 24e3, 16e3, 11025, 12e3, 8e3], - _i = [ - [0, 72, 144, 12], - [0, 0, 0, 0], - [0, 72, 144, 12], - [0, 144, 144, 12], - ], - Li = [0, 1, 1, 4]; - function bi(e, t, r, i, n) { - if (!(r + 24 > t.length)) { - var s = Ri(t, r); - if (s && r + s.frameLength <= t.length) { - var a = i + n * ((9e4 * s.samplesPerFrame) / s.sampleRate), - o = { - unit: t.subarray(r, r + s.frameLength), - pts: a, - dts: a, - }; - return ( - (e.config = []), - (e.channelCount = s.channelCount), - (e.samplerate = s.sampleRate), - e.samples.push(o), - { sample: o, length: s.frameLength, missing: 0 } - ); - } - } - } - function Ri(e, t) { - var r = (e[t + 1] >> 3) & 3, - i = (e[t + 1] >> 1) & 3, - n = (e[t + 2] >> 4) & 15, - s = (e[t + 2] >> 2) & 3; - if (1 !== r && 0 !== n && 15 !== n && 3 !== s) { - var a = (e[t + 2] >> 1) & 1, - o = e[t + 3] >> 6, - l = - 1e3 * - Si[14 * (3 === r ? 3 - i : 3 === i ? 3 : 4) + n - 1], - h = Ti[3 * (3 === r ? 0 : 2 === r ? 1 : 2) + s], - u = 3 === o ? 1 : 2, - d = _i[r][i], - c = Li[i], - f = 8 * d * c, - g = Math.floor((d * l) / h + a) * c; - if (null === Ei) { - var p = (navigator.userAgent || "").match(/Chrome\/(\d+)/i); - Ei = p ? parseInt(p[1]) : 0; - } - return ( - !!Ei && - Ei <= 87 && - 2 === i && - l >= 224e3 && - 0 === o && - (e[t + 3] = 128 | e[t + 3]), - { - sampleRate: h, - channelCount: u, - frameLength: g, - samplesPerFrame: f, - } - ); - } - } - function Ai(e, t) { - return !(255 !== e[t] || 224 & ~e[t + 1] || !(6 & e[t + 1])); - } - function wi(e, t) { - return t + 1 < e.length && Ai(e, t); - } - function Pi(e, t) { - if (t + 1 < e.length && Ai(e, t)) { - var r = Ri(e, t), - i = 4; - null != r && r.frameLength && (i = r.frameLength); - var n = t + i; - return n === e.length || wi(e, n); - } - return !1; - } - var Ii = (function (e) { - function t(t, r) { - var i; - return ( - ((i = e.call(this) || this).observer = void 0), - (i.config = void 0), - (i.observer = t), - (i.config = r), - i - ); - } - l(t, e); - var r = t.prototype; - return ( - (r.resetInitSegment = function (t, r, i, n) { - e.prototype.resetInitSegment.call(this, t, r, i, n), - (this._audioTrack = { - container: "audio/adts", - type: "audio", - id: 2, - pid: -1, - sequenceNumber: 0, - segmentCodec: "aac", - samples: [], - manifestCodec: r, - duration: n, - inputTimeScale: 9e4, - dropped: 0, - }); - }), - (t.probe = function (e) { - if (!e) return !1; - var t = ne(e, 0), - r = (null == t ? void 0 : t.length) || 0; - if (Pi(e, r)) return !1; - for (var i = e.length; r < i; r++) - if (pi(e, r)) - return A.log("ADTS sync word found !"), !0; - return !1; - }), - (r.canParse = function (e, t) { - return (function (e, t) { - return ( - (function (e, t) { - return t + 5 < e.length; - })(e, t) && - di(e, t) && - fi(e, t) <= e.length - t - ); - })(e, t); - }), - (r.appendFrame = function (e, t, r) { - mi(e, this.observer, t, r, e.manifestCodec); - var i = yi(e, t, r, this.basePTS, this.frameIndex); - if (i && 0 === i.missing) return i; - }), - t - ); - })(hi), - Ci = /\/emsg[-/]ID3/i, - ki = (function () { - function e(e, t) { - (this.remainderData = null), - (this.timeOffset = 0), - (this.config = void 0), - (this.videoTrack = void 0), - (this.audioTrack = void 0), - (this.id3Track = void 0), - (this.txtTrack = void 0), - (this.config = t); - } - var t = e.prototype; - return ( - (t.resetTimeStamp = function () {}), - (t.resetInitSegment = function (e, t, r, i) { - var n = (this.videoTrack = li("video", 1)), - s = (this.audioTrack = li("audio", 1)), - a = (this.txtTrack = li("text", 1)); - if ( - ((this.id3Track = li("id3", 1)), - (this.timeOffset = 0), - null != e && e.byteLength) - ) { - var o = Ie(e); - if (o.video) { - var l = o.video, - h = l.id, - u = l.timescale, - d = l.codec; - (n.id = h), - (n.timescale = a.timescale = u), - (n.codec = d); - } - if (o.audio) { - var c = o.audio, - f = c.id, - g = c.timescale, - p = c.codec; - (s.id = f), (s.timescale = g), (s.codec = p); - } - (a.id = Se.text), - (n.sampleDuration = 0), - (n.duration = s.duration = i); - } - }), - (t.resetContiguity = function () { - this.remainderData = null; - }), - (e.probe = function (e) { - return (function (e) { - for (var t = e.byteLength, r = 0; r < t; ) { - var i = Le(e, r); - if ( - i > 8 && - 109 === e[r + 4] && - 111 === e[r + 5] && - 111 === e[r + 6] && - 102 === e[r + 7] - ) - return !0; - r = i > 1 ? r + i : t; - } - return !1; - })(e); - }), - (t.demux = function (e, t) { - this.timeOffset = t; - var r = e, - i = this.videoTrack, - n = this.txtTrack; - if (this.config.progressive) { - this.remainderData && (r = Fe(this.remainderData, e)); - var s = (function (e) { - var t = { valid: null, remainder: null }, - r = we(e, ["moof"]); - if (r.length < 2) return (t.remainder = e), t; - var i = r[r.length - 1]; - return ( - (t.valid = ee(e, 0, i.byteOffset - 8)), - (t.remainder = ee(e, i.byteOffset - 8)), - t - ); - })(r); - (this.remainderData = s.remainder), - (i.samples = s.valid || new Uint8Array()); - } else i.samples = r; - var a = this.extractID3Track(i, t); - return ( - (n.samples = Ne(t, i)), - { - videoTrack: i, - audioTrack: this.audioTrack, - id3Track: a, - textTrack: this.txtTrack, - } - ); - }), - (t.flush = function () { - var e = this.timeOffset, - t = this.videoTrack, - r = this.txtTrack; - (t.samples = this.remainderData || new Uint8Array()), - (this.remainderData = null); - var i = this.extractID3Track(t, this.timeOffset); - return ( - (r.samples = Ne(e, t)), - { - videoTrack: t, - audioTrack: li(), - id3Track: i, - textTrack: li(), - } - ); - }), - (t.extractID3Track = function (e, t) { - var r = this.id3Track; - if (e.samples.length) { - var i = we(e.samples, ["emsg"]); - i && - i.forEach(function (e) { - var i = (function (e) { - var t = e[0], - r = "", - i = "", - n = 0, - s = 0, - a = 0, - o = 0, - l = 0, - h = 0; - if (0 === t) { - for (; "\0" !== Te(e.subarray(h, h + 1)); ) - (r += Te(e.subarray(h, h + 1))), (h += 1); - for ( - r += Te(e.subarray(h, h + 1)), h += 1; - "\0" !== Te(e.subarray(h, h + 1)); - - ) - (i += Te(e.subarray(h, h + 1))), (h += 1); - (i += Te(e.subarray(h, h + 1))), - (h += 1), - (n = Le(e, 12)), - (s = Le(e, 16)), - (o = Le(e, 20)), - (l = Le(e, 24)), - (h = 28); - } else if (1 === t) { - n = Le(e, (h += 4)); - var u = Le(e, (h += 4)), - d = Le(e, (h += 4)); - for ( - h += 4, - a = Math.pow(2, 32) * u + d, - v(a) || - ((a = Number.MAX_SAFE_INTEGER), - A.warn( - "Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box" - )), - o = Le(e, h), - l = Le(e, (h += 4)), - h += 4; - "\0" !== Te(e.subarray(h, h + 1)); - - ) - (r += Te(e.subarray(h, h + 1))), (h += 1); - for ( - r += Te(e.subarray(h, h + 1)), h += 1; - "\0" !== Te(e.subarray(h, h + 1)); - - ) - (i += Te(e.subarray(h, h + 1))), (h += 1); - (i += Te(e.subarray(h, h + 1))), (h += 1); - } - return { - schemeIdUri: r, - value: i, - timeScale: n, - presentationTime: a, - presentationTimeDelta: s, - eventDuration: o, - id: l, - payload: e.subarray(h, e.byteLength), - }; - })(e); - if (Ci.test(i.schemeIdUri)) { - var n = m(i.presentationTime) - ? i.presentationTime / i.timeScale - : t + i.presentationTimeDelta / i.timeScale, - s = - 4294967295 === i.eventDuration - ? Number.POSITIVE_INFINITY - : i.eventDuration / i.timeScale; - s <= 0.001 && (s = Number.POSITIVE_INFINITY); - var a = i.payload; - r.samples.push({ - data: a, - len: a.byteLength, - dts: n, - pts: n, - type: Ot, - duration: s, - }); - } - }); - } - return r; - }), - (t.demuxSampleAes = function (e, t, r) { - return Promise.reject( - new Error( - "The MP4 demuxer does not support SAMPLE-AES decryption" - ) - ); - }), - (t.destroy = function () {}), - e - ); - })(), - Di = function (e, t) { - var r = 0, - i = 5; - t += i; - for ( - var n = new Uint32Array(1), - s = new Uint32Array(1), - a = new Uint8Array(1); - i > 0; - - ) { - a[0] = e[t]; - var o = Math.min(i, 8), - l = 8 - o; - (s[0] = (4278190080 >>> (24 + l)) << l), - (n[0] = (a[0] & s[0]) >> l), - (r = r ? (r << o) | n[0] : n[0]), - (t += 1), - (i -= o); - } - return r; - }, - Mi = (function (e) { - function t(t) { - var r; - return ( - ((r = e.call(this) || this).observer = void 0), - (r.observer = t), - r - ); - } - l(t, e); - var r = t.prototype; - return ( - (r.resetInitSegment = function (t, r, i, n) { - e.prototype.resetInitSegment.call(this, t, r, i, n), - (this._audioTrack = { - container: "audio/ac-3", - type: "audio", - id: 2, - pid: -1, - sequenceNumber: 0, - segmentCodec: "ac3", - samples: [], - manifestCodec: r, - duration: n, - inputTimeScale: 9e4, - dropped: 0, - }); - }), - (r.canParse = function (e, t) { - return t + 64 < e.length; - }), - (r.appendFrame = function (e, t, r) { - var i = xi(e, t, r, this.basePTS, this.frameIndex); - if (-1 !== i) - return { - sample: e.samples[e.samples.length - 1], - length: i, - missing: 0, - }; - }), - (t.probe = function (e) { - if (!e) return !1; - var t = ne(e, 0); - if (!t) return !1; - var r = t.length; - return ( - 11 === e[r] && - 119 === e[r + 1] && - void 0 !== oe(t) && - Di(e, r) < 16 - ); - }), - t - ); - })(hi); - function xi(e, t, r, i, n) { - if (r + 8 > t.length) return -1; - if (11 !== t[r] || 119 !== t[r + 1]) return -1; - var s = t[r + 4] >> 6; - if (s >= 3) return -1; - var a = [48e3, 44100, 32e3][s], - o = 63 & t[r + 4], - l = - 2 * - [ - 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, - ][3 * o + s]; - if (r + l > t.length) return -1; - var h = t[r + 6] >> 5, - u = 0; - 2 === h - ? (u += 2) - : (1 & h && 1 !== h && (u += 2), 4 & h && (u += 2)); - var d = (((t[r + 6] << 8) | t[r + 7]) >> (12 - u)) & 1, - c = [2, 1, 2, 3, 3, 4, 4, 5][h] + d, - f = t[r + 5] >> 3, - g = 7 & t[r + 5], - p = new Uint8Array([ - (s << 6) | (f << 1) | (g >> 2), - ((3 & g) << 6) | (h << 3) | (d << 2) | (o >> 4), - (o << 4) & 224, - ]), - m = i + n * ((1536 / a) * 9e4), - v = t.subarray(r, r + l); - return ( - (e.config = p), - (e.channelCount = c), - (e.samplerate = a), - e.samples.push({ unit: v, pts: m }), - l - ); - } - var Oi = (function () { - function e() { - this.VideoSample = null; - } - var t = e.prototype; - return ( - (t.createVideoSample = function (e, t, r, i) { - return { - key: e, - frame: !1, - pts: t, - dts: r, - units: [], - debug: i, - length: 0, - }; - }), - (t.getLastNalUnit = function (e) { - var t, - r, - i = this.VideoSample; - if ( - ((i && 0 !== i.units.length) || (i = e[e.length - 1]), - null != (t = i) && t.units) - ) { - var n = i.units; - r = n[n.length - 1]; - } - return r; - }), - (t.pushAccessUnit = function (e, t) { - if (e.units.length && e.frame) { - if (void 0 === e.pts) { - var r = t.samples, - i = r.length; - if (!i) return void t.dropped++; - var n = r[i - 1]; - (e.pts = n.pts), (e.dts = n.dts); - } - t.samples.push(e); - } - e.debug.length && - A.log(e.pts + "/" + e.dts + ":" + e.debug); - }), - e - ); - })(), - Fi = (function () { - function e(e) { - (this.data = void 0), - (this.bytesAvailable = void 0), - (this.word = void 0), - (this.bitsAvailable = void 0), - (this.data = e), - (this.bytesAvailable = e.byteLength), - (this.word = 0), - (this.bitsAvailable = 0); - } - var t = e.prototype; - return ( - (t.loadWord = function () { - var e = this.data, - t = this.bytesAvailable, - r = e.byteLength - t, - i = new Uint8Array(4), - n = Math.min(4, t); - if (0 === n) throw new Error("no bytes available"); - i.set(e.subarray(r, r + n)), - (this.word = new DataView(i.buffer).getUint32(0)), - (this.bitsAvailable = 8 * n), - (this.bytesAvailable -= n); - }), - (t.skipBits = function (e) { - var t; - (e = Math.min( - e, - 8 * this.bytesAvailable + this.bitsAvailable - )), - this.bitsAvailable > e - ? ((this.word <<= e), (this.bitsAvailable -= e)) - : ((e -= this.bitsAvailable), - (e -= (t = e >> 3) << 3), - (this.bytesAvailable -= t), - this.loadWord(), - (this.word <<= e), - (this.bitsAvailable -= e)); - }), - (t.readBits = function (e) { - var t = Math.min(this.bitsAvailable, e), - r = this.word >>> (32 - t); - if ( - (e > 32 && - A.error("Cannot read more than 32 bits at a time"), - (this.bitsAvailable -= t), - this.bitsAvailable > 0) - ) - this.word <<= t; - else { - if (!(this.bytesAvailable > 0)) - throw new Error("no bits available"); - this.loadWord(); - } - return (t = e - t) > 0 && this.bitsAvailable - ? (r << t) | this.readBits(t) - : r; - }), - (t.skipLZ = function () { - var e; - for (e = 0; e < this.bitsAvailable; ++e) - if (this.word & (2147483648 >>> e)) - return ( - (this.word <<= e), (this.bitsAvailable -= e), e - ); - return this.loadWord(), e + this.skipLZ(); - }), - (t.skipUEG = function () { - this.skipBits(1 + this.skipLZ()); - }), - (t.skipEG = function () { - this.skipBits(1 + this.skipLZ()); - }), - (t.readUEG = function () { - var e = this.skipLZ(); - return this.readBits(e + 1) - 1; - }), - (t.readEG = function () { - var e = this.readUEG(); - return 1 & e ? (1 + e) >>> 1 : -1 * (e >>> 1); - }), - (t.readBoolean = function () { - return 1 === this.readBits(1); - }), - (t.readUByte = function () { - return this.readBits(8); - }), - (t.readUShort = function () { - return this.readBits(16); - }), - (t.readUInt = function () { - return this.readBits(32); - }), - (t.skipScalingList = function (e) { - for (var t = 8, r = 8, i = 0; i < e; i++) - 0 !== r && (r = (t + this.readEG() + 256) % 256), - (t = 0 === r ? t : r); - }), - (t.readSPS = function () { - var e, - t, - r, - i = 0, - n = 0, - s = 0, - a = 0, - o = this.readUByte.bind(this), - l = this.readBits.bind(this), - h = this.readUEG.bind(this), - u = this.readBoolean.bind(this), - d = this.skipBits.bind(this), - c = this.skipEG.bind(this), - f = this.skipUEG.bind(this), - g = this.skipScalingList.bind(this); - o(); - var p = o(); - if ( - (l(5), - d(3), - o(), - f(), - 100 === p || - 110 === p || - 122 === p || - 244 === p || - 44 === p || - 83 === p || - 86 === p || - 118 === p || - 128 === p) - ) { - var m = h(); - if ((3 === m && d(1), f(), f(), d(1), u())) - for (t = 3 !== m ? 8 : 12, r = 0; r < t; r++) - u() && g(r < 6 ? 16 : 64); - } - f(); - var v = h(); - if (0 === v) h(); - else if (1 === v) - for (d(1), c(), c(), e = h(), r = 0; r < e; r++) c(); - f(), d(1); - var y = h(), - E = h(), - S = l(1); - 0 === S && d(1), - d(1), - u() && ((i = h()), (n = h()), (s = h()), (a = h())); - var T = [1, 1]; - if (u() && u()) - switch (o()) { - case 1: - T = [1, 1]; - break; - case 2: - T = [12, 11]; - break; - case 3: - T = [10, 11]; - break; - case 4: - T = [16, 11]; - break; - case 5: - T = [40, 33]; - break; - case 6: - T = [24, 11]; - break; - case 7: - T = [20, 11]; - break; - case 8: - T = [32, 11]; - break; - case 9: - T = [80, 33]; - break; - case 10: - T = [18, 11]; - break; - case 11: - T = [15, 11]; - break; - case 12: - T = [64, 33]; - break; - case 13: - T = [160, 99]; - break; - case 14: - T = [4, 3]; - break; - case 15: - T = [3, 2]; - break; - case 16: - T = [2, 1]; - break; - case 255: - T = [(o() << 8) | o(), (o() << 8) | o()]; - } - return { - width: Math.ceil(16 * (y + 1) - 2 * i - 2 * n), - height: (2 - S) * (E + 1) * 16 - (S ? 2 : 4) * (s + a), - pixelRatio: T, - }; - }), - (t.readSliceType = function () { - return this.readUByte(), this.readUEG(), this.readUEG(); - }), - e - ); - })(), - Ni = (function (e) { - function t() { - return e.apply(this, arguments) || this; - } - l(t, e); - var r = t.prototype; - return ( - (r.parseAVCPES = function (e, t, r, i, n) { - var s, - a = this, - o = this.parseAVCNALu(e, r.data), - l = this.VideoSample, - h = !1; - (r.data = null), - l && - o.length && - !e.audFound && - (this.pushAccessUnit(l, e), - (l = this.VideoSample = - this.createVideoSample(!1, r.pts, r.dts, ""))), - o.forEach(function (i) { - var o; - switch (i.type) { - case 1: - var u = !1; - s = !0; - var d, - c = i.data; - if (h && c.length > 4) { - var f = new Fi(c).readSliceType(); - (2 !== f && 4 !== f && 7 !== f && 9 !== f) || - (u = !0); - } - u && - null != (d = l) && - d.frame && - !l.key && - (a.pushAccessUnit(l, e), - (l = a.VideoSample = null)), - l || - (l = a.VideoSample = - a.createVideoSample(!0, r.pts, r.dts, "")), - (l.frame = !0), - (l.key = u); - break; - case 5: - (s = !0), - null != (o = l) && - o.frame && - !l.key && - (a.pushAccessUnit(l, e), - (l = a.VideoSample = null)), - l || - (l = a.VideoSample = - a.createVideoSample(!0, r.pts, r.dts, "")), - (l.key = !0), - (l.frame = !0); - break; - case 6: - (s = !0), Ue(i.data, 1, r.pts, t.samples); - break; - case 7: - var g, p; - (s = !0), (h = !0); - var m = i.data, - v = new Fi(m).readSPS(); - if ( - !e.sps || - e.width !== v.width || - e.height !== v.height || - (null == (g = e.pixelRatio) ? void 0 : g[0]) !== - v.pixelRatio[0] || - (null == (p = e.pixelRatio) ? void 0 : p[1]) !== - v.pixelRatio[1] - ) { - (e.width = v.width), - (e.height = v.height), - (e.pixelRatio = v.pixelRatio), - (e.sps = [m]), - (e.duration = n); - for ( - var y = m.subarray(1, 4), E = "avc1.", S = 0; - S < 3; - S++ - ) { - var T = y[S].toString(16); - T.length < 2 && (T = "0" + T), (E += T); - } - e.codec = E; - } - break; - case 8: - (s = !0), (e.pps = [i.data]); - break; - case 9: - (s = !0), - (e.audFound = !0), - l && a.pushAccessUnit(l, e), - (l = a.VideoSample = - a.createVideoSample(!1, r.pts, r.dts, "")); - break; - case 12: - s = !0; - break; - default: - (s = !1), - l && (l.debug += "unknown NAL " + i.type + " "); - } - l && s && l.units.push(i); - }), - i && - l && - (this.pushAccessUnit(l, e), - (this.VideoSample = null)); - }), - (r.parseAVCNALu = function (e, t) { - var r, - i, - n = t.byteLength, - s = e.naluState || 0, - a = s, - o = [], - l = 0, - h = -1, - u = 0; - for ( - -1 === s && - ((h = 0), (u = 31 & t[0]), (s = 0), (l = 1)); - l < n; - - ) - if (((r = t[l++]), s)) - if (1 !== s) - if (r) - if (1 === r) { - if (((i = l - s - 1), h >= 0)) { - var d = { data: t.subarray(h, i), type: u }; - o.push(d); - } else { - var c = this.getLastNalUnit(e.samples); - c && - (a && - l <= 4 - a && - c.state && - (c.data = c.data.subarray( - 0, - c.data.byteLength - a - )), - i > 0 && - ((c.data = Fe(c.data, t.subarray(0, i))), - (c.state = 0))); - } - l < n - ? ((h = l), (u = 31 & t[l]), (s = 0)) - : (s = -1); - } else s = 0; - else s = 3; - else s = r ? 0 : 2; - else s = r ? 0 : 1; - if (h >= 0 && s >= 0) { - var f = { data: t.subarray(h, n), type: u, state: s }; - o.push(f); - } - if (0 === o.length) { - var g = this.getLastNalUnit(e.samples); - g && (g.data = Fe(g.data, t)); - } - return (e.naluState = s), o; - }), - t - ); - })(Oi), - Bi = (function () { - function e(e, t, r) { - (this.keyData = void 0), - (this.decrypter = void 0), - (this.keyData = r), - (this.decrypter = new jr(t, { removePKCS7Padding: !1 })); - } - var t = e.prototype; - return ( - (t.decryptBuffer = function (e) { - return this.decrypter.decrypt( - e, - this.keyData.key.buffer, - this.keyData.iv.buffer - ); - }), - (t.decryptAacSample = function (e, t, r) { - var i = this, - n = e[t].unit; - if (!(n.length <= 16)) { - var s = n.subarray(16, n.length - (n.length % 16)), - a = s.buffer.slice( - s.byteOffset, - s.byteOffset + s.length - ); - this.decryptBuffer(a).then(function (s) { - var a = new Uint8Array(s); - n.set(a, 16), - i.decrypter.isSync() || - i.decryptAacSamples(e, t + 1, r); - }); - } - }), - (t.decryptAacSamples = function (e, t, r) { - for (; ; t++) { - if (t >= e.length) return void r(); - if ( - !( - e[t].unit.length < 32 || - (this.decryptAacSample(e, t, r), - this.decrypter.isSync()) - ) - ) - return; - } - }), - (t.getAvcEncryptedData = function (e) { - for ( - var t = 16 * Math.floor((e.length - 48) / 160) + 16, - r = new Int8Array(t), - i = 0, - n = 32; - n < e.length - 16; - n += 160, i += 16 - ) - r.set(e.subarray(n, n + 16), i); - return r; - }), - (t.getAvcDecryptedUnit = function (e, t) { - for ( - var r = new Uint8Array(t), i = 0, n = 32; - n < e.length - 16; - n += 160, i += 16 - ) - e.set(r.subarray(i, i + 16), n); - return e; - }), - (t.decryptAvcSample = function (e, t, r, i, n) { - var s = this, - a = Ge(n.data), - o = this.getAvcEncryptedData(a); - this.decryptBuffer(o.buffer).then(function (o) { - (n.data = s.getAvcDecryptedUnit(a, o)), - s.decrypter.isSync() || - s.decryptAvcSamples(e, t, r + 1, i); - }); - }), - (t.decryptAvcSamples = function (e, t, r, i) { - if (e instanceof Uint8Array) - throw new Error( - "Cannot decrypt samples of type Uint8Array" - ); - for (; ; t++, r = 0) { - if (t >= e.length) return void i(); - for (var n = e[t].units; !(r >= n.length); r++) { - var s = n[r]; - if ( - !( - s.data.length <= 48 || - (1 !== s.type && 5 !== s.type) || - (this.decryptAvcSample(e, t, r, i, s), - this.decrypter.isSync()) - ) - ) - return; - } - } - }), - e - ); - })(), - Ui = 188, - Gi = (function () { - function e(e, t, r) { - (this.observer = void 0), - (this.config = void 0), - (this.typeSupported = void 0), - (this.sampleAes = null), - (this.pmtParsed = !1), - (this.audioCodec = void 0), - (this.videoCodec = void 0), - (this._duration = 0), - (this._pmtId = -1), - (this._videoTrack = void 0), - (this._audioTrack = void 0), - (this._id3Track = void 0), - (this._txtTrack = void 0), - (this.aacOverFlow = null), - (this.remainderData = null), - (this.videoParser = void 0), - (this.observer = e), - (this.config = t), - (this.typeSupported = r), - (this.videoParser = new Ni()); - } - (e.probe = function (t) { - var r = e.syncOffset(t); - return ( - r > 0 && - A.warn( - "MPEG2-TS detected but first sync word found @ offset " + - r - ), - -1 !== r - ); - }), - (e.syncOffset = function (e) { - for ( - var t = e.length, r = Math.min(940, t - Ui) + 1, i = 0; - i < r; - - ) { - for (var n = !1, s = -1, a = 0, o = i; o < t; o += Ui) { - if ( - 71 !== e[o] || - (t - o !== Ui && 71 !== e[o + Ui]) - ) { - if (a) return -1; - break; - } - if ( - (a++, - -1 === s && - 0 !== (s = o) && - (r = Math.min(s + 18612, e.length - Ui) + 1), - n || (n = 0 === Hi(e, o)), - n && a > 1 && ((0 === s && a > 2) || o + Ui > r)) - ) - return s; - } - i++; - } - return -1; - }), - (e.createTrack = function (e, t) { - return { - container: - "video" === e || "audio" === e - ? "video/mp2t" - : void 0, - type: e, - id: Se[e], - pid: -1, - inputTimeScale: 9e4, - sequenceNumber: 0, - samples: [], - dropped: 0, - duration: "audio" === e ? t : void 0, - }; - }); - var t = e.prototype; - return ( - (t.resetInitSegment = function (t, r, i, n) { - (this.pmtParsed = !1), - (this._pmtId = -1), - (this._videoTrack = e.createTrack("video")), - (this._audioTrack = e.createTrack("audio", n)), - (this._id3Track = e.createTrack("id3")), - (this._txtTrack = e.createTrack("text")), - (this._audioTrack.segmentCodec = "aac"), - (this.aacOverFlow = null), - (this.remainderData = null), - (this.audioCodec = r), - (this.videoCodec = i), - (this._duration = n); - }), - (t.resetTimeStamp = function () {}), - (t.resetContiguity = function () { - var e = this._audioTrack, - t = this._videoTrack, - r = this._id3Track; - e && (e.pesData = null), - t && (t.pesData = null), - r && (r.pesData = null), - (this.aacOverFlow = null), - (this.remainderData = null); - }), - (t.demux = function (t, r, i, n) { - var s; - void 0 === i && (i = !1), - void 0 === n && (n = !1), - i || (this.sampleAes = null); - var a = this._videoTrack, - o = this._audioTrack, - l = this._id3Track, - h = this._txtTrack, - u = a.pid, - d = a.pesData, - c = o.pid, - f = l.pid, - g = o.pesData, - p = l.pesData, - m = null, - v = this.pmtParsed, - y = this._pmtId, - E = t.length; - if ( - (this.remainderData && - ((E = (t = Fe(this.remainderData, t)).length), - (this.remainderData = null)), - E < Ui && !n) - ) - return ( - (this.remainderData = t), - { - audioTrack: o, - videoTrack: a, - id3Track: l, - textTrack: h, - } - ); - var S = Math.max(0, e.syncOffset(t)); - (E -= (E - S) % Ui) < t.byteLength && - !n && - (this.remainderData = new Uint8Array( - t.buffer, - E, - t.buffer.byteLength - E - )); - for (var T = 0, _ = S; _ < E; _ += Ui) - if (71 === t[_]) { - var L = !!(64 & t[_ + 1]), - b = Hi(t, _), - R = void 0; - if ((48 & t[_ + 3]) >> 4 > 1) { - if ((R = _ + 5 + t[_ + 4]) === _ + Ui) continue; - } else R = _ + 4; - switch (b) { - case u: - L && - (d && - (s = qi(d)) && - this.videoParser.parseAVCPES( - a, - h, - s, - !1, - this._duration - ), - (d = { data: [], size: 0 })), - d && - (d.data.push(t.subarray(R, _ + Ui)), - (d.size += _ + Ui - R)); - break; - case c: - if (L) { - if (g && (s = qi(g))) - switch (o.segmentCodec) { - case "aac": - this.parseAACPES(o, s); - break; - case "mp3": - this.parseMPEGPES(o, s); - break; - case "ac3": - this.parseAC3PES(o, s); - } - g = { data: [], size: 0 }; - } - g && - (g.data.push(t.subarray(R, _ + Ui)), - (g.size += _ + Ui - R)); - break; - case f: - L && - (p && (s = qi(p)) && this.parseID3PES(l, s), - (p = { data: [], size: 0 })), - p && - (p.data.push(t.subarray(R, _ + Ui)), - (p.size += _ + Ui - R)); - break; - case 0: - L && (R += t[R] + 1), - (y = this._pmtId = $i(t, R)); - break; - case y: - L && (R += t[R] + 1); - var w = Ki( - t, - R, - this.typeSupported, - i, - this.observer - ); - (u = w.videoPid) > 0 && - ((a.pid = u), - (a.segmentCodec = w.segmentVideoCodec)), - (c = w.audioPid) > 0 && - ((o.pid = c), - (o.segmentCodec = w.segmentAudioCodec)), - (f = w.id3Pid) > 0 && (l.pid = f), - null === m || - v || - (A.warn( - "MPEG-TS PMT found at " + - _ + - " after unknown PID '" + - m + - "'. Backtracking to sync byte @" + - S + - " to parse all TS packets." - ), - (m = null), - (_ = S - 188)), - (v = this.pmtParsed = !0); - break; - case 17: - case 8191: - break; - default: - m = b; - } - } else T++; - T > 0 && - Wi( - this.observer, - new Error( - "Found " + - T + - " TS packet/s that do not start with 0x47" - ) - ), - (a.pesData = d), - (o.pesData = g), - (l.pesData = p); - var P = { - audioTrack: o, - videoTrack: a, - id3Track: l, - textTrack: h, - }; - return n && this.extractRemainingSamples(P), P; - }), - (t.flush = function () { - var e, - t = this.remainderData; - return ( - (this.remainderData = null), - (e = t - ? this.demux(t, -1, !1, !0) - : { - videoTrack: this._videoTrack, - audioTrack: this._audioTrack, - id3Track: this._id3Track, - textTrack: this._txtTrack, - }), - this.extractRemainingSamples(e), - this.sampleAes ? this.decrypt(e, this.sampleAes) : e - ); - }), - (t.extractRemainingSamples = function (e) { - var t, - r = e.audioTrack, - i = e.videoTrack, - n = e.id3Track, - s = e.textTrack, - a = i.pesData, - o = r.pesData, - l = n.pesData; - if ( - (a && (t = qi(a)) - ? (this.videoParser.parseAVCPES( - i, - s, - t, - !0, - this._duration - ), - (i.pesData = null)) - : (i.pesData = a), - o && (t = qi(o))) - ) { - switch (r.segmentCodec) { - case "aac": - this.parseAACPES(r, t); - break; - case "mp3": - this.parseMPEGPES(r, t); - break; - case "ac3": - this.parseAC3PES(r, t); - } - r.pesData = null; - } else - null != o && - o.size && - A.log( - "last AAC PES packet truncated,might overlap between fragments" - ), - (r.pesData = o); - l && (t = qi(l)) - ? (this.parseID3PES(n, t), (n.pesData = null)) - : (n.pesData = l); - }), - (t.demuxSampleAes = function (e, t, r) { - var i = this.demux(e, r, !0, !this.config.progressive), - n = (this.sampleAes = new Bi( - this.observer, - this.config, - t - )); - return this.decrypt(i, n); - }), - (t.decrypt = function (e, t) { - return new Promise(function (r) { - var i = e.audioTrack, - n = e.videoTrack; - i.samples && "aac" === i.segmentCodec - ? t.decryptAacSamples(i.samples, 0, function () { - n.samples - ? t.decryptAvcSamples( - n.samples, - 0, - 0, - function () { - r(e); - } - ) - : r(e); - }) - : n.samples && - t.decryptAvcSamples(n.samples, 0, 0, function () { - r(e); - }); - }); - }), - (t.destroy = function () { - this._duration = 0; - }), - (t.parseAACPES = function (e, t) { - var r, - i, - n, - s = 0, - a = this.aacOverFlow, - o = t.data; - if (a) { - this.aacOverFlow = null; - var l = a.missing, - h = a.sample.unit.byteLength; - if (-1 === l) o = Fe(a.sample.unit, o); - else { - var u = h - l; - a.sample.unit.set(o.subarray(0, l), u), - e.samples.push(a.sample), - (s = a.missing); - } - } - for (r = s, i = o.length; r < i - 1 && !gi(o, r); r++); - if (r !== s) { - var d, - c = r < i - 1; - if ( - ((d = c - ? "AAC PES did not start with ADTS header,offset:" + - r - : "No ADTS header found in AAC PES"), - Wi(this.observer, new Error(d), c), - !c) - ) - return; - } - if ( - (mi(e, this.observer, o, r, this.audioCodec), - void 0 !== t.pts) - ) - n = t.pts; - else { - if (!a) - return void A.warn( - "[tsdemuxer]: AAC PES unknown PTS" - ); - var f = vi(e.samplerate); - n = a.sample.pts + f; - } - for (var g, p = 0; r < i; ) { - if ( - ((r += (g = yi(e, o, r, n, p)).length), g.missing) - ) { - this.aacOverFlow = g; - break; - } - for (p++; r < i - 1 && !gi(o, r); r++); - } - }), - (t.parseMPEGPES = function (e, t) { - var r = t.data, - i = r.length, - n = 0, - s = 0, - a = t.pts; - if (void 0 !== a) - for (; s < i; ) - if (wi(r, s)) { - var o = bi(e, r, s, a, n); - if (!o) break; - (s += o.length), n++; - } else s++; - else A.warn("[tsdemuxer]: MPEG PES unknown PTS"); - }), - (t.parseAC3PES = function (e, t) { - var r = t.data, - i = t.pts; - if (void 0 !== i) - for ( - var n, s = r.length, a = 0, o = 0; - o < s && (n = xi(e, r, o, i, a++)) > 0; - - ) - o += n; - else A.warn("[tsdemuxer]: AC3 PES unknown PTS"); - }), - (t.parseID3PES = function (e, t) { - if (void 0 !== t.pts) { - var r = o({}, t, { - type: this._videoTrack ? Ot : xt, - duration: Number.POSITIVE_INFINITY, - }); - e.samples.push(r); - } else A.warn("[tsdemuxer]: ID3 PES unknown PTS"); - }), - e - ); - })(); - function Hi(e, t) { - return ((31 & e[t + 1]) << 8) + e[t + 2]; - } - function $i(e, t) { - return ((31 & e[t + 10]) << 8) | e[t + 11]; - } - function Ki(e, t, r, i, n) { - var s = { - audioPid: -1, - videoPid: -1, - id3Pid: -1, - segmentVideoCodec: "avc", - segmentAudioCodec: "aac", - }, - a = t + 3 + (((15 & e[t + 1]) << 8) | e[t + 2]) - 4; - for (t += 12 + (((15 & e[t + 10]) << 8) | e[t + 11]); t < a; ) { - var o = Hi(e, t), - l = ((15 & e[t + 3]) << 8) | e[t + 4]; - switch (e[t]) { - case 207: - if (!i) { - Vi("ADTS AAC"); - break; - } - case 15: - -1 === s.audioPid && (s.audioPid = o); - break; - case 21: - -1 === s.id3Pid && (s.id3Pid = o); - break; - case 219: - if (!i) { - Vi("H.264"); - break; - } - case 27: - -1 === s.videoPid && - ((s.videoPid = o), (s.segmentVideoCodec = "avc")); - break; - case 3: - case 4: - r.mpeg || r.mp3 - ? -1 === s.audioPid && - ((s.audioPid = o), (s.segmentAudioCodec = "mp3")) - : A.log( - "MPEG audio found, not supported in this browser" - ); - break; - case 193: - if (!i) { - Vi("AC-3"); - break; - } - case 129: - r.ac3 - ? -1 === s.audioPid && - ((s.audioPid = o), (s.segmentAudioCodec = "ac3")) - : A.log( - "AC-3 audio found, not supported in this browser" - ); - break; - case 6: - if (-1 === s.audioPid && l > 0) - for (var h = t + 5, u = l; u > 2; ) { - 106 === e[h] && - (!0 !== r.ac3 - ? A.log( - "AC-3 audio found, not supported in this browser for now" - ) - : ((s.audioPid = o), - (s.segmentAudioCodec = "ac3"))); - var d = e[h + 1] + 2; - (h += d), (u -= d); - } - break; - case 194: - case 135: - return ( - Wi(n, new Error("Unsupported EC-3 in M2TS found")), s - ); - case 36: - return ( - Wi(n, new Error("Unsupported HEVC in M2TS found")), s - ); - } - t += l + 5; - } - return s; - } - function Wi(e, t, r) { - A.warn("parsing error: " + t.message), - e.emit(E.ERROR, E.ERROR, { - type: S.MEDIA_ERROR, - details: T.FRAG_PARSING_ERROR, - fatal: !1, - levelRetry: r, - error: t, - reason: t.message, - }); - } - function Vi(e) { - A.log( - e + " with AES-128-CBC encryption found in unencrypted stream" - ); - } - function qi(e) { - var t, - r, - i, - n, - s, - a = 0, - o = e.data; - if (!e || 0 === e.size) return null; - for (; o[0].length < 19 && o.length > 1; ) - (o[0] = Fe(o[0], o[1])), o.splice(1, 1); - if (1 === ((t = o[0])[0] << 16) + (t[1] << 8) + t[2]) { - if ((r = (t[4] << 8) + t[5]) && r > e.size - 6) return null; - var l = t[7]; - 192 & l && - ((n = - 536870912 * (14 & t[9]) + - 4194304 * (255 & t[10]) + - 16384 * (254 & t[11]) + - 128 * (255 & t[12]) + - (254 & t[13]) / 2), - 64 & l - ? n - - (s = - 536870912 * (14 & t[14]) + - 4194304 * (255 & t[15]) + - 16384 * (254 & t[16]) + - 128 * (255 & t[17]) + - (254 & t[18]) / 2) > - 54e5 && - (A.warn( - Math.round((n - s) / 9e4) + - "s delta between PTS and DTS, align them" - ), - (n = s)) - : (s = n)); - var h = (i = t[8]) + 9; - if (e.size <= h) return null; - e.size -= h; - for ( - var u = new Uint8Array(e.size), d = 0, c = o.length; - d < c; - d++ - ) { - var f = (t = o[d]).byteLength; - if (h) { - if (h > f) { - h -= f; - continue; - } - (t = t.subarray(h)), (f -= h), (h = 0); - } - u.set(t, a), (a += f); - } - return r && (r -= i + 3), { data: u, pts: n, dts: s, len: r }; - } - return null; - } - var ji = (function (e) { - function t() { - return e.apply(this, arguments) || this; - } - l(t, e); - var r = t.prototype; - return ( - (r.resetInitSegment = function (t, r, i, n) { - e.prototype.resetInitSegment.call(this, t, r, i, n), - (this._audioTrack = { - container: "audio/mpeg", - type: "audio", - id: 2, - pid: -1, - sequenceNumber: 0, - segmentCodec: "mp3", - samples: [], - manifestCodec: r, - duration: n, - inputTimeScale: 9e4, - dropped: 0, - }); - }), - (t.probe = function (e) { - if (!e) return !1; - var t = ne(e, 0), - r = (null == t ? void 0 : t.length) || 0; - if ( - t && - 11 === e[r] && - 119 === e[r + 1] && - void 0 !== oe(t) && - Di(e, r) <= 16 - ) - return !1; - for (var i = e.length; r < i; r++) - if (Pi(e, r)) - return A.log("MPEG Audio sync word found !"), !0; - return !1; - }), - (r.canParse = function (e, t) { - return (function (e, t) { - return Ai(e, t) && 4 <= e.length - t; - })(e, t); - }), - (r.appendFrame = function (e, t, r) { - if (null !== this.basePTS) - return bi(e, t, r, this.basePTS, this.frameIndex); - }), - t - ); - })(hi), - Yi = (function () { - function e() {} - return ( - (e.getSilentFrame = function (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, - ]); - } - }), - e - ); - })(), - zi = Math.pow(2, 32) - 1, - Xi = (function () { - function e() {} - return ( - (e.init = function () { - var t; - for (t in ((e.types = { - avc1: [], - avcC: [], - btrt: [], - dinf: [], - dref: [], - esds: [], - ftyp: [], - hdlr: [], - mdat: [], - mdhd: [], - mdia: [], - mfhd: [], - minf: [], - moof: [], - moov: [], - mp4a: [], - ".mp3": [], - dac3: [], - "ac-3": [], - mvex: [], - mvhd: [], - pasp: [], - sdtp: [], - stbl: [], - stco: [], - stsc: [], - stsd: [], - stsz: [], - stts: [], - tfdt: [], - tfhd: [], - traf: [], - trak: [], - trun: [], - trex: [], - tkhd: [], - vmhd: [], - smhd: [], - }), - e.types)) - e.types.hasOwnProperty(t) && - (e.types[t] = [ - t.charCodeAt(0), - t.charCodeAt(1), - t.charCodeAt(2), - t.charCodeAt(3), - ]); - var r = 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, - ]); - e.HDLR_TYPES = { video: r, audio: i }; - var n = new Uint8Array([ - 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 12, 117, 114, 108, - 32, 0, 0, 0, 1, - ]), - s = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]); - (e.STTS = e.STSC = e.STCO = s), - (e.STSZ = new Uint8Array([ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - ])), - (e.VMHD = new Uint8Array([ - 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, - ])), - (e.SMHD = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0])), - (e.STSD = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1])); - var a = new Uint8Array([105, 115, 111, 109]), - o = new Uint8Array([97, 118, 99, 49]), - l = new Uint8Array([0, 0, 0, 1]); - (e.FTYP = e.box(e.types.ftyp, a, l, a, o)), - (e.DINF = e.box(e.types.dinf, e.box(e.types.dref, n))); - }), - (e.box = function (e) { - for ( - var t = 8, - r = arguments.length, - i = new Array(r > 1 ? r - 1 : 0), - n = 1; - n < r; - n++ - ) - i[n - 1] = arguments[n]; - for (var s = i.length, a = s; s--; ) t += i[s].byteLength; - var o = new Uint8Array(t); - for ( - o[0] = (t >> 24) & 255, - o[1] = (t >> 16) & 255, - o[2] = (t >> 8) & 255, - o[3] = 255 & t, - o.set(e, 4), - s = 0, - t = 8; - s < a; - s++ - ) - o.set(i[s], t), (t += i[s].byteLength); - return o; - }), - (e.hdlr = function (t) { - return e.box(e.types.hdlr, e.HDLR_TYPES[t]); - }), - (e.mdat = function (t) { - return e.box(e.types.mdat, t); - }), - (e.mdhd = function (t, r) { - r *= t; - var i = Math.floor(r / (zi + 1)), - n = Math.floor(r % (zi + 1)); - return e.box( - e.types.mdhd, - new Uint8Array([ - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 3, - (t >> 24) & 255, - (t >> 16) & 255, - (t >> 8) & 255, - 255 & t, - i >> 24, - (i >> 16) & 255, - (i >> 8) & 255, - 255 & i, - n >> 24, - (n >> 16) & 255, - (n >> 8) & 255, - 255 & n, - 85, - 196, - 0, - 0, - ]) - ); - }), - (e.mdia = function (t) { - return e.box( - e.types.mdia, - e.mdhd(t.timescale, t.duration), - e.hdlr(t.type), - e.minf(t) - ); - }), - (e.mfhd = function (t) { - return e.box( - e.types.mfhd, - new Uint8Array([ - 0, - 0, - 0, - 0, - t >> 24, - (t >> 16) & 255, - (t >> 8) & 255, - 255 & t, - ]) - ); - }), - (e.minf = function (t) { - return "audio" === t.type - ? e.box( - e.types.minf, - e.box(e.types.smhd, e.SMHD), - e.DINF, - e.stbl(t) - ) - : e.box( - e.types.minf, - e.box(e.types.vmhd, e.VMHD), - e.DINF, - e.stbl(t) - ); - }), - (e.moof = function (t, r, i) { - return e.box(e.types.moof, e.mfhd(t), e.traf(i, r)); - }), - (e.moov = function (t) { - for (var r = t.length, i = []; r--; ) i[r] = e.trak(t[r]); - return e.box.apply( - null, - [e.types.moov, e.mvhd(t[0].timescale, t[0].duration)] - .concat(i) - .concat(e.mvex(t)) - ); - }), - (e.mvex = function (t) { - for (var r = t.length, i = []; r--; ) i[r] = e.trex(t[r]); - return e.box.apply(null, [e.types.mvex].concat(i)); - }), - (e.mvhd = function (t, r) { - r *= t; - var i = Math.floor(r / (zi + 1)), - n = Math.floor(r % (zi + 1)), - s = new Uint8Array([ - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 3, - (t >> 24) & 255, - (t >> 16) & 255, - (t >> 8) & 255, - 255 & t, - i >> 24, - (i >> 16) & 255, - (i >> 8) & 255, - 255 & i, - n >> 24, - (n >> 16) & 255, - (n >> 8) & 255, - 255 & n, - 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 e.box(e.types.mvhd, s); - }), - (e.sdtp = function (t) { - var r, - i, - n = t.samples || [], - s = new Uint8Array(4 + n.length); - for (r = 0; r < n.length; r++) - (i = n[r].flags), - (s[r + 4] = - (i.dependsOn << 4) | - (i.isDependedOn << 2) | - i.hasRedundancy); - return e.box(e.types.sdtp, s); - }), - (e.stbl = function (t) { - return e.box( - e.types.stbl, - e.stsd(t), - e.box(e.types.stts, e.STTS), - e.box(e.types.stsc, e.STSC), - e.box(e.types.stsz, e.STSZ), - e.box(e.types.stco, e.STCO) - ); - }), - (e.avc1 = function (t) { - var r, - i, - n, - s = [], - a = []; - for (r = 0; r < t.sps.length; r++) - (n = (i = t.sps[r]).byteLength), - s.push((n >>> 8) & 255), - s.push(255 & n), - (s = s.concat(Array.prototype.slice.call(i))); - for (r = 0; r < t.pps.length; r++) - (n = (i = t.pps[r]).byteLength), - a.push((n >>> 8) & 255), - a.push(255 & n), - (a = a.concat(Array.prototype.slice.call(i))); - var o = e.box( - e.types.avcC, - new Uint8Array( - [1, s[3], s[4], s[5], 255, 224 | t.sps.length] - .concat(s) - .concat([t.pps.length]) - .concat(a) - ) - ), - l = t.width, - h = t.height, - u = t.pixelRatio[0], - d = t.pixelRatio[1]; - return e.box( - e.types.avc1, - new Uint8Array([ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - (l >> 8) & 255, - 255 & l, - (h >> 8) & 255, - 255 & h, - 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, - e.box( - e.types.btrt, - new Uint8Array([ - 0, 28, 156, 128, 0, 45, 198, 192, 0, 45, 198, 192, - ]) - ), - e.box( - e.types.pasp, - new Uint8Array([ - u >> 24, - (u >> 16) & 255, - (u >> 8) & 255, - 255 & u, - d >> 24, - (d >> 16) & 255, - (d >> 8) & 255, - 255 & d, - ]) - ) - ); - }), - (e.esds = function (e) { - var t = e.config.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.config) - .concat([6, 1, 2]) - ); - }), - (e.audioStsd = function (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, - ]); - }), - (e.mp4a = function (t) { - return e.box( - e.types.mp4a, - e.audioStsd(t), - e.box(e.types.esds, e.esds(t)) - ); - }), - (e.mp3 = function (t) { - return e.box(e.types[".mp3"], e.audioStsd(t)); - }), - (e.ac3 = function (t) { - return e.box( - e.types["ac-3"], - e.audioStsd(t), - e.box(e.types.dac3, t.config) - ); - }), - (e.stsd = function (t) { - return "audio" === t.type - ? "mp3" === t.segmentCodec && "mp3" === t.codec - ? e.box(e.types.stsd, e.STSD, e.mp3(t)) - : "ac3" === t.segmentCodec - ? e.box(e.types.stsd, e.STSD, e.ac3(t)) - : e.box(e.types.stsd, e.STSD, e.mp4a(t)) - : e.box(e.types.stsd, e.STSD, e.avc1(t)); - }), - (e.tkhd = function (t) { - var r = t.id, - i = t.duration * t.timescale, - n = t.width, - s = t.height, - a = Math.floor(i / (zi + 1)), - o = Math.floor(i % (zi + 1)); - return e.box( - e.types.tkhd, - new Uint8Array([ - 1, - 0, - 0, - 7, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 2, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 3, - (r >> 24) & 255, - (r >> 16) & 255, - (r >> 8) & 255, - 255 & r, - 0, - 0, - 0, - 0, - a >> 24, - (a >> 16) & 255, - (a >> 8) & 255, - 255 & a, - o >> 24, - (o >> 16) & 255, - (o >> 8) & 255, - 255 & o, - 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, - ]) - ); - }), - (e.traf = function (t, r) { - var i = e.sdtp(t), - n = t.id, - s = Math.floor(r / (zi + 1)), - a = Math.floor(r % (zi + 1)); - return e.box( - e.types.traf, - e.box( - e.types.tfhd, - new Uint8Array([ - 0, - 0, - 0, - 0, - n >> 24, - (n >> 16) & 255, - (n >> 8) & 255, - 255 & n, - ]) - ), - e.box( - e.types.tfdt, - new Uint8Array([ - 1, - 0, - 0, - 0, - s >> 24, - (s >> 16) & 255, - (s >> 8) & 255, - 255 & s, - a >> 24, - (a >> 16) & 255, - (a >> 8) & 255, - 255 & a, - ]) - ), - e.trun(t, i.length + 16 + 20 + 8 + 16 + 8 + 8), - i - ); - }), - (e.trak = function (t) { - return ( - (t.duration = t.duration || 4294967295), - e.box(e.types.trak, e.tkhd(t), e.mdia(t)) - ); - }), - (e.trex = function (t) { - var r = t.id; - return e.box( - e.types.trex, - new Uint8Array([ - 0, - 0, - 0, - 0, - r >> 24, - (r >> 16) & 255, - (r >> 8) & 255, - 255 & r, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - ]) - ); - }), - (e.trun = function (t, r) { - var i, - n, - s, - a, - o, - l, - h = t.samples || [], - u = h.length, - d = 12 + 16 * u, - c = new Uint8Array(d); - for ( - r += 8 + d, - c.set( - [ - "video" === t.type ? 1 : 0, - 0, - 15, - 1, - (u >>> 24) & 255, - (u >>> 16) & 255, - (u >>> 8) & 255, - 255 & u, - (r >>> 24) & 255, - (r >>> 16) & 255, - (r >>> 8) & 255, - 255 & r, - ], - 0 - ), - i = 0; - i < u; - i++ - ) - (s = (n = h[i]).duration), - (a = n.size), - (o = n.flags), - (l = n.cts), - c.set( - [ - (s >>> 24) & 255, - (s >>> 16) & 255, - (s >>> 8) & 255, - 255 & s, - (a >>> 24) & 255, - (a >>> 16) & 255, - (a >>> 8) & 255, - 255 & a, - (o.isLeading << 2) | o.dependsOn, - (o.isDependedOn << 6) | - (o.hasRedundancy << 4) | - (o.paddingValue << 1) | - o.isNonSync, - 61440 & o.degradPrio, - 15 & o.degradPrio, - (l >>> 24) & 255, - (l >>> 16) & 255, - (l >>> 8) & 255, - 255 & l, - ], - 12 + 16 * i - ); - return e.box(e.types.trun, c); - }), - (e.initSegment = function (t) { - e.types || e.init(); - var r = e.moov(t); - return Fe(e.FTYP, r); - }), - e - ); - })(); - (Xi.types = void 0), - (Xi.HDLR_TYPES = void 0), - (Xi.STTS = void 0), - (Xi.STSC = void 0), - (Xi.STCO = void 0), - (Xi.STSZ = void 0), - (Xi.VMHD = void 0), - (Xi.SMHD = void 0), - (Xi.STSD = void 0), - (Xi.FTYP = void 0), - (Xi.DINF = void 0); - function Qi(e, t, r, i) { - void 0 === r && (r = 1), void 0 === i && (i = !1); - var n = e * t * r; - return i ? Math.round(n) : n; - } - function Ji(e, t) { - return void 0 === t && (t = !1), Qi(e, 1e3, 1 / 9e4, t); - } - var Zi = null, - en = null, - tn = (function () { - function e(e, t, r, i) { - if ( - ((this.observer = void 0), - (this.config = void 0), - (this.typeSupported = void 0), - (this.ISGenerated = !1), - (this._initPTS = null), - (this._initDTS = null), - (this.nextAvcDts = null), - (this.nextAudioPts = null), - (this.videoSampleDuration = null), - (this.isAudioContiguous = !1), - (this.isVideoContiguous = !1), - (this.videoTrackConfig = void 0), - (this.observer = e), - (this.config = t), - (this.typeSupported = r), - (this.ISGenerated = !1), - null === Zi) - ) { - var n = (navigator.userAgent || "").match( - /Chrome\/(\d+)/i - ); - Zi = n ? parseInt(n[1]) : 0; - } - if (null === en) { - var s = navigator.userAgent.match(/Safari\/(\d+)/i); - en = s ? parseInt(s[1]) : 0; - } - } - var t = e.prototype; - return ( - (t.destroy = function () { - this.config = - this.videoTrackConfig = - this._initPTS = - this._initDTS = - null; - }), - (t.resetTimeStamp = function (e) { - A.log("[mp4-remuxer]: initPTS & initDTS reset"), - (this._initPTS = this._initDTS = e); - }), - (t.resetNextTimestamp = function () { - A.log("[mp4-remuxer]: reset next timestamp"), - (this.isVideoContiguous = !1), - (this.isAudioContiguous = !1); - }), - (t.resetInitSegment = function () { - A.log("[mp4-remuxer]: ISGenerated flag reset"), - (this.ISGenerated = !1), - (this.videoTrackConfig = void 0); - }), - (t.getVideoStartPts = function (e) { - var t = !1, - r = e.reduce(function (e, r) { - var i = r.pts - e; - return i < -4294967296 - ? ((t = !0), rn(e, r.pts)) - : i > 0 - ? e - : r.pts; - }, e[0].pts); - return t && A.debug("PTS rollover detected"), r; - }), - (t.remux = function (e, t, r, i, n, s, a, o) { - var l, - h, - u, - d, - c, - f, - g = n, - p = n, - m = e.pid > -1, - v = t.pid > -1, - y = t.samples.length, - E = e.samples.length > 0, - S = (a && y > 0) || y > 1; - if (((!m || E) && (!v || S)) || this.ISGenerated || a) { - if (this.ISGenerated) { - var T, - _, - L, - b, - R = this.videoTrackConfig; - !R || - (t.width === R.width && - t.height === R.height && - (null == (T = t.pixelRatio) ? void 0 : T[0]) === - (null == (_ = R.pixelRatio) ? void 0 : _[0]) && - (null == (L = t.pixelRatio) ? void 0 : L[1]) === - (null == (b = R.pixelRatio) ? void 0 : b[1])) || - this.resetInitSegment(); - } else u = this.generateIS(e, t, n, s); - var w, - P = this.isVideoContiguous, - I = -1; - if ( - S && - ((I = (function (e) { - for (var t = 0; t < e.length; t++) - if (e[t].key) return t; - return -1; - })(t.samples)), - !P && this.config.forceKeyFrameOnDiscontinuity) - ) - if (((f = !0), I > 0)) { - A.warn( - "[mp4-remuxer]: Dropped " + - I + - " out of " + - y + - " video samples due to a missing keyframe" - ); - var C = this.getVideoStartPts(t.samples); - (t.samples = t.samples.slice(I)), - (t.dropped += I), - (w = p += - (t.samples[0].pts - C) / t.inputTimeScale); - } else - -1 === I && - (A.warn( - "[mp4-remuxer]: No keyframe found out of " + - y + - " video samples" - ), - (f = !1)); - if (this.ISGenerated) { - if (E && S) { - var k = this.getVideoStartPts(t.samples), - D = - (rn(e.samples[0].pts, k) - k) / - t.inputTimeScale; - (g += Math.max(0, D)), (p += Math.max(0, -D)); - } - if (E) { - if ( - (e.samplerate || - (A.warn( - "[mp4-remuxer]: regenerate InitSegment as audio detected" - ), - (u = this.generateIS(e, t, n, s))), - (h = this.remuxAudio( - e, - g, - this.isAudioContiguous, - s, - v || S || o === bt ? p : void 0 - )), - S) - ) { - var M = h ? h.endPTS - h.startPTS : 0; - t.inputTimeScale || - (A.warn( - "[mp4-remuxer]: regenerate InitSegment as video detected" - ), - (u = this.generateIS(e, t, n, s))), - (l = this.remuxVideo(t, p, P, M)); - } - } else S && (l = this.remuxVideo(t, p, P, 0)); - l && - ((l.firstKeyFrame = I), - (l.independent = -1 !== I), - (l.firstKeyFramePTS = w)); - } - } - return ( - this.ISGenerated && - this._initPTS && - this._initDTS && - (r.samples.length && - (c = nn(r, n, this._initPTS, this._initDTS)), - i.samples.length && (d = sn(i, n, this._initPTS))), - { - audio: h, - video: l, - initSegment: u, - independent: f, - text: d, - id3: c, - } - ); - }), - (t.generateIS = function (e, t, r, i) { - var n, - s, - a, - o = e.samples, - l = t.samples, - h = this.typeSupported, - u = {}, - d = this._initPTS, - c = !d || i, - f = "audio/mp4"; - if ((c && (n = s = 1 / 0), e.config && o.length)) { - switch ( - ((e.timescale = e.samplerate), e.segmentCodec) - ) { - case "mp3": - h.mpeg - ? ((f = "audio/mpeg"), (e.codec = "")) - : h.mp3 && (e.codec = "mp3"); - break; - case "ac3": - e.codec = "ac-3"; - } - (u.audio = { - id: "audio", - container: f, - codec: e.codec, - initSegment: - "mp3" === e.segmentCodec && h.mpeg - ? new Uint8Array(0) - : Xi.initSegment([e]), - metadata: { channelCount: e.channelCount }, - }), - c && - ((a = e.inputTimeScale), - d && a === d.timescale - ? (c = !1) - : (n = s = o[0].pts - Math.round(a * r))); - } - if (t.sps && t.pps && l.length) { - if ( - ((t.timescale = t.inputTimeScale), - (u.video = { - id: "main", - container: "video/mp4", - codec: t.codec, - initSegment: Xi.initSegment([t]), - metadata: { width: t.width, height: t.height }, - }), - c) - ) - if (((a = t.inputTimeScale), d && a === d.timescale)) - c = !1; - else { - var g = this.getVideoStartPts(l), - p = Math.round(a * r); - (s = Math.min(s, rn(l[0].dts, g) - p)), - (n = Math.min(n, g - p)); - } - this.videoTrackConfig = { - width: t.width, - height: t.height, - pixelRatio: t.pixelRatio, - }; - } - if (Object.keys(u).length) - return ( - (this.ISGenerated = !0), - c - ? ((this._initPTS = { baseTime: n, timescale: a }), - (this._initDTS = { baseTime: s, timescale: a })) - : (n = a = void 0), - { tracks: u, initPTS: n, timescale: a } - ); - }), - (t.remuxVideo = function (e, t, r, i) { - var n, - s, - a = e.inputTimeScale, - l = e.samples, - h = [], - u = l.length, - d = this._initPTS, - c = this.nextAvcDts, - f = 8, - g = this.videoSampleDuration, - p = Number.POSITIVE_INFINITY, - m = Number.NEGATIVE_INFINITY, - v = !1; - if (!r || null === c) { - var y = t * a, - _ = l[0].pts - rn(l[0].dts, l[0].pts); - Zi && null !== c && Math.abs(y - _ - c) < 15e3 - ? (r = !0) - : (c = y - _); - } - for ( - var L = (d.baseTime * a) / d.timescale, b = 0; - b < u; - b++ - ) { - var R = l[b]; - (R.pts = rn(R.pts - L, c)), - (R.dts = rn(R.dts - L, c)), - R.dts < l[b > 0 ? b - 1 : b].dts && (v = !0); - } - v && - l.sort(function (e, t) { - var r = e.dts - t.dts, - i = e.pts - t.pts; - return r || i; - }), - (n = l[0].dts); - var w = l[l.length - 1].dts - n, - P = w - ? Math.round(w / (u - 1)) - : g || e.inputTimeScale / 30; - if (r) { - var I = n - c, - C = I > P, - k = I < -1; - if ( - (C || k) && - (C - ? A.warn( - "AVC: " + - Ji(I, !0) + - " ms (" + - I + - "dts) hole between fragments detected at " + - t.toFixed(3) - ) - : A.warn( - "AVC: " + - Ji(-I, !0) + - " ms (" + - I + - "dts) overlapping between fragments detected at " + - t.toFixed(3) - ), - !k || c >= l[0].pts || Zi) - ) { - n = c; - var D = l[0].pts - I; - if (C) (l[0].dts = n), (l[0].pts = D); - else - for ( - var M = 0; - M < l.length && !(l[M].dts > D); - M++ - ) - (l[M].dts -= I), (l[M].pts -= I); - A.log( - "Video: Initial PTS/DTS adjusted: " + - Ji(D, !0) + - "/" + - Ji(n, !0) + - ", delta: " + - Ji(I, !0) + - " ms" - ); - } - } - for ( - var x = 0, O = 0, F = (n = Math.max(0, n)), N = 0; - N < u; - N++ - ) { - for ( - var B = l[N], U = B.units, G = U.length, H = 0, $ = 0; - $ < G; - $++ - ) - H += U[$].data.length; - (O += H), - (x += G), - (B.length = H), - B.dts < F - ? ((B.dts = F), (F += (P / 4) | 0 || 1)) - : (F = B.dts), - (p = Math.min(B.pts, p)), - (m = Math.max(B.pts, m)); - } - s = l[u - 1].dts; - var K, - W = O + 4 * x + 8; - try { - K = new Uint8Array(W); - } catch (e) { - return void this.observer.emit(E.ERROR, E.ERROR, { - type: S.MUX_ERROR, - details: T.REMUX_ALLOC_ERROR, - fatal: !1, - error: e, - bytes: W, - reason: "fail allocating video mdat " + W, - }); - } - var V = new DataView(K.buffer); - V.setUint32(0, W), K.set(Xi.types.mdat, 4); - for ( - var q = !1, - j = Number.POSITIVE_INFINITY, - Y = Number.POSITIVE_INFINITY, - z = Number.NEGATIVE_INFINITY, - X = Number.NEGATIVE_INFINITY, - Q = 0; - Q < u; - Q++ - ) { - for ( - var J = l[Q], - Z = J.units, - ee = 0, - te = 0, - re = Z.length; - te < re; - te++ - ) { - var ie = Z[te], - ne = ie.data, - se = ie.data.byteLength; - V.setUint32(f, se), - (f += 4), - K.set(ne, f), - (f += se), - (ee += 4 + se); - } - var ae = void 0; - if (Q < u - 1) - (g = l[Q + 1].dts - J.dts), - (ae = l[Q + 1].pts - J.pts); - else { - var oe = this.config, - le = Q > 0 ? J.dts - l[Q - 1].dts : P; - if ( - ((ae = Q > 0 ? J.pts - l[Q - 1].pts : P), - oe.stretchShortVideoTrack && - null !== this.nextAudioPts) - ) { - var he = Math.floor(oe.maxBufferHole * a), - ue = (i ? p + i * a : this.nextAudioPts) - J.pts; - ue > he - ? ((g = ue - le) < 0 ? (g = le) : (q = !0), - A.log( - "[mp4-remuxer]: It is approximately " + - ue / 90 + - " ms to the next segment; using duration " + - g / 90 + - " ms for the last video frame." - )) - : (g = le); - } else g = le; - } - var de = Math.round(J.pts - J.dts); - (j = Math.min(j, g)), - (z = Math.max(z, g)), - (Y = Math.min(Y, ae)), - (X = Math.max(X, ae)), - h.push(new on(J.key, g, ee, de)); - } - if (h.length) - if (Zi) { - if (Zi < 70) { - var ce = h[0].flags; - (ce.dependsOn = 2), (ce.isNonSync = 0); - } - } else if ( - en && - X - Y < z - j && - P / z < 0.025 && - 0 === h[0].cts - ) { - A.warn( - "Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration." - ); - for ( - var fe = n, ge = 0, pe = h.length; - ge < pe; - ge++ - ) { - var me = fe + h[ge].duration, - ve = fe + h[ge].cts; - if (ge < pe - 1) { - var ye = me + h[ge + 1].cts; - h[ge].duration = ye - ve; - } else h[ge].duration = ge ? h[ge - 1].duration : P; - (h[ge].cts = 0), (fe = me); - } - } - (g = q || !g ? P : g), - (this.nextAvcDts = c = s + g), - (this.videoSampleDuration = g), - (this.isVideoContiguous = !0); - var Ee = { - data1: Xi.moof( - e.sequenceNumber++, - n, - o({}, e, { samples: h }) - ), - data2: K, - startPTS: p / a, - endPTS: (m + g) / a, - startDTS: n / a, - endDTS: c / a, - type: "video", - hasAudio: !1, - hasVideo: !0, - nb: h.length, - dropped: e.dropped, - }; - return (e.samples = []), (e.dropped = 0), Ee; - }), - (t.getSamplesPerFrame = function (e) { - switch (e.segmentCodec) { - case "mp3": - return 1152; - case "ac3": - return 1536; - default: - return 1024; - } - }), - (t.remuxAudio = function (e, t, r, i, n) { - var s = e.inputTimeScale, - a = s / (e.samplerate ? e.samplerate : s), - l = this.getSamplesPerFrame(e), - h = l * a, - u = this._initPTS, - d = "mp3" === e.segmentCodec && this.typeSupported.mpeg, - c = [], - f = void 0 !== n, - g = e.samples, - p = d ? 0 : 8, - m = this.nextAudioPts || -1, - v = t * s, - y = (u.baseTime * s) / u.timescale; - if ( - ((this.isAudioContiguous = r = - r || - (g.length && - m > 0 && - ((i && Math.abs(v - m) < 9e3) || - Math.abs(rn(g[0].pts - y, v) - m) < 20 * h))), - g.forEach(function (e) { - e.pts = rn(e.pts - y, v); - }), - !r || m < 0) - ) { - if ( - ((g = g.filter(function (e) { - return e.pts >= 0; - })), - !g.length) - ) - return; - m = 0 === n ? 0 : i && !f ? Math.max(0, v) : g[0].pts; - } - if ("aac" === e.segmentCodec) - for ( - var _ = this.config.maxAudioFramesDrift, L = 0, b = m; - L < g.length; - L++ - ) { - var R = g[L], - w = R.pts, - P = w - b, - I = Math.abs((1e3 * P) / s); - if (P <= -_ * h && f) - 0 === L && - (A.warn( - "Audio frame @ " + - (w / s).toFixed(3) + - "s overlaps nextAudioPts by " + - Math.round((1e3 * P) / s) + - " ms." - ), - (this.nextAudioPts = m = b = w)); - else if (P >= _ * h && I < 1e4 && f) { - var C = Math.round(P / h); - (b = w - C * h) < 0 && (C--, (b += h)), - 0 === L && (this.nextAudioPts = m = b), - A.warn( - "[mp4-remuxer]: Injecting " + - C + - " audio frame @ " + - (b / s).toFixed(3) + - "s due to " + - Math.round((1e3 * P) / s) + - " ms gap." - ); - for (var k = 0; k < C; k++) { - var D = Math.max(b, 0), - M = Yi.getSilentFrame( - e.manifestCodec || e.codec, - e.channelCount - ); - M || - (A.log( - "[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead." - ), - (M = R.unit.subarray())), - g.splice(L, 0, { unit: M, pts: D }), - (b += h), - L++; - } - } - (R.pts = b), (b += h); - } - for ( - var x, O = null, F = null, N = 0, B = g.length; - B--; - - ) - N += g[B].unit.byteLength; - for (var U = 0, G = g.length; U < G; U++) { - var H = g[U], - $ = H.unit, - K = H.pts; - if (null !== F) - c[U - 1].duration = Math.round((K - F) / a); - else { - if ( - (r && "aac" === e.segmentCodec && (K = m), - (O = K), - !(N > 0)) - ) - return; - N += p; - try { - x = new Uint8Array(N); - } catch (e) { - return void this.observer.emit(E.ERROR, E.ERROR, { - type: S.MUX_ERROR, - details: T.REMUX_ALLOC_ERROR, - fatal: !1, - error: e, - bytes: N, - reason: "fail allocating audio mdat " + N, - }); - } - d || - (new DataView(x.buffer).setUint32(0, N), - x.set(Xi.types.mdat, 4)); - } - x.set($, p); - var W = $.byteLength; - (p += W), c.push(new on(!0, l, W, 0)), (F = K); - } - var V = c.length; - if (V) { - var q = c[c.length - 1]; - this.nextAudioPts = m = F + a * q.duration; - var j = d - ? new Uint8Array(0) - : Xi.moof( - e.sequenceNumber++, - O / a, - o({}, e, { samples: c }) - ); - e.samples = []; - var Y = O / s, - z = m / s, - X = { - data1: j, - data2: x, - startPTS: Y, - endPTS: z, - startDTS: Y, - endDTS: z, - type: "audio", - hasAudio: !0, - hasVideo: !1, - nb: V, - }; - return (this.isAudioContiguous = !0), X; - } - }), - (t.remuxEmptyAudio = function (e, t, r, i) { - var n = e.inputTimeScale, - s = n / (e.samplerate ? e.samplerate : n), - a = this.nextAudioPts, - o = this._initDTS, - l = (9e4 * o.baseTime) / o.timescale, - h = (null !== a ? a : i.startDTS * n) + l, - u = i.endDTS * n + l, - d = 1024 * s, - c = Math.ceil((u - h) / d), - f = Yi.getSilentFrame( - e.manifestCodec || e.codec, - e.channelCount - ); - if ((A.warn("[mp4-remuxer]: remux empty Audio"), f)) { - for (var g = [], p = 0; p < c; p++) { - var m = h + p * d; - g.push({ unit: f, pts: m, dts: m }); - } - return (e.samples = g), this.remuxAudio(e, t, r, !1); - } - A.trace( - "[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec" - ); - }), - e - ); - })(); - function rn(e, t) { - var r; - if (null === t) return e; - for ( - r = t < e ? -8589934592 : 8589934592; - Math.abs(e - t) > 4294967296; - - ) - e += r; - return e; - } - function nn(e, t, r, i) { - var n = e.samples.length; - if (n) { - for (var s = e.inputTimeScale, a = 0; a < n; a++) { - var o = e.samples[a]; - (o.pts = - rn(o.pts - (r.baseTime * s) / r.timescale, t * s) / s), - (o.dts = - rn(o.dts - (i.baseTime * s) / i.timescale, t * s) / s); - } - var l = e.samples; - return (e.samples = []), { samples: l }; - } - } - function sn(e, t, r) { - var i = e.samples.length; - if (i) { - for (var n = e.inputTimeScale, s = 0; s < i; s++) { - var a = e.samples[s]; - a.pts = - rn(a.pts - (r.baseTime * n) / r.timescale, t * n) / n; - } - e.samples.sort(function (e, t) { - return e.pts - t.pts; - }); - var o = e.samples; - return (e.samples = []), { samples: o }; - } - } - var an, - on = function (e, t, r, i) { - (this.size = void 0), - (this.duration = void 0), - (this.cts = void 0), - (this.flags = void 0), - (this.duration = t), - (this.size = r), - (this.cts = i), - (this.flags = { - isLeading: 0, - isDependedOn: 0, - hasRedundancy: 0, - degradPrio: 0, - dependsOn: e ? 2 : 1, - isNonSync: e ? 0 : 1, - }); - }, - ln = (function () { - function e() { - (this.emitInitSegment = !1), - (this.audioCodec = void 0), - (this.videoCodec = void 0), - (this.initData = void 0), - (this.initPTS = null), - (this.initTracks = void 0), - (this.lastEndTime = null); - } - var t = e.prototype; - return ( - (t.destroy = function () {}), - (t.resetTimeStamp = function (e) { - (this.initPTS = e), (this.lastEndTime = null); - }), - (t.resetNextTimestamp = function () { - this.lastEndTime = null; - }), - (t.resetInitSegment = function (e, t, r, i) { - (this.audioCodec = t), - (this.videoCodec = r), - this.generateInitSegment( - (function (e, t) { - if (!e || !t) return e; - var r = t.keyId; - return ( - r && - t.isCommonEncryption && - we(e, ["moov", "trak"]).forEach(function (e) { - var t = we(e, [ - "mdia", - "minf", - "stbl", - "stsd", - ])[0].subarray(8), - i = we(t, ["enca"]), - n = i.length > 0; - n || (i = we(t, ["encv"])), - i.forEach(function (e) { - we(n ? e.subarray(28) : e.subarray(78), [ - "sinf", - ]).forEach(function (e) { - var t = xe(e); - if (t) { - var i = t.subarray(8, 24); - i.some(function (e) { - return 0 !== e; - }) || - (A.log( - "[eme] Patching keyId in 'enc" + - (n ? "a" : "v") + - ">sinf>>tenc' box: " + - ve(i) + - " -> " + - ve(r) - ), - t.set(r, 8)); - } - }); - }); - }), - e - ); - })(e, i) - ), - (this.emitInitSegment = !0); - }), - (t.generateInitSegment = function (e) { - var t = this.audioCodec, - r = this.videoCodec; - if (null == e || !e.byteLength) - return ( - (this.initTracks = void 0), - void (this.initData = void 0) - ); - var i = (this.initData = Ie(e)); - i.audio && (t = hn(i.audio, M)), - i.video && (r = hn(i.video, x)); - var n = {}; - i.audio && i.video - ? (n.audiovideo = { - container: "video/mp4", - codec: t + "," + r, - initSegment: e, - id: "main", - }) - : i.audio - ? (n.audio = { - container: "audio/mp4", - codec: t, - initSegment: e, - id: "audio", - }) - : i.video - ? (n.video = { - container: "video/mp4", - codec: r, - initSegment: e, - id: "main", - }) - : A.warn( - "[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes." - ), - (this.initTracks = n); - }), - (t.remux = function (e, t, r, i, n, s) { - var a, - o, - l = this.initPTS, - h = this.lastEndTime, - u = { - audio: void 0, - video: void 0, - text: i, - id3: r, - initSegment: void 0, - }; - m(h) || (h = this.lastEndTime = n || 0); - var d = t.samples; - if (null == d || !d.length) return u; - var c = { initPTS: void 0, timescale: 1 }, - f = this.initData; - if ( - ((null != (a = f) && a.length) || - (this.generateInitSegment(d), (f = this.initData)), - null == (o = f) || !o.length) - ) - return ( - A.warn( - "[passthrough-remuxer.ts]: Failed to generate initSegment." - ), - u - ); - this.emitInitSegment && - ((c.tracks = this.initTracks), - (this.emitInitSegment = !1)); - var g = (function (e, t) { - for ( - var r = 0, - i = 0, - n = 0, - s = we(e, ["moof", "traf"]), - a = 0; - a < s.length; - a++ - ) { - var o = s[a], - l = we(o, ["tfhd"])[0], - h = t[Le(l, 4)]; - if (h) { - var u = h.default, - d = Le(l, 0) | (null == u ? void 0 : u.flags), - c = null == u ? void 0 : u.duration; - 8 & d && (c = Le(l, 2 & d ? 12 : 8)); - for ( - var f = h.timescale || 9e4, - g = we(o, ["trun"]), - p = 0; - p < g.length; - p++ - ) - !(r = Oe(g[p])) && c && (r = c * Le(g[p], 4)), - h.type === x - ? (i += r / f) - : h.type === M && (n += r / f); - } - } - if (0 === i && 0 === n) { - for ( - var v = 1 / 0, - y = 0, - E = 0, - S = we(e, ["sidx"]), - T = 0; - T < S.length; - T++ - ) { - var _ = Pe(S[T]); - if (null != _ && _.references) { - v = Math.min( - v, - _.earliestPresentationTime / _.timescale - ); - var L = _.references.reduce(function (e, t) { - return e + t.info.duration || 0; - }, 0); - E = - (y = Math.max( - y, - L + _.earliestPresentationTime / _.timescale - )) - v; - } - } - if (E && m(E)) return E; - } - return i || n; - })(d, f), - p = (function (e, t) { - return we(t, ["moof", "traf"]).reduce(function ( - t, - r - ) { - var i = we(r, ["tfdt"])[0], - n = i[0], - s = we(r, ["tfhd"]).reduce(function (t, r) { - var s = Le(r, 4), - a = e[s]; - if (a) { - var o = Le(i, 4); - if (1 === n) { - if (o === ye) - return ( - A.warn( - "[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time" - ), - t - ); - (o *= ye + 1), (o += Le(i, 8)); - } - var l = o / (a.timescale || 9e4); - if (m(l) && (null === t || l < t)) return l; - } - return t; - }, null); - return null !== s && m(s) && (null === t || s < t) - ? s - : t; - }, - null); - })(f, d), - v = null === p ? n : p; - ((function (e, t, r, i) { - if (null === e) return !0; - var n = Math.max(i, 1), - s = t - e.baseTime / e.timescale; - return Math.abs(s - r) > n; - })(l, v, n, g) || - (c.timescale !== l.timescale && s)) && - ((c.initPTS = v - n), - l && - 1 === l.timescale && - A.warn( - "Adjusting initPTS by " + (c.initPTS - l.baseTime) - ), - (this.initPTS = l = - { baseTime: c.initPTS, timescale: 1 })); - var y = e ? v - l.baseTime / l.timescale : h, - E = y + g; - !(function (e, t, r) { - we(t, ["moof", "traf"]).forEach(function (t) { - we(t, ["tfhd"]).forEach(function (i) { - var n = Le(i, 4), - s = e[n]; - if (s) { - var a = s.timescale || 9e4; - we(t, ["tfdt"]).forEach(function (e) { - var t = e[0], - i = r * a; - if (i) { - var n = Le(e, 4); - if (0 === t) - (n -= i), Ae(e, 4, (n = Math.max(n, 0))); - else { - (n *= Math.pow(2, 32)), - (n += Le(e, 8)), - (n -= i), - (n = Math.max(n, 0)); - var s = Math.floor(n / (ye + 1)), - o = Math.floor(n % (ye + 1)); - Ae(e, 4, s), Ae(e, 8, o); - } - } - }); - } - }); - }); - })(f, d, l.baseTime / l.timescale), - g > 0 - ? (this.lastEndTime = E) - : (A.warn( - "Duration parsed from mp4 should be greater than zero" - ), - this.resetNextTimestamp()); - var S = !!f.audio, - T = !!f.video, - _ = ""; - S && (_ += "audio"), T && (_ += "video"); - var L = { - data1: d, - startPTS: y, - startDTS: y, - endPTS: E, - endDTS: E, - type: _, - hasAudio: S, - hasVideo: T, - nb: 1, - dropped: 0, - }; - return ( - (u.audio = "audio" === L.type ? L : void 0), - (u.video = "audio" !== L.type ? L : void 0), - (u.initSegment = c), - (u.id3 = nn(r, n, l, l)), - i.samples.length && (u.text = sn(i, n, l)), - u - ); - }), - e - ); - })(); - function hn(e, t) { - var r = null == e ? void 0 : e.codec; - if (r && r.length > 4) return r; - if (t === M) { - if ("ec-3" === r || "ac-3" === r || "alac" === r) return r; - if ("fLaC" === r || "Opus" === r) return nt(r, !1); - var i = "mp4a.40.5"; - return ( - A.info( - 'Parsed audio codec "' + - r + - '" or audio object type not handled. Using "' + - i + - '"' - ), - i - ); - } - return ( - A.warn('Unhandled video codec "' + r + '"'), - "hvc1" === r || "hev1" === r - ? "hvc1.1.6.L120.90" - : "av01" === r - ? "av01.0.04M.08" - : "avc1.42e01e" - ); - } - try { - an = self.performance.now.bind(self.performance); - } catch (e) { - A.debug("Unable to use Performance API on this environment"), - (an = null == $ ? void 0 : $.Date.now); - } - var un = [ - { demux: ki, remux: ln }, - { demux: Gi, remux: tn }, - { demux: Ii, remux: tn }, - { demux: ji, remux: tn }, - ]; - un.splice(2, 0, { demux: Mi, remux: tn }); - var dn = (function () { - function e(e, t, r, i, n) { - (this.async = !1), - (this.observer = void 0), - (this.typeSupported = void 0), - (this.config = void 0), - (this.vendor = void 0), - (this.id = void 0), - (this.demuxer = void 0), - (this.remuxer = void 0), - (this.decrypter = void 0), - (this.probe = void 0), - (this.decryptionPromise = null), - (this.transmuxConfig = void 0), - (this.currentTransmuxState = void 0), - (this.observer = e), - (this.typeSupported = t), - (this.config = r), - (this.vendor = i), - (this.id = n); - } - var t = e.prototype; - return ( - (t.configure = function (e) { - (this.transmuxConfig = e), - this.decrypter && this.decrypter.reset(); - }), - (t.push = function (e, t, r, i) { - var n = this, - s = r.transmuxing; - s.executeStart = an(); - var a = new Uint8Array(e), - o = this.currentTransmuxState, - l = this.transmuxConfig; - i && (this.currentTransmuxState = i); - var h = i || o, - u = h.contiguous, - d = h.discontinuity, - c = h.trackSwitch, - f = h.accurateTimeOffset, - g = h.timeOffset, - p = h.initSegmentChange, - m = l.audioCodec, - v = l.videoCodec, - y = l.defaultInitPts, - _ = l.duration, - L = l.initSegmentData, - b = (function (e, t) { - var r = null; - return ( - e.byteLength > 0 && - null != (null == t ? void 0 : t.key) && - null !== t.iv && - null != t.method && - (r = t), - r - ); - })(a, t); - if (b && "AES-128" === b.method) { - var R = this.getDecrypter(); - if (!R.isSync()) - return ( - (this.decryptionPromise = R.webCryptoDecrypt( - a, - b.key.buffer, - b.iv.buffer - ).then(function (e) { - var t = n.push(e, null, r); - return (n.decryptionPromise = null), t; - })), - this.decryptionPromise - ); - var w = R.softwareDecrypt(a, b.key.buffer, b.iv.buffer); - if ((r.part > -1 && (w = R.flush()), !w)) - return (s.executeEnd = an()), cn(r); - a = new Uint8Array(w); - } - var P = this.needsProbing(d, c); - if (P) { - var I = this.configureTransmuxer(a); - if (I) - return ( - A.warn("[transmuxer] " + I.message), - this.observer.emit(E.ERROR, E.ERROR, { - type: S.MEDIA_ERROR, - details: T.FRAG_PARSING_ERROR, - fatal: !1, - error: I, - reason: I.message, - }), - (s.executeEnd = an()), - cn(r) - ); - } - (d || c || p || P) && - this.resetInitSegment(L, m, v, _, t), - (d || p || P) && this.resetInitialTimestamp(y), - u || this.resetContiguity(); - var C = this.transmux(a, b, g, f, r), - k = this.currentTransmuxState; - return ( - (k.contiguous = !0), - (k.discontinuity = !1), - (k.trackSwitch = !1), - (s.executeEnd = an()), - C - ); - }), - (t.flush = function (e) { - var t = this, - r = e.transmuxing; - r.executeStart = an(); - var i = this.decrypter, - n = this.currentTransmuxState, - s = this.decryptionPromise; - if (s) - return s.then(function () { - return t.flush(e); - }); - var a = [], - o = n.timeOffset; - if (i) { - var l = i.flush(); - l && a.push(this.push(l, null, e)); - } - var h = this.demuxer, - u = this.remuxer; - if (!h || !u) return (r.executeEnd = an()), [cn(e)]; - var d = h.flush(o); - return fn(d) - ? d.then(function (r) { - return t.flushRemux(a, r, e), a; - }) - : (this.flushRemux(a, d, e), a); - }), - (t.flushRemux = function (e, t, r) { - var i = t.audioTrack, - n = t.videoTrack, - s = t.id3Track, - a = t.textTrack, - o = this.currentTransmuxState, - l = o.accurateTimeOffset, - h = o.timeOffset; - A.log( - "[transmuxer.ts]: Flushed fragment " + - r.sn + - (r.part > -1 ? " p: " + r.part : "") + - " of level " + - r.level - ); - var u = this.remuxer.remux(i, n, s, a, h, l, !0, this.id); - e.push({ remuxResult: u, chunkMeta: r }), - (r.transmuxing.executeEnd = an()); - }), - (t.resetInitialTimestamp = function (e) { - var t = this.demuxer, - r = this.remuxer; - t && r && (t.resetTimeStamp(e), r.resetTimeStamp(e)); - }), - (t.resetContiguity = function () { - var e = this.demuxer, - t = this.remuxer; - e && t && (e.resetContiguity(), t.resetNextTimestamp()); - }), - (t.resetInitSegment = function (e, t, r, i, n) { - var s = this.demuxer, - a = this.remuxer; - s && - a && - (s.resetInitSegment(e, t, r, i), - a.resetInitSegment(e, t, r, n)); - }), - (t.destroy = function () { - this.demuxer && - (this.demuxer.destroy(), (this.demuxer = void 0)), - this.remuxer && - (this.remuxer.destroy(), (this.remuxer = void 0)); - }), - (t.transmux = function (e, t, r, i, n) { - return t && "SAMPLE-AES" === t.method - ? this.transmuxSampleAes(e, t, r, i, n) - : this.transmuxUnencrypted(e, r, i, n); - }), - (t.transmuxUnencrypted = function (e, t, r, i) { - var n = this.demuxer.demux( - e, - t, - !1, - !this.config.progressive - ), - s = n.audioTrack, - a = n.videoTrack, - o = n.id3Track, - l = n.textTrack; - return { - remuxResult: this.remuxer.remux( - s, - a, - o, - l, - t, - r, - !1, - this.id - ), - chunkMeta: i, - }; - }), - (t.transmuxSampleAes = function (e, t, r, i, n) { - var s = this; - return this.demuxer - .demuxSampleAes(e, t, r) - .then(function (e) { - return { - remuxResult: s.remuxer.remux( - e.audioTrack, - e.videoTrack, - e.id3Track, - e.textTrack, - r, - i, - !1, - s.id - ), - chunkMeta: n, - }; - }); - }), - (t.configureTransmuxer = function (e) { - for ( - var t, - r = this.config, - i = this.observer, - n = this.typeSupported, - s = this.vendor, - a = 0, - o = un.length; - a < o; - a++ - ) { - var l; - if (null != (l = un[a].demux) && l.probe(e)) { - t = un[a]; - break; - } - } - if (!t) - return new Error( - "Failed to find demuxer by probing fragment data" - ); - var h = this.demuxer, - u = this.remuxer, - d = t.remux, - c = t.demux; - (u && u instanceof d) || - (this.remuxer = new d(i, r, n, s)), - (h && h instanceof c) || - ((this.demuxer = new c(i, r, n)), - (this.probe = c.probe)); - }), - (t.needsProbing = function (e, t) { - return !this.demuxer || !this.remuxer || e || t; - }), - (t.getDecrypter = function () { - var e = this.decrypter; - return e || (e = this.decrypter = new jr(this.config)), e; - }), - e - ); - })(), - cn = function (e) { - return { remuxResult: {}, chunkMeta: e }; - }; - function fn(e) { - return "then" in e && e.then instanceof Function; - } - var gn = function (e, t, r, i, n) { - (this.audioCodec = void 0), - (this.videoCodec = void 0), - (this.initSegmentData = void 0), - (this.duration = void 0), - (this.defaultInitPts = void 0), - (this.audioCodec = e), - (this.videoCodec = t), - (this.initSegmentData = r), - (this.duration = i), - (this.defaultInitPts = n || null); - }, - pn = function (e, t, r, i, n, s) { - (this.discontinuity = void 0), - (this.contiguous = void 0), - (this.accurateTimeOffset = void 0), - (this.trackSwitch = void 0), - (this.timeOffset = void 0), - (this.initSegmentChange = void 0), - (this.discontinuity = e), - (this.contiguous = t), - (this.accurateTimeOffset = r), - (this.trackSwitch = i), - (this.timeOffset = n), - (this.initSegmentChange = s); - }, - mn = { exports: {} }; - !(function (e) { - var t = Object.prototype.hasOwnProperty, - r = "~"; - function i() {} - function n(e, t, r) { - (this.fn = e), (this.context = t), (this.once = r || !1); - } - function s(e, t, i, s, a) { - if ("function" != typeof i) - throw new TypeError("The listener must be a function"); - var o = new n(i, s || e, a), - l = r ? r + t : t; - return ( - e._events[l] - ? e._events[l].fn - ? (e._events[l] = [e._events[l], o]) - : e._events[l].push(o) - : ((e._events[l] = o), e._eventsCount++), - e - ); - } - function a(e, t) { - 0 == --e._eventsCount - ? (e._events = new i()) - : delete e._events[t]; - } - function o() { - (this._events = new i()), (this._eventsCount = 0); - } - Object.create && - ((i.prototype = Object.create(null)), - new i().__proto__ || (r = !1)), - (o.prototype.eventNames = function () { - var e, - i, - n = []; - if (0 === this._eventsCount) return n; - for (i in (e = this._events)) - t.call(e, i) && n.push(r ? i.slice(1) : i); - return Object.getOwnPropertySymbols - ? n.concat(Object.getOwnPropertySymbols(e)) - : n; - }), - (o.prototype.listeners = function (e) { - var t = r ? r + e : e, - i = this._events[t]; - if (!i) return []; - if (i.fn) return [i.fn]; - for (var n = 0, s = i.length, a = new Array(s); n < s; n++) - a[n] = i[n].fn; - return a; - }), - (o.prototype.listenerCount = function (e) { - var t = r ? r + e : e, - i = this._events[t]; - return i ? (i.fn ? 1 : i.length) : 0; - }), - (o.prototype.emit = function (e, t, i, n, s, a) { - var o = r ? r + e : e; - if (!this._events[o]) return !1; - var l, - h, - u = this._events[o], - d = arguments.length; - if (u.fn) { - switch ( - (u.once && this.removeListener(e, u.fn, void 0, !0), d) - ) { - case 1: - return u.fn.call(u.context), !0; - case 2: - return u.fn.call(u.context, t), !0; - case 3: - return u.fn.call(u.context, t, i), !0; - case 4: - return u.fn.call(u.context, t, i, n), !0; - case 5: - return u.fn.call(u.context, t, i, n, s), !0; - case 6: - return u.fn.call(u.context, t, i, n, s, a), !0; - } - for (h = 1, l = new Array(d - 1); h < d; h++) - l[h - 1] = arguments[h]; - u.fn.apply(u.context, l); - } else { - var c, - f = u.length; - for (h = 0; h < f; h++) - switch ( - (u[h].once && - this.removeListener(e, u[h].fn, void 0, !0), - d) - ) { - case 1: - u[h].fn.call(u[h].context); - break; - case 2: - u[h].fn.call(u[h].context, t); - break; - case 3: - u[h].fn.call(u[h].context, t, i); - break; - case 4: - u[h].fn.call(u[h].context, t, i, n); - break; - default: - if (!l) - for (c = 1, l = new Array(d - 1); c < d; c++) - l[c - 1] = arguments[c]; - u[h].fn.apply(u[h].context, l); - } - } - return !0; - }), - (o.prototype.on = function (e, t, r) { - return s(this, e, t, r, !1); - }), - (o.prototype.once = function (e, t, r) { - return s(this, e, t, r, !0); - }), - (o.prototype.removeListener = function (e, t, i, n) { - var s = r ? r + e : e; - if (!this._events[s]) return this; - if (!t) return a(this, s), this; - var o = this._events[s]; - if (o.fn) - o.fn !== t || - (n && !o.once) || - (i && o.context !== i) || - a(this, s); - else { - for (var l = 0, h = [], u = o.length; l < u; l++) - (o[l].fn !== t || - (n && !o[l].once) || - (i && o[l].context !== i)) && - h.push(o[l]); - h.length - ? (this._events[s] = 1 === h.length ? h[0] : h) - : a(this, s); - } - return this; - }), - (o.prototype.removeAllListeners = function (e) { - var t; - return ( - e - ? ((t = r ? r + e : e), this._events[t] && a(this, t)) - : ((this._events = new i()), (this._eventsCount = 0)), - this - ); - }), - (o.prototype.off = o.prototype.removeListener), - (o.prototype.addListener = o.prototype.on), - (o.prefixed = r), - (o.EventEmitter = o), - (e.exports = o); - })(mn); - var vn = (function (e) { - return e && - e.__esModule && - Object.prototype.hasOwnProperty.call(e, "default") - ? e.default - : e; - })(mn.exports); - function yn(e, t) { - if ( - !( - (r = t.remuxResult).audio || - r.video || - r.text || - r.id3 || - r.initSegment - ) - ) - return !1; - var r, - i = [], - n = t.remuxResult, - s = n.audio, - a = n.video; - return ( - s && En(i, s), - a && En(i, a), - e.postMessage({ event: "transmuxComplete", data: t }, i), - !0 - ); - } - function En(e, t) { - t.data1 && e.push(t.data1.buffer), - t.data2 && e.push(t.data2.buffer); - } - function Sn(e, t, r) { - t.reduce(function (t, r) { - return yn(e, r) || t; - }, !1) || - e.postMessage({ event: "transmuxComplete", data: t[0] }), - e.postMessage({ event: "flush", data: r }); - } - void 0 !== r && - r && - (function (e) { - var t = new vn(), - r = function (t, r) { - e.postMessage({ event: t, data: r }); - }; - t.on(E.FRAG_DECRYPTED, r), t.on(E.ERROR, r); - e.addEventListener("message", function (i) { - var n = i.data; - switch (n.cmd) { - case "init": - var s = JSON.parse(n.config); - (e.transmuxer = new dn( - t, - n.typeSupported, - s, - "", - n.id - )), - R(s.debug, n.id), - (function () { - var e = function (e) { - A[e] = function (t) { - r("workerLog", { logType: e, message: t }); - }; - }; - for (var t in A) e(t); - })(), - r("init", null); - break; - case "configure": - e.transmuxer.configure(n.config); - break; - case "demux": - var a = e.transmuxer.push( - n.data, - n.decryptdata, - n.chunkMeta, - n.state - ); - fn(a) - ? ((e.transmuxer.async = !0), - a - .then(function (t) { - yn(e, t); - }) - .catch(function (e) { - r(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.FRAG_PARSING_ERROR, - chunkMeta: n.chunkMeta, - fatal: !1, - error: e, - err: e, - reason: "transmuxer-worker push error", - }); - })) - : ((e.transmuxer.async = !1), yn(e, a)); - break; - case "flush": - var o = n.chunkMeta, - l = e.transmuxer.flush(o); - fn(l) || e.transmuxer.async - ? (fn(l) || (l = Promise.resolve(l)), - l - .then(function (t) { - Sn(e, t, o); - }) - .catch(function (e) { - r(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.FRAG_PARSING_ERROR, - chunkMeta: n.chunkMeta, - fatal: !1, - error: e, - err: e, - reason: "transmuxer-worker flush error", - }); - })) - : Sn(e, l, o); - } - }); - })(self); - var Tn = (function () { - function e(e, r, i, n) { - var s = this; - (this.error = null), - (this.hls = void 0), - (this.id = void 0), - (this.observer = void 0), - (this.frag = null), - (this.part = null), - (this.useWorker = void 0), - (this.workerContext = null), - (this.onwmsg = void 0), - (this.transmuxer = null), - (this.onTransmuxComplete = void 0), - (this.onFlush = void 0); - var a = e.config; - (this.hls = e), - (this.id = r), - (this.useWorker = !!a.enableWorker), - (this.onTransmuxComplete = i), - (this.onFlush = n); - var o = function (e, t) { - ((t = t || {}).frag = s.frag), - (t.id = s.id), - e === E.ERROR && (s.error = t.error), - s.hls.trigger(e, t); - }; - (this.observer = new vn()), - this.observer.on(E.FRAG_DECRYPTED, o), - this.observer.on(E.ERROR, o); - var l, - h, - u, - d, - c = ze(a.preferManagedMediaSource) || { - isTypeSupported: function () { - return !1; - }, - }, - f = { - mpeg: c.isTypeSupported("audio/mpeg"), - mp3: c.isTypeSupported('audio/mp4; codecs="mp3"'), - ac3: c.isTypeSupported('audio/mp4; codecs="ac-3"'), - }; - if ( - !this.useWorker || - "undefined" == typeof Worker || - (a.workerPath, 0) - ) - this.transmuxer = new dn(this.observer, f, a, "", r); - else - try { - a.workerPath - ? (A.log( - "loading Web Worker " + - a.workerPath + - ' for "' + - r + - '"' - ), - (this.workerContext = - ((u = a.workerPath), - (d = new self.URL(u, self.location.href).href), - { worker: new self.Worker(d), scriptURL: d }))) - : (A.log('injecting Web Worker for "' + r + '"'), - (this.workerContext = - ((l = new self.Blob( - [ - "var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(" + - t.toString() + - ")(true);", - ], - { type: "text/javascript" } - )), - (h = self.URL.createObjectURL(l)), - { worker: new self.Worker(h), objectURL: h }))), - (this.onwmsg = function (e) { - return s.onWorkerMessage(e); - }); - var g = this.workerContext.worker; - g.addEventListener("message", this.onwmsg), - (g.onerror = function (e) { - var t = new Error( - e.message + - " (" + - e.filename + - ":" + - e.lineno + - ")" - ); - (a.enableWorker = !1), - A.warn( - 'Error in "' + - r + - '" Web Worker, fallback to inline' - ), - s.hls.trigger(E.ERROR, { - type: S.OTHER_ERROR, - details: T.INTERNAL_EXCEPTION, - fatal: !1, - event: "demuxerWorker", - error: t, - }); - }), - g.postMessage({ - cmd: "init", - typeSupported: f, - vendor: "", - id: r, - config: JSON.stringify(a), - }); - } catch (e) { - A.warn( - 'Error setting up "' + - r + - '" Web Worker, fallback to inline', - e - ), - this.resetWorker(), - (this.error = null), - (this.transmuxer = new dn(this.observer, f, a, "", r)); - } - } - var r = e.prototype; - return ( - (r.resetWorker = function () { - if (this.workerContext) { - var e = this.workerContext, - t = e.worker, - r = e.objectURL; - r && self.URL.revokeObjectURL(r), - t.removeEventListener("message", this.onwmsg), - (t.onerror = null), - t.terminate(), - (this.workerContext = null); - } - }), - (r.destroy = function () { - if (this.workerContext) - this.resetWorker(), (this.onwmsg = void 0); - else { - var e = this.transmuxer; - e && (e.destroy(), (this.transmuxer = null)); - } - var t = this.observer; - t && t.removeAllListeners(), - (this.frag = null), - (this.observer = null), - (this.hls = null); - }), - (r.push = function (e, t, r, i, n, s, a, o, l, h) { - var u, - d, - c = this; - l.transmuxing.start = self.performance.now(); - var f = this.transmuxer, - g = s ? s.start : n.start, - p = n.decryptdata, - m = this.frag, - v = !(m && n.cc === m.cc), - y = !(m && l.level === m.level), - E = m ? l.sn - m.sn : -1, - S = this.part ? l.part - this.part.index : -1, - T = - 0 === E && - l.id > 1 && - l.id === (null == m ? void 0 : m.stats.chunkCount), - _ = - !y && - (1 === E || (0 === E && (1 === S || (T && S <= 0)))), - L = self.performance.now(); - (y || E || 0 === n.stats.parsing.start) && - (n.stats.parsing.start = L), - !s || (!S && _) || (s.stats.parsing.start = L); - var b = !( - m && - (null == (u = n.initSegment) ? void 0 : u.url) === - (null == (d = m.initSegment) ? void 0 : d.url) - ), - R = new pn(v, _, o, y, g, b); - if (!_ || v || b) { - A.log( - "[transmuxer-interface, " + - n.type + - "]: Starting new transmux session for sn: " + - l.sn + - " p: " + - l.part + - " level: " + - l.level + - " id: " + - l.id + - "\n discontinuity: " + - v + - "\n trackSwitch: " + - y + - "\n contiguous: " + - _ + - "\n accurateTimeOffset: " + - o + - "\n timeOffset: " + - g + - "\n initSegmentChange: " + - b - ); - var w = new gn(r, i, t, a, h); - this.configureTransmuxer(w); - } - if (((this.frag = n), (this.part = s), this.workerContext)) - this.workerContext.worker.postMessage( - { - cmd: "demux", - data: e, - decryptdata: p, - chunkMeta: l, - state: R, - }, - e instanceof ArrayBuffer ? [e] : [] - ); - else if (f) { - var P = f.push(e, p, l, R); - fn(P) - ? ((f.async = !0), - P.then(function (e) { - c.handleTransmuxComplete(e); - }).catch(function (e) { - c.transmuxerError( - e, - l, - "transmuxer-interface push error" - ); - })) - : ((f.async = !1), this.handleTransmuxComplete(P)); - } - }), - (r.flush = function (e) { - var t = this; - e.transmuxing.start = self.performance.now(); - var r = this.transmuxer; - if (this.workerContext) - this.workerContext.worker.postMessage({ - cmd: "flush", - chunkMeta: e, - }); - else if (r) { - var i = r.flush(e); - fn(i) || r.async - ? (fn(i) || (i = Promise.resolve(i)), - i - .then(function (r) { - t.handleFlushResult(r, e); - }) - .catch(function (r) { - t.transmuxerError( - r, - e, - "transmuxer-interface flush error" - ); - })) - : this.handleFlushResult(i, e); - } - }), - (r.transmuxerError = function (e, t, r) { - this.hls && - ((this.error = e), - this.hls.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.FRAG_PARSING_ERROR, - chunkMeta: t, - frag: this.frag || void 0, - fatal: !1, - error: e, - err: e, - reason: r, - })); - }), - (r.handleFlushResult = function (e, t) { - var r = this; - e.forEach(function (e) { - r.handleTransmuxComplete(e); - }), - this.onFlush(t); - }), - (r.onWorkerMessage = function (e) { - var t = e.data; - if (null != t && t.event) { - var r = this.hls; - if (this.hls) - switch (t.event) { - case "init": - var i, - n = - null == (i = this.workerContext) - ? void 0 - : i.objectURL; - n && self.URL.revokeObjectURL(n); - break; - case "transmuxComplete": - this.handleTransmuxComplete(t.data); - break; - case "flush": - this.onFlush(t.data); - break; - case "workerLog": - A[t.data.logType] && - A[t.data.logType](t.data.message); - break; - default: - (t.data = t.data || {}), - (t.data.frag = this.frag), - (t.data.id = this.id), - r.trigger(t.event, t.data); - } - } else - A.warn( - "worker message received with no " + - (t ? "event name" : "data") - ); - }), - (r.configureTransmuxer = function (e) { - var t = this.transmuxer; - this.workerContext - ? this.workerContext.worker.postMessage({ - cmd: "configure", - config: e, - }) - : t && t.configure(e); - }), - (r.handleTransmuxComplete = function (e) { - (e.chunkMeta.transmuxing.end = self.performance.now()), - this.onTransmuxComplete(e); - }), - e - ); - })(); - function _n(e, t) { - if (e.length !== t.length) return !1; - for (var r = 0; r < e.length; r++) - if (!Ln(e[r].attrs, t[r].attrs)) return !1; - return !0; - } - function Ln(e, t, r) { - var i = e["STABLE-RENDITION-ID"]; - return i && !r - ? i === t["STABLE-RENDITION-ID"] - : !( - r || [ - "LANGUAGE", - "NAME", - "CHARACTERISTICS", - "AUTOSELECT", - "DEFAULT", - "FORCED", - "ASSOC-LANGUAGE", - ] - ).some(function (r) { - return e[r] !== t[r]; - }); - } - function bn(e, t) { - return ( - t.label.toLowerCase() === e.name.toLowerCase() && - (!t.language || - t.language.toLowerCase() === (e.lang || "").toLowerCase()) - ); - } - var Rn = (function (e) { - function t(t, r, i) { - var n; - return ( - ((n = - e.call( - this, - t, - r, - i, - "[audio-stream-controller]", - bt - ) || this).videoBuffer = null), - (n.videoTrackCC = -1), - (n.waitingVideoCC = -1), - (n.bufferedTrack = null), - (n.switchingTrack = null), - (n.trackId = -1), - (n.waitingData = null), - (n.mainDetails = null), - (n.flushing = !1), - (n.bufferFlushed = !1), - (n.cachedTrackLoadedData = null), - n._registerListeners(), - n - ); - } - l(t, e); - var r = t.prototype; - return ( - (r.onHandlerDestroying = function () { - this._unregisterListeners(), - e.prototype.onHandlerDestroying.call(this), - (this.mainDetails = null), - (this.bufferedTrack = null), - (this.switchingTrack = null); - }), - (r._registerListeners = function () { - var e = this.hls; - e.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.LEVEL_LOADED, this.onLevelLoaded, this), - e.on( - E.AUDIO_TRACKS_UPDATED, - this.onAudioTracksUpdated, - this - ), - e.on( - E.AUDIO_TRACK_SWITCHING, - this.onAudioTrackSwitching, - this - ), - e.on( - E.AUDIO_TRACK_LOADED, - this.onAudioTrackLoaded, - this - ), - e.on(E.ERROR, this.onError, this), - e.on(E.BUFFER_RESET, this.onBufferReset, this), - e.on(E.BUFFER_CREATED, this.onBufferCreated, this), - e.on(E.BUFFER_FLUSHING, this.onBufferFlushing, this), - e.on(E.BUFFER_FLUSHED, this.onBufferFlushed, this), - e.on(E.INIT_PTS_FOUND, this.onInitPtsFound, this), - e.on(E.FRAG_BUFFERED, this.onFragBuffered, this); - }), - (r._unregisterListeners = function () { - var e = this.hls; - e.off(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.off(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.off(E.LEVEL_LOADED, this.onLevelLoaded, this), - e.off( - E.AUDIO_TRACKS_UPDATED, - this.onAudioTracksUpdated, - this - ), - e.off( - E.AUDIO_TRACK_SWITCHING, - this.onAudioTrackSwitching, - this - ), - e.off( - E.AUDIO_TRACK_LOADED, - this.onAudioTrackLoaded, - this - ), - e.off(E.ERROR, this.onError, this), - e.off(E.BUFFER_RESET, this.onBufferReset, this), - e.off(E.BUFFER_CREATED, this.onBufferCreated, this), - e.off(E.BUFFER_FLUSHING, this.onBufferFlushing, this), - e.off(E.BUFFER_FLUSHED, this.onBufferFlushed, this), - e.off(E.INIT_PTS_FOUND, this.onInitPtsFound, this), - e.off(E.FRAG_BUFFERED, this.onFragBuffered, this); - }), - (r.onInitPtsFound = function (e, t) { - var r = t.frag, - i = t.id, - n = t.initPTS, - s = t.timescale; - if ("main" === i) { - var a = r.cc; - (this.initPTS[r.cc] = { baseTime: n, timescale: s }), - this.log( - "InitPTS for cc: " + a + " found from main: " + n - ), - (this.videoTrackCC = a), - this.state === ni && this.tick(); - } - }), - (r.startLoad = function (e) { - if (!this.levels) - return (this.startPosition = e), void (this.state = Yr); - var t = this.lastCurrentTime; - this.stopLoad(), - this.setInterval(100), - t > 0 && -1 === e - ? (this.log( - "Override startPosition with lastCurrentTime @" + - t.toFixed(3) - ), - (e = t), - (this.state = zr)) - : ((this.loadedmetadata = !1), (this.state = Zr)), - (this.nextLoadPosition = - this.startPosition = - this.lastCurrentTime = - e), - this.tick(); - }), - (r.doTick = function () { - switch (this.state) { - case zr: - this.doTickIdle(); - break; - case Zr: - var t, - r = this.levels, - i = this.trackId, - n = - null == r || null == (t = r[i]) - ? void 0 - : t.details; - if (n) { - if (this.waitForCdnTuneIn(n)) break; - this.state = ni; - } - break; - case Jr: - var s, - a = performance.now(), - o = this.retryDate; - if ( - !o || - a >= o || - (null != (s = this.media) && s.seeking) - ) { - var l = this.levels, - h = this.trackId; - this.log( - "RetryDate reached, switch back to IDLE state" - ), - this.resetStartWhenNotLoaded( - (null == l ? void 0 : l[h]) || null - ), - (this.state = zr); - } - break; - case ni: - var u = this.waitingData; - if (u) { - var d = u.frag, - c = u.part, - f = u.cache, - g = u.complete; - if (void 0 !== this.initPTS[d.cc]) { - (this.waitingData = null), - (this.waitingVideoCC = -1), - (this.state = Qr); - var p = { - frag: d, - part: c, - payload: f.flush(), - networkDetails: null, - }; - this._handleFragmentLoadProgress(p), - g && - e.prototype._handleFragmentLoadComplete.call( - this, - p - ); - } else if ( - this.videoTrackCC !== this.waitingVideoCC - ) - this.log( - "Waiting fragment cc (" + - d.cc + - ") cancelled because video is at cc " + - this.videoTrackCC - ), - this.clearWaitingFragment(); - else { - var m = this.getLoadPosition(), - v = Mr.bufferInfo( - this.mediaBuffer, - m, - this.config.maxBufferHole - ); - hr(v.end, this.config.maxFragLookUpTolerance, d) < - 0 && - (this.log( - "Waiting fragment cc (" + - d.cc + - ") @ " + - d.start + - " cancelled because another fragment at " + - v.end + - " is needed" - ), - this.clearWaitingFragment()); - } - } else this.state = zr; - } - this.onTickEnd(); - }), - (r.clearWaitingFragment = function () { - var e = this.waitingData; - e && - (this.fragmentTracker.removeFragment(e.frag), - (this.waitingData = null), - (this.waitingVideoCC = -1), - (this.state = zr)); - }), - (r.resetLoadingState = function () { - this.clearWaitingFragment(), - e.prototype.resetLoadingState.call(this); - }), - (r.onTickEnd = function () { - var e = this.media; - null != e && - e.readyState && - (this.lastCurrentTime = e.currentTime); - }), - (r.doTickIdle = function () { - var e = this.hls, - t = this.levels, - r = this.media, - i = this.trackId, - n = e.config; - if ( - (r || - (!this.startFragRequested && n.startFragPrefetch)) && - null != t && - t[i] - ) { - var s = t[i], - a = s.details; - if ( - !a || - (a.live && this.levelLastLoaded !== s) || - this.waitForCdnTuneIn(a) - ) - this.state = Zr; - else { - var o = this.mediaBuffer - ? this.mediaBuffer - : this.media; - this.bufferFlushed && - o && - ((this.bufferFlushed = !1), - this.afterBufferFlushed(o, M, bt)); - var l = this.getFwdBufferInfo(o, bt); - if (null !== l) { - var h = this.bufferedTrack, - u = this.switchingTrack; - if (!u && this._streamEnded(l, a)) - return ( - e.trigger(E.BUFFER_EOS, { type: "audio" }), - void (this.state = ri) - ); - var d = this.getFwdBufferInfo( - this.videoBuffer - ? this.videoBuffer - : this.media, - Lt - ), - c = l.len, - f = this.getMaxBufferLength( - null == d ? void 0 : d.len - ), - g = a.fragments, - p = g[0].start, - m = this.flushing - ? this.getLoadPosition() - : l.end; - if (u && r) { - var v = this.getLoadPosition(); - h && !Ln(u.attrs, h.attrs) && (m = v), - a.PTSKnown && - v < p && - (l.end > p || l.nextStart) && - (this.log( - "Alt audio track ahead of main track, seek to start of alt audio track" - ), - (r.currentTime = p + 0.05)); - } - if (!(c >= f && !u && m < g[g.length - 1].start)) { - var y = this.getNextFragment(m, a), - S = !1; - if ( - (y && - this.isLoopLoading(y, m) && - ((S = !!y.gap), - (y = this.getNextFragmentLoopLoading( - y, - a, - l, - Lt, - f - ))), - y) - ) { - var T = d && y.start > d.end + a.targetduration; - if (T || ((null == d || !d.len) && l.len)) { - var _ = this.getAppendedFrag(y.start, Lt); - if (null === _) return; - if ( - (S || (S = !!_.gap || (!!T && 0 === d.len)), - (T && !S) || - (S && l.nextStart && l.nextStart < _.end)) - ) - return; - } - this.loadFragment(y, s, m); - } else this.bufferFlushed = !0; - } - } - } - } - }), - (r.getMaxBufferLength = function (t) { - var r = e.prototype.getMaxBufferLength.call(this); - return t - ? Math.min( - Math.max(r, t), - this.config.maxMaxBufferLength - ) - : r; - }), - (r.onMediaDetaching = function () { - (this.videoBuffer = null), - (this.bufferFlushed = this.flushing = !1), - e.prototype.onMediaDetaching.call(this); - }), - (r.onAudioTracksUpdated = function (e, t) { - var r = t.audioTracks; - this.resetTransmuxer(), - (this.levels = r.map(function (e) { - return new qt(e); - })); - }), - (r.onAudioTrackSwitching = function (e, t) { - var r = !!t.url; - this.trackId = t.id; - var i = this.fragCurrent; - i && - (i.abortRequests(), - this.removeUnbufferedFrags(i.start)), - this.resetLoadingState(), - r ? this.setInterval(100) : this.resetTransmuxer(), - r - ? ((this.switchingTrack = t), - (this.state = zr), - this.flushAudioIfNeeded(t)) - : ((this.switchingTrack = null), - (this.bufferedTrack = t), - (this.state = Yr)), - this.tick(); - }), - (r.onManifestLoading = function () { - this.fragmentTracker.removeAllFragments(), - (this.startPosition = this.lastCurrentTime = 0), - (this.bufferFlushed = this.flushing = !1), - (this.levels = - this.mainDetails = - this.waitingData = - this.bufferedTrack = - this.cachedTrackLoadedData = - this.switchingTrack = - null), - (this.startFragRequested = !1), - (this.trackId = - this.videoTrackCC = - this.waitingVideoCC = - -1); - }), - (r.onLevelLoaded = function (e, t) { - (this.mainDetails = t.details), - null !== this.cachedTrackLoadedData && - (this.hls.trigger( - E.AUDIO_TRACK_LOADED, - this.cachedTrackLoadedData - ), - (this.cachedTrackLoadedData = null)); - }), - (r.onAudioTrackLoaded = function (e, t) { - var r; - if (null != this.mainDetails) { - var i = this.levels, - n = t.details, - s = t.id; - if (i) { - this.log( - "Audio track " + - s + - " loaded [" + - n.startSN + - "," + - n.endSN + - "]" + - (n.lastPartSn - ? "[part-" + - n.lastPartSn + - "-" + - n.lastPartIndex + - "]" - : "") + - ",duration:" + - n.totalduration - ); - var a = i[s], - o = 0; - if (n.live || (null != (r = a.details) && r.live)) { - this.checkLiveUpdate(n); - var l, - h = this.mainDetails; - if (n.deltaUpdateFailed || !h) return; - !a.details && - n.hasProgramDateTime && - h.hasProgramDateTime - ? (Br(n, h), (o = n.fragments[0].start)) - : (o = this.alignPlaylists( - n, - a.details, - null == (l = this.levelLastLoaded) - ? void 0 - : l.details - )); - } - (a.details = n), - (this.levelLastLoaded = a), - this.startFragRequested || - (!this.mainDetails && n.live) || - this.setStartPosition(this.mainDetails || n, o), - this.state !== Zr || - this.waitForCdnTuneIn(n) || - (this.state = zr), - this.tick(); - } else - this.warn( - "Audio tracks were reset while loading level " + s - ); - } else this.cachedTrackLoadedData = t; - }), - (r._handleFragmentLoadProgress = function (e) { - var t, - r = e.frag, - i = e.part, - n = e.payload, - s = this.config, - a = this.trackId, - o = this.levels; - if (o) { - var l = o[a]; - if (l) { - var h = l.details; - if (!h) - return ( - this.warn( - "Audio track details undefined on fragment load progress" - ), - void this.removeUnbufferedFrags(r.start) - ); - var u = - s.defaultAudioCodec || - l.audioCodec || - "mp4a.40.2", - d = this.transmuxer; - d || - (d = this.transmuxer = - new Tn( - this.hls, - bt, - this._handleTransmuxComplete.bind(this), - this._handleTransmuxerFlush.bind(this) - )); - var c = this.initPTS[r.cc], - f = null == (t = r.initSegment) ? void 0 : t.data; - if (void 0 !== c) { - var g = i ? i.index : -1, - p = -1 !== g, - m = new xr( - r.level, - r.sn, - r.stats.chunkCount, - n.byteLength, - g, - p - ); - d.push( - n, - f, - u, - "", - r, - i, - h.totalduration, - !1, - m, - c - ); - } else - this.log( - "Unknown video PTS for cc " + - r.cc + - ", waiting for video PTS before demuxing audio frag " + - r.sn + - " of [" + - h.startSN + - " ," + - h.endSN + - "],track " + - a - ), - (this.waitingData = this.waitingData || { - frag: r, - part: i, - cache: new oi(), - complete: !1, - }).cache.push(new Uint8Array(n)), - (this.waitingVideoCC = this.videoTrackCC), - (this.state = ni); - } else - this.warn( - "Audio track is undefined on fragment load progress" - ); - } else - this.warn( - "Audio tracks were reset while fragment load was in progress. Fragment " + - r.sn + - " of level " + - r.level + - " will not be buffered" - ); - }), - (r._handleFragmentLoadComplete = function (t) { - this.waitingData - ? (this.waitingData.complete = !0) - : e.prototype._handleFragmentLoadComplete.call(this, t); - }), - (r.onBufferReset = function () { - (this.mediaBuffer = this.videoBuffer = null), - (this.loadedmetadata = !1); - }), - (r.onBufferCreated = function (e, t) { - var r = t.tracks.audio; - r && (this.mediaBuffer = r.buffer || null), - t.tracks.video && - (this.videoBuffer = t.tracks.video.buffer || null); - }), - (r.onFragBuffered = function (e, t) { - var r = t.frag, - n = t.part; - if (r.type === bt) - if (this.fragContextChanged(r)) - this.warn( - "Fragment " + - r.sn + - (n ? " p: " + n.index : "") + - " of level " + - r.level + - " finished buffering, but was aborted. state: " + - this.state + - ", audioSwitch: " + - (this.switchingTrack - ? this.switchingTrack.name - : "false") - ); - else { - if ("initSegment" !== r.sn) { - this.fragPrevious = r; - var s = this.switchingTrack; - s && - ((this.bufferedTrack = s), - (this.switchingTrack = null), - this.hls.trigger( - E.AUDIO_TRACK_SWITCHED, - i({}, s) - )); - } - this.fragBufferedComplete(r, n); - } - else if (!this.loadedmetadata && r.type === Lt) { - var a = this.videoBuffer || this.media; - a && - Mr.getBuffered(a).length && - (this.loadedmetadata = !0); - } - }), - (r.onError = function (t, r) { - var i; - if (r.fatal) this.state = ii; - else - switch (r.details) { - case T.FRAG_GAP: - case T.FRAG_PARSING_ERROR: - case T.FRAG_DECRYPT_ERROR: - case T.FRAG_LOAD_ERROR: - case T.FRAG_LOAD_TIMEOUT: - case T.KEY_LOAD_ERROR: - case T.KEY_LOAD_TIMEOUT: - this.onFragmentOrKeyLoadError(bt, r); - break; - case T.AUDIO_TRACK_LOAD_ERROR: - case T.AUDIO_TRACK_LOAD_TIMEOUT: - case T.LEVEL_PARSING_ERROR: - r.levelRetry || - this.state !== Zr || - (null == (i = r.context) ? void 0 : i.type) !== - Tt || - (this.state = zr); - break; - case T.BUFFER_APPEND_ERROR: - case T.BUFFER_FULL_ERROR: - if (!r.parent || "audio" !== r.parent) return; - if (r.details === T.BUFFER_APPEND_ERROR) - return void this.resetLoadingState(); - this.reduceLengthAndFlushBuffer(r) && - ((this.bufferedTrack = null), - e.prototype.flushMainBuffer.call( - this, - 0, - Number.POSITIVE_INFINITY, - "audio" - )); - break; - case T.INTERNAL_EXCEPTION: - this.recoverWorkerError(r); - } - }), - (r.onBufferFlushing = function (e, t) { - t.type !== x && (this.flushing = !0); - }), - (r.onBufferFlushed = function (e, t) { - var r = t.type; - if (r !== x) { - (this.flushing = !1), - (this.bufferFlushed = !0), - this.state === ri && (this.state = zr); - var i = this.mediaBuffer || this.media; - i && (this.afterBufferFlushed(i, r, bt), this.tick()); - } - }), - (r._handleTransmuxComplete = function (e) { - var t, - r = "audio", - i = this.hls, - n = e.remuxResult, - s = e.chunkMeta, - a = this.getCurrentContext(s); - if (a) { - var l = a.frag, - h = a.part, - u = a.level, - d = u.details, - c = n.audio, - f = n.text, - g = n.id3, - p = n.initSegment; - if (!this.fragContextChanged(l) && d) { - if ( - ((this.state = ei), - this.switchingTrack && - c && - this.completeAudioSwitch(this.switchingTrack), - null != p && p.tracks) - ) { - var m = l.initSegment || l; - this._bufferInitSegment(u, p.tracks, m, s), - i.trigger(E.FRAG_PARSING_INIT_SEGMENT, { - frag: m, - id: r, - tracks: p.tracks, - }); - } - if (c) { - var v = c.startPTS, - y = c.endPTS, - S = c.startDTS, - T = c.endDTS; - h && - (h.elementaryStreams[M] = { - startPTS: v, - endPTS: y, - startDTS: S, - endDTS: T, - }), - l.setElementaryStreamInfo(M, v, y, S, T), - this.bufferFragmentData(c, l, h, s); - } - if ( - null != g && - null != (t = g.samples) && - t.length - ) { - var _ = o({ id: r, frag: l, details: d }, g); - i.trigger(E.FRAG_PARSING_METADATA, _); - } - if (f) { - var L = o({ id: r, frag: l, details: d }, f); - i.trigger(E.FRAG_PARSING_USERDATA, L); - } - } else this.fragmentTracker.removeFragment(l); - } else this.resetWhenMissingContext(s); - }), - (r._bufferInitSegment = function (e, t, r, i) { - if (this.state === ei) { - t.video && delete t.video; - var n = t.audio; - if (n) { - n.id = "audio"; - var s = e.audioCodec; - this.log( - "Init audio buffer, container:" + - n.container + - ", codecs[level/parsed]=[" + - s + - "/" + - n.codec + - "]" - ), - s && - 1 === s.split(",").length && - (n.levelCodec = s), - this.hls.trigger(E.BUFFER_CODECS, t); - var a = n.initSegment; - if (null != a && a.byteLength) { - var o = { - type: "audio", - frag: r, - part: null, - chunkMeta: i, - parent: r.type, - data: a, - }; - this.hls.trigger(E.BUFFER_APPENDING, o); - } - this.tickImmediate(); - } - } - }), - (r.loadFragment = function (t, r, i) { - var n, - s = this.fragmentTracker.getState(t); - if ( - ((this.fragCurrent = t), - this.switchingTrack || s === Rr || s === wr) - ) - if ("initSegment" === t.sn) this._loadInitSegment(t, r); - else if ( - null != (n = r.details) && - n.live && - !this.initPTS[t.cc] - ) { - this.log( - "Waiting for video PTS in continuity counter " + - t.cc + - " of live stream before loading audio fragment " + - t.sn + - " of level " + - this.trackId - ), - (this.state = ni); - var a = this.mainDetails; - a && - a.fragments[0].start !== - r.details.fragments[0].start && - Br(r.details, a); - } else - (this.startFragRequested = !0), - e.prototype.loadFragment.call(this, t, r, i); - else this.clearTrackerIfNeeded(t); - }), - (r.flushAudioIfNeeded = function (t) { - var r = this.media, - i = this.bufferedTrack, - n = null == i ? void 0 : i.attrs, - s = t.attrs; - r && - n && - (n.CHANNELS !== s.CHANNELS || - i.name !== t.name || - i.lang !== t.lang) && - (this.log("Switching audio track : flushing all audio"), - e.prototype.flushMainBuffer.call( - this, - 0, - Number.POSITIVE_INFINITY, - "audio" - ), - (this.bufferedTrack = null)); - }), - (r.completeAudioSwitch = function (e) { - var t = this.hls; - this.flushAudioIfNeeded(e), - (this.bufferedTrack = e), - (this.switchingTrack = null), - t.trigger(E.AUDIO_TRACK_SWITCHED, i({}, e)); - }), - t - ); - })(ai), - An = (function (e) { - function t(t) { - var r; - return ( - ((r = - e.call(this, t, "[audio-track-controller]") || - this).tracks = []), - (r.groupIds = null), - (r.tracksInGroup = []), - (r.trackId = -1), - (r.currentTrack = null), - (r.selectDefaultTrack = !0), - r.registerListeners(), - r - ); - } - l(t, e); - var r = t.prototype; - return ( - (r.registerListeners = function () { - var e = this.hls; - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.on(E.LEVEL_LOADING, this.onLevelLoading, this), - e.on(E.LEVEL_SWITCHING, this.onLevelSwitching, this), - e.on( - E.AUDIO_TRACK_LOADED, - this.onAudioTrackLoaded, - this - ), - e.on(E.ERROR, this.onError, this); - }), - (r.unregisterListeners = function () { - var e = this.hls; - e.off(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.off(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.off(E.LEVEL_LOADING, this.onLevelLoading, this), - e.off(E.LEVEL_SWITCHING, this.onLevelSwitching, this), - e.off( - E.AUDIO_TRACK_LOADED, - this.onAudioTrackLoaded, - this - ), - e.off(E.ERROR, this.onError, this); - }), - (r.destroy = function () { - this.unregisterListeners(), - (this.tracks.length = 0), - (this.tracksInGroup.length = 0), - (this.currentTrack = null), - e.prototype.destroy.call(this); - }), - (r.onManifestLoading = function () { - (this.tracks = []), - (this.tracksInGroup = []), - (this.groupIds = null), - (this.currentTrack = null), - (this.trackId = -1), - (this.selectDefaultTrack = !0); - }), - (r.onManifestParsed = function (e, t) { - this.tracks = t.audioTracks || []; - }), - (r.onAudioTrackLoaded = function (e, t) { - var r = t.id, - i = t.groupId, - n = t.details, - s = this.tracksInGroup[r]; - if (s && s.groupId === i) { - var a = s.details; - (s.details = t.details), - this.log( - "Audio track " + - r + - ' "' + - s.name + - '" lang:' + - s.lang + - " group:" + - i + - " loaded [" + - n.startSN + - "-" + - n.endSN + - "]" - ), - r === this.trackId && this.playlistLoaded(r, t, a); - } else - this.warn( - "Audio track with id:" + - r + - " and group:" + - i + - " not found in active group " + - (null == s ? void 0 : s.groupId) - ); - }), - (r.onLevelLoading = function (e, t) { - this.switchLevel(t.level); - }), - (r.onLevelSwitching = function (e, t) { - this.switchLevel(t.level); - }), - (r.switchLevel = function (e) { - var t = this.hls.levels[e]; - if (t) { - var r = t.audioGroups || null, - i = this.groupIds, - n = this.currentTrack; - if ( - !r || - (null == i ? void 0 : i.length) !== - (null == r ? void 0 : r.length) || - (null != r && - r.some(function (e) { - return -1 === (null == i ? void 0 : i.indexOf(e)); - })) - ) { - (this.groupIds = r), - (this.trackId = -1), - (this.currentTrack = null); - var s = this.tracks.filter(function (e) { - return !r || -1 !== r.indexOf(e.groupId); - }); - if (s.length) - this.selectDefaultTrack && - !s.some(function (e) { - return e.default; - }) && - (this.selectDefaultTrack = !1), - s.forEach(function (e, t) { - e.id = t; - }); - else if (!n && !this.tracksInGroup.length) return; - this.tracksInGroup = s; - var a = this.hls.config.audioPreference; - if (!n && a) { - var o = Er(a, s, Tr); - if (o > -1) n = s[o]; - else { - var l = Er(a, this.tracks); - n = this.tracks[l]; - } - } - var h = this.findTrackId(n); - -1 === h && n && (h = this.findTrackId(null)); - var u = { audioTracks: s }; - this.log( - "Updating audio tracks, " + - s.length + - " track(s) found in group(s): " + - (null == r ? void 0 : r.join(",")) - ), - this.hls.trigger(E.AUDIO_TRACKS_UPDATED, u); - var d = this.trackId; - if (-1 !== h && -1 === d) this.setAudioTrack(h); - else if (s.length && -1 === d) { - var c, - f = new Error( - "No audio track selected for current audio group-ID(s): " + - (null == (c = this.groupIds) - ? void 0 - : c.join(",")) + - " track count: " + - s.length - ); - this.warn(f.message), - this.hls.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.AUDIO_TRACK_LOAD_ERROR, - fatal: !0, - error: f, - }); - } - } else - this.shouldReloadPlaylist(n) && - this.setAudioTrack(this.trackId); - } - }), - (r.onError = function (e, t) { - !t.fatal && - t.context && - (t.context.type !== Tt || - t.context.id !== this.trackId || - (this.groupIds && - -1 === this.groupIds.indexOf(t.context.groupId)) || - ((this.requestScheduled = -1), this.checkRetry(t))); - }), - (r.setAudioOption = function (e) { - var t = this.hls; - if (((t.config.audioPreference = e), e)) { - var r = this.allAudioTracks; - if (((this.selectDefaultTrack = !1), r.length)) { - var i = this.currentTrack; - if (i && Sr(e, i, Tr)) return i; - var n = Er(e, this.tracksInGroup, Tr); - if (n > -1) { - var s = this.tracksInGroup[n]; - return this.setAudioTrack(n), s; - } - if (i) { - var a = t.loadLevel; - -1 === a && (a = t.firstAutoLevel); - var o = (function (e, t, r, i, n) { - var s = t[i], - a = t.reduce(function (e, t, r) { - var i = t.uri; - return (e[i] || (e[i] = [])).push(r), e; - }, {})[s.uri]; - a.length > 1 && (i = Math.max.apply(Math, a)); - var o = s.videoRange, - l = s.frameRate, - h = s.codecSet.substring(0, 4), - u = _r(t, i, function (t) { - if ( - t.videoRange !== o || - t.frameRate !== l || - t.codecSet.substring(0, 4) !== h - ) - return !1; - var i = t.audioGroups, - s = r.filter(function (e) { - return !i || -1 !== i.indexOf(e.groupId); - }); - return Er(e, s, n) > -1; - }); - return u > -1 - ? u - : _r(t, i, function (t) { - var i = t.audioGroups, - s = r.filter(function (e) { - return ( - !i || -1 !== i.indexOf(e.groupId) - ); - }); - return Er(e, s, n) > -1; - }); - })(e, t.levels, r, a, Tr); - if (-1 === o) return null; - t.nextLoadLevel = o; - } - if (e.channels || e.audioCodec) { - var l = Er(e, r); - if (l > -1) return r[l]; - } - } - } - return null; - }), - (r.setAudioTrack = function (e) { - var t = this.tracksInGroup; - if (e < 0 || e >= t.length) - this.warn("Invalid audio track id: " + e); - else { - this.clearTimer(), (this.selectDefaultTrack = !1); - var r = this.currentTrack, - n = t[e], - s = n.details && !n.details.live; - if ( - !( - (e === this.trackId && n === r && s) || - (this.log( - "Switching to audio-track " + - e + - ' "' + - n.name + - '" lang:' + - n.lang + - " group:" + - n.groupId + - " channels:" + - n.channels - ), - (this.trackId = e), - (this.currentTrack = n), - this.hls.trigger(E.AUDIO_TRACK_SWITCHING, i({}, n)), - s) - ) - ) { - var a = this.switchParams( - n.url, - null == r ? void 0 : r.details, - n.details - ); - this.loadPlaylist(a); - } - } - }), - (r.findTrackId = function (e) { - for ( - var t = this.tracksInGroup, r = 0; - r < t.length; - r++ - ) { - var i = t[r]; - if ( - (!this.selectDefaultTrack || i.default) && - (!e || Sr(e, i, Tr)) - ) - return r; - } - if (e) { - for ( - var n = e.name, - s = e.lang, - a = e.assocLang, - o = e.characteristics, - l = e.audioCodec, - h = e.channels, - u = 0; - u < t.length; - u++ - ) - if ( - Sr( - { - name: n, - lang: s, - assocLang: a, - characteristics: o, - audioCodec: l, - channels: h, - }, - t[u], - Tr - ) - ) - return u; - for (var d = 0; d < t.length; d++) { - var c = t[d]; - if ( - Ln(e.attrs, c.attrs, [ - "LANGUAGE", - "ASSOC-LANGUAGE", - "CHARACTERISTICS", - ]) - ) - return d; - } - for (var f = 0; f < t.length; f++) { - var g = t[f]; - if (Ln(e.attrs, g.attrs, ["LANGUAGE"])) return f; - } - } - return -1; - }), - (r.loadPlaylist = function (t) { - var r = this.currentTrack; - if (this.shouldLoadPlaylist(r) && r) { - e.prototype.loadPlaylist.call(this); - var i = r.id, - n = r.groupId, - s = r.url; - if (t) - try { - s = t.addDirectives(s); - } catch (e) { - this.warn( - "Could not construct new URL with HLS Delivery Directives: " + - e - ); - } - this.log( - "loading audio-track playlist " + - i + - ' "' + - r.name + - '" lang:' + - r.lang + - " group:" + - n - ), - this.clearTimer(), - this.hls.trigger(E.AUDIO_TRACK_LOADING, { - url: s, - id: i, - groupId: n, - deliveryDirectives: t || null, - }); - } - }), - a(t, [ - { - key: "allAudioTracks", - get: function () { - return this.tracks; - }, - }, - { - key: "audioTracks", - get: function () { - return this.tracksInGroup; - }, - }, - { - key: "audioTrack", - get: function () { - return this.trackId; - }, - set: function (e) { - (this.selectDefaultTrack = !1), this.setAudioTrack(e); - }, - }, - ]), - t - ); - })(cr), - wn = (function (e) { - function t(t, r, i) { - var n; - return ( - ((n = - e.call( - this, - t, - r, - i, - "[subtitle-stream-controller]", - Rt - ) || this).currentTrackId = -1), - (n.tracksBuffered = []), - (n.mainDetails = null), - n._registerListeners(), - n - ); - } - l(t, e); - var r = t.prototype; - return ( - (r.onHandlerDestroying = function () { - this._unregisterListeners(), - e.prototype.onHandlerDestroying.call(this), - (this.mainDetails = null); - }), - (r._registerListeners = function () { - var e = this.hls; - e.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.LEVEL_LOADED, this.onLevelLoaded, this), - e.on(E.ERROR, this.onError, this), - e.on( - E.SUBTITLE_TRACKS_UPDATED, - this.onSubtitleTracksUpdated, - this - ), - e.on( - E.SUBTITLE_TRACK_SWITCH, - this.onSubtitleTrackSwitch, - this - ), - e.on( - E.SUBTITLE_TRACK_LOADED, - this.onSubtitleTrackLoaded, - this - ), - e.on( - E.SUBTITLE_FRAG_PROCESSED, - this.onSubtitleFragProcessed, - this - ), - e.on(E.BUFFER_FLUSHING, this.onBufferFlushing, this), - e.on(E.FRAG_BUFFERED, this.onFragBuffered, this); - }), - (r._unregisterListeners = function () { - var e = this.hls; - e.off(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.off(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.off(E.LEVEL_LOADED, this.onLevelLoaded, this), - e.off(E.ERROR, this.onError, this), - e.off( - E.SUBTITLE_TRACKS_UPDATED, - this.onSubtitleTracksUpdated, - this - ), - e.off( - E.SUBTITLE_TRACK_SWITCH, - this.onSubtitleTrackSwitch, - this - ), - e.off( - E.SUBTITLE_TRACK_LOADED, - this.onSubtitleTrackLoaded, - this - ), - e.off( - E.SUBTITLE_FRAG_PROCESSED, - this.onSubtitleFragProcessed, - this - ), - e.off(E.BUFFER_FLUSHING, this.onBufferFlushing, this), - e.off(E.FRAG_BUFFERED, this.onFragBuffered, this); - }), - (r.startLoad = function (e) { - this.stopLoad(), - (this.state = zr), - this.setInterval(500), - (this.nextLoadPosition = - this.startPosition = - this.lastCurrentTime = - e), - this.tick(); - }), - (r.onManifestLoading = function () { - (this.mainDetails = null), - this.fragmentTracker.removeAllFragments(); - }), - (r.onMediaDetaching = function () { - (this.tracksBuffered = []), - e.prototype.onMediaDetaching.call(this); - }), - (r.onLevelLoaded = function (e, t) { - this.mainDetails = t.details; - }), - (r.onSubtitleFragProcessed = function (e, t) { - var r = t.frag, - i = t.success; - if (((this.fragPrevious = r), (this.state = zr), i)) { - var n = this.tracksBuffered[this.currentTrackId]; - if (n) { - for (var s, a = r.start, o = 0; o < n.length; o++) - if (a >= n[o].start && a <= n[o].end) { - s = n[o]; - break; - } - var l = r.start + r.duration; - s - ? (s.end = l) - : ((s = { start: a, end: l }), n.push(s)), - this.fragmentTracker.fragBuffered(r), - this.fragBufferedComplete(r, null); - } - } - }), - (r.onBufferFlushing = function (e, t) { - var r = t.startOffset, - i = t.endOffset; - if (0 === r && i !== Number.POSITIVE_INFINITY) { - var n = i - 1; - if (n <= 0) return; - (t.endOffsetSubtitles = Math.max(0, n)), - this.tracksBuffered.forEach(function (e) { - for (var t = 0; t < e.length; ) - if (e[t].end <= n) e.shift(); - else { - if (!(e[t].start < n)) break; - (e[t].start = n), t++; - } - }), - this.fragmentTracker.removeFragmentsInRange(r, n, Rt); - } - }), - (r.onFragBuffered = function (e, t) { - var r; - this.loadedmetadata || - t.frag.type !== Lt || - (null != (r = this.media) && - r.buffered.length && - (this.loadedmetadata = !0)); - }), - (r.onError = function (e, t) { - var r = t.frag; - (null == r ? void 0 : r.type) === Rt && - (t.details === T.FRAG_GAP && - this.fragmentTracker.fragBuffered(r, !0), - this.fragCurrent && this.fragCurrent.abortRequests(), - this.state !== Yr && (this.state = zr)); - }), - (r.onSubtitleTracksUpdated = function (e, t) { - var r = this, - i = t.subtitleTracks; - this.levels && _n(this.levels, i) - ? (this.levels = i.map(function (e) { - return new qt(e); - })) - : ((this.tracksBuffered = []), - (this.levels = i.map(function (e) { - var t = new qt(e); - return (r.tracksBuffered[t.id] = []), t; - })), - this.fragmentTracker.removeFragmentsInRange( - 0, - Number.POSITIVE_INFINITY, - Rt - ), - (this.fragPrevious = null), - (this.mediaBuffer = null)); - }), - (r.onSubtitleTrackSwitch = function (e, t) { - var r; - if ( - ((this.currentTrackId = t.id), - null != (r = this.levels) && - r.length && - -1 !== this.currentTrackId) - ) { - var i = this.levels[this.currentTrackId]; - null != i && i.details - ? (this.mediaBuffer = this.mediaBufferTimeRanges) - : (this.mediaBuffer = null), - i && this.setInterval(500); - } else this.clearInterval(); - }), - (r.onSubtitleTrackLoaded = function (e, t) { - var r, - i = this.currentTrackId, - n = this.levels, - s = t.details, - a = t.id; - if (n) { - var o = n[a]; - if (!(a >= n.length) && o) { - this.log( - "Subtitle track " + - a + - " loaded [" + - s.startSN + - "," + - s.endSN + - "]" + - (s.lastPartSn - ? "[part-" + - s.lastPartSn + - "-" + - s.lastPartIndex + - "]" - : "") + - ",duration:" + - s.totalduration - ), - (this.mediaBuffer = this.mediaBufferTimeRanges); - var l = 0; - if (s.live || (null != (r = o.details) && r.live)) { - var h = this.mainDetails; - if (s.deltaUpdateFailed || !h) return; - var u, - d = h.fragments[0]; - o.details - ? 0 === - (l = this.alignPlaylists( - s, - o.details, - null == (u = this.levelLastLoaded) - ? void 0 - : u.details - )) && - d && - Jt(s, (l = d.start)) - : s.hasProgramDateTime && h.hasProgramDateTime - ? (Br(s, h), (l = s.fragments[0].start)) - : d && Jt(s, (l = d.start)); - } - (o.details = s), - (this.levelLastLoaded = o), - a === i && - (this.startFragRequested || - (!this.mainDetails && s.live) || - this.setStartPosition(this.mainDetails || s, l), - this.tick(), - s.live && - !this.fragCurrent && - this.media && - this.state === zr && - (lr( - null, - s.fragments, - this.media.currentTime, - 0 - ) || - (this.warn( - "Subtitle playlist not aligned with playback" - ), - (o.details = void 0)))); - } - } else - this.warn( - "Subtitle tracks were reset while loading level " + a - ); - }), - (r._handleFragmentLoadComplete = function (e) { - var t = this, - r = e.frag, - i = e.payload, - n = r.decryptdata, - s = this.hls; - if ( - !this.fragContextChanged(r) && - i && - i.byteLength > 0 && - null != n && - n.key && - n.iv && - "AES-128" === n.method - ) { - var a = performance.now(); - this.decrypter - .decrypt(new Uint8Array(i), n.key.buffer, n.iv.buffer) - .catch(function (e) { - throw ( - (s.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.FRAG_DECRYPT_ERROR, - fatal: !1, - error: e, - reason: e.message, - frag: r, - }), - e) - ); - }) - .then(function (e) { - var t = performance.now(); - s.trigger(E.FRAG_DECRYPTED, { - frag: r, - payload: e, - stats: { tstart: a, tdecrypt: t }, - }); - }) - .catch(function (e) { - t.warn(e.name + ": " + e.message), (t.state = zr); - }); - } - }), - (r.doTick = function () { - if (this.media) { - if (this.state === zr) { - var e = this.currentTrackId, - t = this.levels, - r = null == t ? void 0 : t[e]; - if (!r || !t.length || !r.details) return; - var i = this.config, - n = this.getLoadPosition(), - s = Mr.bufferedInfo( - this.tracksBuffered[this.currentTrackId] || [], - n, - i.maxBufferHole - ), - a = s.end, - o = s.len, - l = this.getFwdBufferInfo(this.media, Lt), - h = r.details; - if ( - o > - this.getMaxBufferLength( - null == l ? void 0 : l.len - ) + - h.levelTargetDuration - ) - return; - var u = h.fragments, - d = u.length, - c = h.edge, - f = null, - g = this.fragPrevious; - if (a < c) { - var p = i.maxFragLookUpTolerance, - m = a > c - p ? 0 : p; - !(f = lr(g, u, Math.max(u[0].start, a), m)) && - g && - g.start < u[0].start && - (f = u[0]); - } else f = u[d - 1]; - if (!f) return; - if ( - "initSegment" !== - (f = this.mapToInitFragWhenRequired(f)).sn - ) { - var v = u[f.sn - h.startSN - 1]; - v && - v.cc === f.cc && - this.fragmentTracker.getState(v) === Rr && - (f = v); - } - this.fragmentTracker.getState(f) === Rr && - this.loadFragment(f, r, a); - } - } else this.state = zr; - }), - (r.getMaxBufferLength = function (t) { - var r = e.prototype.getMaxBufferLength.call(this); - return t ? Math.max(r, t) : r; - }), - (r.loadFragment = function (t, r, i) { - (this.fragCurrent = t), - "initSegment" === t.sn - ? this._loadInitSegment(t, r) - : ((this.startFragRequested = !0), - e.prototype.loadFragment.call(this, t, r, i)); - }), - a(t, [ - { - key: "mediaBufferTimeRanges", - get: function () { - return new Pn( - this.tracksBuffered[this.currentTrackId] || [] - ); - }, - }, - ]), - t - ); - })(ai), - Pn = function (e) { - this.buffered = void 0; - var t = function (t, r, i) { - if ((r >>>= 0) > i - 1) - throw new DOMException( - "Failed to execute '" + - t + - "' on 'TimeRanges': The index provided (" + - r + - ") is greater than the maximum bound (" + - i + - ")" - ); - return e[r][t]; - }; - this.buffered = { - get length() { - return e.length; - }, - end: function (r) { - return t("end", r, e.length); - }, - start: function (r) { - return t("start", r, e.length); - }, - }; - }, - In = (function (e) { - function t(t) { - var r; - return ( - ((r = - e.call(this, t, "[subtitle-track-controller]") || - this).media = null), - (r.tracks = []), - (r.groupIds = null), - (r.tracksInGroup = []), - (r.trackId = -1), - (r.currentTrack = null), - (r.selectDefaultTrack = !0), - (r.queuedDefaultTrack = -1), - (r.asyncPollTrackChange = function () { - return r.pollTrackChange(0); - }), - (r.useTextTrackPolling = !1), - (r.subtitlePollingInterval = -1), - (r._subtitleDisplay = !0), - (r.onTextTracksChanged = function () { - if ( - (r.useTextTrackPolling || - self.clearInterval(r.subtitlePollingInterval), - r.media && r.hls.config.renderTextTracksNatively) - ) { - for ( - var e = null, t = Mt(r.media.textTracks), i = 0; - i < t.length; - i++ - ) - if ("hidden" === t[i].mode) e = t[i]; - else if ("showing" === t[i].mode) { - e = t[i]; - break; - } - var n = r.findTrackForTextTrack(e); - r.subtitleTrack !== n && r.setSubtitleTrack(n); - } - }), - r.registerListeners(), - r - ); - } - l(t, e); - var r = t.prototype; - return ( - (r.destroy = function () { - this.unregisterListeners(), - (this.tracks.length = 0), - (this.tracksInGroup.length = 0), - (this.currentTrack = null), - (this.onTextTracksChanged = this.asyncPollTrackChange = - null), - e.prototype.destroy.call(this); - }), - (r.registerListeners = function () { - var e = this.hls; - e.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.on(E.LEVEL_LOADING, this.onLevelLoading, this), - e.on(E.LEVEL_SWITCHING, this.onLevelSwitching, this), - e.on( - E.SUBTITLE_TRACK_LOADED, - this.onSubtitleTrackLoaded, - this - ), - e.on(E.ERROR, this.onError, this); - }), - (r.unregisterListeners = function () { - var e = this.hls; - e.off(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.off(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.off(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.off(E.LEVEL_LOADING, this.onLevelLoading, this), - e.off(E.LEVEL_SWITCHING, this.onLevelSwitching, this), - e.off( - E.SUBTITLE_TRACK_LOADED, - this.onSubtitleTrackLoaded, - this - ), - e.off(E.ERROR, this.onError, this); - }), - (r.onMediaAttached = function (e, t) { - (this.media = t.media), - this.media && - (this.queuedDefaultTrack > -1 && - ((this.subtitleTrack = this.queuedDefaultTrack), - (this.queuedDefaultTrack = -1)), - (this.useTextTrackPolling = !( - this.media.textTracks && - "onchange" in this.media.textTracks - )), - this.useTextTrackPolling - ? this.pollTrackChange(500) - : this.media.textTracks.addEventListener( - "change", - this.asyncPollTrackChange - )); - }), - (r.pollTrackChange = function (e) { - self.clearInterval(this.subtitlePollingInterval), - (this.subtitlePollingInterval = self.setInterval( - this.onTextTracksChanged, - e - )); - }), - (r.onMediaDetaching = function () { - this.media && - (self.clearInterval(this.subtitlePollingInterval), - this.useTextTrackPolling || - this.media.textTracks.removeEventListener( - "change", - this.asyncPollTrackChange - ), - this.trackId > -1 && - (this.queuedDefaultTrack = this.trackId), - Mt(this.media.textTracks).forEach(function (e) { - kt(e); - }), - (this.subtitleTrack = -1), - (this.media = null)); - }), - (r.onManifestLoading = function () { - (this.tracks = []), - (this.groupIds = null), - (this.tracksInGroup = []), - (this.trackId = -1), - (this.currentTrack = null), - (this.selectDefaultTrack = !0); - }), - (r.onManifestParsed = function (e, t) { - this.tracks = t.subtitleTracks; - }), - (r.onSubtitleTrackLoaded = function (e, t) { - var r = t.id, - i = t.groupId, - n = t.details, - s = this.tracksInGroup[r]; - if (s && s.groupId === i) { - var a = s.details; - (s.details = t.details), - this.log( - "Subtitle track " + - r + - ' "' + - s.name + - '" lang:' + - s.lang + - " group:" + - i + - " loaded [" + - n.startSN + - "-" + - n.endSN + - "]" - ), - r === this.trackId && this.playlistLoaded(r, t, a); - } else - this.warn( - "Subtitle track with id:" + - r + - " and group:" + - i + - " not found in active group " + - (null == s ? void 0 : s.groupId) - ); - }), - (r.onLevelLoading = function (e, t) { - this.switchLevel(t.level); - }), - (r.onLevelSwitching = function (e, t) { - this.switchLevel(t.level); - }), - (r.switchLevel = function (e) { - var t = this.hls.levels[e]; - if (t) { - var r = t.subtitleGroups || null, - i = this.groupIds, - n = this.currentTrack; - if ( - !r || - (null == i ? void 0 : i.length) !== - (null == r ? void 0 : r.length) || - (null != r && - r.some(function (e) { - return -1 === (null == i ? void 0 : i.indexOf(e)); - })) - ) { - (this.groupIds = r), - (this.trackId = -1), - (this.currentTrack = null); - var s = this.tracks.filter(function (e) { - return !r || -1 !== r.indexOf(e.groupId); - }); - if (s.length) - this.selectDefaultTrack && - !s.some(function (e) { - return e.default; - }) && - (this.selectDefaultTrack = !1), - s.forEach(function (e, t) { - e.id = t; - }); - else if (!n && !this.tracksInGroup.length) return; - this.tracksInGroup = s; - var a = this.hls.config.subtitlePreference; - if (!n && a) { - this.selectDefaultTrack = !1; - var o = Er(a, s); - if (o > -1) n = s[o]; - else { - var l = Er(a, this.tracks); - n = this.tracks[l]; - } - } - var h = this.findTrackId(n); - -1 === h && n && (h = this.findTrackId(null)); - var u = { subtitleTracks: s }; - this.log( - "Updating subtitle tracks, " + - s.length + - ' track(s) found in "' + - (null == r ? void 0 : r.join(",")) + - '" group-id' - ), - this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED, u), - -1 !== h && - -1 === this.trackId && - this.setSubtitleTrack(h); - } else - this.shouldReloadPlaylist(n) && - this.setSubtitleTrack(this.trackId); - } - }), - (r.findTrackId = function (e) { - for ( - var t = this.tracksInGroup, - r = this.selectDefaultTrack, - i = 0; - i < t.length; - i++ - ) { - var n = t[i]; - if ((!r || n.default) && (r || e) && (!e || Sr(n, e))) - return i; - } - if (e) { - for (var s = 0; s < t.length; s++) { - var a = t[s]; - if ( - Ln(e.attrs, a.attrs, [ - "LANGUAGE", - "ASSOC-LANGUAGE", - "CHARACTERISTICS", - ]) - ) - return s; - } - for (var o = 0; o < t.length; o++) { - var l = t[o]; - if (Ln(e.attrs, l.attrs, ["LANGUAGE"])) return o; - } - } - return -1; - }), - (r.findTrackForTextTrack = function (e) { - if (e) - for ( - var t = this.tracksInGroup, r = 0; - r < t.length; - r++ - ) - if (bn(t[r], e)) return r; - return -1; - }), - (r.onError = function (e, t) { - !t.fatal && - t.context && - (t.context.type !== _t || - t.context.id !== this.trackId || - (this.groupIds && - -1 === this.groupIds.indexOf(t.context.groupId)) || - this.checkRetry(t)); - }), - (r.setSubtitleOption = function (e) { - if (((this.hls.config.subtitlePreference = e), e)) { - var t = this.allSubtitleTracks; - if (((this.selectDefaultTrack = !1), t.length)) { - var r = this.currentTrack; - if (r && Sr(e, r)) return r; - var i = Er(e, this.tracksInGroup); - if (i > -1) { - var n = this.tracksInGroup[i]; - return this.setSubtitleTrack(i), n; - } - if (r) return null; - var s = Er(e, t); - if (s > -1) return t[s]; - } - } - return null; - }), - (r.loadPlaylist = function (t) { - e.prototype.loadPlaylist.call(this); - var r = this.currentTrack; - if (this.shouldLoadPlaylist(r) && r) { - var i = r.id, - n = r.groupId, - s = r.url; - if (t) - try { - s = t.addDirectives(s); - } catch (e) { - this.warn( - "Could not construct new URL with HLS Delivery Directives: " + - e - ); - } - this.log("Loading subtitle playlist for id " + i), - this.hls.trigger(E.SUBTITLE_TRACK_LOADING, { - url: s, - id: i, - groupId: n, - deliveryDirectives: t || null, - }); - } - }), - (r.toggleTrackModes = function () { - var e = this.media; - if (e) { - var t, - r = Mt(e.textTracks), - i = this.currentTrack; - if ( - (i && - ((t = r.filter(function (e) { - return bn(i, e); - })[0]) || - this.warn( - 'Unable to find subtitle TextTrack with name "' + - i.name + - '" and language "' + - i.lang + - '"' - )), - [].slice.call(r).forEach(function (e) { - "disabled" !== e.mode && - e !== t && - (e.mode = "disabled"); - }), - t) - ) { - var n = this.subtitleDisplay ? "showing" : "hidden"; - t.mode !== n && (t.mode = n); - } - } - }), - (r.setSubtitleTrack = function (e) { - var t = this.tracksInGroup; - if (this.media) - if (e < -1 || e >= t.length || !m(e)) - this.warn("Invalid subtitle track id: " + e); - else { - this.clearTimer(), (this.selectDefaultTrack = !1); - var r = this.currentTrack, - i = t[e] || null; - if ( - ((this.trackId = e), - (this.currentTrack = i), - this.toggleTrackModes(), - i) - ) { - var n = !!i.details && !i.details.live; - if (e !== this.trackId || i !== r || !n) { - this.log( - "Switching to subtitle-track " + - e + - (i - ? ' "' + - i.name + - '" lang:' + - i.lang + - " group:" + - i.groupId - : "") - ); - var s = i.id, - a = i.groupId, - o = void 0 === a ? "" : a, - l = i.name, - h = i.type, - u = i.url; - this.hls.trigger(E.SUBTITLE_TRACK_SWITCH, { - id: s, - groupId: o, - name: l, - type: h, - url: u, - }); - var d = this.switchParams( - i.url, - null == r ? void 0 : r.details, - i.details - ); - this.loadPlaylist(d); - } - } else - this.hls.trigger(E.SUBTITLE_TRACK_SWITCH, { - id: e, - }); - } - else this.queuedDefaultTrack = e; - }), - a(t, [ - { - key: "subtitleDisplay", - get: function () { - return this._subtitleDisplay; - }, - set: function (e) { - (this._subtitleDisplay = e), - this.trackId > -1 && this.toggleTrackModes(); - }, - }, - { - key: "allSubtitleTracks", - get: function () { - return this.tracks; - }, - }, - { - key: "subtitleTracks", - get: function () { - return this.tracksInGroup; - }, - }, - { - key: "subtitleTrack", - get: function () { - return this.trackId; - }, - set: function (e) { - (this.selectDefaultTrack = !1), - this.setSubtitleTrack(e); - }, - }, - ]), - t - ); - })(cr), - Cn = (function () { - function e(e) { - (this.buffers = void 0), - (this.queues = { video: [], audio: [], audiovideo: [] }), - (this.buffers = e); - } - var t = e.prototype; - return ( - (t.append = function (e, t, r) { - var i = this.queues[t]; - i.push(e), 1 !== i.length || r || this.executeNext(t); - }), - (t.insertAbort = function (e, t) { - this.queues[t].unshift(e), this.executeNext(t); - }), - (t.appendBlocker = function (e) { - var t, - r = new Promise(function (e) { - t = e; - }), - i = { - execute: t, - onStart: function () {}, - onComplete: function () {}, - onError: function () {}, - }; - return this.append(i, e), r; - }), - (t.executeNext = function (e) { - var t = this.queues[e]; - if (t.length) { - var r = t[0]; - try { - r.execute(); - } catch (t) { - A.warn( - '[buffer-operation-queue]: Exception executing "' + - e + - '" SourceBuffer operation: ' + - t - ), - r.onError(t); - var i = this.buffers[e]; - (null != i && i.updating) || - this.shiftAndExecuteNext(e); - } - } - }), - (t.shiftAndExecuteNext = function (e) { - this.queues[e].shift(), this.executeNext(e); - }), - (t.current = function (e) { - return this.queues[e][0]; - }), - e - ); - })(), - kn = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/, - Dn = (function () { - function e(e) { - var t = this; - (this.details = null), - (this._objectUrl = null), - (this.operationQueue = void 0), - (this.listeners = void 0), - (this.hls = void 0), - (this.bufferCodecEventsExpected = 0), - (this._bufferCodecEventsTotal = 0), - (this.media = null), - (this.mediaSource = null), - (this.lastMpegAudioChunk = null), - (this.appendSource = void 0), - (this.appendErrors = { - audio: 0, - video: 0, - audiovideo: 0, - }), - (this.tracks = {}), - (this.pendingTracks = {}), - (this.sourceBuffer = void 0), - (this.log = void 0), - (this.warn = void 0), - (this.error = void 0), - (this._onEndStreaming = function (e) { - t.hls && t.hls.pauseBuffering(); - }), - (this._onStartStreaming = function (e) { - t.hls && t.hls.resumeBuffering(); - }), - (this._onMediaSourceOpen = function () { - var e = t.media, - r = t.mediaSource; - t.log("Media source opened"), - e && - (e.removeEventListener( - "emptied", - t._onMediaEmptied - ), - t.updateMediaElementDuration(), - t.hls.trigger(E.MEDIA_ATTACHED, { - media: e, - mediaSource: r, - })), - r && - r.removeEventListener( - "sourceopen", - t._onMediaSourceOpen - ), - t.checkPendingTracks(); - }), - (this._onMediaSourceClose = function () { - t.log("Media source closed"); - }), - (this._onMediaSourceEnded = function () { - t.log("Media source ended"); - }), - (this._onMediaEmptied = function () { - var e = t.mediaSrc, - r = t._objectUrl; - e !== r && - A.error( - "Media element src was set while attaching MediaSource (" + - r + - " > " + - e + - ")" - ); - }), - (this.hls = e); - var r, - i = "[buffer-controller]"; - (this.appendSource = - ((r = ze(e.config.preferManagedMediaSource)), - "undefined" != typeof self && - r === self.ManagedMediaSource)), - (this.log = A.log.bind(A, i)), - (this.warn = A.warn.bind(A, i)), - (this.error = A.error.bind(A, i)), - this._initSourceBuffer(), - this.registerListeners(); - } - var t = e.prototype; - return ( - (t.hasSourceTypes = function () { - return ( - this.getSourceBufferTypes().length > 0 || - Object.keys(this.pendingTracks).length > 0 - ); - }), - (t.destroy = function () { - this.unregisterListeners(), - (this.details = null), - (this.lastMpegAudioChunk = null), - (this.hls = null); - }), - (t.registerListeners = function () { - var e = this.hls; - e.on(E.MEDIA_ATTACHING, this.onMediaAttaching, this), - e.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.on(E.BUFFER_RESET, this.onBufferReset, this), - e.on(E.BUFFER_APPENDING, this.onBufferAppending, this), - e.on(E.BUFFER_CODECS, this.onBufferCodecs, this), - e.on(E.BUFFER_EOS, this.onBufferEos, this), - e.on(E.BUFFER_FLUSHING, this.onBufferFlushing, this), - e.on(E.LEVEL_UPDATED, this.onLevelUpdated, this), - e.on(E.FRAG_PARSED, this.onFragParsed, this), - e.on(E.FRAG_CHANGED, this.onFragChanged, this); - }), - (t.unregisterListeners = function () { - var e = this.hls; - e.off(E.MEDIA_ATTACHING, this.onMediaAttaching, this), - e.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.off(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.off(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.off(E.BUFFER_RESET, this.onBufferReset, this), - e.off(E.BUFFER_APPENDING, this.onBufferAppending, this), - e.off(E.BUFFER_CODECS, this.onBufferCodecs, this), - e.off(E.BUFFER_EOS, this.onBufferEos, this), - e.off(E.BUFFER_FLUSHING, this.onBufferFlushing, this), - e.off(E.LEVEL_UPDATED, this.onLevelUpdated, this), - e.off(E.FRAG_PARSED, this.onFragParsed, this), - e.off(E.FRAG_CHANGED, this.onFragChanged, this); - }), - (t._initSourceBuffer = function () { - (this.sourceBuffer = {}), - (this.operationQueue = new Cn(this.sourceBuffer)), - (this.listeners = { - audio: [], - video: [], - audiovideo: [], - }), - (this.appendErrors = { - audio: 0, - video: 0, - audiovideo: 0, - }), - (this.lastMpegAudioChunk = null); - }), - (t.onManifestLoading = function () { - (this.bufferCodecEventsExpected = - this._bufferCodecEventsTotal = - 0), - (this.details = null); - }), - (t.onManifestParsed = function (e, t) { - var r = 2; - ((t.audio && !t.video) || !t.altAudio) && (r = 1), - (this.bufferCodecEventsExpected = - this._bufferCodecEventsTotal = - r), - this.log( - this.bufferCodecEventsExpected + - " bufferCodec event(s) expected" - ); - }), - (t.onMediaAttaching = function (e, t) { - var r = (this.media = t.media), - i = ze(this.appendSource); - if (r && i) { - var n, - s = (this.mediaSource = new i()); - this.log( - "created media source: " + - (null == (n = s.constructor) ? void 0 : n.name) - ), - s.addEventListener( - "sourceopen", - this._onMediaSourceOpen - ), - s.addEventListener( - "sourceended", - this._onMediaSourceEnded - ), - s.addEventListener( - "sourceclose", - this._onMediaSourceClose - ), - this.appendSource && - (s.addEventListener( - "startstreaming", - this._onStartStreaming - ), - s.addEventListener( - "endstreaming", - this._onEndStreaming - )); - var a = (this._objectUrl = self.URL.createObjectURL(s)); - if (this.appendSource) - try { - r.removeAttribute("src"); - var o = self.ManagedMediaSource; - (r.disableRemotePlayback = - r.disableRemotePlayback || (o && s instanceof o)), - Mn(r), - (function (e, t) { - var r = self.document.createElement("source"); - (r.type = "video/mp4"), - (r.src = t), - e.appendChild(r); - })(r, a), - r.load(); - } catch (e) { - r.src = a; - } - else r.src = a; - r.addEventListener("emptied", this._onMediaEmptied); - } - }), - (t.onMediaDetaching = function () { - var e = this.media, - t = this.mediaSource, - r = this._objectUrl; - if (t) { - if ( - (this.log("media source detaching"), - "open" === t.readyState) - ) - try { - t.endOfStream(); - } catch (e) { - this.warn( - "onMediaDetaching: " + - e.message + - " while calling endOfStream" - ); - } - this.onBufferReset(), - t.removeEventListener( - "sourceopen", - this._onMediaSourceOpen - ), - t.removeEventListener( - "sourceended", - this._onMediaSourceEnded - ), - t.removeEventListener( - "sourceclose", - this._onMediaSourceClose - ), - this.appendSource && - (t.removeEventListener( - "startstreaming", - this._onStartStreaming - ), - t.removeEventListener( - "endstreaming", - this._onEndStreaming - )), - e && - (e.removeEventListener( - "emptied", - this._onMediaEmptied - ), - r && self.URL.revokeObjectURL(r), - this.mediaSrc === r - ? (e.removeAttribute("src"), - this.appendSource && Mn(e), - e.load()) - : this.warn( - "media|source.src was changed by a third party - skip cleanup" - )), - (this.mediaSource = null), - (this.media = null), - (this._objectUrl = null), - (this.bufferCodecEventsExpected = - this._bufferCodecEventsTotal), - (this.pendingTracks = {}), - (this.tracks = {}); - } - this.hls.trigger(E.MEDIA_DETACHED, void 0); - }), - (t.onBufferReset = function () { - var e = this; - this.getSourceBufferTypes().forEach(function (t) { - e.resetBuffer(t); - }), - this._initSourceBuffer(); - }), - (t.resetBuffer = function (e) { - var t = this.sourceBuffer[e]; - try { - var r; - t && - (this.removeBufferListeners(e), - (this.sourceBuffer[e] = void 0), - null != (r = this.mediaSource) && - r.sourceBuffers.length && - this.mediaSource.removeSourceBuffer(t)); - } catch (t) { - this.warn("onBufferReset " + e, t); - } - }), - (t.onBufferCodecs = function (e, t) { - var r = this, - i = this.getSourceBufferTypes().length, - n = Object.keys(t); - if ( - (n.forEach(function (e) { - if (i) { - var n = r.tracks[e]; - if (n && "function" == typeof n.buffer.changeType) { - var s, - a = t[e], - o = a.id, - l = a.codec, - h = a.levelCodec, - u = a.container, - d = a.metadata, - c = st(n.codec, n.levelCodec), - f = null == c ? void 0 : c.replace(kn, "$1"), - g = st(l, h), - p = - null == (s = g) - ? void 0 - : s.replace(kn, "$1"); - if (g && f !== p) { - "audio" === e.slice(0, 5) && - (g = nt(g, r.appendSource)); - var m = u + ";codecs=" + g; - r.appendChangeType(e, m), - r.log("switching codec " + c + " to " + g), - (r.tracks[e] = { - buffer: n.buffer, - codec: l, - container: u, - levelCodec: h, - metadata: d, - id: o, - }); - } - } - } else r.pendingTracks[e] = t[e]; - }), - !i) - ) { - var s = Math.max(this.bufferCodecEventsExpected - 1, 0); - this.bufferCodecEventsExpected !== s && - (this.log( - s + " bufferCodec event(s) expected " + n.join(",") - ), - (this.bufferCodecEventsExpected = s)), - this.mediaSource && - "open" === this.mediaSource.readyState && - this.checkPendingTracks(); - } - }), - (t.appendChangeType = function (e, t) { - var r = this, - i = this.operationQueue, - n = { - execute: function () { - var n = r.sourceBuffer[e]; - n && - (r.log( - "changing " + e + " sourceBuffer type to " + t - ), - n.changeType(t)), - i.shiftAndExecuteNext(e); - }, - onStart: function () {}, - onComplete: function () {}, - onError: function (t) { - r.warn( - "Failed to change " + e + " SourceBuffer type", - t - ); - }, - }; - i.append(n, e, !!this.pendingTracks[e]); - }), - (t.onBufferAppending = function (e, t) { - var r = this, - i = this.hls, - n = this.operationQueue, - s = this.tracks, - a = t.data, - o = t.type, - l = t.frag, - h = t.part, - u = t.chunkMeta, - d = u.buffering[o], - c = self.performance.now(); - d.start = c; - var f = l.stats.buffering, - g = h ? h.stats.buffering : null; - 0 === f.start && (f.start = c), - g && 0 === g.start && (g.start = c); - var p = s.audio, - m = !1; - "audio" === o && - "audio/mpeg" === (null == p ? void 0 : p.container) && - ((m = - !this.lastMpegAudioChunk || - 1 === u.id || - this.lastMpegAudioChunk.sn !== u.sn), - (this.lastMpegAudioChunk = u)); - var v = l.start, - y = { - execute: function () { - if ( - ((d.executeStart = self.performance.now()), m) - ) { - var e = r.sourceBuffer[o]; - if (e) { - var t = v - e.timestampOffset; - Math.abs(t) >= 0.1 && - (r.log( - "Updating audio SourceBuffer timestampOffset to " + - v + - " (delta: " + - t + - ") sn: " + - l.sn + - ")" - ), - (e.timestampOffset = v)); - } - } - r.appendExecutor(a, o); - }, - onStart: function () {}, - onComplete: function () { - var e = self.performance.now(); - (d.executeEnd = d.end = e), - 0 === f.first && (f.first = e), - g && 0 === g.first && (g.first = e); - var t = r.sourceBuffer, - i = {}; - for (var n in t) i[n] = Mr.getBuffered(t[n]); - (r.appendErrors[o] = 0), - "audio" === o || "video" === o - ? (r.appendErrors.audiovideo = 0) - : ((r.appendErrors.audio = 0), - (r.appendErrors.video = 0)), - r.hls.trigger(E.BUFFER_APPENDED, { - type: o, - frag: l, - part: h, - chunkMeta: u, - parent: l.type, - timeRanges: i, - }); - }, - onError: function (e) { - var t = { - type: S.MEDIA_ERROR, - parent: l.type, - details: T.BUFFER_APPEND_ERROR, - sourceBufferName: o, - frag: l, - part: h, - chunkMeta: u, - error: e, - err: e, - fatal: !1, - }; - if (e.code === DOMException.QUOTA_EXCEEDED_ERR) - t.details = T.BUFFER_FULL_ERROR; - else { - var n = ++r.appendErrors[o]; - (t.details = T.BUFFER_APPEND_ERROR), - r.warn( - "Failed " + - n + - "/" + - i.config.appendErrorMaxRetry + - ' times to append segment in "' + - o + - '" sourceBuffer' - ), - n >= i.config.appendErrorMaxRetry && - (t.fatal = !0); - } - i.trigger(E.ERROR, t); - }, - }; - n.append(y, o, !!this.pendingTracks[o]); - }), - (t.onBufferFlushing = function (e, t) { - var r = this, - i = this.operationQueue, - n = function (e) { - return { - execute: r.removeExecutor.bind( - r, - e, - t.startOffset, - t.endOffset - ), - onStart: function () {}, - onComplete: function () { - r.hls.trigger(E.BUFFER_FLUSHED, { type: e }); - }, - onError: function (t) { - r.warn( - "Failed to remove from " + e + " SourceBuffer", - t - ); - }, - }; - }; - t.type - ? i.append(n(t.type), t.type) - : this.getSourceBufferTypes().forEach(function (e) { - i.append(n(e), e); - }); - }), - (t.onFragParsed = function (e, t) { - var r = this, - i = t.frag, - n = t.part, - s = [], - a = n ? n.elementaryStreams : i.elementaryStreams; - a[O] - ? s.push("audiovideo") - : (a[M] && s.push("audio"), a[x] && s.push("video")), - 0 === s.length && - this.warn( - "Fragments must have at least one ElementaryStreamType set. type: " + - i.type + - " level: " + - i.level + - " sn: " + - i.sn - ), - this.blockBuffers(function () { - var e = self.performance.now(); - (i.stats.buffering.end = e), - n && (n.stats.buffering.end = e); - var t = n ? n.stats : i.stats; - r.hls.trigger(E.FRAG_BUFFERED, { - frag: i, - part: n, - stats: t, - id: i.type, - }); - }, s); - }), - (t.onFragChanged = function (e, t) { - this.trimBuffers(); - }), - (t.onBufferEos = function (e, t) { - var r = this; - this.getSourceBufferTypes().reduce(function (e, i) { - var n = r.sourceBuffer[i]; - return ( - !n || - (t.type && t.type !== i) || - ((n.ending = !0), - n.ended || - ((n.ended = !0), - r.log(i + " sourceBuffer now EOS"))), - e && !(n && !n.ended) - ); - }, !0) && - (this.log("Queueing mediaSource.endOfStream()"), - this.blockBuffers(function () { - r.getSourceBufferTypes().forEach(function (e) { - var t = r.sourceBuffer[e]; - t && (t.ending = !1); - }); - var e = r.mediaSource; - e && "open" === e.readyState - ? (r.log("Calling mediaSource.endOfStream()"), - e.endOfStream()) - : e && - r.log( - "Could not call mediaSource.endOfStream(). mediaSource.readyState: " + - e.readyState - ); - })); - }), - (t.onLevelUpdated = function (e, t) { - var r = t.details; - r.fragments.length && - ((this.details = r), - this.getSourceBufferTypes().length - ? this.blockBuffers( - this.updateMediaElementDuration.bind(this) - ) - : this.updateMediaElementDuration()); - }), - (t.trimBuffers = function () { - var e = this.hls, - t = this.details, - r = this.media; - if ( - r && - null !== t && - this.getSourceBufferTypes().length - ) { - var i = e.config, - n = r.currentTime, - s = t.levelTargetDuration, - a = - t.live && null !== i.liveBackBufferLength - ? i.liveBackBufferLength - : i.backBufferLength; - if (m(a) && a > 0) { - var o = Math.max(a, s), - l = Math.floor(n / s) * s - o; - this.flushBackBuffer(n, s, l); - } - if ( - m(i.frontBufferFlushThreshold) && - i.frontBufferFlushThreshold > 0 - ) { - var h = Math.max( - i.maxBufferLength, - i.frontBufferFlushThreshold - ), - u = Math.max(h, s), - d = Math.floor(n / s) * s + u; - this.flushFrontBuffer(n, s, d); - } - } - }), - (t.flushBackBuffer = function (e, t, r) { - var i = this, - n = this.details, - s = this.sourceBuffer; - this.getSourceBufferTypes().forEach(function (a) { - var o = s[a]; - if (o) { - var l = Mr.getBuffered(o); - if (l.length > 0 && r > l.start(0)) { - if ( - (i.hls.trigger(E.BACK_BUFFER_REACHED, { - bufferEnd: r, - }), - null != n && n.live) - ) - i.hls.trigger(E.LIVE_BACK_BUFFER_REACHED, { - bufferEnd: r, - }); - else if (o.ended && l.end(l.length - 1) - e < 2 * t) - return void i.log( - "Cannot flush " + - a + - " back buffer while SourceBuffer is in ended state" - ); - i.hls.trigger(E.BUFFER_FLUSHING, { - startOffset: 0, - endOffset: r, - type: a, - }); - } - } - }); - }), - (t.flushFrontBuffer = function (e, t, r) { - var i = this, - n = this.sourceBuffer; - this.getSourceBufferTypes().forEach(function (s) { - var a = n[s]; - if (a) { - var o = Mr.getBuffered(a), - l = o.length; - if (l < 2) return; - var h = o.start(l - 1), - u = o.end(l - 1); - if (r > h || (e >= h && e <= u)) return; - if (a.ended && e - u < 2 * t) - return void i.log( - "Cannot flush " + - s + - " front buffer while SourceBuffer is in ended state" - ); - i.hls.trigger(E.BUFFER_FLUSHING, { - startOffset: h, - endOffset: 1 / 0, - type: s, - }); - } - }); - }), - (t.updateMediaElementDuration = function () { - if ( - this.details && - this.media && - this.mediaSource && - "open" === this.mediaSource.readyState - ) { - var e = this.details, - t = this.hls, - r = this.media, - i = this.mediaSource, - n = e.fragments[0].start + e.totalduration, - s = r.duration, - a = m(i.duration) ? i.duration : 0; - e.live && t.config.liveDurationInfinity - ? ((i.duration = 1 / 0), this.updateSeekableRange(e)) - : ((n > a && n > s) || !m(s)) && - (this.log( - "Updating Media Source duration to " + - n.toFixed(3) - ), - (i.duration = n)); - } - }), - (t.updateSeekableRange = function (e) { - var t = this.mediaSource, - r = e.fragments; - if ( - r.length && - e.live && - null != t && - t.setLiveSeekableRange - ) { - var i = Math.max(0, r[0].start), - n = Math.max(i, i + e.totalduration); - this.log( - "Media Source duration is set to " + - t.duration + - ". Setting seekable range to " + - i + - "-" + - n + - "." - ), - t.setLiveSeekableRange(i, n); - } - }), - (t.checkPendingTracks = function () { - var e = this.bufferCodecEventsExpected, - t = this.operationQueue, - r = this.pendingTracks, - i = Object.keys(r).length; - if (i && (!e || 2 === i || "audiovideo" in r)) { - this.createSourceBuffers(r), (this.pendingTracks = {}); - var n = this.getSourceBufferTypes(); - if (n.length) - this.hls.trigger(E.BUFFER_CREATED, { - tracks: this.tracks, - }), - n.forEach(function (e) { - t.executeNext(e); - }); - else { - var s = new Error( - "could not create source buffer for media codec(s)" - ); - this.hls.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.BUFFER_INCOMPATIBLE_CODECS_ERROR, - fatal: !0, - error: s, - reason: s.message, - }); - } - } - }), - (t.createSourceBuffers = function (e) { - var t = this, - r = this.sourceBuffer, - i = this.mediaSource; - if (!i) - throw Error( - "createSourceBuffers called when mediaSource was null" - ); - var n = function (n) { - if (!r[n]) { - var s, - a = e[n]; - if (!a) - throw Error( - "source buffer exists for track " + - n + - ", however track does not" - ); - var o = - -1 === - (null == (s = a.levelCodec) - ? void 0 - : s.indexOf(",")) - ? a.levelCodec - : a.codec; - o && - "audio" === n.slice(0, 5) && - (o = nt(o, t.appendSource)); - var l = a.container + ";codecs=" + o; - t.log("creating sourceBuffer(" + l + ")"); - try { - var h = (r[n] = i.addSourceBuffer(l)), - u = n; - t.addBufferListener( - u, - "updatestart", - t._onSBUpdateStart - ), - t.addBufferListener( - u, - "updateend", - t._onSBUpdateEnd - ), - t.addBufferListener( - u, - "error", - t._onSBUpdateError - ), - t.appendSource && - t.addBufferListener( - u, - "bufferedchange", - function (e, r) { - var i = r.removedRanges; - null != i && - i.length && - t.hls.trigger(E.BUFFER_FLUSHED, { - type: n, - }); - } - ), - (t.tracks[n] = { - buffer: h, - codec: o, - container: a.container, - levelCodec: a.levelCodec, - metadata: a.metadata, - id: a.id, - }); - } catch (e) { - t.error( - "error while trying to add sourceBuffer: " + - e.message - ), - t.hls.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.BUFFER_ADD_CODEC_ERROR, - fatal: !1, - error: e, - sourceBufferName: n, - mimeType: l, - }); - } - } - }; - for (var s in e) n(s); - }), - (t._onSBUpdateStart = function (e) { - this.operationQueue.current(e).onStart(); - }), - (t._onSBUpdateEnd = function (e) { - var t; - if ( - "closed" !== - (null == (t = this.mediaSource) ? void 0 : t.readyState) - ) { - var r = this.operationQueue; - r.current(e).onComplete(), r.shiftAndExecuteNext(e); - } else this.resetBuffer(e); - }), - (t._onSBUpdateError = function (e, t) { - var r, - i = new Error( - e + - " SourceBuffer error. MediaSource readyState: " + - (null == (r = this.mediaSource) - ? void 0 - : r.readyState) - ); - this.error("" + i, t), - this.hls.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.BUFFER_APPENDING_ERROR, - sourceBufferName: e, - error: i, - fatal: !1, - }); - var n = this.operationQueue.current(e); - n && n.onError(i); - }), - (t.removeExecutor = function (e, t, r) { - var i = this.media, - n = this.mediaSource, - s = this.operationQueue, - a = this.sourceBuffer[e]; - if (!i || !n || !a) - return ( - this.warn( - "Attempting to remove from the " + - e + - " SourceBuffer, but it does not exist" - ), - void s.shiftAndExecuteNext(e) - ); - var o = m(i.duration) ? i.duration : 1 / 0, - l = m(n.duration) ? n.duration : 1 / 0, - h = Math.max(0, t), - u = Math.min(r, o, l); - u > h && (!a.ending || a.ended) - ? ((a.ended = !1), - this.log( - "Removing [" + - h + - "," + - u + - "] from the " + - e + - " SourceBuffer" - ), - a.remove(h, u)) - : s.shiftAndExecuteNext(e); - }), - (t.appendExecutor = function (e, t) { - var r = this.sourceBuffer[t]; - if (r) (r.ended = !1), r.appendBuffer(e); - else if (!this.pendingTracks[t]) - throw new Error( - "Attempting to append to the " + - t + - " SourceBuffer, but it does not exist" - ); - }), - (t.blockBuffers = function (e, t) { - var r = this; - if ( - (void 0 === t && (t = this.getSourceBufferTypes()), - !t.length) - ) - return ( - this.log( - "Blocking operation requested, but no SourceBuffers exist" - ), - void Promise.resolve().then(e) - ); - var i = this.operationQueue, - n = t.map(function (e) { - return i.appendBlocker(e); - }); - Promise.all(n).then(function () { - e(), - t.forEach(function (e) { - var t = r.sourceBuffer[e]; - (null != t && t.updating) || - i.shiftAndExecuteNext(e); - }); - }); - }), - (t.getSourceBufferTypes = function () { - return Object.keys(this.sourceBuffer); - }), - (t.addBufferListener = function (e, t, r) { - var i = this.sourceBuffer[e]; - if (i) { - var n = r.bind(this, e); - this.listeners[e].push({ event: t, listener: n }), - i.addEventListener(t, n); - } - }), - (t.removeBufferListeners = function (e) { - var t = this.sourceBuffer[e]; - t && - this.listeners[e].forEach(function (e) { - t.removeEventListener(e.event, e.listener); - }); - }), - a(e, [ - { - key: "mediaSrc", - get: function () { - var e, - t = - (null == (e = this.media) - ? void 0 - : e.firstChild) || this.media; - return null == t ? void 0 : t.src; - }, - }, - ]), - e - ); - })(); - function Mn(e) { - var t = e.querySelectorAll("source"); - [].slice.call(t).forEach(function (t) { - e.removeChild(t); - }); - } - var xn = { - 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, - }, - On = function (e) { - return String.fromCharCode(xn[e] || e); - }, - Fn = 15, - Nn = 100, - Bn = { - 17: 1, - 18: 3, - 21: 5, - 22: 7, - 23: 9, - 16: 11, - 19: 12, - 20: 14, - }, - Un = { 17: 2, 18: 4, 21: 6, 22: 8, 23: 10, 19: 13, 20: 15 }, - Gn = { - 25: 1, - 26: 3, - 29: 5, - 30: 7, - 31: 9, - 24: 11, - 27: 12, - 28: 14, - }, - Hn = { 25: 2, 26: 4, 29: 6, 30: 8, 31: 10, 27: 13, 28: 15 }, - $n = [ - "white", - "green", - "blue", - "cyan", - "red", - "yellow", - "magenta", - "black", - "transparent", - ], - Kn = (function () { - function e() { - (this.time = null), (this.verboseLevel = 0); - } - return ( - (e.prototype.log = function (e, t) { - if (this.verboseLevel >= e) { - var r = "function" == typeof t ? t() : t; - A.log(this.time + " [" + e + "] " + r); - } - }), - e - ); - })(), - Wn = function (e) { - for (var t = [], r = 0; r < e.length; r++) - t.push(e[r].toString(16)); - return t; - }, - Vn = (function () { - function e() { - (this.foreground = "white"), - (this.underline = !1), - (this.italics = !1), - (this.background = "black"), - (this.flash = !1); - } - var t = e.prototype; - return ( - (t.reset = function () { - (this.foreground = "white"), - (this.underline = !1), - (this.italics = !1), - (this.background = "black"), - (this.flash = !1); - }), - (t.setStyles = function (e) { - for ( - var t = [ - "foreground", - "underline", - "italics", - "background", - "flash", - ], - r = 0; - r < t.length; - r++ - ) { - var i = t[r]; - e.hasOwnProperty(i) && (this[i] = e[i]); - } - }), - (t.isDefault = function () { - return ( - "white" === this.foreground && - !this.underline && - !this.italics && - "black" === this.background && - !this.flash - ); - }), - (t.equals = function (e) { - return ( - this.foreground === e.foreground && - this.underline === e.underline && - this.italics === e.italics && - this.background === e.background && - this.flash === e.flash - ); - }), - (t.copy = function (e) { - (this.foreground = e.foreground), - (this.underline = e.underline), - (this.italics = e.italics), - (this.background = e.background), - (this.flash = e.flash); - }), - (t.toString = function () { - return ( - "color=" + - this.foreground + - ", underline=" + - this.underline + - ", italics=" + - this.italics + - ", background=" + - this.background + - ", flash=" + - this.flash - ); - }), - e - ); - })(), - qn = (function () { - function e() { - (this.uchar = " "), (this.penState = new Vn()); - } - var t = e.prototype; - return ( - (t.reset = function () { - (this.uchar = " "), this.penState.reset(); - }), - (t.setChar = function (e, t) { - (this.uchar = e), this.penState.copy(t); - }), - (t.setPenState = function (e) { - this.penState.copy(e); - }), - (t.equals = function (e) { - return ( - this.uchar === e.uchar && - this.penState.equals(e.penState) - ); - }), - (t.copy = function (e) { - (this.uchar = e.uchar), this.penState.copy(e.penState); - }), - (t.isEmpty = function () { - return " " === this.uchar && this.penState.isDefault(); - }), - e - ); - })(), - jn = (function () { - function e(e) { - (this.chars = []), - (this.pos = 0), - (this.currPenState = new Vn()), - (this.cueStartTime = null), - (this.logger = void 0); - for (var t = 0; t < Nn; t++) this.chars.push(new qn()); - this.logger = e; - } - var t = e.prototype; - return ( - (t.equals = function (e) { - for (var t = 0; t < Nn; t++) - if (!this.chars[t].equals(e.chars[t])) return !1; - return !0; - }), - (t.copy = function (e) { - for (var t = 0; t < Nn; t++) - this.chars[t].copy(e.chars[t]); - }), - (t.isEmpty = function () { - for (var e = !0, t = 0; t < Nn; t++) - if (!this.chars[t].isEmpty()) { - e = !1; - break; - } - return e; - }), - (t.setCursor = function (e) { - this.pos !== e && (this.pos = e), - this.pos < 0 - ? (this.logger.log( - 3, - "Negative cursor position " + this.pos - ), - (this.pos = 0)) - : this.pos > Nn && - (this.logger.log( - 3, - "Too large cursor position " + this.pos - ), - (this.pos = Nn)); - }), - (t.moveCursor = function (e) { - var t = this.pos + e; - if (e > 1) - for (var r = this.pos + 1; r < t + 1; r++) - this.chars[r].setPenState(this.currPenState); - this.setCursor(t); - }), - (t.backSpace = function () { - this.moveCursor(-1), - this.chars[this.pos].setChar(" ", this.currPenState); - }), - (t.insertChar = function (e) { - var t = this; - e >= 144 && this.backSpace(); - var r = On(e); - this.pos >= Nn - ? this.logger.log(0, function () { - return ( - "Cannot insert " + - e.toString(16) + - " (" + - r + - ") at position " + - t.pos + - ". Skipping it!" - ); - }) - : (this.chars[this.pos].setChar(r, this.currPenState), - this.moveCursor(1)); - }), - (t.clearFromPos = function (e) { - var t; - for (t = e; t < Nn; t++) this.chars[t].reset(); - }), - (t.clear = function () { - this.clearFromPos(0), - (this.pos = 0), - this.currPenState.reset(); - }), - (t.clearToEndOfRow = function () { - this.clearFromPos(this.pos); - }), - (t.getTextString = function () { - for (var e = [], t = !0, r = 0; r < Nn; r++) { - var i = this.chars[r].uchar; - " " !== i && (t = !1), e.push(i); - } - return t ? "" : e.join(""); - }), - (t.setPenStyles = function (e) { - this.currPenState.setStyles(e), - this.chars[this.pos].setPenState(this.currPenState); - }), - e - ); - })(), - Yn = (function () { - function e(e) { - (this.rows = []), - (this.currRow = 14), - (this.nrRollUpRows = null), - (this.lastOutputScreen = null), - (this.logger = void 0); - for (var t = 0; t < Fn; t++) this.rows.push(new jn(e)); - this.logger = e; - } - var t = e.prototype; - return ( - (t.reset = function () { - for (var e = 0; e < Fn; e++) this.rows[e].clear(); - this.currRow = 14; - }), - (t.equals = function (e) { - for (var t = !0, r = 0; r < Fn; r++) - if (!this.rows[r].equals(e.rows[r])) { - t = !1; - break; - } - return t; - }), - (t.copy = function (e) { - for (var t = 0; t < Fn; t++) this.rows[t].copy(e.rows[t]); - }), - (t.isEmpty = function () { - for (var e = !0, t = 0; t < Fn; t++) - if (!this.rows[t].isEmpty()) { - e = !1; - break; - } - return e; - }), - (t.backSpace = function () { - this.rows[this.currRow].backSpace(); - }), - (t.clearToEndOfRow = function () { - this.rows[this.currRow].clearToEndOfRow(); - }), - (t.insertChar = function (e) { - this.rows[this.currRow].insertChar(e); - }), - (t.setPen = function (e) { - this.rows[this.currRow].setPenStyles(e); - }), - (t.moveCursor = function (e) { - this.rows[this.currRow].moveCursor(e); - }), - (t.setCursor = function (e) { - this.logger.log(2, "setCursor: " + e), - this.rows[this.currRow].setCursor(e); - }), - (t.setPAC = function (e) { - this.logger.log(2, function () { - return "pacData = " + JSON.stringify(e); - }); - var t = e.row - 1; - if ( - (this.nrRollUpRows && - t < this.nrRollUpRows - 1 && - (t = this.nrRollUpRows - 1), - this.nrRollUpRows && this.currRow !== t) - ) { - for (var r = 0; r < Fn; r++) this.rows[r].clear(); - var i = this.currRow + 1 - this.nrRollUpRows, - n = this.lastOutputScreen; - if (n) { - var s = n.rows[i].cueStartTime, - a = this.logger.time; - if (null !== s && null !== a && s < a) - for (var o = 0; o < this.nrRollUpRows; o++) - this.rows[t - this.nrRollUpRows + o + 1].copy( - n.rows[i + o] - ); - } - } - this.currRow = t; - var l = this.rows[this.currRow]; - if (null !== e.indent) { - var h = e.indent, - u = Math.max(h - 1, 0); - l.setCursor(e.indent), - (e.color = l.chars[u].penState.foreground); - } - var d = { - foreground: e.color, - underline: e.underline, - italics: e.italics, - background: "black", - flash: !1, - }; - this.setPen(d); - }), - (t.setBkgData = function (e) { - this.logger.log(2, function () { - return "bkgData = " + JSON.stringify(e); - }), - this.backSpace(), - this.setPen(e), - this.insertChar(32); - }), - (t.setRollUpRows = function (e) { - this.nrRollUpRows = e; - }), - (t.rollUp = function () { - var e = this; - if (null !== this.nrRollUpRows) { - this.logger.log(1, function () { - return e.getDisplayText(); - }); - var t = this.currRow + 1 - this.nrRollUpRows, - r = this.rows.splice(t, 1)[0]; - r.clear(), - this.rows.splice(this.currRow, 0, r), - this.logger.log(2, "Rolling up"); - } else - this.logger.log( - 3, - "roll_up but nrRollUpRows not set yet" - ); - }), - (t.getDisplayText = function (e) { - e = e || !1; - for (var t = [], r = "", i = -1, n = 0; n < Fn; n++) { - var s = this.rows[n].getTextString(); - s && - ((i = n + 1), - e - ? t.push("Row " + i + ": '" + s + "'") - : t.push(s.trim())); - } - return ( - t.length > 0 && - (r = e ? "[" + t.join(" | ") + "]" : t.join("\n")), - r - ); - }), - (t.getTextAndFormat = function () { - return this.rows; - }), - e - ); - })(), - zn = (function () { - function e(e, t, r) { - (this.chNr = void 0), - (this.outputFilter = void 0), - (this.mode = void 0), - (this.verbose = void 0), - (this.displayedMemory = void 0), - (this.nonDisplayedMemory = void 0), - (this.lastOutputScreen = void 0), - (this.currRollUpRow = void 0), - (this.writeScreen = void 0), - (this.cueStartTime = void 0), - (this.logger = void 0), - (this.chNr = e), - (this.outputFilter = t), - (this.mode = null), - (this.verbose = 0), - (this.displayedMemory = new Yn(r)), - (this.nonDisplayedMemory = new Yn(r)), - (this.lastOutputScreen = new Yn(r)), - (this.currRollUpRow = this.displayedMemory.rows[14]), - (this.writeScreen = this.displayedMemory), - (this.mode = null), - (this.cueStartTime = null), - (this.logger = r); - } - var t = e.prototype; - return ( - (t.reset = function () { - (this.mode = null), - this.displayedMemory.reset(), - this.nonDisplayedMemory.reset(), - this.lastOutputScreen.reset(), - this.outputFilter.reset(), - (this.currRollUpRow = this.displayedMemory.rows[14]), - (this.writeScreen = this.displayedMemory), - (this.mode = null), - (this.cueStartTime = null); - }), - (t.getHandler = function () { - return this.outputFilter; - }), - (t.setHandler = function (e) { - this.outputFilter = e; - }), - (t.setPAC = function (e) { - this.writeScreen.setPAC(e); - }), - (t.setBkgData = function (e) { - this.writeScreen.setBkgData(e); - }), - (t.setMode = function (e) { - e !== this.mode && - ((this.mode = e), - this.logger.log(2, function () { - return "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)); - }), - (t.insertChars = function (e) { - for (var t = this, r = 0; r < e.length; r++) - this.writeScreen.insertChar(e[r]); - var i = - this.writeScreen === this.displayedMemory - ? "DISP" - : "NON_DISP"; - this.logger.log(2, function () { - return i + ": " + t.writeScreen.getDisplayText(!0); - }), - ("MODE_PAINT-ON" !== this.mode && - "MODE_ROLL-UP" !== this.mode) || - (this.logger.log(1, function () { - return ( - "DISPLAYED: " + - t.displayedMemory.getDisplayText(!0) - ); - }), - this.outputDataUpdate()); - }), - (t.ccRCL = function () { - this.logger.log(2, "RCL - Resume Caption Loading"), - this.setMode("MODE_POP-ON"); - }), - (t.ccBS = function () { - this.logger.log(2, "BS - BackSpace"), - "MODE_TEXT" !== this.mode && - (this.writeScreen.backSpace(), - this.writeScreen === this.displayedMemory && - this.outputDataUpdate()); - }), - (t.ccAOF = function () {}), - (t.ccAON = function () {}), - (t.ccDER = function () { - this.logger.log(2, "DER- Delete to End of Row"), - this.writeScreen.clearToEndOfRow(), - this.outputDataUpdate(); - }), - (t.ccRU = function (e) { - this.logger.log(2, "RU(" + e + ") - Roll Up"), - (this.writeScreen = this.displayedMemory), - this.setMode("MODE_ROLL-UP"), - this.writeScreen.setRollUpRows(e); - }), - (t.ccFON = function () { - this.logger.log(2, "FON - Flash On"), - this.writeScreen.setPen({ flash: !0 }); - }), - (t.ccRDC = function () { - this.logger.log(2, "RDC - Resume Direct Captioning"), - this.setMode("MODE_PAINT-ON"); - }), - (t.ccTR = function () { - this.logger.log(2, "TR"), this.setMode("MODE_TEXT"); - }), - (t.ccRTD = function () { - this.logger.log(2, "RTD"), this.setMode("MODE_TEXT"); - }), - (t.ccEDM = function () { - this.logger.log(2, "EDM - Erase Displayed Memory"), - this.displayedMemory.reset(), - this.outputDataUpdate(!0); - }), - (t.ccCR = function () { - this.logger.log(2, "CR - Carriage Return"), - this.writeScreen.rollUp(), - this.outputDataUpdate(!0); - }), - (t.ccENM = function () { - this.logger.log(2, "ENM - Erase Non-displayed Memory"), - this.nonDisplayedMemory.reset(); - }), - (t.ccEOC = function () { - var e = this; - if ( - (this.logger.log(2, "EOC - End Of Caption"), - "MODE_POP-ON" === this.mode) - ) { - var t = this.displayedMemory; - (this.displayedMemory = this.nonDisplayedMemory), - (this.nonDisplayedMemory = t), - (this.writeScreen = this.nonDisplayedMemory), - this.logger.log(1, function () { - return ( - "DISP: " + e.displayedMemory.getDisplayText() - ); - }); - } - this.outputDataUpdate(!0); - }), - (t.ccTO = function (e) { - this.logger.log(2, "TO(" + e + ") - Tab Offset"), - this.writeScreen.moveCursor(e); - }), - (t.ccMIDROW = function (e) { - var t = { flash: !1 }; - if ( - ((t.underline = e % 2 == 1), - (t.italics = e >= 46), - t.italics) - ) - t.foreground = "white"; - else { - var r = Math.floor(e / 2) - 16; - t.foreground = [ - "white", - "green", - "blue", - "cyan", - "red", - "yellow", - "magenta", - ][r]; - } - this.logger.log(2, "MIDROW: " + JSON.stringify(t)), - this.writeScreen.setPen(t); - }), - (t.outputDataUpdate = function (e) { - void 0 === e && (e = !1); - var t = this.logger.time; - null !== t && - this.outputFilter && - (null !== this.cueStartTime || - this.displayedMemory.isEmpty() - ? this.displayedMemory.equals( - this.lastOutputScreen - ) || - (this.outputFilter.newCue( - this.cueStartTime, - t, - this.lastOutputScreen - ), - e && - this.outputFilter.dispatchCue && - this.outputFilter.dispatchCue(), - (this.cueStartTime = this.displayedMemory.isEmpty() - ? null - : t)) - : (this.cueStartTime = t), - this.lastOutputScreen.copy(this.displayedMemory)); - }), - (t.cueSplitAtTime = function (e) { - this.outputFilter && - (this.displayedMemory.isEmpty() || - (this.outputFilter.newCue && - this.outputFilter.newCue( - this.cueStartTime, - e, - this.displayedMemory - ), - (this.cueStartTime = e))); - }), - e - ); - })(), - Xn = (function () { - function e(e, t, r) { - (this.channels = void 0), - (this.currentChannel = 0), - (this.cmdHistory = { a: null, b: null }), - (this.logger = void 0); - var i = (this.logger = new Kn()); - this.channels = [ - null, - new zn(e, t, i), - new zn(e + 1, r, i), - ]; - } - var t = e.prototype; - return ( - (t.getHandler = function (e) { - return this.channels[e].getHandler(); - }), - (t.setHandler = function (e, t) { - this.channels[e].setHandler(t); - }), - (t.addData = function (e, t) { - var r = this; - this.logger.time = e; - for ( - var i = function (e) { - var i = 127 & t[e], - n = 127 & t[e + 1], - s = !1, - a = null; - if (0 === i && 0 === n) return 0; - r.logger.log(3, function () { - return ( - "[" + - Wn([t[e], t[e + 1]]) + - "] -> (" + - Wn([i, n]) + - ")" - ); - }); - var o = r.cmdHistory; - if (i >= 16 && i <= 31) { - if ( - (function (e, t, r) { - return r.a === e && r.b === t; - })(i, n, o) - ) - return ( - Qn(null, null, o), - r.logger.log(3, function () { - return ( - "Repeated command (" + - Wn([i, n]) + - ") is dropped" - ); - }), - 0 - ); - Qn(i, n, r.cmdHistory), - (s = r.parseCmd(i, n)) || - (s = r.parseMidrow(i, n)), - s || (s = r.parsePAC(i, n)), - s || (s = r.parseBackgroundAttributes(i, n)); - } else Qn(null, null, o); - if (!s && (a = r.parseChars(i, n))) { - var l = r.currentChannel; - l && l > 0 - ? r.channels[l].insertChars(a) - : r.logger.log( - 2, - "No channel found yet. TEXT-MODE?" - ); - } - s || - a || - r.logger.log(2, function () { - return ( - "Couldn't parse cleaned data " + - Wn([i, n]) + - " orig: " + - Wn([t[e], t[e + 1]]) - ); - }); - }, - n = 0; - n < t.length; - n += 2 - ) - i(n); - }), - (t.parseCmd = function (e, t) { - if ( - !( - ((20 === e || 28 === e || 21 === e || 29 === e) && - t >= 32 && - t <= 47) || - ((23 === e || 31 === e) && t >= 33 && t <= 35) - ) - ) - return !1; - var r = 20 === e || 21 === e || 23 === e ? 1 : 2, - i = this.channels[r]; - return ( - 20 === e || 21 === e || 28 === e || 29 === e - ? 32 === t - ? i.ccRCL() - : 33 === t - ? i.ccBS() - : 34 === t - ? i.ccAOF() - : 35 === t - ? i.ccAON() - : 36 === t - ? i.ccDER() - : 37 === t - ? i.ccRU(2) - : 38 === t - ? i.ccRU(3) - : 39 === t - ? i.ccRU(4) - : 40 === t - ? i.ccFON() - : 41 === t - ? i.ccRDC() - : 42 === t - ? i.ccTR() - : 43 === t - ? i.ccRTD() - : 44 === t - ? i.ccEDM() - : 45 === t - ? i.ccCR() - : 46 === t - ? i.ccENM() - : 47 === t && i.ccEOC() - : i.ccTO(t - 32), - (this.currentChannel = r), - !0 - ); - }), - (t.parseMidrow = function (e, t) { - var r = 0; - if ((17 === e || 25 === e) && t >= 32 && t <= 47) { - if ((r = 17 === e ? 1 : 2) !== this.currentChannel) - return ( - this.logger.log( - 0, - "Mismatch channel in midrow parsing" - ), - !1 - ); - var i = this.channels[r]; - return ( - !!i && - (i.ccMIDROW(t), - this.logger.log(3, function () { - return "MIDROW (" + Wn([e, t]) + ")"; - }), - !0) - ); - } - return !1; - }), - (t.parsePAC = function (e, t) { - var r; - if ( - !( - (((e >= 17 && e <= 23) || (e >= 25 && e <= 31)) && - t >= 64 && - t <= 127) || - ((16 === e || 24 === e) && t >= 64 && t <= 95) - ) - ) - return !1; - var i = e <= 23 ? 1 : 2; - r = - t >= 64 && t <= 95 - ? 1 === i - ? Bn[e] - : Gn[e] - : 1 === i - ? Un[e] - : Hn[e]; - var n = this.channels[i]; - return ( - !!n && - (n.setPAC(this.interpretPAC(r, t)), - (this.currentChannel = i), - !0) - ); - }), - (t.interpretPAC = function (e, t) { - var r, - i = { - color: null, - italics: !1, - indent: null, - underline: !1, - row: e, - }; - return ( - (r = t > 95 ? t - 96 : t - 64), - (i.underline = !(1 & ~r)), - r <= 13 - ? (i.color = [ - "white", - "green", - "blue", - "cyan", - "red", - "yellow", - "magenta", - "white", - ][Math.floor(r / 2)]) - : r <= 15 - ? ((i.italics = !0), (i.color = "white")) - : (i.indent = 4 * Math.floor((r - 16) / 2)), - i - ); - }), - (t.parseChars = function (e, t) { - var r, - i, - n = null, - s = null; - return ( - e >= 25 ? ((r = 2), (s = e - 8)) : ((r = 1), (s = e)), - s >= 17 && s <= 19 - ? ((i = - 17 === s ? t + 80 : 18 === s ? t + 112 : t + 144), - this.logger.log(2, function () { - return ( - "Special char '" + On(i) + "' in channel " + r - ); - }), - (n = [i])) - : e >= 32 && e <= 127 && (n = 0 === t ? [e] : [e, t]), - n && - this.logger.log(3, function () { - return "Char codes = " + Wn(n).join(","); - }), - n - ); - }), - (t.parseBackgroundAttributes = function (e, t) { - var r; - if ( - !( - ((16 === e || 24 === e) && t >= 32 && t <= 47) || - ((23 === e || 31 === e) && t >= 45 && t <= 47) - ) - ) - return !1; - var i = {}; - 16 === e || 24 === e - ? ((r = Math.floor((t - 32) / 2)), - (i.background = $n[r]), - t % 2 == 1 && (i.background = i.background + "_semi")) - : 45 === t - ? (i.background = "transparent") - : ((i.foreground = "black"), - 47 === t && (i.underline = !0)); - var n = e <= 23 ? 1 : 2; - return this.channels[n].setBkgData(i), !0; - }), - (t.reset = function () { - for ( - var e = 0; - e < Object.keys(this.channels).length; - e++ - ) { - var t = this.channels[e]; - t && t.reset(); - } - Qn(null, null, this.cmdHistory); - }), - (t.cueSplitAtTime = function (e) { - for (var t = 0; t < this.channels.length; t++) { - var r = this.channels[t]; - r && r.cueSplitAtTime(e); - } - }), - e - ); - })(); - function Qn(e, t, r) { - (r.a = e), (r.b = t); - } - var Jn = (function () { - function e(e, t) { - (this.timelineController = void 0), - (this.cueRanges = []), - (this.trackName = void 0), - (this.startTime = null), - (this.endTime = null), - (this.screen = null), - (this.timelineController = e), - (this.trackName = t); - } - var t = e.prototype; - return ( - (t.dispatchCue = function () { - null !== this.startTime && - (this.timelineController.addCues( - this.trackName, - this.startTime, - this.endTime, - this.screen, - this.cueRanges - ), - (this.startTime = null)); - }), - (t.newCue = function (e, t, r) { - (null === this.startTime || this.startTime > e) && - (this.startTime = e), - (this.endTime = t), - (this.screen = r), - this.timelineController.createCaptionsTrack( - this.trackName - ); - }), - (t.reset = function () { - (this.cueRanges = []), (this.startTime = null); - }), - e - ); - })(), - Zn = (function () { - if (null != $ && $.VTTCue) return self.VTTCue; - var e = ["", "lr", "rl"], - t = ["start", "middle", "end", "left", "right"]; - function r(e, t) { - if ("string" != typeof t) return !1; - if (!Array.isArray(e)) return !1; - var r = t.toLowerCase(); - return !!~e.indexOf(r) && r; - } - function i(e) { - return r(t, e); - } - function n(e) { - for ( - var t = arguments.length, - r = new Array(t > 1 ? t - 1 : 0), - i = 1; - i < t; - i++ - ) - r[i - 1] = arguments[i]; - for (var n = 1; n < arguments.length; n++) { - var s = arguments[n]; - for (var a in s) e[a] = s[a]; - } - return e; - } - function s(t, s, a) { - var o = this, - l = { enumerable: !0 }; - o.hasBeenReset = !1; - var h = "", - u = !1, - d = t, - c = s, - f = a, - g = null, - p = "", - m = !0, - v = "auto", - y = "start", - E = 50, - S = "middle", - T = 50, - _ = "middle"; - Object.defineProperty( - o, - "id", - n({}, l, { - get: function () { - return h; - }, - set: function (e) { - h = "" + e; - }, - }) - ), - Object.defineProperty( - o, - "pauseOnExit", - n({}, l, { - get: function () { - return u; - }, - set: function (e) { - u = !!e; - }, - }) - ), - Object.defineProperty( - o, - "startTime", - n({}, l, { - get: function () { - return d; - }, - set: function (e) { - if ("number" != typeof e) - throw new TypeError( - "Start time must be set to a number." - ); - (d = e), (this.hasBeenReset = !0); - }, - }) - ), - Object.defineProperty( - o, - "endTime", - n({}, l, { - get: function () { - return c; - }, - set: function (e) { - if ("number" != typeof e) - throw new TypeError( - "End time must be set to a number." - ); - (c = e), (this.hasBeenReset = !0); - }, - }) - ), - Object.defineProperty( - o, - "text", - n({}, l, { - get: function () { - return f; - }, - set: function (e) { - (f = "" + e), (this.hasBeenReset = !0); - }, - }) - ), - Object.defineProperty( - o, - "region", - n({}, l, { - get: function () { - return g; - }, - set: function (e) { - (g = e), (this.hasBeenReset = !0); - }, - }) - ), - Object.defineProperty( - o, - "vertical", - n({}, l, { - get: function () { - return p; - }, - set: function (t) { - var i = (function (t) { - return r(e, t); - })(t); - if (!1 === i) - throw new SyntaxError( - "An invalid or illegal string was specified." - ); - (p = i), (this.hasBeenReset = !0); - }, - }) - ), - Object.defineProperty( - o, - "snapToLines", - n({}, l, { - get: function () { - return m; - }, - set: function (e) { - (m = !!e), (this.hasBeenReset = !0); - }, - }) - ), - Object.defineProperty( - o, - "line", - n({}, l, { - get: function () { - return v; - }, - set: function (e) { - if ("number" != typeof e && "auto" !== e) - throw new SyntaxError( - "An invalid number or illegal string was specified." - ); - (v = e), (this.hasBeenReset = !0); - }, - }) - ), - Object.defineProperty( - o, - "lineAlign", - n({}, l, { - get: function () { - return y; - }, - set: function (e) { - var t = i(e); - if (!t) - throw new SyntaxError( - "An invalid or illegal string was specified." - ); - (y = t), (this.hasBeenReset = !0); - }, - }) - ), - Object.defineProperty( - o, - "position", - n({}, l, { - get: function () { - return E; - }, - set: function (e) { - if (e < 0 || e > 100) - throw new Error( - "Position must be between 0 and 100." - ); - (E = e), (this.hasBeenReset = !0); - }, - }) - ), - Object.defineProperty( - o, - "positionAlign", - n({}, l, { - get: function () { - return S; - }, - set: function (e) { - var t = i(e); - if (!t) - throw new SyntaxError( - "An invalid or illegal string was specified." - ); - (S = t), (this.hasBeenReset = !0); - }, - }) - ), - Object.defineProperty( - o, - "size", - n({}, l, { - get: function () { - return T; - }, - set: function (e) { - if (e < 0 || e > 100) - throw new Error( - "Size must be between 0 and 100." - ); - (T = e), (this.hasBeenReset = !0); - }, - }) - ), - Object.defineProperty( - o, - "align", - n({}, l, { - get: function () { - return _; - }, - set: function (e) { - var t = i(e); - if (!t) - throw new SyntaxError( - "An invalid or illegal string was specified." - ); - (_ = t), (this.hasBeenReset = !0); - }, - }) - ), - (o.displayState = void 0); - } - return ( - (s.prototype.getCueAsHTML = function () { - return self.WebVTT.convertCueToDOMTree(self, this.text); - }), - s - ); - })(), - es = (function () { - function e() {} - return ( - (e.prototype.decode = function (e, t) { - if (!e) return ""; - if ("string" != typeof e) - throw new Error("Error - expected string data."); - return decodeURIComponent(encodeURIComponent(e)); - }), - e - ); - })(); - function ts(e) { - function t(e, t, r, i) { - return ( - 3600 * (0 | e) + 60 * (0 | t) + (0 | r) + parseFloat(i || 0) - ); - } - var r = e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/); - return r - ? parseFloat(r[2]) > 59 - ? t(r[2], r[3], 0, r[4]) - : t(r[1], r[2], r[3], r[4]) - : null; - } - var rs = (function () { - function e() { - this.values = Object.create(null); - } - var t = e.prototype; - return ( - (t.set = function (e, t) { - this.get(e) || "" === t || (this.values[e] = t); - }), - (t.get = function (e, t, r) { - return r - ? this.has(e) - ? this.values[e] - : t[r] - : this.has(e) - ? this.values[e] - : t; - }), - (t.has = function (e) { - return e in this.values; - }), - (t.alt = function (e, t, r) { - for (var i = 0; i < r.length; ++i) - if (t === r[i]) { - this.set(e, t); - break; - } - }), - (t.integer = function (e, t) { - /^-?\d+$/.test(t) && this.set(e, parseInt(t, 10)); - }), - (t.percent = function (e, t) { - if (/^([\d]{1,3})(\.[\d]*)?%$/.test(t)) { - var r = parseFloat(t); - if (r >= 0 && r <= 100) return this.set(e, r), !0; - } - return !1; - }), - e - ); - })(); - function is(e, t, r, i) { - var n = i ? e.split(i) : [e]; - for (var s in n) - if ("string" == typeof n[s]) { - var a = n[s].split(r); - 2 === a.length && t(a[0], a[1]); - } - } - var ns = new Zn(0, 0, ""), - ss = "middle" === ns.align ? "middle" : "center"; - function as(e, t, r) { - var i = e; - function n() { - var t = ts(e); - if (null === t) throw new Error("Malformed timestamp: " + i); - return (e = e.replace(/^[^\sa-zA-Z-]+/, "")), t; - } - function s() { - e = e.replace(/^\s+/, ""); - } - if ((s(), (t.startTime = n()), s(), "--\x3e" !== e.slice(0, 3))) - throw new Error( - "Malformed time stamp (time stamps must be separated by '--\x3e'): " + - i - ); - (e = e.slice(3)), - s(), - (t.endTime = n()), - s(), - (function (e, t) { - var i = new rs(); - is( - e, - function (e, t) { - var n; - switch (e) { - case "region": - for (var s = r.length - 1; s >= 0; s--) - if (r[s].id === t) { - i.set(e, r[s].region); - break; - } - break; - case "vertical": - i.alt(e, t, ["rl", "lr"]); - break; - case "line": - (n = t.split(",")), - i.integer(e, n[0]), - i.percent(e, n[0]) && i.set("snapToLines", !1), - i.alt(e, n[0], ["auto"]), - 2 === n.length && - i.alt("lineAlign", n[1], ["start", ss, "end"]); - break; - case "position": - (n = t.split(",")), - i.percent(e, n[0]), - 2 === n.length && - i.alt("positionAlign", n[1], [ - "start", - ss, - "end", - "line-left", - "line-right", - "auto", - ]); - break; - case "size": - i.percent(e, t); - break; - case "align": - i.alt(e, t, ["start", ss, "end", "left", "right"]); - } - }, - /:/, - /\s/ - ), - (t.region = i.get("region", null)), - (t.vertical = i.get("vertical", "")); - var n = i.get("line", "auto"); - "auto" === n && -1 === ns.line && (n = -1), - (t.line = n), - (t.lineAlign = i.get("lineAlign", "start")), - (t.snapToLines = i.get("snapToLines", !0)), - (t.size = i.get("size", 100)), - (t.align = i.get("align", ss)); - var s = i.get("position", "auto"); - "auto" === s && - 50 === ns.position && - (s = - "start" === t.align || "left" === t.align - ? 0 - : "end" === t.align || "right" === t.align - ? 100 - : 50), - (t.position = s); - })(e, t); - } - function os(e) { - return e.replace(//gi, "\n"); - } - var ls = (function () { - function e() { - (this.state = "INITIAL"), - (this.buffer = ""), - (this.decoder = new es()), - (this.regionList = []), - (this.cue = null), - (this.oncue = void 0), - (this.onparsingerror = void 0), - (this.onflush = void 0); - } - var t = e.prototype; - return ( - (t.parse = function (e) { - var t = this; - function r() { - var e = t.buffer, - r = 0; - for ( - e = os(e); - r < e.length && "\r" !== e[r] && "\n" !== e[r]; - - ) - ++r; - var i = e.slice(0, r); - return ( - "\r" === e[r] && ++r, - "\n" === e[r] && ++r, - (t.buffer = e.slice(r)), - i - ); - } - e && (t.buffer += t.decoder.decode(e, { stream: !0 })); - try { - var i = ""; - if ("INITIAL" === t.state) { - if (!/\r\n|\n/.test(t.buffer)) return this; - var n = (i = r()).match(/^()?WEBVTT([ \t].*)?$/); - if (null == n || !n[0]) - throw new Error("Malformed WebVTT signature."); - t.state = "HEADER"; - } - for (var s = !1; t.buffer; ) { - if (!/\r\n|\n/.test(t.buffer)) return this; - switch ((s ? (s = !1) : (i = r()), t.state)) { - case "HEADER": - /:/.test(i) - ? is(i, function (e, t) {}, /:/) - : i || (t.state = "ID"); - continue; - case "NOTE": - i || (t.state = "ID"); - continue; - case "ID": - if (/^NOTE($|[ \t])/.test(i)) { - t.state = "NOTE"; - break; - } - if (!i) continue; - if ( - ((t.cue = new Zn(0, 0, "")), - (t.state = "CUE"), - -1 === i.indexOf("--\x3e")) - ) { - t.cue.id = i; - continue; - } - case "CUE": - if (!t.cue) { - t.state = "BADCUE"; - continue; - } - try { - as(i, t.cue, t.regionList); - } catch (e) { - (t.cue = null), (t.state = "BADCUE"); - continue; - } - t.state = "CUETEXT"; - continue; - case "CUETEXT": - var a = -1 !== i.indexOf("--\x3e"); - if (!i || (a && (s = !0))) { - t.oncue && t.cue && t.oncue(t.cue), - (t.cue = null), - (t.state = "ID"); - continue; - } - if (null === t.cue) continue; - t.cue.text && (t.cue.text += "\n"), - (t.cue.text += i); - continue; - case "BADCUE": - i || (t.state = "ID"); - } - } - } catch (e) { - "CUETEXT" === t.state && - t.cue && - t.oncue && - t.oncue(t.cue), - (t.cue = null), - (t.state = - "INITIAL" === t.state ? "BADWEBVTT" : "BADCUE"); - } - return this; - }), - (t.flush = function () { - var e = this; - try { - if ( - ((e.cue || "HEADER" === e.state) && - ((e.buffer += "\n\n"), e.parse()), - "INITIAL" === e.state || "BADWEBVTT" === e.state) - ) - throw new Error("Malformed WebVTT signature."); - } catch (t) { - e.onparsingerror && e.onparsingerror(t); - } - return e.onflush && e.onflush(), this; - }), - e - ); - })(), - hs = /\r\n|\n\r|\n|\r/g, - us = function (e, t, r) { - return ( - void 0 === r && (r = 0), e.slice(r, r + t.length) === t - ); - }, - ds = function (e) { - for (var t = 5381, r = e.length; r; ) - t = (33 * t) ^ e.charCodeAt(--r); - return (t >>> 0).toString(); - }; - function cs(e, t, r) { - return ds(e.toString()) + ds(t.toString()) + ds(r); - } - var fs = "stpp.ttml.im1t", - gs = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/, - ps = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/, - ms = { - left: "start", - center: "center", - right: "end", - start: "start", - end: "end", - }; - function vs(e, t, r, i) { - var n = we(new Uint8Array(e), ["mdat"]); - if (0 !== n.length) { - var s, - a, - l, - h = n.map(function (e) { - return me(e); - }), - u = - ((s = t.baseTime), - 1, - void 0 === (a = t.timescale) && (a = 1), - void 0 === l && (l = !1), - Qi(s, 1, 1 / a, l)); - try { - h.forEach(function (e) { - return r( - (function (e, t) { - var r = new DOMParser() - .parseFromString(e, "text/xml") - .getElementsByTagName("tt")[0]; - if (!r) throw new Error("Invalid ttml"); - var i = { - frameRate: 30, - subFrameRate: 1, - frameRateMultiplier: 0, - tickRate: 0, - }, - n = Object.keys(i).reduce(function (e, t) { - return ( - (e[t] = r.getAttribute("ttp:" + t) || i[t]), e - ); - }, {}), - s = "preserve" !== r.getAttribute("xml:space"), - a = Es(ys(r, "styling", "style")), - l = Es(ys(r, "layout", "region")), - h = ys(r, "body", "[begin]"); - return [].map - .call(h, function (e) { - var r = Ss(e, s); - if (!r || !e.hasAttribute("begin")) return null; - var i = Ls(e.getAttribute("begin"), n), - h = Ls(e.getAttribute("dur"), n), - u = Ls(e.getAttribute("end"), n); - if (null === i) throw _s(e); - if (null === u) { - if (null === h) throw _s(e); - u = i + h; - } - var d = new Zn(i - t, u - t, r); - d.id = cs(d.startTime, d.endTime, d.text); - var c = (function (e, t, r) { - var i = "http://www.w3.org/ns/ttml#styling", - n = null, - s = - null != e && e.hasAttribute("style") - ? e.getAttribute("style") - : null; - return ( - s && r.hasOwnProperty(s) && (n = r[s]), - [ - "displayAlign", - "textAlign", - "color", - "backgroundColor", - "fontSize", - "fontFamily", - ].reduce(function (r, s) { - var a = - Ts(t, i, s) || - Ts(e, i, s) || - Ts(n, i, s); - return a && (r[s] = a), r; - }, {}) - ); - })( - l[e.getAttribute("region")], - a[e.getAttribute("style")], - a - ), - f = c.textAlign; - if (f) { - var g = ms[f]; - g && (d.lineAlign = g), (d.align = f); - } - return o(d, c), d; - }) - .filter(function (e) { - return null !== e; - }); - })(e, u) - ); - }); - } catch (e) { - i(e); - } - } else i(new Error("Could not parse IMSC1 mdat")); - } - function ys(e, t, r) { - var i = e.getElementsByTagName(t)[0]; - return i ? [].slice.call(i.querySelectorAll(r)) : []; - } - function Es(e) { - return e.reduce(function (e, t) { - var r = t.getAttribute("xml:id"); - return r && (e[r] = t), e; - }, {}); - } - function Ss(e, t) { - return [].slice.call(e.childNodes).reduce(function (e, r, i) { - var n; - return "br" === r.nodeName && i - ? e + "\n" - : null != (n = r.childNodes) && n.length - ? Ss(r, t) - : t - ? e + r.textContent.trim().replace(/\s+/g, " ") - : e + r.textContent; - }, ""); - } - function Ts(e, t, r) { - return e && e.hasAttributeNS(t, r) - ? e.getAttributeNS(t, r) - : null; - } - function _s(e) { - return new Error("Could not parse ttml timestamp " + e); - } - function Ls(e, t) { - if (!e) return null; - var r = ts(e); - return ( - null === r && - (gs.test(e) - ? (r = (function (e, t) { - var r = gs.exec(e), - i = (0 | r[4]) + (0 | r[5]) / t.subFrameRate; - return ( - 3600 * (0 | r[1]) + - 60 * (0 | r[2]) + - (0 | r[3]) + - i / t.frameRate - ); - })(e, t)) - : ps.test(e) && - (r = (function (e, t) { - var r = ps.exec(e), - i = Number(r[1]); - switch (r[2]) { - case "h": - return 3600 * i; - case "m": - return 60 * i; - case "ms": - return 1e3 * i; - case "f": - return i / t.frameRate; - case "t": - return i / t.tickRate; - } - return i; - })(e, t))), - r - ); - } - var bs = (function () { - function e(e) { - (this.hls = void 0), - (this.media = null), - (this.config = void 0), - (this.enabled = !0), - (this.Cues = void 0), - (this.textTracks = []), - (this.tracks = []), - (this.initPTS = []), - (this.unparsedVttFrags = []), - (this.captionsTracks = {}), - (this.nonNativeCaptionsTracks = {}), - (this.cea608Parser1 = void 0), - (this.cea608Parser2 = void 0), - (this.lastCc = -1), - (this.lastSn = -1), - (this.lastPartIndex = -1), - (this.prevCC = -1), - (this.vttCCs = { - ccOffset: 0, - presentationOffset: 0, - 0: { start: 0, prevCC: -1, new: !0 }, - }), - (this.captionsProperties = void 0), - (this.hls = e), - (this.config = e.config), - (this.Cues = e.config.cueHandler), - (this.captionsProperties = { - textTrack1: { - label: this.config.captionsTextTrack1Label, - languageCode: - this.config.captionsTextTrack1LanguageCode, - }, - textTrack2: { - label: this.config.captionsTextTrack2Label, - languageCode: - this.config.captionsTextTrack2LanguageCode, - }, - textTrack3: { - label: this.config.captionsTextTrack3Label, - languageCode: - this.config.captionsTextTrack3LanguageCode, - }, - textTrack4: { - label: this.config.captionsTextTrack4Label, - languageCode: - this.config.captionsTextTrack4LanguageCode, - }, - }), - e.on(E.MEDIA_ATTACHING, this.onMediaAttaching, this), - e.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.MANIFEST_LOADED, this.onManifestLoaded, this), - e.on( - E.SUBTITLE_TRACKS_UPDATED, - this.onSubtitleTracksUpdated, - this - ), - e.on(E.FRAG_LOADING, this.onFragLoading, this), - e.on(E.FRAG_LOADED, this.onFragLoaded, this), - e.on( - E.FRAG_PARSING_USERDATA, - this.onFragParsingUserdata, - this - ), - e.on(E.FRAG_DECRYPTED, this.onFragDecrypted, this), - e.on(E.INIT_PTS_FOUND, this.onInitPtsFound, this), - e.on( - E.SUBTITLE_TRACKS_CLEARED, - this.onSubtitleTracksCleared, - this - ), - e.on(E.BUFFER_FLUSHING, this.onBufferFlushing, this); - } - var t = e.prototype; - return ( - (t.destroy = function () { - var e = this.hls; - e.off(E.MEDIA_ATTACHING, this.onMediaAttaching, this), - e.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.off(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.off(E.MANIFEST_LOADED, this.onManifestLoaded, this), - e.off( - E.SUBTITLE_TRACKS_UPDATED, - this.onSubtitleTracksUpdated, - this - ), - e.off(E.FRAG_LOADING, this.onFragLoading, this), - e.off(E.FRAG_LOADED, this.onFragLoaded, this), - e.off( - E.FRAG_PARSING_USERDATA, - this.onFragParsingUserdata, - this - ), - e.off(E.FRAG_DECRYPTED, this.onFragDecrypted, this), - e.off(E.INIT_PTS_FOUND, this.onInitPtsFound, this), - e.off( - E.SUBTITLE_TRACKS_CLEARED, - this.onSubtitleTracksCleared, - this - ), - e.off(E.BUFFER_FLUSHING, this.onBufferFlushing, this), - (this.hls = this.config = null), - (this.cea608Parser1 = this.cea608Parser2 = void 0); - }), - (t.initCea608Parsers = function () { - if ( - this.config.enableCEA708Captions && - (!this.cea608Parser1 || !this.cea608Parser2) - ) { - var e = new Jn(this, "textTrack1"), - t = new Jn(this, "textTrack2"), - r = new Jn(this, "textTrack3"), - i = new Jn(this, "textTrack4"); - (this.cea608Parser1 = new Xn(1, e, t)), - (this.cea608Parser2 = new Xn(3, r, i)); - } - }), - (t.addCues = function (e, t, r, i, n) { - for (var s, a, o, l, h = !1, u = n.length; u--; ) { - var d = n[u], - c = - ((s = d[0]), - (a = d[1]), - (o = t), - (l = r), - Math.min(a, l) - Math.max(s, o)); - if ( - c >= 0 && - ((d[0] = Math.min(d[0], t)), - (d[1] = Math.max(d[1], r)), - (h = !0), - c / (r - t) > 0.5) - ) - return; - } - if ( - (h || n.push([t, r]), - this.config.renderTextTracksNatively) - ) { - var f = this.captionsTracks[e]; - this.Cues.newCue(f, t, r, i); - } else { - var g = this.Cues.newCue(null, t, r, i); - this.hls.trigger(E.CUES_PARSED, { - type: "captions", - cues: g, - track: e, - }); - } - }), - (t.onInitPtsFound = function (e, t) { - var r = this, - i = t.frag, - n = t.id, - s = t.initPTS, - a = t.timescale, - o = this.unparsedVttFrags; - "main" === n && - (this.initPTS[i.cc] = { baseTime: s, timescale: a }), - o.length && - ((this.unparsedVttFrags = []), - o.forEach(function (e) { - r.onFragLoaded(E.FRAG_LOADED, e); - })); - }), - (t.getExistingTrack = function (e, t) { - var r = this.media; - if (r) - for (var i = 0; i < r.textTracks.length; i++) { - var n = r.textTracks[i]; - if (As(n, { name: e, lang: t, attrs: {} })) return n; - } - return null; - }), - (t.createCaptionsTrack = function (e) { - this.config.renderTextTracksNatively - ? this.createNativeTrack(e) - : this.createNonNativeTrack(e); - }), - (t.createNativeTrack = function (e) { - if (!this.captionsTracks[e]) { - var t = this.captionsProperties, - r = this.captionsTracks, - i = this.media, - n = t[e], - s = n.label, - a = n.languageCode, - o = this.getExistingTrack(s, a); - if (o) (r[e] = o), kt(r[e]), It(r[e], i); - else { - var l = this.createTextTrack("captions", s, a); - l && ((l[e] = !0), (r[e] = l)); - } - } - }), - (t.createNonNativeTrack = function (e) { - if (!this.nonNativeCaptionsTracks[e]) { - var t = this.captionsProperties[e]; - if (t) { - var r = { - _id: e, - label: t.label, - kind: "captions", - default: !!t.media && !!t.media.default, - closedCaptions: t.media, - }; - (this.nonNativeCaptionsTracks[e] = r), - this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND, { - tracks: [r], - }); - } - } - }), - (t.createTextTrack = function (e, t, r) { - var i = this.media; - if (i) return i.addTextTrack(e, t, r); - }), - (t.onMediaAttaching = function (e, t) { - (this.media = t.media), this._cleanTracks(); - }), - (t.onMediaDetaching = function () { - var e = this.captionsTracks; - Object.keys(e).forEach(function (t) { - kt(e[t]), delete e[t]; - }), - (this.nonNativeCaptionsTracks = {}); - }), - (t.onManifestLoading = function () { - (this.lastCc = -1), - (this.lastSn = -1), - (this.lastPartIndex = -1), - (this.prevCC = -1), - (this.vttCCs = { - ccOffset: 0, - presentationOffset: 0, - 0: { start: 0, prevCC: -1, new: !0 }, - }), - this._cleanTracks(), - (this.tracks = []), - (this.captionsTracks = {}), - (this.nonNativeCaptionsTracks = {}), - (this.textTracks = []), - (this.unparsedVttFrags = []), - (this.initPTS = []), - this.cea608Parser1 && - this.cea608Parser2 && - (this.cea608Parser1.reset(), - this.cea608Parser2.reset()); - }), - (t._cleanTracks = function () { - var e = this.media; - if (e) { - var t = e.textTracks; - if (t) for (var r = 0; r < t.length; r++) kt(t[r]); - } - }), - (t.onSubtitleTracksUpdated = function (e, t) { - var r = this, - i = t.subtitleTracks || [], - n = i.some(function (e) { - return e.textCodec === fs; - }); - if ( - this.config.enableWebVTT || - (n && this.config.enableIMSC1) - ) { - if (_n(this.tracks, i)) return void (this.tracks = i); - if ( - ((this.textTracks = []), - (this.tracks = i), - this.config.renderTextTracksNatively) - ) { - var s = this.media, - a = s ? Mt(s.textTracks) : null; - if ( - (this.tracks.forEach(function (e, t) { - var i; - if (a) { - for (var n = null, s = 0; s < a.length; s++) - if (a[s] && As(a[s], e)) { - (n = a[s]), (a[s] = null); - break; - } - n && (i = n); - } - if (i) kt(i); - else { - var o = Rs(e); - (i = r.createTextTrack(o, e.name, e.lang)) && - (i.mode = "disabled"); - } - i && r.textTracks.push(i); - }), - null != a && a.length) - ) { - var o = a - .filter(function (e) { - return null !== e; - }) - .map(function (e) { - return e.label; - }); - o.length && - A.warn( - "Media element contains unused subtitle tracks: " + - o.join(", ") + - ". Replace media element for each source to clear TextTracks and captions menu." - ); - } - } else if (this.tracks.length) { - var l = this.tracks.map(function (e) { - return { - label: e.name, - kind: e.type.toLowerCase(), - default: e.default, - subtitleTrack: e, - }; - }); - this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND, { - tracks: l, - }); - } - } - }), - (t.onManifestLoaded = function (e, t) { - var r = this; - this.config.enableCEA708Captions && - t.captions && - t.captions.forEach(function (e) { - var t = /(?:CC|SERVICE)([1-4])/.exec(e.instreamId); - if (t) { - var i = "textTrack" + t[1], - n = r.captionsProperties[i]; - n && - ((n.label = e.name), - e.lang && (n.languageCode = e.lang), - (n.media = e)); - } - }); - }), - (t.closedCaptionsForLevel = function (e) { - var t = this.hls.levels[e.level]; - return null == t ? void 0 : t.attrs["CLOSED-CAPTIONS"]; - }), - (t.onFragLoading = function (e, t) { - if (this.enabled && t.frag.type === Lt) { - var r, - i, - n = this.cea608Parser1, - s = this.cea608Parser2, - a = this.lastSn, - o = t.frag, - l = o.cc, - h = o.sn, - u = - null != (r = null == (i = t.part) ? void 0 : i.index) - ? r - : -1; - n && - s && - (h !== a + 1 || - (h === a && u !== this.lastPartIndex + 1) || - l !== this.lastCc) && - (n.reset(), s.reset()), - (this.lastCc = l), - (this.lastSn = h), - (this.lastPartIndex = u); - } - }), - (t.onFragLoaded = function (e, t) { - var r = t.frag, - i = t.payload; - if (r.type === Rt) - if (i.byteLength) { - var n = r.decryptdata, - s = "stats" in t; - if (null == n || !n.encrypted || s) { - var a = this.tracks[r.level], - o = this.vttCCs; - o[r.cc] || - ((o[r.cc] = { - start: r.start, - prevCC: this.prevCC, - new: !0, - }), - (this.prevCC = r.cc)), - a && a.textCodec === fs - ? this._parseIMSC1(r, i) - : this._parseVTTs(t); - } - } else - this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED, { - success: !1, - frag: r, - error: new Error("Empty subtitle payload"), - }); - }), - (t._parseIMSC1 = function (e, t) { - var r = this, - i = this.hls; - vs( - t, - this.initPTS[e.cc], - function (t) { - r._appendCues(t, e.level), - i.trigger(E.SUBTITLE_FRAG_PROCESSED, { - success: !0, - frag: e, - }); - }, - function (t) { - A.log("Failed to parse IMSC1: " + t), - i.trigger(E.SUBTITLE_FRAG_PROCESSED, { - success: !1, - frag: e, - error: t, - }); - } - ); - }), - (t._parseVTTs = function (e) { - var t, - r = this, - i = e.frag, - n = e.payload, - s = this.initPTS, - a = this.unparsedVttFrags, - o = s.length - 1; - if (s[i.cc] || -1 !== o) { - var l = this.hls; - !(function (e, t, r, i, n, s, a) { - var o, - l, - h, - u = new ls(), - d = me(new Uint8Array(e)) - .trim() - .replace(hs, "\n") - .split("\n"), - c = [], - f = t - ? ((o = t.baseTime), - void 0 === (l = t.timescale) && (l = 1), - Qi(o, 9e4, 1 / l)) - : 0, - g = "00:00.000", - p = 0, - v = 0, - y = !0; - (u.oncue = function (e) { - var s = r[i], - a = r.ccOffset, - o = (p - f) / 9e4; - if ( - (null != s && - s.new && - (void 0 !== v - ? (a = r.ccOffset = s.start) - : (function (e, t, r) { - var i = e[t], - n = e[i.prevCC]; - if (!n || (!n.new && i.new)) - return ( - (e.ccOffset = e.presentationOffset = - i.start), - void (i.new = !1) - ); - for (; null != (s = n) && s.new; ) { - var s; - (e.ccOffset += i.start - n.start), - (i.new = !1), - (n = e[(i = n).prevCC]); - } - e.presentationOffset = r; - })(r, i, o)), - o) - ) { - if (!t) - return void (h = new Error( - "Missing initPTS for VTT MPEGTS" - )); - a = o - r.presentationOffset; - } - var l = e.endTime - e.startTime, - u = rn(9e4 * (e.startTime + a - v), 9e4 * n) / 9e4; - (e.startTime = Math.max(u, 0)), - (e.endTime = Math.max(u + l, 0)); - var d = e.text.trim(); - (e.text = decodeURIComponent(encodeURIComponent(d))), - e.id || (e.id = cs(e.startTime, e.endTime, d)), - e.endTime > 0 && c.push(e); - }), - (u.onparsingerror = function (e) { - h = e; - }), - (u.onflush = function () { - h ? a(h) : s(c); - }), - d.forEach(function (e) { - if (y) { - if (us(e, "X-TIMESTAMP-MAP=")) { - (y = !1), - e - .slice(16) - .split(",") - .forEach(function (e) { - us(e, "LOCAL:") - ? (g = e.slice(6)) - : us(e, "MPEGTS:") && - (p = parseInt(e.slice(7))); - }); - try { - v = - (function (e) { - var t = parseInt(e.slice(-3)), - r = parseInt(e.slice(-6, -4)), - i = parseInt(e.slice(-9, -7)), - n = - e.length > 9 - ? parseInt( - e.substring(0, e.indexOf(":")) - ) - : 0; - if (!(m(t) && m(r) && m(i) && m(n))) - throw Error( - "Malformed X-TIMESTAMP-MAP: Local:" + - e - ); - return ( - (t += 1e3 * r), - (t += 6e4 * i) + 36e5 * n - ); - })(g) / 1e3; - } catch (e) { - h = e; - } - return; - } - "" === e && (y = !1); - } - u.parse(e + "\n"); - }), - u.flush(); - })( - null != (t = i.initSegment) && t.data - ? Fe(i.initSegment.data, new Uint8Array(n)) - : n, - this.initPTS[i.cc], - this.vttCCs, - i.cc, - i.start, - function (e) { - r._appendCues(e, i.level), - l.trigger(E.SUBTITLE_FRAG_PROCESSED, { - success: !0, - frag: i, - }); - }, - function (t) { - var s = - "Missing initPTS for VTT MPEGTS" === t.message; - s ? a.push(e) : r._fallbackToIMSC1(i, n), - A.log("Failed to parse VTT cue: " + t), - (s && o > i.cc) || - l.trigger(E.SUBTITLE_FRAG_PROCESSED, { - success: !1, - frag: i, - error: t, - }); - } - ); - } else a.push(e); - }), - (t._fallbackToIMSC1 = function (e, t) { - var r = this, - i = this.tracks[e.level]; - i.textCodec || - vs( - t, - this.initPTS[e.cc], - function () { - (i.textCodec = fs), r._parseIMSC1(e, t); - }, - function () { - i.textCodec = "wvtt"; - } - ); - }), - (t._appendCues = function (e, t) { - var r = this.hls; - if (this.config.renderTextTracksNatively) { - var i = this.textTracks[t]; - if (!i || "disabled" === i.mode) return; - e.forEach(function (e) { - return Ct(i, e); - }); - } else { - var n = this.tracks[t]; - if (!n) return; - var s = n.default ? "default" : "subtitles" + t; - r.trigger(E.CUES_PARSED, { - type: "subtitles", - cues: e, - track: s, - }); - } - }), - (t.onFragDecrypted = function (e, t) { - t.frag.type === Rt && this.onFragLoaded(E.FRAG_LOADED, t); - }), - (t.onSubtitleTracksCleared = function () { - (this.tracks = []), (this.captionsTracks = {}); - }), - (t.onFragParsingUserdata = function (e, t) { - this.initCea608Parsers(); - var r = this.cea608Parser1, - i = this.cea608Parser2; - if (this.enabled && r && i) { - var n = t.frag, - s = t.samples; - if ( - n.type !== Lt || - "NONE" !== this.closedCaptionsForLevel(n) - ) - for (var a = 0; a < s.length; a++) { - var o = s[a].bytes; - if (o) { - var l = this.extractCea608Data(o); - r.addData(s[a].pts, l[0]), - i.addData(s[a].pts, l[1]); - } - } - } - }), - (t.onBufferFlushing = function (e, t) { - var r = t.startOffset, - i = t.endOffset, - n = t.endOffsetSubtitles, - s = t.type, - a = this.media; - if (a && !(a.currentTime < i)) { - if (!s || "video" === s) { - var o = this.captionsTracks; - Object.keys(o).forEach(function (e) { - return Dt(o[e], r, i); - }); - } - if ( - this.config.renderTextTracksNatively && - 0 === r && - void 0 !== n - ) { - var l = this.textTracks; - Object.keys(l).forEach(function (e) { - return Dt(l[e], r, n); - }); - } - } - }), - (t.extractCea608Data = function (e) { - for ( - var t = [[], []], r = 31 & e[0], i = 2, n = 0; - n < r; - n++ - ) { - var s = e[i++], - a = 127 & e[i++], - o = 127 & e[i++]; - if ((0 !== a || 0 !== o) && 4 & s) { - var l = 3 & s; - (0 !== l && 1 !== l) || (t[l].push(a), t[l].push(o)); - } - } - return t; - }), - e - ); - })(); - function Rs(e) { - return e.characteristics && - /transcribes-spoken-dialog/gi.test(e.characteristics) && - /describes-music-and-sound/gi.test(e.characteristics) - ? "captions" - : "subtitles"; - } - function As(e, t) { - return !!e && e.kind === Rs(t) && bn(t, e); - } - var ws = (function () { - function e(e) { - (this.hls = void 0), - (this.autoLevelCapping = void 0), - (this.firstLevel = void 0), - (this.media = void 0), - (this.restrictedLevels = void 0), - (this.timer = void 0), - (this.clientRect = void 0), - (this.streamController = void 0), - (this.hls = e), - (this.autoLevelCapping = Number.POSITIVE_INFINITY), - (this.firstLevel = -1), - (this.media = null), - (this.restrictedLevels = []), - (this.timer = void 0), - (this.clientRect = null), - this.registerListeners(); - } - var t = e.prototype; - return ( - (t.setStreamController = function (e) { - this.streamController = e; - }), - (t.destroy = function () { - this.hls && this.unregisterListener(), - this.timer && this.stopCapping(), - (this.media = null), - (this.clientRect = null), - (this.hls = this.streamController = null); - }), - (t.registerListeners = function () { - var e = this.hls; - e.on( - E.FPS_DROP_LEVEL_CAPPING, - this.onFpsDropLevelCapping, - this - ), - e.on(E.MEDIA_ATTACHING, this.onMediaAttaching, this), - e.on(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.on(E.LEVELS_UPDATED, this.onLevelsUpdated, this), - e.on(E.BUFFER_CODECS, this.onBufferCodecs, this), - e.on(E.MEDIA_DETACHING, this.onMediaDetaching, this); - }), - (t.unregisterListener = function () { - var e = this.hls; - e.off( - E.FPS_DROP_LEVEL_CAPPING, - this.onFpsDropLevelCapping, - this - ), - e.off(E.MEDIA_ATTACHING, this.onMediaAttaching, this), - e.off(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.off(E.LEVELS_UPDATED, this.onLevelsUpdated, this), - e.off(E.BUFFER_CODECS, this.onBufferCodecs, this), - e.off(E.MEDIA_DETACHING, this.onMediaDetaching, this); - }), - (t.onFpsDropLevelCapping = function (e, t) { - var r = this.hls.levels[t.droppedLevel]; - this.isLevelAllowed(r) && - this.restrictedLevels.push({ - bitrate: r.bitrate, - height: r.height, - width: r.width, - }); - }), - (t.onMediaAttaching = function (e, t) { - (this.media = - t.media instanceof HTMLVideoElement ? t.media : null), - (this.clientRect = null), - this.timer && - this.hls.levels.length && - this.detectPlayerSize(); - }), - (t.onManifestParsed = function (e, t) { - var r = this.hls; - (this.restrictedLevels = []), - (this.firstLevel = t.firstLevel), - r.config.capLevelToPlayerSize && - t.video && - this.startCapping(); - }), - (t.onLevelsUpdated = function (e, t) { - this.timer && - m(this.autoLevelCapping) && - this.detectPlayerSize(); - }), - (t.onBufferCodecs = function (e, t) { - this.hls.config.capLevelToPlayerSize && - t.video && - this.startCapping(); - }), - (t.onMediaDetaching = function () { - this.stopCapping(); - }), - (t.detectPlayerSize = function () { - if (this.media) { - if (this.mediaHeight <= 0 || this.mediaWidth <= 0) - return void (this.clientRect = null); - var e = this.hls.levels; - if (e.length) { - var t = this.hls, - r = this.getMaxLevel(e.length - 1); - r !== this.autoLevelCapping && - A.log( - "Setting autoLevelCapping to " + - r + - ": " + - e[r].height + - "p@" + - e[r].bitrate + - " for media " + - this.mediaWidth + - "x" + - this.mediaHeight - ), - (t.autoLevelCapping = r), - t.autoLevelCapping > this.autoLevelCapping && - this.streamController && - this.streamController.nextLevelSwitch(), - (this.autoLevelCapping = t.autoLevelCapping); - } - } - }), - (t.getMaxLevel = function (t) { - var r = this, - i = this.hls.levels; - if (!i.length) return -1; - var n = i.filter(function (e, i) { - return r.isLevelAllowed(e) && i <= t; - }); - return ( - (this.clientRect = null), - e.getMaxLevelByMediaSize( - n, - this.mediaWidth, - this.mediaHeight - ) - ); - }), - (t.startCapping = function () { - this.timer || - ((this.autoLevelCapping = Number.POSITIVE_INFINITY), - self.clearInterval(this.timer), - (this.timer = self.setInterval( - this.detectPlayerSize.bind(this), - 1e3 - )), - this.detectPlayerSize()); - }), - (t.stopCapping = function () { - (this.restrictedLevels = []), - (this.firstLevel = -1), - (this.autoLevelCapping = Number.POSITIVE_INFINITY), - this.timer && - (self.clearInterval(this.timer), - (this.timer = void 0)); - }), - (t.getDimensions = function () { - if (this.clientRect) return this.clientRect; - var e = this.media, - t = { width: 0, height: 0 }; - if (e) { - var r = e.getBoundingClientRect(); - (t.width = r.width), - (t.height = r.height), - t.width || - t.height || - ((t.width = r.right - r.left || e.width || 0), - (t.height = r.bottom - r.top || e.height || 0)); - } - return (this.clientRect = t), t; - }), - (t.isLevelAllowed = function (e) { - return !this.restrictedLevels.some(function (t) { - return ( - e.bitrate === t.bitrate && - e.width === t.width && - e.height === t.height - ); - }); - }), - (e.getMaxLevelByMediaSize = function (e, t, r) { - if (null == e || !e.length) return -1; - for ( - var i, n, s = e.length - 1, a = Math.max(t, r), o = 0; - o < e.length; - o += 1 - ) { - var l = e[o]; - if ( - (l.width >= a || l.height >= a) && - ((i = l), - !(n = e[o + 1]) || - i.width !== n.width || - i.height !== n.height) - ) { - s = o; - break; - } - } - return s; - }), - a(e, [ - { - key: "mediaWidth", - get: function () { - return ( - this.getDimensions().width * this.contentScaleFactor - ); - }, - }, - { - key: "mediaHeight", - get: function () { - return ( - this.getDimensions().height * - this.contentScaleFactor - ); - }, - }, - { - key: "contentScaleFactor", - get: function () { - var e = 1; - if (!this.hls.config.ignoreDevicePixelRatio) - try { - e = self.devicePixelRatio; - } catch (e) {} - return e; - }, - }, - ]), - e - ); - })(), - Ps = (function () { - function e(e) { - (this.hls = void 0), - (this.isVideoPlaybackQualityAvailable = !1), - (this.timer = void 0), - (this.media = null), - (this.lastTime = void 0), - (this.lastDroppedFrames = 0), - (this.lastDecodedFrames = 0), - (this.streamController = void 0), - (this.hls = e), - this.registerListeners(); - } - var t = e.prototype; - return ( - (t.setStreamController = function (e) { - this.streamController = e; - }), - (t.registerListeners = function () { - this.hls.on( - E.MEDIA_ATTACHING, - this.onMediaAttaching, - this - ); - }), - (t.unregisterListeners = function () { - this.hls.off( - E.MEDIA_ATTACHING, - this.onMediaAttaching, - this - ); - }), - (t.destroy = function () { - this.timer && clearInterval(this.timer), - this.unregisterListeners(), - (this.isVideoPlaybackQualityAvailable = !1), - (this.media = null); - }), - (t.onMediaAttaching = function (e, t) { - var r = this.hls.config; - if (r.capLevelOnFPSDrop) { - var i = - t.media instanceof self.HTMLVideoElement - ? t.media - : null; - (this.media = i), - i && - "function" == typeof i.getVideoPlaybackQuality && - (this.isVideoPlaybackQualityAvailable = !0), - self.clearInterval(this.timer), - (this.timer = self.setInterval( - this.checkFPSInterval.bind(this), - r.fpsDroppedMonitoringPeriod - )); - } - }), - (t.checkFPS = function (e, t, r) { - var i = performance.now(); - if (t) { - if (this.lastTime) { - var n = i - this.lastTime, - s = r - this.lastDroppedFrames, - a = t - this.lastDecodedFrames, - o = (1e3 * s) / n, - l = this.hls; - if ( - (l.trigger(E.FPS_DROP, { - currentDropped: s, - currentDecoded: a, - totalDroppedFrames: r, - }), - o > 0 && - s > l.config.fpsDroppedMonitoringThreshold * a) - ) { - var h = l.currentLevel; - A.warn( - "drop FPS ratio greater than max allowed value for currentLevel: " + - h - ), - h > 0 && - (-1 === l.autoLevelCapping || - l.autoLevelCapping >= h) && - ((h -= 1), - l.trigger(E.FPS_DROP_LEVEL_CAPPING, { - level: h, - droppedLevel: l.currentLevel, - }), - (l.autoLevelCapping = h), - this.streamController.nextLevelSwitch()); - } - } - (this.lastTime = i), - (this.lastDroppedFrames = r), - (this.lastDecodedFrames = t); - } - }), - (t.checkFPSInterval = function () { - var e = this.media; - if (e) - if (this.isVideoPlaybackQualityAvailable) { - var t = e.getVideoPlaybackQuality(); - this.checkFPS( - e, - t.totalVideoFrames, - t.droppedVideoFrames - ); - } else - this.checkFPS( - e, - e.webkitDecodedFrameCount, - e.webkitDroppedFrameCount - ); - }), - e - ); - })(), - Is = "[eme]", - Cs = (function () { - function e(t) { - (this.hls = void 0), - (this.config = void 0), - (this.media = null), - (this.keyFormatPromise = null), - (this.keySystemAccessPromises = {}), - (this._requestLicenseFailureCount = 0), - (this.mediaKeySessions = []), - (this.keyIdToKeySessionPromise = {}), - (this.setMediaKeysQueue = e.CDMCleanupPromise - ? [e.CDMCleanupPromise] - : []), - (this.onMediaEncrypted = - this._onMediaEncrypted.bind(this)), - (this.onWaitingForKey = this._onWaitingForKey.bind(this)), - (this.debug = A.debug.bind(A, Is)), - (this.log = A.log.bind(A, Is)), - (this.warn = A.warn.bind(A, Is)), - (this.error = A.error.bind(A, Is)), - (this.hls = t), - (this.config = t.config), - this.registerListeners(); - } - var t = e.prototype; - return ( - (t.destroy = function () { - this.unregisterListeners(), this.onMediaDetached(); - var e = this.config; - (e.requestMediaKeySystemAccessFunc = null), - (e.licenseXhrSetup = e.licenseResponseCallback = - void 0), - (e.drmSystems = e.drmSystemOptions = {}), - (this.hls = - this.onMediaEncrypted = - this.onWaitingForKey = - this.keyIdToKeySessionPromise = - null), - (this.config = null); - }), - (t.registerListeners = function () { - this.hls.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), - this.hls.on( - E.MEDIA_DETACHED, - this.onMediaDetached, - this - ), - this.hls.on( - E.MANIFEST_LOADING, - this.onManifestLoading, - this - ), - this.hls.on( - E.MANIFEST_LOADED, - this.onManifestLoaded, - this - ); - }), - (t.unregisterListeners = function () { - this.hls.off( - E.MEDIA_ATTACHED, - this.onMediaAttached, - this - ), - this.hls.off( - E.MEDIA_DETACHED, - this.onMediaDetached, - this - ), - this.hls.off( - E.MANIFEST_LOADING, - this.onManifestLoading, - this - ), - this.hls.off( - E.MANIFEST_LOADED, - this.onManifestLoaded, - this - ); - }), - (t.getLicenseServerUrl = function (e) { - var t = this.config, - r = t.drmSystems, - i = t.widevineLicenseUrl, - n = r[e]; - if (n) return n.licenseUrl; - if (e === K.WIDEVINE && i) return i; - throw new Error( - 'no license server URL configured for key-system "' + - e + - '"' - ); - }), - (t.getServerCertificateUrl = function (e) { - var t = this.config.drmSystems[e]; - if (t) return t.serverCertificateUrl; - this.log( - 'No Server Certificate in config.drmSystems["' + - e + - '"]' - ); - }), - (t.attemptKeySystemAccess = function (e) { - var t = this, - r = this.hls.levels, - i = function (e, t, r) { - return !!e && r.indexOf(e) === t; - }, - n = r - .map(function (e) { - return e.audioCodec; - }) - .filter(i), - s = r - .map(function (e) { - return e.videoCodec; - }) - .filter(i); - return ( - n.length + s.length === 0 && s.push("avc1.42e01e"), - new Promise(function (r, i) { - !(function e(a) { - var o = a.shift(); - t.getMediaKeysPromise(o, n, s) - .then(function (e) { - return r({ keySystem: o, mediaKeys: e }); - }) - .catch(function (t) { - a.length - ? e(a) - : i( - t instanceof Os - ? t - : new Os( - { - type: S.KEY_SYSTEM_ERROR, - details: T.KEY_SYSTEM_NO_ACCESS, - error: t, - fatal: !0, - }, - t.message - ) - ); - }); - })(e); - }) - ); - }), - (t.requestMediaKeySystemAccess = function (e, t) { - var r = this.config.requestMediaKeySystemAccessFunc; - if ("function" != typeof r) { - var i = - "Configured requestMediaKeySystemAccess is not a function " + - r; - return ( - null === Z && - "http:" === self.location.protocol && - (i = - "navigator.requestMediaKeySystemAccess is not available over insecure protocol " + - location.protocol), - Promise.reject(new Error(i)) - ); - } - return r(e, t); - }), - (t.getMediaKeysPromise = function (e, t, r) { - var i = this, - n = (function (e, t, r, i) { - var n; - switch (e) { - case K.FAIRPLAY: - n = ["cenc", "sinf"]; - break; - case K.WIDEVINE: - case K.PLAYREADY: - n = ["cenc"]; - break; - case K.CLEARKEY: - n = ["cenc", "keyids"]; - break; - default: - throw new Error("Unknown key-system: " + e); - } - return (function (e, t, r, i) { - return [ - { - initDataTypes: e, - persistentState: - i.persistentState || "optional", - distinctiveIdentifier: - i.distinctiveIdentifier || "optional", - sessionTypes: i.sessionTypes || [ - i.sessionType || "temporary", - ], - audioCapabilities: t.map(function (e) { - return { - contentType: - 'audio/mp4; codecs="' + e + '"', - robustness: i.audioRobustness || "", - encryptionScheme: - i.audioEncryptionScheme || null, - }; - }), - videoCapabilities: r.map(function (e) { - return { - contentType: - 'video/mp4; codecs="' + e + '"', - robustness: i.videoRobustness || "", - encryptionScheme: - i.videoEncryptionScheme || null, - }; - }), - }, - ]; - })(n, t, r, i); - })(e, t, r, this.config.drmSystemOptions), - s = this.keySystemAccessPromises[e], - a = null == s ? void 0 : s.keySystemAccess; - if (!a) { - this.log( - 'Requesting encrypted media "' + - e + - '" key-system access with config: ' + - JSON.stringify(n) - ), - (a = this.requestMediaKeySystemAccess(e, n)); - var o = (this.keySystemAccessPromises[e] = { - keySystemAccess: a, - }); - return ( - a.catch(function (t) { - i.log( - 'Failed to obtain access to key-system "' + - e + - '": ' + - t - ); - }), - a.then(function (t) { - i.log( - 'Access for key-system "' + - t.keySystem + - '" obtained' - ); - var r = i.fetchServerCertificate(e); - return ( - i.log('Create media-keys for "' + e + '"'), - (o.mediaKeys = t - .createMediaKeys() - .then(function (t) { - return ( - i.log('Media-keys created for "' + e + '"'), - r.then(function (r) { - return r - ? i.setMediaKeysServerCertificate( - t, - e, - r - ) - : t; - }) - ); - })), - o.mediaKeys.catch(function (t) { - i.error( - 'Failed to create media-keys for "' + - e + - '"}: ' + - t - ); - }), - o.mediaKeys - ); - }) - ); - } - return a.then(function () { - return s.mediaKeys; - }); - }), - (t.createMediaKeySessionContext = function (e) { - var t = e.decryptdata, - r = e.keySystem, - i = e.mediaKeys; - this.log( - 'Creating key-system session "' + - r + - '" keyId: ' + - ve(t.keyId || []) - ); - var n = i.createSession(), - s = { - decryptdata: t, - keySystem: r, - mediaKeys: i, - mediaKeysSession: n, - keyStatus: "status-pending", - }; - return this.mediaKeySessions.push(s), s; - }), - (t.renewKeySession = function (e) { - var t = e.decryptdata; - if (t.pssh) { - var r = this.createMediaKeySessionContext(e), - i = this.getKeyIdString(t); - this.keyIdToKeySessionPromise[i] = - this.generateRequestWithPreferredKeySession( - r, - "cenc", - t.pssh, - "expired" - ); - } else - this.warn( - "Could not renew expired session. Missing pssh initData." - ); - this.removeSession(e); - }), - (t.getKeyIdString = function (e) { - if (!e) - throw new Error( - "Could not read keyId of undefined decryptdata" - ); - if (null === e.keyId) throw new Error("keyId is null"); - return ve(e.keyId); - }), - (t.updateKeySession = function (e, t) { - var r, - i = e.mediaKeysSession; - return ( - this.log( - 'Updating key-session "' + - i.sessionId + - '" for keyID ' + - ve( - (null == (r = e.decryptdata) - ? void 0 - : r.keyId) || [] - ) + - "\n } (data length: " + - (t ? t.byteLength : t) + - ")" - ), - i.update(t) - ); - }), - (t.selectKeySystemFormat = function (e) { - var t = Object.keys(e.levelkeys || {}); - return ( - this.keyFormatPromise || - (this.log( - "Selecting key-system from fragment (sn: " + - e.sn + - " " + - e.type + - ": " + - e.level + - ") key formats " + - t.join(", ") - ), - (this.keyFormatPromise = - this.getKeyFormatPromise(t))), - this.keyFormatPromise - ); - }), - (t.getKeyFormatPromise = function (e) { - var t = this; - return new Promise(function (r, i) { - var n = Q(t.config), - s = e.map(Y).filter(function (e) { - return !!e && -1 !== n.indexOf(e); - }); - return t - .getKeySystemSelectionPromise(s) - .then(function (e) { - var t = e.keySystem, - n = X(t); - n - ? r(n) - : i( - new Error( - 'Unable to find format for key-system "' + - t + - '"' - ) - ); - }) - .catch(i); - }); - }), - (t.loadKey = function (e) { - var t = this, - r = e.keyInfo.decryptdata, - i = this.getKeyIdString(r), - n = - "(keyId: " + - i + - ' format: "' + - r.keyFormat + - '" method: ' + - r.method + - " uri: " + - r.uri + - ")"; - this.log("Starting session for key " + n); - var s = this.keyIdToKeySessionPromise[i]; - return ( - s || - (s = this.keyIdToKeySessionPromise[i] = - this.getKeySystemForKeyPromise(r).then(function ( - i - ) { - var s = i.keySystem, - a = i.mediaKeys; - return ( - t.throwIfDestroyed(), - t.log( - "Handle encrypted media sn: " + - e.frag.sn + - " " + - e.frag.type + - ": " + - e.frag.level + - " using key " + - n - ), - t.attemptSetMediaKeys(s, a).then(function () { - t.throwIfDestroyed(); - var e = t.createMediaKeySessionContext({ - keySystem: s, - mediaKeys: a, - decryptdata: r, - }); - return t.generateRequestWithPreferredKeySession( - e, - "cenc", - r.pssh, - "playlist-key" - ); - }) - ); - })).catch(function (e) { - return t.handleError(e); - }), - s - ); - }), - (t.throwIfDestroyed = function (e) { - if (!this.hls) throw new Error("invalid state"); - }), - (t.handleError = function (e) { - this.hls && - (this.error(e.message), - e instanceof Os - ? this.hls.trigger(E.ERROR, e.data) - : this.hls.trigger(E.ERROR, { - type: S.KEY_SYSTEM_ERROR, - details: T.KEY_SYSTEM_NO_KEYS, - error: e, - fatal: !0, - })); - }), - (t.getKeySystemForKeyPromise = function (e) { - var t = this.getKeyIdString(e), - r = this.keyIdToKeySessionPromise[t]; - if (!r) { - var i = Y(e.keyFormat), - n = i ? [i] : Q(this.config); - return this.attemptKeySystemAccess(n); - } - return r; - }), - (t.getKeySystemSelectionPromise = function (e) { - if ((e.length || (e = Q(this.config)), 0 === e.length)) - throw new Os( - { - type: S.KEY_SYSTEM_ERROR, - details: T.KEY_SYSTEM_NO_CONFIGURED_LICENSE, - fatal: !0, - }, - "Missing key-system license configuration options " + - JSON.stringify({ - drmSystems: this.config.drmSystems, - }) - ); - return this.attemptKeySystemAccess(e); - }), - (t._onMediaEncrypted = function (e) { - var t = this, - r = e.initDataType, - i = e.initData; - if ( - (this.debug( - '"' + e.type + '" event: init data type: "' + r + '"' - ), - null !== i) - ) { - var n, s; - if ( - "sinf" === r && - this.config.drmSystems[K.FAIRPLAY] - ) { - var a = Te(new Uint8Array(i)); - try { - var o = G(JSON.parse(a).sinf), - l = xe(new Uint8Array(o)); - if (!l) return; - (n = l.subarray(8, 24)), (s = K.FAIRPLAY); - } catch (e) { - return void this.warn( - 'Failed to parse sinf "encrypted" event message initData' - ); - } - } else { - var h = (function (e) { - if ( - !(e instanceof ArrayBuffer) || - e.byteLength < 32 - ) - return null; - var t = { - version: 0, - systemId: "", - kids: null, - data: null, - }, - r = new DataView(e), - i = r.getUint32(0); - if (e.byteLength !== i && i > 44) return null; - if (1886614376 !== r.getUint32(4)) return null; - if ( - ((t.version = r.getUint32(8) >>> 24), - t.version > 1) - ) - return null; - t.systemId = ve(new Uint8Array(e, 12, 16)); - var n = r.getUint32(28); - if (0 === t.version) { - if (i - 32 < n) return null; - t.data = new Uint8Array(e, 32, n); - } else if (1 === t.version) { - t.kids = []; - for (var s = 0; s < n; s++) - t.kids.push(new Uint8Array(e, 32 + 16 * s, 16)); - } - return t; - })(i); - if (null === h) return; - 0 === h.version && - h.systemId === z && - h.data && - (n = h.data.subarray(8, 24)), - (s = (function (e) { - if (e === z) return K.WIDEVINE; - })(h.systemId)); - } - if (s && n) { - for ( - var u, - d = ve(n), - c = this.keyIdToKeySessionPromise, - f = this.mediaKeySessions, - g = c[d], - p = function () { - var e = f[m], - s = e.decryptdata; - if (s.pssh || !s.keyId) return 0; - var a = ve(s.keyId); - return d === a || - -1 !== s.uri.replace(/-/g, "").indexOf(d) - ? ((g = c[a]), - delete c[a], - (s.pssh = new Uint8Array(i)), - (s.keyId = n), - (g = c[d] = - g.then(function () { - return t.generateRequestWithPreferredKeySession( - e, - r, - i, - "encrypted-event-key-match" - ); - })), - 1) - : void 0; - }, - m = 0; - m < f.length && (0 === (u = p()) || 1 !== u); - m++ - ); - g || - (g = c[d] = - this.getKeySystemSelectionPromise([s]).then( - function (e) { - var s, - a = e.keySystem, - o = e.mediaKeys; - t.throwIfDestroyed(); - var l = new $e( - "ISO-23001-7", - d, - null != (s = X(a)) ? s : "" - ); - return ( - (l.pssh = new Uint8Array(i)), - (l.keyId = n), - t - .attemptSetMediaKeys(a, o) - .then(function () { - t.throwIfDestroyed(); - var e = t.createMediaKeySessionContext({ - decryptdata: l, - keySystem: a, - mediaKeys: o, - }); - return t.generateRequestWithPreferredKeySession( - e, - r, - i, - "encrypted-event-no-match" - ); - }) - ); - } - )), - g.catch(function (e) { - return t.handleError(e); - }); - } - } - }), - (t._onWaitingForKey = function (e) { - this.log('"' + e.type + '" event'); - }), - (t.attemptSetMediaKeys = function (e, t) { - var r = this, - i = this.setMediaKeysQueue.slice(); - this.log('Setting media-keys for "' + e + '"'); - var n = Promise.all(i).then(function () { - if (!r.media) - throw new Error( - "Attempted to set mediaKeys without media element attached" - ); - return r.media.setMediaKeys(t); - }); - return ( - this.setMediaKeysQueue.push(n), - n.then(function () { - r.log('Media-keys set for "' + e + '"'), - i.push(n), - (r.setMediaKeysQueue = r.setMediaKeysQueue.filter( - function (e) { - return -1 === i.indexOf(e); - } - )); - }) - ); - }), - (t.generateRequestWithPreferredKeySession = function ( - e, - t, - r, - i - ) { - var n, - s, - a = this, - o = - null == (n = this.config.drmSystems) || - null == (s = n[e.keySystem]) - ? void 0 - : s.generateRequest; - if (o) - try { - var l = o.call(this.hls, t, r, e); - if (!l) - throw new Error( - "Invalid response from configured generateRequest filter" - ); - (t = l.initDataType), - (r = e.decryptdata.pssh = - l.initData ? new Uint8Array(l.initData) : null); - } catch (e) { - var h; - if ( - (this.warn(e.message), - null != (h = this.hls) && h.config.debug) - ) - throw e; - } - if (null === r) - return ( - this.log( - 'Skipping key-session request for "' + - i + - '" (no initData)' - ), - Promise.resolve(e) - ); - var u = this.getKeyIdString(e.decryptdata); - this.log( - 'Generating key-session request for "' + - i + - '": ' + - u + - " (init data type: " + - t + - " length: " + - (r ? r.byteLength : null) + - ")" - ); - var d = new vn(), - c = (e._onmessage = function (t) { - var r = e.mediaKeysSession; - if (r) { - var i = t.messageType, - n = t.message; - a.log( - '"' + - i + - '" message event for session "' + - r.sessionId + - '" message size: ' + - n.byteLength - ), - "license-request" === i || "license-renewal" === i - ? a.renewLicense(e, n).catch(function (e) { - a.handleError(e), d.emit("error", e); - }) - : "license-release" === i - ? e.keySystem === K.FAIRPLAY && - (a.updateKeySession(e, H("acknowledged")), - a.removeSession(e)) - : a.warn( - 'unhandled media key message type "' + - i + - '"' - ); - } else d.emit("error", new Error("invalid state")); - }), - f = (e._onkeystatuseschange = function (t) { - if (e.mediaKeysSession) { - a.onKeyStatusChange(e); - var r = e.keyStatus; - d.emit("keyStatus", r), - "expired" === r && - (a.warn(e.keySystem + " expired for key " + u), - a.renewKeySession(e)); - } else d.emit("error", new Error("invalid state")); - }); - e.mediaKeysSession.addEventListener("message", c), - e.mediaKeysSession.addEventListener( - "keystatuseschange", - f - ); - var g = new Promise(function (e, t) { - d.on("error", t), - d.on("keyStatus", function (r) { - r.startsWith("usable") - ? e() - : "output-restricted" === r - ? t( - new Os( - { - type: S.KEY_SYSTEM_ERROR, - details: - T.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED, - fatal: !1, - }, - "HDCP level output restricted" - ) - ) - : "internal-error" === r - ? t( - new Os( - { - type: S.KEY_SYSTEM_ERROR, - details: - T.KEY_SYSTEM_STATUS_INTERNAL_ERROR, - fatal: !0, - }, - 'key status changed to "' + r + '"' - ) - ) - : "expired" === r - ? t( - new Error( - "key expired while generating request" - ) - ) - : a.warn( - 'unhandled key status change "' + r + '"' - ); - }); - }); - return e.mediaKeysSession - .generateRequest(t, r) - .then(function () { - var t; - a.log( - 'Request generated for key-session "' + - (null == (t = e.mediaKeysSession) - ? void 0 - : t.sessionId) + - '" keyId: ' + - u - ); - }) - .catch(function (e) { - throw new Os( - { - type: S.KEY_SYSTEM_ERROR, - details: T.KEY_SYSTEM_NO_SESSION, - error: e, - fatal: !1, - }, - "Error generating key-session request: " + e - ); - }) - .then(function () { - return g; - }) - .catch(function (t) { - throw (d.removeAllListeners(), a.removeSession(e), t); - }) - .then(function () { - return d.removeAllListeners(), e; - }); - }), - (t.onKeyStatusChange = function (e) { - var t = this; - e.mediaKeysSession.keyStatuses.forEach(function (r, i) { - t.log( - 'key status change "' + - r + - '" for keyStatuses keyId: ' + - ve( - "buffer" in i - ? new Uint8Array( - i.buffer, - i.byteOffset, - i.byteLength - ) - : new Uint8Array(i) - ) + - " session keyId: " + - ve(new Uint8Array(e.decryptdata.keyId || [])) + - " uri: " + - e.decryptdata.uri - ), - (e.keyStatus = r); - }); - }), - (t.fetchServerCertificate = function (e) { - var t = this.config, - r = new (0, t.loader)(t), - n = this.getServerCertificateUrl(e); - return n - ? (this.log( - 'Fetching server certificate for "' + e + '"' - ), - new Promise(function (s, a) { - var o = { responseType: "arraybuffer", url: n }, - l = t.certLoadPolicy.default, - h = { - loadPolicy: l, - timeout: l.maxLoadTimeMs, - maxRetry: 0, - retryDelay: 0, - maxRetryDelay: 0, - }, - u = { - onSuccess: function (e, t, r, i) { - s(e.data); - }, - onError: function (t, r, s, l) { - a( - new Os( - { - type: S.KEY_SYSTEM_ERROR, - details: - T.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED, - fatal: !0, - networkDetails: s, - response: i( - { url: o.url, data: void 0 }, - t - ), - }, - '"' + - e + - '" certificate request failed (' + - n + - "). Status: " + - t.code + - " (" + - t.text + - ")" - ) - ); - }, - onTimeout: function (t, r, i) { - a( - new Os( - { - type: S.KEY_SYSTEM_ERROR, - details: - T.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED, - fatal: !0, - networkDetails: i, - response: { url: o.url, data: void 0 }, - }, - '"' + - e + - '" certificate request timed out (' + - n + - ")" - ) - ); - }, - onAbort: function (e, t, r) { - a(new Error("aborted")); - }, - }; - r.load(o, h, u); - })) - : Promise.resolve(); - }), - (t.setMediaKeysServerCertificate = function (e, t, r) { - var i = this; - return new Promise(function (n, s) { - e.setServerCertificate(r) - .then(function (s) { - i.log( - "setServerCertificate " + - (s ? "success" : "not supported by CDM") + - " (" + - (null == r ? void 0 : r.byteLength) + - ') on "' + - t + - '"' - ), - n(e); - }) - .catch(function (e) { - s( - new Os( - { - type: S.KEY_SYSTEM_ERROR, - details: - T.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED, - error: e, - fatal: !0, - }, - e.message - ) - ); - }); - }); - }), - (t.renewLicense = function (e, t) { - var r = this; - return this.requestLicense(e, new Uint8Array(t)).then( - function (t) { - return r - .updateKeySession(e, new Uint8Array(t)) - .catch(function (e) { - throw new Os( - { - type: S.KEY_SYSTEM_ERROR, - details: T.KEY_SYSTEM_SESSION_UPDATE_FAILED, - error: e, - fatal: !0, - }, - e.message - ); - }); - } - ); - }), - (t.unpackPlayReadyKeyMessage = function (e, t) { - var r = String.fromCharCode.apply( - null, - new Uint16Array(t.buffer) - ); - if (!r.includes("PlayReadyKeyMessage")) - return ( - e.setRequestHeader( - "Content-Type", - "text/xml; charset=utf-8" - ), - t - ); - var i = new DOMParser().parseFromString( - r, - "application/xml" - ), - n = i.querySelectorAll("HttpHeader"); - if (n.length > 0) - for (var s, a = 0, o = n.length; a < o; a++) { - var l, - h, - u = - null == (l = (s = n[a]).querySelector("name")) - ? void 0 - : l.textContent, - d = - null == (h = s.querySelector("value")) - ? void 0 - : h.textContent; - u && d && e.setRequestHeader(u, d); - } - var c = i.querySelector("Challenge"), - f = null == c ? void 0 : c.textContent; - if (!f) - throw new Error( - "Cannot find in key message" - ); - return H(atob(f)); - }), - (t.setupLicenseXHR = function (e, t, r, i) { - var n = this, - s = this.config.licenseXhrSetup; - return s - ? Promise.resolve() - .then(function () { - if (!r.decryptdata) - throw new Error("Key removed"); - return s.call(n.hls, e, t, r, i); - }) - .catch(function (a) { - if (!r.decryptdata) throw a; - return ( - e.open("POST", t, !0), s.call(n.hls, e, t, r, i) - ); - }) - .then(function (r) { - return ( - e.readyState || e.open("POST", t, !0), - { xhr: e, licenseChallenge: r || i } - ); - }) - : (e.open("POST", t, !0), - Promise.resolve({ xhr: e, licenseChallenge: i })); - }), - (t.requestLicense = function (e, t) { - var r = this, - i = this.config.keyLoadPolicy.default; - return new Promise(function (n, s) { - var a = r.getLicenseServerUrl(e.keySystem); - r.log("Sending license request to URL: " + a); - var o = new XMLHttpRequest(); - (o.responseType = "arraybuffer"), - (o.onreadystatechange = function () { - if (!r.hls || !e.mediaKeysSession) - return s(new Error("invalid state")); - if (4 === o.readyState) - if (200 === o.status) { - r._requestLicenseFailureCount = 0; - var l = o.response; - r.log( - "License received " + - (l instanceof ArrayBuffer - ? l.byteLength - : l) - ); - var h = r.config.licenseResponseCallback; - if (h) - try { - l = h.call(r.hls, o, a, e); - } catch (e) { - r.error(e); - } - n(l); - } else { - var u = i.errorRetry, - d = u ? u.maxNumRetry : 0; - if ( - (r._requestLicenseFailureCount++, - r._requestLicenseFailureCount > d || - (o.status >= 400 && o.status < 500)) - ) - s( - new Os( - { - type: S.KEY_SYSTEM_ERROR, - details: - T.KEY_SYSTEM_LICENSE_REQUEST_FAILED, - fatal: !0, - networkDetails: o, - response: { - url: a, - data: void 0, - code: o.status, - text: o.statusText, - }, - }, - "License Request XHR failed (" + - a + - "). Status: " + - o.status + - " (" + - o.statusText + - ")" - ) - ); - else { - var c = d - r._requestLicenseFailureCount + 1; - r.warn( - "Retrying license request, " + - c + - " attempts left" - ), - r.requestLicense(e, t).then(n, s); - } - } - }), - e.licenseXhr && - e.licenseXhr.readyState !== XMLHttpRequest.DONE && - e.licenseXhr.abort(), - (e.licenseXhr = o), - r.setupLicenseXHR(o, a, e, t).then(function (t) { - var i = t.xhr, - n = t.licenseChallenge; - e.keySystem == K.PLAYREADY && - (n = r.unpackPlayReadyKeyMessage(i, n)), - i.send(n); - }); - }); - }), - (t.onMediaAttached = function (e, t) { - if (this.config.emeEnabled) { - var r = t.media; - (this.media = r), - r.addEventListener( - "encrypted", - this.onMediaEncrypted - ), - r.addEventListener( - "waitingforkey", - this.onWaitingForKey - ); - } - }), - (t.onMediaDetached = function () { - var t = this, - r = this.media, - i = this.mediaKeySessions; - r && - (r.removeEventListener( - "encrypted", - this.onMediaEncrypted - ), - r.removeEventListener( - "waitingforkey", - this.onWaitingForKey - ), - (this.media = null)), - (this._requestLicenseFailureCount = 0), - (this.setMediaKeysQueue = []), - (this.mediaKeySessions = []), - (this.keyIdToKeySessionPromise = {}), - $e.clearKeyUriToKeyIdMap(); - var n = i.length; - e.CDMCleanupPromise = Promise.all( - i - .map(function (e) { - return t.removeSession(e); - }) - .concat( - null == r - ? void 0 - : r.setMediaKeys(null).catch(function (e) { - t.log("Could not clear media keys: " + e); - }) - ) - ) - .then(function () { - n && - (t.log( - "finished closing key sessions and clearing media keys" - ), - (i.length = 0)); - }) - .catch(function (e) { - t.log( - "Could not close sessions and clear media keys: " + - e - ); - }); - }), - (t.onManifestLoading = function () { - this.keyFormatPromise = null; - }), - (t.onManifestLoaded = function (e, t) { - var r = t.sessionKeys; - if ( - r && - this.config.emeEnabled && - !this.keyFormatPromise - ) { - var i = r.reduce(function (e, t) { - return ( - -1 === e.indexOf(t.keyFormat) && - e.push(t.keyFormat), - e - ); - }, []); - this.log( - "Selecting key-system from session-keys " + - i.join(", ") - ), - (this.keyFormatPromise = this.getKeyFormatPromise(i)); - } - }), - (t.removeSession = function (e) { - var t = this, - r = e.mediaKeysSession, - i = e.licenseXhr; - if (r) { - this.log( - "Remove licenses and keys and close session " + - r.sessionId - ), - e._onmessage && - (r.removeEventListener("message", e._onmessage), - (e._onmessage = void 0)), - e._onkeystatuseschange && - (r.removeEventListener( - "keystatuseschange", - e._onkeystatuseschange - ), - (e._onkeystatuseschange = void 0)), - i && - i.readyState !== XMLHttpRequest.DONE && - i.abort(), - (e.mediaKeysSession = - e.decryptdata = - e.licenseXhr = - void 0); - var n = this.mediaKeySessions.indexOf(e); - return ( - n > -1 && this.mediaKeySessions.splice(n, 1), - r - .remove() - .catch(function (e) { - t.log("Could not remove session: " + e); - }) - .then(function () { - return r.close(); - }) - .catch(function (e) { - t.log("Could not close session: " + e); - }) - ); - } - }), - e - ); - })(); - Cs.CDMCleanupPromise = void 0; - var ks, - Ds, - Ms, - xs, - Os = (function (e) { - function t(t, r) { - var i; - return ( - ((i = e.call(this, r) || this).data = void 0), - t.error || (t.error = new Error(r)), - (i.data = t), - (t.err = t.error), - i - ); - } - return l(t, e), t; - })(c(Error)); - !(function (e) { - (e.MANIFEST = "m"), - (e.AUDIO = "a"), - (e.VIDEO = "v"), - (e.MUXED = "av"), - (e.INIT = "i"), - (e.CAPTION = "c"), - (e.TIMED_TEXT = "tt"), - (e.KEY = "k"), - (e.OTHER = "o"); - })(ks || (ks = {})), - (function (e) { - (e.DASH = "d"), - (e.HLS = "h"), - (e.SMOOTH = "s"), - (e.OTHER = "o"); - })(Ds || (Ds = {})), - (function (e) { - (e.OBJECT = "CMCD-Object"), - (e.REQUEST = "CMCD-Request"), - (e.SESSION = "CMCD-Session"), - (e.STATUS = "CMCD-Status"); - })(Ms || (Ms = {})); - var Fs = - (((xs = {})[Ms.OBJECT] = ["br", "d", "ot", "tb"]), - (xs[Ms.REQUEST] = ["bl", "dl", "mtp", "nor", "nrr", "su"]), - (xs[Ms.SESSION] = ["cid", "pr", "sf", "sid", "st", "v"]), - (xs[Ms.STATUS] = ["bs", "rtp"]), - xs), - Ns = function e(t, r) { - (this.value = void 0), - (this.params = void 0), - Array.isArray(t) && - (t = t.map(function (t) { - return t instanceof e ? t : new e(t); - })), - (this.value = t), - (this.params = r); - }, - Bs = function (e) { - (this.description = void 0), (this.description = e); - }, - Us = "Dict"; - var Gs = "Bare Item", - Hs = "Boolean", - $s = "Byte Sequence", - Ks = "Decimal", - Ws = "Integer", - Vs = /[\x00-\x1f\x7f]+/, - qs = "Token", - js = "Key"; - function Ys(e, t, r) { - return (function (e, t, r, i) { - return new Error( - "failed to " + - e + - ' "' + - ((n = t), - (Array.isArray(n) - ? JSON.stringify(n) - : n instanceof Map - ? "Map{}" - : n instanceof Set - ? "Set{}" - : "object" == typeof n - ? JSON.stringify(n) - : String(n)) + '" as ') + - r, - { cause: i } - ); - var n; - })("serialize", e, t, r); - } - function zs(e) { - if ( - (function (e) { - return e < -999999999999999 || 999999999999999 < e; - })(e) - ) - throw Ys(e, Ws); - return e.toString(); - } - function Xs(e, t) { - if (e < 0) return -Xs(-e, t); - var r = Math.pow(10, t); - if (Math.abs(((e * r) % 1) - 0.5) < Number.EPSILON) { - var i = Math.floor(e * r); - return (i % 2 == 0 ? i : i + 1) / r; - } - return Math.round(e * r) / r; - } - function Qs(e) { - var t = Xs(e, 3); - if (Math.floor(Math.abs(t)).toString().length > 12) - throw Ys(e, Ks); - var r = t.toString(); - return r.includes(".") ? r : r + ".0"; - } - var Js = "String"; - function Zs(e) { - var t, - r = (t = e).description || t.toString().slice(7, -1); - if (!1 === /^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r)) - throw Ys(r, qs); - return r; - } - function ea(e) { - switch (typeof e) { - case "number": - if (!m(e)) throw Ys(e, Gs); - return Number.isInteger(e) ? zs(e) : Qs(e); - case "string": - return (function (e) { - if (Vs.test(e)) throw Ys(e, Js); - return ( - '"' + - e.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + - '"' - ); - })(e); - case "symbol": - return Zs(e); - case "boolean": - return (function (e) { - if ("boolean" != typeof e) throw Ys(e, Hs); - return e ? "?1" : "?0"; - })(e); - case "object": - if (e instanceof Date) - return (function (e) { - return "@" + zs(e.getTime() / 1e3); - })(e); - if (e instanceof Uint8Array) - return (function (e) { - if (!1 === ArrayBuffer.isView(e)) throw Ys(e, $s); - return ( - ":" + - ((t = e), - btoa(String.fromCharCode.apply(String, t)) + ":") - ); - var t; - })(e); - if (e instanceof Bs) return Zs(e); - default: - throw Ys(e, Gs); - } - } - function ta(e) { - if (!1 === /^[a-z*][a-z0-9\-_.*]*$/.test(e)) throw Ys(e, js); - return e; - } - function ra(e) { - return null == e - ? "" - : Object.entries(e) - .map(function (e) { - var t = e[0], - r = e[1]; - return !0 === r - ? ";" + ta(t) - : ";" + ta(t) + "=" + ea(r); - }) - .join(""); - } - function ia(e) { - return e instanceof Ns - ? "" + ea(e.value) + ra(e.params) - : ea(e); - } - var na = function (e) { - return "ot" === e || "sf" === e || "st" === e; - }, - sa = function (e) { - return "number" == typeof e - ? m(e) - : null != e && "" !== e && !1 !== e; - }, - aa = function (e) { - return Math.round(e); - }, - oa = function (e) { - return 100 * aa(e / 100); - }, - la = { - br: aa, - d: aa, - bl: oa, - dl: oa, - mtp: oa, - nor: function (e, t) { - return ( - null != t && - t.baseUrl && - (e = (function (e, t) { - var r = new URL(e), - i = new URL(t); - if (r.origin !== i.origin) return e; - for ( - var n = r.pathname.split("/").slice(1), - s = i.pathname.split("/").slice(1, -1); - n[0] === s[0]; - - ) - n.shift(), s.shift(); - for (; s.length; ) s.shift(), n.unshift(".."); - return n.join("/"); - })(e, t.baseUrl)), - encodeURIComponent(e) - ); - }, - rtp: oa, - tb: aa, - }; - function ha(e, t) { - return ( - void 0 === t && (t = {}), - e - ? (function (e, t) { - return (function (e, t) { - var r; - if ( - (void 0 === t && (t = { whitespace: !0 }), - "object" != typeof e) - ) - throw Ys(e, Us); - var i = - e instanceof Map - ? e.entries() - : Object.entries(e), - n = null != (r = t) && r.whitespace ? " " : ""; - return Array.from(i) - .map(function (e) { - var t = e[0], - r = e[1]; - r instanceof Ns == 0 && (r = new Ns(r)); - var i, - n = ta(t); - return ( - !0 === r.value - ? (n += ra(r.params)) - : ((n += "="), - Array.isArray(r.value) - ? (n += - "(" + - (i = r).value.map(ia).join(" ") + - ")" + - ra(i.params)) - : (n += ia(r))), - n - ); - }) - .join("," + n); - })(e, t); - })( - (function (e, t) { - var r = {}; - if (null == e || "object" != typeof e) return r; - var i = Object.keys(e).sort(), - n = o({}, la, null == t ? void 0 : t.formatters), - s = null == t ? void 0 : t.filter; - return ( - i.forEach(function (i) { - if (null == s || !s(i)) { - var a = e[i], - o = n[i]; - o && (a = o(a, t)), - ("v" === i && 1 === a) || - ("pr" == i && 1 === a) || - (sa(a) && - (na(i) && - "string" == typeof a && - (a = new Bs(a)), - (r[i] = a))); - } - }), - r - ); - })(e, t), - o({ whitespace: !1 }, t) - ) - : "" - ); - } - var ua = /CMCD=[^&#]+/; - var da = (function () { - function e(e) { - var t = this; - (this.hls = void 0), - (this.config = void 0), - (this.media = void 0), - (this.sid = void 0), - (this.cid = void 0), - (this.useHeaders = !1), - (this.includeKeys = void 0), - (this.initialized = !1), - (this.starved = !1), - (this.buffering = !0), - (this.audioBuffer = void 0), - (this.videoBuffer = void 0), - (this.onWaiting = function () { - t.initialized && (t.starved = !0), (t.buffering = !0); - }), - (this.onPlaying = function () { - t.initialized || (t.initialized = !0), - (t.buffering = !1); - }), - (this.applyPlaylistData = function (e) { - try { - t.apply(e, { ot: ks.MANIFEST, su: !t.initialized }); - } catch (e) { - A.warn("Could not generate manifest CMCD data.", e); - } - }), - (this.applyFragmentData = function (e) { - try { - var r = e.frag, - i = t.hls.levels[r.level], - n = t.getObjectType(r), - s = { d: 1e3 * r.duration, ot: n }; - (n !== ks.VIDEO && n !== ks.AUDIO && n != ks.MUXED) || - ((s.br = i.bitrate / 1e3), - (s.tb = t.getTopBandwidth(n) / 1e3), - (s.bl = t.getBufferLength(n))), - t.apply(e, s); - } catch (e) { - A.warn("Could not generate segment CMCD data.", e); - } - }), - (this.hls = e); - var r = (this.config = e.config), - i = r.cmcd; - null != i && - ((r.pLoader = this.createPlaylistLoader()), - (r.fLoader = this.createFragmentLoader()), - (this.sid = - i.sessionId || - (function () { - try { - return crypto.randomUUID(); - } catch (i) { - try { - var e = URL.createObjectURL(new Blob()), - t = e.toString(); - return ( - URL.revokeObjectURL(e), - t.slice(t.lastIndexOf("/") + 1) - ); - } catch (e) { - var r = new Date().getTime(); - return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace( - /[xy]/g, - function (e) { - var t = (r + 16 * Math.random()) % 16 | 0; - return ( - (r = Math.floor(r / 16)), - ("x" == e ? t : (3 & t) | 8).toString(16) - ); - } - ); - } - } - })()), - (this.cid = i.contentId), - (this.useHeaders = !0 === i.useHeaders), - (this.includeKeys = i.includeKeys), - this.registerListeners()); - } - var t = e.prototype; - return ( - (t.registerListeners = function () { - var e = this.hls; - e.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.on(E.MEDIA_DETACHED, this.onMediaDetached, this), - e.on(E.BUFFER_CREATED, this.onBufferCreated, this); - }), - (t.unregisterListeners = function () { - var e = this.hls; - e.off(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.off(E.MEDIA_DETACHED, this.onMediaDetached, this), - e.off(E.BUFFER_CREATED, this.onBufferCreated, this); - }), - (t.destroy = function () { - this.unregisterListeners(), - this.onMediaDetached(), - (this.hls = - this.config = - this.audioBuffer = - this.videoBuffer = - null), - (this.onWaiting = this.onPlaying = null); - }), - (t.onMediaAttached = function (e, t) { - (this.media = t.media), - this.media.addEventListener("waiting", this.onWaiting), - this.media.addEventListener("playing", this.onPlaying); - }), - (t.onMediaDetached = function () { - this.media && - (this.media.removeEventListener( - "waiting", - this.onWaiting - ), - this.media.removeEventListener( - "playing", - this.onPlaying - ), - (this.media = null)); - }), - (t.onBufferCreated = function (e, t) { - var r, i; - (this.audioBuffer = - null == (r = t.tracks.audio) ? void 0 : r.buffer), - (this.videoBuffer = - null == (i = t.tracks.video) ? void 0 : i.buffer); - }), - (t.createData = function () { - var e; - return { - v: 1, - sf: Ds.HLS, - sid: this.sid, - cid: this.cid, - pr: null == (e = this.media) ? void 0 : e.playbackRate, - mtp: this.hls.bandwidthEstimate / 1e3, - }; - }), - (t.apply = function (e, t) { - void 0 === t && (t = {}), o(t, this.createData()); - var r = - t.ot === ks.INIT || - t.ot === ks.VIDEO || - t.ot === ks.MUXED; - this.starved && - r && - ((t.bs = !0), (t.su = !0), (this.starved = !1)), - null == t.su && (t.su = this.buffering); - var i = this.includeKeys; - i && - (t = Object.keys(t).reduce(function (e, r) { - return i.includes(r) && (e[r] = t[r]), e; - }, {})), - this.useHeaders - ? (e.headers || (e.headers = {}), - (function (e, t, r) { - o( - e, - (function (e, t) { - var r; - if ((void 0 === t && (t = {}), !e)) return {}; - var i = Object.entries(e), - n = Object.entries(Fs).concat( - Object.entries( - (null == (r = t) - ? void 0 - : r.customHeaderMap) || {} - ) - ), - s = i.reduce(function (e, t) { - var r, - i = t[0], - s = t[1], - a = - (null == - (r = n.find(function (e) { - return e[1].includes(i); - })) - ? void 0 - : r[0]) || Ms.REQUEST; - return ( - null != e[a] || (e[a] = {}), - (e[a][i] = s), - e - ); - }, {}); - return Object.entries(s).reduce(function ( - e, - r - ) { - var i = r[0], - n = r[1]; - return (e[i] = ha(n, t)), e; - }, - {}); - })(t, r) - ); - })(e.headers, t)) - : (e.url = (function (e, t, r) { - var i = (function (e, t) { - if ((void 0 === t && (t = {}), !e)) return ""; - var r = ha(e, t); - return "CMCD=" + encodeURIComponent(r); - })(t, r); - if (!i) return e; - if (ua.test(e)) return e.replace(ua, i); - var n = e.includes("?") ? "&" : "?"; - return "" + e + n + i; - })(e.url, t)); - }), - (t.getObjectType = function (e) { - var t = e.type; - return "subtitle" === t - ? ks.TIMED_TEXT - : "initSegment" === e.sn - ? ks.INIT - : "audio" === t - ? ks.AUDIO - : "main" === t - ? this.hls.audioTracks.length - ? ks.VIDEO - : ks.MUXED - : void 0; - }), - (t.getTopBandwidth = function (e) { - var t, - r = 0, - i = this.hls; - if (e === ks.AUDIO) t = i.audioTracks; - else { - var n = i.maxAutoLevel, - s = n > -1 ? n + 1 : i.levels.length; - t = i.levels.slice(0, s); - } - for ( - var a, - o = (function (e, t) { - var r = - ("undefined" != typeof Symbol && - e[Symbol.iterator]) || - e["@@iterator"]; - if (r) return (r = r.call(e)).next.bind(r); - if ( - Array.isArray(e) || - (r = (function (e, t) { - if (e) { - if ("string" == typeof e) return f(e, t); - var r = Object.prototype.toString - .call(e) - .slice(8, -1); - return ( - "Object" === r && - e.constructor && - (r = e.constructor.name), - "Map" === r || "Set" === r - ? Array.from(e) - : "Arguments" === r || - /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test( - r - ) - ? f(e, t) - : void 0 - ); - } - })(e)) || - (t && e && "number" == typeof e.length) - ) { - r && (e = r); - var i = 0; - return function () { - return i >= e.length - ? { done: !0 } - : { done: !1, value: e[i++] }; - }; - } - throw new TypeError( - "Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method." - ); - })(t); - !(a = o()).done; - - ) { - var l = a.value; - l.bitrate > r && (r = l.bitrate); - } - return r > 0 ? r : NaN; - }), - (t.getBufferLength = function (e) { - var t = this.hls.media, - r = - e === ks.AUDIO ? this.audioBuffer : this.videoBuffer; - return r && t - ? 1e3 * - Mr.bufferInfo( - r, - t.currentTime, - this.config.maxBufferHole - ).len - : NaN; - }), - (t.createPlaylistLoader = function () { - var e = this.config.pLoader, - t = this.applyPlaylistData, - r = e || this.config.loader; - return (function () { - function e(e) { - (this.loader = void 0), (this.loader = new r(e)); - } - var i = e.prototype; - return ( - (i.destroy = function () { - this.loader.destroy(); - }), - (i.abort = function () { - this.loader.abort(); - }), - (i.load = function (e, r, i) { - t(e), this.loader.load(e, r, i); - }), - a(e, [ - { - key: "stats", - get: function () { - return this.loader.stats; - }, - }, - { - key: "context", - get: function () { - return this.loader.context; - }, - }, - ]), - e - ); - })(); - }), - (t.createFragmentLoader = function () { - var e = this.config.fLoader, - t = this.applyFragmentData, - r = e || this.config.loader; - return (function () { - function e(e) { - (this.loader = void 0), (this.loader = new r(e)); - } - var i = e.prototype; - return ( - (i.destroy = function () { - this.loader.destroy(); - }), - (i.abort = function () { - this.loader.abort(); - }), - (i.load = function (e, r, i) { - t(e), this.loader.load(e, r, i); - }), - a(e, [ - { - key: "stats", - get: function () { - return this.loader.stats; - }, - }, - { - key: "context", - get: function () { - return this.loader.context; - }, - }, - ]), - e - ); - })(); - }), - e - ); - })(), - ca = (function () { - function e(e) { - (this.hls = void 0), - (this.log = void 0), - (this.loader = null), - (this.uri = null), - (this.pathwayId = "."), - (this.pathwayPriority = null), - (this.timeToLoad = 300), - (this.reloadTimer = -1), - (this.updated = 0), - (this.started = !1), - (this.enabled = !0), - (this.levels = null), - (this.audioTracks = null), - (this.subtitleTracks = null), - (this.penalizedPathways = {}), - (this.hls = e), - (this.log = A.log.bind(A, "[content-steering]:")), - this.registerListeners(); - } - var t = e.prototype; - return ( - (t.registerListeners = function () { - var e = this.hls; - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.MANIFEST_LOADED, this.onManifestLoaded, this), - e.on(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.on(E.ERROR, this.onError, this); - }), - (t.unregisterListeners = function () { - var e = this.hls; - e && - (e.off( - E.MANIFEST_LOADING, - this.onManifestLoading, - this - ), - e.off(E.MANIFEST_LOADED, this.onManifestLoaded, this), - e.off(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.off(E.ERROR, this.onError, this)); - }), - (t.startLoad = function () { - if ( - ((this.started = !0), - this.clearTimeout(), - this.enabled && this.uri) - ) { - if (this.updated) { - var e = - 1e3 * this.timeToLoad - - (performance.now() - this.updated); - if (e > 0) - return void this.scheduleRefresh(this.uri, e); - } - this.loadSteeringManifest(this.uri); - } - }), - (t.stopLoad = function () { - (this.started = !1), - this.loader && - (this.loader.destroy(), (this.loader = null)), - this.clearTimeout(); - }), - (t.clearTimeout = function () { - -1 !== this.reloadTimer && - (self.clearTimeout(this.reloadTimer), - (this.reloadTimer = -1)); - }), - (t.destroy = function () { - this.unregisterListeners(), - this.stopLoad(), - (this.hls = null), - (this.levels = - this.audioTracks = - this.subtitleTracks = - null); - }), - (t.removeLevel = function (e) { - var t = this.levels; - t && - (this.levels = t.filter(function (t) { - return t !== e; - })); - }), - (t.onManifestLoading = function () { - this.stopLoad(), - (this.enabled = !0), - (this.timeToLoad = 300), - (this.updated = 0), - (this.uri = null), - (this.pathwayId = "."), - (this.levels = - this.audioTracks = - this.subtitleTracks = - null); - }), - (t.onManifestLoaded = function (e, t) { - var r = t.contentSteering; - null !== r && - ((this.pathwayId = r.pathwayId), - (this.uri = r.uri), - this.started && this.startLoad()); - }), - (t.onManifestParsed = function (e, t) { - (this.audioTracks = t.audioTracks), - (this.subtitleTracks = t.subtitleTracks); - }), - (t.onError = function (e, t) { - var r = t.errorAction; - if ( - 2 === (null == r ? void 0 : r.action) && - 1 === r.flags - ) { - var i = this.levels, - n = this.pathwayPriority, - s = this.pathwayId; - if (t.context) { - var a = t.context, - o = a.groupId, - l = a.pathwayId, - h = a.type; - o && i - ? (s = this.getPathwayForGroupId(o, h, s)) - : l && (s = l); - } - s in this.penalizedPathways || - (this.penalizedPathways[s] = performance.now()), - !n && - i && - (n = i.reduce(function (e, t) { - return ( - -1 === e.indexOf(t.pathwayId) && - e.push(t.pathwayId), - e - ); - }, [])), - n && - n.length > 1 && - (this.updatePathwayPriority(n), - (r.resolved = this.pathwayId !== s)), - r.resolved || - A.warn( - "Could not resolve " + - t.details + - ' ("' + - t.error.message + - '") with content-steering for Pathway: ' + - s + - " levels: " + - (i ? i.length : i) + - " priorities: " + - JSON.stringify(n) + - " penalized: " + - JSON.stringify(this.penalizedPathways) - ); - } - }), - (t.filterParsedLevels = function (e) { - this.levels = e; - var t = this.getLevelsForPathway(this.pathwayId); - if (0 === t.length) { - var r = e[0].pathwayId; - this.log( - "No levels found in Pathway " + - this.pathwayId + - '. Setting initial Pathway to "' + - r + - '"' - ), - (t = this.getLevelsForPathway(r)), - (this.pathwayId = r); - } - return t.length !== e.length - ? (this.log( - "Found " + - t.length + - "/" + - e.length + - ' levels in Pathway "' + - this.pathwayId + - '"' - ), - t) - : e; - }), - (t.getLevelsForPathway = function (e) { - return null === this.levels - ? [] - : this.levels.filter(function (t) { - return e === t.pathwayId; - }); - }), - (t.updatePathwayPriority = function (e) { - var t; - this.pathwayPriority = e; - var r = this.penalizedPathways, - i = performance.now(); - Object.keys(r).forEach(function (e) { - i - r[e] > 3e5 && delete r[e]; - }); - for (var n = 0; n < e.length; n++) { - var s = e[n]; - if (!(s in r)) { - if (s === this.pathwayId) return; - var a = this.hls.nextLoadLevel, - o = this.hls.levels[a]; - if ((t = this.getLevelsForPathway(s)).length > 0) { - this.log('Setting Pathway to "' + s + '"'), - (this.pathwayId = s), - tr(t), - this.hls.trigger(E.LEVELS_UPDATED, { levels: t }); - var l = this.hls.levels[a]; - o && - l && - this.levels && - (l.attrs["STABLE-VARIANT-ID"] !== - o.attrs["STABLE-VARIANT-ID"] && - l.bitrate !== o.bitrate && - this.log( - "Unstable Pathways change from bitrate " + - o.bitrate + - " to " + - l.bitrate - ), - (this.hls.nextLoadLevel = a)); - break; - } - } - } - }), - (t.getPathwayForGroupId = function (e, t, r) { - for ( - var i = this.getLevelsForPathway(r).concat( - this.levels || [] - ), - n = 0; - n < i.length; - n++ - ) - if ( - (t === Tt && i[n].hasAudioGroup(e)) || - (t === _t && i[n].hasSubtitleGroup(e)) - ) - return i[n].pathwayId; - return r; - }), - (t.clonePathways = function (e) { - var t = this, - r = this.levels; - if (r) { - var i = {}, - n = {}; - e.forEach(function (e) { - var s = e.ID, - a = e["BASE-ID"], - o = e["URI-REPLACEMENT"]; - if ( - !r.some(function (e) { - return e.pathwayId === s; - }) - ) { - var l = t.getLevelsForPathway(a).map(function (e) { - var t = new I(e.attrs); - t["PATHWAY-ID"] = s; - var r = t.AUDIO && t.AUDIO + "_clone_" + s, - a = t.SUBTITLES && t.SUBTITLES + "_clone_" + s; - r && ((i[t.AUDIO] = r), (t.AUDIO = r)), - a && ((n[t.SUBTITLES] = a), (t.SUBTITLES = a)); - var l = ga( - e.uri, - t["STABLE-VARIANT-ID"], - "PER-VARIANT-URIS", - o - ), - h = new qt({ - attrs: t, - audioCodec: e.audioCodec, - bitrate: e.bitrate, - height: e.height, - name: e.name, - url: l, - videoCodec: e.videoCodec, - width: e.width, - }); - if (e.audioGroups) - for (var u = 1; u < e.audioGroups.length; u++) - h.addGroupId( - "audio", - e.audioGroups[u] + "_clone_" + s - ); - if (e.subtitleGroups) - for ( - var d = 1; - d < e.subtitleGroups.length; - d++ - ) - h.addGroupId( - "text", - e.subtitleGroups[d] + "_clone_" + s - ); - return h; - }); - r.push.apply(r, l), - fa(t.audioTracks, i, o, s), - fa(t.subtitleTracks, n, o, s); - } - }); - } - }), - (t.loadSteeringManifest = function (e) { - var t, - r = this, - i = this.hls.config, - n = i.loader; - this.loader && this.loader.destroy(), - (this.loader = new n(i)); - try { - t = new self.URL(e); - } catch (t) { - return ( - (this.enabled = !1), - void this.log( - "Failed to parse Steering Manifest URI: " + e - ) - ); - } - if ("data:" !== t.protocol) { - var s = - 0 | - (this.hls.bandwidthEstimate || - i.abrEwmaDefaultEstimate); - t.searchParams.set("_HLS_pathway", this.pathwayId), - t.searchParams.set("_HLS_throughput", "" + s); - } - var a = { responseType: "json", url: t.href }, - o = i.steeringManifestLoadPolicy.default, - l = o.errorRetry || o.timeoutRetry || {}, - h = { - loadPolicy: o, - timeout: o.maxLoadTimeMs, - maxRetry: l.maxNumRetry || 0, - retryDelay: l.retryDelayMs || 0, - maxRetryDelay: l.maxRetryDelayMs || 0, - }, - u = { - onSuccess: function (e, i, n, s) { - r.log('Loaded steering manifest: "' + t + '"'); - var a = e.data; - if (1 === a.VERSION) { - (r.updated = performance.now()), - (r.timeToLoad = a.TTL); - var o = a["RELOAD-URI"], - l = a["PATHWAY-CLONES"], - h = a["PATHWAY-PRIORITY"]; - if (o) - try { - r.uri = new self.URL(o, t).href; - } catch (e) { - return ( - (r.enabled = !1), - void r.log( - "Failed to parse Steering Manifest RELOAD-URI: " + - o - ) - ); - } - r.scheduleRefresh(r.uri || n.url), - l && r.clonePathways(l); - var u = { - steeringManifest: a, - url: t.toString(), - }; - r.hls.trigger(E.STEERING_MANIFEST_LOADED, u), - h && r.updatePathwayPriority(h); - } else - r.log( - "Steering VERSION " + - a.VERSION + - " not supported!" - ); - }, - onError: function (e, t, i, n) { - if ( - (r.log( - "Error loading steering manifest: " + - e.code + - " " + - e.text + - " (" + - t.url + - ")" - ), - r.stopLoad(), - 410 === e.code) - ) - return ( - (r.enabled = !1), - void r.log( - "Steering manifest " + - t.url + - " no longer available" - ) - ); - var s = 1e3 * r.timeToLoad; - if (429 !== e.code) - r.scheduleRefresh(r.uri || t.url, s); - else { - var a = r.loader; - if ( - "function" == - typeof (null == a - ? void 0 - : a.getResponseHeader) - ) { - var o = a.getResponseHeader("Retry-After"); - o && (s = 1e3 * parseFloat(o)); - } - r.log( - "Steering manifest " + t.url + " rate limited" - ); - } - }, - onTimeout: function (e, t, i) { - r.log( - "Timeout loading steering manifest (" + - t.url + - ")" - ), - r.scheduleRefresh(r.uri || t.url); - }, - }; - this.log("Requesting steering manifest: " + t), - this.loader.load(a, h, u); - }), - (t.scheduleRefresh = function (e, t) { - var r = this; - void 0 === t && (t = 1e3 * this.timeToLoad), - this.clearTimeout(), - (this.reloadTimer = self.setTimeout(function () { - var t, - i = null == (t = r.hls) ? void 0 : t.media; - !i || i.ended - ? r.scheduleRefresh(e, 1e3 * r.timeToLoad) - : r.loadSteeringManifest(e); - }, t)); - }), - e - ); - })(); - function fa(e, t, r, i) { - e && - Object.keys(t).forEach(function (n) { - var s = e - .filter(function (e) { - return e.groupId === n; - }) - .map(function (e) { - var s = o({}, e); - return ( - (s.details = void 0), - (s.attrs = new I(s.attrs)), - (s.url = s.attrs.URI = - ga( - e.url, - e.attrs["STABLE-RENDITION-ID"], - "PER-RENDITION-URIS", - r - )), - (s.groupId = s.attrs["GROUP-ID"] = t[n]), - (s.attrs["PATHWAY-ID"] = i), - s - ); - }); - e.push.apply(e, s); - }); - } - function ga(e, t, r, i) { - var n, - s = i.HOST, - a = i.PARAMS, - o = i[r]; - t && (n = null == o ? void 0 : o[t]) && (e = n); - var l = new self.URL(e); - return ( - s && !n && (l.host = s), - a && - Object.keys(a) - .sort() - .forEach(function (e) { - e && l.searchParams.set(e, a[e]); - }), - l.href - ); - } - var pa = /^age:\s*[\d.]+\s*$/im, - ma = (function () { - function e(e) { - (this.xhrSetup = void 0), - (this.requestTimeout = void 0), - (this.retryTimeout = void 0), - (this.retryDelay = void 0), - (this.config = null), - (this.callbacks = null), - (this.context = null), - (this.loader = null), - (this.stats = void 0), - (this.xhrSetup = (e && e.xhrSetup) || null), - (this.stats = new D()), - (this.retryDelay = 0); - } - var t = e.prototype; - return ( - (t.destroy = function () { - (this.callbacks = null), - this.abortInternal(), - (this.loader = null), - (this.config = null), - (this.context = null), - (this.xhrSetup = null); - }), - (t.abortInternal = function () { - var e = this.loader; - self.clearTimeout(this.requestTimeout), - self.clearTimeout(this.retryTimeout), - e && - ((e.onreadystatechange = null), - (e.onprogress = null), - 4 !== e.readyState && - ((this.stats.aborted = !0), e.abort())); - }), - (t.abort = function () { - var e; - this.abortInternal(), - null != (e = this.callbacks) && - e.onAbort && - this.callbacks.onAbort( - this.stats, - this.context, - this.loader - ); - }), - (t.load = function (e, t, r) { - if (this.stats.loading.start) - throw new Error("Loader can only be used once."); - (this.stats.loading.start = self.performance.now()), - (this.context = e), - (this.config = t), - (this.callbacks = r), - this.loadInternal(); - }), - (t.loadInternal = function () { - var e = this, - t = this.config, - r = this.context; - if (t && r) { - var i = (this.loader = new self.XMLHttpRequest()), - n = this.stats; - (n.loading.first = 0), (n.loaded = 0), (n.aborted = !1); - var s = this.xhrSetup; - s - ? Promise.resolve() - .then(function () { - if (e.loader === i && !e.stats.aborted) - return s(i, r.url); - }) - .catch(function (t) { - if (e.loader === i && !e.stats.aborted) - return i.open("GET", r.url, !0), s(i, r.url); - }) - .then(function () { - e.loader !== i || - e.stats.aborted || - e.openAndSendXhr(i, r, t); - }) - .catch(function (t) { - e.callbacks.onError( - { code: i.status, text: t.message }, - r, - i, - n - ); - }) - : this.openAndSendXhr(i, r, t); - } - }), - (t.openAndSendXhr = function (e, t, r) { - e.readyState || e.open("GET", t.url, !0); - var i = t.headers, - n = r.loadPolicy, - s = n.maxTimeToFirstByteMs, - a = n.maxLoadTimeMs; - if (i) for (var o in i) e.setRequestHeader(o, i[o]); - t.rangeEnd && - e.setRequestHeader( - "Range", - "bytes=" + t.rangeStart + "-" + (t.rangeEnd - 1) - ), - (e.onreadystatechange = - this.readystatechange.bind(this)), - (e.onprogress = this.loadprogress.bind(this)), - (e.responseType = t.responseType), - self.clearTimeout(this.requestTimeout), - (r.timeout = s && m(s) ? s : a), - (this.requestTimeout = self.setTimeout( - this.loadtimeout.bind(this), - r.timeout - )), - e.send(); - }), - (t.readystatechange = function () { - var e = this.context, - t = this.loader, - r = this.stats; - if (e && t) { - var i = t.readyState, - n = this.config; - if ( - !r.aborted && - i >= 2 && - (0 === r.loading.first && - ((r.loading.first = Math.max( - self.performance.now(), - r.loading.start - )), - n.timeout !== n.loadPolicy.maxLoadTimeMs && - (self.clearTimeout(this.requestTimeout), - (n.timeout = n.loadPolicy.maxLoadTimeMs), - (this.requestTimeout = self.setTimeout( - this.loadtimeout.bind(this), - n.loadPolicy.maxLoadTimeMs - - (r.loading.first - r.loading.start) - )))), - 4 === i) - ) { - self.clearTimeout(this.requestTimeout), - (t.onreadystatechange = null), - (t.onprogress = null); - var s = t.status, - a = "text" !== t.responseType; - if ( - s >= 200 && - s < 300 && - ((a && t.response) || null !== t.responseText) - ) { - r.loading.end = Math.max( - self.performance.now(), - r.loading.first - ); - var o = a ? t.response : t.responseText, - l = - "arraybuffer" === t.responseType - ? o.byteLength - : o.length; - if ( - ((r.loaded = r.total = l), - (r.bwEstimate = - (8e3 * r.total) / - (r.loading.end - r.loading.first)), - !this.callbacks) - ) - return; - var h = this.callbacks.onProgress; - if ((h && h(r, e, o, t), !this.callbacks)) return; - var u = { url: t.responseURL, data: o, code: s }; - this.callbacks.onSuccess(u, r, e, t); - } else { - var d = n.loadPolicy.errorRetry; - ar(d, r.retry, !1, { - url: e.url, - data: void 0, - code: s, - }) - ? this.retry(d) - : (A.error(s + " while loading " + e.url), - this.callbacks.onError( - { code: s, text: t.statusText }, - e, - t, - r - )); - } - } - } - }), - (t.loadtimeout = function () { - if (this.config) { - var e = this.config.loadPolicy.timeoutRetry; - if (ar(e, this.stats.retry, !0)) this.retry(e); - else { - var t; - A.warn( - "timeout while loading " + - (null == (t = this.context) ? void 0 : t.url) - ); - var r = this.callbacks; - r && - (this.abortInternal(), - r.onTimeout(this.stats, this.context, this.loader)); - } - } - }), - (t.retry = function (e) { - var t = this.context, - r = this.stats; - (this.retryDelay = nr(e, r.retry)), - r.retry++, - A.warn( - (status ? "HTTP Status " + status : "Timeout") + - " while loading " + - (null == t ? void 0 : t.url) + - ", retrying " + - r.retry + - "/" + - e.maxNumRetry + - " in " + - this.retryDelay + - "ms" - ), - this.abortInternal(), - (this.loader = null), - self.clearTimeout(this.retryTimeout), - (this.retryTimeout = self.setTimeout( - this.loadInternal.bind(this), - this.retryDelay - )); - }), - (t.loadprogress = function (e) { - var t = this.stats; - (t.loaded = e.loaded), - e.lengthComputable && (t.total = e.total); - }), - (t.getCacheAge = function () { - var e = null; - if ( - this.loader && - pa.test(this.loader.getAllResponseHeaders()) - ) { - var t = this.loader.getResponseHeader("age"); - e = t ? parseFloat(t) : null; - } - return e; - }), - (t.getResponseHeader = function (e) { - return this.loader && - new RegExp("^" + e + ":\\s*[\\d.]+\\s*$", "im").test( - this.loader.getAllResponseHeaders() - ) - ? this.loader.getResponseHeader(e) - : null; - }), - e - ); - })(), - va = /(\d+)-(\d+)\/(\d+)/, - ya = (function () { - function e(e) { - (this.fetchSetup = void 0), - (this.requestTimeout = void 0), - (this.request = null), - (this.response = null), - (this.controller = void 0), - (this.context = null), - (this.config = null), - (this.callbacks = null), - (this.stats = void 0), - (this.loader = null), - (this.fetchSetup = e.fetchSetup || Ea), - (this.controller = new self.AbortController()), - (this.stats = new D()); - } - var t = e.prototype; - return ( - (t.destroy = function () { - (this.loader = - this.callbacks = - this.context = - this.config = - this.request = - null), - this.abortInternal(), - (this.response = null), - (this.fetchSetup = this.controller = this.stats = null); - }), - (t.abortInternal = function () { - this.controller && - !this.stats.loading.end && - ((this.stats.aborted = !0), this.controller.abort()); - }), - (t.abort = function () { - var e; - this.abortInternal(), - null != (e = this.callbacks) && - e.onAbort && - this.callbacks.onAbort( - this.stats, - this.context, - this.response - ); - }), - (t.load = function (e, t, r) { - var i = this, - n = this.stats; - if (n.loading.start) - throw new Error("Loader can only be used once."); - n.loading.start = self.performance.now(); - var s = (function (e, t) { - var r = { - method: "GET", - mode: "cors", - credentials: "same-origin", - signal: t, - headers: new self.Headers(o({}, e.headers)), - }; - return ( - e.rangeEnd && - r.headers.set( - "Range", - "bytes=" + - e.rangeStart + - "-" + - String(e.rangeEnd - 1) - ), - r - ); - })(e, this.controller.signal), - a = r.onProgress, - l = "arraybuffer" === e.responseType, - h = l ? "byteLength" : "length", - u = t.loadPolicy, - d = u.maxTimeToFirstByteMs, - c = u.maxLoadTimeMs; - (this.context = e), - (this.config = t), - (this.callbacks = r), - (this.request = this.fetchSetup(e, s)), - self.clearTimeout(this.requestTimeout), - (t.timeout = d && m(d) ? d : c), - (this.requestTimeout = self.setTimeout(function () { - i.abortInternal(), r.onTimeout(n, e, i.response); - }, t.timeout)), - self - .fetch(this.request) - .then(function (s) { - i.response = i.loader = s; - var o = Math.max( - self.performance.now(), - n.loading.start - ); - if ( - (self.clearTimeout(i.requestTimeout), - (t.timeout = c), - (i.requestTimeout = self.setTimeout(function () { - i.abortInternal(), - r.onTimeout(n, e, i.response); - }, c - (o - n.loading.start))), - !s.ok) - ) { - var h = s.status, - u = s.statusText; - throw new Ta( - u || "fetch, bad network response", - h, - s - ); - } - return ( - (n.loading.first = o), - (n.total = - (function (e) { - var t = e.get("Content-Range"); - if (t) { - var r = (function (e) { - var t = va.exec(e); - if (t) - return ( - parseInt(t[2]) - parseInt(t[1]) + 1 - ); - })(t); - if (m(r)) return r; - } - var i = e.get("Content-Length"); - if (i) return parseInt(i); - })(s.headers) || n.total), - a && m(t.highWaterMark) - ? i.loadProgressively( - s, - n, - e, - t.highWaterMark, - a - ) - : l - ? s.arrayBuffer() - : "json" === e.responseType - ? s.json() - : s.text() - ); - }) - .then(function (s) { - var o = i.response; - if (!o) throw new Error("loader destroyed"); - self.clearTimeout(i.requestTimeout), - (n.loading.end = Math.max( - self.performance.now(), - n.loading.first - )); - var l = s[h]; - l && (n.loaded = n.total = l); - var u = { url: o.url, data: s, code: o.status }; - a && !m(t.highWaterMark) && a(n, e, s, o), - r.onSuccess(u, n, e, o); - }) - .catch(function (t) { - if ( - (self.clearTimeout(i.requestTimeout), !n.aborted) - ) { - var s = (t && t.code) || 0, - a = t ? t.message : null; - r.onError( - { code: s, text: a }, - e, - t ? t.details : null, - n - ); - } - }); - }), - (t.getCacheAge = function () { - var e = null; - if (this.response) { - var t = this.response.headers.get("age"); - e = t ? parseFloat(t) : null; - } - return e; - }), - (t.getResponseHeader = function (e) { - return this.response - ? this.response.headers.get(e) - : null; - }), - (t.loadProgressively = function (e, t, r, i, n) { - void 0 === i && (i = 0); - var s = new oi(), - a = e.body.getReader(); - return (function o() { - return a - .read() - .then(function (a) { - if (a.done) - return ( - s.dataLength && n(t, r, s.flush(), e), - Promise.resolve(new ArrayBuffer(0)) - ); - var l = a.value, - h = l.length; - return ( - (t.loaded += h), - h < i || s.dataLength - ? (s.push(l), - s.dataLength >= i && n(t, r, s.flush(), e)) - : n(t, r, l, e), - o() - ); - }) - .catch(function () { - return Promise.reject(); - }); - })(); - }), - e - ); - })(); - function Ea(e, t) { - return new self.Request(e.url, t); - } - var Sa, - Ta = (function (e) { - function t(t, r, i) { - var n; - return ( - ((n = e.call(this, t) || this).code = void 0), - (n.details = void 0), - (n.code = r), - (n.details = i), - n - ); - } - return l(t, e), t; - })(c(Error)), - _a = /\s/, - La = i( - i( - { - autoStartLoad: !0, - startPosition: -1, - defaultAudioCodec: void 0, - debug: !1, - capLevelOnFPSDrop: !1, - capLevelToPlayerSize: !1, - ignoreDevicePixelRatio: !1, - preferManagedMediaSource: !0, - initialLiveManifestSize: 1, - maxBufferLength: 30, - backBufferLength: 1 / 0, - frontBufferFlushThreshold: 1 / 0, - maxBufferSize: 6e7, - maxBufferHole: 0.1, - highBufferWatchdogPeriod: 2, - nudgeOffset: 0.1, - nudgeMaxRetry: 3, - maxFragLookUpTolerance: 0.25, - liveSyncDurationCount: 3, - liveMaxLatencyDurationCount: 1 / 0, - liveSyncDuration: void 0, - liveMaxLatencyDuration: void 0, - maxLiveSyncPlaybackRate: 1, - liveDurationInfinity: !1, - liveBackBufferLength: null, - maxMaxBufferLength: 600, - enableWorker: !0, - workerPath: null, - enableSoftwareAES: !0, - startLevel: void 0, - startFragPrefetch: !1, - fpsDroppedMonitoringPeriod: 5e3, - fpsDroppedMonitoringThreshold: 0.2, - appendErrorMaxRetry: 3, - loader: ma, - fLoader: void 0, - pLoader: void 0, - xhrSetup: void 0, - licenseXhrSetup: void 0, - licenseResponseCallback: void 0, - abrController: Lr, - bufferController: Dn, - capLevelController: ws, - errorController: dr, - fpsController: Ps, - stretchShortVideoTrack: !1, - maxAudioFramesDrift: 1, - forceKeyFrameOnDiscontinuity: !0, - abrEwmaFastLive: 3, - abrEwmaSlowLive: 9, - abrEwmaFastVoD: 3, - abrEwmaSlowVoD: 9, - abrEwmaDefaultEstimate: 5e5, - abrEwmaDefaultEstimateMax: 5e6, - abrBandWidthFactor: 0.95, - abrBandWidthUpFactor: 0.7, - abrMaxWithRealBitrate: !1, - maxStarvationDelay: 4, - maxLoadingDelay: 4, - minAutoBitrate: 0, - emeEnabled: !1, - widevineLicenseUrl: void 0, - drmSystems: {}, - drmSystemOptions: {}, - requestMediaKeySystemAccessFunc: Z, - testBandwidth: !0, - progressive: !1, - lowLatencyMode: !0, - cmcd: void 0, - enableDateRangeMetadataCues: !0, - enableEmsgMetadataCues: !0, - enableID3MetadataCues: !0, - useMediaCapabilities: !0, - certLoadPolicy: { - default: { - maxTimeToFirstByteMs: 8e3, - maxLoadTimeMs: 2e4, - timeoutRetry: null, - errorRetry: null, - }, - }, - keyLoadPolicy: { - default: { - maxTimeToFirstByteMs: 8e3, - maxLoadTimeMs: 2e4, - timeoutRetry: { - maxNumRetry: 1, - retryDelayMs: 1e3, - maxRetryDelayMs: 2e4, - backoff: "linear", - }, - errorRetry: { - maxNumRetry: 8, - retryDelayMs: 1e3, - maxRetryDelayMs: 2e4, - backoff: "linear", - }, - }, - }, - manifestLoadPolicy: { - default: { - maxTimeToFirstByteMs: 1 / 0, - maxLoadTimeMs: 2e4, - timeoutRetry: { - maxNumRetry: 2, - retryDelayMs: 0, - maxRetryDelayMs: 0, - }, - errorRetry: { - maxNumRetry: 1, - retryDelayMs: 1e3, - maxRetryDelayMs: 8e3, - }, - }, - }, - playlistLoadPolicy: { - default: { - maxTimeToFirstByteMs: 1e4, - maxLoadTimeMs: 2e4, - timeoutRetry: { - maxNumRetry: 2, - retryDelayMs: 0, - maxRetryDelayMs: 0, - }, - errorRetry: { - maxNumRetry: 2, - retryDelayMs: 1e3, - maxRetryDelayMs: 8e3, - }, - }, - }, - fragLoadPolicy: { - default: { - maxTimeToFirstByteMs: 1e4, - maxLoadTimeMs: 12e4, - timeoutRetry: { - maxNumRetry: 4, - retryDelayMs: 0, - maxRetryDelayMs: 0, - }, - errorRetry: { - maxNumRetry: 6, - retryDelayMs: 1e3, - maxRetryDelayMs: 8e3, - }, - }, - }, - steeringManifestLoadPolicy: { - default: { - maxTimeToFirstByteMs: 1e4, - maxLoadTimeMs: 2e4, - timeoutRetry: { - maxNumRetry: 2, - retryDelayMs: 0, - maxRetryDelayMs: 0, - }, - errorRetry: { - maxNumRetry: 1, - retryDelayMs: 1e3, - maxRetryDelayMs: 8e3, - }, - }, - }, - manifestLoadingTimeOut: 1e4, - manifestLoadingMaxRetry: 1, - manifestLoadingRetryDelay: 1e3, - manifestLoadingMaxRetryTimeout: 64e3, - levelLoadingTimeOut: 1e4, - levelLoadingMaxRetry: 4, - levelLoadingRetryDelay: 1e3, - levelLoadingMaxRetryTimeout: 64e3, - fragLoadingTimeOut: 2e4, - fragLoadingMaxRetry: 6, - fragLoadingRetryDelay: 1e3, - fragLoadingMaxRetryTimeout: 64e3, - }, - { - cueHandler: { - newCue: function (e, t, r, i) { - for ( - var n, - s, - a, - o, - l, - h = [], - u = self.VTTCue || self.TextTrackCue, - d = 0; - d < i.rows.length; - d++ - ) - if ( - ((a = !0), - (o = 0), - (l = ""), - !(n = i.rows[d]).isEmpty()) - ) { - for (var c, f = 0; f < n.chars.length; f++) - _a.test(n.chars[f].uchar) && a - ? o++ - : ((l += n.chars[f].uchar), (a = !1)); - (n.cueStartTime = t), - t === r && (r += 1e-4), - o >= 16 ? o-- : o++; - var g = os(l.trim()), - p = cs(t, r, g); - (null != e && - null != (c = e.cues) && - c.getCueById(p)) || - (((s = new u(t, r, g)).id = p), - (s.line = d + 1), - (s.align = "left"), - (s.position = - 10 + - Math.min(80, 10 * Math.floor((8 * o) / 32))), - h.push(s)); - } - return ( - e && - h.length && - (h.sort(function (e, t) { - return "auto" === e.line || "auto" === t.line - ? 0 - : e.line > 8 && t.line > 8 - ? t.line - e.line - : e.line - t.line; - }), - h.forEach(function (t) { - return Ct(e, t); - })), - h - ); - }, - }, - enableWebVTT: !0, - enableIMSC1: !0, - enableCEA708Captions: !0, - captionsTextTrack1Label: "English", - captionsTextTrack1LanguageCode: "en", - captionsTextTrack2Label: "Spanish", - captionsTextTrack2LanguageCode: "es", - captionsTextTrack3Label: "Unknown CC", - captionsTextTrack3LanguageCode: "", - captionsTextTrack4Label: "Unknown CC", - captionsTextTrack4LanguageCode: "", - renderTextTracksNatively: !0, - } - ), - {}, - { - subtitleStreamController: wn, - subtitleTrackController: In, - timelineController: bs, - audioStreamController: Rn, - audioTrackController: An, - emeController: Cs, - cmcdController: da, - contentSteeringController: ca, - } - ); - function ba(e) { - return e && "object" == typeof e - ? Array.isArray(e) - ? e.map(ba) - : Object.keys(e).reduce(function (t, r) { - return (t[r] = ba(e[r])), t; - }, {}) - : e; - } - var Ra = (function (e) { - function t(t, r) { - var i; - return ( - ((i = - e.call(this, t, "[level-controller]") || this)._levels = - []), - (i._firstLevel = -1), - (i._maxAutoLevel = -1), - (i._startLevel = void 0), - (i.currentLevel = null), - (i.currentLevelIndex = -1), - (i.manualLevelIndex = -1), - (i.steering = void 0), - (i.onParsedComplete = void 0), - (i.steering = r), - i._registerListeners(), - i - ); - } - l(t, e); - var r = t.prototype; - return ( - (r._registerListeners = function () { - var e = this.hls; - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.MANIFEST_LOADED, this.onManifestLoaded, this), - e.on(E.LEVEL_LOADED, this.onLevelLoaded, this), - e.on(E.LEVELS_UPDATED, this.onLevelsUpdated, this), - e.on(E.FRAG_BUFFERED, this.onFragBuffered, this), - e.on(E.ERROR, this.onError, this); - }), - (r._unregisterListeners = function () { - var e = this.hls; - e.off(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.off(E.MANIFEST_LOADED, this.onManifestLoaded, this), - e.off(E.LEVEL_LOADED, this.onLevelLoaded, this), - e.off(E.LEVELS_UPDATED, this.onLevelsUpdated, this), - e.off(E.FRAG_BUFFERED, this.onFragBuffered, this), - e.off(E.ERROR, this.onError, this); - }), - (r.destroy = function () { - this._unregisterListeners(), - (this.steering = null), - this.resetLevels(), - e.prototype.destroy.call(this); - }), - (r.stopLoad = function () { - this._levels.forEach(function (e) { - (e.loadError = 0), (e.fragmentError = 0); - }), - e.prototype.stopLoad.call(this); - }), - (r.resetLevels = function () { - (this._startLevel = void 0), - (this.manualLevelIndex = -1), - (this.currentLevelIndex = -1), - (this.currentLevel = null), - (this._levels = []), - (this._maxAutoLevel = -1); - }), - (r.onManifestLoading = function (e, t) { - this.resetLevels(); - }), - (r.onManifestLoaded = function (e, t) { - var r = this.hls.config.preferManagedMediaSource, - i = [], - n = {}, - s = {}, - a = !1, - o = !1, - l = !1; - t.levels.forEach(function (e) { - var t, - h, - u = e.attrs, - d = e.audioCodec, - c = e.videoCodec; - -1 !== - (null == (t = d) ? void 0 : t.indexOf("mp4a.40.34")) && - (Sa || - (Sa = /chrome|firefox/i.test(navigator.userAgent)), - Sa && (e.audioCodec = d = void 0)), - d && (e.audioCodec = d = nt(d, r)), - 0 === (null == (h = c) ? void 0 : h.indexOf("avc1")) && - (c = e.videoCodec = - (function (e) { - for ( - var t = e.split(","), r = 0; - r < t.length; - r++ - ) { - var i = t[r].split("."); - if (i.length > 2) { - var n = i.shift() + "."; - (n += parseInt(i.shift()).toString(16)), - (n += ( - "000" + parseInt(i.shift()).toString(16) - ).slice(-4)), - (t[r] = n); - } - } - return t.join(","); - })(c)); - var f = e.width, - g = e.height, - p = e.unknownCodecs; - if ( - (a || (a = !(!f || !g)), - o || (o = !!c), - l || (l = !!d), - !( - (null != p && p.length) || - (d && !Qe(d, "audio", r)) || - (c && !Qe(c, "video", r)) - )) - ) { - var m = u.CODECS, - v = u["FRAME-RATE"], - y = u["HDCP-LEVEL"], - E = u["PATHWAY-ID"], - S = u.RESOLUTION, - T = u["VIDEO-RANGE"], - _ = - (E || ".") + - "-" + - e.bitrate + - "-" + - S + - "-" + - v + - "-" + - m + - "-" + - T + - "-" + - y; - if (n[_]) - if (n[_].uri === e.url || e.attrs["PATHWAY-ID"]) - n[_].addGroupId("audio", u.AUDIO), - n[_].addGroupId("text", u.SUBTITLES); - else { - var L = (s[_] += 1); - e.attrs["PATHWAY-ID"] = new Array(L + 1).join("."); - var b = new qt(e); - (n[_] = b), i.push(b); - } - else { - var R = new qt(e); - (n[_] = R), (s[_] = 1), i.push(R); - } - } - }), - this.filterAndSortMediaOptions(i, t, a, o, l); - }), - (r.filterAndSortMediaOptions = function (e, t, r, i, n) { - var s = this, - a = [], - o = [], - l = e; - if ( - ((r || i) && - n && - (l = l.filter(function (e) { - var t, - r = e.videoCodec, - i = e.videoRange, - n = e.width, - s = e.height; - return ( - (!!r || !(!n || !s)) && - !!(t = i) && - Kt.indexOf(t) > -1 - ); - })), - 0 !== l.length) - ) { - if (t.audioTracks) { - var h = this.hls.config.preferManagedMediaSource; - Aa( - (a = t.audioTracks.filter(function (e) { - return ( - !e.audioCodec || Qe(e.audioCodec, "audio", h) - ); - })) - ); - } - t.subtitles && Aa((o = t.subtitles)); - var u = l.slice(0); - l.sort(function (e, t) { - if (e.attrs["HDCP-LEVEL"] !== t.attrs["HDCP-LEVEL"]) - return (e.attrs["HDCP-LEVEL"] || "") > - (t.attrs["HDCP-LEVEL"] || "") - ? 1 - : -1; - if (r && e.height !== t.height) - return e.height - t.height; - if (e.frameRate !== t.frameRate) - return e.frameRate - t.frameRate; - if (e.videoRange !== t.videoRange) - return ( - Kt.indexOf(e.videoRange) - Kt.indexOf(t.videoRange) - ); - if (e.videoCodec !== t.videoCodec) { - var i = et(e.videoCodec), - n = et(t.videoCodec); - if (i !== n) return n - i; - } - if (e.uri === t.uri && e.codecSet !== t.codecSet) { - var s = tt(e.codecSet), - a = tt(t.codecSet); - if (s !== a) return a - s; - } - return e.averageBitrate !== t.averageBitrate - ? e.averageBitrate - t.averageBitrate - : 0; - }); - var d = u[0]; - if ( - this.steering && - (l = this.steering.filterParsedLevels(l)).length !== - u.length - ) - for (var c = 0; c < u.length; c++) - if (u[c].pathwayId === l[0].pathwayId) { - d = u[c]; - break; - } - this._levels = l; - for (var f = 0; f < l.length; f++) - if (l[f] === d) { - var g; - this._firstLevel = f; - var p = d.bitrate, - m = this.hls.bandwidthEstimate; - if ( - (this.log( - "manifest loaded, " + - l.length + - " level(s) found, first bitrate: " + - p - ), - void 0 === - (null == (g = this.hls.userConfig) - ? void 0 - : g.abrEwmaDefaultEstimate)) - ) { - var v = Math.min( - p, - this.hls.config.abrEwmaDefaultEstimateMax - ); - v > m && - m === La.abrEwmaDefaultEstimate && - (this.hls.bandwidthEstimate = v); - } - break; - } - var y = n && !i, - _ = { - levels: l, - audioTracks: a, - subtitleTracks: o, - sessionData: t.sessionData, - sessionKeys: t.sessionKeys, - firstLevel: this._firstLevel, - stats: t.stats, - audio: n, - video: i, - altAudio: - !y && - a.some(function (e) { - return !!e.url; - }), - }; - this.hls.trigger(E.MANIFEST_PARSED, _), - (this.hls.config.autoStartLoad || - this.hls.forceStartLoad) && - this.hls.startLoad(this.hls.config.startPosition); - } else - Promise.resolve().then(function () { - if (s.hls) { - t.levels.length && - s.warn( - "One or more CODECS in variant not supported: " + - JSON.stringify(t.levels[0].attrs) - ); - var e = new Error( - "no level with compatible codecs found in manifest" - ); - s.hls.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.MANIFEST_INCOMPATIBLE_CODECS_ERROR, - fatal: !0, - url: t.url, - error: e, - reason: e.message, - }); - } - }); - }), - (r.onError = function (e, t) { - !t.fatal && - t.context && - t.context.type === St && - t.context.level === this.level && - this.checkRetry(t); - }), - (r.onFragBuffered = function (e, t) { - var r = t.frag; - if (void 0 !== r && r.type === Lt) { - var i = r.elementaryStreams; - if ( - !Object.keys(i).some(function (e) { - return !!i[e]; - }) - ) - return; - var n = this._levels[r.level]; - null != n && - n.loadError && - (this.log( - "Resetting level error count of " + - n.loadError + - " on frag buffered" - ), - (n.loadError = 0)); - } - }), - (r.onLevelLoaded = function (e, t) { - var r, - i, - n = t.level, - s = t.details, - a = this._levels[n]; - if (!a) - return ( - this.warn("Invalid level index " + n), - void ( - null != (i = t.deliveryDirectives) && - i.skip && - (s.deltaUpdateFailed = !0) - ) - ); - n === this.currentLevelIndex - ? (0 === a.fragmentError && (a.loadError = 0), - this.playlistLoaded(n, t, a.details)) - : null != (r = t.deliveryDirectives) && - r.skip && - (s.deltaUpdateFailed = !0); - }), - (r.loadPlaylist = function (t) { - e.prototype.loadPlaylist.call(this); - var r = this.currentLevelIndex, - i = this.currentLevel; - if (i && this.shouldLoadPlaylist(i)) { - var n = i.uri; - if (t) - try { - n = t.addDirectives(n); - } catch (e) { - this.warn( - "Could not construct new URL with HLS Delivery Directives: " + - e - ); - } - var s = i.attrs["PATHWAY-ID"]; - this.log( - "Loading level index " + - r + - (void 0 !== (null == t ? void 0 : t.msn) - ? " at sn " + t.msn + " part " + t.part - : "") + - " with" + - (s ? " Pathway " + s : "") + - " " + - n - ), - this.clearTimer(), - this.hls.trigger(E.LEVEL_LOADING, { - url: n, - level: r, - pathwayId: i.attrs["PATHWAY-ID"], - id: 0, - deliveryDirectives: t || null, - }); - } - }), - (r.removeLevel = function (e) { - var t, - r = this, - i = this._levels.filter(function (t, i) { - return ( - i !== e || - (r.steering && r.steering.removeLevel(t), - t === r.currentLevel && - ((r.currentLevel = null), - (r.currentLevelIndex = -1), - t.details && - t.details.fragments.forEach(function (e) { - return (e.level = -1); - })), - !1) - ); - }); - tr(i), - (this._levels = i), - this.currentLevelIndex > -1 && - null != (t = this.currentLevel) && - t.details && - (this.currentLevelIndex = - this.currentLevel.details.fragments[0].level), - this.hls.trigger(E.LEVELS_UPDATED, { levels: i }); - }), - (r.onLevelsUpdated = function (e, t) { - var r = t.levels; - this._levels = r; - }), - (r.checkMaxAutoUpdated = function () { - var e = this.hls, - t = e.autoLevelCapping, - r = e.maxAutoLevel, - i = e.maxHdcpLevel; - this._maxAutoLevel !== r && - ((this._maxAutoLevel = r), - this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED, { - autoLevelCapping: t, - levels: this.levels, - maxAutoLevel: r, - minAutoLevel: this.hls.minAutoLevel, - maxHdcpLevel: i, - })); - }), - a(t, [ - { - key: "levels", - get: function () { - return 0 === this._levels.length ? null : this._levels; - }, - }, - { - key: "level", - get: function () { - return this.currentLevelIndex; - }, - set: function (e) { - var t = this._levels; - if (0 !== t.length) { - if (e < 0 || e >= t.length) { - var r = new Error("invalid level idx"), - i = e < 0; - if ( - (this.hls.trigger(E.ERROR, { - type: S.OTHER_ERROR, - details: T.LEVEL_SWITCH_ERROR, - level: e, - fatal: i, - error: r, - reason: r.message, - }), - i) - ) - return; - e = Math.min(e, t.length - 1); - } - var n = this.currentLevelIndex, - s = this.currentLevel, - a = s ? s.attrs["PATHWAY-ID"] : void 0, - o = t[e], - l = o.attrs["PATHWAY-ID"]; - if ( - ((this.currentLevelIndex = e), - (this.currentLevel = o), - n !== e || !o.details || !s || a !== l) - ) { - this.log( - "Switching to level " + - e + - " (" + - (o.height ? o.height + "p " : "") + - (o.videoRange ? o.videoRange + " " : "") + - (o.codecSet ? o.codecSet + " " : "") + - "@" + - o.bitrate + - ")" + - (l ? " with Pathway " + l : "") + - " from level " + - n + - (a ? " with Pathway " + a : "") - ); - var h = { - level: e, - attrs: o.attrs, - details: o.details, - bitrate: o.bitrate, - averageBitrate: o.averageBitrate, - maxBitrate: o.maxBitrate, - realBitrate: o.realBitrate, - width: o.width, - height: o.height, - codecSet: o.codecSet, - audioCodec: o.audioCodec, - videoCodec: o.videoCodec, - audioGroups: o.audioGroups, - subtitleGroups: o.subtitleGroups, - loaded: o.loaded, - loadError: o.loadError, - fragmentError: o.fragmentError, - name: o.name, - id: o.id, - uri: o.uri, - url: o.url, - urlId: 0, - audioGroupIds: o.audioGroupIds, - textGroupIds: o.textGroupIds, - }; - this.hls.trigger(E.LEVEL_SWITCHING, h); - var u = o.details; - if (!u || u.live) { - var d = this.switchParams( - o.uri, - null == s ? void 0 : s.details, - u - ); - this.loadPlaylist(d); - } - } - } - }, - }, - { - key: "manualLevel", - get: function () { - return this.manualLevelIndex; - }, - set: function (e) { - (this.manualLevelIndex = e), - void 0 === this._startLevel && (this._startLevel = e), - -1 !== e && (this.level = e); - }, - }, - { - key: "firstLevel", - get: function () { - return this._firstLevel; - }, - set: function (e) { - this._firstLevel = e; - }, - }, - { - key: "startLevel", - get: function () { - if (void 0 === this._startLevel) { - var e = this.hls.config.startLevel; - return void 0 !== e ? e : this.hls.firstAutoLevel; - } - return this._startLevel; - }, - set: function (e) { - this._startLevel = e; - }, - }, - { - key: "nextLoadLevel", - get: function () { - return -1 !== this.manualLevelIndex - ? this.manualLevelIndex - : this.hls.nextAutoLevel; - }, - set: function (e) { - (this.level = e), - -1 === this.manualLevelIndex && - (this.hls.nextAutoLevel = e); - }, - }, - ]), - t - ); - })(cr); - function Aa(e) { - var t = {}; - e.forEach(function (e) { - var r = e.groupId || ""; - (e.id = t[r] = t[r] || 0), t[r]++; - }); - } - var wa = (function () { - function e(e) { - (this.config = void 0), - (this.keyUriToKeyInfo = {}), - (this.emeController = null), - (this.config = e); - } - var t = e.prototype; - return ( - (t.abort = function (e) { - for (var t in this.keyUriToKeyInfo) { - var r = this.keyUriToKeyInfo[t].loader; - if (r) { - var i; - if ( - e && - e !== (null == (i = r.context) ? void 0 : i.frag.type) - ) - return; - r.abort(); - } - } - }), - (t.detach = function () { - for (var e in this.keyUriToKeyInfo) { - var t = this.keyUriToKeyInfo[e]; - (t.mediaKeySessionContext || - t.decryptdata.isCommonEncryption) && - delete this.keyUriToKeyInfo[e]; - } - }), - (t.destroy = function () { - for (var e in (this.detach(), this.keyUriToKeyInfo)) { - var t = this.keyUriToKeyInfo[e].loader; - t && t.destroy(); - } - this.keyUriToKeyInfo = {}; - }), - (t.createKeyLoadError = function (e, t, r, i, n) { - return ( - void 0 === t && (t = T.KEY_LOAD_ERROR), - new Kr({ - type: S.NETWORK_ERROR, - details: t, - fatal: !1, - frag: e, - response: n, - error: r, - networkDetails: i, - }) - ); - }), - (t.loadClear = function (e, t) { - var r = this; - if (this.emeController && this.config.emeEnabled) - for ( - var i = e.sn, - n = e.cc, - s = function () { - var e = t[a]; - if ( - n <= e.cc && - ("initSegment" === i || - "initSegment" === e.sn || - i < e.sn) - ) - return ( - r.emeController - .selectKeySystemFormat(e) - .then(function (t) { - e.setKeyFormat(t); - }), - 1 - ); - }, - a = 0; - a < t.length && !s(); - a++ - ); - }), - (t.load = function (e) { - var t = this; - return !e.decryptdata && e.encrypted && this.emeController - ? this.emeController - .selectKeySystemFormat(e) - .then(function (r) { - return t.loadInternal(e, r); - }) - : this.loadInternal(e); - }), - (t.loadInternal = function (e, t) { - var r, i; - t && e.setKeyFormat(t); - var n = e.decryptdata; - if (!n) { - var s = new Error( - t - ? "Expected frag.decryptdata to be defined after setting format " + - t - : "Missing decryption data on fragment in onKeyLoading" - ); - return Promise.reject( - this.createKeyLoadError(e, T.KEY_LOAD_ERROR, s) - ); - } - var a = n.uri; - if (!a) - return Promise.reject( - this.createKeyLoadError( - e, - T.KEY_LOAD_ERROR, - new Error('Invalid key URI: "' + a + '"') - ) - ); - var o, - l = this.keyUriToKeyInfo[a]; - if (null != (r = l) && r.decryptdata.key) - return ( - (n.key = l.decryptdata.key), - Promise.resolve({ frag: e, keyInfo: l }) - ); - if (null != (i = l) && i.keyLoadPromise) - switch ( - null == (o = l.mediaKeySessionContext) - ? void 0 - : o.keyStatus - ) { - case void 0: - case "status-pending": - case "usable": - case "usable-in-future": - return l.keyLoadPromise.then(function (t) { - return ( - (n.key = t.keyInfo.decryptdata.key), - { frag: e, keyInfo: l } - ); - }); - } - switch ( - ((l = this.keyUriToKeyInfo[a] = - { - decryptdata: n, - keyLoadPromise: null, - loader: null, - mediaKeySessionContext: null, - }), - n.method) - ) { - case "ISO-23001-7": - case "SAMPLE-AES": - case "SAMPLE-AES-CENC": - case "SAMPLE-AES-CTR": - return "identity" === n.keyFormat - ? this.loadKeyHTTP(l, e) - : this.loadKeyEME(l, e); - case "AES-128": - return this.loadKeyHTTP(l, e); - default: - return Promise.reject( - this.createKeyLoadError( - e, - T.KEY_LOAD_ERROR, - new Error( - 'Key supplied with unsupported METHOD: "' + - n.method + - '"' - ) - ) - ); - } - }), - (t.loadKeyEME = function (e, t) { - var r = { frag: t, keyInfo: e }; - if (this.emeController && this.config.emeEnabled) { - var i = this.emeController.loadKey(r); - if (i) - return (e.keyLoadPromise = i.then(function (t) { - return (e.mediaKeySessionContext = t), r; - })).catch(function (t) { - throw ((e.keyLoadPromise = null), t); - }); - } - return Promise.resolve(r); - }), - (t.loadKeyHTTP = function (e, t) { - var r = this, - n = this.config, - s = new (0, n.loader)(n); - return ( - (t.keyLoader = e.loader = s), - (e.keyLoadPromise = new Promise(function (a, o) { - var l = { - keyInfo: e, - frag: t, - responseType: "arraybuffer", - url: e.decryptdata.uri, - }, - h = n.keyLoadPolicy.default, - u = { - loadPolicy: h, - timeout: h.maxLoadTimeMs, - maxRetry: 0, - retryDelay: 0, - maxRetryDelay: 0, - }, - d = { - onSuccess: function (e, t, i, n) { - var s = i.frag, - l = i.keyInfo, - h = i.url; - if (!s.decryptdata || l !== r.keyUriToKeyInfo[h]) - return o( - r.createKeyLoadError( - s, - T.KEY_LOAD_ERROR, - new Error( - "after key load, decryptdata unset or changed" - ), - n - ) - ); - (l.decryptdata.key = s.decryptdata.key = - new Uint8Array(e.data)), - (s.keyLoader = null), - (l.loader = null), - a({ frag: s, keyInfo: l }); - }, - onError: function (e, n, s, a) { - r.resetLoader(n), - o( - r.createKeyLoadError( - t, - T.KEY_LOAD_ERROR, - new Error( - "HTTP Error " + - e.code + - " loading key " + - e.text - ), - s, - i({ url: l.url, data: void 0 }, e) - ) - ); - }, - onTimeout: function (e, i, n) { - r.resetLoader(i), - o( - r.createKeyLoadError( - t, - T.KEY_LOAD_TIMEOUT, - new Error("key loading timed out"), - n - ) - ); - }, - onAbort: function (e, i, n) { - r.resetLoader(i), - o( - r.createKeyLoadError( - t, - T.INTERNAL_ABORTED, - new Error("key loading aborted"), - n - ) - ); - }, - }; - s.load(l, u, d); - })) - ); - }), - (t.resetLoader = function (e) { - var t = e.frag, - r = e.keyInfo, - i = e.url, - n = r.loader; - t.keyLoader === n && - ((t.keyLoader = null), (r.loader = null)), - delete this.keyUriToKeyInfo[i], - n && n.destroy(); - }), - e - ); - })(); - function Pa() { - return self.SourceBuffer || self.WebKitSourceBuffer; - } - function Ia() { - if (!ze()) return !1; - var e = Pa(); - return ( - !e || - (e.prototype && - "function" == typeof e.prototype.appendBuffer && - "function" == typeof e.prototype.remove) - ); - } - var Ca = (function () { - function e(e, t, r, i) { - (this.config = void 0), - (this.media = null), - (this.fragmentTracker = void 0), - (this.hls = void 0), - (this.nudgeRetry = 0), - (this.stallReported = !1), - (this.stalled = null), - (this.moved = !1), - (this.seeking = !1), - (this.config = e), - (this.media = t), - (this.fragmentTracker = r), - (this.hls = i); - } - var t = e.prototype; - return ( - (t.destroy = function () { - (this.media = null), - (this.hls = this.fragmentTracker = null); - }), - (t.poll = function (e, t) { - var r = this.config, - i = this.media, - n = this.stalled; - if (null !== i) { - var s = i.currentTime, - a = i.seeking, - o = this.seeking && !a, - l = !this.seeking && a; - if (((this.seeking = a), s === e)) - if (l || o) this.stalled = null; - else if ( - (i.paused && !a) || - i.ended || - 0 === i.playbackRate || - !Mr.getBuffered(i).length - ) - this.nudgeRetry = 0; - else { - var h = Mr.bufferInfo(i, s, 0), - u = h.nextStart || 0; - if (a) { - var d = h.len > 2, - c = - !u || - (t && t.start <= s) || - (u - s > 2 && - !this.fragmentTracker.getPartialFragment( - s - )); - if (d || c) return; - this.moved = !1; - } - if (!this.moved && null !== this.stalled) { - var f; - if (!(h.len > 0 || u)) return; - var g = Math.max(u, h.start || 0) - s, - p = this.hls.levels - ? this.hls.levels[this.hls.currentLevel] - : null, - m = ( - null == p || null == (f = p.details) - ? void 0 - : f.live - ) - ? 2 * p.details.targetduration - : 2, - v = this.fragmentTracker.getPartialFragment(s); - if (g > 0 && (g <= m || v)) - return void ( - i.paused || this._trySkipBufferHole(v) - ); - } - var y = self.performance.now(); - if (null !== n) { - var E = y - n; - if ( - a || - !(E >= 250) || - (this._reportStall(h), this.media) - ) { - var S = Mr.bufferInfo(i, s, r.maxBufferHole); - this._tryFixBufferStall(S, E); - } - } else this.stalled = y; - } - else if ( - ((this.moved = !0), - a || (this.nudgeRetry = 0), - null !== n) - ) { - if (this.stallReported) { - var T = self.performance.now() - n; - A.warn( - "playback not stuck anymore @" + - s + - ", after " + - Math.round(T) + - "ms" - ), - (this.stallReported = !1); - } - this.stalled = null; - } - } - }), - (t._tryFixBufferStall = function (e, t) { - var r = this.config, - i = this.fragmentTracker, - n = this.media; - if (null !== n) { - var s = n.currentTime, - a = i.getPartialFragment(s); - if (a && (this._trySkipBufferHole(a) || !this.media)) - return; - (e.len > r.maxBufferHole || - (e.nextStart && e.nextStart - s < r.maxBufferHole)) && - t > 1e3 * r.highBufferWatchdogPeriod && - (A.warn("Trying to nudge playhead over buffer-hole"), - (this.stalled = null), - this._tryNudgeBuffer()); - } - }), - (t._reportStall = function (e) { - var t = this.hls, - r = this.media; - if (!this.stallReported && r) { - this.stallReported = !0; - var i = new Error( - "Playback stalling at @" + - r.currentTime + - " due to low buffer (" + - JSON.stringify(e) + - ")" - ); - A.warn(i.message), - t.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.BUFFER_STALLED_ERROR, - fatal: !1, - error: i, - buffer: e.len, - }); - } - }), - (t._trySkipBufferHole = function (e) { - var t = this.config, - r = this.hls, - i = this.media; - if (null === i) return 0; - var n = i.currentTime, - s = Mr.bufferInfo(i, n, 0), - a = n < s.start ? s.start : s.nextStart; - if (a) { - var o = s.len <= t.maxBufferHole, - l = s.len > 0 && s.len < 1 && i.readyState < 3, - h = a - n; - if (h > 0 && (o || l)) { - if (h > t.maxBufferHole) { - var u = this.fragmentTracker, - d = !1; - if (0 === n) { - var c = u.getAppendedFrag(0, Lt); - c && a < c.end && (d = !0); - } - if (!d) { - var f = e || u.getAppendedFrag(n, Lt); - if (f) { - for (var g = !1, p = f.end; p < a; ) { - var m = u.getPartialFragment(p); - if (!m) { - g = !0; - break; - } - p += m.duration; - } - if (g) return 0; - } - } - } - var v = Math.max(a + 0.05, n + 0.1); - if ( - (A.warn( - "skipping hole, adjusting currentTime from " + - n + - " to " + - v - ), - (this.moved = !0), - (this.stalled = null), - (i.currentTime = v), - e && !e.gap) - ) { - var y = new Error( - "fragment loaded with buffer holes, seeking from " + - n + - " to " + - v - ); - r.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.BUFFER_SEEK_OVER_HOLE, - fatal: !1, - error: y, - reason: y.message, - frag: e, - }); - } - return v; - } - } - return 0; - }), - (t._tryNudgeBuffer = function () { - var e = this.config, - t = this.hls, - r = this.media, - i = this.nudgeRetry; - if (null !== r) { - var n = r.currentTime; - if ((this.nudgeRetry++, i < e.nudgeMaxRetry)) { - var s = n + (i + 1) * e.nudgeOffset, - a = new Error( - "Nudging 'currentTime' from " + n + " to " + s - ); - A.warn(a.message), - (r.currentTime = s), - t.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.BUFFER_NUDGE_ON_STALL, - error: a, - fatal: !1, - }); - } else { - var o = new Error( - "Playhead still not moving while enough data buffered @" + - n + - " after " + - e.nudgeMaxRetry + - " nudges" - ); - A.error(o.message), - t.trigger(E.ERROR, { - type: S.MEDIA_ERROR, - details: T.BUFFER_STALLED_ERROR, - error: o, - fatal: !0, - }); - } - } - }), - e - ); - })(), - ka = (function (e) { - function t(t, r, i) { - var n; - return ( - ((n = - e.call(this, t, r, i, "[stream-controller]", Lt) || - this).audioCodecSwap = !1), - (n.gapController = null), - (n.level = -1), - (n._forceStartLoad = !1), - (n.altAudio = !1), - (n.audioOnly = !1), - (n.fragPlaying = null), - (n.onvplaying = null), - (n.onvseeked = null), - (n.fragLastKbps = 0), - (n.couldBacktrack = !1), - (n.backtrackFragment = null), - (n.audioCodecSwitch = !1), - (n.videoBuffer = null), - n._registerListeners(), - n - ); - } - l(t, e); - var r = t.prototype; - return ( - (r._registerListeners = function () { - var e = this.hls; - e.on(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.on(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.on(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.on(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.on(E.LEVEL_LOADING, this.onLevelLoading, this), - e.on(E.LEVEL_LOADED, this.onLevelLoaded, this), - e.on( - E.FRAG_LOAD_EMERGENCY_ABORTED, - this.onFragLoadEmergencyAborted, - this - ), - e.on(E.ERROR, this.onError, this), - e.on( - E.AUDIO_TRACK_SWITCHING, - this.onAudioTrackSwitching, - this - ), - e.on( - E.AUDIO_TRACK_SWITCHED, - this.onAudioTrackSwitched, - this - ), - e.on(E.BUFFER_CREATED, this.onBufferCreated, this), - e.on(E.BUFFER_FLUSHED, this.onBufferFlushed, this), - e.on(E.LEVELS_UPDATED, this.onLevelsUpdated, this), - e.on(E.FRAG_BUFFERED, this.onFragBuffered, this); - }), - (r._unregisterListeners = function () { - var e = this.hls; - e.off(E.MEDIA_ATTACHED, this.onMediaAttached, this), - e.off(E.MEDIA_DETACHING, this.onMediaDetaching, this), - e.off(E.MANIFEST_LOADING, this.onManifestLoading, this), - e.off(E.MANIFEST_PARSED, this.onManifestParsed, this), - e.off(E.LEVEL_LOADED, this.onLevelLoaded, this), - e.off( - E.FRAG_LOAD_EMERGENCY_ABORTED, - this.onFragLoadEmergencyAborted, - this - ), - e.off(E.ERROR, this.onError, this), - e.off( - E.AUDIO_TRACK_SWITCHING, - this.onAudioTrackSwitching, - this - ), - e.off( - E.AUDIO_TRACK_SWITCHED, - this.onAudioTrackSwitched, - this - ), - e.off(E.BUFFER_CREATED, this.onBufferCreated, this), - e.off(E.BUFFER_FLUSHED, this.onBufferFlushed, this), - e.off(E.LEVELS_UPDATED, this.onLevelsUpdated, this), - e.off(E.FRAG_BUFFERED, this.onFragBuffered, this); - }), - (r.onHandlerDestroying = function () { - this._unregisterListeners(), - e.prototype.onHandlerDestroying.call(this); - }), - (r.startLoad = function (e) { - if (this.levels) { - var t = this.lastCurrentTime, - r = this.hls; - if ( - (this.stopLoad(), - this.setInterval(100), - (this.level = -1), - !this.startFragRequested) - ) { - var i = r.startLevel; - -1 === i && - (r.config.testBandwidth && this.levels.length > 1 - ? ((i = 0), (this.bitrateTest = !0)) - : (i = r.firstAutoLevel)), - (r.nextLoadLevel = i), - (this.level = r.loadLevel), - (this.loadedmetadata = !1); - } - t > 0 && - -1 === e && - (this.log( - "Override startPosition with lastCurrentTime @" + - t.toFixed(3) - ), - (e = t)), - (this.state = zr), - (this.nextLoadPosition = - this.startPosition = - this.lastCurrentTime = - e), - this.tick(); - } else (this._forceStartLoad = !0), (this.state = Yr); - }), - (r.stopLoad = function () { - (this._forceStartLoad = !1), - e.prototype.stopLoad.call(this); - }), - (r.doTick = function () { - switch (this.state) { - case si: - var e = this.levels, - t = this.level, - r = null == e ? void 0 : e[t], - i = null == r ? void 0 : r.details; - if (i && (!i.live || this.levelLastLoaded === r)) { - if (this.waitForCdnTuneIn(i)) break; - this.state = zr; - break; - } - if (this.hls.nextLoadLevel !== this.level) { - this.state = zr; - break; - } - break; - case Jr: - var n, - s = self.performance.now(), - a = this.retryDate; - if ( - !a || - s >= a || - (null != (n = this.media) && n.seeking) - ) { - var o = this.levels, - l = this.level, - h = null == o ? void 0 : o[l]; - this.resetStartWhenNotLoaded(h || null), - (this.state = zr); - } - } - this.state === zr && this.doTickIdle(), this.onTickEnd(); - }), - (r.onTickEnd = function () { - e.prototype.onTickEnd.call(this), - this.checkBuffer(), - this.checkFragmentChanged(); - }), - (r.doTickIdle = function () { - var e = this.hls, - t = this.levelLastLoaded, - r = this.levels, - i = this.media; - if ( - null !== t && - (i || - (!this.startFragRequested && - e.config.startFragPrefetch)) && - (!this.altAudio || !this.audioOnly) - ) { - var n = e.nextLoadLevel; - if (null != r && r[n]) { - var s = r[n], - a = this.getMainFwdBufferInfo(); - if (null !== a) { - var o = this.getLevelDetails(); - if (o && this._streamEnded(a, o)) { - var l = {}; - return ( - this.altAudio && (l.type = "video"), - this.hls.trigger(E.BUFFER_EOS, l), - void (this.state = ri) - ); - } - e.loadLevel !== n && - -1 === e.manualLevel && - this.log( - "Adapting to level " + - n + - " from level " + - this.level - ), - (this.level = e.nextLoadLevel = n); - var h = s.details; - if ( - !h || - this.state === si || - (h.live && this.levelLastLoaded !== s) - ) - return (this.level = n), void (this.state = si); - var u = a.len, - d = this.getMaxBufferLength(s.maxBitrate); - if (!(u >= d)) { - this.backtrackFragment && - this.backtrackFragment.start > a.end && - (this.backtrackFragment = null); - var c = this.backtrackFragment - ? this.backtrackFragment.start - : a.end, - f = this.getNextFragment(c, h); - if ( - this.couldBacktrack && - !this.fragPrevious && - f && - "initSegment" !== f.sn && - this.fragmentTracker.getState(f) !== Pr - ) { - var g, - p = - (null != (g = this.backtrackFragment) - ? g - : f - ).sn - h.startSN, - m = h.fragments[p - 1]; - m && - f.cc === m.cc && - ((f = m), - this.fragmentTracker.removeFragment(m)); - } else - this.backtrackFragment && - a.len && - (this.backtrackFragment = null); - if (f && this.isLoopLoading(f, c)) { - if (!f.gap) { - var v = - this.audioOnly && !this.altAudio ? M : x, - y = - (v === x - ? this.videoBuffer - : this.mediaBuffer) || this.media; - y && this.afterBufferFlushed(y, v, Lt); - } - f = this.getNextFragmentLoopLoading( - f, - h, - a, - Lt, - d - ); - } - f && - (!f.initSegment || - f.initSegment.data || - this.bitrateTest || - (f = f.initSegment), - this.loadFragment(f, s, c)); - } - } - } - } - }), - (r.loadFragment = function (t, r, i) { - var n = this.fragmentTracker.getState(t); - (this.fragCurrent = t), - n === Rr || n === wr - ? "initSegment" === t.sn - ? this._loadInitSegment(t, r) - : this.bitrateTest - ? (this.log( - "Fragment " + - t.sn + - " of level " + - t.level + - " is being downloaded to test bitrate and will not be buffered" - ), - this._loadBitrateTestFrag(t, r)) - : ((this.startFragRequested = !0), - e.prototype.loadFragment.call(this, t, r, i)) - : this.clearTrackerIfNeeded(t); - }), - (r.getBufferedFrag = function (e) { - return this.fragmentTracker.getBufferedFrag(e, Lt); - }), - (r.followingBufferedFrag = function (e) { - return e ? this.getBufferedFrag(e.end + 0.5) : null; - }), - (r.immediateLevelSwitch = function () { - this.abortCurrentFrag(), - this.flushMainBuffer(0, Number.POSITIVE_INFINITY); - }), - (r.nextLevelSwitch = function () { - var e = this.levels, - t = this.media; - if (null != t && t.readyState) { - var r, - i = this.getAppendedFrag(t.currentTime); - i && - i.start > 1 && - this.flushMainBuffer(0, i.start - 1); - var n = this.getLevelDetails(); - if (null != n && n.live) { - var s = this.getMainFwdBufferInfo(); - if (!s || s.len < 2 * n.targetduration) return; - } - if (!t.paused && e) { - var a = e[this.hls.nextLoadLevel], - o = this.fragLastKbps; - r = - o && this.fragCurrent - ? (this.fragCurrent.duration * a.maxBitrate) / - (1e3 * o) + - 1 - : 0; - } else r = 0; - var l = this.getBufferedFrag(t.currentTime + r); - if (l) { - var h = this.followingBufferedFrag(l); - if (h) { - this.abortCurrentFrag(); - var u = h.maxStartPTS ? h.maxStartPTS : h.start, - d = h.duration, - c = Math.max( - l.end, - u + - Math.min( - Math.max( - d - this.config.maxFragLookUpTolerance, - d * (this.couldBacktrack ? 0.5 : 0.125) - ), - d * (this.couldBacktrack ? 0.75 : 0.25) - ) - ); - this.flushMainBuffer(c, Number.POSITIVE_INFINITY); - } - } - } - }), - (r.abortCurrentFrag = function () { - var e = this.fragCurrent; - switch ( - ((this.fragCurrent = null), - (this.backtrackFragment = null), - e && - (e.abortRequests(), - this.fragmentTracker.removeFragment(e)), - this.state) - ) { - case Xr: - case Qr: - case Jr: - case ei: - case ti: - this.state = zr; - } - this.nextLoadPosition = this.getLoadPosition(); - }), - (r.flushMainBuffer = function (t, r) { - e.prototype.flushMainBuffer.call( - this, - t, - r, - this.altAudio ? "video" : null - ); - }), - (r.onMediaAttached = function (t, r) { - e.prototype.onMediaAttached.call(this, t, r); - var i = r.media; - (this.onvplaying = this.onMediaPlaying.bind(this)), - (this.onvseeked = this.onMediaSeeked.bind(this)), - i.addEventListener("playing", this.onvplaying), - i.addEventListener("seeked", this.onvseeked), - (this.gapController = new Ca( - this.config, - i, - this.fragmentTracker, - this.hls - )); - }), - (r.onMediaDetaching = function () { - var t = this.media; - t && - this.onvplaying && - this.onvseeked && - (t.removeEventListener("playing", this.onvplaying), - t.removeEventListener("seeked", this.onvseeked), - (this.onvplaying = this.onvseeked = null), - (this.videoBuffer = null)), - (this.fragPlaying = null), - this.gapController && - (this.gapController.destroy(), - (this.gapController = null)), - e.prototype.onMediaDetaching.call(this); - }), - (r.onMediaPlaying = function () { - this.tick(); - }), - (r.onMediaSeeked = function () { - var e = this.media, - t = e ? e.currentTime : null; - m(t) && this.log("Media seeked to " + t.toFixed(3)); - var r = this.getMainFwdBufferInfo(); - null !== r && 0 !== r.len - ? this.tick() - : this.warn( - 'Main forward buffer length on "seeked" event ' + - (r ? r.len : "empty") + - ")" - ); - }), - (r.onManifestLoading = function () { - this.log("Trigger BUFFER_RESET"), - this.hls.trigger(E.BUFFER_RESET, void 0), - this.fragmentTracker.removeAllFragments(), - (this.couldBacktrack = !1), - (this.startPosition = - this.lastCurrentTime = - this.fragLastKbps = - 0), - (this.levels = - this.fragPlaying = - this.backtrackFragment = - this.levelLastLoaded = - null), - (this.altAudio = - this.audioOnly = - this.startFragRequested = - !1); - }), - (r.onManifestParsed = function (e, t) { - var r, - i, - n = !1, - s = !1; - t.levels.forEach(function (e) { - var t = e.audioCodec; - t && - ((n = n || -1 !== t.indexOf("mp4a.40.2")), - (s = s || -1 !== t.indexOf("mp4a.40.5"))); - }), - (this.audioCodecSwitch = - n && - s && - !( - "function" == - typeof (null == (i = Pa()) || - null == (r = i.prototype) - ? void 0 - : r.changeType) - )), - this.audioCodecSwitch && - this.log( - "Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC" - ), - (this.levels = t.levels), - (this.startFragRequested = !1); - }), - (r.onLevelLoading = function (e, t) { - var r = this.levels; - if (r && this.state === zr) { - var i = r[t.level]; - (!i.details || - (i.details.live && this.levelLastLoaded !== i) || - this.waitForCdnTuneIn(i.details)) && - (this.state = si); - } - }), - (r.onLevelLoaded = function (e, t) { - var r, - i = this.levels, - n = t.level, - s = t.details, - a = s.totalduration; - if (i) { - this.log( - "Level " + - n + - " loaded [" + - s.startSN + - "," + - s.endSN + - "]" + - (s.lastPartSn - ? "[part-" + - s.lastPartSn + - "-" + - s.lastPartIndex + - "]" - : "") + - ", cc [" + - s.startCC + - ", " + - s.endCC + - "] duration:" + - a - ); - var o = i[n], - l = this.fragCurrent; - !l || - (this.state !== Qr && this.state !== Jr) || - (l.level !== t.level && - l.loader && - this.abortCurrentFrag()); - var h = 0; - if (s.live || (null != (r = o.details) && r.live)) { - var u; - if ((this.checkLiveUpdate(s), s.deltaUpdateFailed)) - return; - h = this.alignPlaylists( - s, - o.details, - null == (u = this.levelLastLoaded) - ? void 0 - : u.details - ); - } - if ( - ((o.details = s), - (this.levelLastLoaded = o), - this.hls.trigger(E.LEVEL_UPDATED, { - details: s, - level: n, - }), - this.state === si) - ) { - if (this.waitForCdnTuneIn(s)) return; - this.state = zr; - } - this.startFragRequested - ? s.live && this.synchronizeToLiveEdge(s) - : this.setStartPosition(s, h), - this.tick(); - } else - this.warn("Levels were reset while loading level " + n); - }), - (r._handleFragmentLoadProgress = function (e) { - var t, - r = e.frag, - i = e.part, - n = e.payload, - s = this.levels; - if (s) { - var a = s[r.level], - o = a.details; - if (!o) - return ( - this.warn( - "Dropping fragment " + - r.sn + - " of level " + - r.level + - " after level details were reset" - ), - void this.fragmentTracker.removeFragment(r) - ); - var l = a.videoCodec, - h = o.PTSKnown || !o.live, - u = null == (t = r.initSegment) ? void 0 : t.data, - d = this._getAudioCodec(a), - c = (this.transmuxer = - this.transmuxer || - new Tn( - this.hls, - Lt, - this._handleTransmuxComplete.bind(this), - this._handleTransmuxerFlush.bind(this) - )), - f = i ? i.index : -1, - g = -1 !== f, - p = new xr( - r.level, - r.sn, - r.stats.chunkCount, - n.byteLength, - f, - g - ), - m = this.initPTS[r.cc]; - c.push(n, u, d, l, r, i, o.totalduration, h, p, m); - } else - this.warn( - "Levels were reset while fragment load was in progress. Fragment " + - r.sn + - " of level " + - r.level + - " will not be buffered" - ); - }), - (r.onAudioTrackSwitching = function (e, t) { - var r = this.altAudio; - if (!t.url) { - if (this.mediaBuffer !== this.media) { - this.log( - "Switching on main audio, use media.buffered to schedule main fragment loading" - ), - (this.mediaBuffer = this.media); - var i = this.fragCurrent; - i && - (this.log( - "Switching to main audio track, cancel main fragment load" - ), - i.abortRequests(), - this.fragmentTracker.removeFragment(i)), - this.resetTransmuxer(), - this.resetLoadingState(); - } else this.audioOnly && this.resetTransmuxer(); - var n = this.hls; - r && - (n.trigger(E.BUFFER_FLUSHING, { - startOffset: 0, - endOffset: Number.POSITIVE_INFINITY, - type: null, - }), - this.fragmentTracker.removeAllFragments()), - n.trigger(E.AUDIO_TRACK_SWITCHED, t); - } - }), - (r.onAudioTrackSwitched = function (e, t) { - var r = t.id, - i = !!this.hls.audioTracks[r].url; - if (i) { - var n = this.videoBuffer; - n && - this.mediaBuffer !== n && - (this.log( - "Switching on alternate audio, use video.buffered to schedule main fragment loading" - ), - (this.mediaBuffer = n)); - } - (this.altAudio = i), this.tick(); - }), - (r.onBufferCreated = function (e, t) { - var r, - i, - n = t.tracks, - s = !1; - for (var a in n) { - var o = n[a]; - if ("main" === o.id) { - if (((i = a), (r = o), "video" === a)) { - var l = n[a]; - l && (this.videoBuffer = l.buffer); - } - } else s = !0; - } - s && r - ? (this.log( - "Alternate track found, use " + - i + - ".buffered to schedule main fragment loading" - ), - (this.mediaBuffer = r.buffer)) - : (this.mediaBuffer = this.media); - }), - (r.onFragBuffered = function (e, t) { - var r = t.frag, - i = t.part; - if (!r || r.type === Lt) { - if (this.fragContextChanged(r)) - return ( - this.warn( - "Fragment " + - r.sn + - (i ? " p: " + i.index : "") + - " of level " + - r.level + - " finished buffering, but was aborted. state: " + - this.state - ), - void (this.state === ti && (this.state = zr)) - ); - var n = i ? i.stats : r.stats; - (this.fragLastKbps = Math.round( - (8 * n.total) / (n.buffering.end - n.loading.first) - )), - "initSegment" !== r.sn && (this.fragPrevious = r), - this.fragBufferedComplete(r, i); - } - }), - (r.onError = function (e, t) { - var r; - if (t.fatal) this.state = ii; - else - switch (t.details) { - case T.FRAG_GAP: - case T.FRAG_PARSING_ERROR: - case T.FRAG_DECRYPT_ERROR: - case T.FRAG_LOAD_ERROR: - case T.FRAG_LOAD_TIMEOUT: - case T.KEY_LOAD_ERROR: - case T.KEY_LOAD_TIMEOUT: - this.onFragmentOrKeyLoadError(Lt, t); - break; - case T.LEVEL_LOAD_ERROR: - case T.LEVEL_LOAD_TIMEOUT: - case T.LEVEL_PARSING_ERROR: - t.levelRetry || - this.state !== si || - (null == (r = t.context) ? void 0 : r.type) !== - St || - (this.state = zr); - break; - case T.BUFFER_APPEND_ERROR: - case T.BUFFER_FULL_ERROR: - if (!t.parent || "main" !== t.parent) return; - if (t.details === T.BUFFER_APPEND_ERROR) - return void this.resetLoadingState(); - this.reduceLengthAndFlushBuffer(t) && - this.flushMainBuffer(0, Number.POSITIVE_INFINITY); - break; - case T.INTERNAL_EXCEPTION: - this.recoverWorkerError(t); - } - }), - (r.checkBuffer = function () { - var e = this.media, - t = this.gapController; - if (e && t && e.readyState) { - if (this.loadedmetadata || !Mr.getBuffered(e).length) { - var r = this.state !== zr ? this.fragCurrent : null; - t.poll(this.lastCurrentTime, r); - } - this.lastCurrentTime = e.currentTime; - } - }), - (r.onFragLoadEmergencyAborted = function () { - (this.state = zr), - this.loadedmetadata || - ((this.startFragRequested = !1), - (this.nextLoadPosition = this.startPosition)), - this.tickImmediate(); - }), - (r.onBufferFlushed = function (e, t) { - var r = t.type; - if (r !== M || (this.audioOnly && !this.altAudio)) { - var i = - (r === x ? this.videoBuffer : this.mediaBuffer) || - this.media; - this.afterBufferFlushed(i, r, Lt), this.tick(); - } - }), - (r.onLevelsUpdated = function (e, t) { - this.level > -1 && - this.fragCurrent && - (this.level = this.fragCurrent.level), - (this.levels = t.levels); - }), - (r.swapAudioCodec = function () { - this.audioCodecSwap = !this.audioCodecSwap; - }), - (r.seekToStartPos = function () { - var e = this.media; - if (e) { - var t = e.currentTime, - r = this.startPosition; - if (r >= 0 && t < r) { - if (e.seeking) - return void this.log( - "could not seek to " + - r + - ", already seeking at " + - t - ); - var i = Mr.getBuffered(e), - n = (i.length ? i.start(0) : 0) - r; - n > 0 && - (n < this.config.maxBufferHole || - n < this.config.maxFragLookUpTolerance) && - (this.log( - "adjusting start position by " + - n + - " to match buffer start" - ), - (r += n), - (this.startPosition = r)), - this.log( - "seek to target start position " + - r + - " from current time " + - t - ), - (e.currentTime = r); - } - } - }), - (r._getAudioCodec = function (e) { - var t = this.config.defaultAudioCodec || e.audioCodec; - return ( - this.audioCodecSwap && - t && - (this.log("Swapping audio codec"), - (t = - -1 !== t.indexOf("mp4a.40.5") - ? "mp4a.40.2" - : "mp4a.40.5")), - t - ); - }), - (r._loadBitrateTestFrag = function (e, t) { - var r = this; - (e.bitrateTest = !0), - this._doFragLoad(e, t).then(function (i) { - var n = r.hls; - if (i && !r.fragContextChanged(e)) { - (t.fragmentError = 0), - (r.state = zr), - (r.startFragRequested = !1), - (r.bitrateTest = !1); - var s = e.stats; - (s.parsing.start = - s.parsing.end = - s.buffering.start = - s.buffering.end = - self.performance.now()), - n.trigger(E.FRAG_LOADED, i), - (e.bitrateTest = !1); - } - }); - }), - (r._handleTransmuxComplete = function (e) { - var t, - r = "main", - i = this.hls, - n = e.remuxResult, - s = e.chunkMeta, - a = this.getCurrentContext(s); - if (a) { - var o = a.frag, - l = a.part, - h = a.level, - u = n.video, - d = n.text, - c = n.id3, - f = n.initSegment, - g = h.details, - p = this.altAudio ? void 0 : n.audio; - if (this.fragContextChanged(o)) - this.fragmentTracker.removeFragment(o); - else { - if (((this.state = ei), f)) { - if (null != f && f.tracks) { - var v = o.initSegment || o; - this._bufferInitSegment(h, f.tracks, v, s), - i.trigger(E.FRAG_PARSING_INIT_SEGMENT, { - frag: v, - id: r, - tracks: f.tracks, - }); - } - var y = f.initPTS, - S = f.timescale; - m(y) && - ((this.initPTS[o.cc] = { - baseTime: y, - timescale: S, - }), - i.trigger(E.INIT_PTS_FOUND, { - frag: o, - id: r, - initPTS: y, - timescale: S, - })); - } - if (u && g && "initSegment" !== o.sn) { - var T = g.fragments[o.sn - 1 - g.startSN], - _ = o.sn === g.startSN, - L = !T || o.cc > T.cc; - if (!1 !== n.independent) { - var b = u.startPTS, - R = u.endPTS, - A = u.startDTS, - w = u.endDTS; - if (l) - l.elementaryStreams[u.type] = { - startPTS: b, - endPTS: R, - startDTS: A, - endDTS: w, - }; - else if ( - (u.firstKeyFrame && - u.independent && - 1 === s.id && - !L && - (this.couldBacktrack = !0), - u.dropped && u.independent) - ) { - var P = this.getMainFwdBufferInfo(), - I = - (P ? P.end : this.getLoadPosition()) + - this.config.maxBufferHole, - C = u.firstKeyFramePTS - ? u.firstKeyFramePTS - : b; - if ( - !_ && - I < C - this.config.maxBufferHole && - !L - ) - return void this.backtrack(o); - L && (o.gap = !0), - o.setElementaryStreamInfo( - u.type, - o.start, - R, - o.start, - w, - !0 - ); - } else _ && b > 2 && (o.gap = !0); - o.setElementaryStreamInfo(u.type, b, R, A, w), - this.backtrackFragment && - (this.backtrackFragment = o), - this.bufferFragmentData(u, o, l, s, _ || L); - } else { - if (!_ && !L) return void this.backtrack(o); - o.gap = !0; - } - } - if (p) { - var k = p.startPTS, - D = p.endPTS, - x = p.startDTS, - O = p.endDTS; - l && - (l.elementaryStreams[M] = { - startPTS: k, - endPTS: D, - startDTS: x, - endDTS: O, - }), - o.setElementaryStreamInfo(M, k, D, x, O), - this.bufferFragmentData(p, o, l, s); - } - if ( - g && - null != c && - null != (t = c.samples) && - t.length - ) { - var F = { - id: r, - frag: o, - details: g, - samples: c.samples, - }; - i.trigger(E.FRAG_PARSING_METADATA, F); - } - if (g && d) { - var N = { - id: r, - frag: o, - details: g, - samples: d.samples, - }; - i.trigger(E.FRAG_PARSING_USERDATA, N); - } - } - } else this.resetWhenMissingContext(s); - }), - (r._bufferInitSegment = function (e, t, r, i) { - var n = this; - if (this.state === ei) { - (this.audioOnly = !!t.audio && !t.video), - this.altAudio && !this.audioOnly && delete t.audio; - var s = t.audio, - a = t.video, - o = t.audiovideo; - if (s) { - var l = e.audioCodec, - h = navigator.userAgent.toLowerCase(); - if (this.audioCodecSwitch) { - l && - (l = - -1 !== l.indexOf("mp4a.40.5") - ? "mp4a.40.2" - : "mp4a.40.5"); - var u = s.metadata; - u && - "channelCount" in u && - 1 !== (u.channelCount || 1) && - -1 === h.indexOf("firefox") && - (l = "mp4a.40.5"); - } - l && - -1 !== l.indexOf("mp4a.40.5") && - -1 !== h.indexOf("android") && - "audio/mpeg" !== s.container && - ((l = "mp4a.40.2"), - this.log("Android: force audio codec to " + l)), - e.audioCodec && - e.audioCodec !== l && - this.log( - 'Swapping manifest audio codec "' + - e.audioCodec + - '" for "' + - l + - '"' - ), - (s.levelCodec = l), - (s.id = "main"), - this.log( - "Init audio buffer, container:" + - s.container + - ", codecs[selected/level/parsed]=[" + - (l || "") + - "/" + - (e.audioCodec || "") + - "/" + - s.codec + - "]" - ); - } - a && - ((a.levelCodec = e.videoCodec), - (a.id = "main"), - this.log( - "Init video buffer, container:" + - a.container + - ", codecs[level/parsed]=[" + - (e.videoCodec || "") + - "/" + - a.codec + - "]" - )), - o && - this.log( - "Init audiovideo buffer, container:" + - o.container + - ", codecs[level/parsed]=[" + - e.codecs + - "/" + - o.codec + - "]" - ), - this.hls.trigger(E.BUFFER_CODECS, t), - Object.keys(t).forEach(function (e) { - var s = t[e].initSegment; - null != s && - s.byteLength && - n.hls.trigger(E.BUFFER_APPENDING, { - type: e, - data: s, - frag: r, - part: null, - chunkMeta: i, - parent: r.type, - }); - }), - this.tickImmediate(); - } - }), - (r.getMainFwdBufferInfo = function () { - return this.getFwdBufferInfo( - this.mediaBuffer ? this.mediaBuffer : this.media, - Lt - ); - }), - (r.backtrack = function (e) { - (this.couldBacktrack = !0), - (this.backtrackFragment = e), - this.resetTransmuxer(), - this.flushBufferGap(e), - this.fragmentTracker.removeFragment(e), - (this.fragPrevious = null), - (this.nextLoadPosition = e.start), - (this.state = zr); - }), - (r.checkFragmentChanged = function () { - var e = this.media, - t = null; - if (e && e.readyState > 1 && !1 === e.seeking) { - var r = e.currentTime; - if ( - (Mr.isBuffered(e, r) - ? (t = this.getAppendedFrag(r)) - : Mr.isBuffered(e, r + 0.1) && - (t = this.getAppendedFrag(r + 0.1)), - t) - ) { - this.backtrackFragment = null; - var i = this.fragPlaying, - n = t.level; - (i && t.sn === i.sn && i.level === n) || - ((this.fragPlaying = t), - this.hls.trigger(E.FRAG_CHANGED, { frag: t }), - (i && i.level === n) || - this.hls.trigger(E.LEVEL_SWITCHED, { level: n })); - } - } - }), - a(t, [ - { - key: "nextLevel", - get: function () { - var e = this.nextBufferedFrag; - return e ? e.level : -1; - }, - }, - { - key: "currentFrag", - get: function () { - var e = this.media; - return e - ? this.fragPlaying || - this.getAppendedFrag(e.currentTime) - : null; - }, - }, - { - key: "currentProgramDateTime", - get: function () { - var e = this.media; - if (e) { - var t = e.currentTime, - r = this.currentFrag; - if (r && m(t) && m(r.programDateTime)) { - var i = r.programDateTime + 1e3 * (t - r.start); - return new Date(i); - } - } - return null; - }, - }, - { - key: "currentLevel", - get: function () { - var e = this.currentFrag; - return e ? e.level : -1; - }, - }, - { - key: "nextBufferedFrag", - get: function () { - var e = this.currentFrag; - return e ? this.followingBufferedFrag(e) : null; - }, - }, - { - key: "forceStartLoad", - get: function () { - return this._forceStartLoad; - }, - }, - ]), - t - ); - })(ai), - Da = (function () { - function e(t) { - void 0 === t && (t = {}), - (this.config = void 0), - (this.userConfig = void 0), - (this.coreComponents = void 0), - (this.networkControllers = void 0), - (this.started = !1), - (this._emitter = new vn()), - (this._autoLevelCapping = -1), - (this._maxHdcpLevel = null), - (this.abrController = void 0), - (this.bufferController = void 0), - (this.capLevelController = void 0), - (this.latencyController = void 0), - (this.levelController = void 0), - (this.streamController = void 0), - (this.audioTrackController = void 0), - (this.subtitleTrackController = void 0), - (this.emeController = void 0), - (this.cmcdController = void 0), - (this._media = null), - (this.url = null), - (this.triggeringException = void 0), - R(t.debug || !1, "Hls instance"); - var r = (this.config = (function (e, t) { - if ( - (t.liveSyncDurationCount || - t.liveMaxLatencyDurationCount) && - (t.liveSyncDuration || t.liveMaxLatencyDuration) - ) - throw new Error( - "Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration" - ); - if ( - void 0 !== t.liveMaxLatencyDurationCount && - (void 0 === t.liveSyncDurationCount || - t.liveMaxLatencyDurationCount <= - t.liveSyncDurationCount) - ) - throw new Error( - 'Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"' - ); - if ( - void 0 !== t.liveMaxLatencyDuration && - (void 0 === t.liveSyncDuration || - t.liveMaxLatencyDuration <= t.liveSyncDuration) - ) - throw new Error( - 'Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"' - ); - var r = ba(e), - n = [ - "TimeOut", - "MaxRetry", - "RetryDelay", - "MaxRetryTimeout", - ]; - return ( - ["manifest", "level", "frag"].forEach(function (e) { - var i = - ("level" === e ? "playlist" : e) + "LoadPolicy", - s = void 0 === t[i], - a = []; - n.forEach(function (n) { - var o = e + "Loading" + n, - l = t[o]; - if (void 0 !== l && s) { - a.push(o); - var h = r[i].default; - switch (((t[i] = { default: h }), n)) { - case "TimeOut": - (h.maxLoadTimeMs = l), - (h.maxTimeToFirstByteMs = l); - break; - case "MaxRetry": - (h.errorRetry.maxNumRetry = l), - (h.timeoutRetry.maxNumRetry = l); - break; - case "RetryDelay": - (h.errorRetry.retryDelayMs = l), - (h.timeoutRetry.retryDelayMs = l); - break; - case "MaxRetryTimeout": - (h.errorRetry.maxRetryDelayMs = l), - (h.timeoutRetry.maxRetryDelayMs = l); - } - } - }), - a.length && - A.warn( - 'hls.js config: "' + - a.join('", "') + - '" setting(s) are deprecated, use "' + - i + - '": ' + - JSON.stringify(t[i]) - ); - }), - i(i({}, r), t) - ); - })(e.DefaultConfig, t)); - (this.userConfig = t), - r.progressive && - (function (e) { - var t = e.loader; - t !== ya && t !== ma - ? (A.log( - "[config]: Custom loader detected, cannot enable progressive streaming" - ), - (e.progressive = !1)) - : (function () { - if ( - self.fetch && - self.AbortController && - self.ReadableStream && - self.Request - ) - try { - return new self.ReadableStream({}), !0; - } catch (e) {} - return !1; - })() && - ((e.loader = ya), - (e.progressive = !0), - (e.enableSoftwareAES = !0), - A.log( - "[config]: Progressive streaming enabled, using FetchLoader" - )); - })(r); - var n = r.abrController, - s = r.bufferController, - a = r.capLevelController, - o = r.errorController, - l = r.fpsController, - h = new o(this), - u = (this.abrController = new n(this)), - d = (this.bufferController = new s(this)), - c = (this.capLevelController = new a(this)), - f = new l(this), - g = new Pt(this), - p = new Gt(this), - m = r.contentSteeringController, - v = m ? new m(this) : null, - y = (this.levelController = new Ra(this, v)), - S = new Ir(this), - T = new wa(this.config), - _ = (this.streamController = new ka(this, S, T)); - c.setStreamController(_), f.setStreamController(_); - var L = [g, y, _]; - v && L.splice(1, 0, v), (this.networkControllers = L); - var b = [u, d, c, f, p, S]; - this.audioTrackController = this.createController( - r.audioTrackController, - L - ); - var w = r.audioStreamController; - w && L.push(new w(this, S, T)), - (this.subtitleTrackController = this.createController( - r.subtitleTrackController, - L - )); - var P = r.subtitleStreamController; - P && L.push(new P(this, S, T)), - this.createController(r.timelineController, b), - (T.emeController = this.emeController = - this.createController(r.emeController, b)), - (this.cmcdController = this.createController( - r.cmcdController, - b - )), - (this.latencyController = this.createController(Ht, b)), - (this.coreComponents = b), - L.push(h); - var I = h.onErrorOut; - "function" == typeof I && this.on(E.ERROR, I, h); - } - (e.isMSESupported = function () { - return Ia(); - }), - (e.isSupported = function () { - return (function () { - if (!Ia()) return !1; - var e = ze(); - return ( - "function" == - typeof (null == e ? void 0 : e.isTypeSupported) && - ([ - "avc1.42E01E,mp4a.40.2", - "av01.0.01M.08", - "vp09.00.50.08", - ].some(function (t) { - return e.isTypeSupported(Ze(t, "video")); - }) || - ["mp4a.40.2", "fLaC"].some(function (t) { - return e.isTypeSupported(Ze(t, "audio")); - })) - ); - })(); - }), - (e.getMediaSource = function () { - return ze(); - }); - var t = e.prototype; - return ( - (t.createController = function (e, t) { - if (e) { - var r = new e(this); - return t && t.push(r), r; - } - return null; - }), - (t.on = function (e, t, r) { - void 0 === r && (r = this), this._emitter.on(e, t, r); - }), - (t.once = function (e, t, r) { - void 0 === r && (r = this), this._emitter.once(e, t, r); - }), - (t.removeAllListeners = function (e) { - this._emitter.removeAllListeners(e); - }), - (t.off = function (e, t, r, i) { - void 0 === r && (r = this), this._emitter.off(e, t, r, i); - }), - (t.listeners = function (e) { - return this._emitter.listeners(e); - }), - (t.emit = function (e, t, r) { - return this._emitter.emit(e, t, r); - }), - (t.trigger = function (e, t) { - if (this.config.debug) return this.emit(e, e, t); - try { - return this.emit(e, e, t); - } catch (t) { - if ( - (A.error( - "An internal error happened while handling event " + - e + - '. Error message: "' + - t.message + - '". Here is a stacktrace:', - t - ), - !this.triggeringException) - ) { - this.triggeringException = !0; - var r = e === E.ERROR; - this.trigger(E.ERROR, { - type: S.OTHER_ERROR, - details: T.INTERNAL_EXCEPTION, - fatal: r, - event: e, - error: t, - }), - (this.triggeringException = !1); - } - } - return !1; - }), - (t.listenerCount = function (e) { - return this._emitter.listenerCount(e); - }), - (t.destroy = function () { - A.log("destroy"), - this.trigger(E.DESTROYING, void 0), - this.detachMedia(), - this.removeAllListeners(), - (this._autoLevelCapping = -1), - (this.url = null), - this.networkControllers.forEach(function (e) { - return e.destroy(); - }), - (this.networkControllers.length = 0), - this.coreComponents.forEach(function (e) { - return e.destroy(); - }), - (this.coreComponents.length = 0); - var e = this.config; - (e.xhrSetup = e.fetchSetup = void 0), - (this.userConfig = null); - }), - (t.attachMedia = function (e) { - A.log("attachMedia"), - (this._media = e), - this.trigger(E.MEDIA_ATTACHING, { media: e }); - }), - (t.detachMedia = function () { - A.log("detachMedia"), - this.trigger(E.MEDIA_DETACHING, void 0), - (this._media = null); - }), - (t.loadSource = function (e) { - this.stopLoad(); - var t = this.media, - r = this.url, - i = (this.url = p.buildAbsoluteURL( - self.location.href, - e, - { alwaysNormalize: !0 } - )); - (this._autoLevelCapping = -1), - (this._maxHdcpLevel = null), - A.log("loadSource:" + i), - t && - r && - (r !== i || this.bufferController.hasSourceTypes()) && - (this.detachMedia(), this.attachMedia(t)), - this.trigger(E.MANIFEST_LOADING, { url: e }); - }), - (t.startLoad = function (e) { - void 0 === e && (e = -1), - A.log("startLoad(" + e + ")"), - (this.started = !0), - this.networkControllers.forEach(function (t) { - t.startLoad(e); - }); - }), - (t.stopLoad = function () { - A.log("stopLoad"), - (this.started = !1), - this.networkControllers.forEach(function (e) { - e.stopLoad(); - }); - }), - (t.resumeBuffering = function () { - this.started && - this.networkControllers.forEach(function (e) { - "fragmentLoader" in e && e.startLoad(-1); - }); - }), - (t.pauseBuffering = function () { - this.networkControllers.forEach(function (e) { - "fragmentLoader" in e && e.stopLoad(); - }); - }), - (t.swapAudioCodec = function () { - A.log("swapAudioCodec"), - this.streamController.swapAudioCodec(); - }), - (t.recoverMediaError = function () { - A.log("recoverMediaError"); - var e = this._media; - this.detachMedia(), e && this.attachMedia(e); - }), - (t.removeLevel = function (e) { - this.levelController.removeLevel(e); - }), - (t.setAudioOption = function (e) { - var t; - return null == (t = this.audioTrackController) - ? void 0 - : t.setAudioOption(e); - }), - (t.setSubtitleOption = function (e) { - var t; - return ( - null == (t = this.subtitleTrackController) || - t.setSubtitleOption(e), - null - ); - }), - a( - e, - [ - { - key: "levels", - get: function () { - return this.levelController.levels || []; - }, - }, - { - key: "currentLevel", - get: function () { - return this.streamController.currentLevel; - }, - set: function (e) { - A.log("set currentLevel:" + e), - (this.levelController.manualLevel = e), - this.streamController.immediateLevelSwitch(); - }, - }, - { - key: "nextLevel", - get: function () { - return this.streamController.nextLevel; - }, - set: function (e) { - A.log("set nextLevel:" + e), - (this.levelController.manualLevel = e), - this.streamController.nextLevelSwitch(); - }, - }, - { - key: "loadLevel", - get: function () { - return this.levelController.level; - }, - set: function (e) { - A.log("set loadLevel:" + e), - (this.levelController.manualLevel = e); - }, - }, - { - key: "nextLoadLevel", - get: function () { - return this.levelController.nextLoadLevel; - }, - set: function (e) { - this.levelController.nextLoadLevel = e; - }, - }, - { - key: "firstLevel", - get: function () { - return Math.max( - this.levelController.firstLevel, - this.minAutoLevel - ); - }, - set: function (e) { - A.log("set firstLevel:" + e), - (this.levelController.firstLevel = e); - }, - }, - { - key: "startLevel", - get: function () { - var e = this.levelController.startLevel; - return -1 === e && - this.abrController.forcedAutoLevel > -1 - ? this.abrController.forcedAutoLevel - : e; - }, - set: function (e) { - A.log("set startLevel:" + e), - -1 !== e && (e = Math.max(e, this.minAutoLevel)), - (this.levelController.startLevel = e); - }, - }, - { - key: "capLevelToPlayerSize", - get: function () { - return this.config.capLevelToPlayerSize; - }, - set: function (e) { - var t = !!e; - t !== this.config.capLevelToPlayerSize && - (t - ? this.capLevelController.startCapping() - : (this.capLevelController.stopCapping(), - (this.autoLevelCapping = -1), - this.streamController.nextLevelSwitch()), - (this.config.capLevelToPlayerSize = t)); - }, - }, - { - key: "autoLevelCapping", - get: function () { - return this._autoLevelCapping; - }, - set: function (e) { - this._autoLevelCapping !== e && - (A.log("set autoLevelCapping:" + e), - (this._autoLevelCapping = e), - this.levelController.checkMaxAutoUpdated()); - }, - }, - { - key: "bandwidthEstimate", - get: function () { - var e = this.abrController.bwEstimator; - return e ? e.getEstimate() : NaN; - }, - set: function (e) { - this.abrController.resetEstimator(e); - }, - }, - { - key: "ttfbEstimate", - get: function () { - var e = this.abrController.bwEstimator; - return e ? e.getEstimateTTFB() : NaN; - }, - }, - { - key: "maxHdcpLevel", - get: function () { - return this._maxHdcpLevel; - }, - set: function (e) { - (function (e) { - return $t.indexOf(e) > -1; - })(e) && - this._maxHdcpLevel !== e && - ((this._maxHdcpLevel = e), - this.levelController.checkMaxAutoUpdated()); - }, - }, - { - key: "autoLevelEnabled", - get: function () { - return -1 === this.levelController.manualLevel; - }, - }, - { - key: "manualLevel", - get: function () { - return this.levelController.manualLevel; - }, - }, - { - key: "minAutoLevel", - get: function () { - var e = this.levels, - t = this.config.minAutoBitrate; - if (!e) return 0; - for (var r = e.length, i = 0; i < r; i++) - if (e[i].maxBitrate >= t) return i; - return 0; - }, - }, - { - key: "maxAutoLevel", - get: function () { - var e, - t = this.levels, - r = this.autoLevelCapping, - i = this.maxHdcpLevel; - if ( - ((e = - -1 === r && null != t && t.length - ? t.length - 1 - : r), - i) - ) - for (var n = e; n--; ) { - var s = t[n].attrs["HDCP-LEVEL"]; - if (s && s <= i) return n; - } - return e; - }, - }, - { - key: "firstAutoLevel", - get: function () { - return this.abrController.firstAutoLevel; - }, - }, - { - key: "nextAutoLevel", - get: function () { - return this.abrController.nextAutoLevel; - }, - set: function (e) { - this.abrController.nextAutoLevel = e; - }, - }, - { - key: "playingDate", - get: function () { - return this.streamController.currentProgramDateTime; - }, - }, - { - key: "mainForwardBufferInfo", - get: function () { - return this.streamController.getMainFwdBufferInfo(); - }, - }, - { - key: "allAudioTracks", - get: function () { - var e = this.audioTrackController; - return e ? e.allAudioTracks : []; - }, - }, - { - key: "audioTracks", - get: function () { - var e = this.audioTrackController; - return e ? e.audioTracks : []; - }, - }, - { - key: "audioTrack", - get: function () { - var e = this.audioTrackController; - return e ? e.audioTrack : -1; - }, - set: function (e) { - var t = this.audioTrackController; - t && (t.audioTrack = e); - }, - }, - { - key: "allSubtitleTracks", - get: function () { - var e = this.subtitleTrackController; - return e ? e.allSubtitleTracks : []; - }, - }, - { - key: "subtitleTracks", - get: function () { - var e = this.subtitleTrackController; - return e ? e.subtitleTracks : []; - }, - }, - { - key: "subtitleTrack", - get: function () { - var e = this.subtitleTrackController; - return e ? e.subtitleTrack : -1; - }, - set: function (e) { - var t = this.subtitleTrackController; - t && (t.subtitleTrack = e); - }, - }, - { - key: "media", - get: function () { - return this._media; - }, - }, - { - key: "subtitleDisplay", - get: function () { - var e = this.subtitleTrackController; - return !!e && e.subtitleDisplay; - }, - set: function (e) { - var t = this.subtitleTrackController; - t && (t.subtitleDisplay = e); - }, - }, - { - key: "lowLatencyMode", - get: function () { - return this.config.lowLatencyMode; - }, - set: function (e) { - this.config.lowLatencyMode = e; - }, - }, - { - key: "liveSyncPosition", - get: function () { - return this.latencyController.liveSyncPosition; - }, - }, - { - key: "latency", - get: function () { - return this.latencyController.latency; - }, - }, - { - key: "maxLatency", - get: function () { - return this.latencyController.maxLatency; - }, - }, - { - key: "targetLatency", - get: function () { - return this.latencyController.targetLatency; - }, - }, - { - key: "drift", - get: function () { - return this.latencyController.drift; - }, - }, - { - key: "forceStartLoad", - get: function () { - return this.streamController.forceStartLoad; - }, - }, - ], - [ - { - key: "version", - get: function () { - return "1.5.13"; - }, - }, - { - key: "Events", - get: function () { - return E; - }, - }, - { - key: "ErrorTypes", - get: function () { - return S; - }, - }, - { - key: "ErrorDetails", - get: function () { - return T; - }, - }, - { - key: "DefaultConfig", - get: function () { - return e.defaultConfig ? e.defaultConfig : La; - }, - set: function (t) { - e.defaultConfig = t; - }, - }, - ] - ), - e - ); - })(); - return (Da.defaultConfig = void 0), Da; - }), - (e.exports = i()); - })(!1); - }, - 424: (e, t) => { - "use strict"; - t.h = n; - var r = 2147483647; - function i(e) { - if (e > r) - throw new RangeError( - 'The value "' + e + '" is invalid for option "size"' - ); - var t = new Uint8Array(e); - return (t.__proto__ = n.prototype), t; - } - function n(e, t, r) { - if ("number" == typeof e) { - if ("string" == typeof t) - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ); - return o(e); - } - return s(e, t, r); - } - function s(e, t, r) { - if ("string" == typeof e) - return (function (e, t) { - ("string" == typeof t && "" !== t) || (t = "utf8"); - if (!n.isEncoding(t)) - throw new TypeError("Unknown encoding: " + t); - var r = 0 | u(e, t), - s = i(r), - a = s.write(e, t); - a !== r && (s = s.slice(0, a)); - return s; - })(e, t); - if (ArrayBuffer.isView(e)) return l(e); - if (null == e) - throw TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + - typeof e - ); - if (v(e, ArrayBuffer) || (e && v(e.buffer, ArrayBuffer))) - return (function (e, t, r) { - if (t < 0 || e.byteLength < t) - throw new RangeError('"offset" is outside of buffer bounds'); - if (e.byteLength < t + (r || 0)) - throw new RangeError('"length" is outside of buffer bounds'); - var i; - i = - void 0 === t && void 0 === r - ? new Uint8Array(e) - : void 0 === r - ? new Uint8Array(e, t) - : new Uint8Array(e, t, r); - return (i.__proto__ = n.prototype), i; - })(e, t, r); - if ("number" == typeof e) - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ); - var s = e.valueOf && e.valueOf(); - if (null != s && s !== e) return n.from(s, t, r); - var a = (function (e) { - if (n.isBuffer(e)) { - var t = 0 | h(e.length), - r = i(t); - return 0 === r.length || e.copy(r, 0, 0, t), r; - } - if (void 0 !== e.length) - return "number" != typeof e.length || y(e.length) ? i(0) : l(e); - if ("Buffer" === e.type && Array.isArray(e.data)) - return l(e.data); - })(e); - if (a) return a; - if ( - "undefined" != typeof Symbol && - null != Symbol.toPrimitive && - "function" == typeof e[Symbol.toPrimitive] - ) - return n.from(e[Symbol.toPrimitive]("string"), t, r); - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + - typeof e - ); - } - function a(e) { - if ("number" != typeof e) - throw new TypeError('"size" argument must be of type number'); - if (e < 0) - throw new RangeError( - 'The value "' + e + '" is invalid for option "size"' - ); - } - function o(e) { - return a(e), i(e < 0 ? 0 : 0 | h(e)); - } - function l(e) { - for ( - var t = e.length < 0 ? 0 : 0 | h(e.length), r = i(t), n = 0; - n < t; - n += 1 - ) - r[n] = 255 & e[n]; - return r; - } - function h(e) { - if (e >= r) - throw new RangeError( - "Attempt to allocate Buffer larger than maximum size: 0x" + - r.toString(16) + - " bytes" - ); - return 0 | e; - } - function u(e, t) { - if (n.isBuffer(e)) return e.length; - if (ArrayBuffer.isView(e) || v(e, ArrayBuffer)) return e.byteLength; - if ("string" != typeof e) - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + - typeof e - ); - var r = e.length, - i = arguments.length > 2 && !0 === arguments[2]; - if (!i && 0 === r) return 0; - for (var s = !1; ; ) - switch (t) { - case "ascii": - case "latin1": - case "binary": - return r; - case "utf8": - case "utf-8": - return m(e).length; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return 2 * r; - case "hex": - return r >>> 1; - default: - if (s) return i ? -1 : m(e).length; - (t = ("" + t).toLowerCase()), (s = !0); - } - } - function d(e, t, r, i) { - r = Number(r) || 0; - const n = e.length - r; - i ? (i = Number(i)) > n && (i = n) : (i = n); - const s = t.length; - let a; - for (i > s / 2 && (i = s / 2), a = 0; a < i; ++a) { - const i = parseInt(t.substr(2 * a, 2), 16); - if (y(i)) return a; - e[r + a] = i; - } - return a; - } - function c(e, t, r, i) { - return p(m(t, e.length - r), e, r, i); - } - function f(e, t, r, i) { - return p( - (function (e) { - const t = []; - for (let r = 0; r < e.length; ++r) - t.push(255 & e.charCodeAt(r)); - return t; - })(t), - e, - r, - i - ); - } - function g(e, t, r, i) { - return p( - (function (e, t) { - let r, i, n; - const s = []; - for (let a = 0; a < e.length && !((t -= 2) < 0); ++a) - (r = e.charCodeAt(a)), - (i = r >> 8), - (n = r % 256), - s.push(n), - s.push(i); - return s; - })(t, e.length - r), - e, - r, - i - ); - } - function p(e, t, r, i) { - let n; - for (n = 0; n < i && !(n + r >= t.length || n >= e.length); ++n) - t[n + r] = e[n]; - return n; - } - function m(e, t) { - var r; - t = t || 1 / 0; - for (var i = e.length, n = null, s = [], a = 0; a < i; ++a) { - if ((r = e.charCodeAt(a)) > 55295 && r < 57344) { - if (!n) { - if (r > 56319) { - (t -= 3) > -1 && s.push(239, 191, 189); - continue; - } - if (a + 1 === i) { - (t -= 3) > -1 && s.push(239, 191, 189); - continue; - } - n = r; - continue; - } - if (r < 56320) { - (t -= 3) > -1 && s.push(239, 191, 189), (n = r); - continue; - } - r = 65536 + (((n - 55296) << 10) | (r - 56320)); - } else n && (t -= 3) > -1 && s.push(239, 191, 189); - if (((n = null), r < 128)) { - if ((t -= 1) < 0) break; - s.push(r); - } else if (r < 2048) { - if ((t -= 2) < 0) break; - s.push((r >> 6) | 192, (63 & r) | 128); - } else if (r < 65536) { - if ((t -= 3) < 0) break; - s.push((r >> 12) | 224, ((r >> 6) & 63) | 128, (63 & r) | 128); - } else { - if (!(r < 1114112)) throw new Error("Invalid code point"); - if ((t -= 4) < 0) break; - s.push( - (r >> 18) | 240, - ((r >> 12) & 63) | 128, - ((r >> 6) & 63) | 128, - (63 & r) | 128 - ); - } - } - return s; - } - function v(e, t) { - return ( - e instanceof t || - (null != e && - null != e.constructor && - null != e.constructor.name && - e.constructor.name === t.name) - ); - } - function y(e) { - return e != e; - } - "undefined" != typeof Symbol && - null != Symbol.species && - n[Symbol.species] === n && - Object.defineProperty(n, Symbol.species, { - value: null, - configurable: !0, - enumerable: !1, - writable: !1, - }), - (n.from = function (e, t, r) { - return s(e, t, r); - }), - (n.prototype.__proto__ = Uint8Array.prototype), - (n.__proto__ = Uint8Array), - (n.alloc = function (e, t, r) { - return (function (e, t, r) { - return ( - a(e), - e <= 0 - ? i(e) - : void 0 !== t - ? "string" == typeof r - ? i(e).fill(t, r) - : i(e).fill(t) - : i(e) - ); - })(e, t, r); - }), - (n.allocUnsafe = function (e) { - return o(e); - }), - (n.isBuffer = function (e) { - return null != e && !0 === e._isBuffer && e !== n.prototype; - }), - (n.isEncoding = function (e) { - switch (String(e).toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "latin1": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return !0; - default: - return !1; - } - }), - (n.concat = function (e, t) { - if (!Array.isArray(e)) - throw new TypeError( - '"list" argument must be an Array of Buffers' - ); - if (0 === e.length) return n.alloc(0); - var r; - if (void 0 === t) - for (t = 0, r = 0; r < e.length; ++r) t += e[r].length; - var i = n.allocUnsafe(t), - s = 0; - for (r = 0; r < e.length; ++r) { - var a = e[r]; - if ((v(a, Uint8Array) && (a = n.from(a)), !n.isBuffer(a))) - throw new TypeError( - '"list" argument must be an Array of Buffers' - ); - a.copy(i, s), (s += a.length); - } - return i; - }), - (n.byteLength = u), - (n.prototype._isBuffer = !0), - (n.prototype.copy = function (e, t, r, i) { - if (!n.isBuffer(e)) - throw new TypeError("argument should be a Buffer"); - if ( - (r || (r = 0), - i || 0 === i || (i = this.length), - t >= e.length && (t = e.length), - t || (t = 0), - i > 0 && i < r && (i = r), - i === r) - ) - return 0; - if (0 === e.length || 0 === this.length) return 0; - if (t < 0) throw new RangeError("targetStart out of bounds"); - if (r < 0 || r >= this.length) - throw new RangeError("Index out of range"); - if (i < 0) throw new RangeError("sourceEnd out of bounds"); - i > this.length && (i = this.length), - e.length - t < i - r && (i = e.length - t + r); - var s = i - r; - if ( - this === e && - "function" == typeof Uint8Array.prototype.copyWithin - ) - this.copyWithin(t, r, i); - else if (this === e && r < t && t < i) - for (var a = s - 1; a >= 0; --a) e[a + t] = this[a + r]; - else Uint8Array.prototype.set.call(e, this.subarray(r, i), t); - return s; - }), - (n.prototype.write = function (e, t, r, i) { - if (void 0 === t) (i = "utf8"), (r = this.length), (t = 0); - else if (void 0 === r && "string" == typeof t) - (i = t), (r = this.length), (t = 0); - else { - if (!isFinite(t)) - throw new Error( - "Buffer.write(string, encoding, offset[, length]) is no longer supported" - ); - (t >>>= 0), - isFinite(r) - ? ((r >>>= 0), void 0 === i && (i = "utf8")) - : ((i = r), (r = void 0)); - } - const n = this.length - t; - if ( - ((void 0 === r || r > n) && (r = n), - (e.length > 0 && (r < 0 || t < 0)) || t > this.length) - ) - throw new RangeError("Attempt to write outside buffer bounds"); - i || (i = "utf8"); - let s = !1; - for (;;) - switch (i) { - case "hex": - return d(this, e, t, r); - case "utf8": - case "utf-8": - return c(this, e, t, r); - case "ascii": - case "latin1": - case "binary": - return f(this, e, t, r); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return g(this, e, t, r); - default: - if (s) throw new TypeError("Unknown encoding: " + i); - (i = ("" + i).toLowerCase()), (s = !0); - } - }); - }, - 832: function (e, t, r) { - var i; - !(function (n) { - "use strict"; - function s(e, t) { - var r = (65535 & e) + (65535 & t); - return (((e >> 16) + (t >> 16) + (r >> 16)) << 16) | (65535 & r); - } - function a(e, t, r, i, n, a) { - return s( - ((o = s(s(t, e), s(i, a))) << (l = n)) | (o >>> (32 - l)), - r - ); - var o, l; - } - function o(e, t, r, i, n, s, o) { - return a((t & r) | (~t & i), e, t, n, s, o); - } - function l(e, t, r, i, n, s, o) { - return a((t & i) | (r & ~i), e, t, n, s, o); - } - function h(e, t, r, i, n, s, o) { - return a(t ^ r ^ i, e, t, n, s, o); - } - function u(e, t, r, i, n, s, o) { - return a(r ^ (t | ~i), e, t, n, s, o); - } - function d(e, t) { - var r, i, n, a, d; - (e[t >> 5] |= 128 << t % 32), - (e[14 + (((t + 64) >>> 9) << 4)] = t); - var c = 1732584193, - f = -271733879, - g = -1732584194, - p = 271733878; - for (r = 0; r < e.length; r += 16) - (i = c), - (n = f), - (a = g), - (d = p), - (c = o(c, f, g, p, e[r], 7, -680876936)), - (p = o(p, c, f, g, e[r + 1], 12, -389564586)), - (g = o(g, p, c, f, e[r + 2], 17, 606105819)), - (f = o(f, g, p, c, e[r + 3], 22, -1044525330)), - (c = o(c, f, g, p, e[r + 4], 7, -176418897)), - (p = o(p, c, f, g, e[r + 5], 12, 1200080426)), - (g = o(g, p, c, f, e[r + 6], 17, -1473231341)), - (f = o(f, g, p, c, e[r + 7], 22, -45705983)), - (c = o(c, f, g, p, e[r + 8], 7, 1770035416)), - (p = o(p, c, f, g, e[r + 9], 12, -1958414417)), - (g = o(g, p, c, f, e[r + 10], 17, -42063)), - (f = o(f, g, p, c, e[r + 11], 22, -1990404162)), - (c = o(c, f, g, p, e[r + 12], 7, 1804603682)), - (p = o(p, c, f, g, e[r + 13], 12, -40341101)), - (g = o(g, p, c, f, e[r + 14], 17, -1502002290)), - (c = l( - c, - (f = o(f, g, p, c, e[r + 15], 22, 1236535329)), - g, - p, - e[r + 1], - 5, - -165796510 - )), - (p = l(p, c, f, g, e[r + 6], 9, -1069501632)), - (g = l(g, p, c, f, e[r + 11], 14, 643717713)), - (f = l(f, g, p, c, e[r], 20, -373897302)), - (c = l(c, f, g, p, e[r + 5], 5, -701558691)), - (p = l(p, c, f, g, e[r + 10], 9, 38016083)), - (g = l(g, p, c, f, e[r + 15], 14, -660478335)), - (f = l(f, g, p, c, e[r + 4], 20, -405537848)), - (c = l(c, f, g, p, e[r + 9], 5, 568446438)), - (p = l(p, c, f, g, e[r + 14], 9, -1019803690)), - (g = l(g, p, c, f, e[r + 3], 14, -187363961)), - (f = l(f, g, p, c, e[r + 8], 20, 1163531501)), - (c = l(c, f, g, p, e[r + 13], 5, -1444681467)), - (p = l(p, c, f, g, e[r + 2], 9, -51403784)), - (g = l(g, p, c, f, e[r + 7], 14, 1735328473)), - (c = h( - c, - (f = l(f, g, p, c, e[r + 12], 20, -1926607734)), - g, - p, - e[r + 5], - 4, - -378558 - )), - (p = h(p, c, f, g, e[r + 8], 11, -2022574463)), - (g = h(g, p, c, f, e[r + 11], 16, 1839030562)), - (f = h(f, g, p, c, e[r + 14], 23, -35309556)), - (c = h(c, f, g, p, e[r + 1], 4, -1530992060)), - (p = h(p, c, f, g, e[r + 4], 11, 1272893353)), - (g = h(g, p, c, f, e[r + 7], 16, -155497632)), - (f = h(f, g, p, c, e[r + 10], 23, -1094730640)), - (c = h(c, f, g, p, e[r + 13], 4, 681279174)), - (p = h(p, c, f, g, e[r], 11, -358537222)), - (g = h(g, p, c, f, e[r + 3], 16, -722521979)), - (f = h(f, g, p, c, e[r + 6], 23, 76029189)), - (c = h(c, f, g, p, e[r + 9], 4, -640364487)), - (p = h(p, c, f, g, e[r + 12], 11, -421815835)), - (g = h(g, p, c, f, e[r + 15], 16, 530742520)), - (c = u( - c, - (f = h(f, g, p, c, e[r + 2], 23, -995338651)), - g, - p, - e[r], - 6, - -198630844 - )), - (p = u(p, c, f, g, e[r + 7], 10, 1126891415)), - (g = u(g, p, c, f, e[r + 14], 15, -1416354905)), - (f = u(f, g, p, c, e[r + 5], 21, -57434055)), - (c = u(c, f, g, p, e[r + 12], 6, 1700485571)), - (p = u(p, c, f, g, e[r + 3], 10, -1894986606)), - (g = u(g, p, c, f, e[r + 10], 15, -1051523)), - (f = u(f, g, p, c, e[r + 1], 21, -2054922799)), - (c = u(c, f, g, p, e[r + 8], 6, 1873313359)), - (p = u(p, c, f, g, e[r + 15], 10, -30611744)), - (g = u(g, p, c, f, e[r + 6], 15, -1560198380)), - (f = u(f, g, p, c, e[r + 13], 21, 1309151649)), - (c = u(c, f, g, p, e[r + 4], 6, -145523070)), - (p = u(p, c, f, g, e[r + 11], 10, -1120210379)), - (g = u(g, p, c, f, e[r + 2], 15, 718787259)), - (f = u(f, g, p, c, e[r + 9], 21, -343485551)), - (c = s(c, i)), - (f = s(f, n)), - (g = s(g, a)), - (p = s(p, d)); - return [c, f, g, p]; - } - function c(e) { - var t, - r = "", - i = 32 * e.length; - for (t = 0; t < i; t += 8) - r += String.fromCharCode((e[t >> 5] >>> t % 32) & 255); - return r; - } - function f(e) { - var t, - r = []; - for (r[(e.length >> 2) - 1] = void 0, t = 0; t < r.length; t += 1) - r[t] = 0; - var i = 8 * e.length; - for (t = 0; t < i; t += 8) - r[t >> 5] |= (255 & e.charCodeAt(t / 8)) << t % 32; - return r; - } - function g(e) { - var t, - r, - i = "0123456789abcdef", - n = ""; - for (r = 0; r < e.length; r += 1) - (t = e.charCodeAt(r)), - (n += i.charAt((t >>> 4) & 15) + i.charAt(15 & t)); - return n; - } - function p(e) { - return unescape(encodeURIComponent(e)); - } - function m(e) { - return (function (e) { - return c(d(f(e), 8 * e.length)); - })(p(e)); - } - function v(e, t) { - return (function (e, t) { - var r, - i, - n = f(e), - s = [], - a = []; - for ( - s[15] = a[15] = void 0, - n.length > 16 && (n = d(n, 8 * e.length)), - r = 0; - r < 16; - r += 1 - ) - (s[r] = 909522486 ^ n[r]), (a[r] = 1549556828 ^ n[r]); - return ( - (i = d(s.concat(f(t)), 512 + 8 * t.length)), - c(d(a.concat(i), 640)) - ); - })(p(e), p(t)); - } - function y(e, t, r) { - return t ? (r ? v(t, e) : g(v(t, e))) : r ? m(e) : g(m(e)); - } - void 0 === - (i = function () { - return y; - }.call(t, r, t, e)) || (e.exports = i); - })(); - }, - 365: (e) => { - const t = { - ANDROID_WEB: "android-web", - IOS_WEB: "iOS-web", - PC_NATIVE: "PC-web", - PC_WEB: "PC-web", - }; - var r = { - getNetType: function () { - let e = (new RegExp("nettype\\/(\\w*)").exec(i()) || [ - , - "", - ])[1].toLowerCase(); - if (!e && navigator.connection) { - switch (navigator.connection.type) { - case "ethernet": - e = "ethernet"; - break; - case "cellular": - e = "cellular"; - break; - default: - e = "wifi"; - } - } - return e; - }, - getPlatform: function () { - return r.isAndroid() || r.isAndroidWebView() - ? t.ANDROID_WEB - : r.isIOS() || r.isIpad() || r.isIOSWebView() - ? t.IOS_WEB - : r.isElectron() - ? t.PC_NATIVE - : t.PC_WEB; - }, - isX5: function () { - return this.isAndroid() && /\s(TBS|X5Core)\/[\w\.\-]+/i.test(i()); - }, - isPC: function () { - return !s(n("os ")) && !s(n("android[/ ]")); - }, - isIOS: function () { - return s(n("os ")); - }, - isIpad: function () { - return ( - i().match(/(ipad)/) || - ("MacIntel" === navigator.platform && - navigator.maxTouchPoints > 1) - ); - }, - isAndroid: function () { - return s(n("android[/ ]")); - }, - isIOSSafari: function () { - return this.isIOS() && this.isSafari(); - }, - isIpadSafari: function () { - return this.isIpad() && this.isSafari(); - }, - isElectron: function () { - return /electron/i.test(i()); - }, - isMobile: function () { - return r.isAndroid() || r.isIOS(); - }, - isSafari: function () { - return /^((?!chrome|android).)*safari/i.test(i()); - }, - isFirefox: function () { - return /firefox/i.test(i()); - }, - isChrome: function () { - return /chrome/i.test(i()); - }, - isLocalHost: function () { - return "localhost" === location.hostname; - }, - isAndroidWebView: function () { - const e = i(); - return e.indexOf("wv") > -1 && e.indexOf("android") > -1; - }, - isIOSWebView: function () { - const e = i(); - return /\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test( - e - ); - }, - isWebView: function () { - return r.isAndroidWebView() || r.isIOSWebView(); - }, - device: t, - getBrowser: function () { - return r.isX5() - ? "X5" - : r.isAndroidWebView() - ? "Android-WebView" - : r.isIOSWebView() - ? "iOS-WebView" - : r.isChrome() - ? "Chrome" - : r.isFirefox() - ? "Firefox" - : r.isIpadSafari() - ? "iPad-Safari" - : r.isIOSSafari() - ? "iPhone-Safari" - : r.isSafari() - ? "Mac-Safari" - : "Unknown"; - }, - }; - function i() { - return navigator.userAgent.toLowerCase(); - } - function n(e) { - return ( - "" + - (new RegExp(e + "(\\d+((\\.|_)\\d+)*)").exec(i()) || [ - , - 0, - ])[1] || void 0 - ); - } - function s(e) { - return parseFloat((e || "").replace(/\_/g, ".")) || 0; - } - e.exports = r; - }, - }, - t = {}; - function r(i) { - var n = t[i]; - if (void 0 !== n) return n.exports; - var s = (t[i] = { exports: {} }); - return e[i].call(s.exports, s, s.exports, r), s.exports; - } - (r.n = (e) => { - var t = e && e.__esModule ? () => e.default : () => e; - return r.d(t, { a: t }), t; - }), - (r.d = (e, t) => { - for (var i in t) - r.o(t, i) && - !r.o(e, i) && - Object.defineProperty(e, i, { enumerable: !0, get: t[i] }); - }), - (r.o = (e, t) => Object.prototype.hasOwnProperty.call(e, t)); - var i = {}; - return ( - (() => { - "use strict"; - r.d(i, { default: () => Or }); - const e = { - DC_SIGNAL: "SIGNAL", - DC_SIGNAL_BATCH: "SIGNAL_BATCH", - DC_OPEN: "OPEN", - DC_REQUEST: "REQUEST", - DC_PIECE_NOT_FOUND: "PIECE_NOT_FOUND", - DC_PIECE_ABORT: "PIECE_ABORT", - DC_PIECE_CANCEL: "PIECE_CANCEL", - DC_CLOSE: "CLOSE", - DC_DISCONNECT: "DISCONNECT", - DC_RESPONSE: "RESPONSE", - DC_ERROR: "ERROR", - DC_PIECE: "PIECE", - DC_PIECE_DATA: "PIECE_DATA", - DC_TIMEOUT: "TIMEOUT", - DC_PIECE_ACK: "PIECE_ACK", - DC_METADATA: "METADATA", - DC_PLAT_ANDROID: "ANDROID", - DC_PLAT_IOS: "IOS", - DC_PLAT_WEB: "WEB", - DC_CHOKE: "CHOKE", - DC_UNCHOKE: "UNCHOKE", - DC_HAVE: "HAVE", - DC_HAVE_REVERSE: "HAVE_REVERSE", - DC_LOST: "LOST", - DC_GET_PEERS: "GET_PEERS", - DC_PEERS: "PEERS", - DC_STATS: "STATS", - DC_PEER_SIGNAL: "PEER_SIGNAL", - DC_PLAYLIST: "PLAYLIST", - BM_LOST: "lost", - BM_ADDED_SEG_: "BM_ADDED_SEG_", - BM_ADDED_SN_: "BM_ADDED_SN_", - BM_SEG_ADDED: "BM_SEG_ADDED", - BM_FATAL_ERROR: "BM_FATAL_ERROR", - FRAG_CHANGED: "FRAG_CHANGED", - FRAG_LOADED: "FRAG_LOADED", - FRAG_LOADING: "FRAG_LOADING", - RESTART_P2P: "RESTART_P2P", - EXCEPTION: "exception", - SYN_OUTPUT: "SYN_OUTPUT", - SYN_ERROR: "SYN_ERROR", - SYN_PROGRESS: "SYN_PROGRESS", - MEDIA_REBUFFER: "MEDIA_REBUFFER", - }, - t = { - ...e, - SCH_WAIT_PEER: "SCH_WAIT_PEER", - SW_PLAYLIST: "SW_PLAYLIST", - SW_GET_PLAYLIST: "SW_GET_PLAYLIST", - SW_GET_MEDIA: "SW_GET_MEDIA", - SW_DEBUG: "SW_DEBUG", - LEVEL_LOADED: "LEVEL_LOADED", - MANIFEST_PARSED: "MANIFEST_PARSED", - }; - var n = r(415), - s = r.n(n), - a = r(424), - o = r(558), - l = r.n(o); - const h = "__PROXY_IDENTIFIER__"; - const u = 64e3; - function d() { - return !0; - } - function c(e) { - return new URL(location.href).searchParams.get(e); - } - function f(e, t, r) { - const i = new URL(e); - return i.searchParams.append(t, r), i.href; - } - function g() { - return Date.parse(new Date()) / 1e3; - } - function p(e, t) { - return parseInt(Math.random() * (t - e + 1) + e, 10); - } - function m(e) { - return new Promise((t) => setTimeout(t, e)); - } - function v() { - if ("object" != typeof self) return null; - var e = { - RTCPeerConnection: - self.RTCPeerConnection || - self.mozRTCPeerConnection || - self.webkitRTCPeerConnection, - RTCSessionDescription: - self.RTCSessionDescription || - self.mozRTCSessionDescription || - self.webkitRTCSessionDescription, - RTCIceCandidate: - self.RTCIceCandidate || - self.mozRTCIceCandidate || - self.webkitRTCIceCandidate, - }; - return e.RTCPeerConnection && e.RTCPeerConnection.prototype - ? e - : null; - } - function y(e) { - const t = a.h.from(e), - r = new a.h(e.byteLength); - return t.copy(r), r; - } - function E() { - return location.protocol.startsWith("https"); - } - function S(e, t, r) { - if (e.size <= t) return; - const i = [...e.keys()]; - do { - const t = i.shift(); - r && r(e.get(t)), e.delete(t); - } while (e.size > t); - } - function T(e, t) { - if (e.size <= t) return; - const r = [...e.values()]; - do { - e.delete(r.shift()); - } while (e.size > t); - } - function _(e) { - return e instanceof ArrayBuffer && 0 !== e.byteLength; - } - function L(e) { - if (!e) return {}; - const t = (e = e.substring(6)).split("-"); - if (2 !== t.length) return {}; - const r = Number(t[0]), - i = t[1] ? Number(t[1]) : -1; - return { rangeStart: r, rangeEnd: i >= 0 ? i + 1 : void 0 }; - } - function b(e) { - return e.split("?")[0]; - } - function R() { - let e = new Date(), - t = e.getHours(), - r = e.getMinutes(), - i = e.getSeconds(), - n = e.getMilliseconds(); - return `${t.toString().padStart(2, "0")}:${r - .toString() - .padStart(2, "0")}:${i.toString().padStart(2, "0")}.${n}`; - } - function A(e) { - return e && "function" == typeof e; - } - function w(e, t, r, i, n, s) { - e.sendPartialBuffer(r, i, { from: n, incompletes: s }), - i.length < r.attachments - ? (function (e, t, r) { - e.addStreamListener(r, t.remotePeerId, (e, r, i, n, s) => { - i - ? t.sendMsgPieceAbort(n, r, !0) - : t.uploading && t.send(n), - s && (t.uploading = !1); - }); - })(t, e, !!r.reverse) - : (e.uploading = !1); - } - const P = (e) => (0 === p(0, 1) ? [null, e] : [e, null]); - function I(e, t, r) { - return 1 === e.length - ? t.length >= 1 && r.length >= 1 - ? t[0].weight > r[0].weight - ? [t[0], e[0]] - : [e[0], r[0]] - : t.length >= 1 - ? [t[0], e[0]] - : r.length >= 1 - ? [e[0], r[0]] - : P(e[0]) - : [t.length >= 1 ? t[0] : null, r.length >= 1 ? r[0] : null]; - } - function C() { - const e = performance.now(); - return { - trequest: e, - tfirst: 0, - tload: 0, - aborted: !1, - loaded: 0, - retry: 0, - total: 0, - chunkCount: 0, - bwEstimate: 0, - loading: { start: e, first: 0, end: 0 }, - parsing: { start: 0, end: 0 }, - buffering: { start: 0, first: 0, end: 0 }, - }; - } - class k { - constructor(e, t) { - (this.target = t), (this.type = e); - } - } - class D extends k { - constructor(e, t) { - super("error", t), (this.message = e.message), (this.error = e); - } - } - class M extends k { - constructor(e = 1e3, t = "", r) { - super("close", r), - (this.code = e), - (this.reason = t), - (this.wasClean = !0); - } - } - const x = () => { - if ("undefined" != typeof WebSocket) return WebSocket; - }, - O = { - maxReconnectionDelay: 1e4, - minReconnectionDelay: 1e3 + 4e3 * Math.random(), - minUptime: 5e3, - reconnectionDelayGrowFactor: 1.3, - connectionTimeout: 4e3, - maxRetries: 1 / 0, - maxEnqueuedMessages: 1 / 0, - startClosed: !1, - }; - class F { - constructor(e, t, r = {}) { - (this._listeners = { error: [], message: [], open: [], close: [] }), - (this.onclose = null), - (this.onerror = null), - (this.onmessage = null), - (this.onopen = null), - (this._messageQueue = []), - (this._closeCalled = !1), - (this._connectLock = !1), - (this._shouldReconnect = !0), - (this._retryCount = -1), - (this._binaryType = "blob"), - (this._url = e), - (this._protocols = t), - (this._options = r), - this._options.startClosed && (this._shouldReconnect = !1), - this._connect(), - (this._handleOpen = this._handleOpen.bind(this)), - (this._handleClose = this._handleClose.bind(this)), - (this._handleMessage = this._handleMessage.bind(this)), - (this._handleError = this._handleError.bind(this)); - } - static get CONNECTING() { - return 0; - } - static get OPEN() { - return 1; - } - static get CLOSING() { - return 2; - } - static get CLOSED() { - return 3; - } - get CONNECTING() { - return F.CONNECTING; - } - get OPEN() { - return F.OPEN; - } - get CLOSING() { - return F.CLOSING; - } - get CLOSED() { - return F.CLOSED; - } - get readyState() { - return this._ws - ? this._ws.readyState - : this._options.startClosed - ? F.CLOSED - : F.CONNECTING; - } - get url() { - return this._ws ? this._ws.url : ""; - } - close(e = 1e3, t) { - (this._closeCalled = !0), - (this._shouldReconnect = !1), - this._clearTimeouts(), - this._ws && - this._ws.readyState !== this.CLOSED && - this._ws.close(e, t); - } - reconnect(e, t) { - (this._shouldReconnect = !0), - (this._closeCalled = !1), - (this._retryCount = -1), - this._ws && this._ws.readyState !== this.CLOSED - ? (this._disconnect(e, t), this._connect()) - : this._connect(); - } - send(e) { - if (this._ws && this._ws.readyState === this.OPEN) this._ws.send(e); - else { - const { maxEnqueuedMessages: t = O.maxEnqueuedMessages } = - this._options; - this._messageQueue.length < t && this._messageQueue.push(e); - } - } - addEventListener(e, t) { - this._listeners[e] && this._listeners[e].push(t); - } - dispatchEvent(e) { - const t = this._listeners[e.type]; - if (t) for (const r of t) this._callEventListener(e, r); - return !0; - } - removeEventListener(e, t) { - this._listeners[e] && - (this._listeners[e] = this._listeners[e].filter((e) => e !== t)); - } - _getNextDelay() { - const { - reconnectionDelayGrowFactor: e = O.reconnectionDelayGrowFactor, - minReconnectionDelay: t = O.minReconnectionDelay, - maxReconnectionDelay: r = O.maxReconnectionDelay, - } = this._options; - let i = 0; - return ( - this._retryCount > 0 && - ((i = t * Math.pow(e, this._retryCount - 1)), i > r && (i = r)), - i - ); - } - _wait() { - return new Promise((e) => { - setTimeout(e, this._getNextDelay()); - }); - } - _getNextUrl(e) { - if ("string" == typeof e) return Promise.resolve(e); - if ("function" == typeof e) { - const t = e(); - if ("string" == typeof t) return Promise.resolve(t); - if (t.then) return t; - } - throw Error("Invalid URL"); - } - _connect() { - if (this._connectLock || !this._shouldReconnect) return; - this._connectLock = !0; - const { - maxRetries: e = O.maxRetries, - connectionTimeout: t = O.connectionTimeout, - WebSocket: r = x(), - } = this._options; - if (!(this._retryCount >= e)) { - if ( - (this._retryCount++, - this._removeListeners(), - void 0 === (i = r) || !i || 2 !== i.CLOSING) - ) - throw Error("No valid WebSocket class provided"); - var i; - this._wait() - .then(() => this._getNextUrl(this._url)) - .then((e) => { - this._closeCalled - ? (this._connectLock = !1) - : ((this._ws = this._protocols - ? new r(e, this._protocols) - : new r(e)), - (this._ws.binaryType = this._binaryType), - (this._connectLock = !1), - this._addListeners(), - (this._connectTimeout = setTimeout( - () => this._handleTimeout(), - t - ))); - }) - .catch((e) => { - (this._connectLock = !1), - this._handleError(new D(Error(e.message), this)); - }); - } - } - _handleTimeout() { - this._handleError(new D(Error("TIMEOUT"), this)); - } - _disconnect(e = 1e3, t) { - if ((this._clearTimeouts(), this._ws)) { - this._removeListeners(); - try { - this._ws.close(e, t), this._handleClose(new M(e, t, this)); - } catch (e) {} - } - } - _acceptOpen() { - this._retryCount = 0; - } - _callEventListener(e, t) { - "handleEvent" in t ? t.handleEvent(e) : t(e); - } - _handleOpen(e) { - const { minUptime: t = O.minUptime } = this._options; - clearTimeout(this._connectTimeout), - (this._uptimeTimeout = setTimeout(() => this._acceptOpen(), t)), - (this._ws.binaryType = this._binaryType), - this._messageQueue.forEach((e) => this._ws.send(e)), - (this._messageQueue = []), - this.onopen && this.onopen(e), - this._listeners.open.forEach((t) => - this._callEventListener(e, t) - ); - } - _handleMessage(e) { - this.onmessage && this.onmessage(e), - this._listeners.message.forEach((t) => - this._callEventListener(e, t) - ); - } - _handleError(e) { - this._disconnect( - void 0, - "TIMEOUT" === e.message ? "timeout" : void 0 - ), - this.onerror && this.onerror(e), - this._listeners.error.forEach((t) => - this._callEventListener(e, t) - ), - this._connect(); - } - _handleClose(e) { - this._clearTimeouts(), - this._shouldReconnect && this._connect(), - this.onclose && this.onclose(e), - this._listeners.close.forEach((t) => - this._callEventListener(e, t) - ); - } - _removeListeners() { - this._ws && - (this._ws.removeEventListener("open", this._handleOpen), - this._ws.removeEventListener("close", this._handleClose), - this._ws.removeEventListener("message", this._handleMessage), - this._ws.removeEventListener("error", this._handleError)); - } - _addListeners() { - this._ws && - (this._ws.addEventListener("open", this._handleOpen), - this._ws.addEventListener("close", this._handleClose), - this._ws.addEventListener("message", this._handleMessage), - this._ws.addEventListener("error", this._handleError)); - } - _clearTimeouts() { - clearTimeout(this._connectTimeout), - clearTimeout(this._uptimeTimeout); - } - } - const N = { debug: 3, info: 4, warn: 5, error: 6 }; - class B { - constructor(e, t, r, i) { - (this.wsAddr = `${e}?app=${t}&id=${r}&v=${i}`), - (this.destroyed = !1); - try { - this._ws = this._init(); - } catch (e) { - console.error(e); - } - } - _init() { - const e = { - maxRetries: 3, - minReconnectionDelay: p(5e3, 15e3), - maxReconnectionDelay: 6e5, - maxEnqueuedMessages: 200, - }; - return new F(this.wsAddr, void 0, e); - } - send(e, t) { - if (this.destroyed) return; - const r = N[e]; - this._ws.send( - JSON.stringify({ records: [{ level: r, text: `${R()}: ${t}` }] }) - ); - } - sendBatch(e) { - const t = []; - for (let r of e) t.push({ level: N[r.levelKey], text: r.message }); - this._ws.send(JSON.stringify({ records: t })); - } - destroy() { - this._ws && - (this._ws.close(1e3), (this._ws = null), (this.destroyed = !0)); - } - } - const U = (e) => { - const t = localStorage.getItem(e); - try { - const e = JSON.parse(t); - return e.value ? e.value : e; - } catch (e) { - return t; - } - }, - G = (e, t, r) => { - ((e, t) => { - "object" == typeof t && (t = JSON.stringify(t)), - localStorage.setItem(e, t); - })(e, { value: t, duration: r, startTime: Date.now() }); - }, - H = { debug: 0, info: 1, warn: 2, error: 3, none: 4 }; - const $ = class { - constructor(e) { - (this.logLevel = e), (this.onlineDebug = !1), (this.logCache = []); - try { - console.debug = console.log; - } catch (e) { - console.debug = console.info; - } - ("debug" !== e && "info" !== e) || (this.logLevel = "error"), - U("SW_DEBUG") && (this.logLevel = "debug"), - !0 === e - ? (this.logLevel = "warn") - : !1 === e - ? (this.logLevel = "none") - : e in H || (this.logLevel = "error"), - this.resetLogger(); - } - enableDebug() { - this.onlineDebug = !0; - for (let e in H) this[e] = console[e]; - this._hookLogFunc((e, t) => { - this.logUploader && this.logUploader.send(e, t); - }); - } - enableReport(e) { - (this.reportUrl = e), - this._hookLogFunc((e, t) => { - this.reportUrl - ? (this.logCache.push({ - levelKey: e, - message: `${R()}: ${t}`, - }), - this.logCache.length > 350 && this.logCache.shift()) - : this.reporter && this.reporter.send(e, t); - }); - } - report(e, t, r, i, n = 5e3) { - this.reportUrl && - (e && this.logCache.unshift({ levelKey: "info", message: e }), - (this.reporter = new B(this.reportUrl, t, r, i)), - this.reporter._ws.addEventListener( - "open", - () => { - (this.reportUrl = void 0), - this.reporter.sendBatch(this.logCache), - setTimeout(() => { - this.reporter.destroy(), (this.reporter = null); - }, n); - }, - { once: !0 } - )); - } - _hookLogFunc(e) { - for (let t in H) { - const r = this[t]; - this[t] = (i) => { - e(t, i), r(i); - }; - } - } - setUploader(e) { - this.logUploader = e; - } - resetLogger() { - this.onlineDebug = !1; - for (let e in H) - H[e] < H[this.logLevel] ? (this[e] = d) : (this[e] = console[e]); - } - get isDebugLevel() { - return H[this.logLevel] <= 2 || this.onlineDebug; - } - }; - let K; - const W = - "function" == typeof queueMicrotask - ? queueMicrotask.bind(globalThis) - : (e) => - (K || (K = Promise.resolve())).then(e).catch((e) => - setTimeout(() => { - throw e; - }, 0) - ), - V = 65536; - function q(e) { - return e.replace(/a=ice-options:trickle\s\n/g, ""); - } - class j extends s() { - constructor(e) { - super(), - (this.channelName = e.initiator ? e.channelName : null), - (this.initiator = e.initiator || !1), - (this.channelConfig = e.channelConfig || j.channelConfig), - (this.channelNegotiated = this.channelConfig.negotiated), - (this.config = Object.assign({}, j.config, e.config)), - (this.offerOptions = e.offerOptions || {}), - (this.answerOptions = e.answerOptions || {}), - (this.sdpTransform = e.sdpTransform || ((e) => e)), - (this.trickle = void 0 === e.trickle || e.trickle), - (this.allowHalfTrickle = - void 0 !== e.allowHalfTrickle && e.allowHalfTrickle), - (this.iceCompleteTimeout = e.iceCompleteTimeout || 5e3), - (this.destroyed = !1), - (this.destroying = !1), - (this._connected = !1), - (this.remoteAddress = void 0), - (this.remoteFamily = void 0), - (this.remotePort = void 0), - (this.localAddress = void 0), - (this.localFamily = void 0), - (this.localPort = void 0), - (this._wrtc = e.wrtc && "object" == typeof e.wrtc ? e.wrtc : v()), - (this._pcReady = !1), - (this._channelReady = !1), - (this._iceComplete = !1), - (this._iceCompleteTimer = null), - (this._channel = null), - (this._pendingCandidates = []), - (this._pendingData = []), - (this._isNegotiating = !1), - (this._firstNegotiation = !0), - (this._batchedNegotiation = !1), - (this._queuedNegotiation = !1), - (this._senderMap = new Map()), - (this._closingInterval = null), - (this._chunk = null), - (this._cb = null), - (this._interval = null); - try { - this._pc = new this._wrtc.RTCPeerConnection(this.config); - } catch (e) { - return void W(() => this.destroy(e)); - } - (this._pc.oniceconnectionstatechange = () => { - this._onIceStateChange(); - }), - (this._pc.onicegatheringstatechange = () => { - this._onIceStateChange(); - }), - (this._pc.onconnectionstatechange = () => { - this._onConnectionStateChange(); - }), - (this._pc.onsignalingstatechange = () => { - this._onSignalingStateChange(); - }), - (this._pc.onicecandidate = (e) => { - this._onIceCandidate(e); - }), - this.initiator || this.channelNegotiated - ? this._setupData({ - channel: this._pc.createDataChannel( - this.channelName, - this.channelConfig - ), - }) - : (this._pc.ondatachannel = (e) => { - this._setupData(e); - }), - this._needsNegotiation(); - } - get bufferSize() { - return (this._channel && this._channel.bufferedAmount) || 0; - } - get connected() { - return this._connected && "open" === this._channel.readyState; - } - signal(e) { - if (!this.destroyed && this._pc) { - if ("string" == typeof e) - try { - e = JSON.parse(e); - } catch (t) { - e = {}; - } - if ( - (e.renegotiate && this.initiator && this._needsNegotiation(), - e.candidate) - ) - if ( - this._pc.remoteDescription && - this._pc.remoteDescription.type - ) - try { - this._addIceCandidate(e.candidate); - } catch (e) {} - else this._pendingCandidates.push(e.candidate); - e.sdp && - this._pc - .setRemoteDescription(new this._wrtc.RTCSessionDescription(e)) - .then(() => { - this.destroyed || - (this._pendingCandidates.forEach((e) => { - try { - this._addIceCandidate(e); - } catch (e) {} - }), - (this._pendingCandidates = []), - "offer" === this._pc.remoteDescription.type && - this._createAnswer()); - }) - .catch((e) => { - this.destroy(e); - }), - e.sdp || - e.candidate || - e.renegotiate || - e.transceiverRequest || - this.destroy( - new Error("signal() called with invalid signal data") - ); - } - } - _addIceCandidate(e) { - const t = new this._wrtc.RTCIceCandidate(e); - this._pc.addIceCandidate(t).catch((e) => { - var r; - !t.address || t.address.endsWith(".local") - ? ((r = "Ignoring unsupported ICE candidate."), console.warn(r)) - : this.destroy(e); - }); - } - send(e) { - if ("string" == typeof e) { - RTCDataChannel.prototype.send - .toString() - .includes("[native code]") && this._channel.send(e); - } else this._channel.send(e); - } - _needsNegotiation() { - this._batchedNegotiation || - ((this._batchedNegotiation = !0), - W(() => { - (this._batchedNegotiation = !1), - (!this.initiator && this._firstNegotiation) || - this.negotiate(), - (this._firstNegotiation = !1); - })); - } - negotiate() { - this.initiator - ? this._isNegotiating - ? (this._queuedNegotiation = !0) - : setTimeout(() => { - this._createOffer(); - }, 0) - : this._isNegotiating - ? (this._queuedNegotiation = !0) - : this.emit("signal", { type: "renegotiate", renegotiate: !0 }), - (this._isNegotiating = !0); - } - destroy(e) { - this._destroy(e); - } - _destroy(e) { - this.destroyed || - this.destroying || - ((this.destroying = !0), - W(() => { - if ( - ((this.destroyed = !0), - (this.destroying = !1), - (this._connected = !1), - (this._pcReady = !1), - (this._channelReady = !1), - (this._senderMap = null), - clearInterval(this._closingInterval), - (this._closingInterval = null), - clearInterval(this._interval), - (this._interval = null), - (this._chunk = null), - (this._cb = null), - this._channel) - ) { - try { - this._channel.close(); - } catch (e) {} - (this._channel.onmessage = null), - (this._channel.onopen = null), - (this._channel.onclose = null), - (this._channel.onerror = null); - } - if (this._pc) { - try { - this._pc.close(); - } catch (e) {} - (this._pc.oniceconnectionstatechange = null), - (this._pc.onicegatheringstatechange = null), - (this._pc.onsignalingstatechange = null), - (this._pc.onicecandidate = null), - (this._pc.ondatachannel = null); - } - (this._pc = null), - (this._channel = null), - e && this.emit("error", e), - this.emit("close"); - })); - } - _setupData(e) { - if (!e.channel) - return this.destroy( - new Error("Data channel event is missing `channel` property") - ); - (this._channel = e.channel), - (this._channel.binaryType = "arraybuffer"), - "number" == typeof this._channel.bufferedAmountLowThreshold && - (this._channel.bufferedAmountLowThreshold = V), - (this.channelName = this._channel.label), - (this._channel.onmessage = (e) => { - this._onChannelMessage(e); - }), - (this._channel.onbufferedamountlow = () => { - this._onChannelBufferedAmountLow(); - }), - (this._channel.onopen = () => { - this._onChannelOpen(); - }), - (this._channel.onclose = () => { - this._onChannelClose(); - }), - (this._channel.onerror = (e) => { - this.destroy(e); - }); - let t = !1; - this._closingInterval = setInterval(() => { - this._channel && "closing" === this._channel.readyState - ? (t && this._onChannelClose(), (t = !0)) - : (t = !1); - }, 5e3); - } - get isBufferedAmountHigh() { - return this._channel.bufferedAmount > V; - } - write(e, t) { - if (this.destroyed) - return t(new Error("cannot write after peer is destroyed")); - if (this._connected) { - try { - this.send(e); - } catch (e) { - return this.destroy(e); - } - this.isBufferedAmountHigh ? (this._cb = t) : t(null); - } else (this._chunk = e), (this._cb = t); - } - _startIceCompleteTimeout() { - this.destroyed || - this._iceCompleteTimer || - (this._iceCompleteTimer = setTimeout(() => { - this._iceComplete || - ((this._iceComplete = !0), - this.emit("iceTimeout"), - this.emit("_iceComplete")); - }, this.iceCompleteTimeout)); - } - _createOffer() { - this.destroyed || - this._pc - .createOffer(this.offerOptions) - .then((e) => { - if (this.destroyed) return; - this.trickle || this.allowHalfTrickle || (e.sdp = q(e.sdp)), - (e.sdp = this.sdpTransform(e.sdp)); - const t = () => { - if (this.destroyed) return; - const t = this._pc.localDescription || e; - this.emit("signal", { type: t.type, sdp: t.sdp }); - }; - this._pc - .setLocalDescription(e) - .then(() => { - this.destroyed || - (this.trickle || this._iceComplete - ? t() - : this.once("_iceComplete", t)); - }) - .catch((e) => { - this.destroy(e); - }); - }) - .catch((e) => { - this.destroy(e); - }); - } - _createAnswer() { - this.destroyed || - this._pc - .createAnswer(this.answerOptions) - .then((e) => { - if (this.destroyed) return; - this.trickle || this.allowHalfTrickle || (e.sdp = q(e.sdp)), - (e.sdp = this.sdpTransform(e.sdp)); - const t = () => { - if (this.destroyed) return; - const t = this._pc.localDescription || e; - this.emit("signal", { type: t.type, sdp: t.sdp }); - }; - this._pc - .setLocalDescription(e) - .then(() => { - this.destroyed || - (this.trickle || this._iceComplete - ? t() - : this.once("_iceComplete", t)); - }) - .catch((e) => { - this.destroy(e); - }); - }) - .catch((e) => { - this.destroy(e); - }); - } - _onConnectionStateChange() { - this.destroyed || - ("failed" === this._pc.connectionState && - this.destroy(new Error("Connection failed."))); - } - _onIceStateChange() { - if (this.destroyed) return; - const e = this._pc.iceConnectionState, - t = this._pc.iceGatheringState; - this.emit("iceStateChange", e, t), - ("connected" !== e && "completed" !== e) || - ((this._pcReady = !0), this._maybeReady()), - "failed" === e && - this.destroy(new Error("Ice connection failed.")), - "closed" === e && - this.destroy(new Error("Ice connection closed.")); - } - getStats(e) { - const t = (e) => ( - "[object Array]" === Object.prototype.toString.call(e.values) && - e.values.forEach((t) => { - Object.assign(e, t); - }), - e - ); - 0 === this._pc.getStats.length - ? this._pc.getStats().then( - (r) => { - const i = []; - r.forEach((e) => { - i.push(t(e)); - }), - e(null, i); - }, - (t) => e(t) - ) - : this._pc.getStats.length > 0 - ? this._pc.getStats( - (r) => { - if (this.destroyed) return; - const i = []; - r.result().forEach((e) => { - const r = {}; - e.names().forEach((t) => { - r[t] = e.stat(t); - }), - (r.id = e.id), - (r.type = e.type), - (r.timestamp = e.timestamp), - i.push(t(r)); - }), - e(null, i); - }, - (t) => e(t) - ) - : e(null, []); - } - _maybeReady() { - if ( - this._connected || - this._connecting || - !this._pcReady || - !this._channelReady - ) - return; - this._connecting = !0; - const e = () => { - this.destroyed || - this.getStats((t, r) => { - if (this.destroyed) return; - t && (r = []); - const i = {}, - n = {}, - s = {}; - let a = !1; - r.forEach((e) => { - ("remotecandidate" !== e.type && - "remote-candidate" !== e.type) || - (i[e.id] = e), - ("localcandidate" !== e.type && - "local-candidate" !== e.type) || - (n[e.id] = e), - ("candidatepair" !== e.type && - "candidate-pair" !== e.type) || - (s[e.id] = e); - }); - const o = (e) => { - a = !0; - let t = n[e.localCandidateId]; - t && (t.ip || t.address) - ? ((this.localAddress = t.ip || t.address), - (this.localPort = Number(t.port))) - : t && t.ipAddress - ? ((this.localAddress = t.ipAddress), - (this.localPort = Number(t.portNumber))) - : "string" == typeof e.googLocalAddress && - ((t = e.googLocalAddress.split(":")), - (this.localAddress = t[0]), - (this.localPort = Number(t[1]))), - this.localAddress && - (this.localFamily = this.localAddress.includes(":") - ? "IPv6" - : "IPv4"); - let r = i[e.remoteCandidateId]; - r && (r.ip || r.address) - ? ((this.remoteAddress = r.ip || r.address), - (this.remotePort = Number(r.port))) - : r && r.ipAddress - ? ((this.remoteAddress = r.ipAddress), - (this.remotePort = Number(r.portNumber))) - : "string" == typeof e.googRemoteAddress && - ((r = e.googRemoteAddress.split(":")), - (this.remoteAddress = r[0]), - (this.remotePort = Number(r[1]))), - this.remoteAddress && - (this.remoteFamily = this.remoteAddress.includes(":") - ? "IPv6" - : "IPv4"); - }; - if ( - (r.forEach((e) => { - "transport" === e.type && - e.selectedCandidatePairId && - o(s[e.selectedCandidatePairId]), - (("googCandidatePair" === e.type && - "true" === e.googActiveConnection) || - (("candidatepair" === e.type || - "candidate-pair" === e.type) && - e.selected)) && - o(e); - }), - a || (Object.keys(s).length && !Object.keys(n).length)) - ) { - if ( - ((this._connecting = !1), - (this._connected = !0), - this._chunk) - ) { - try { - this.send(this._chunk); - } catch (t) { - return this.destroy(t); - } - this._chunk = null; - const e = this._cb; - (this._cb = null), e(null); - } - "number" != - typeof this._channel.bufferedAmountLowThreshold && - ((this._interval = setInterval( - () => this._onInterval(), - 150 - )), - this._interval.unref && this._interval.unref()), - this.emit("connect"); - for (let e of this._pendingData) this.emit("data", e); - this._pendingData = []; - } else setTimeout(e, 100); - }); - }; - e(); - } - _onInterval() { - !this._cb || - !this._channel || - this._channel.bufferedAmount > V || - this._onChannelBufferedAmountLow(); - } - _onSignalingStateChange() { - this.destroyed || - ("stable" === this._pc.signalingState && - ((this._isNegotiating = !1), - this._queuedNegotiation - ? ((this._queuedNegotiation = !1), this._needsNegotiation()) - : this.emit("negotiated")), - this.emit("signalingStateChange", this._pc.signalingState)); - } - _onIceCandidate(e) { - this.destroyed || - (e.candidate && this.trickle - ? this.emit("signal", { - type: "candidate", - candidate: { - candidate: e.candidate.candidate, - sdpMLineIndex: e.candidate.sdpMLineIndex, - sdpMid: e.candidate.sdpMid, - }, - }) - : e.candidate || - this._iceComplete || - ((this._iceComplete = !0), this.emit("_iceComplete")), - e.candidate && this._startIceCompleteTimeout()); - } - _onChannelMessage(e) { - if (this.destroyed) return; - let t = e.data; - t instanceof ArrayBuffer && (t = a.h.from(t)), - this._connected - ? this.emit("data", t) - : this._pendingData.length < 10 && this._pendingData.push(t); - } - _onChannelBufferedAmountLow() { - if (this.destroyed || !this._cb) return; - const e = this._cb; - (this._cb = null), e(null); - } - _onChannelOpen() { - this._connected || - this.destroyed || - ((this._channelReady = !0), this._maybeReady()); - } - _onChannelClose() { - this.destroyed || this.destroy(); - } - } - (j.config = { - iceServers: [ - { - urls: [ - "stun:stun.l.google.com:19302", - "stun:global.stun.twilio.com:3478", - ], - }, - ], - sdpSemantics: "unified-plan", - }), - (j.channelConfig = {}); - const Y = j; - class z { - constructor(e, t, r, i, n = 0, s = void 0) { - (this.sn = e), - (this.segId = t), - (this.data = r), - (this.fromPeerId = i), - (this.level = n || 0), - (this.ext = s); - } - static fromSegment(e) { - const t = new z( - e.sn, - e.segId, - e.data, - e.fromPeerId, - e.level, - e.ext - ); - return (t.from = e.from), t; - } - get size() { - return this.data.byteLength; - } - get isSequential() { - return this.sn >= 0; - } - } - var X = r(365), - Q = r.n(X); - class J extends s() { - static get defaultPacketSize() { - return u; - } - static get VERSION() { - return "8"; - } - constructor(e, t, r, i, n, s = {}) { - super(), - (this.channel = e.fetcher.channelId), - (this.logger = e.logger), - (this.config = n), - (this.isInitiator = i), - (this.options = s), - (this.intermediator = s.intermediator || null), - (this.signalMsgs = []), - this.assignPeerId(t, r), - (this.platform = "unknown"), - (this.super = !1), - (this.mobile = !1), - (this.mobileWeb = !1), - (this.mobileNet = !1), - (this.connected = !1), - (this.msgQueue = []), - (this.miss = 0), - (this.notifySet = new Set()), - (this.bufArr = []), - (this.packetSize = u), - (this.sendReqQueue = []), - (this.downloading = !1), - (this.uploading = !1), - (this.choked = !1), - (this.streamListeners = []), - (this.pieceMsg = {}), - (this.datasToSend = []), - (this.bytesUploaded = 0), - (this.dataWriting = !1), - (this.timeSendRequest = 0), - (this.timeReceivePiece = 0), - (this.timeSendPiece = 0), - (this.weight = 0), - (this.peersConnected = 1), - (this.uploadSpeed = 0), - (this.currentLevel = 0), - (this.currentPos = 0), - (this.useBackupSignal = !1), - (this.gotPeersTS = 0), - (this.gotAnswer = !1), - (this.gotOffer = !1), - (this.gotSignal = !1), - (this.sentSignal = !1), - (this.webRTCConfig = {}); - const { stuns: a } = this.options; - if (a && a.length > 0) { - const e = []; - a.forEach((t) => { - this.logger.info(`use stun ${t}`), e.push({ urls: t }); - }), - (this.webRTCConfig.iceServers = e); - } - this.config.webRTCConfig && - (this.webRTCConfig = { - ...this.config.webRTCConfig, - ...this.webRTCConfig, - }), - (this.playlistMap = new Map()), - this._initPeerChannel(), - (this.notFatalClosed = !1), - (this.startSN = Number.MAX_SAFE_INTEGER), - (this.endSN = -1), - (this._loadedBytes = 0); - } - assignPeerId(t, r) { - (this.remotePeerId = r), - (this.channelId = this.isInitiator ? `${t}-${r}` : `${r}-${t}`), - r && this._startTimer(), - setTimeout(() => { - this.signalMsgs.length > 0 && - this.emit(e.DC_SIGNAL_BATCH, this.signalMsgs); - }, 0); - } - _startTimer() { - (this.timeJoin = g()), - (this.dataExchangeTs = this.timeJoin), - (this.gotStatsTs = this.timeJoin), - (this.connTimeout = setTimeout( - () => { - const { gotSignal: t, sentSignal: r, signalName: i } = this; - this.logger.warn( - `dc ${this.channelId} connection timeout, gotSignal ${t} sentSignal ${r} signalName ${i}` - ), - this.emit(e.DC_TIMEOUT, { - gotSignal: t, - sentSignal: r, - data: this.signalMsgs, - }); - }, - this.isInitiator ? 15e3 : 12e3 - )); - } - get isAvailable() { - return this.downloadNum < 2 && !this.choked; - } - get isAvailableUrgently() { - return !this.downloading && !this.choked; - } - cancelDownload(t, r, i) { - return ( - !!this.downloading && - !(this.bufSN > t) && - !(this.streamListeners.length > 0) && - (this.logger.info( - `cancel download ${i} to ${this.remotePeerId} remain packets ${this.remainAttachments}` - ), - (this.timeReceivePiece = 0), - this.sendJson({ - event: e.DC_PIECE_CANCEL, - sn: t, - level: r, - seg_id: i, - })) - ); - } - addStreamListener(e, t, r) { - this.streamListeners.push({ handler: r, peerId: t }); - } - removeStreamListener(e) { - this.streamListeners = this.streamListeners.filter( - (t) => - t.peerId !== e || - (t.handler(void 0, void 0, !0, "aborted by cancel"), !1) - ); - } - _initPeerChannel() { - const t = new Y({ - initiator: this.isInitiator, - trickle: this.options.trickle || !1, - config: this.webRTCConfig, - }); - (this._datachannel = t), - t.on("error", (t) => { - let r = !0; - (this.connected || this.notFatalClosed) && (r = !1), - this.emit(e.DC_ERROR, r, t.message); - }), - t.on("signal", (t) => { - (t.candidate && !t.candidate.candidate) || - (!this.useBackupSignal && - this.signalMsgs.length < 10 && - this.signalMsgs.push(t), - (this.sentSignal = !0), - this.emit(e.DC_SIGNAL, t)); - }); - t.on("connect", () => { - for ( - this.logger.info( - `datachannel CONNECTED from ${ - this.intermediator ? "peer" : "server " + this.signalName - } to ${this.remotePeerId}` - ), - this.connected = !0, - clearTimeout(this.connTimeout), - this.signalMsgs = [], - this.emit(e.DC_OPEN); - this.msgQueue.length > 0; - - ) { - let e = this.msgQueue.shift(); - this.emit(e.event, e); - } - }), - t.on("data", (t) => { - const { logger: r } = this; - if ("string" == typeof t) { - let i = JSON.parse(t); - if (!i) return void r.error("dc received string is null"); - if (!this.connected) return void this.msgQueue.push(i); - let n, - s = i.event; - switch ( - ((n = - s !== e.DC_PLAYLIST && s !== e.DC_PEER_SIGNAL - ? `string: ${t}` - : `event: ${s}`), - r.debug( - `datachannel receive ${n} from ${this.remotePeerId}` - ), - s) - ) { - case e.DC_HAVE: - if ((this.emit(i.event, i), !i.sn)) return; - this.config.live || - (i.sn < this.startSN && (this.startSN = i.sn), - i.sn > this.endSN && (this.endSN = i.sn)); - break; - case e.DC_PIECE: - (this.downloading = !0), - (this.dataExchangeTs = g()), - (this.timeReceivePiece = performance.now()), - (this.pieceMsg = i), - this._prepareForBinary( - i.attachments, - i.seg_id, - i.sn, - i.size - ), - this.emit(i.event, i); - break; - case e.DC_PIECE_CANCEL: - r.info( - `send queue ${this.datasToSend.length}, uploading ${this.uploading}` - ), - this.emit(i.event, i), - this.sendMsgPieceAbort("transfer canceled", i.seg_id); - break; - case e.DC_PIECE_NOT_FOUND: - this._sendNextReq() || (this.downloading = !1), - this.emit(i.event, i); - break; - case e.DC_REQUEST: - this._handleRequestMsg(i); - break; - case e.DC_PIECE_ACK: - this._handlePieceAck(i.seg_id, i.size, i.miss); - break; - case e.DC_STATS: - this._handleStats(i); - break; - case e.DC_PLAYLIST: - this.config.sharePlaylist && this._handlePlaylist(i); - break; - case e.DC_METADATA: - this._handleMetadata(i); - break; - case e.DC_PIECE_ABORT: - this.downloading && - (this._notifyDownloadListenersAbort( - "aborted by upstream peer" - ), - this.emit(e.DC_PIECE_ABORT, i)), - (this.downloading = !1); - break; - case e.DC_CHOKE: - r.info(`choke peer ${this.remotePeerId}`), - (this.choked = !0); - break; - case e.DC_UNCHOKE: - r.info(`unchoke peer ${this.remotePeerId}`), - (this.choked = !1); - break; - case e.DC_CLOSE: - this.emit(i.event, i.fatal || !1); - break; - default: - this.emit(i.event, i); - } - } else { - if (!t) - return void r.error("datachannel on data is undefined!"); - if (!this.downloading) - return void r.warn( - `peer ${this.remotePeerId} not downloading, data size ${ - t.byteLength - } pieceMsg ${JSON.stringify(this.pieceMsg)}` - ); - this._handleBinaryMsg(t); - } - }), - t.once("close", () => { - this.emit(e.DC_CLOSE, !1); - }), - t.on("iceStateChange", (t, r) => { - this.connected && - "disconnected" === t && - (this.logger.warn(`${this.remotePeerId} disconnected`), - this.emit(e.DC_DISCONNECT)); - }); - } - sendJson(t) { - if (!this.remotePeerId) return !1; - t.event !== e.DC_PLAYLIST && t.event !== e.DC_PEER_SIGNAL - ? this.logger.debug( - `dc bufferSize ${ - this._datachannel.bufferSize - } send ${JSON.stringify(t)} to ${this.remotePeerId}` - ) - : this.logger.debug( - `dc send event ${t.event} to ${this.remotePeerId}` - ); - const r = JSON.stringify(t); - return r.length > u - ? (this.logger.error("string to send is too large"), !1) - : this.send(r, !1); - } - send(e, t = !0) { - return t - ? (this.datasToSend.push(e), - this.dataWriting || this._sendDataSync(), - !0) - : this.sendImmediately(e); - } - _sendDataSync() { - if (!this._datachannel.connected || 0 === this.datasToSend.length) - return void (this.dataWriting = !1); - this.dataWriting = !0; - const t = this.datasToSend.shift(); - t - ? ("string" != typeof t && (this.bytesUploaded += t.byteLength), - this._datachannel.write(t, (t) => { - if (t) - return ( - (this.dataWriting = !1), - void this.emit(e.DC_ERROR, !1, t.message) - ); - this._sendDataSync(); - })) - : this.logger.error("sendDataSync data is undefined!"); - } - sendImmediately(t) { - if (this._datachannel.connected) - try { - return this._datachannel.send(t), !0; - } catch (t) { - const r = `datachannel ${this.channelId} send data failed, close it`; - this.emit(e.DC_ERROR, !1, r); - } - return !1; - } - sendMsgHave(t, r, i = {}) { - const n = i.reverse || void 0; - delete i.reverse, - this.sendJson({ - event: n ? e.DC_HAVE_REVERSE : e.DC_HAVE, - sn: t, - seg_id: r, - ...i, - }); - } - sendPieceNotFound(t, r, i = {}) { - (this.uploading = !1), - this.sendJson({ - event: e.DC_PIECE_NOT_FOUND, - seg_id: r || void 0, - sn: t, - ...i, - }); - } - sendPeers(t) { - this.sendJson({ event: e.DC_PEERS, peers: t }); - } - sendPeersRequest() { - this.sendJson({ event: e.DC_GET_PEERS }); - } - sendMsgStats(t, r = {}) { - const i = { event: e.DC_STATS, total_conns: t, ...r }; - this.sendJson(i); - } - sendMsgPlaylist(t, r, i) { - const n = this.playlistMap.get(t); - if (n && n.seq >= i) return; - const s = { event: e.DC_PLAYLIST, url: t, data: r, seq: i }; - this.playlistMap.set(t, { data: r, seq: i }), this.sendJson(s); - } - sendMsgSignal(t, r, i) { - return this.sendJson({ - event: e.DC_PEER_SIGNAL, - action: "signal", - to_peer_id: t, - from_peer_id: r, - data: i, - }); - } - sendMsgSignalReject(t, r, i, n = !1) { - return this.sendJson({ - event: e.DC_PEER_SIGNAL, - action: "reject", - to_peer_id: t, - from_peer_id: r, - reason: i, - fatal: n, - }); - } - sendMetaData(t, r, i, n, s = !1) { - this.isInitiator && (this.timeSendRequest = performance.now()), - this.sendJson({ - event: e.DC_METADATA, - field: t, - platform: e.DC_PLAT_WEB, - mobile: !!Q().isMobile(), - mobile_net: s, - channel: this.channel, - version: "2.12.15", - sequential: r, - peers: i, - region: n, - }); - } - sendPartialBuffer(e, t, r = {}) { - this.sendMsgPiece(e, r); - for (let e = 0; e < t.length; e++) this.send(t[e]); - } - sendMsgPiece(e, t = {}) { - if (!this.uploading) return; - (this.datasToSend = []), - (this.bytesUploaded = 0), - e.ext || (e.ext = {}), - e.ext.from && - t.from && - t.from.length < 2500 && - (t.from = `${e.ext.from}-${t.from}`), - t.incompletes && - e.ext.incompletes && - (t.incompletes += e.ext.incompletes), - (t = Object.assign({}, e.ext, t)); - const r = { ...e, ext: t }; - this.sendJson(r); - } - sendBuffer(t, r, i, n = {}) { - const s = n.reverse || void 0; - if ((delete n.reverse, !i)) - return void this.logger.error("sendBuffer payload is undefined!"); - let a = i.byteLength, - o = 0, - l = 0; - a % this.packetSize == 0 - ? (l = a / this.packetSize) - : ((l = Math.floor(a / this.packetSize) + 1), - (o = a % this.packetSize)); - let h = { - event: e.DC_PIECE, - attachments: l, - seg_id: r, - sn: t, - level: n.level, - size: a, - reverse: s, - }; - delete n.level, this.sendMsgPiece(h, n); - const u = (function (e, t, r, i) { - let n = []; - if (i) { - let s; - for (let i = 0; i < r - 1; i++) - (s = e.slice(i * t, (i + 1) * t)), n.push(s); - (s = e.slice(e.byteLength - i, e.byteLength)), n.push(s); - } else { - let i; - for (let s = 0; s < r; s++) - (i = e.slice(s * t, (s + 1) * t)), n.push(i); - } - return n; - })(i, this.packetSize, l, o); - this._sendBufferArray(u, s), - (this.uploading = !1), - (this.timeSendPiece = performance.now()); - } - get downloadNum() { - return this.downloading ? this.sendReqQueue.length + 1 : 0; - } - requestDataById(t, r, i = !1, n = {}) { - const s = { - event: e.DC_REQUEST, - seg_id: t, - sn: r, - ...n, - urgent: i, - }; - this.downloading - ? (this.logger.info(`${this.remotePeerId} add req ${t} in queue`), - i ? this.sendReqQueue.unshift(s) : this.sendReqQueue.push(s)) - : this._realRequestData(s); - } - requestDataBySN(t, r = !1, i = {}) { - const n = { event: e.DC_REQUEST, sn: t, ...i, urgent: r }; - this.downloading - ? (this.logger.info(`add req ${t} in queue`), - r ? this.sendReqQueue.unshift(n) : this.sendReqQueue.push(n)) - : this._realRequestData(n); - } - _sendBufferArray(e, t = !1) { - const r = t ? e.reverse() : e; - for (let e = 0; e < r.length; e++) this.send(r[e]); - } - _realRequestData(e) { - this.sendJson(e), - (this.timeSendRequest = performance.now()), - (this.downloading = !0); - } - shouldWaitForRemain(e) { - return ( - 0 !== this.bufArrSize && - 0 !== this.timeReceivePiece && - this.currentLoadSpeed() >= this.minRequiredSpeed(e) - ); - } - close(t) { - t || (this.notFatalClosed = !0), this.emit(e.DC_CLOSE, t); - } - receiveSignal(e) { - if ("answer" === e.type) { - if (this.gotAnswer || this.gotOffer) return; - this.gotAnswer = !0; - } else if ("offer" === e.type) { - if (this.gotOffer || this.gotAnswer) return; - this.gotOffer = !0; - } - (this.gotSignal = !0), e && this._datachannel.signal(e); - } - _notifyDownloadListenersAbort(e) { - for (let t of this.streamListeners) { - const { handler: r } = t; - r(void 0, void 0, !0, e); - } - this.streamListeners = []; - } - destroy(t = !0) { - this.logger.info(`destroy datachannel ${this.channelId}`), - clearTimeout(this.chokeTimer), - clearTimeout(this.connTimeout), - this._notifyDownloadListenersAbort("upstream peer is closed"); - let r = { event: e.DC_CLOSE, fatal: t }; - this.sendJson(r), - this._datachannel.removeAllListeners(), - this.removeAllListeners(), - this._datachannel.destroy(); - } - _handleBinaryMsg(t) { - const { attachments: r, reverse: i } = this.pieceMsg; - this.listenerCount(e.DC_RESPONSE) > 0 && this.bufArr.push(t), - (this._loadedBytes += t.byteLength), - this.remainAttachments--; - let n = i ? this.remainAttachments + 1 : r - this.remainAttachments; - const s = 0 === this.remainAttachments; - if ( - (this.emit( - e.DC_PIECE_DATA, - this.bufSN, - this.segId, - t, - n, - s, - this.pieceMsg - ), - this.streamListeners.length > 0) - ) - for (let e of this.streamListeners) { - const { handler: r } = e; - r(this.bufSN, this.segId, !1, t, s); - } - if (s) { - if (((this.streamListeners = []), this.timeSendRequest > 0)) - if (this.super) this.weight = 1; - else { - const e = - this.expectedSize / - (performance.now() - this.timeSendRequest); - this.weight = - this.weight > 0 ? 0.6 * this.weight + 0.4 * e : e; - } - this.sendJson({ - event: e.DC_PIECE_ACK, - seg_id: this.segId, - size: this.expectedSize, - miss: this.miss || void 0, - }), - (this.timeSendRequest = 0), - (this.timeReceivePiece = 0), - this._sendNextReq() || (this.downloading = !1), - this._handleBinaryData(i); - } - } - _sendNextReq() { - if (this.sendReqQueue.length > 0) { - const e = this.sendReqQueue.shift(); - return ( - this.logger.info( - `get msg from sendReqQueue ${JSON.stringify(e)}` - ), - this._realRequestData(e), - !0 - ); - } - return !1; - } - _handlePlaylist(e) { - const { url: t, data: r, seq: i } = e; - this.playlistMap.set(t, { data: r, seq: i }); - } - getLatestPlaylist(e, t) { - if (!this.playlistMap.has(e)) return null; - const r = this.playlistMap.get(e); - return r.seq <= t || r.seq > t + 2 ? null : r; - } - _handleMetadata(t) { - const { logger: r } = this; - if (this.isInitiator) { - const e = performance.now() - this.timeSendRequest; - e > 0 && - ((this.weight = 1e5 / e), - r.info( - `handle Metadata from ${this.remotePeerId} initial weight ${this.weight}` - )), - (this.timeSendRequest = 0); - } - const i = t.channel; - if (this.channel !== i) { - const t = `peer channel ${i} not matched!`; - return r.error(t), void this.emit(e.DC_ERROR, !0, t); - } - if (t.super) { - r.info(`got super peer ${this.remotePeerId}`), (this.super = !0); - const { token: i } = this.config; - if (i && t.token !== i) - return void this.emit( - e.DC_ERROR, - !0, - `super peer token ${t.token} not matched!` - ); - } - t.region && (this.region = t.region); - switch (t.platform) { - case e.DC_PLAT_ANDROID: - this.platform = e.DC_PLAT_ANDROID; - break; - case e.DC_PLAT_IOS: - this.platform = e.DC_PLAT_IOS; - break; - case e.DC_PLAT_WEB: - this.platform = e.DC_PLAT_WEB; - } - if ( - ((this.mobile = t.mobile || !1), - (this.mobileNet = t.mobile_net || !1), - (this.mobileWeb = - (this.mobile && this.platform === e.DC_PLAT_WEB) || !1), - (this.sequential = t.sequential), - r.info( - `${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}` - ), - t.peers && - ((this.peersConnected += t.peers), - r.info( - `${this.remotePeerId} now has ${this.peersConnected} peers` - )), - this.emit(e.DC_METADATA, t), - t.field && !this.config.live && t.sequential) - ) { - const { field: e } = t; - if (Array.isArray(e)) this._handleField(e); - else for (let t in e) this._handleField(e[t]); - } - } - _handleField(e) { - e.forEach((e) => { - e >= 0 && - (e < this.startSN && (this.startSN = e), - e > this.endSN && (this.endSN = e)); - }); - } - _handleStats(e) { - this.gotStatsTs = g(); - const t = e.total_conns; - t > 0 && - this.peersConnected !== t && - ((this.peersConnected = t), - this.logger.info( - `${this.remotePeerId} now has ${this.peersConnected} peers` - )), - e.level && (this.currentLevel = e.level), - e.pos && (this.currentPos = e.pos); - } - _handleRequestMsg(t) { - if (((this.dataExchangeTs = g()), this.uploading)) - return ( - this.logger.warn( - `${this.remotePeerId} is uploading when receive request` - ), - void this.sendPieceNotFound(t.sn, t.seg_id, { level: t.level }) - ); - (this.uploading = !0), this.emit(e.DC_REQUEST, t); - } - _handlePieceAck(t, r, i) { - 0 !== this.timeSendPiece && - ((this.uploadSpeed = Math.round( - (r / (performance.now() - this.timeSendPiece)) * 2 - )), - (this.timeSendPiece = 0), - this.logger.info( - `${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}` - )), - i > 0 && this.logger.warn(`peer ${this.remotePeerId} miss ${i}`), - this.bytesUploaded > 0 && - this.emit(e.DC_PIECE_ACK, { seg_id: t, size: r }); - } - _prepareForBinary(e, t, r, i) { - (this.bufArr = []), - (this._loadedBytes = 0), - (this.remainAttachments = e), - (this.segId = t), - (this.bufSN = r), - (this.expectedSize = i); - } - _handleBinaryData(t = !1) { - if (this.listenerCount(e.DC_RESPONSE) > 0) { - t && this.bufArr.reverse(); - let r = a.h.concat(this.bufArr); - const i = r.byteLength; - if (i === this.expectedSize) { - let t = r.buffer; - const i = new z( - this.bufSN, - this.segId, - t, - this.remotePeerId, - this.pieceMsg.level - ); - this.emit(e.DC_RESPONSE, i, this.weight); - } else - this.logger.error( - `${this.segId} expectedSize ${this.expectedSize} != byteLength ${i}` - ); - } - this.bufArr = []; - } - checkIfNeedChoke(e = !1) { - const { logger: t } = this, - r = performance.now() - this.timeSendRequest; - if ( - (e || !(r < 1e3)) && - (this.miss++, - t.info(`${this.remotePeerId} miss ${this.miss}`), - this.miss >= 3 && !this.choked) - ) { - this.choked = !0; - const e = 30 * this.miss; - e <= 150 - ? (t.warn(`datachannel ${this.channelId} is choked`), - (this.chokeTimer = setTimeout(() => { - (this.choked = !1), - t.warn(`datachannel ${this.channelId} is unchoked`); - }, 1e3 * e))) - : t.warn(`datachannel ${this.channelId} is choked permanently`); - } - } - get bufArrSize() { - return this.downloading - ? this.pieceMsg.attachments - this.remainAttachments - : 0; - } - loadtimeout() { - const { logger: e, pieceMsg: t } = this; - return ( - e.warn( - `timeout while downloading from ${this.remotePeerId}, ${this.bufArrSize} of ${t.attachments} packets loaded` - ), - this.checkIfNeedChoke(), - !0 - ); - } - sendMsgPieceAbort(t, r, i = !1) { - if (!i && !this.uploading && 0 === this.datasToSend.length) return; - (this.uploading = !1), - (this.datasToSend = []), - this._handlePieceAck(r, this.bytesUploaded, 0), - (this.bytesUploaded = 0); - const n = { event: e.DC_PIECE_ABORT, reason: t }; - return this.sendJson(n); - } - loadedBytes() { - return this._loadedBytes; - } - currentLoadSpeed() { - return 0 === this.timeReceivePiece - ? 0 - : this.loadedBytes() / - (performance.now() - this.timeReceivePiece); - } - minRequiredSpeed(e) { - return (this.pieceMsg.size - this.loadedBytes()) / e; - } - } - const Z = J, - ee = { - DPlayer: "dplayer", - CBPlayer: "cbplayer", - jwplayer: "jwplayer", - videojs: "videojs", - Clappr: "clappr", - ckplayer: "ckplayer", - MediaElementPlayer: "mediaelement", - MediaElement: "mediaelement", - TcPlayer: "tcplayer", - flowplayer: "flowplayer", - Chimee: "chimee", - ChimeePlayer: "chimee", - HlsJsPlayer: "xgplayer", - fluidPlayer: "fluidplayer", - OpenPlayer: "openplayer", - Plyr: "plyr", - Playerjs: "playerjs", - Aliplayer: "aliplayer", - shaka: "shakaplayer", - RadiantMP: "rmp", - bitmovin: "bitmovin", - }; - const te = "nllL", - re = "d3NzJ", - ie = "==", - ne = "TNBLy9z", - se = "aWduY", - ae = "mNvbQ", - oe = "WwuY2RuY", - le = { - [e.EXCEPTION]: "onException", - serverConnected: "onServerConnected", - peerId: "getPeerId", - p2pDownloaded: "onP2pDownloaded", - p2pUploaded: "onP2pUploaded", - httpDownloaded: "onHttpDownloaded", - bufferStalled: "onBufferStalled", - peers: "getPeersInfo", - }; - class he extends s() { - constructor(e = {}) { - if ( - (super(), - (this.p2pEnabled = !(!1 === e.p2pEnabled || "0" === c("_p2p"))), - e.tag && e.tag.length > 20) - ) - throw new Error("Tag is too long"); - if (e.appName && e.appName.length > 30) - throw new Error("appName is too long"); - if (e.appId && e.appId.length > 30) - throw new Error("appId is too long"); - if (e.token && e.token.length > 20) - throw new Error("Token is too long"); - (this.segmentLoadCount = 0), - (this.rangeTested = !1), - (this.playerName = (function () { - let e; - for (let t in ee) - if (self[t]) { - e = ee[t]; - break; - } - return e; - })()); - } - startRangeRequestTimer() { - const { config: e, logger: t } = this, - r = () => { - this.curTsUri && - (function (e, t, r, i = 2e3, n = !1) { - const s = new XMLHttpRequest(); - let a = e; - return ( - n && (a = f(e, h, !0)), - (t = t || "bytes=0-0"), - new Promise((n, o) => { - s.open("GET", a, !0), - (s.responseType = "arraybuffer"), - (s.timeout = i), - (s.onreadystatechange = (e) => { - if (4 === s.readyState) { - const e = s.status; - 206 === e || (200 === e && t) - ? n(s.response) - : o(`status ${e} url ${a} range ${t}`); - } - }), - (s.onerror = (e) => { - o("request error"); - }), - (s.ontimeout = (e) => { - o("timeout"); - }), - s.setRequestHeader("Range", t), - r && r(s, e), - s.send(); - }) - ); - })(this.curTsUri, void 0, e.xhrSetup) - .then(() => { - (e.httpRangeSupported = !0), - clearTimeout(this.rangeRequestTimer); - }) - .catch((i) => { - (e.httpRangeSupported = !1), - t.warn(i), - (this.rangeRequestTimer = setTimeout(r, 6e4)); - }) - .finally(() => { - t.info( - `http range is${ - e.httpRangeSupported ? "" : " not" - } supported` - ); - }); - }; - this.rangeRequestTimer = setTimeout(r, 0); - } - initLogger() { - const { config: e } = this; - e.showSlogan && - "en" == - ("zh-CN" === (navigator.language || navigator.userLanguage) - ? "cn" - : "en") && - console.log( - `%cLet the browsers become your unlimitedly scalable CDN!\n%c${self.atob( - "aHR0cHM6Ly9zd2FybWNsb3VkLm5ldA==" - )}`, - "color: dodgerblue; padding:20px 0; font-size: x-large", - "font-size: medium; padding-bottom:15px" - ); - const t = new $(e.logLevel); - return (e.logger = this.logger = t), t; - } - getExtraForStats() { - return {}; - } - getExtraForPeersRequest() { - const e = {}; - return (e.num_want = this._getNumWant()), e; - } - _getNumWant() { - const { tracker: e } = this; - if (!e.scheduler) return; - const t = e.scheduler.peersNum; - return t > 0 && e.maxConnsActive - t > 0 - ? e.maxConnsActive - t - : void 0; - } - makeChannelId(e, t) { - if (!e || "string" != typeof e) { - const e = "token is required while using customized channelId!"; - throw (console.error(e), new Error(e)); - } - return A(t) ? (r, i) => `${e}-${t(r, i)}` : () => `${e}-${t}`; - } - makeSignalId() { - let e = ""; - const { config: t } = this, - r = decodeURIComponent( - self.atob(re + ne + se + oe + te + ae + ie) - ); - t.signalConfig && (t.wsSignalerAddr = t.signalConfig); - const { wsSignalerAddr: i } = t; - if (i) { - let n; - "object" == typeof i - ? (i.main || (i.main = r), (n = i.main)) - : "string" == typeof i && - ((n = i), (t.wsSignalerAddr = { main: n })), - n === r && (n = void 0), - n && - !t.wsSignalerAddr.backup && - (e = l().parseURL(n).netLoc.substring(2)); - } else t.wsSignalerAddr = { main: r, byDefault: !0 }; - return e; - } - get commonBrowserInfo() { - const e = Q().getPlatform(), - t = Q().getNetType() || "wifi"; - this.netType = t; - const { - main: r, - backup: i, - byDefault: n, - } = this.config.wsSignalerAddr || {}; - return { - signal: n ? void 0 : r, - signal2: i, - device: e, - netType: t, - player: this.playerName, - }; - } - get isMobileNet() { - return "wifi" !== this.netType && "ethernet" !== this.netType; - } - setupWindowListeners(e) { - const t = - ["iPad", "iPhone"].indexOf(navigator.platform) >= 0 - ? "pagehide" - : "beforeunload", - r = () => { - this.fetcher && this.fetcher.postStatsWithBeacon(), - this.p2pEnabled && this.disableP2P(), - self.removeEventListener(t, r); - }; - e ? self.removeEventListener(t, r) : self.addEventListener(t, r); - } - destroy() { - clearTimeout(this.rangeRequestTimer), - this.disableP2P(!0), - this.removeAllListeners(), - this.setupWindowListeners(!0); - } - enableP2P() { - return this.p2pEnabled - ? null - : (this.logger && this.logger.info("enable P2P"), - (this.config.p2pEnabled = this.p2pEnabled = !0), - this.browserInfo - ? (this._init(this.channel, this.browserInfo), this) - : null); - } - get version() { - return he.version; - } - static isSupported() { - const e = v(); - return !( - !e || void 0 === e.RTCPeerConnection.prototype.createDataChannel - ); - } - static get TrackerZone() { - return { EU: "eu", HK: "hk", USA: "us", CN: "cn" }; - } - determineHttpLoadTime(e, t, r) { - this.logger && - this.logger.info( - `segments in playlist: ${e.length}, targetDuration: ${t} startSN ${r}` - ); - let i = 3.5; - return ( - t <= 2 - ? (i = 1) - : t <= 3 - ? (i = 1.5) - : t <= 4 - ? (i = 2) - : t <= 6 - ? (i = 2.5) - : t <= 8 && (i = 3), - i - ); - } - emitEvent(e, ...t) { - this.emit(e, ...t); - const r = le[e]; - r && A(this.config[r]) && this.config[r](...t); - } - } - (he.version = "2.12.15"), (he.protocolVersion = Z.VERSION); - const ue = he; - function de() { - if ( - !(function () { - if ("object" == typeof self) - return ( - self.ManagedMediaSource || - self.MediaSource || - self.WebKitMediaSource - ); - })() - ) - return !1; - const e = self.SourceBuffer || self.WebKitSourceBuffer; - return ( - !e || - (e.prototype && - "function" == typeof e.prototype.appendBuffer && - "function" == typeof e.prototype.remove) - ); - } - function ce(e, t) { - let r; - if ( - (e && - ("string" == typeof e - ? ((r = document.querySelector(e)), - fe(r) || - (r = (function (e) { - const t = document.getElementById(e); - if (fe(t)) return t; - const r = t.getElementsByTagName("*"); - for (let e = 0; e < r.length; e++) - if (fe(r[e])) return r[e]; - return null; - })(e))) - : e instanceof HTMLMediaElement && (r = e)), - !r) - ) { - const e = [ - ...document.getElementsByTagName("video"), - ...document.getElementsByTagName("audio"), - ]; - 1 === e.length - ? (r = e[0]) - : (t && (r = e.find((e) => e.src === t)), - r || (r = e.find((e) => e.currentTime > 0))); - } - return r; - } - function fe(e) { - if (!e) return null; - const t = e.tagName.toLowerCase(); - return "video" === t || "audio" === t; - } - function ge(e, t, r, i = 0, n = 0) { - const s = u; - let a = i, - o = n || r - 1; - const l = Math.floor(r / s), - h = r % s > 0 ? l + 1 : l; - if ((e >= 0 && (a += (e + 1) * s), t >= 0 && t < h)) { - o -= (r % s) + (h - t - 1) * s; - } - return { rangeStart: a, rangeEnd: o + 1 }; - } - function pe(e, t) { - return `${e}-${t}`; - } - function me(e, t, r, i) { - let n = r.split("?")[0]; - return ( - n.startsWith("http") && (n = n.split("://")[1]), - i ? `${n}|${i}` : `${n}` - ); - } - function ve(e, t) { - return "number" != typeof t && (t = Number(t)), `${t}-${e}`; - } - let ye = { - wsMaxRetries: 10, - p2pEnabled: !0, - signalCompact: !0, - wifiOnly: !1, - memoryCacheLimit: { pc: 419430400, mobile: 104857600 }, - dcDownloadTimeout: 25, - logLevel: "error", - webRTCConfig: {}, - token: void 0, - appName: void 0, - appId: void 0, - prefetchNum: 4, - showSlogan: !0, - trickleICE: !0, - announceLocation: "eu", - trackerZone: void 0, - geoIpPreflight: !0, - ICEPreflight: !0, - useDiskCache: !0, - startFromSegmentOffset: 0, - getStats: function (e, t, r) {}, - getPeerId: function (e) {}, - getPeersInfo: function (e) {}, - }; - const Ee = { - ...ye, - httpLoadTime: 0, - sharePlaylist: !1, - useHttpRange: !0, - hlsjsInstance: null, - proxyOnly: !1, - proxyFirst: !1, - p2pBlackList: ["vtt", "webvtt", "key"], - live: !0, - swFile: "./sw.js", - swScope: "./", - swAutoRegister: !0, - mediaElem: void 0, - httpStreamEnabled: !0, - diskCacheLimit: { pc: 1572864e3, mobile: 1048576e3 }, - waitForPeer: !1, - waitForPeerTimeout: 4, - strictSegmentId: !1, - prefetchOnly: !1, - }, - Se = "store not init", - Te = 1e3; - function _e(e) { - const t = new Promise((t, r) => { - (e.oncomplete = e.onsuccess = () => t(e.result)), - (e.onabort = e.onerror = () => r(e.error)); - }), - r = - ((i = Te), - (n = "indexedDB timeout"), - new Promise((e, t) => - setTimeout(() => { - t(n); - }, i) - )); - var i, n; - return Promise.race([t, r]); - } - function Le(e, t) { - return t ? t("readonly", (t) => _e(t.get(e))) : Promise.reject(Se); - } - function be(e, t, r) { - return r - ? r("readwrite", (r) => (r.put(t, e), _e(r.transaction))) - : Promise.reject(Se); - } - function Re(e, t) { - return t - ? t("readwrite", (t) => (t.delete(e), _e(t.transaction))) - : Promise.reject(Se); - } - function Ae(e) { - return e - ? e("readwrite", (e) => (e.clear(), _e(e.transaction))) - : Promise.reject(Se); - } - function we(e, t) { - return ( - (e.openCursor().onsuccess = function () { - this.result && (t(this.result), this.result.continue()); - }), - _e(e.transaction) - ); - } - const Pe = "size"; - class Ie extends s() { - constructor(e, t) { - super(), - (this.name = "SegmentStore"), - (this.logger = t.logger), - this.logger.info(`use ${this.name}`), - (this.engine = e), - (this.channel = e.channel); - const r = e.browserInfo.device; - (this.isPC = r === Q().device.PC_WEB || r === Q().device.PC_NATIVE), - (this.maxBufSize = this.isPC - ? t.diskCacheLimit.pc - : t.diskCacheLimit.mobile), - (this.overflowed = !1), - (this.countErrors = 0), - (this.isCleared = !0), - (this.destroyed = !1); - } - async setupStore() { - if (navigator.storage && navigator.storage.estimate) { - const e = await navigator.storage.estimate(), - t = Math.floor(e.quota - e.usage); - t < this.maxBufSize && (this.maxBufSize = t - 104857600); - } - return new Promise(async (e, t) => { - if ( - (this.isPC && this.maxBufSize < 419430400) || - (!this.isPC && this.maxBufSize < 104857600) - ) - return void t("disk storage not enough"); - const r = this.stores; - let i; - try { - i = (function (e, t) { - const r = indexedDB.open(e); - r.onupgradeneeded = () => { - const e = r.result; - t.forEach((t) => { - e.createObjectStore(t); - }); - }; - const i = _e(r); - return t.map( - (e) => (t, r) => - i.then((i) => r(i.transaction(e, t).objectStore(e))) - ); - })(this.channel, r); - } catch (e) { - return void t(e); - } - this._createStores(i), this._initMetaStore().then(e).catch(t); - }); - } - _initMetaStore() { - return be(Pe, 0, this.metaStore); - } - currBufSize() { - return new Promise(async (e, t) => { - try { - const r = await Le(Pe, this.metaStore); - if (isNaN(r)) return void t("size is NaN"); - e(r); - } catch (e) { - t(e); - } - }); - } - async putSeg(t) { - if (this.destroyed) return; - this.isCleared = !1; - const { logger: r } = this; - if (_(t.data)) - return new Promise((i) => { - this._addSeg(t) - .then((t) => { - this._onSegPut(t), this.emit(e.BM_SEG_ADDED, t), i(); - }) - .catch((t) => { - this._handleFataError(), - t && - (r.warn(`putSeg ${t}`), - ("QuotaExceededError" === t.name || - (t.inner && "QuotaExceededError" === t.inner.name)) && - this.currBufSize() - .then((e) => { - this._trimDisk(e, !0); - }) - .catch((t) => { - this.logger.error(`putSeg ${t}`), - this.engine.emit(e.BM_FATAL_ERROR); - })), - i(); - }); - }); - r.error(`putSeg ${t.segId} is not buffer`); - } - _handleFataError() { - this.countErrors++, - this.countErrors >= 3 && - (this.engine.emit(e.BM_FATAL_ERROR), (this.countErrors = 0)); - } - _decreaseBufSize(e) { - this.currBufSize() - .then((t) => { - t && be(Pe, t - e, this.metaStore); - }) - .catch((e) => { - this.logger.warn(`decreaseBufSize ${e}`); - }); - } - _increaseBufSize(t) { - this.destroyed || - this.currBufSize() - .then((e) => { - be(Pe, e + t, this.metaStore), this._trimDisk(e + t); - }) - .catch((t) => { - this.logger.warn(`increaseBufSize ${t}`), - this.engine.emit(e.BM_FATAL_ERROR); - }); - } - clear(e = !1) { - if (!this.isCleared) { - this.logger.warn("clear segment store"); - try { - this._clearDisk(e); - } catch (e) {} - this.isCleared = !0; - } - } - _clearDisk(e) { - Ae(this.segmentsStore), - e ? this._initMetaStore() : Ae(this.metaStore), - (this.overflowed = !1); - } - destroy() { - this.clear(), this.removeAllListeners(), (this.destroyed = !0); - } - } - const Ce = Ie; - const ke = class extends Ce { - constructor(e, t) { - super(e, t), - (this.loadingSN = -1), - (this.stores = ["segments", "id2Sn", "metadata"]); - } - _createStores(e) { - (this.segmentsStore = e[0]), - (this.id2SnStore = e[1]), - (this.metaStore = e[2]); - } - async hasSegOfId(e) { - if (!e) return Promise.resolve(!1); - let t; - try { - t = await Le(e, this.id2SnStore); - } catch (e) { - return Promise.resolve(!1); - } - return new Promise((r) => { - void 0 !== t - ? Le(t, this.segmentsStore) - .then((t) => { - t && t.length > 0 && t.some((t) => t.segId === e) - ? r(!0) - : r(!1); - }) - .catch((e) => { - this.logger.warn(`hasSegOfId ${e}`), r(!1); - }) - : r(!1); - }); - } - async getSegById(e) { - if (!e) return null; - const { logger: t } = this; - let r; - try { - r = await Le(e, this.id2SnStore); - } catch (e) { - return null; - } - return new Promise((i) => { - void 0 !== r - ? Le(r, this.segmentsStore) - .then((r) => { - if (r && r.length > 0) { - const n = r.find((t) => t.segId === e); - if (!n) return void i(null); - if (!_(n.data)) - return ( - t.error(`getSegById ${n.sn} is not buffer`), - void i(null) - ); - i(z.fromSegment(n)); - } else i(null); - }) - .catch((e) => { - t.warn(`getSegById ${e}`), - this._handleFataError(), - i(null); - }) - : i(null); - }); - } - getSegIdBySN(e) { - return new Promise((t) => { - Le(e, this.segmentsStore) - .then((e) => { - e && e.length > 0 ? t(e[0].segId) : t(null); - }) - .catch((e) => { - this.logger.warn(`getSegIdBySN ${e}`), t(null); - }); - }); - } - _addSeg(e) { - const { segId: t, sn: r, size: i } = e; - return ( - be(t, r, this.id2SnStore), - new Promise((n, s) => { - Le(r, this.segmentsStore) - .then((a) => { - a - ? 0 === a.filter((e) => e.segId === t).length - ? (a.push(this._segmentToCache(e)), - be(r, a, this.segmentsStore) - .then(() => { - this._increaseBufSize(i), n(e); - }) - .catch((e) => { - s(e); - })) - : n(e) - : be(r, [this._segmentToCache(e)], this.segmentsStore) - .then(() => { - this._increaseBufSize(i), n(e); - }) - .catch((e) => { - s(e); - }); - }) - .catch((e) => { - s(e); - }); - }) - ); - } - async _trimDisk(t, r = !1) { - if (this.isCleared || this.destroyed) return; - let i = this.maxBufSize; - const { logger: n } = this; - var s; - (r && ((i = t - 104857600), i < 0 && (i = 0)), t < i) || - (n.warn(`_trimDisk currentSize ${t} upBound ${i}`), - ((s = this.segmentsStore), - s - ? s("readonly", (e) => { - if (e.getAllKeys) return _e(e.getAllKeys()); - const t = []; - return we(e, (e) => t.push(e.key)).then(() => t); - }) - : Promise.reject(Se)).then(async (r) => { - const s = r.sort((e, t) => e - t); - let a = 0; - do { - if (a++ > 10) { - n.warn("too much loops in SegmentStore"); - break; - } - const r = s.shift(); - if (void 0 === r) { - n.warn("lastSN not found"); - continue; - } - if (r >= this.loadingSN) { - n.warn(`trimDisk failed, loadingSN ${this.loadingSN}`); - break; - } - const i = s[0], - o = await Le(r, this.segmentsStore); - if (!o) { - n.warn("lastSeg not found"); - continue; - } - let l = 0; - o.forEach((e) => { - l += e.data.byteLength; - }), - Re(r, this.segmentsStore).then(() => { - this._decreaseBufSize(parseInt(l)); - }), - o.forEach((t) => { - Re(t.segId, this.id2SnStore), - n.info(`pop seg ${t.segId} size ${t.data.byteLength}`), - this.emit(e.BM_LOST, { - sn: r, - segId: t.segId, - next: i, - level: t.level, - }); - }), - (t -= l), - n.info(`pop sn ${r} size ${l} currBufSize ${t}`), - this.overflowed || (this.overflowed = !0); - } while (t >= i); - })); - } - _segmentToCache(e) { - return { data: e.data, level: e.level, segId: e.segId, sn: e.sn }; - } - _onSegPut(t) { - this.emit(`${e.BM_ADDED_SN_}${t.sn}`, t); - } - _clearDisk(e) { - try { - super._clearDisk(e); - } catch (e) {} - Ae(this.id2SnStore).catch((e) => {}); - } - }; - class De extends s() { - constructor(e, t) { - super(), - (this.name = "SegmentCache"), - (this.logger = t.logger), - this.logger.info(`use ${this.name}`); - const r = e.browserInfo.device; - if ( - ((this.maxBufSize = - r === Q().device.PC_WEB || r === Q().device.PC_NATIVE - ? t.memoryCacheLimit.pc - : t.memoryCacheLimit.mobile), - (this.isLive = t.live), - this.isLive) - ) - this.maxBufSize = 47185920; - else { - if (0 === this.maxBufSize) - throw new Error("cannot use SegmentCache"); - const e = (function () { - const { memory: e } = performance; - return e ? e.jsHeapSizeLimit - e.usedJSHeapSize : -1; - })(); - e >= 0 && e < this.maxBufSize && (this.maxBufSize = e - 31457280); - } - (this._segPool = new Map()), - (this._currBufSize = 0), - (this.overflowed = !1), - (this.isCleared = !0), - (this.destroyed = !1); - } - get currBufSize() { - return this._currBufSize; - } - _calSegPoolSize() { - let e = 0; - return ( - this._segPool.forEach((t) => { - t.forEach((t) => { - e += t.size; - }); - }), - e - ); - } - async putSeg(e) { - this.destroyed || - ((this.isCleared = !1), - this._currBufSize >= 1.5 * this.maxBufSize && - ((this._currBufSize = this._calSegPoolSize()), - this._currBufSize >= 1.5 * this.maxBufSize && - (this.clear(), (this.overflowed = !1))), - _(e.data) - ? this._addSeg(e) - : this.logger.error(`putSeg ${e.segId} is not buffer`)); - } - clear() { - this.isCleared || - (this.logger.warn("clear segment cache"), - this._segPool.clear(), - (this._currBufSize = 0), - (this.isCleared = !0), - (this.overflowed = !1)); - } - destroy() { - this.clear(), this.removeAllListeners(), (this.destroyed = !0); - } - } - const Me = De; - const xe = class extends Me { - constructor(e, t) { - super(e, t), (this.id2Sn = new Map()), (this.loadingSN = -1); - } - hasSegOfId(e) { - return new Promise((t, r) => { - const i = this.id2Sn.get(e); - this._segPool.has(i) - ? t(this._segPool.get(i).some((t) => t.segId === e)) - : t(!1); - }); - } - getSegById(e) { - const t = this.id2Sn.get(e); - return new Promise((r, i) => { - if (!this._segPool.has(t)) return void r(null); - r(this._segPool.get(t).find((t) => t.segId === e)); - }); - } - getSegIdBySN(e) { - return new Promise((t, r) => { - if (this._segPool.has(e)) { - t(this._segPool.get(e)[0].segId); - } else t(null); - }); - } - _addSeg(t) { - const { logger: r } = this, - { segId: i, sn: n, size: s } = t; - if ((this.id2Sn.set(i, n), this._segPool.has(n))) { - this._segPool.get(n).push(t); - } else this._segPool.set(n, [t]); - this._currBufSize += parseInt(s); - const a = this._segPool.size; - if ( - (this.emit(`${e.BM_ADDED_SN_}${t.sn}`, t), - this.emit(e.BM_SEG_ADDED, t), - this._currBufSize < this.maxBufSize || a <= 5) - ) - return; - let o = Array.from(this._segPool.keys()); - this.isLive || (o = o.sort((e, t) => e - t)); - let l = 0; - do { - if (l++ > 10) { - r.error("too much loops in SegmentCache"); - break; - } - const t = o.shift(); - if (void 0 === t) { - r.error("lastSN not found"); - continue; - } - const i = o[0], - n = this._segPool.get(t); - if (!n) { - r.error("lastSeg not found"); - continue; - } - let s = 0; - n.forEach((e) => { - s += e.size; - }), - (this._currBufSize -= parseInt(s)), - this._segPool.delete(t), - n.forEach((r) => { - this.id2Sn.delete(r.segId), - this.emit(e.BM_LOST, { - sn: t, - segId: r.segId, - next: i, - level: r.level, - }); - }), - r.info( - `pop sn ${t} size ${s} currBufSize ${this._currBufSize}` - ), - this.overflowed || (this.overflowed = !0); - } while ( - this._currBufSize >= this.maxBufSize && - this._segPool.size > 5 - ); - } - clear() { - super.clear(), this.id2Sn.clear(); - } - }; - var Oe = r(832), - Fe = r.n(Oe); - function Ne(e, t) { - for (const r in t) - Object.defineProperty(e, r, { - value: t[r], - enumerable: !0, - configurable: !0, - }); - return e; - } - const Be = function (e, t, r) { - if (!e || "string" == typeof e) - throw new TypeError("Please pass an Error to err-code"); - r || (r = {}), - "object" == typeof t && ((r = t), (t = void 0)), - null != t && (r.code = t); - try { - return Ne(e, r); - } catch (t) { - (r.message = e.message), (r.stack = e.stack); - const i = function () {}; - return ( - (i.prototype = Object.create(Object.getPrototypeOf(e))), - Ne(new i(), r) - ); - } - }; - class Ue { - constructor() { - (this.p2p = 0), (this.share = 0), (this.http = 0); - } - recordP2p(e) { - this.p2p += e; - } - recordShare(e) { - this.share += e; - } - recordHttp(e) { - this.http += e; - } - resetTraffic() { - (this.p2p = 0), (this.share = 0), (this.http = 0); - } - get healthRatio() { - if (0 === this.http) return 1e3; - let e = Math.round(((this.p2p + this.share) / this.http) * 100); - return e <= 0 && (e = 1), e; - } - } - const Ge = "SW_GEOIP_KEY", - He = 2592e5, - $e = 432e5, - Ke = "TRACKER_EXPT", - We = "IPAPI_ERROR", - Ve = "ZXU", - qe = "uY2R", - je = "LmNv", - Ye = "uYnll", - ze = "bQ==", - Xe = "Z3o", - Qe = "aGsuc3d", - Je = "hcm1j", - Ze = "bG91ZC", - et = "5uZXQ=", - tt = Symbol("httpDownloaded"), - rt = Symbol("p2pDownloaded"), - it = Symbol("p2pUploaded"); - class nt extends s() { - constructor(e, t, r, i, n) { - let s; - super(), (this.config = e.config); - let a = this.config.announceLocation; - switch ( - (this.config.trackerZone && (a = this.config.trackerZone), a) - ) { - case "hk": - s = Qe + Je + Ze + et; - break; - case "us": - s = "dXMuaGR0dmNsb3VkLmNvbQ=="; - break; - case "cn": - s = Xe + qe + Ye + je + ze; - break; - default: - s = Ve + qe + Ye + je + ze; - } - (this.engine = e), - (this.key = t || void 0), - (this.baseUrl = i || `https://${self.atob(s)}/v1`), - (this.channelId = self.btoa(r)), - (this.timestamp = g()), - (this.health = new Ue()); - const o = l().parseURL(this.baseUrl).netLoc; - (this.announce = o.replace(/\/\//, "")), - (function (e, t) { - function r(e, t, r, i, n) { - return h(r - 219, n); - } - var i, - n, - s = e(); - function a(e, t, r, i, n) { - return h(n - -994, e); - } - function o(e, t, r, i, n) { - return h(i - 233, t); - } - function l(e, t, r, i, n) { - return h(n - 305, r); - } - for (;;) - try { - if ( - 156690 === - (-parseInt(o(0, 246, 0, 247)) / 1) * - (-parseInt(o(0, 243, 0, 248)) / 2) + - -parseInt(o(0, 238, 0, 245)) / 3 + - (parseInt(a(-1e3, 0, 0, 0, -989)) / 4) * - (-parseInt(r(0, 0, 225, 0, 216)) / 5) + - (-parseInt(((i = -180), (n = -173), h(n - -181, i))) / - 6) * - (parseInt(l(0, 0, 324, 0, 324)) / 7) + - (-parseInt(a(-991, 0, 0, 0, -990)) / 8) * - (parseInt(l(0, 0, 313, 0, 307)) / 9) + - -parseInt(l(0, 0, 310, 0, 305)) / 10 + - (-parseInt(a(-968, 0, 0, 0, -974)) / 11) * - (-parseInt(r(0, 0, 226, 0, 216)) / 12) - ) - break; - s.push(s.shift()); - } catch (e) { - s.push(s.shift()); - } - })(d); - function h(e, t) { - var r = d(); - return (h = function (e, t) { - return r[(e -= 0)]; - })(e, t); - } - const u = (function (e, t, r, i, n, s) { - let a = location.hostname; - a === h(-922 - -923, -915) && s && (a = s + "." + a); - return 13, Fe()(a + "2.12.15" + r + i + n, e).substr(0, 8); - })( - this.timestamp, - 0, - this.announce, - this.channelId, - n.type, - this.key - ); - function d() { - var e = [ - "13055AgbnUs", - "2739cfXSxI", - "CxYEuy093515".split("").reverse().join(""), - "localhost", - "OCXDId9".split("").reverse().join(""), - "yek".split("").reverse().join(""), - "QyapiZ8635101".split("").reverse().join(""), - "scRrUF02".split("").reverse().join(""), - "bNcslL58187".split("").reverse().join(""), - "QEbZrW65772".split("").reverse().join(""), - "12gYmKGR", - "emantsoh".split("").reverse().join(""), - "dIlennahc".split("").reverse().join(""), - "pmatsemit".split("").reverse().join(""), - "676614MZdLCs", - "type", - "hpNRbU1".split("").reverse().join(""), - "133332xoUKrS", - "announce", - "lmia", - "substr", - ]; - return (d = function () { - return e; - })(); - } - h(895 - 878, 886), - (this.native = !!n.bundle), - (this.announceInfo = { - ...n, - channel: this.channelId, - ts: this.timestamp, - version: "2.12.15", - v: u, - announce: this.announce, - k: lt(this.key), - }), - (this.announceURL = `${this.baseUrl}/channel`), - (this.reportFails = 0), - (this.statsRequesting = !1), - (this.forbidden = !1), - (this.failConns = 0), - (this.totalHTTPDownloaded = 0), - (this.totalP2PDownloaded = 0), - (this.totalP2PUploaded = 0), - (this[tt] = 0), - (this[rt] = 0), - (this[it] = 0), - (this.speed = 0), - (this.offline = !1), - (this.errsBufStalled = 0), - (this.mediaRequests = 0), - (this.errsInternalExpt = 0); - } - geoipRequest() { - const { logger: e } = this.engine; - return new Promise((t, r) => { - if ( - ((e) => { - const t = localStorage.getItem(e); - try { - const e = JSON.parse(t); - return ( - !(!e.duration || !e.startTime) && - Date.now() - e.startTime < e.duration - ); - } catch (e) { - return !1; - } - })(Ge) - ) { - const r = U(Ge); - e.info("found local geo data"), t(r); - } else - fetch( - self.atob( - "aHR0cHM6Ly9wcm8uaXAtYXBpLmNvbS9qc29uP2ZpZWxkcz0yMTgxODI2JmtleT1YT3BpYW5zUmdZeEdUaG8=" - ) - ) - .then((e) => e.json()) - .then((e) => { - if ("success" !== e.status) { - const t = new Error(`preflight status ${e.status}`); - throw Be(t, We); - } - { - const r = e.mobile ? $e : He; - G(Ge, e, r), t(e); - } - }) - .catch((e) => { - r(e); - }); - }); - } - btAnnouncePreflight() { - const { logger: e } = this.engine; - return this.announceInfo.asn - ? this.btAnnounce() - : (e.info("preflight ip-api"), - Promise.race([ - this.geoipRequest(), - new Promise((e, t) => { - setTimeout(() => { - t(Be(new Error("request timeout"), We)); - }, 600); - }), - ]) - .then((e) => (this._parseGeoResponse(e), this.btAnnounce())) - .catch((t) => { - if (t.code !== Ke) { - const t = U(Ge); - return ( - t && - (e.info("use expired ipData"), - this._parseGeoResponse(t)), - this.btAnnounce() - ); - } - throw t; - })); - } - _parseGeoResponse(e) { - const { - lat: t, - lon: r, - isp: i, - as: n, - mobile: s, - countryCode: a, - continentCode: o, - } = e; - s && (this.announceInfo.netType = "cellular"); - const l = n.split(" ")[0].substr(2); - this.announceInfo = { - ...this.announceInfo, - lat: t, - lon: r, - isp: i, - asn: l, - country: a, - }; - } - btAnnounce() { - const { logger: e } = this.engine; - return new Promise((t, r) => { - fetch(this.announceURL, { - headers: this._requestHeader, - method: "POST", - body: JSON.stringify(this.announceInfo), - }) - .then((e) => { - if (!e.ok) { - const t = e.status >= 500 && e.status < 600; - throw Be( - new Error(`server response code is ${e.status}`), - Ke, - { retry: t } - ); - } - return e.json(); - }) - .then((e) => { - if (!this.engine) - throw Be(new Error("runtime error"), Ke, { retry: !1 }); - const r = e.data; - if ((r.f && (this.forbidden = !0), -1 === e.ret)) { - const { code: t, msg: r } = e.data; - throw Be(new Error(r), Ke, { retry: t >= 5e3 }); - } - if ( - (r.info && console.info(`${r.info}`), - r.warn && console.warn(`${r.warn}`), - r.min_conns || (r.min_conns = 8), - (!r.rejected || (r.rejected && r.share_only)) && - r.id && - r.report_interval && - r.peers) - ) { - if ( - ((this.peerId = this.id = r.id), - r.report_interval < 20 && (r.report_interval = 20), - this.btStats(r.report_interval), - (this.getPeersURL = `${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/peers`), - (this.statsURL = `${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/stats`), - !this.announceInfo.asn && r.asn) - ) { - const { - country: e, - asn: t, - mobile: i, - isp: n, - lat: s, - lon: a, - } = r; - (this.announceInfo = { - ...this.announceInfo, - country: e, - asn: t, - }), - G( - Ge, - { - countryCode: e, - as: `AS${t}`, - mobile: i, - isp: n, - lat: s, - lon: a, - status: "success", - }, - i ? $e : He - ); - } - t(r); - } else this.engine && (this.engine.p2pEnabled = !1); - }) - .catch((t) => { - e.error(`btAnnounce error ${t}`); - const i = t.code || Ke, - n = !t.code || t.retry; - r(Be(t, i, { retry: n })); - }); - }); - } - btStats(e = 10) { - this.heartbeater = setInterval(() => { - this.postStats(); - }, 1e3 * e); - } - postStatsWithBeacon() { - if (this.offline) return; - this.offline = !0; - let e = { off: !0 }; - this.statsRequesting || (e = { ...e, ...this._makeStatsBody() }), - this.statsURL && - navigator.sendBeacon && - navigator.sendBeacon(this.statsURL, JSON.stringify(e)); - } - postStats() { - const { logger: t } = this.engine; - (this.statsRequesting = !0), - fetch(this.statsURL, { - method: "POST", - body: JSON.stringify(this._makeStatsBody()), - }) - .then( - (e) => ( - (this.statsRequesting = !1), - (this.reportFails = 0), - e.text() - ) - ) - .then((r) => { - let i; - if ( - ((i = r ? JSON.parse(r) : { ret: 0, data: {} }), - -1 === i.ret) - ) - clearInterval(this.heartbeater), - t.error(`${i.data.msg} code ${i.data.code}`), - this.engine.emit(e.RESTART_P2P); - else { - const { - http: e = 0, - p2p: t = 0, - share: r = 0, - failConns: i = 0, - rebuffers: n = 0, - requests: s = 0, - errsInternalExpt: a = 0, - } = this.lastStats || {}; - this[tt] >= e && (this[tt] -= e), - this[rt] >= t && (this[rt] -= t), - this[it] >= r && (this[it] -= r), - this.failConns >= i && (this.failConns -= i), - this.errsBufStalled >= n && (this.errsBufStalled -= n), - this.mediaRequests >= s && (this.mediaRequests -= s), - this.errsInternalExpt >= a && - (this.errsInternalExpt -= a), - this.exptMsg && (this.exptMsg = void 0); - } - }) - .catch((e) => { - t.error(`btStats error ${e}`), - (this.statsRequesting = !1), - this.reportFails++, - this.reportFails >= 3 && clearInterval(this.heartbeater); - }); - } - btGetPeers(e, t = !1) { - const { logger: r } = this.engine, - { asn: i, country: n } = this.announceInfo; - let s = { - exclusions: e, - asn: i, - country: n, - ratio: this.health.healthRatio, - urgent: t || void 0, - }, - a = {}; - return ( - this.engine.getExtraForPeersRequest && - (a = this.engine.getExtraForPeersRequest()), - (s = Object.assign({}, s, a)), - new Promise((e, t) => { - this.reportFails >= 3 - ? t(new Error("reportFails >= 3")) - : fetch(this.getPeersURL, { - headers: this._requestHeader, - method: "POST", - body: JSON.stringify(s), - }) - .then((e) => e.json()) - .then((r) => { - -1 === r.ret ? t(r.data.msg) : e(r.data); - }) - .catch((e) => { - r.error(`btGetPeers error ${e}`), t(e); - }) - .finally(() => { - this.health.resetTraffic(); - }); - }) - ); - } - increFailConns() { - this.failConns++; - } - increRebuffers() { - this.engine.emitEvent("bufferStalled"), this.errsBufStalled++; - } - increMediaRequests() { - this.mediaRequests++, - this.engine.emit(e.MEDIA_REBUFFER, this.errsBufStalled >= 2); - } - reportFlow(e) { - const t = Math.round(e / 1024); - this.engine.emitEvent("httpDownloaded", t), - (this[tt] += t), - (this.totalHTTPDownloaded += t), - this.health.recordHttp(t), - this._emitStats(); - } - reportDCTraffic(e, t) { - const r = Math.round(e / 1024); - (this[rt] += r), - (this.totalP2PDownloaded += r), - this.health.recordP2p(r), - (this.speed = Math.round(t)), - this.engine.emitEvent("p2pDownloaded", r, this.speed), - this._emitStats(); - } - reportUploaded(e = 0) { - const t = Math.round(e / 1024); - this.engine.emitEvent("p2pUploaded", t), - (this.totalP2PUploaded += t), - this.health.recordShare(t), - (this[it] += t), - this._emitStats(); - } - destroy() { - const { logger: e } = this.engine; - e.warn("destroy fetcher"), - this.removeAllListeners(), - clearInterval(this.heartbeater); - } - _emitStats() { - const { - totalHTTPDownloaded: e, - totalP2PDownloaded: t, - totalP2PUploaded: r, - } = this; - this.engine.emit("stats", { - totalHTTPDownloaded: e, - totalP2PDownloaded: t, - totalP2PUploaded: r, - p2pDownloadSpeed: this.speed, - }); - const { getStats: i } = this.config; - A(i) && i(t, r, e, this.speed); - } - _makeStatsBody() { - const { asn: e, country: t } = this.announceInfo; - let r = { - totalConns: this.engine.tracker.totalConns, - failConns: this.failConns, - rebuffers: this.errsBufStalled || void 0, - requests: this.mediaRequests || void 0, - errsInternalExpt: this.errsInternalExpt, - http: Math.round(this[tt]) || 0, - // p2p: Math.round(this[rt]) || 0, - p2p: 0, - // share: Math.round(this[it]) || 0, - share: 0, - asn: e, - country: t, - }, - i = {}; - this.engine.getExtraForStats && - (i = this.engine.getExtraForStats()), - (r = Object.assign({}, r, i)), - (this.lastStats = JSON.parse(JSON.stringify(r))), - Object.keys(r).forEach((e) => { - 0 === r[e] && delete r[e]; - }); - const { logger: n } = this.engine; - return ( - n.isDebugLevel && n.info(`report ${JSON.stringify(r)}`), - this.exptMsg && (r.exptMsg = "2.12.15 " + this.exptMsg), - r - ); - } - get _requestHeader() { - let e = {}; - return ( - this.native && - (e = { - ...e, - "X-SW-Key": lt(this.key), - "User-Agent": "electron", - "X-SW-ID": this.announceInfo.bundle, - }), - e - ); - } - } - const st = nt; - function at(e, t) { - const r = ot(); - return (at = function (e, t) { - return r[(e -= 0)]; - })(e, t); - } - function ot() { - const e = [ - "CsLPpZ8932212".split("").reverse().join(""), - "htgnel".split("").reverse().join(""), - "UZpUzY5895021".split("").reverse().join(""), - "yJZuxA9452121".split("").reverse().join(""), - "tAedoCrahc".split("").reverse().join(""), - "btoa", - "q# { - this._longPolling(); - }); - } - _hello(e) { - fetch(this.addr + "&hello", { method: "POST" }) - .then((e) => { - if (!e.ok) throw new Error("hello response was not ok"); - return e.json(); - }) - .then((t) => { - (this.connected = !0), e(), this.onopen && this.onopen(t.ver); - }) - .catch((e) => { - (this.closed = !0), this.onerror && this.onerror(e); - }); - } - send(e) { - this.msgQueue.push(e), - this.posting || this._realSend([...this.msgQueue]); - } - _realSend(e) { - 0 !== e.length && - ((this.posting = !0), - (this.msgQueue = []), - fetch(this.addr, { method: "POST", body: JSON.stringify(e) }) - .then(() => { - (this.posting = !1), - this.msgQueue.length > 0 && - this._realSend([...this.msgQueue]); - }) - .catch((e) => { - this.logger.error(e), (this.posting = !1); - })); - } - close() { - this.connected && - ((this.closed = !0), - (this.connected = !1), - this.abortController && - (this.abortController.abort(), (this.abortController = null)), - this.onclose && this.onclose()); - } - destroy() { - this.close(), this.removeAllListeners(); - } - _longPolling() { - if (this.closed) return; - this.abortController = new AbortController(); - const e = this.abortController.signal; - fetch(this.addr, { signal: e }) - .then((e) => { - if (!e.ok) throw new Error("polling response was not ok"); - return e.text(); - }) - .then((e) => { - e && this.onmessage && this.onmessage(JSON.parse(e)), - (this.retryCount = 0), - this._longPolling(); - }) - .catch((e) => { - this.connected && - (this.retryCount <= 3 - ? (this.retryCount++, this._longPolling()) - : ((this.connected = !1), this.onerror && this.onerror(e))); - }); - } - } - const ut = class { - constructor(e, t, r, i = "main") { - (this.logger = e), - (this.config = t), - (this.wsAddr = r), - (this.serverVersion = 0), - (this.pingInterval = 95e3), - (this.name = i), - (this.normalClosed = !1), - (this.lastSendTs = performance.now()), - (this.pollingClient = new ht(e, r)); - try { - this._ws = this._init(); - } catch (t) { - e.error(t), this._startPolling(); - } - } - get batchSupported() { - return this.serverVersion >= 50; - } - _init() { - const e = { - maxRetries: this.config.wsMaxRetries, - minReconnectionDelay: p(15e3, 6e4), - maxReconnectionDelay: 6e5, - maxEnqueuedMessages: 20, - connectionTimeout: 7e3, - }; - let t = new F(this.wsAddr, void 0, e); - return ( - t.addEventListener("open", () => { - this.logger.info( - `signal ${this.name} ${this.wsAddr} connection opened` - ), - (this.normalClosed = !1), - this.pollingClient.connected - ? this.pollingClient.close() - : this.onopen && this.onopen(), - this._startPing(this.pingInterval); - }), - (t.push = t.send), - (t.send = (e) => { - this.lastSendTs = performance.now(); - let r = JSON.stringify(e); - t.push(r); - }), - t.addEventListener("message", (e) => { - let t = e.data; - const r = JSON.parse(t), - i = r.action; - if ("pong" !== i) { - if ("ver" !== i) - return "close" === i - ? (this.logger.warn( - `server close signal ${this.name} reason ${r.reason}` - ), - void this.close()) - : void (this.onmessage && this.onmessage(r, this.name)); - this.serverVersion = r.ver; - } else clearTimeout(this.pongTimer); - }), - t.addEventListener("close", (e) => { - this.logger.warn( - `signal ${this.name} ${this.wsAddr} closed ${e.code} ${e.reason}` - ), - e.code >= 5e3 || e.code < 4e3 - ? (this.onclose && this.onclose(), this._stopPing()) - : this.close(); - }), - t.addEventListener("error", (e) => { - this._stopPing(), - this.onerror && this.onerror(e), - this._startPolling(); - }), - t - ); - } - forcePolling() { - this.pollingClient.connected || - (this.close(), - (this.pollingClient = new ht(this.logger, this.wsAddr)), - this._startPolling()); - } - _startPolling() { - this.pollingClient.connected || - (this.logger.info(`${this.name} start polling`), - this.pollingClient.start(), - this._setupPolling(this.pollingClient)); - } - sendDebug(e, t, r) { - this._send({ - action: "debug", - details: t, - ping: r || void 0, - to: e, - }); - } - sendSignal(e, t) { - const r = { action: "signal", to: e, data: t }; - this._send(r); - } - sendSignalBatch(e, t) { - if (this.batchSupported && t.length > 1) - this._send({ action: "signals", to: e, data: t }); - else for (let r of t) this.sendSignal(e, r); - } - sendReject(e, t, r) { - if (this.rejectIdCache === e) return; - this.rejectIdCache = e; - const i = { action: "reject", to: e, reason: t, fatal: r }; - this._send(i); - } - _send(e) { - this.pollingClient.connected - ? this.pollingClient.send(e) - : this._ws && this._ws.send(e); - } - _startPing(e) { - this.connected && - (this.pingTimer = setTimeout(() => { - const e = 95e3 - (performance.now() - this.lastSendTs); - if (e >= 0) return this._startPing(e); - const t = { action: "ping" }; - this._ws && this._ws.push(JSON.stringify(t)), - (this.pongTimer = setTimeout(() => { - this.logger.warn( - `signal ${this.name} wait for pong timeout, reconnect` - ), - this.close(), - this.reconnect(); - }, 15e3)), - this._startPing(this.pingInterval); - }, e)); - } - _stopPing() { - clearTimeout(this.pingTimer), clearTimeout(this.pongTimer); - } - close() { - this.logger.info(`close signal ${this.name}`), - this._stopPing(), - (() => { - this._ws && this._ws.close(1e3); - })(), - this.pollingClient.close(), - (this.normalClosed = !0); - } - reconnect() { - this._ws && - (this.logger.info(`reconnect signal ${this.name}`), - this._ws.reconnect()); - } - destroy() { - this.close(), (this._ws = null), this.pollingClient.destroy(); - } - get connected() { - return !!this.pollingClient.connected || this._connected; - } - get _connected() { - return !!this._ws && this._ws.readyState === F.OPEN; - } - _setupPolling(e) { - (e.onopen = (e) => { - e && (this.serverVersion = e), - this.logger.info(`${this.name} polling opened`), - this.onopen && this.onopen(); - }), - (e.onerror = (e) => { - this._connected || (this.onerror && this.onerror(e)); - }), - (e.onclose = () => { - this._connected || (this.onclose && this.onclose()); - }), - (e.onmessage = (e) => { - if (this.onmessage) - for (let t of e) this.onmessage(t, this.name); - }); - } - }, - dt = class { - constructor(e, t, r, i) { - (this.logger = e), - (this.config = t), - (this.mainAddr = r), - (this.backupAddr = i), - (this.mainWS = this._init(r)), - (this.backupTimer = setTimeout(() => { - this.destroyed || (this.backupWS = this._init(i, "backup")); - }, 900)), - (this._connected = !1), - (this.destroyed = !1), - (this.normalClosed = !1); - } - _init(e, t) { - if (!e) return null; - let r = new ut(this.logger, this.config, e, t); - return ( - (r.onopen = () => { - (this.normalClosed = !1), - !this._connected && - this.onopen && - ((this._connected = !0), this.onopen()); - }), - (r.onmessage = (e) => { - this.onmessage && this.onmessage(e, r.name); - }), - (r.onclose = () => { - this._connected && - !this.connected && - this.onclose && - ((this._connected = !1), this.onclose()); - }), - (r.onerror = (e) => { - this.onerror && this.onerror(e); - }), - r - ); - } - sendSignalBatch(e, t, r) { - if (r) { - const i = this._getWSByName(r); - i && i.sendSignalBatch(e, t); - } else - this.mainConnected - ? this.mainWS.sendSignalBatch(e, t) - : this.backupConnected && this.backupWS.sendSignalBatch(e, t); - } - sendSignal(e, t, r) { - this.sendSignalBatch(e, [t], r); - } - sendReject(e, t, r, i) { - if (i) { - const n = this._getWSByName(i); - if (n) return void n.sendReject(e, t, r); - } - this.mainConnected - ? this.mainWS.sendReject(e, t, r) - : this.backupConnected - ? this.backupWS.sendReject(e, t, r) - : this.logger.warn("no signal available, send reject failed"); - } - sendDebug(e, t, r) { - this.mainConnected && this.mainWS.sendDebug(e, t, r); - } - close() { - this.mainWS && this.mainWS.close(), - this.backupWS && this.backupWS.close(), - (this.normalClosed = !0); - } - _getWSByName(e) { - return this.mainWS && this.mainWS.name === e - ? this.mainWS - : this.backupWS && this.backupWS.name === e - ? this.backupWS - : null; - } - reconnect(e) { - this.mainWS && "backup" !== e && this.mainWS.reconnect(), - this.backupWS && "main" !== e && this.backupWS.reconnect(); - } - forcePolling(e) { - this.mainWS && "backup" !== e && this.mainWS.forcePolling(), - this.backupWS && "main" !== e && this.backupWS.forcePolling(); - } - destroy() { - this.close(), - clearTimeout(this.backupTimer), - (this.mainWS = null), - (this.backupWS = null), - (this.destroyed = !0); - } - get connected() { - return this.mainConnected || this.backupConnected; - } - get mainConnected() { - return this.mainWS && this.mainWS.connected; - } - get backupConnected() { - return this.backupWS && this.backupWS.connected; - } - }; - const ct = function (e, t, r = 40) { - var i = null, - n = !1, - s = r; - return function (r = !1) { - if (r) return clearTimeout(i), void (n = !1); - n || - ((n = !0), - (i = setTimeout(function () { - e.call(t, s), (n = !1), (i = null); - }, 1e3 * s)), - (s *= 1.1)); - }; - }; - class ft { - constructor(e, t, r = 10) { - (this.engine = e), - (this.config = t), - (this.trickle = t.trickleICE), - (this.poolSize = r), - (this.pool = []), - t.ICEPreflight && this.reset(), - (this.trickle = !1); - } - reset() { - this.destroy(); - for (let e = 0; e < this.poolSize; e++) - this.pool.push(this._createPeer()); - } - _createPeer() { - return new Z(this.engine, void 0, void 0, !0, this.config, { - trickle: this.trickle, - }); - } - get available() { - return 0 !== this.pool.length && this.pool[0].signalMsgs.length > 0; - } - getPeer() { - if (0 === this.pool.length) return this._createPeer(); - const e = this.pool.shift(); - return ( - this.pool.length < 5 && this.pool.push(this._createPeer()), e - ); - } - destroy() { - for (let e of this.pool) e.destroy(!0); - this.pool = []; - } - } - const gt = class { - static CHARSET = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - static BITS_PER_BYTE = 8; - static BITS_PER_BASE64_CHAR = 6; - static decode(e) { - let t = 0, - r = 0, - i = ""; - for (const n of e) { - if ("=" === n) break; - const e = this.CHARSET.indexOf(n); - for ( - t = (t << this.BITS_PER_BASE64_CHAR) | e, - r += this.BITS_PER_BASE64_CHAR; - r >= this.BITS_PER_BYTE; - - ) { - r -= this.BITS_PER_BYTE; - i += ((t >> r) & ((1 << this.BITS_PER_BYTE) - 1)) - .toString(16) - .padStart(2, "0") - .toUpperCase(); - } - } - let n = ""; - for (let e = 0; e < i.length; e++) - (n += i[e]), e % 2 == 1 && e !== i.length - 1 && (n += ":"); - return n; - } - }, - pt = "typ host", - mt = "generation 0", - vt = "network-cost", - yt = "rport", - Et = "0.0.0.0", - St = { - V: "v=", - O: "o=", - S: "s=", - C: "c=", - A: "a=", - M: "m=", - T: "t=", - }, - Tt = { - U: "ice-ufrag:", - P: "ice-pwd:", - F: "fingerprint:", - C: "candidate:", - S: "sctp-port:", - M: "max-message-size:", - }, - _t = { - 1: "sha-1", - 2: "sha-224", - 3: "sha-256", - 4: "sha-384", - 5: "sha-512", - 6: "md5", - 7: "md2", - 8: "token", - }, - Lt = { - P: `${pt} ${mt} ${vt} 999`, - W: `${yt} 0 ${mt} ${vt} 999`, - H: pt, - S: "typ srflx", - R: yt, - A: "raddr", - V: Et, - F: "ufrag", - G: `${yt} 0 ${mt}`, - N: vt, - E: "network-id", - C: "tcptype active", - Q: `${mt}`, - U: "udp", - T: "tcp", - }, - bt = { - P: "application", - U: "UDP/DTLS/SCTP", - D: "webrtc-datachannel", - }, - Rt = { 4: "IP4", 6: "IP6" }, - At = { 0: Et }, - wt = (e) => ( - e.startsWith("C") && (e = "candidate:" + e.slice(1)), - e - .split(" ") - .map((e) => (e in Lt && (e = Lt[e]), e)) - .join(" ") - ); - function Pt(e, t) { - let r = e.split("~"), - i = []; - (r = r.map((e) => { - let t = e.slice(0, 1), - r = e.slice(1); - if ((t in St && (t = St[t]), "a=" === t)) { - let e = r.slice(0, 1); - const t = r.slice(1); - e in Tt && ((e = Tt[e]), (r = e + t)); - } - return t + r; - })), - i.push("v=0"), - i.push("s=-"), - i.push("t=0 0"), - i.push("a=msid-semantic: WMS"); - let n = 0; - r.forEach((e) => { - if (e.startsWith("o=")) { - let t = e.slice(2).split(" "), - r = []; - r.push("-"); - const n = t.shift(); - if ((n && r.push(n), 0 === t.length)) - r.push("2 IN IP4 127.0.0.1"); - else { - const e = t.shift(); - if ((e && r.push(e), 0 === t.length)) - r.push("IN IP4 127.0.0.1"); - else { - r.push("IN"); - const e = t.shift(); - e && r.push(e); - const i = t.shift(); - i && r.push(i); - } - } - i.splice(1, 0, `o=${r.join(" ")}`); - } else { - if (e.startsWith("m=")) - return ( - (e = (function (e) { - return e.replace(It, (e) => bt[e]); - })(e)), - i.push(e), - i.push("a=setup:" + (t ? "actpass" : "active")), - i.push(`a=mid:${n}`), - void n++ - ); - if (e.startsWith("a=candidate:")) - return (e = wt(e)), void i.push(e); - if (e.startsWith("a=fingerprint:")) { - let [t, r] = e.slice(14).split(" "); - return ( - t in _t && (t = _t[t]), - (r = gt.decode(r)), - void i.push(`a=fingerprint:${t} ${r}`) - ); - } - if (e.startsWith("c=")) { - let [t, r] = e.slice(2).split(" "); - return ( - t in Rt && (t = Rt[t]), - r in At && (r = At[r]), - void i.push(`c=IN ${t} ${r}`) - ); - } - "I" !== e - ? "Z" !== e - ? "B" !== e - ? i.push(e) - : i.push("a=sendrecv") - : i.push("a=ice-options:ice2,trickle") - : i.push("a=ice-options:trickle"); - } - }); - const s = i.length - 1; - return ( - i.splice( - s, - 0, - `a=group:BUNDLE ${Array.from(Array(n).keys()).join(" ")}` - ), - i.join("\r\n") - ); - } - const It = new RegExp(Object.keys(bt).join("|"), "g"); - class Ct extends s() { - constructor(e, t, r, i) { - super(), - (this.engine = e), - (this.logger = e.logger), - (this.config = i), - (this.connected = !1), - (this.scheduler = r), - (this.sequential = this.scheduler.sequential), - (this.DCMap = new Map()), - (this.failedDCMap = new Map()), - (this.notFoundDCSet = new Set()); - const n = Q().isMobile(); - (this.peerPool = new ft(e, i, 15)), - (this.signalerWs = null), - (this.fetcher = t), - (this.peers = []), - (this.requestPeersQueue = []), - (this.minConns = 5), - (this.stuns = []), - (this.requestMorePeers = ct( - this._requestMorePeers, - this, - p(35, 45) - )), - (this.maxConns = n ? 15 : 22), - (this.maxConnsActive = n ? 10 : 13), - (this.peersIncrement = 0), - (this.gotPeersFromTracker = !1), - (this.requestPeersWaitCount = 0), - (this.gotSignalFails = { main: 0, backup: 0, limit: 5 }), - (this.fuseRate = -1), - (this.overloaded = !1); - } - get totalConns() { - return this.scheduler.peersNum + 1; - } - resumeP2P() { - if (!this.fetcher) return; - const { engine: t, config: r, fetcher: i } = this, - { btAnnounce: n, btAnnouncePreflight: s } = i, - { wsSignalerAddr: a, wifiOnly: o, geoIpPreflight: l } = r; - (l ? s : n) - .call(i) - .then((e) => { - const { scheduler: r } = this; - if (!r) return; - (t.peerId = this.peerId = e.id), - (this.minConns = e.min_conns), - (r.minConns = this.minConns); - const n = e.peers; - r.notifyPeersLoaded(n.length), - n.length > this.gotSignalFails.limit && - (this.gotSignalFails.limit = n.length), - (t.netType = i.announceInfo.netType), - (e.wifi_only || o) && - t.isMobileNet && - ((r.downloadOnly = !0), - this.logger.info("downloadOnly mode")); - const s = a.main; - let l = a.backup; - function h(e, t) { - var r = u(); - return (h = function (e, t) { - return r[(e -= 0)]; - })(e, t); - } - function u() { - var e = [ - "IHmzPt4745802".split("").reverse().join(""), - "fqbpvJ65672".split("").reverse().join(""), - "peerId", - "evitcAsnnoCxam".split("").reverse().join(""), - "0r^EeI@*KS".split("").reverse().join(""), - "yGChQi82100203".split("").reverse().join(""), - "dIlennahc".split("").reverse().join(""), - "qrZmAF0973735".split("").reverse().join(""), - "qNTzkD6562665".split("").reverse().join(""), - "timestamp", - "HaovMZ5303011".split("").reverse().join(""), - "blnwIB1433257".split("").reverse().join(""), - "39zAjEpC", - "substring", - ]; - return (u = function () { - return e; - })(); - } - var d, c; - e.signal && !e.signal2 && (l = void 0), - (this.signalerWs = this._initSignalerWs( - e.signal || s, - e.signal2 || l, - e.token, - e.token2 - )), - 0 === n.length - ? this.requestMorePeers() - : (this.peers = this._filterPeers(n)), - t.emitEvent("peerId", this.peerId), - e.stun && e.stun.length > 0 && (this.stuns = e.stun), - e.debug && - (this.logger.enableDebug(), - e.log_url && - ((this.logUploader = new B( - e.log_url, - this.fetcher.key || location.hostname, - this.peerId, - "2.12.15" - )), - this.logger.setUploader(this.logUploader))), - t.onTrackerResume && t.onTrackerResume(e), - e.fuse_rate && (this.fuseRate = e.fuse_rate), - e.overload && - ((this.overloaded = !0), - this.logger.warn("server overloaded, degrade signaling")), - this.logger.info( - `announce request response ${JSON.stringify(e, null, 2)}` - ), - (function (e, t) { - function r(e, t, r, i, n) { - return h(t - -94, n); - } - var i = e(); - function n(e, t, r, i, n) { - return h(t - 586, r); - } - function s(e, t, r, i, n) { - return h(i - 742, n); - } - for (;;) - try { - if ( - 595581 === - -parseInt(r(0, -83, 0, 0, -88)) / 1 + - -parseInt(n(0, 587, 588)) / 2 + - (parseInt(n(0, 599, 592)) / 3) * - (-parseInt(n(0, 588, 591)) / 4) + - parseInt(r(0, -86, 0, 0, -83)) / 5 + - -parseInt(s(0, 0, 0, 751, 751)) / 6 + - -parseInt(s(0, 0, 0, 754, 760)) / 7 + - parseInt(h(403 - 397, 399)) / 8 - ) - break; - i.push(i.shift()); - } catch (e) { - i.push(i.shift()); - } - })(u), - e.v !== - Fe()( - i.channelId + - this.peerId + - i.timestamp + - ((d = 701), (c = 702), h(d - 696, c)), - "2.12.15" - ).substring(0, 8) && (this.maxConnsActive = 1); - }) - .catch((r) => { - if ( - this.scheduler && - ("TRACKER_EXPT" === r.code && t.emitEvent(e.EXCEPTION, r), - this.scheduler.notifyPeersLoaded(0), - r.retry) - ) { - const e = p(15e3, 4e4); - this.logger.warn(`announce retry after ${e}ms`), - (this.announceTimer = setTimeout(() => { - this.resumeP2P(); - }, e)); - } - }); - } - stopP2P() { - this.fetcher.postStatsWithBeacon(), - this.fetcher.destroy(), - (this.fetcher = null), - this.requestMorePeers(!0), - this.scheduler.destroy(), - (this.scheduler = null), - this.signalerWs && - (this.signalerWs.destroy(), (this.signalerWs = null)), - (this.peers = []); - for (let e of this.DCMap.values()) e.destroy(!0); - this.DCMap.clear(), - this.peerPool.destroy(), - (this.peerPool = null), - this.failedDCMap.clear(), - this.notFoundDCSet.clear(), - this.logUploader && - (this.logUploader.destroy(), (this.logUploader = null)), - this.logger.warn("tracker stop p2p"); - } - destroy() { - this.stopP2P(), - this.removeAllListeners(), - clearTimeout(this.announceTimer), - clearTimeout(this.requestPeersTimer); - const { config: e } = this; - (e.getStats = e.getPeerId = e.getPeersInfo = null), - this.logger.warn("destroy tracker"); - } - isPeerConnectedOrFailed(e) { - return ( - !e || - this.DCMap.has(e) || - this.failedDCMap.has(e) || - e === this.peerId - ); - } - _filterPeers(e) { - const t = []; - return ( - e - .filter((e) => !this.isPeerConnectedOrFailed(e.id)) - .forEach((e) => { - t.push({ id: e.id, intermediator: e.intermediator }); - }), - t - ); - } - _tryConnectToAllPeers() { - const { logger: e } = this; - if (0 !== this.peers.length) - for ( - this._checkDCMap(), - e.info( - `try connect to ${this.peers.length} peers, map size ${this.DCMap.size} limit ${this.maxConnsActive} peersNum ${this.scheduler.peersNum}` - ); - this.peers.length > 0 && - !(this.DCMap.size >= this.maxConnsActive); - - ) { - let t = this.peers.shift(); - if (this.isPeerConnectedOrFailed(t.id)) continue; - const r = t.intermediator; - this.signalerWs.connected || (r && this.DCMap.has(r)) - ? (e.debug(`create DataChannel ${t.id} intermediator ${r}`), - this._createDatachannel(t.id, !0, r)) - : e.info(`skip peer ${t.id} without intermediator`); - } - else e.info("no peers after filter"); - } - _handleSendSignal(e, t) { - const r = e.remotePeerId; - if (e.intermediator) { - const i = this.DCMap.get(e.intermediator); - if (i) { - let n = !0; - for (let e of t) i.sendMsgSignal(r, this.peerId, e) || (n = !1); - if (n) return; - this.logger.warn( - `intermediator ${e.intermediator} relay failed` - ); - } - } - (e.intermediator = void 0), - this.signalerWs.sendSignalBatch(r, t, e.signalName); - } - _setupDC(t) { - t.on(e.DC_SIGNAL, (e) => { - this._handleSendSignal(t, [e]); - }) - .on(e.DC_SIGNAL_BATCH, (e) => { - this._handleSendSignal(t, e); - }) - .on(e.DC_PEER_SIGNAL, (e) => { - const r = e.to_peer_id || e.to, - i = e.from_peer_id || e.from, - n = e.action; - if (r && i && n) - if (r !== this.peerId) { - this.logger.info(`relay signal for ${i}`); - const s = this.DCMap.get(r); - if (s) { - if ("signal" !== n) - return void s.sendMsgSignalReject( - r, - i, - e.reason, - e.fatal - ); - if (s.sendMsgSignal(r, i, e.data)) return; - } - t.sendMsgSignal(i, r); - } else - "signal" === n - ? this._handleSignalMsg(i, e, t.remotePeerId) - : this._handSignalRejected(i, e); - }) - .on(e.DC_GET_PEERS, () => { - const e = g(), - r = this.scheduler - .getPeers() - .filter( - (e) => - e.peersConnected < (e.mobileWeb ? 15 : 22) && !e.super - ); - if (r && r.length > 0) { - const i = []; - r.forEach((r) => { - if ( - r.remotePeerId === t.remotePeerId || - r.remotePeerId === this.peerId - ) - return; - if ( - !this.config.live && - (r.currentPos - t.currentPos > 600 || - r.currentPos < t.currentPos) - ) - return; - e - r.timeJoin > 50 && - i.push({ id: r.remotePeerId, ...r.region }); - }), - this.logger.info( - `send ${i.length} peers to ${t.remotePeerId}` - ), - t.sendPeers(i); - } - }) - .on(e.DC_PEERS, (e) => { - const r = e.peers; - this.logger.info( - `receive ${r.length} peers from ${t.remotePeerId}` - ), - r && - r.length > 0 && - (r.forEach((e) => { - (e.intermediator = t.remotePeerId), - e.region || (e.region = {}); - }), - this.requestPeersQueue.push(...r)), - this.requestPeersWaitCount--, - this.requestPeersWaitCount <= 0 && - this._handleRequestedPeers(); - }) - .once(e.DC_ERROR, (e, r) => { - this.logger.warn( - `datachannel ${t.channelId} failed fatal ${e} ${r}` - ), - this.scheduler && - (this.scheduler.deletePeer(t), - this._destroyAndDeletePeer(t.remotePeerId, e), - this.fetcher && - (t.connected || (e && this.fetcher.increFailConns()), - e && - this.failedDCMap.set(t.remotePeerId, `DC_FAILED ${r}`), - this._doSignalFusing(this.scheduler.peersNum), - this._doPeersRequest())); - }) - .once( - e.DC_TIMEOUT, - ({ gotSignal: e, sentSignal: r, data: i }) => { - const { logger: n, signalerWs: s, gotSignalFails: a } = this, - { remotePeerId: o, useBackupSignal: l, isInitiator: h } = t, - u = l ? "backup" : "main"; - if ( - (e - ? (a[u] = 0) - : (a[u]++, - a[u] >= a.limit && - ((a[u] = 0), - n.warn("gotSignalFails many, forcePolling"), - s.forcePolling(u))), - r && - e && - h && - (this.failedDCMap.set(o, "DC_TIMEOUT"), - this.fetcher && this.fetcher.increFailConns()), - !e && h && !l && this._tryBackupSignal(t, o, i)) - ) - return ( - t._startTimer(), - void n.warn(`${o} conn timeout, try backup signal`) - ); - this._destroyAndDeletePeer(o, !1), this._doPeersRequest(); - } - ) - .once(e.DC_CLOSE, (e) => { - this.logger.info( - `datachannel ${t.channelId} closed fatal ${e}` - ), - this.scheduler && - (this.scheduler.deletePeer(t), - this._doSignalFusing(this.scheduler.peersNum)), - this._destroyAndDeletePeer(t.remotePeerId, e), - e && this.failedDCMap.set(t.remotePeerId, "DC_CLOSE"), - this._doPeersRequest(); - }) - .once(e.DC_OPEN, () => { - t.isInitiator && this.scheduler.handshakePeer(t); - }) - .once(e.DC_METADATA, (e) => { - const { scheduler: r } = this; - t.isInitiator || r.handshakePeer(t), r.handleMetaData(t, e); - const i = this.DCMap.size >= this.maxConnsActive; - this.requestMorePeers(i), - t.intermediator && this.peersIncrement++, - this._doSignalFusing(r.peersNum); - }); - } - _doPeersRequest() { - const e = this.scheduler.peersNum; - !this.signalerWs.connected || (this.overloaded && e > this.minConns) - ? this._requestPeersFromPeers(e) - : this.requestMorePeers(), - this._tryConnectToAllPeers(); - } - _doSignalFusing(e) { - if (this.fuseRate <= 0) return; - const t = this.signalerWs.connected; - t && e >= this.fuseRate - ? (this.logger.warn( - "reach fuseRate, report stats close signaler" - ), - this.totalConns - 1 > 0 && this.fetcher.postStats(), - this.signalerWs.close()) - : !t && - e <= this.minConns && - this.signalerWs.normalClosed && - (this.logger.warn(`low conns ${e}, reconnect signaler`), - this.signalerWs.reconnect()); - } - _initSignalerWs(t, r, i, n) { - const s = (e, t) => { - let r = `${e}?id=${this.peerId}&p=web&v=2.12.15`; - return ( - this.config.signalCompact && (r = `${r}&c=1`), - t && (r = `${r}&token=${t}`), - r - ); - }; - let a, - o = s(t, i); - if (r && r !== t) { - let e = s(r, n); - a = new dt(this.logger, this.config, o, e); - } else a = new ut(this.logger, this.config, o); - return ( - (a.onopen = () => { - (this.connected = !0), - this.engine.emitEvent("serverConnected", !0), - this._tryConnectToAllPeers(); - }), - (a.onmessage = (e, t) => { - let r = e.action; - const i = e.from_peer_id || e.from; - if (i) - switch (r) { - case "signal": - this._handleSignalMsg(i, e, null, t); - break; - case "reject": - this._handSignalRejected(i, e); - break; - default: - this.logger.warn(`Signal websocket unknown action ${r}`); - } - else this.logger.warn("fromPeerId is missed"); - }), - (a.onclose = () => { - (this.connected = !1), - this.engine.emitEvent("serverConnected", !1); - }), - (a.onerror = (t) => { - t.message && this.logger.warn(`signal err: ${t.message}`), - t.message && - this.engine.emitEvent(e.EXCEPTION, Be(t, "SIGNAL_EXPT")); - }), - a - ); - } - _handSignalRejected(e, t) { - const r = `signaling ${e} rejected`; - this.logger.warn(`${r}, reason ${t.reason}`); - const i = this.DCMap.get(e); - i && !i.connected && (i.destroy(t.fatal), this.DCMap.delete(e)), - this.requestMorePeers(), - t.fatal && this.failedDCMap.set(e, r), - this._tryConnectToAllPeers(); - } - _tryBackupSignal(e, t, r, i = "main") { - return ( - !( - !( - this.signalerWs.backupConnected && - e && - r.length > 0 && - "main" === i - ) || e.useBackupSignal - ) && - ((e.useBackupSignal = !0), - (e.signalName = "backup"), - (e.intermediator = void 0), - this.signalerWs.sendSignalBatch(t, r, "backup"), - !0) - ); - } - _handleSignalMsg(e, t, r, i) { - if (!this.scheduler) return; - const { logger: n } = this; - if (t.data) { - if (this.failedDCMap.has(e)) - return void this._sendSignalReject( - e, - `${e} ${this.failedDCMap.get(e) || "unknown"}`, - r, - i, - !0 - ); - this._handleSignal(e, t.data, r, i); - } else { - const t = this.DCMap.get(e); - if (!t) return; - if (this._tryBackupSignal(t, e, t.signalMsgs, i)) - return void this.logger.warn( - `${e} not found from main, try backup signal` - ); - if (t.useBackupSignal) return; - this._destroyAndDeletePeer(e), n.info(`signaling ${e} not found`); - const { scheduler: s } = this; - s.waitForPeer && - (s.waitingPeers--, - 0 === s.waitingPeers && s.notifyPeersLoaded(0)), - this.requestMorePeers(), - this._tryConnectToAllPeers(), - r || this.notFoundDCSet.add(e); - } - } - _handleSignal(e, t, r, i) { - "string" == typeof t && - (t = ((e) => { - if ("C" === e[0]) - return { - type: "candidate", - candidate: { - candidate: wt(e), - sdpMLineIndex: 0, - sdpMid: "0", - }, - }; - const t = e.slice(1), - r = "O" === e[0]; - return { type: r ? "offer" : "answer", sdp: Pt(t, r) }; - })(t)); - const n = t.type, - { logger: s } = this; - let a = this.DCMap.get(e); - if (a) { - if (a.connected) - return void s.info("datachannel had connected, signal ignored"); - if ("offer" === n && a.isInitiator) { - if (!(this.peerId > e)) - return void s.warn(`${e} signal type wrong ${n}, ignored`); - s.warn(`${e} signal type wrong ${n}, convert to non initiator`), - this._destroyAndDeletePeer(e, !1), - (a = this._createDatachannel(e, !1, r)); - } - } else { - if ("answer" === n) { - const t = `${e} type wrong ${n}`; - return ( - s.warn(t), - this._sendSignalReject(e, t, r, i), - void this._destroyAndDeletePeer(e, !1) - ); - } - if ( - (s.debug(`receive node ${e} connection request`), - this.DCMap.size >= this.maxConns) - ) { - const t = `reach limit ${this.maxConns}`; - return s.warn(t), void this._sendSignalReject(e, t, r, i); - } - a = this._createDatachannel(e, !1, r); - } - a && (i && (a.signalName = i), a.receiveSignal(t)); - } - _createDatachannel(e, t, r) { - if (!this.fetcher) return; - let i; - if (t && this.peerPool.available) - (i = this.peerPool.getPeer()), - this.logger.info( - `get peer from pool, signal size ${i.signalMsgs.length}` - ), - (i.intermediator = r), - i.assignPeerId(this.peerId, e); - else { - let n = this.config.trickleICE; - this.overloaded && (n = !1), - (i = new Z(this.engine, this.peerId, e, t, this.config, { - stuns: this.stuns, - intermediator: r, - trickle: !r && n, - })); - } - return this.DCMap.set(e, i), this._setupDC(i), i; - } - _sendSignalReject(e, t, r, i, n) { - if (r) { - const i = this.DCMap.get(r); - if (i && i.sendMsgSignalReject(e, this.peerId, t, n)) return; - } - this.signalerWs.sendReject(e, t, n, i); - } - _requestMorePeers(e) { - if (!this.fetcher) return; - const { logger: t } = this, - r = this.scheduler.peersNum; - r >= this.maxConnsActive || - (t.info( - `requestMorePeers after delay ${e}, peersIncrement ${this.peersIncrement}` - ), - r < 3 || - (r < this.minConns && - this.peersIncrement <= 3 && - !this.gotPeersFromTracker) - ? this._requestPeersFromServer(r) - : this._requestPeersFromPeers(r) || - this._requestPeersFromServer(r), - (this.peersIncrement = 0)); - } - _requestPeersFromServer(e) { - const { logger: t } = this; - this.failedDCMap.size > 50 && - (this.failedDCMap = new Map([...this.failedDCMap].slice(-50))), - this.notFoundDCSet.size > 20 && - (this.notFoundDCSet = new Set( - [...this.notFoundDCSet].slice(-20) - )), - this.fetcher - .btGetPeers( - [ - ...this.DCMap.keys(), - ...this.failedDCMap.keys(), - ...this.notFoundDCSet.keys(), - ], - 0 === e - ) - .then((e) => { - e && - e.peers && - (t.info( - `requestMorePeers resp ${JSON.stringify(e, null, 2)}` - ), - (this.peers = this._filterPeers(e.peers)), - this._tryConnectToAllPeers()); - }) - .catch((e) => { - t.error(`requestMorePeers error ${e}`); - }), - (this.gotPeersFromTracker = !0); - } - _requestPeersFromPeers(e) { - return ( - !!this.requestPeersTimer || - e >= this.maxConnsActive || - ((this.requestPeersWaitCount = this.scheduler.requestPeers()), - 0 !== this.requestPeersWaitCount && - ((this.gotPeersFromTracker = !1), - (this.requestPeersTimer = setTimeout(() => { - this.logger.warn("requestPeersTimer timeout"), - this._handleRequestedPeers(); - }, 1e4)), - !0)) - ); - } - _handleRequestedPeers() { - if ( - (clearTimeout(this.requestPeersTimer), - (this.requestPeersTimer = void 0), - this.fetcher) - ) { - if (this.requestPeersQueue.length > 0) { - const e = (function (e, t) { - const r = [], - i = new Set(); - for (let t of e) i.has(t.id) || (i.add(t.id), r.push(t)); - const { asn: n, country: s } = t; - if (!n || !s || r.length < 2) return r; - const a = r.filter((e) => !e.asn && !e.country), - o = r.filter((e) => e.country === s && e.asn !== n), - l = r.filter((e) => e.asn === n && e.country === s), - h = r.filter( - (e) => !a.includes(e) && !l.includes(e) && !o.includes(e) - ); - return l.concat(o).concat(a).concat(h); - })(this.requestPeersQueue, this.fetcher.announceInfo); - (this.peers = this._filterPeers(e)), - (this.requestPeersQueue = []); - } - this._tryConnectToAllPeers(); - } - } - _destroyAndDeletePeer(e, t = !0) { - const r = this.DCMap.get(e); - return !!r && (r.destroy(t), this.DCMap.delete(e), !0); - } - _checkDCMap() { - const e = g(); - for (let t of this.DCMap.values()) { - const r = e - t.timeJoin; - e - t.timeJoin > 30 && - !t.connected && - (this.logger.warn( - `delete ${t.remotePeerId} not connected for ${r} in DCMap` - ), - this._destroyAndDeletePeer(t.remotePeerId, !1)); - } - } - } - const kt = Ct; - class Dt extends ue { - constructor(e = {}, t = null) { - if ( - (super(e), - e.validateSegment || - (e.validateSegment = function (e, t) { - return !0; - }), - (this.hlsjs = t), - (this.config = Object.assign({ useDiskCache: !e.live }, Ee, e)), - t) - ) { - this.HLSEvents = t.constructor.Events; - const e = t.constructor.version; - (this.hlsjsVersion = e), - (this.config.isHlsV0 = e && "0" === e.split(".")[0]); - } - (this.lastLevel = 0), (this.multiBitrate = !1); - } - setup() { - let { token: e, channelId: t } = this.config, - r = (e) => { - const t = l().parseURL(e); - return `${ - t.netLoc.substring(2) + - t.path.substring(0, t.path.lastIndexOf(".")) - }`; - }; - t && (r = this.makeChannelId(e, t)); - return { - channelIdMaker: r, - signalId: this.makeSignalId(), - browserInfo: { ...this.commonBrowserInfo }, - }; - } - setupElectron() { - this.browserInfo.device === X.device.PC_NATIVE && - (this.browserInfo = { - ...this.browserInfo, - app: this.config.appName, - bundle: this.config.appId, - }); - } - getExtraForStats() { - const e = super.getExtraForStats(); - return ( - !this.config.live && - this.media && - (e.pos = Math.round(this.media.currentTime)), - this.multiBitrate && - this.currentLevel !== this.lastLevel && - ((e.level = this.currentLevel + ""), - (this.lastLevel = this.currentLevel)), - e - ); - } - getExtraForPeersRequest() { - const e = super.getExtraForPeersRequest(); - return this.multiBitrate && (e.level = this.currentLevel + ""), e; - } - destroy() { - super.destroy(); - } - async initSegmentManager(e) { - const { logger: r, config: i } = this; - if (self.indexedDB && i.useDiskCache && !i.live) { - const e = new ke(this, i); - try { - await e.setupStore(), (this.bufMgr = e); - } catch (e) { - r.warn(e), (this.bufMgr = new xe(this, i)); - } - } else this.bufMgr = new xe(this, i); - if (this.bufMgr.maxBufSize <= 0) - throw new Error("bufMgr state is invalid"); - "SegmentStore" === this.bufMgr.name && - (this.removeAllListeners(t.BM_FATAL_ERROR), - this.once(t.BM_FATAL_ERROR, () => { - const t = "SegmentStoreFatalError"; - r.warn(`${t}, switch to SegmentCache`), - this.bufMgr.destroy(), - (this.bufMgr = new xe(this, i)), - e && e(this.bufMgr), - r.report( - JSON.stringify(this.browserInfo), - t, - this.peerId, - "2.12.15", - 5e4 - ); - })); - } - generateTag() { - let e = (0, X.getBrowser)(); - return ( - e.includes("iPhone") && - "HlsSwP2pEngine" === this.engineName && - (e = `${e}_p`), - this.playerName && (e = `${e}_${this.playerName}`), - e - ); - } - onTrackerResume(e) { - e.report_url && this.logger.enableReport(e.report_url); - } - async _init(e, t, r) { - const { logger: i, config: n } = this; - await this.initSegmentManager((e) => { - if (this.tracker) { - const { scheduler: t } = this.tracker; - (t.bufferManager = e), t.bitset.clear(); - } - }), - r.live || - (this.media && (r.pos = Math.round(this.media.currentTime))), - (r.tag = void 0 === n.tag ? this.generateTag() : n.tag); - let s = new st( - this, - n.token, - encodeURIComponent(e), - n.announce || "", - r - ); - (this.fetcher = s), - (this.tracker = new kt(this, s, t, n)), - (t.bufferManager = this.bufMgr), - this.setupWindowListeners(); - } - _setupSegmentId() { - this.config.segmentId || - (this.config.segmentId = this.config.strictSegmentId ? me : pe); - } - _onHlsError(e, r) { - if (!r || !this.hlsjs) return; - const { logger: i, tracker: n } = this; - if (!i) return; - const s = `${r.type} details ${r.details} reason ${r.reason}`; - if ( - (r.fatal ? i.error(s) : i.warn(s), - "networkError" === r.type && "HlsjsP2pEngine" === this.engineName) - ) - return; - const { player: a } = this.browserInfo, - o = `${a || ""} hlsjs ${this.hlsjsVersion} ${location.href}`, - l = this.hlsjs.constructor.ErrorDetails; - switch (r.details) { - case l.BUFFER_STALLED_ERROR: - "HlsjsP2pEngine" === this.engineName && - this.fetcher && - this.fetcher.increRebuffers(), - n && - n.scheduler && - i.warn( - "buffered: " + 1e3 * n.scheduler.getBufferedDuration() - ); - break; - case l.INTERNAL_EXCEPTION: - if (r.event && "demuxerWorker" !== r.event) { - r.error || (r.error = {}); - const e = `${r.error.message} event ${r.event} ${o}`; - this.fetcher && - r.fatal && - (this.fetcher.errsInternalExpt++, - (this.fetcher.exptMsg = e)), - i.error( - `INTERNAL_EXCEPTION event ${r.event} err ${r.error.message}` - ), - this.emitEvent(t.EXCEPTION, Be(r.error, "HLSJS_EXPT")), - i.report(e, r.event, this.peerId, "2.12.15"); - } - break; - default: - if (r.fatal || r.details === l.FRAG_PARSING_ERROR) { - const e = `${r.type} ${r.details} ${r.err || ""} ${o}`; - i.report(e, r.details, this.peerId, "2.12.15"), - "mediaError" === r.type && - this.tracker && - this.tracker.scheduler && - this.tracker.scheduler.clearCache(); - } - } - } - } - class Mt { - constructor() { - (this.method = null), - (this.key = null), - (this.iv = null), - (this._uri = null); - } - get uri() { - return ( - !this._uri && - this.reluri && - (this._uri = o.buildAbsoluteURL(this.baseuri, this.reluri, { - alwaysNormalize: !0, - })), - this._uri - ); - } - } - class xt { - constructor() { - (this._url = null), - (this._byteRange = null), - (this._decryptdata = null), - (this.tagList = []), - (this.programDateTime = null), - (this.rawProgramDateTime = null), - (this._elementaryStreams = { - [xt.ElementaryStreamTypes.AUDIO]: !1, - [xt.ElementaryStreamTypes.VIDEO]: !1, - }); - } - static get ElementaryStreamTypes() { - return { AUDIO: "audio", VIDEO: "video" }; - } - get url() { - return ( - !this._url && - this.relurl && - (this._url = o.buildAbsoluteURL(this.baseurl, this.relurl, { - alwaysNormalize: !0, - })), - this._url - ); - } - set url(e) { - this._url = e; - } - get byteRange() { - if (!this._byteRange && !this.rawByteRange) return []; - if (this._byteRange) return this._byteRange; - let e = []; - if (this.rawByteRange) { - const t = this.rawByteRange.split("@", 2); - if (1 === t.length) { - const t = this.lastByteRangeEndOffset; - e[0] = t || 0; - } else e[0] = parseInt(t[1]); - (e[1] = parseInt(t[0]) + e[0]), (this._byteRange = e); - } - return e; - } - get byteRangeStartOffset() { - return this.byteRange[0]; - } - get byteRangeEndOffset() { - return this.byteRange[1]; - } - get decryptdata() { - return ( - this._decryptdata || - (this._decryptdata = this.fragmentDecryptdataFromLevelkey( - this.levelkey, - this.sn - )), - this._decryptdata - ); - } - get endProgramDateTime() { - if (!Number.isFinite(this.programDateTime)) return null; - let e = Number.isFinite(this.duration) ? this.duration : 0; - return this.programDateTime + 1e3 * e; - } - get encrypted() { - return !( - !this.decryptdata || - null === this.decryptdata.uri || - null !== this.decryptdata.key - ); - } - addElementaryStream(e) { - this._elementaryStreams[e] = !0; - } - hasElementaryStream(e) { - return !0 === this._elementaryStreams[e]; - } - createInitializationVector(e) { - let t = new Uint8Array(16); - for (let r = 12; r < 16; r++) t[r] = (e >> (8 * (15 - r))) & 255; - return t; - } - fragmentDecryptdataFromLevelkey(e, t) { - let r = e; - return ( - e && - e.method && - e.uri && - !e.iv && - ((r = new Mt()), - (r.method = e.method), - (r.baseuri = e.baseuri), - (r.reluri = e.reluri), - (r.iv = this.createInitializationVector(t))), - r - ); - } - } - class Ot { - constructor(e) { - (this.endCC = 0), - (this.endSN = 0), - (this.fragments = []), - (this.initSegment = null), - (this.live = !0), - (this.needSidxRanges = !1), - (this.startCC = 0), - (this.startSN = 0), - (this.startTimeOffset = null), - (this.targetduration = 0), - (this.totalduration = 0), - (this.type = null), - (this.url = e), - (this.version = null); - } - get hasProgramDateTime() { - return !( - !this.fragments[0] || - !Number.isFinite(this.fragments[0].programDateTime) - ); - } - } - const Ft = /^(\d+)x(\d+)$/, - Nt = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; - class Bt { - constructor(e) { - "string" == typeof e && (e = Bt.parseAttrList(e)); - for (let t in e) e.hasOwnProperty(t) && (this[t] = e[t]); - } - decimalInteger(e) { - const t = parseInt(this[e], 10); - return t > Number.MAX_SAFE_INTEGER ? 1 / 0 : t; - } - hexadecimalInteger(e) { - if (this[e]) { - let t = (this[e] || "0x").slice(2); - t = (1 & t.length ? "0" : "") + t; - const r = new Uint8Array(t.length / 2); - for (let e = 0; e < t.length / 2; e++) - r[e] = parseInt(t.slice(2 * e, 2 * e + 2), 16); - return r; - } - return null; - } - hexadecimalIntegerAsNumber(e) { - const t = parseInt(this[e], 16); - return t > Number.MAX_SAFE_INTEGER ? 1 / 0 : t; - } - decimalFloatingPoint(e) { - return parseFloat(this[e]); - } - enumeratedString(e) { - return this[e]; - } - decimalResolution(e) { - const t = Ft.exec(this[e]); - if (null !== t) - return { width: parseInt(t[1], 10), height: parseInt(t[2], 10) }; - } - static parseAttrList(e) { - let t, - r = {}; - for (Nt.lastIndex = 0; null !== (t = Nt.exec(e)); ) { - let e = t[2], - i = '"'; - 0 === e.indexOf(i) && - e.lastIndexOf(i) === e.length - 1 && - (e = e.slice(1, -1)), - (r[t[1]] = e); - } - return r; - } - } - const Ut = Bt, - Gt = { - audio: { - a3ds: !0, - "ac-3": !0, - "ac-4": !0, - alac: !0, - alaw: !0, - dra1: !0, - "dts+": !0, - "dts-": !0, - dtsc: !0, - dtse: !0, - dtsh: !0, - "ec-3": !0, - enca: !0, - g719: !0, - g726: !0, - m4ae: !0, - mha1: !0, - mha2: !0, - mhm1: !0, - mhm2: !0, - mlpa: !0, - mp4a: !0, - "raw ": !0, - Opus: !0, - samr: !0, - sawb: !0, - sawp: !0, - sevc: !0, - sqcp: !0, - ssmv: !0, - twos: !0, - ulaw: !0, - }, - video: { - avc1: !0, - avc2: !0, - avc3: !0, - avc4: !0, - avcp: !0, - drac: !0, - dvav: !0, - dvhe: !0, - encv: !0, - hev1: !0, - hvc1: !0, - mjp2: !0, - mp4v: !0, - mvc1: !0, - mvc2: !0, - mvc3: !0, - mvc4: !0, - resv: !0, - rv60: !0, - s263: !0, - svc1: !0, - svc2: !0, - "vc-1": !0, - vp08: !0, - vp09: !0, - }, - }; - const Ht = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g, - $t = /#EXT-X-MEDIA:(.*)/g, - Kt = new RegExp( - [ - /#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, - /|(?!#)([\S+ ?]+)/.source, - /|#EXT-X-BYTERANGE:*(.+)/.source, - /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, - /|#.*/.source, - ].join(""), - "g" - ), - Wt = - /(?:(?:#(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):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/, - Vt = /\.(mp4|m4s|m4v|m4a)$/i; - class qt { - static findGroup(e, t) { - if (!e) return null; - let r = null; - for (let i = 0; i < e.length; i++) { - const n = e[i]; - n.id === t && (r = n); - } - return r; - } - static convertAVC1ToAVCOTI(e) { - let t, - r = e.split("."); - return ( - r.length > 2 - ? ((t = r.shift() + "."), - (t += parseInt(r.shift()).toString(16)), - (t += ("000" + parseInt(r.shift()).toString(16)).substr(-4))) - : (t = e), - t - ); - } - static resolve(e, t) { - return o.buildAbsoluteURL(t, e, { alwaysNormalize: !0 }); - } - static parseMasterPlaylist(e, t) { - let r, - i = []; - function n(e, t) { - ["video", "audio"].forEach((r) => { - const i = e.filter((e) => - (function (e, t) { - const r = Gt[t]; - return !!r && !0 === r[e.slice(0, 4)]; - })(e, r) - ); - if (i.length) { - const n = i.filter( - (e) => - 0 === e.lastIndexOf("avc1", 0) || - 0 === e.lastIndexOf("mp4a", 0) - ); - (t[`${r}Codec`] = n.length > 0 ? n[0] : i[0]), - (e = e.filter((e) => -1 === i.indexOf(e))); - } - }), - (t.unknownCodecs = e); - } - for (Ht.lastIndex = 0; null != (r = Ht.exec(e)); ) { - const e = {}, - s = (e.attrs = new Ut(r[1])); - e.url = qt.resolve(r[2], t); - const a = s.decimalResolution("RESOLUTION"); - a && ((e.width = a.width), (e.height = a.height)), - (e.bitrate = - s.decimalInteger("AVERAGE-BANDWIDTH") || - s.decimalInteger("BANDWIDTH")), - (e.name = s.NAME), - n([].concat((s.CODECS || "").split(/[ ,]+/)), e), - e.videoCodec && - -1 !== e.videoCodec.indexOf("avc1") && - (e.videoCodec = qt.convertAVC1ToAVCOTI(e.videoCodec)), - i.push(e); - } - return i; - } - static parseMasterPlaylistMedia(e, t, r, i = []) { - let n, - s = [], - a = 0; - for ($t.lastIndex = 0; null !== (n = $t.exec(e)); ) { - const e = {}, - o = new Ut(n[1]); - if (o.TYPE === r) { - if ( - ((e.groupId = o["GROUP-ID"]), - (e.name = o.NAME), - (e.type = r), - (e.default = "YES" === o.DEFAULT), - (e.autoselect = "YES" === o.AUTOSELECT), - (e.forced = "YES" === o.FORCED), - o.URI && (e.url = qt.resolve(o.URI, t)), - (e.lang = o.LANGUAGE), - e.name || (e.name = e.lang), - i.length) - ) { - const t = qt.findGroup(i, e.groupId); - e.audioCodec = t ? t.codec : i[0].codec; - } - (e.id = a++), s.push(e); - } - } - return s; - } - static parseLevelPlaylist(e, t) { - let r, - i, - n = 0, - s = 0, - a = new Ot(t), - o = new Mt(), - l = 0, - h = null, - u = new xt(), - d = null; - for (Kt.lastIndex = 0; null !== (r = Kt.exec(e)); ) { - const e = r[1]; - if (e) { - u.duration = parseFloat(e); - const t = (" " + r[2]).slice(1); - (u.title = t || null), - u.tagList.push(t ? ["INF", e, t] : ["INF", e]); - } else if (r[3]) { - if (Number.isFinite(u.duration)) { - const e = n++; - (u.start = s), - (u.levelkey = o), - (u.sn = e), - (u.cc = l), - (u.baseurl = t), - (u.relurl = (" " + r[3]).slice(1)), - jt(u, h), - a.fragments.push(u), - (h = u), - (s += u.duration), - (u = new xt()); - } - } else if (r[4]) { - if (((u.rawByteRange = (" " + r[4]).slice(1)), h)) { - const e = h.byteRangeEndOffset; - e && (u.lastByteRangeEndOffset = e); - } - } else if (r[5]) - (u.rawProgramDateTime = (" " + r[5]).slice(1)), - u.tagList.push(["PROGRAM-DATE-TIME", u.rawProgramDateTime]), - null === d && (d = a.fragments.length); - else { - for ( - r = r[0].match(Wt), i = 1; - i < r.length && void 0 === r[i]; - i++ - ); - const e = (" " + r[i + 1]).slice(1), - s = (" " + r[i + 2]).slice(1); - switch (r[i]) { - case "#": - u.tagList.push(s ? [e, s] : [e]); - break; - case "PLAYLIST-TYPE": - a.type = e.toUpperCase(); - break; - case "MEDIA-SEQUENCE": - n = a.startSN = parseInt(e); - break; - case "TARGETDURATION": - a.targetduration = parseFloat(e); - break; - case "VERSION": - a.version = parseInt(e); - break; - case "EXTM3U": - break; - case "ENDLIST": - a.live = !1; - break; - case "DIS": - l++, u.tagList.push(["DIS"]); - break; - case "DISCONTINUITY-SEQ": - l = parseInt(e); - break; - case "KEY": - var c = new Ut(e), - f = c.enumeratedString("METHOD"), - g = c.URI, - p = c.hexadecimalInteger("IV"); - f && - ((o = new Mt()), - g && - ["AES-128", "SAMPLE-AES", "SAMPLE-AES-CENC"].indexOf( - f - ) >= 0 && - ((o.method = f), - (o.baseuri = t), - (o.reluri = g), - (o.key = null), - (o.iv = p))); - break; - case "START": - let i = new Ut(e).decimalFloatingPoint("TIME-OFFSET"); - Number.isFinite(i) && (a.startTimeOffset = i); - break; - case "MAP": - let h = new Ut(e); - (u.relurl = h.URI), - (u.rawByteRange = h.BYTERANGE), - (u.baseurl = t), - (u.sn = "initSegment"), - (a.initSegment = u), - (u = new xt()), - (u.rawProgramDateTime = a.initSegment.rawProgramDateTime); - break; - default: - console.warn(`line parsed but not handled: ${r}`); - } - } - } - return ( - (u = h), - u && !u.relurl && (a.fragments.pop(), (s -= u.duration)), - (a.totalduration = s), - (a.averagetargetduration = s / a.fragments.length), - (a.endSN = n - 1), - (a.startCC = a.fragments[0] ? a.fragments[0].cc : 0), - (a.endCC = l), - !a.initSegment && - a.fragments.length && - a.fragments.every((e) => Vt.test(e.relurl)) && - (console.warn( - "MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX" - ), - (u = new xt()), - (u.relurl = a.fragments[0].relurl), - (u.baseurl = t), - (u.level = id), - (u.sn = "initSegment"), - (a.initSegment = u), - (a.needSidxRanges = !0)), - d && - (function (e, t) { - let r = e[t]; - for (let i = t - 1; i >= 0; i--) { - const t = e[i]; - (t.programDateTime = r.programDateTime - 1e3 * t.duration), - (r = t); - } - })(a.fragments, d), - a - ); - } - } - function jt(e, t) { - e.rawProgramDateTime - ? (e.programDateTime = Date.parse(e.rawProgramDateTime)) - : t && - t.programDateTime && - (e.programDateTime = t.endProgramDateTime), - Number.isFinite(e.programDateTime) || - ((e.programDateTime = null), (e.rawProgramDateTime = null)); - } - const Yt = { - ANY: 0, - COMPLETE: 1, - PARTIAL_FORWARD: 2, - PARTIAL_REVERSE: 3, - }, - zt = (e, t, r, i, n = !1) => { - const [s, a, o] = Xt(e, t, r, i); - return n && s.length >= 1 - ? P(s[0]) - : s.length >= 2 - ? [s[0], s[1]] - : I(s, a, o); - }, - Xt = (e, t, r, i) => { - const n = [], - { COMPLETE: s, PARTIAL_FORWARD: a, PARTIAL_REVERSE: o } = Yt; - return ( - [s, a, o].forEach((s) => { - n.push(Qt(e, s, t, r, i)); - }), - n - ); - }, - Qt = (e, t, r, i, n) => - e.filter((e) => e.bitset.hasWithId(r, i, n, t)); - class Jt { - constructor(e = !1, t) { - (this.isLive = e), (this.levelMap = new Map()); - for (let e in t) { - const r = Number(e); - if (r < 0) continue; - const i = new Map(); - if (t[e]) - for (let r of t[e]) - i.set(r, { state: Yt.COMPLETE, segId: void 0 }); - this.levelMap.set(r, i); - } - } - totalLevels() { - return this.levelMap.size; - } - hasWithId(e, t, r, i = Yt.ANY) { - if (t < 0) return !1; - const n = this._createOrGetSet(t).get(e); - return ( - !!n && - (!r || !n.segId || n.segId === r) && - (i === Yt.ANY || n.state === i) - ); - } - has(e, t, r = Yt.ANY) { - return this.hasWithId(e, t, void 0, r); - } - hasCompleteOr(e, t, r = Yt.COMPLETE) { - const i = this._createOrGetSet(t).get(e); - return !!i && (i.state === Yt.COMPLETE || i.state === r); - } - getObj(e, t) { - let r = this._createOrGetSet(t).get(e); - return r || (r = {}), r; - } - getSegId(e, t) { - return this.getObj(e, t).segId; - } - getState(e, t) { - return this.getObj(e, t).state; - } - delete(e, t) { - return this._createOrGetSet(t).delete(e); - } - add(e, t, r, i) { - if ("number" != typeof (n = e) || n % 1 != 0) return; - var n; - this._createOrGetSet(t).set(e, { state: i, segId: r }), - this.isLive && this._trimBitset(e); - } - array(e) { - const t = this._createOrGetSet(e); - return this._keysForStateComplete(t); - } - allArray() { - let e = {}; - return ( - this.levelMap.forEach((t, r) => { - e[r] = this._keysForStateComplete(t); - }), - e - ); - } - clear() { - this.levelMap.forEach((e) => { - e.clear(); - }); - } - size(e) { - return this._createOrGetSet(e).size; - } - _createOrGetSet(e) { - "number" != typeof e && (e = Number(e)); - let t = this.levelMap.get(e); - return t || ((t = new Map()), this.levelMap.set(e, t)), t; - } - _trimBitset(e) { - const t = e - 20; - t > 0 && - this.levelMap.forEach((e) => { - e.delete(t); - }); - } - _keysForStateComplete(e) { - const t = []; - for (let [r, i] of e) i.state === Yt.COMPLETE && t.push(r); - return t; - } - } - class Zt { - constructor() { - this.levelMap = new Map(); - } - totalLevels() { - return this.levelMap.size; - } - has(e, t) { - return this._createOrGetMap(t).has(e); - } - delete(e, t) { - return this._createOrGetMap(t).delete(e); - } - decre(e, t) { - const r = this._createOrGetMap(t); - if (r.has(e)) { - let t = r.get(e); - 1 === t ? r.delete(e) : r.set(e, t - 1); - } - } - incre(e, t) { - const r = this._createOrGetMap(t); - if (r.has(e)) { - let t = r.get(e); - r.set(e, t + 1); - } else r.set(e, 1); - } - clear() { - this.levelMap.forEach((e) => { - e.clear(); - }); - } - size(e) { - return this._createOrGetMap(e).size; - } - _createOrGetMap(e) { - "number" != typeof e && (e = Number(e)); - let t = this.levelMap.get(e); - return t || ((t = new Map()), this.levelMap.set(e, t)), t; - } - } - const er = class { - constructor() { - this.peerMap = new Map(); - } - isEmpty() { - return 0 === this.peerMap.size; - } - size() { - return this.peerMap.size; - } - clear() { - this.peerMap.clear(); - } - getPeers() { - return [...this.peerMap.values()]; - } - getPeerValues() { - return this.peerMap.values(); - } - hasPeer(e) { - return this.peerMap.has(e); - } - addPeer(e, t) { - this.peerMap.set(e, t); - } - getPeerIds() { - return [...this.peerMap.keys()]; - } - removePeer(e) { - this.peerMap.delete(e); - } - getPeersOrderByWeight() { - const e = this.getAvailablePeers(); - return ( - e.sort((e, t) => - 0 === t.weight ? 1 : 0 === e.weight ? -1 : t.weight - e.weight - ), - e - ); - } - getPeer(e) { - return this.peerMap.get(e); - } - getAvailablePeers() { - return this.getPeers().filter((e) => e.isAvailableUrgently); - } - }, - tr = Symbol("shareOnly"); - class rr extends s() { - constructor(e, t) { - super(), - (this.engine = e), - (this.config = t), - (this.logger = e.logger), - (this.bufMgr = null), - (this.peerManager = new er()), - (this.fragLoading = !1), - this._setupEngine && this._setupEngine(), - this.startCheckConnsTimer(), - (this.dcDownloadTimeout = t.dcDownloadTimeout), - (this[tr] = !1), - (this.downloadOnly = !1), - (this.loadedPeerNum = 0), - (this.minConns = 5); - } - get isMobileNet() { - return this.engine.isMobileNet; - } - startCheckConnsTimer() { - this.checkConnsTimer = setInterval(() => { - this.logger.info("start check conns"); - const e = this.getStatsForPeer(); - let t = this.peersNum; - const r = g(); - this.getPeers().forEach((i) => { - t > this.minConns + 1 && - (r - i.dataExchangeTs > 120 || r - i.gotStatsTs >= 83) - ? (this.logger.warn( - `close dead peer ${i.remotePeerId} level ${i.currentLevel}` - ), - i.close(!1), - t--) - : i.connected && i.sendMsgStats(t, e); - }); - }, 4e4); - } - get httpRangeSupported() { - return this.config.httpRangeSupported; - } - getStatsForPeer() { - return {}; - } - _handlePieceAborted() {} - requestPeers() { - const e = g(); - let t = 0; - for (let r of this.getPeers()) - r.mobileNet || - r.super || - (e - r.gotPeersTS < 60 - ? this.logger.warn( - `${r.remotePeerId} just got peers, ignored` - ) - : (r.sendPeersRequest(), (r.gotPeersTS = e), t++)); - return t; - } - chokePeerRequest(t) { - const r = { event: e.DC_CHOKE }; - t ? t.sendJson(r) : this._broadcastToPeers(r); - } - unchokePeerRequest(t) { - const r = { event: e.DC_UNCHOKE }; - t ? t.sendJson(r) : this._broadcastToPeers(r); - } - stopRequestFromPeers() { - for (let e of this.getPeers()) e.choked = !0; - } - resumeRequestFromPeers() { - for (let e of this.getPeers()) e.choked = !1; - } - setShareOnly() { - this[tr] = !0; - } - deletePeer(e) { - e.downloading && this._handlePieceAborted(e.remotePeerId), - this.peerManager.hasPeer(e.remotePeerId) && - this.peerManager.removePeer(e.remotePeerId), - this._peersStats(this.peerManager.getPeerIds()); - } - getPeers() { - return [...this.peerManager.getPeerValues()]; - } - addPeer(e) { - const { logger: t } = this; - this.peerManager.addPeer(e.remotePeerId, e), - this[tr] && (e.choked = !0); - const r = this.peerManager.getPeerIds(); - this._peersStats(r); - const { asn: i, country: n } = e.region || {}; - t.info( - `add peer ${e.remotePeerId} country ${n || ""} asn ${ - i || "" - }, now has ${r.length} peers` - ); - } - hasPeer(e) { - return this.peerManager.hasPeer(e); - } - get hasPeers() { - return this.peersNum > 0; - } - get peersNum() { - return this.peerManager.size(); - } - get hasIdlePeers() { - const { logger: e } = this, - t = this.getIdlePeer().length; - if ( - (e.info(`peers: ${this.peersNum} idle peers: ${t}`), - t < this.peersNum) - ) { - const t = this.peerManager.getPeers(), - r = t.filter((e) => e.downloading); - e.warn( - `downloading: ${r.length} choked: ${ - t.filter((e) => e.choked).length - }` - ); - for (let t of r) - e.warn( - `${t.remotePeerId} loading ${t.segId} remains ${t.remainAttachments} total ${t.pieceMsg.attachments}` - ); - } - return t > 0; - } - getIdlePeer() { - return this.peerManager.getAvailablePeers(); - } - set bufferManager(t) { - (this.bufMgr = t), - t - .on(e.BM_LOST, ({ sn: e, segId: t, next: r, level: i }) => { - this._broadcastLost(e, t, i), - this.onBufferManagerLost(e, t, r, i); - }) - .on(e.BM_SEG_ADDED, (e) => { - this.onBufferManagerSegAdded(e); - }); - } - onBufferManagerSegAdded(e) {} - _broadcastLost(t, r, i, n) { - this.config.live || - this._broadcastToPeers( - { event: e.DC_LOST, sn: t, seg_id: r || void 0, level: i }, - n - ); - } - destroy() { - const { logger: e } = this; - this.peersNum > 0 && this.peerManager.clear(), - this.removeAllListeners(), - clearInterval(this.checkConnsTimer), - clearTimeout(this.checkTimer), - e.warn("destroy BtScheduler"); - } - notifyPeersLoaded(e) {} - _setupDC(t) { - const { logger: r } = this; - t.on(e.DC_PIECE_ACK, (e) => { - e.size && - (this.engine.fetcher.reportUploaded(e.size), - r.info( - `uploaded ${e.seg_id} size ${e.size} to ${t.remotePeerId}` - )); - }) - .on(e.DC_PIECE_ABORT, (e) => { - r.warn( - `peer ${t.remotePeerId} download aborted, reason ${e.reason}` - ), - this._handlePieceAborted(t.remotePeerId), - this.config.live && this.checkPeers && this.checkPeers(); - }) - .on(e.DC_DISCONNECT, () => { - this.peersNum >= this.minConns && - (this.logger.warn( - `close disconnected peer ${t.remotePeerId}` - ), - t.close(!1)); - }); - } - _broadcastToPeers(e, t) { - for (let r of this.getPeers()) (t && r === t) || r.sendJson(e); - } - _peersStats(e) { - this.engine.emitEvent("peers", e); - const t = this.engine.config.getPeersInfo; - A(t) && t(e); - } - startCheckPeersTimer() { - this.logger.info("startCheckPeersTimer"); - const e = () => { - this.checkPeers(); - const t = - 1e3 * (0 === (r = this.loadedPeerNum) ? 3 : 0.5 * r + 1.67); - var r; - (this.loadedPeerNum = 0), (this.checkTimer = setTimeout(e, t)); - }; - this.checkTimer = setTimeout(e, 15e3); - } - removeStreamListener(e, t) { - const r = this.requestingMap.get(e); - if (r) return void r.removeStreamListener(t); - const i = this.segmentBuilderMap.get(e); - i && i.removeStreamListener(t); - } - setTargetPeersFromGroup(e, t, r, i) { - if (e.hasReversePeer) { - if ((r = t.concat(r)).length > 0) - return (this.targetPeers.forwardPeer = r[0]), !0; - } else if (e.hasForwardPeer && (i = t.concat(i)).length > 0) - return (this.targetPeers.reversePeer = i[0]), !0; - return t.length > 0 - ? (e.hasForwardBuffer - ? (this.targetPeers.reversePeer = t[0]) - : (this.targetPeers.forwardPeer = t[0]), - !0) - : ((this.targetPeers = I(t, r, i)), - this.targetPeers.some((e) => !!e)); - } - } - const ir = rr; - class nr extends s() { - constructor() { - super(), (this.internalMap = new Map()); - } - has(e) { - return this.internalMap.has(e); - } - set(e, t) { - this.internalMap.set(e, t), - S(this.internalMap, 13, (e) => { - e && e.destroy(); - }); - } - get(e) { - return this.internalMap.get(e); - } - delete(e) { - const t = this.internalMap.get(e); - t && (t.destroy(), this.internalMap.delete(e)); - } - get size() { - return this.internalMap.size; - } - clear() { - this.internalMap.clear(), this.removeAllListeners(); - } - } - const sr = 0, - ar = 1, - or = 2, - lr = 3; - class hr extends s() { - constructor() { - super(), - (this.UNSENT = 0), - (this.OPENED = 1), - (this.HEADERS_RECEIVED = 2), - (this.LOADING = 3), - (this.DONE = 4), - (this.timeout = 0), - (this.withCredentials = !1), - (this.status = 0), - (this.readyState = this.UNSENT), - (this.headers = new Map()), - (this.responseHeaders = null), - this.on("load", (e) => { - this.onload && this.onload(e); - }), - this.on("abort", (e) => { - this.onabort && this.onabort(e); - }), - this.on("error", (e) => { - this.onerror && this.onerror(e); - }), - this.on("loadstart", (e) => { - this.onloadstart && this.onloadstart(e); - }), - this.on("progress", (e) => { - this.onprogress && this.onprogress(e); - }), - this.on("timeout", (e) => { - this.ontimeout && this.ontimeout(e); - }), - this.on("loadend", (e) => { - this.onloadend && this.onloadend(e); - }), - this.on("readystatechange", () => { - this.onreadystatechange && this.onreadystatechange(); - }); - } - setRequestHeader(e, t) { - this.headers.set(e, t); - } - addEventListener(e, t) { - this.addListener(e, t); - } - removeEventListener(e, t) { - this.removeListener(e, t); - } - overrideMimeType() {} - getAllResponseHeaders() { - if (!this.responseHeaders) return null; - let e = ""; - return ( - this.responseHeaders.forEach((t, r) => { - e += `${r}: ${t}\n`; - }), - e - ); - } - getResponseHeader(e) { - return this.responseHeaders ? this.responseHeaders.get(e) : null; - } - open() { - (this.readyState = this.OPENED), this.emit("loadstart"); - } - abort() { - (this.readyState = this.DONE), - (this.status = 0), - this.emit("loadend"); - } - send() {} - _emitEvent(e) { - this.emit(e, { type: e, target: this }); - } - } - function ur() { - if ( - self.fetch && - self.AbortController && - self.ReadableStream && - self.Request - ) - try { - return new self.ReadableStream({}), !0; - } catch (e) {} - return !1; - } - class dr { - constructor(e) { - (this.fetchSetup = e.fetchSetup || cr), - (this.xhrSetup = e.xhrSetup), - (function (e) { - try { - new e(); - } catch (e) { - return !1; - } - return !0; - })(self.AbortController) && - (this.controller = new self.AbortController()), - (this.stats = C()), - (this.packetSize = u), - (this.fakeXhr = new hr()); - } - destroy() { - (this.loader = this.callbacks = null), this.abortInternal(); - } - abortInternal() { - const e = this.response; - (e && e.ok) || - ((this.stats.aborted = !0), - this.callbacks && - this.callbacks.onUpdate && - this.callbacks.onUpdate(void 0, !1, !0), - this.controller && this.controller.abort()); - } - abort() { - this.abortInternal(), - this.callbacks && - this.callbacks.onAbort && - this.callbacks.onAbort(this.stats, this.context, this.response); - } - load(e, t, r) { - const i = this.stats; - i.trequest = i.loading.start = performance.now(); - let n = (function (e, t) { - const r = { - method: "GET", - mode: "cors", - credentials: "same-origin", - signal: t, - headers: new self.Headers(Object.assign({}, e.headers)), - }; - e.rangeEnd && - r.headers.set( - "Range", - "bytes=" + e.rangeStart + "-" + String(e.rangeEnd - 1) - ); - return r; - })(e, this.controller ? this.controller.signal : void 0); - const s = "arraybuffer" === e.responseType, - a = s ? "byteLength" : "length", - o = r.onUpdate, - l = r.onBodyStart; - (this.context = e), - (this.config = t), - (this.callbacks = r), - this.xhrSetup && - (this.xhrSetup(this.fakeXhr, e.url), - (n = (function (e, t) { - e.withCredentials && (t.credentials = "include"); - for (let [r, i] of e.headers) t.headers.set(r, i); - return t; - })(this.fakeXhr, n))), - (this.request = this.fetchSetup(e, n)), - clearTimeout(this.requestTimeout), - (this.requestTimeout = setTimeout(() => { - this.abortInternal(), - this.fakeXhr._emitEvent("timeout"), - this.fakeXhr._emitEvent("loadend"), - r.onTimeout && r.onTimeout(i, e, this.response); - }, this.fakeXhr.timeout || t.timeout)); - const h = - "then" in (u = this.request) && u.then instanceof Function - ? this.request.then(self.fetch) - : self.fetch(this.request); - var u; - const { fakeXhr: d } = this; - (d.readyState = d.OPENED), - d.emit("readystatechange"), - d._emitEvent("loadstart"), - h - .then((t) => { - if (((this.response = this.loader = t), !t.ok)) { - const { status: e, statusText: i } = t, - n = i || "fetch, bad network response"; - throw ( - (r.onError && r.onError({ text: n }), new fr(n, e, t)) - ); - } - (i.tfirst = i.loading.first = - Math.max(performance.now(), i.loading.start)), - (i.total = parseInt( - t.headers.get("Content-Length") || "0" - )); - let n = 0; - try { - const e = t.headers.get("Content-Range").split("/"); - 2 === e.length && (n = parseInt(e[1], 10)); - } catch (e) {} - const { fakeXhr: a } = this; - return ( - (a.readyState = a.HEADERS_RECEIVED), - (a.responseHeaders = t.headers), - a.emit("readystatechange"), - o && "0" !== i.total - ? (l && l(i.total, n), this.loadProgressively(t, i, e, o)) - : (a.emit( - "progress", - new ProgressEvent("progress", { - lengthComputable: !1, - }) - ), - s ? t.arrayBuffer() : t.text()) - ); - }) - .then((t) => { - const { response: n } = this; - clearTimeout(this.requestTimeout), - (i.tload = i.loading.end = - Math.max(performance.now(), i.loading.first)), - (i.loaded = i.total = t[a]); - const s = { url: n.url, data: t }; - r.onProgress && r.onProgress(i, e, t, n), - r.onSuccess && r.onSuccess(s, i, e, n); - }) - .catch((t) => { - if ((clearTimeout(this.requestTimeout), i.aborted)) return; - const n = (t && t.code) || 0, - s = t ? t.message : null; - r.onError && - r.onError({ code: n, text: s }, e, t ? t.details : null); - }); - } - loadProgressively(e, t, r, i) { - const n = e.body.getReader(); - let s = 0, - o = 0, - l = (0, a.h)(0), - h = !1; - const d = () => - n - .read() - .then(({ value: r, done: n }) => { - const { fakeXhr: c } = this; - if ( - (c.readyState !== c.LOADING && - ((c.readyState = c.LOADING), c.emit("readystatechange")), - r && (s += r.length), - n) - ) { - if (l.byteLength > 0) - if (s <= this.packetSize) { - const e = (0, a.h)(s); - l.copy(e, 0, o * this.packetSize, l.byteLength), - i(e, !0); - } else { - const e = (function (e, t) { - const r = e.byteLength - t, - i = []; - let n = t, - s = Math.floor(r / u), - o = r % u; - for (let t = 0; t < s; t++) { - const t = (0, a.h)(u); - e.copy(t, 0, n, n + u), i.push(t), (n += u); - } - if (o > 0) { - const t = (0, a.h)(o); - e.copy(t, 0, n, n + o), i.push(t); - } - return i; - })(l, o * this.packetSize); - for (let t = 0; t < e.length; t++) - i(e[t], t === e.length - 1); - } - const t = l.buffer, - { fakeXhr: r } = this, - { status: n, statusText: h, url: d } = e; - return ( - (r.readyState = r.DONE), - (r.responseText = n), - (r.status = h), - (r.responseURL = d), - (r.responseType = "arraybuffer"), - (r.response = t), - r.emit("readystatechange"), - r._emitEvent("load"), - r._emitEvent("loadend"), - Promise.resolve(t) - ); - } - if ( - ((t.loaded += r.length), - c.emit( - "progress", - new ProgressEvent("progress", { - lengthComputable: !0, - loaded: t.loaded, - total: t.total, - }) - ), - this.callbacks.onLoaded && - this.callbacks.onLoaded( - { total: t.total, loaded: t.loaded, first: !h }, - this.context - ), - (h = !0), - (l = a.h.concat([l, r])), - s >= this.packetSize) - ) { - s -= this.packetSize; - const e = (0, a.h)(this.packetSize); - l.copy( - e, - 0, - o * this.packetSize, - (o + 1) * this.packetSize - ), - o++, - i(e, !1); - } - return d(); - }) - .catch( - () => ( - this.fakeXhr._emitEvent("abort"), - this.fakeXhr._emitEvent("loadend"), - Promise.reject() - ) - ); - return d(); - } - } - function cr(e, t) { - return new self.Request(e.url, t); - } - class fr extends Error { - constructor(e, t, r) { - super(e), (this.code = t), (this.details = r); - } - } - class gr extends s() { - constructor(e, t, r = !1) { - super(), - (this.coordinator = e), - (this.logger = t), - (this.rangeSupported = r), - (this.rangeStart = 0), - (this.rangeEnd = 0), - (this.httpLoadTime = 2e3), - (this.proxied = !1), - (this.forwardPeer = null), - (this.reversePeer = null), - (this.bufArr = []), - (this.forwardBufList = []), - (this.reverseBufList = []), - (this.forwardOffset = -1), - (this.reverseOffset = 1e4), - (this.timeStart = 0), - (this.timeReceivePiece = 0), - (this.destroyed = !1), - (this.forwardStreamListeners = []), - (this.reverseStreamListeners = []), - (this.rangeRequesting = !1), - (this.waitingRemain = !1), - (this.httpLoaded = 0), - (this.p2pLoaded = 0), - (this.deadline = 0), - (this.forwardCanceled = !1), - (this.reverseCanceled = !1), - (this.firstReceived = !1); - } - get isDownloading() { - return this.timeReceivePiece > 0; - } - get isAlmostDeadline() { - if (this.rangeRequesting) return !0; - if (this.isEmpty) return !1; - if (0 === this.deadline) return !0; - const e = this.deadline - performance.now(); - return ( - e <= 0 || this.p2pSpeed > 3 * this.minRequiredSpeed(e) || e < 500 - ); - } - hasPeer(e) { - return !!e && (e === this.forwardPeer || e === this.reversePeer); - } - get streamListeners() { - return [ - ...this.reverseStreamListeners, - ...this.forwardStreamListeners, - ].length; - } - _notifyStreamListenersAbort() { - const { sn: e, seg_id: t } = this.pieceMsg, - r = [ - ...this.reverseStreamListeners, - ...this.forwardStreamListeners, - ]; - for (let i of r) { - const { handler: r } = i; - r(e, t, !0, "aborted by synthesizer"); - } - this._resetStreamListeners(); - } - _resetStreamListeners() { - (this.reverseStreamListeners.length = 0), - (this.forwardStreamListeners.length = 0); - } - _notifyStreamListenersRemain() { - if (this.forwardStreamListeners.length > 0) { - for (let e = this.forwardOffset + 1; e < this.bufArr.length; e++) - this._notifyStreamListeners(!1, this.bufArr[e], e); - this.forwardStreamListeners = []; - } - if (this.reverseStreamListeners.length > 0) { - for (let e = this.reverseOffset - 1; e >= 0; e--) - this._notifyStreamListeners(!0, this.bufArr[e], e); - this.reverseStreamListeners = []; - } - } - addStreamListener(e, t, r) { - (e - ? this.reverseStreamListeners - : this.forwardStreamListeners - ).push({ handler: r, peerId: t }); - } - removeStreamListener(e) { - const { sn: t, seg_id: r } = this.pieceMsg, - i = (i) => - i.filter( - (i) => - i.peerId !== e || - (i.handler(t, r, !0, "aborted by cancel"), !1) - ); - (this.forwardStreamListeners = i(this.forwardStreamListeners)), - (this.reverseStreamListeners = i(this.reverseStreamListeners)); - } - setTimeout(e = 0, t = !1) { - this.logger.info(`syn setTimeout ${e}`); - let r = performance.now(); - e <= 0 - ? setTimeout(() => { - this._handleTimeout(!1, !1); - }, 0) - : ((this.firstPieceTimer = setTimeout(() => { - if (this.firstReceived) return; - const e = () => { - this.logger.warn( - `switch to http, firstReceived ${this.firstReceived}` - ), - this._handleTimeout(!1); - }; - if (this.timeReceivePiece > 0) { - const t = (this.timeReceivePiece - r) / 2; - t > 0 - ? (this.firstPieceTimer = setTimeout(() => { - (this.firstReceived && !this._shouldSwitch()) || e(); - }, t)) - : e(); - } else e(); - }, e / 2)), - (this.deadline = r + e), - this._startTimer(e, t)); - } - setExtra(e = {}) { - e.url && (this.url = e.url), - e.rangeStart && (this.rangeStart = e.rangeStart), - e.rangeEnd && (this.rangeEnd = e.rangeEnd), - e.httpLoadTime && (this.httpLoadTime = e.httpLoadTime), - e.proxied && (this.proxied = !0), - e.xhrSetup && (this.xhrSetup = e.xhrSetup), - e.headers && (this.headers = e.headers), - e.segId && - !this.pieceMsg.seg_id && - (this.pieceMsg.seg_id = e.segId); - } - get hasForwardPeer() { - return !!this.forwardPeer; - } - get hasReversePeer() { - return !!this.reversePeer; - } - hasPeerId(e) { - return ( - (this.forwardPeer && this.forwardPeer.remotePeerId === e) || - (this.reversePeer && this.reversePeer.remotePeerId === e) - ); - } - get isEmpty() { - return null === this.forwardPeer && null === this.reversePeer; - } - get isFull() { - return this.forwardPeer && this.reversePeer; - } - setForwardPeer(e) { - (this.forwardPeer = e), - this.reversePeer && this._print(), - this._setupPeer(e, !1); - } - setReversePeer(e) { - (this.reversePeer = e), - this.forwardPeer && this._print(), - this._setupPeer(e, !0); - } - setPeer(e, t) { - t ? this.setReversePeer(e) : this.setForwardPeer(e); - } - deletePeer(e) { - const t = e === this.reversePeer; - this._detachPeer(e), - t ? (this.reversePeer = null) : (this.forwardPeer = null), - (this.isEmpty || this.deadline > 0) && - this._handleTimeout(!1, !1); - } - terminate() { - this._handleTimeout(!1, !1); - } - get hasPartialBuffer() { - return this.hasForwardBuffer || this.hasReverseBuffer; - } - get hasForwardBuffer() { - return this.forwardOffset >= 0; - } - get hasReverseBuffer() { - return ( - this.pieceMsg && this.reverseOffset < this.pieceMsg.attachments - ); - } - get isForwardBufferFull() { - return ( - this.pieceMsg && - this.forwardOffset >= this.pieceMsg.attachments - 1 - ); - } - get isReverseBufferFull() { - return this.reverseOffset <= 0; - } - _cancelP2p(e = !1) { - const { seg_id: t, sn: r, level: i } = this.pieceMsg; - !this.forwardPeer || - this.isForwardBufferFull || - this.forwardCanceled || - (this.forwardPeer.cancelDownload(r, i, t), - (this.forwardCanceled = !0)), - e || - !this.reversePeer || - this.isReverseBufferFull || - this.reverseCanceled || - (this.reversePeer.cancelDownload(r, i, t), - (this.reverseCanceled = !0)); - } - detachPeers() { - this._detachPeer(this.forwardPeer), - this._detachPeer(this.reversePeer); - } - destroy() { - clearTimeout(this.timer), - clearTimeout(this.firstPieceTimer), - this._notifyStreamListenersAbort(), - this._cancelP2p(), - this.removeAllListeners(), - (this.destroyed = !0), - this._detachPeer(this.forwardPeer), - (this.forwardPeer = null), - (this.forwardOffset = -1), - this._detachPeer(this.reversePeer), - (this.reversePeer = null), - (this.reverseOffset = 1e4), - (this.bufArr = []), - (this.forwardStreamListeners = []), - (this.reverseStreamListeners = []), - this.httpLoader && - (this.logger.warn("abort syn httpLoader"), - this.httpLoader.abort()); - } - _detachPeer(t) { - if (!t) return; - const r = - t === this.reversePeer ? this.reverseEvents : this.forwardEvents; - r && - r && - t - .off(e.DC_PIECE_DATA, r.onPieceData) - .off(e.DC_PIECE, r.onPiece) - .off(e.DC_PIECE_NOT_FOUND, r.onPieceNotFound) - .off(e.DC_PIECE_ABORT, r.onPieceAbort); - } - _receivePacket(t, r, i, n = !0) { - const { - seg_id: s, - sn: o, - level: l, - size: h, - attachments: u, - } = this.pieceMsg, - d = r - 1; - if ( - (this.bufArr[d] - ? (this.logger.warn( - `syn bufArr ${s} already has ${d} size ${i.byteLength}` - ), - (this.bufArr[d] = i)) - : (n - ? (this.p2pLoaded += i.byteLength) - : (this.httpLoaded += i.byteLength), - this.emit(e.SYN_PROGRESS, { - total: h, - loaded: this.p2pLoaded + this.httpLoaded, - first: !this.firstReceived, - segId: s, - sn: o, - }), - (this.firstReceived = !0), - (this.bufArr[d] = i), - t ? (this.reverseOffset = d) : (this.forwardOffset = d), - this._notifyStreamListeners(t, i, d)), - this.forwardOffset !== this.reverseOffset - 1) - ) - return !0; - this.rangeRequesting || - (this.forwardPeer && (this.forwardPeer.miss = 0), - this.reversePeer && (this.reversePeer.miss = 0)), - clearTimeout(this.timer), - this._notifyStreamListenersRemain(); - const c = h / (performance.now() - this.timeStart); - let f = a.h.concat(this.bufArr); - const g = f.byteLength; - if (g === h) { - let t = f.buffer; - const r = new z( - o, - s, - t, - this.getFromPeerId(), - l, - this.pieceMsg.ext - ); - this.emit(e.SYN_OUTPUT, r, { - speed: c, - p2p: this.p2pLoaded, - http: this.httpLoaded, - }); - } else { - this.logger.error( - `${s} expectedSize ${h} != byteLength ${g} forward ${this.forwardOffset} reverse ${this.reverseOffset}` - ); - for (let e = 0; e < this.bufArr.length; e++) - this.logger.error( - `piece ${e} size ${this.bufArr[e].byteLength}` - ); - this.emit(e.SYN_ERROR, this.pieceMsg, sr), - this._disconnectPeers(); - } - } - _disconnectPeers() { - [this.forwardPeer, this.reversePeer].forEach((t) => { - t && t.emit(e.DC_ERROR, !0); - }); - } - _setupPeer(t, r) { - const { logger: i } = this; - 0 === this.timeStart && (this.timeStart = performance.now()); - const n = (r, n, s, a, o, l) => { - if (this.destroyed) return; - if (!this._validateMsg(r, l.level, n)) - return void i.error( - `onPieceData ${n || r} not match ${JSON.stringify( - this.pieceMsg - )} from ${t.remotePeerId}` - ); - if (a < this.pieceMsg.attachments && s.byteLength !== u) - return ( - i.error(`${n} dataSn ${a} size is ${s.byteLength}`), - this.emit(e.SYN_ERROR, this.pieceMsg, sr), - void this._disconnectPeers() - ); - const { reverse: h } = l; - this._receivePacket(h, a, s) && - !this.waitingRemain && - !this.rangeRequesting && - this.deadline > 0 && - this._shouldSwitch() && - (i.warn("should switch to http"), - clearTimeout(this.timer), - clearTimeout(this.firstPieceTimer), - this._handleTimeout(!1, !1)); - }, - s = (e) => { - if (this.destroyed) return; - const { - attachments: r, - size: n, - sn: s, - level: a, - seg_id: o, - ext: l, - } = e; - return n && this._validateMsg(s, a, o) - ? this.pieceMsg.size && n !== this.pieceMsg.size - ? (i.warn(`onPiece ${o} size not match`), - t.cancelDownload(s, a, o), - void this.deletePeer(t)) - : void ( - 0 === this.bufArr.length && - ((this.pieceMsg = { - ...this.pieceMsg, - seg_id: o, - size: n, - attachments: r, - ext: l, - }), - (this.reverseOffset = r), - (this.bufArr = new Array(r)), - (this.timeReceivePiece = performance.now())) - ) - : (i.warn( - `onPiece ${JSON.stringify(e)} not match ${JSON.stringify( - this.pieceMsg - )}` - ), - t.cancelDownload(s, a, o), - void this.deletePeer(t)); - }, - a = (e) => { - this.destroyed || this.deletePeer(t); - }, - o = () => { - this.destroyed || this.deletePeer(t); - }, - l = { - onPieceData: n, - onPiece: s, - onPieceNotFound: a, - onPieceAbort: o, - }; - r ? (this.reverseEvents = l) : (this.forwardEvents = l), - t - .on(e.DC_PIECE_DATA, n) - .once(e.DC_PIECE, s) - .once(e.DC_PIECE_NOT_FOUND, a) - .once(e.DC_PIECE_ABORT, o); - } - _shouldSwitch() { - const e = u, - t = this.pieceMsg.size - e * this.loadedPackets; - return this.coordinator.shouldSwitchToHttp( - t, - this.deadline, - this.p2pSpeed, - e, - this.httpLoadTime - ); - } - _startTimer(e, t = !0) { - this.timer = setTimeout(this._handleTimeout.bind(this, t), e); - } - get loadedPackets() { - return ( - this.pieceMsg.attachments - - (this.reverseOffset - this.forwardOffset - 1) - ); - } - _handleTimeout(t = !1, r = !0) { - if (this.destroyed || this.rangeRequesting) return; - const { seg_id: i, size: n, attachments: s } = this.pieceMsg; - if (!n || 0 === this.timeReceivePiece) - return ( - this.logger.warn(`syn load timeout ${i} url ${this.url}`), - void this.emit(e.SYN_ERROR, this.pieceMsg, sr) - ); - if (t && this.timeReceivePiece > 0 && s) { - this.logger.warn( - `syn ${this.loadedPackets} of ${s} packets loaded` - ); - const e = this.httpLoadTime > 3e3 ? 3e3 : this.httpLoadTime; - if (this.shouldWaitForRemain(e)) - return ( - (this.waitingRemain = !0), - this.logger.info(`syn wait for remain ${e}`), - void this._startTimer(e, !1) - ); - } - if (r) { - const e = [this.forwardPeer, this.reversePeer] - .filter((e) => !!e) - .sort((e, t) => { - const r = e.currentLoadSpeed(), - i = t.currentLoadSpeed(); - return r === i - ? e.timeSendRequest - t.timeSendRequest - : r - i; - }) - .shift(); - e && e.loadtimeout(); - } - if ( - this.rangeSupported && - this.url && - (this.hasPartialBuffer || this.hasReversePeer) - ) - return this._cancelP2p(!0), this._loadRemainBufferByHttp(); - this._notifyStreamListenersAbort(), - this.emit(e.SYN_ERROR, this.pieceMsg, lr); - } - shouldWaitForRemain(e) { - return !this.isEmpty && this.shouldWaitForRemainUrgent(e); - } - shouldWaitForRemainUrgent(e) { - if (0 === this.timeReceivePiece || e <= 0) return !1; - const t = this.p2pSpeed, - r = this.minRequiredSpeed(e); - return ( - this.logger.info(`syn remainTime ${e} speed ${t} required ${r}`), - t >= r - ); - } - minRequiredSpeed(e) { - let t = 0; - return ( - [this.forwardPeer, this.reversePeer].forEach((e) => { - e && (t += e.loadedBytes()); - }), - (this.pieceMsg.size - t) / e - ); - } - get p2pSpeed() { - let e = 0; - return ( - [this.forwardPeer, this.reversePeer].forEach((t) => { - t && (e += t.currentLoadSpeed()); - }), - e - ); - } - getFromPeerId() { - const { forwardPeer: e, reversePeer: t } = this; - return this.isFull && e !== t - ? `${e.remotePeerId}:${t.remotePeerId}` - : e - ? `${e.remotePeerId}` - : t - ? `${t.remotePeerId}` - : ""; - } - getStreamInfo(e) { - const t = e ? this.reverseBufList : this.forwardBufList; - let r, i; - return ( - t.length < this.pieceMsg.attachments - ? ((r = this.isFull - ? "WaitPartialDouble" - : "WaitPartialSingle"), - (i = 1)) - : ((r = this.isFull ? "SynFullDouble" : "SynFullSingle"), - (i = 0)), - { from: r, incompletes: i, bufferList: t } - ); - } - _loadRemainBufferByHttp() { - if (this.rangeRequesting) return; - const { size: t, seg_id: r } = this.pieceMsg, - { logger: i } = this, - n = this.rangeEnd > 0 ? this.rangeEnd - 1 : 0; - let s = this.forwardOffset; - const a = performance.now(); - this.rangeRequesting = !0; - let o = ge(s, this.reverseOffset, t, this.rangeStart, n); - const l = o.rangeEnd - o.rangeStart; - i.info( - `listeners ${this.streamListeners} continue download ${r} from ${this.url} range: ${o.rangeStart}-${o.rangeEnd}` - ), - this.hasPartialBuffer || (o = {}); - const u = new dr({ xhrSetup: this.xhrSetup }); - this.httpLoader = u; - let d = { url: this.proxied ? f(this.url, h, !0) : this.url, ...o }; - let c, - g = s + 1; - const p = { - onUpdate: (t, r, n) => { - if (!this.destroyed) { - if (n) - return ( - i.warn("httpLoader aborted"), - void this.emit(e.SYN_ERROR, this.pieceMsg, ar) - ); - if (r) { - const e = c / (performance.now() - a); - this.coordinator.addHttpSpeed(e), - (this.httpLoader = void 0); - } - this.bufArr[g] || this._receivePacket(!1, g + 1, t, !1), g++; - } - }, - onBodyStart: (t, n) => { - if ( - (0 === n && i.warn(`range request fileSize ${n}`), - this.destroyed) - ) - return; - const { size: s } = this.pieceMsg; - if (((c = t), t !== s || (0 !== n && n !== s))) { - let r = !1; - n > 0 && n !== s - ? (i.error(`onBodyStart fileSize ${n} != ${s}`), (r = !0)) - : t !== l && - (i.error(`onBodyStart size ${t} != expectedSize ${l}`), - (r = !0)), - r && this.emit(e.SYN_ERROR, this.pieceMsg, ar); - } else i.warn(`syn range request ${r} resp whole ts`), (g = 0); - }, - onError: (t) => { - this.destroyed || - (i.error(`httpLoader error ${t.text}`), - this.emit(e.SYN_ERROR, this.pieceMsg, ar)); - }, - onTimeout: () => { - this.destroyed || - (i.warn("httpLoader timeout"), - this.emit(e.SYN_ERROR, this.pieceMsg, or)); - }, - }; - u.load(d, { timeout: 15e3 }, p); - } - _print() { - const { seg_id: e, sn: t } = this.pieceMsg; - this.logger.info(`syn parallel loading ${e || t}`); - } - } - class pr extends gr { - constructor(e, r, i, n, s, a = !1, o) { - super(e, r, a, o), - (this.pieceMsg = { - event: t.DC_PIECE, - sn: i, - level: n, - seg_id: s, - }), - o && this.setExtra(o); - } - get segId() { - return this.pieceMsg.seg_id; - } - _notifyStreamListeners(e, t, r) { - const { sn: i, seg_id: n, attachments: s } = this.pieceMsg, - a = (e && 0 === r) || (!e && r === s - 1), - o = e ? this.reverseStreamListeners : this.forwardStreamListeners; - e ? this.reverseBufList.push(t) : this.forwardBufList.push(t), - a && - (this.forwardBufList.push([...this.reverseBufList].reverse()), - this.reverseBufList.push([...this.forwardBufList].reverse())); - for (let e of o) { - const { handler: r } = e; - r(i, n, !1, t, a); - } - a && this._resetStreamListeners(); - } - _validateMsg(e, t, r) { - return ( - (!this.pieceMsg.seg_id || r === this.pieceMsg.seg_id) && - e === this.pieceMsg.sn && - t === this.pieceMsg.level - ); - } - } - class mr { - constructor() { - this.meanHttpSpeed = 0; - } - addHttpSpeed(e) { - this.meanHttpSpeed = 0.4 * this.meanHttpSpeed + 0.6 * e; - } - shouldSwitchToHttp(e, t, r, i, n) { - if (this.meanHttpSpeed <= 0) return !1; - if (r >= this.meanHttpSpeed) return !1; - if (this.meanHttpSpeed * n >= e) return !1; - return ( - (((n + t - performance.now()) * this.meanHttpSpeed - e) / - (this.meanHttpSpeed - r)) * - r < - i - ); - } - } - class vr extends ir { - constructor(e, t) { - super(e, t), - (this.prefetchOnly = t.prefetchOnly), - (this.bitset = new Jt(t.live || !1)), - (this.bitCounts = new Zt()), - (this.requestingMap = new nr()), - (this.segmentBuilderMap = new nr()), - (this.allowP2pLimit = t.httpLoadTime + 1.5), - (this.playlistInfo = new Map()), - (this.gotPlaylist = !1), - (this.targetPeers = {}), - (this.sequential = !0), - (this.coordinator = new mr()), - (this.loadingSegId = ""), - (this.loadingSN = 0), - (this.currPlaySN = 0), - (this.currLostSN = -1), - (this.nextLostSN = -1), - this.config.live - ? (this.maxPrefetchCount = 10) - : ((this.maxPrefetchCount = 150), this.startCheckPeersTimer()); - } - handshakePeer(e) { - this._setupDC(e); - const { asn: t, country: r } = this.engine.fetcher.announceInfo; - e.sendMetaData( - this.bitset.allArray(), - !0, - this.peersNum, - { asn: t, country: r }, - this.isMobileNet - ); - } - _receiveDCHave(e, t, r, i) { - this.bitset.has(e, t) || this.bitCounts.incre(e, t); - } - _setupDC(e) { - super._setupDC(e), - e - .on(t.DC_HAVE, (t) => { - if (e.bitset && t.sn >= 0) { - const { sn: r, level: i, complete: n, seg_id: s } = t, - a = n ? Yt.COMPLETE : Yt.PARTIAL_FORWARD; - e.bitset.add(r, i, s, a), - this._receiveDCHave(r, i, s, e), - e.isAvailableUrgently && - this._handleDCHave(e, r, i, s, a); - } - }) - .on(t.DC_HAVE_REVERSE, (t) => { - if (e.bitset && t.sn >= 0) { - const { sn: r, level: i, seg_id: n } = t; - e.bitset.hasCompleteOr(r, i, Yt.PARTIAL_REVERSE) || - e.bitset.add(r, i, n, Yt.PARTIAL_REVERSE), - this._receiveDCHave(r, i, n, e), - e.isAvailableUrgently && - this._handleDCHave(e, r, i, n, Yt.PARTIAL_REVERSE); - } - }) - .on(t.DC_LOST, (t) => { - if (!e.bitset) return; - const { sn: r, level: i } = t; - e.bitset.has(r, i) && - (e.bitset.delete(r, i), this.bitCounts.decre(r, i)); - }) - .on(t.DC_PIECE, (e) => { - (e.ext && e.ext.incompletes >= 7) || - this.notifyAllPeers( - e.sn, - e.level, - e.seg_id, - e.reverse ? Yt.PARTIAL_REVERSE : Yt.PARTIAL_FORWARD - ); - }) - .on(t.DC_PIECE_CANCEL, (t) => { - const { sn: r, level: i } = t, - n = ve(r, i); - this.removeStreamListener(n, e.remotePeerId); - }) - .on(t.DC_PIECE_NOT_FOUND, (t) => { - const { sn: r, level: i } = t; - e.bitset.delete(r, i), - this.bitCounts.decre(r, i), - e.checkIfNeedChoke(!0); - }) - .on(t.DC_DISCONNECT, () => { - this.cleanRequestingMap(e.remotePeerId); - }) - .on(t.DC_REQUEST, async (t) => { - const { logger: r } = this, - { sn: i, level: n, reverse: s } = t; - let a = t.seg_id; - a || (a = await this.bufMgr.getSegIdBySN(i)); - const o = () => { - this.bitset.delete(i, n), - e.sendPieceNotFound(i, a, { level: n }), - this._broadcastLost(i, a, n, e); - }, - l = await this.bufMgr.getSegById(a), - h = ve(i, n), - u = this.requestingMap.get(h); - let d = !1; - u && u.isDownloading && (d = !0); - const c = this.segmentBuilderMap.get(h); - if (l) - if ((r.info(`found seg ${a} from bufMgr`), l.level === n)) { - let t = - "SegmentStore" === this.bufMgr.name ? "Disk" : "Cache"; - l.ext && - l.ext.from && - l.ext.from.length < 2500 && - (t = `${l.ext.from}-${t}`), - e.sendBuffer(l.sn, l.segId, l.data, { - from: t, - level: l.level, - reverse: s, - }); - } else o(); - else if (!s && c) - r.info( - `peer request ${i} wait from builder, sent ${c.bufferList.length}` - ), - w(e, c, c.pieceMsg, c.bufferList, c.source, 1); - else if (d) { - r.info( - `syn had ${ - u.loadedPackets - } packets, wait remain from upstream ${u.getFromPeerId()}` - ); - const t = { ...u.pieceMsg, reverse: s }, - { - from: i, - incompletes: n, - bufferList: a, - } = u.getStreamInfo(s); - w(e, u, t, a, i, n); - } else o(); - }); - } - handleMetaData(e, t) { - if (t.field) { - e.bitset = new Jt(this.config.live, t.field); - for (let e in t.field) { - const r = Number(e); - if (r < 0) continue; - t.field[r].forEach((e) => { - this.bitset.has(e, r) || this.bitCounts.incre(e, r); - }); - } - this.addPeer(e), this.downloadOnly && this.chokePeerRequest(e); - } - } - peersHas(e, t) { - return this.bitCounts.has(e, t); - } - deletePeer(e) { - if (this.peerManager.hasPeer(e.remotePeerId) && e.bitset) { - const t = e.bitset.allArray(); - for (let e in t) { - const r = Number(e), - i = t[r]; - i && - i.forEach((e) => { - this.bitCounts.decre(e, r); - }); - } - } - this.cleanRequestingMap(e.remotePeerId), super.deletePeer(e); - } - hasAndSetTargetPeer(e, t, r, i) { - const { logger: n, config: s } = this; - let a = 1e3 * (i - s.httpLoadTime); - (this.allowP2pLimit = s.httpLoadTime + 1.5), - n.info( - `bufferedDuration ${ - 1e3 * i - } remainLoadTime ${a} allowP2pLimit ${1e3 * this.allowP2pLimit}` - ); - const o = ve(e, t), - l = this.requestingMap.get(o); - if (l) { - const s = l.segId; - if (s && s !== r) - return ( - n.warn(`syn segId ${s} not match ${r}`), - this.requestingMap.delete(o), - this._searchAvailablePeers(e, t, r, i) - ); - if (!l.shouldWaitForRemain(a)) { - if ( - (n.warn(`syn prefetch timeout at ${e}`), - (l.prefetchTimeout = !0), - l.isFull) - ) - return this.httpRangeSupported; - const i = this.peerManager.getPeersOrderByWeight(); - let [s, o, h] = Xt(i, e, t, r); - return ( - !!this.setTargetPeersFromGroup(l, s, o, h) || - ((l.hasReversePeer || - l.hasPartialBuffer || - a > 1e3 * (this.allowP2pLimit + 1)) && - this.httpRangeSupported) - ); - } - return n.info(`prefetch ${e} wait for remain`), !0; - } - return this._searchAvailablePeers(e, t, r, i); - } - _searchAvailablePeers(e, t, r, i) { - if (i <= this.allowP2pLimit) return !1; - if (!this.hasIdlePeers || !this.peersHas(e, t)) return !1; - const n = this.peerManager.getPeersOrderByWeight(), - [s, a] = zt(n, e, t, r); - return ( - (this.targetPeers = { forwardPeer: s, reversePeer: a }), - [s, a].some((e) => !!e) - ); - } - reportTraffic(e, t, r) { - const { fetcher: i } = this.engine; - i && (e > 0 && i.reportFlow(e), t > 0 && i.reportDCTraffic(t, r)); - } - notifyAllPeers(e, t, r, i = Yt.COMPLETE) { - if (!r) return void this.logger.error("segId is required"); - if (this.downloadOnly) return; - const { live: n } = this.config; - if (this.bitset.has(e, t, i)) return; - const s = ((e, t, r) => `${e}-${t}-${r}`)(e, t, i); - let a; - i !== Yt.PARTIAL_REVERSE && (a = i === Yt.COMPLETE); - const o = this.requestingMap.get(ve(e, t)); - for (let l of this.getPeers()) - (o && o.hasPeer(l)) || - l.notifySet.has(s) || - l.bitset.hasCompleteOr(e, t, i) || - l.uploading || - (l.sendMsgHave(e, r, { - level: t, - reverse: i === Yt.PARTIAL_REVERSE, - complete: a, - }), - l.notifySet.add(s), - n && T(l.notifySet, 20)); - } - checkPeers() { - const { logger: e, config: t, engine: r } = this, - i = this.requestingMap.size; - if (i > 5 && (e.warn(`requestingMap size ${i}`), i > 9)) return; - if (!this.hasPeers) return; - const n = t.live; - if (this.fragLoading && !n) - return void e.warn("loading urgently, skip prefetch"); - const { currentLevel: s } = r; - if (0 === this.bitCounts.size(s)) return; - if ( - !n && - this.nextLostSN >= 0 && - this.nextLostSN >= this.currPlaySN - 10 - ) - return; - let a = this.peerManager.getPeersOrderByWeight(); - if (0 === a.length) return; - let o = 0, - { prefetchNum: l, endSN: h, startSN: u } = t; - if ( - (n && (l = 3), this.getBufferedDuration() < this.allowP2pLimit) - ) { - if (!n) return; - l = 1; - } - let d = 0, - c = this.loadingSN + 1; - if ((this.prefetchOnly && c++, !n)) - if (this.loadingSN >= h && !this.bufMgr.overflowed) c = u; - else { - const e = Math.min( - ...a - .filter((e) => e.endSN >= c) - .map((e) => (e ? e.startSN : 1 / 0)) - ); - if (!isFinite(e)) return; - c < e && (c = e); - } - for ( - ; - o < l && - d < this.maxPrefetchCount && - (n || !(c > h)) && - !(n && c > this.loadingSN + 2); - - ) { - if (this.bitset.has(c, s)) { - c++; - continue; - } - const t = ve(c, s); - if (this.bitCounts.has(c, s) && !this.requestingMap.has(t)) { - let r = [null, null]; - if (n) r = zt(a, c, s, void 0, !0); - else - for (let e of a) - if (e.bitset.has(c, s)) { - const t = e.bitset.getState(c, s); - let i; - (i = - t === Yt.COMPLETE - ? 0 === p(0, 1) - : t === Yt.PARTIAL_REVERSE), - (r[i ? 1 : 0] = e); - break; - } - if (r.some((e) => !!e)) { - const i = new pr( - this.coordinator, - this.logger, - c, - s, - void 0, - this.httpRangeSupported - ); - this._setupSynthesizer(i), - this.requestingMap.set(t, i), - r.forEach((t, r) => { - if (t && o < l) { - o++; - const n = 1 === r; - i.setPeer(t, n), - t.requestDataBySN(c, !1, { level: s, reverse: n }), - e.info( - `request prefetch ${c} level ${s} from peer ${t.remotePeerId} downloadNum ${t.downloadNum} reverse ${n}` - ); - } - }), - (a = this.peerManager.getPeersOrderByWeight()); - } - } - if ((d++, c++, 0 === a.length)) break; - } - this.loadedPeerNum = o; - } - onBufferManagerLost(e, t, r, i) { - (this.currLostSN = e), - r && (this.nextLostSN = r), - this.bitset.delete(e, i), - this.bitCounts.delete(e, i); - } - cleanRequestingMap(e) { - const t = this.peerManager.getPeer(e); - if (t) - for (let [r, i] of this.requestingMap.internalMap) { - const n = r.split("-"), - s = Number(n[1]), - a = Number(n[0]); - i.hasPeerId(e) && - (this.logger.info(`delete ${e} in synthesizer`), - i.deletePeer(t), - this.bitCounts.decre(s, a), - t.bitset.delete(s, a)); - } - } - updateLoaded(e, t, r) { - this.bitset.hasCompleteOr(e, t) || - (this.bitset.add(e, t, r, Yt.COMPLETE), - this.bitCounts.delete(e, t)); - } - broadcastPlaylist(e, t) { - if (!this.config.live) return; - const r = (function (e) { - const t = e.split("\n"); - let r = 0, - i = 0; - for (let e of t) { - const t = /^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(e); - if (t && t[1]) { - r = parseInt(t[1], 10); - break; - } - } - for (let e of t) e.startsWith("#EXTINF") && i++; - return r + i - 1; - })(t); - if (!this.isMobileNet) - for (let i of this.getPeers()) i.sendMsgPlaylist(e, t, r); - this.playlistInfo.set(e, { seq: r, data: t }); - } - async getPlaylistFromPeer(e) { - if (!this.config.live) return null; - const { seq: t, data: r } = this.playlistInfo.get(e), - i = () => { - for (let r of this.getPeers()) { - const i = r.getLatestPlaylist(e, t); - if (i) - return ( - this.playlistInfo.set(e, i), (this.gotPlaylist = !0), i - ); - } - return null; - }; - let n = i(); - return ( - !n && - this.gotPlaylist && - (this.logger.info("getPlaylist wait 240ms"), - await m(240), - (this.gotPlaylist = !1), - (n = i())), - n - ); - } - getBufferedDuration() { - const { config: e } = this; - if (this.waitForPeer) return e.waitForPeerTimeout + e.httpLoadTime; - let { media: t, currentSrc: r } = this.engine; - if (!t || (t.src !== r && 0 === t.currentTime)) { - if ( - (this.logger.info("try get video element"), - (t = ce(this.config.mediaElem, r)), - !t) - ) - return 4; - this.engine.media = t; - } - let i = (function (e) { - let t = 0, - r = e.currentTime, - i = e.buffered; - for (let e = i.length - 1; e >= 0; e--) - if (r >= i.start(e) && r <= i.end(e)) { - t = i.end(e) - r; - break; - } - return e.playbackRate && (t /= e.playbackRate), t > 0 ? t : 0; - })(t); - return i; - } - destroy() { - super.destroy(), - this.requestingMap.clear(), - this.segmentBuilderMap.clear(), - this.engine.removeAllListeners(t.MEDIA_REBUFFER); - } - clearCache() { - "SegmentStore" === this.bufMgr.name - ? this.engine.emit(t.BM_FATAL_ERROR) - : this.bufMgr.clear(), - this.bitset.clear(); - } - _handleSynOutput(e, t, r, i) { - this.logger.info(`syn output ${e} http ${t} p2p ${r}`); - } - _handleSynError(e, t, r, i) { - const { logger: n, config: s } = this; - n.warn(`SYN_ERROR ${t}-${r} code ${i}`), - i !== sr && e.hasPartialBuffer && r > this.loadingSN - ? n.warn(`syn abort ${r} with partial buffer`) - : this.requestingMap.delete(ve(r, t)), - s.live && this.checkPeers(); - } - _notifySynthesizer(e, t, r, i, n, s = !0) { - const { logger: a } = this, - o = this.requestingMap.get(ve(r, i)); - if (!o) return; - const l = o.segId; - function h(n, s) { - s - ? e.requestDataById(t, r, !0, { level: i, reverse: n }) - : e.requestDataBySN(r, !1, { level: i, reverse: n }); - } - function u() { - return n === Yt.PARTIAL_FORWARD || n === Yt.COMPLETE; - } - function d() { - return n === Yt.PARTIAL_REVERSE || n === Yt.COMPLETE; - } - t && l && t !== l - ? a.warn(`notifySynthesizer segId ${t} not match ${l}`) - : o.isFull || - (!this.prefetchOnly && o.isAlmostDeadline) || - (o.isEmpty - ? o.hasForwardBuffer && d() - ? (o.setReversePeer(e), h(!0, s)) - : o.hasReverseBuffer && - u() && - (o.setForwardPeer(e), h(!1, s)) - : !o.hasForwardPeer && u() - ? (o.setForwardPeer(e), h(!1, s)) - : !o.hasReversePeer && - d() && - (o.setReversePeer(e), h(!0, s))); - } - _setupEngine() { - this.engine.on(t.MEDIA_REBUFFER, (e) => { - const { prefetchOnly: t, live: r } = this.config; - t || - r || - (e && - !this.prefetchOnly && - this.logger.warn("rebuffer reach limit"), - (this.prefetchOnly = e)); - }); - } - getStatsForPeer() { - const { currentLevel: e, media: t } = this.engine, - r = { level: e }; - if (t && !this.config.live) { - const { currentTime: e } = t; - r.pos = Math.round(e); - } - return r; - } - checkSynthesizer(e, t) { - const r = ve(e, t), - i = this.requestingMap.get(r); - i && - (0 === i.streamListeners - ? (this.logger.info(`destroy syn ${r} without listeners`), - this.requestingMap.delete(r)) - : this.logger.info(`keep syn ${r} with listeners`)); - } - setupSynForLoad(e, t, r, i, n) { - const { forwardPeer: s, reversePeer: a } = this.targetPeers, - o = ve(e, t); - let l = this.requestingMap.get(o); - if ( - (l - ? l.setExtra(i) - : ((l = new pr( - this.coordinator, - this.logger, - e, - t, - r, - this.httpRangeSupported, - i - )), - this._setupSynthesizer(l), - this.requestingMap.set(o, l)), - l.prefetchTimeout && n < 1e3 * this.allowP2pLimit && !s && !a) - ) - return l.setTimeout(0); - let h = !1; - n > 700 && - (s && - (l.setForwardPeer(s), - s.requestDataById(r, e, !0, { level: t }), - (h = !0)), - a && - (l.setReversePeer(a), - a.requestDataById(r, e, !0, { level: t, reverse: !0 }), - (h = !0))), - l.setTimeout(l.isEmpty ? 0 : n, h); - } - } - class yr { - constructor(t, r, i, n) { - (this.bufferList = []), - (this.streamListeners = []), - (this.finished = !1), - (this.packetSize = u), - (this.attachments = - n % this.packetSize == 0 - ? n / this.packetSize - : Math.floor(n / this.packetSize) + 1), - (this.pieceMsg = { - event: e.DC_PIECE, - attachments: this.attachments, - seg_id: i, - sn: t, - level: r, - size: n, - reverse: !1, - }), - (this.sink = (0, a.h)(0)), - (this.source = "HttpStream"); - } - receiveBytes(e, t) { - e.byteLength && - ((this.sink = a.h.concat([this.sink, e])), - this.bufferList.push(e), - t && (this.finished = !0), - this._notifyStreamListeners(e)); - } - getCompleteBuffer() { - return this.sink.buffer; - } - destroy() { - this.finished || this._notifyStreamListenersAbort(); - } - addStreamListener(e, t, r) { - this.streamListeners.push({ handler: r, peerId: t }); - } - removeStreamListener(e) { - const { sn: t, seg_id: r } = this.pieceMsg; - this.streamListeners = this.streamListeners.filter( - (i) => - i.peerId !== e || (i.handler(t, r, !0, "aborted by cancel"), !1) - ); - } - _notifyStreamListenersAbort() { - const { sn: e, seg_id: t } = this.pieceMsg; - for (let r of this.streamListeners) { - const { handler: i } = r; - i(e, t, !0, "aborted by httpLoader"); - } - this.streamListeners.length = 0; - } - _notifyStreamListeners(e) { - const { sn: t, seg_id: r } = this.pieceMsg; - for (let i of this.streamListeners) { - const { handler: n } = i; - n(t, r, !1, e, this.finished); - } - this.finished && (this.streamListeners.length = 0); - } - } - const Er = class extends vr { - constructor(e, t) { - super(e, t), - (this.fragloadTimeout = e.hlsjs ? 10 : 6.8), - (this.resolveMap = new Map()), - (this.segmentBypass = A(t.segmentBypass) - ? t.segmentBypass - : () => !1), - !0 === this.config.httpStreamEnabled - ? (this.streamEnabled = ur()) - : (this.streamEnabled = !1); - } - async handleGetMediaData(e, r) { - const { logger: i, engine: n, config: s } = this; - let { url: a, range: o } = e; - const l = this._getFrag(a, o); - if (!l) - return ( - i.warn(`cannot get frag ${a}`), - r.postMessage({ action: t.SW_GET_MEDIA }) - ); - if ( - (n.segmentLoadCount++, - this.segmentBypass(a, l.tagList) || - n.segmentLoadCount < s.startFromSegmentOffset) - ) - return ( - i.info(`bypass frag ${a}`), - r.postMessage({ action: t.SW_GET_MEDIA }) - ); - n.currentLevelIndex = l.level; - const { sn: h, level: u } = l, - d = this.config.segmentId(String(u), h, a, o), - c = d === this.loadingSegId; - if (c && (i.warn(`duplicate request ${d}`), this.prefetchOnly)) - return r.postMessage({ action: t.SW_GET_MEDIA }); - (this.loadingSN = h), - n.bufMgr && (n.bufMgr.loadingSN = h), - (this.loadingSegId = d); - const f = await this.bufMgr.getSegById(d); - if (f) - return ( - i.info(`bufMgr found seg sn ${h} segId ${d}`), - (l.loaded = f.data.byteLength), - (l.fromPeerId = f.fromPeerId), - n.emit(t.FRAG_LOADED, { - url: a, - sn: h, - level: u, - segId: d, - loaded: l.loaded, - duration: l.duration, - byP2p: !0, - fromPeerId: f.fromPeerId, - }), - this._onFragLoaded(a, l), - r.postMessage({ - action: t.SW_GET_MEDIA, - data: { url: a, buffer: f.data }, - }) - ); - if (((this.fragLoading = !0), this.prefetchOnly)) - return ( - i.info(`prefetchOnly, skip p2p load ${d}`), - this._loadFragByHttp( - l, - r, - h, - d, - a, - u, - o, - 1e3 * this.fragloadTimeout - ) - ); - let g = this.getBufferedDuration(); - g > this.fragloadTimeout && (g = this.fragloadTimeout), - i.info(`handleGetMediaData sn ${h} bufferedDuration ${g}`); - let p = 1e3 * (g - this.config.httpLoadTime); - p < 0 ? (p = 0) : p > 4e3 && (p = 4e3); - const m = ve(h, u); - if (this.resolveMap.has(h) || c) { - let e = this.requestingMap.get(m); - if (e || c) { - e && - this.httpRangeSupported && - (i.warn(`${h} is requesting, terminate syn wait for seg`), - e.terminate()); - let n = setTimeout(() => { - i.info(`notify seg ${h} timeout`), - (n = -1), - r.postMessage({ action: t.SW_GET_MEDIA }); - }, p); - this.bufMgr.once(`${t.BM_ADDED_SN_}${h}`, (e) => { - n < 0 || - (e && - e.level === u && - (clearTimeout(n), - i.info(`notify seg ${e.sn}`), - r.postMessage({ - action: t.SW_GET_MEDIA, - data: { url: a, buffer: e.data }, - }))); - }); - } else - i.warn(`${h} is requesting, fallback`), - r.postMessage({ action: t.SW_GET_MEDIA }); - } else if (this.hasAndSetTargetPeer(h, u, d, g)) { - (await this._loadFragByP2p(l, r, h, d, a, u, o, p)) || - (i.warn(`p2p timeout switch to http load ${d}`), - this._loadFragByHttp( - l, - r, - h, - d, - a, - u, - o, - 1e3 * this.fragloadTimeout - )); - } else - this._loadFragByHttp( - l, - r, - h, - d, - a, - u, - o, - 1e3 * this.fragloadTimeout - ); - } - _loadFragByHttp(e, r, i, n, s, a, o, l) { - const u = ve(i, a), - d = f(s, h, !0), - c = new dr({}); - let g = { url: d, ...L(o) }; - const p = { timeout: l }, - m = { - onError: (e) => { - e.text && this.logger.warn(e.text), - (this.fragLoading = !1), - r.postMessage({ action: t.SW_GET_MEDIA }); - }, - onTimeout: () => { - this.logger.warn("http load timeout"), - (this.fragLoading = !1), - r.postMessage({ action: t.SW_GET_MEDIA }); - }, - onSuccess: async (o, l) => { - (this.fragLoading = !1), this.notifyAllPeers(i, a, n); - const { data: h } = o; - let d = l.tload - l.trequest; - if ( - (this.logger.info( - `HTTP loaded ${n} time ${d} speed ${h.byteLength / d}` - ), - !(await this.bufMgr.hasSegOfId(n))) - ) { - const e = y(h).buffer, - t = new z(i, n, e, "", a); - await this.bufMgr.putSeg(t), - this.reportTraffic(h.byteLength, 0, 0); - } - this.segmentBuilderMap.delete(u), - (e.segId = n), - (e.loaded = h.byteLength), - this.engine.emit(t.FRAG_LOADED, { - url: s, - sn: i, - level: a, - segId: n, - loaded: e.loaded, - duration: e.duration, - byP2p: !1, - }), - this._onFragLoaded(s, e), - r.postMessage({ - action: t.SW_GET_MEDIA, - data: { url: s, buffer: h }, - }); - }, - }; - if (this.streamEnabled) { - let e; - (m.onBodyStart = (t) => { - !e && - t > 0 && - (this.isMobileNet || - this.notifyAllPeers(i, a, n, Yt.PARTIAL_FORWARD), - (e = new yr(i, a, n, t)), - this.segmentBuilderMap.has(u) || - this.segmentBuilderMap.set(u, e)); - }), - (m.onUpdate = (t, r, i) => { - if (i) - return ( - this.logger.warn(`loadFragByHttp ${n} aborted`), - void this.segmentBuilderMap.delete(u) - ); - e && e.receiveBytes(t, r); - }); - } - c.load(g, p, m); - } - async _loadFragByP2p(e, r, i, n, s, a, o, l) { - const { logger: h } = this; - h.info(`p2p load sn ${i} segId ${n} level ${a}`); - const u = await this.load(i, n, a, s, o, l); - if (u && u.data) { - const { data: o, fromPeerId: l, size: d } = u; - if ( - (h.info( - `p2p loaded segId ${n} level ${a} size ${o.byteLength}` - ), - !(await this.bufMgr.hasSegOfId(n))) - ) { - const e = new z(i, n, o, l, a); - h.info(`bufMgr putSeg ${i} level ${a}`), - await this.bufMgr.putSeg(e); - } - return ( - (e.loaded = o.byteLength), - (e.fromPeerId = l), - this.engine.emit(t.FRAG_LOADED, { - url: s, - sn: i, - level: a, - segId: n, - loaded: e.loaded, - duration: e.duration, - byP2p: !0, - fromPeerId: l, - }), - this._onFragLoaded(s, e), - r.postMessage({ - action: t.SW_GET_MEDIA, - data: { url: s, buffer: o, size: d }, - }), - !0 - ); - } - h.warn(`P2P timeout load segId ${n}`); - const d = await this.bufMgr.getSegById(n); - return ( - !!d && - ((this.fragLoading = !1), - h.info(`already loaded seg sn ${i} segId ${n}`), - r.postMessage({ - action: t.SW_GET_MEDIA, - data: { url: s, buffer: d.data }, - }), - !0) - ); - } - notifySWMessage(e, r, i) { - if (e === t.SW_GET_MEDIA) - this.engine.fetcher && this.engine.fetcher.increMediaRequests(), - this.handleGetMediaData(r, i); - else this.logger.warn(`unknown action ${e}`); - } - _getFrag(e, t) { - return t && (e = `${e}|${t}`), this.fragMap.get(e); - } - destroy() { - super.destroy(), this.logger.warn("destroy HlsSwScheduler"); - } - _onFragLoaded(e, t) { - if ((this.updateLoaded(t.sn, t.level, t.segId), !this.engine)) - return; - const { media: r, targetDuration: i } = this.engine; - !this.config.live && - r && - i && - (this.currPlaySN = Math.ceil(r.currentTime / i)); - } - load(e, t, r, i, n, s) { - const { logger: a, config: o } = this; - let l = { - ...L(n), - proxied: !0, - url: i, - segId: t, - httpLoadTime: 1e3 * o.httpLoadTime, - }; - this.setupSynForLoad(e, r, t, l, s); - const h = new Promise((i) => { - const n = { resolve: i, sn: e, level: r, segId: t }; - this.resolveMap.set(e, n); - }); - return (this.targetPeers = {}), h; - } - _setupSynthesizer(e) { - e.on(t.SYN_OUTPUT, async (t, r) => { - const { config: i, logger: n } = this, - { segId: s, sn: a, data: o, level: l } = t, - { speed: h, http: u, p2p: d, underused: c } = r; - this._handleSynOutput(s, u, d, c); - const f = this.resolveMap.has(a); - f && (this.fragLoading = !1); - if (i.validateSegment(s, new Uint8Array(o))) { - this.notifyAllPeers(a, l, s), - this.bitset.has(a, l) || this.reportTraffic(u, d, h); - const r = e.getFromPeerId(); - if (f) { - n.info(`receive criticalSeg seg_id ${s}`); - const e = this.resolveMap.get(a); - this.resolveMap.delete(a), - e.resolve({ data: o, fromPeerId: r }); - } else - this.bitset.has(a, l) || - (e.detachPeers(), - await this.bufMgr.putSeg(t), - this.updateLoaded(a, l, s)); - } else if ((n.error(`segment ${s} validate failed`), f)) { - const e = this.resolveMap.get(a); - this.resolveMap.delete(a), e.resolve(); - } - this.requestingMap.delete(ve(a, l)), - i.live && this.checkPeers(); - }).on(t.SYN_ERROR, (t, r) => { - const { sn: i, level: n } = t; - if (this.resolveMap.has(i)) { - const e = this.resolveMap.get(i); - this.resolveMap.delete(i), e.resolve(); - } - this._handleSynError(e, n, i, r); - }); - } - _handleDCHave(e, t, r, i, n) { - this._notifySynthesizer(e, i, t, r, n, this.resolveMap.has(t)), - this.config.live && - W(() => { - this.checkPeers(); - }); - } - }, - Sr = "2.7.10"; - class Tr extends Dt { - static get name() { - return "HlsSwP2pEngine"; - } - static isServiceWorkerSupported() { - return "serviceWorker" in navigator; - } - constructor(e = {}, r = null) { - super(e, r), - (this.swSupported = self.isSecureContext), - (this.levels = []), - (this.bypassLevels = []), - (this.currentLevelIndex = 0), - (this.currentSrc = ""), - (this.swVersion = ""), - (this.media = ce(this.config.mediaElem)), - (this.workerKeepAliveInterval = null), - (this.fragMap = new Map()), - (this.engineName = Tr.name), - Tr.isServiceWorkerSupported() || - ((this.swSupported = !1), - console.warn("service worker is not supported")), - r && - (r.once("hlsDestroying", () => { - this.destroy(), (this.hlsjs = null); - }), - r.on(this.HLSEvents.ERROR, this._onHlsError.bind(this))); - const { - channelIdMaker: i, - signalId: n, - browserInfo: s, - } = this.setup(); - if ( - ((this.onLevelLoaded = (e) => { - const { config: r } = this, - a = e.live; - (r.live = a), - (this.targetDuration = e.averagetargetduration), - (this.browserInfo = { - ...s, - live: a, - abr: this.multiBitrate || void 0, - type: "hls_sw", - }), - (this.channel = `${i(this.currentSrc)}|${n}[${Z.VERSION}]`), - this.setupElectron(); - const o = this.initLogger(); - o.info("use HlsSwP2pEngine"), - o.info( - `engine version: ${ue.version} hls-proxy version: ${this.swVersion}` - ), - o.info(`channel ${this.channel}`), - a || - ((r.startSN = e.startSN), - (r.endSN = e.endSN), - o.info(`startSN ${e.startSN} endSN ${e.endSN}`)), - this._init(this.channel, this.browserInfo), - this.off(t.LEVEL_LOADED, this.onLevelLoaded); - }), - 0 === this.config.httpLoadTime && - (this.config.live - ? this.on(t.LEVEL_LOADED, (e) => { - const { - fragments: t, - averagetargetduration: r, - startSN: i, - } = e; - this.config.httpLoadTime = this.determineHttpLoadTime( - t, - r, - i - ); - }) - : (this.config.httpLoadTime = 3.5)), - this.on(t.LEVEL_LOADED, this.onLevelLoaded), - (this.onManifestParsed = (e, r) => { - (this.multiBitrate = e.length > 1), - (this.currentSrc = r), - this.off(t.MANIFEST_PARSED, this.onManifestParsed); - }), - this.on(t.MANIFEST_PARSED, this.onManifestParsed), - (this.onFragLoaded = ({ url: e }) => { - this.curTsUri = e; - const { config: t } = this; - !this.rangeTested && - t.useHttpRange && - (this.startRangeRequestTimer(), - (this.rangeTested = !0), - t.logger && - t.logger.info( - JSON.stringify({ - engine: this.engineName, - ...this.browserInfo, - }) - )); - }), - this.on(t.FRAG_LOADED, this.onFragLoaded), - this.swSupported) - ) { - const { serviceWorker: e } = navigator; - e.onmessage = (e) => { - const { action: r, data: i } = e.data; - if (!r) return; - if (r === t.SW_DEBUG) { - const { level: e, text: t } = i; - return void ( - this.logger && this.logger[e](`hls-proxy: ${t}`) - ); - } - const n = e.ports[0]; - if (n) { - if ( - (this.logger && - this.logger.info(`engine onmessage action ${r}`), - n.postMessage({ action: r, pong: !0 }), - !this.p2pEnabled || !i) - ) - return n.postMessage({ action: r }); - switch (r) { - case t.SW_PLAYLIST: - this.handlePlaylist(i, n); - break; - case t.SW_GET_PLAYLIST: - this.handleGetPlaylist(i, n); - break; - default: - if (!this.scheduler) return n.postMessage({ action: r }); - this.scheduler.notifySWMessage(r, i, n); - } - } else - this.logger && - this.logger.error(`sender not found in action ${r}`); - }; - } - this.config.swAutoRegister && - this.registerServiceWorker() - .then(function (e) {}) - .catch((e) => { - console.warn("ServiceWorker registration failed ", e); - }); - } - get currentLevel() { - return this.currentLevelIndex; - } - watchRebuffering(e) { - this.offEventRebuffer = (function (e, t) { - let r = null; - const i = () => { - r || - (r = setTimeout(() => { - t(); - }, 2500)); - }, - n = () => { - null != r && (clearTimeout(r), (r = null)); - }; - return ( - e.addEventListener("waiting", i), - e.addEventListener("playing", n), - () => { - e.removeEventListener("waiting", i), - e.removeEventListener("playing", n); - } - ); - })(e, () => { - this.fetcher && this.fetcher.increRebuffers(); - }); - } - handlePlaylist(e, r) { - const { config: i, logger: n } = this, - { url: s, redirectedUrl: a, text: o, ver: l } = e; - return ( - (this.swVersion = l), - -1 === - (function (e, t) { - for ( - var r = e.split("."), i = t.split("."), n = 0; - n < Math.max(r.length, i.length); - n++ - ) { - var s = parseInt(r[n] || 0), - a = parseInt(i[n] || 0); - if (s < a) return -1; - if (s > a) return 1; - } - return 0; - })(l, Sr) - ? (console.warn(`hls-proxy.js version should >= ${Sr}`), - r.postMessage({ action: t.SW_PLAYLIST })) - : this.bypassLevels.indexOf(b(s)) >= 0 - ? (n && n.warn("bypass audio track"), - r.postMessage({ action: t.SW_PLAYLIST })) - : (r.postMessage({ - action: t.SW_PLAYLIST, - data: { - active: !0, - debug: n && n.isDebugLevel, - sharePlaylist: !!i.sharePlaylist, - }, - }), - this._parsePlaylist(o, b(s), a), - void ( - this.workerKeepAliveInterval || - navigator.serviceWorker.getRegistration().then((e) => { - const t = () => - e && e.active && "activated" === e.active.state; - if (!i.live && t()) { - const r = new URL(e.scope); - this.pathname = r.pathname + h; - const i = (e) => { - clearInterval(this.workerKeepAliveInterval), - (this.workerKeepAliveInterval = null); - const t = `keep alive failed ${e}`; - n && - (n.error(t), - n.report(t, "SWKeepAlive", this.peerId, "2.12.15")); - }; - this.workerKeepAliveInterval = setInterval(() => { - var e; - t() - ? ((e = this.pathname), - new Promise((t, r) => { - fetch(`${e}/keepalive/`) - .then((e) => { - if (e.ok) return e.text(); - throw new Error("keepalive failed"); - }) - .then((e) => { - if ("" !== e.trim()) - throw new Error( - "not valid keepalive response" - ); - t(); - }) - .catch((e) => { - r(e); - }); - })).catch((e) => { - i(e); - }) - : i("sw not activated`"); - }, 15e3); - } - }) - )) - ); - } - _parsePlaylist(e, r, i, n = !1) { - const s = r; - i && (r = i); - const { config: a, logger: o } = this; - if ( - e.indexOf("#EXTINF:") > 0 || - e.indexOf("#EXT-X-TARGETDURATION:") > 0 - ) { - let i = 0; - const o = qt.parseLevelPlaylist(e, r); - this.levels.length > 0 - ? ((i = this.levels.indexOf(b(o.url))), - -1 === i - ? (this.restartP2p(), (this.currentSrc = s), (i = 0)) - : (this.currentLevelIndex = i)) - : ("" !== this.currentSrc && - s !== this.currentSrc && - this.restartP2p(), - (this.currentSrc = s), - (this.levels = [b(r)])), - this.emit(t.LEVEL_LOADED, o), - a.live && S(this.fragMap, 200), - o.fragments.forEach((e) => { - e.level = i; - let t = l().buildAbsoluteURL(e.baseurl, e.relurl, { - alwaysNormalize: !0, - }); - const r = e.byteRange; - 2 === r.length && (t = `${t}|bytes=${r[0]}-${r[1] - 1}`), - this.fragMap.set(t, e); - }), - !n && - a.sharePlaylist && - this.scheduler && - !this.scheduler.isMobileNet && - this.scheduler.broadcastPlaylist(b(r), e); - } else { - const i = qt.parseMasterPlaylist(e, r); - "" !== this.currentSrc && this.restartP2p(), - i.length > 0 && - (i.sort((e, t) => e.bitrate - t.bitrate), - (this.levels = i.map((e) => b(e.url))), - ["AUDIO", "SUBTITLES", "CLOSED-CAPTIONS"].forEach((t) => { - qt.parseMasterPlaylistMedia(e, r, t).forEach((e) => { - e.url && this.bypassLevels.push(b(e.url)); - }); - })), - this.emit(t.MANIFEST_PARSED, i, s); - } - this._setupSegmentId(); - } - async handleGetPlaylist(e, r) { - const { config: i, logger: n } = this; - if (!n) return r.postMessage({ action: t.SW_GET_PLAYLIST }); - const { scheduler: s } = this; - if (!s) return void n.warn("scheduler not found"); - const { url: a } = e, - o = b(a); - if (s.playlistInfo.has(o)) { - const e = await s.getPlaylistFromPeer(o); - if (e && e.data) { - const { data: i, seq: s } = e; - return ( - n.info(`got playlist from peer seq ${s}`), - r.postMessage({ - action: t.SW_GET_PLAYLIST, - data: { text: i }, - }), - void this._parsePlaylist(i, b(a), void 0, !0) - ); - } - } - return r.postMessage({ action: t.SW_GET_PLAYLIST }); - } - async registerServiceWorker() { - const { logger: e, config: t } = this; - if (!this.swSupported) { - let e = "sw is not supported"; - return ( - E || - ((e = "https is required when using ServiceWorker"), - console.warn(e)), - Promise.reject(e) - ); - } - return ( - (this.media = ce(t.mediaElem)), - this.media || (e && e.warn("no video element found")), - Ir.registerServiceWorker(t) - ); - } - async unregisterServiceWorker() { - clearInterval(this.workerKeepAliveInterval), - (this.workerKeepAliveInterval = null); - const e = "serviceWorker is not registered"; - return new Promise((t, r) => { - const { serviceWorker: i } = navigator; - i || r(e), - i.getRegistration().then((i) => { - i ? i.unregister().then(t).catch(r) : r(e); - }); - }); - } - async _init(e, t) { - const { logger: r, config: i } = this; - if (!this.p2pEnabled || "object" != typeof self) return; - this.mediaTimer = setInterval(() => { - const e = () => this.hlsjs && this.hlsjs.media; - if (this.media) { - const t = e(); - t && this.media !== t && (this.media = t), - clearInterval(this.mediaTimer), - (this.rubufferTimer = setTimeout(() => { - this.watchRebuffering(this.media); - }, 15e3)); - } else this.media = e() || ce(i.mediaElem); - }, 3e3); - let n = new Er(this, i); - n.fragMap = this.fragMap; - try { - await super._init(e, n, t); - } catch (e) { - return void (r && r.error(e)); - } - (n.server = this.fetcher), - (this.scheduler = n), - this.p2pEnabled && - !this.tracker.connected && - this.tracker.resumeP2P(); - } - restartP2p() { - this.logger && this.logger.warn("restart P2P"), - this.disableP2P(), - this.enableP2P(), - this.on(t.LEVEL_LOADED, this.onLevelLoaded), - this.on(t.MANIFEST_PARSED, this.onManifestParsed), - this.on(t.FRAG_LOADED, this.onFragLoaded); - } - enableP2P() { - return this.p2pEnabled - ? null - : (this.logger && this.logger.info("enable P2P"), - (this.config.p2pEnabled = this.p2pEnabled = !0), - this); - } - disableP2P() { - this.logger && this.logger.warn("disable P2P"), - clearInterval(this.mediaTimer), - clearTimeout(this.rubufferTimer), - this.offEventRebuffer && this.offEventRebuffer(), - this.p2pEnabled && - ((this.config.p2pEnabled = this.p2pEnabled = !1), - this.tracker && - this.tracker instanceof kt && - (this.tracker.stopP2P(), - (this.tracker = {}), - (this.fetcher = null), - this.bufMgr.destroy(), - (this.bufMgr = null))), - (this.levels = []), - (this.currentLevelIndex = 0), - (this.lastLevel = 0), - (this.multiBitrate = !1), - (this.rangeTested = !1), - (this.currentSrc = ""), - (this.media = void 0), - (this.config.live = !1), - this.removeAllListeners(t.MANIFEST_PARSED), - this.removeAllListeners(t.LEVEL_LOADED), - this.removeAllListeners(t.FRAG_LOADED), - clearInterval(this.workerKeepAliveInterval), - (this.workerKeepAliveInterval = null); - } - destroy() { - this.swSupported && (navigator.serviceWorker.onmessage = void 0), - super.destroy(); - } - } - const _r = Tr; - function Lr(e, t, r = "main") { - return "main" !== r; - } - function br(e, t) { - let r, i, n, s, a; - const o = performance.now(); - (r = o - 300), - (i = o - 200), - (n = o), - (e.trequest = r), - (e.tfirst = i), - (e.tload = n), - (e.loading = { first: r, start: i, end: n }), - (s = a = t), - (e.loaded = s), - (e.total = a); - } - const Rr = class extends vr { - constructor(e, t) { - super(e, t), - (this.isHlsjs = !0), - (this.waitForPeer = t.waitForPeer || !1), - (this.waitForPeerTimeout = t.waitForPeerTimeout), - (this.waitingPeers = 0), - (this.waitingSeg = {}), - (this.requestedSet = new Set()); - } - startWaitPeerTimer() { - this.waitForPeer && - (this.waitForPeerTimer = setTimeout(() => { - this.waitForPeer && - ((this.waitForPeer = !1), this.emit(t.SCH_WAIT_PEER)); - }, 1e3 * (this.waitForPeerTimeout + 0))); - } - updatePlaySN(e) { - this.currPlaySN = e; - } - load(e, t, r) { - const { logger: i, config: n } = this; - this.context = e; - const { rangeStart: s, rangeEnd: a, url: o } = e, - l = e.frag, - { segId: h, sn: u, level: d } = l; - (this.callbacks = r), - (this.stats = C()), - (this.criticalSeg = { sn: u, level: d, segId: h }); - let c = e.defaultTimeout - 1e3 * n.httpLoadTime; - const f = { - rangeStart: Number(s), - rangeEnd: Number(a), - url: o, - httpLoadTime: 1e3 * n.httpLoadTime, - xhrSetup: n.xhrSetup, - segId: h, - headers: - Object.keys(e.headers || {}).length > 0 ? e.headers : void 0, - }; - this.setupSynForLoad(u, d, h, f, c), (this.targetPeers = {}); - } - waitPeerNotifier() { - return new Promise((e) => { - this.waitForPeer || e(), - setTimeout(e, 1e3 * this.waitForPeerTimeout), - this.once(t.SCH_WAIT_PEER, e); - }); - } - addPeer(e) { - if ((super.addPeer(e), this.waitForPeer)) { - const { level: r, sn: i } = this.waitingSeg, - n = e.remotePeerId; - e.bitset.has(i, r) && i > 0 - ? (this.logger.info( - `found initial seg ${r}-${i} from peer ${n}` - ), - this.emit(t.SCH_WAIT_PEER)) - : this.waitingPeers === this.peersNum && - this.emit(t.SCH_WAIT_PEER); - } - } - notifyPeersLoaded(e) { - this.logger.info(`notifyPeersLoaded ${e}`), - this.waitForPeer && - (0 === e - ? ((this.waitForPeer = !1), this.emit(t.SCH_WAIT_PEER)) - : (this.waitingPeers = e)); - } - destroy() { - super.destroy(), - this.logger.warn("destroy HlsjsScheduler"), - clearTimeout(this.waitForPeerTimer); - } - _setupDC(e) { - super._setupDC(e); - } - _setupSynthesizer(e) { - e.on(t.SYN_OUTPUT, async (t, r) => { - const { config: i, logger: n } = this, - { segId: s, sn: a, data: o, level: l } = t, - { speed: h, http: u, p2p: d, underused: c } = r; - this._handleSynOutput(s, u, d, c); - const f = this.criticalSeg && this.criticalSeg.segId === s; - if (i.validateSegment(s, new Uint8Array(o))) { - this.notifyAllPeers(a, l, s), - this.bitset.has(a, l) || this.reportTraffic(u, d, h); - const r = e.getFromPeerId(); - if (f) { - n.info(`receive criticalSeg seg_id ${s}`); - let { stats: e } = this; - (e.tload = e.loading.end = performance.now()), - (e.loaded = e.total = o.byteLength), - (this.criticalSeg = null); - const { frag: t } = this.context; - (t.fromPeerId = r), - (t.loadByP2P = !0), - this.callbacks.onSuccess( - { data: o, url: this.context.url }, - e, - this.context - ), - (this.callbacks = void 0); - } else - this.bitset.has(a, l) || - (e.detachPeers(), - await this.bufMgr.putSeg(t), - this.updateLoaded(a, l, s)); - } else - n.error(`segment ${s} validate failed`), - f && this.callbacks.onTimeout(this.stats, this.context, null); - this.requestingMap.delete(ve(a, l)), i.live && this.checkPeers(); - }) - .on(t.SYN_ERROR, (t, r) => { - const { sn: i, level: n } = t; - this.criticalSeg && - this.criticalSeg.sn === i && - ((this.criticalSeg = null), - this.callbacks.onTimeout(this.stats, this.context, null)), - this._handleSynError(e, n, i, r); - }) - .on( - t.SYN_PROGRESS, - ({ total: e, loaded: t, first: r, segId: i }) => { - let { stats: n } = this; - r && - n && - (n.tfirst = n.loading.first = - Math.max(n.trequest, performance.now())); - this.criticalSeg && - this.criticalSeg.segId === i && - this.callbacks && - this.callbacks.onLoaded && - this.callbacks.onLoaded( - { total: e, loaded: t, first: r }, - this.context - ); - } - ); - } - _setupEngine() { - super._setupEngine(), - this.engine - .on( - t.FRAG_LOADING, - ({ sn: e, segId: t, byHttp: r, level: i }) => { - (this.loadingSN = e), - (this.loadingSegId = t), - (this.fragLoading = !0), - r && this.checkSynthesizer(e, i); - } - ) - .on( - t.FRAG_LOADED, - ({ sn: e, segId: t, byP2p: r, level: i }) => { - (this.fragLoading = !1), - r || this.checkSynthesizer(e, i), - this.updateLoaded(e, i, t); - } - ) - .on(t.FRAG_CHANGED, ({ sn: e }) => { - this.updatePlaySN(e); - }); - } - _handleDCHave(e, t, r, i, n) { - this._notifySynthesizer( - e, - i, - t, - r, - n, - this.criticalSeg && this.criticalSeg.segId === i - ), - this.config.live && - W(() => { - this.checkPeers(); - }); - } - }; - class Ar extends Dt { - static get name() { - return "HlsjsP2pEngine"; - } - constructor(e, t = {}) { - if ((super(t, e), !e)) - throw new TypeError("hlsjs instance is null"); - (this.config.xhrSetup = e.config.xhrSetup), - (this.engineName = Ar.name), - (this._onFragLoading = this._onFragLoading.bind(this)), - (this._onFragLoaded = this._onFragLoaded.bind(this)), - (this._onFragChanged = this._onFragChanged.bind(this)), - (this._onHlsError = this._onHlsError.bind(this)), - (this._onLevelUpdated = this._onLevelUpdated.bind(this)); - const { - channelIdMaker: r, - signalId: i, - browserInfo: n, - } = this.setup(); - this.config.waitForPeer && this.config.sourceUrl - ? ((this.config.trickleICE = !0), - (this.config.httpRangeSupported = !0), - this._startEngine( - this.config.sourceUrl, - this.config.live, - n, - r, - i - )) - : (this.config.waitForPeer = !1); - const s = (t, a) => { - if (!a) return; - const { config: o } = this, - l = a.details, - h = l.live; - o.waitForPeer - ? (this.tracker && - this.tracker.scheduler && - this.tracker.scheduler.startWaitPeerTimer(), - this.logger.info("waitForPeer mode")) - : this._startEngine(this.hlsjs.url, h, n, r, i, l), - e.off(this.HLSEvents.LEVEL_LOADED, s); - }; - e.on(this.HLSEvents.LEVEL_LOADED, s); - const a = (e, t) => { - if (!t) return; - const { config: r } = this, - { - fragments: i, - averagetargetduration: n, - startSN: s, - } = t.details; - r.httpLoadTime = this.determineHttpLoadTime(i, n, s); - }; - 0 === this.config.httpLoadTime && - (this.config.live - ? e.on(this.HLSEvents.LEVEL_LOADED, a) - : (this.config.httpLoadTime = 3.5)); - const o = (t, r) => { - this._setupSegmentId(); - const i = r.levels.length; - (this.multiBitrate = i > 1), - e.off(this.HLSEvents.MANIFEST_PARSED, o); - }; - e.on(this.HLSEvents.MANIFEST_PARSED, o), - e.on(this.HLSEvents.DESTROYING, () => { - e.off(this.HLSEvents.LEVEL_LOADED, a), this.destroy(); - }); - } - _startEngine(e, t, r, i, n, s = {}) { - const { config: a } = this; - (a.live = t), - (this.browserInfo = { - ...r, - live: t, - abr: this.multiBitrate || void 0, - type: "hls", - }), - (this.channel = `${i(e)}|${n}[${Z.VERSION}]`), - this.setupElectron(); - const o = this.initLogger(); - o.info("use HlsjsP2pEngine"), - (this.logger = o), - o.info(`channel ${this.channel}`), - t || - ((a.startSN = s.startSN), - (a.endSN = s.endSN), - o.info(`startSN ${s.startSN} endSN ${s.endSN}`)), - (this.eventListened = !1), - this._init(this.channel, this.browserInfo); - } - async _init(e, t) { - const { logger: r, config: i } = this; - if (!this.p2pEnabled || "object" != typeof self) return; - (this.media = this.hlsjs.media), - this.media && (this.currentSrc = this.media.src); - const n = new Rr(this, i); - this.eventListened || - (this._updateHlsEventsHandlers(), (this.eventListened = !0)); - try { - await super._init(e, n, t); - } catch (e) { - return void r.error(e); - } - (this.hlsjs.config.fLoader = (function (e, t, r, i) { - return class extends s() { - constructor(n) { - super(), - (this.logger = r), - (this.isHlsV0 = i.isHlsV0), - (this.bufMgr = e.bufMgr), - (this.streamEnabled = i.httpStreamEnabled && ur()), - (this.httpLoader = this.streamEnabled - ? new dr(n) - : new n.loader(n)), - (this.p2pEnabled = i.p2pEnabled), - (this.isLive = i.live), - (this.scheduler = e), - (this.fetcher = t), - (this.segmentId = i.segmentId), - (this.blockTypes = i.p2pBlackList), - (this.stats = this.httpLoader.stats || C()), - (this.enableWorker = n.enableWorker), - (this.segmentBypass = A(i.segmentBypass) - ? i.segmentBypass - : () => !1), - (this.prefetchOnly = i.prefetchOnly), - (this.startFromSegmentOffset = i.startFromSegmentOffset), - e.engine.segmentLoadCount++, - (this.segmentLoadCount = e.engine.segmentLoadCount); - } - destroy() { - this.httpLoader.destroy(); - } - abort() { - this.httpLoader.abort(); - } - async load(e, t, r) { - const { logger: i, scheduler: n } = this, - { url: s, frag: a } = e; - this.isHlsV0 || (a.stats = this.stats); - const { level: o, sn: l, type: h, tagList: u } = a; - let d = a.segId; - if (!d) { - let t; - e.rangeEnd && - (t = "bytes=" + e.rangeStart + "-" + (e.rangeEnd - 1)), - (d = a.segId = this.segmentId(String(o), l, s, t)); - } - const c = () => ( - (a.loadByHTTP = !0), this.httpLoader.load(e, t, r) - ); - if ( - !s || - !Number.isInteger(l) || - Lr(0, this.blockTypes, h) || - this.segmentBypass(s, u) - ) - return i.info(`HTTP load blockType ${s}`), c(); - if ( - (this.fetcher.increMediaRequests(), - this.isLive && n.requestedSet.has(d)) - ) - return i.warn(`HTTP load duplicated ${s}`), c(); - if (this.segmentLoadCount < this.startFromSegmentOffset) - return c(); - t.maxRetry = 2; - const f = n.getBufferedDuration(), - g = await this.bufMgr.getSegById(d); - if (this.p2pEnabled && g) { - i.info(`bufMgr found seg sn ${l} segId ${d} level ${o}`); - let t = y(g.data).buffer, - n = { url: e.url, data: t }; - return ( - br(this.stats, g.size), - (a.loaded = g.size), - (a.loadByP2P = !0), - (a.fromPeerId = g.fromPeerId), - void W(() => { - !this.isHlsV0 && - r.onProgress && - r.onProgress(this.stats, e, n.data), - r.onSuccess(n, this.stats, e); - }) - ); - } - (!this.prefetchOnly && - this.p2pEnabled && - n.hasAndSetTargetPeer(l, o, d, f)) || - (!this.prefetchOnly && - n.waitForPeer && - (i.warn("waitPeerNotifier start"), - (n.waitingSeg = { sn: l, level: o }), - await n.waitPeerNotifier(), - i.warn("waitPeerNotifier end"), - (n.waitingSeg = {}), - this.p2pEnabled && n.hasAndSetTargetPeer(l, o, d, f))) - ? this.loadFragByP2p(e, t, r, d, f) - : (i.info( - `fragLoader load ${d} at ${l} level ${o} buffered ${ - 1e3 * f - }` - ), - this.loadFragByHttp(e, t, r, d)); - } - loadFragByHttp(e, t, r, i) { - const { logger: n, scheduler: s } = this, - { segmentBuilderMap: a } = s, - o = e.frag, - { sn: l, level: h } = o, - u = ve(l, h); - if (this.streamEnabled) { - let e; - (r.onUpdate = (t, r, s) => { - if (s) - return ( - n.warn(`loadFragByHttp ${i} aborted`), - void a.delete(u) - ); - e && e.receiveBytes(t, r); - }), - (r.onBodyStart = (t) => { - !e && - t > 0 && - ((e = new yr(l, h, i, t)), - a.has(u) || a.set(u, e), - s.isMobileNet || - s.notifyAllPeers(l, h, i, Yt.PARTIAL_FORWARD)); - }); - } - const d = r.onSuccess; - r.onSuccess = async (e, t, r) => { - const { data: o } = e; - let c = t.tload - t.trequest; - if ( - (n.info( - `HTTP loaded ${i} time ${c} speed ${o.byteLength / c}` - ), - !(await this.bufMgr.hasSegOfId(i))) - ) { - const e = y(o).buffer, - t = new z(l, i, e, this.fetcher.peerId, h); - await this.bufMgr.putSeg(t); - } - a.delete(u), - this.fetcher.reportFlow(t.total), - s.notifyAllPeers(l, h, i), - d(e, t, r); - }; - const c = r.onProgress; - c && - (r.onProgress = (e, t, r) => { - (o.loaded = e.total), - c(e, t, r && this.enableWorker ? y(r).buffer : r); - }), - (e.frag.loadByHTTP = !0), - this.httpLoader.load(e, t, r); - } - loadFragByP2p(e, t, r, i, n) { - const { logger: s } = this, - a = e.frag; - let o; - (o = t.loadPolicy - ? t.loadPolicy.maxTimeToFirstByteMs - : t.timeout), - (!o || o > 1e3 * n) && (o = 1e3 * n), - (e.defaultTimeout = o), - this.scheduler.load(e, t, r); - const l = r.onSuccess, - h = r.onTimeout; - (r.onTimeout = (e, n) => { - s.warn( - `P2P timeout switched to HTTP load ${a.relurl} at ${a.sn}` - ), - (r.onSuccess = l), - this.loadFragByHttp(n, t, r, i), - (r.onTimeout = h); - }), - (r.onSuccess = async (e, t, n) => { - if (!(await this.bufMgr.hasSegOfId(i))) { - const t = y(e.data).buffer, - r = new z( - a.sn, - i, - t, - a.fromPeerId || this.fetcher.peerId, - a.level - ); - await this.bufMgr.putSeg(r); - } - a.loadByP2P || this.fetcher.reportFlow(t.total), - (a.loaded = t.loaded), - s.info( - `${ - a.loadByP2P ? "P2P" : "HTTP" - } loaded segment id ${i}` - ), - !this.isHlsV0 && - r.onProgress && - r.onProgress(t, n, e.data), - l(e, t, n); - }); - } - }; - })(n, this.fetcher, r, i)), - i.sharePlaylist && - (this.hlsjs.config.pLoader = (function (e, t, r) { - return class extends s() { - constructor(i) { - super(), - (this.logger = t), - (this.xhrLoader = new i.loader(i)), - (this.p2pEnabled = r.p2pEnabled), - (this.scheduler = e), - (this.stats = this.xhrLoader.stats || C()); - } - destroy() { - this.xhrLoader.destroy(); - } - abort() { - this.xhrLoader.abort(); - } - async load(e, t, r) { - const { logger: i } = this, - { url: n } = e, - s = b(n), - a = r.onSuccess; - if ( - ((r.onSuccess = (e, t, r) => { - this.scheduler && - !r.loadedByPeer && - this.scheduler.broadcastPlaylist(s, e.data), - a(e, t, r); - }), - this.scheduler && this.scheduler.playlistInfo.has(s)) - ) { - const t = await this.scheduler.getPlaylistFromPeer(s); - if (t && t.data) { - const { data: s, seq: a } = t; - i.info(`got playlist from peer seq ${a}`), - br(this.stats, s.length); - let o = { url: n, data: s }; - return ( - (e.loadedByPeer = !0), - void W(() => { - r.onSuccess(o, this.stats, e); - }) - ); - } - } - this.xhrLoader.load(e, t, r); - } - }; - })(n, r, i)), - (this.trackerTried = !1), - this.trackerTried || - this.tracker.connected || - !i.p2pEnabled || - (this.tracker.resumeP2P(), (this.trackerTried = !0)); - } - _onFragLoading(e, r) { - const i = r.frag; - let { sn: n, level: s, segId: a } = i; - if ( - !Lr(i.url, this.config.p2pBlackList, i.type) && - Number.isInteger(n) - ) { - if ( - (this.logger.info("loading frag " + n), - this.bufMgr && (this.bufMgr.loadingSN = n), - !a) - ) { - let e; - i._byteRange && - (e = "bytes=" + i._byteRange[0] + "-" + i._byteRange[1]); - let t = i.url; - this._setupSegmentId(), - (a = i.segId = this.config.segmentId(String(s), i.sn, t, e)); - } - this.emit(t.FRAG_LOADING, { - sn: n, - segId: a, - byHttp: i.loadByHTTP, - level: s, - }); - } - } - _onLevelUpdated(e, t) { - const { details: r } = t, - { hlsjs: i, config: n } = this; - if (!r.live) return; - const s = r.fragments.length, - a = s - 1; - i && - i.config.liveSyncDurationCount !== a && - "main" === r.fragments[0].type && - s > 4 && - (n.isHlsV0 || - (!i.userConfig.liveSyncDuration && - !i.userConfig.liveSyncDurationCount)) && - (this.logger.info(`set liveSyncDurationCount ${a}`), - (i.config.liveSyncDurationCount = a)); - } - _onFragLoaded(e, r) { - if (!this.p2pEnabled) return; - const { frag: i } = r; - this.curTsUri = i.url; - const { - sn: n, - segId: s, - loaded: a, - duration: o, - level: l, - fromPeerId: h, - loadByP2P: u, - url: d, - } = i, - { config: c, logger: f } = this; - this.tracker && - this.tracker.scheduler && - (T(this.tracker.scheduler.requestedSet, 50), - this.tracker.scheduler.requestedSet.add(s)), - Lr(i.url, c.p2pBlackList, i.type) || - (this.bufMgr && - this.bufMgr.loadingSN >= 0 && - this.emit(t.FRAG_LOADED, { - url: d, - sn: n, - level: l, - segId: s, - loaded: a, - duration: o, - byP2p: !!u, - fromPeerId: h, - }), - !this.rangeTested && - c.useHttpRange && - (this.startRangeRequestTimer(), - (this.rangeTested = !0), - f.info( - JSON.stringify({ - engine: this.engineName, - hlsjs: this.hlsjsVersion, - ...this.browserInfo, - }) - ))); - } - _onFragChanged(e, r) { - const { frag: i } = r; - if (!Lr(i.url, this.config.p2pBlackList, i.type)) { - this.logger.info("frag changed: " + i.sn); - const { sn: e, duration: r } = i; - this.emit(t.FRAG_CHANGED, { sn: e, duration: r }); - } - } - get currentLevel() { - const { currentLevel: e } = this.hlsjs; - return e >= 0 ? e : 0; - } - disableP2P() { - this.logger && this.logger.warn("disable P2P"), - this.p2pEnabled && - ((this.p2pEnabled = !1), - (this.config.p2pEnabled = this.p2pEnabled), - this.tracker && - (this.tracker.stopP2P(), - (this.tracker = {}), - (this.fetcher = null), - this.bufMgr.destroy(), - (this.bufMgr = null), - (this.hlsjs.config.fLoader = this.hlsjs.config.pLoader = - this.hlsjs.constructor.DefaultConfig.loader))); - } - _updateHlsEventsHandlers(e = !1) { - const t = this.hlsjs; - if (!t) return; - const r = e ? "off" : "on"; - t[r](this.HLSEvents.FRAG_LOADING, this._onFragLoading), - t[r](this.HLSEvents.FRAG_LOADED, this._onFragLoaded), - t[r](this.HLSEvents.FRAG_CHANGED, this._onFragChanged), - t[r](this.HLSEvents.ERROR, this._onHlsError), - t[r](this.HLSEvents.LEVEL_UPDATED, this._onLevelUpdated); - } - destroy() { - this._updateHlsEventsHandlers(!0), super.destroy(); - } - } - const wr = Ar; - class Pr { - static get Events() { - return t; - } - static get TrackerZone() { - return ue.TrackerZone; - } - static isSupported() { - return ue.isSupported() && (de() || _r.isServiceWorkerSupported()); - } - static isServiceWorkerSupported() { - return _r.isServiceWorkerSupported(); - } - static isMSESupported() { - return de(); - } - static getBrowser() { - return Q().getBrowser(); - } - static get ServiceWorkerEngine() { - return _r; - } - static get HlsjsEngine() { - return wr; - } - static async tryRegisterServiceWorker({ - swFile: e = "./sw.js", - swScope: t = "./", - } = {}) { - return Pr.registerServiceWorker({ swFile: e, swScope: t }); - } - static async registerServiceWorker({ - swFile: e = "./sw.js", - swScope: t = "./", - hlsjsInstance: r, - } = {}) { - const { serviceWorker: i } = navigator; - return !i || r - ? Promise.resolve() - : i - .getRegistration() - .then( - (r) => - r || - Promise.race([ - i.register(e, { scope: t }).then((e) => - (function (e) { - return new Promise((t, r) => { - const i = e.installing || e.waiting || e.active, - n = () => - "activated" === i.state && - (i.removeEventListener("statechange", n), - t(e), - !0); - n() || i.addEventListener("statechange", n); - }); - })(e) - ), - m(300), - ]) - ) - .catch(() => { - Promise.resolve(); - }); - } - constructor(e = {}) { - const { hlsjsInstance: t } = e; - delete e.hlsjsInstance; - const r = () => { - this._realEngine = new wr(t, e); - }, - i = () => { - this._realEngine = new _r(e, t); - }; - "1" !== c("_sw") - ? e.proxyFirst && t - ? _r.isServiceWorkerSupported() - ? i() - : r() - : !e.proxyOnly && de() && t - ? r() - : i() - : i(); - } - get realEngine() { - return this._realEngine; - } - get engineName() { - return this._realEngine.constructor.name; - } - once(e, t) { - return this._realEngine.once(e, t); - } - on(e, t) { - return this._realEngine.on(e, t); - } - off(e, t) { - return this._realEngine.off(e, t); - } - removeListener(e, t) { - return this._realEngine.removeListener(e, t); - } - removeAllListeners(e) { - return this._realEngine.removeAllListeners(e); - } - set p2pEnabled(e) { - this._realEngine.p2pEnabled = e; - } - get p2pEnabled() { - return this._realEngine.p2pEnabled; - } - enableP2P() { - this._realEngine.enableP2P(); - } - disableP2P() { - this._realEngine.disableP2P(); - } - destroy() { - this._realEngine.destroy(); - } - async registerServiceWorker() { - return A(this._realEngine.registerServiceWorker) - ? this._realEngine.registerServiceWorker() - : Promise.reject("Not supported by this engine"); - } - async unregisterServiceWorker() { - return A(this._realEngine.unregisterServiceWorker) - ? this._realEngine.unregisterServiceWorker() - : Promise.reject("Not supported by this engine"); - } - get version() { - return ue.version; - } - } - (Pr.version = ue.version), - (Pr.protocolVersion = Z.VERSION), - "object" == typeof self && (self.P2PEngineHls = Pr); - const Ir = Pr; - var Cr = r(251), - kr = r.n(Cr); - const Dr = { maxBufferLength: 12 }, - Mr = { maxBufferLength: 40 }; - class xr extends kr() { - static get P2PEvents() { - return Ir.Events; - } - static get P2pEngine() { - return Ir; - } - constructor(e = {}) { - let t = e.p2pConfig || {}; - const r = !1 === t.live ? Mr : Dr; - let i = JSON.parse(JSON.stringify(r)); - (i.maxBufferSize = 0), (i.enableWorker = !1); - for (let t in e) "p2pConfig" !== t && (i[t] = e[t]); - super(i), - (this._restartEvent = () => { - this.restartP2P(); - }), - Ir.isSupported() && - ((this._p2pEngine = new Ir({ ...t, hlsjsInstance: this })), - this._p2pEngine.on(Ir.Events.RESTART_P2P, this._restartEvent)), - this.on(kr().Events.DESTROYING, () => { - this._p2pEngine && - (this._p2pEngine.removeListener( - Ir.Events.RESTART_P2P, - this._restartEvent - ), - (this._p2pEngine.hlsjs = null), - (this._p2pEngine = null)); - }); - } - get p2pEngine() { - return this._p2pEngine; - } - enableP2P() { - this._p2pEngine && (this._p2pEngine = this._p2pEngine.enableP2P()); - } - disableP2P() { - this._p2pEngine && this._p2pEngine.disableP2P(); - } - restartP2P() { - this._p2pEngine && - (this._p2pEngine.disableP2P(), - setTimeout(() => { - this.enableP2P(); - }, 2e3), - this._p2pEngine.removeListener( - Ir.Events.RESTART_P2P, - this._restartEvent - )); - } - } - (xr.engineVersion = Ir.version), - (xr.protocolVersion = Ir.protocolVersion), - (xr.WEBRTC_SUPPORT = Ir.isSupported()); - const Or = xr; - })(), - (i = i.default) - ); - })() -); +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Hls=t():e.Hls=t()}(this,(()=>(()=>{var e={415:e=>{"use strict";var t,r="object"==typeof Reflect?Reflect:null,i=r&&"function"==typeof r.apply?r.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};t=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(r,i){function n(r){e.removeListener(t,s),i(r)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",n),r([].slice.call(arguments))}p(e,t,s,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&p(e,"error",t,r)}(e,n,{once:!0})}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function h(e,t,r,i){var n,s,a,h;if(o(r),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),a=s[t]),void 0===a)a=s[t]=r,++e._eventsCount;else if("function"==typeof a?a=s[t]=i?[r,a]:[a,r]:i?a.unshift(r):a.push(r),(n=l(e))>0&&a.length>n&&!a.warned){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,h=u,console&&console.warn&&console.warn(h)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=u.bind(i);return n.listener=r,i.wrapFn=n,n}function c(e,t,r){var i=e._events;if(void 0===i)return[];var n=i[t];return void 0===n?[]:"function"==typeof n?r?[n.listener||n]:[n]:r?function(e){for(var t=new Array(e.length),r=0;r0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var l=s[e];if(void 0===l)return!1;if("function"==typeof l)i(l,this,t);else{var h=l.length,u=g(l,h);for(r=0;r=0;s--)if(r[s]===t||r[s].listener===t){a=r[s].listener,n=s;break}if(n<0)return this;0===n?r.shift():function(e,t){for(;t+1=0;i--)this.removeListener(e,t[i]);return this},s.prototype.listeners=function(e){return c(this,e,!0)},s.prototype.rawListeners=function(e){return c(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},558:function(e){!function(t){var r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=a.normalizePath(n.path),a.buildURLFromParts(n)}var s=a.parseURL(t);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return r.alwaysNormalize?(s.path=a.normalizePath(s.path),a.buildURLFromParts(s)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(h.netLoc=o.netLoc,"/"!==s.path[0]))if(s.path){var u=o.path,d=u.substring(0,u.lastIndexOf("/")+1)+s.path;h.path=a.normalizePath(d)}else h.path=o.path,s.params||(h.params=o.params,s.query||(h.query=o.query));return null===h.path&&(h.path=r.alwaysNormalize?a.normalizePath(s.path):s.path),a.buildURLFromParts(h)},parseURL:function(e){var t=r.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(n,"");e.length!==(e=e.replace(s,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=a}()},251:e=>{!function t(r){var i;i=function(){"use strict";function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function i(t){for(var r=1;re.length)&&(t=e.length);for(var r=0,i=new Array(t);r1?t-1:0),i=1;i"):_}(t)}))}(e,"debug","log","info","warn","error");try{b.log('Debug logs enabled for "'+t+'" in hls.js version 1.5.13')}catch(e){b=L}}else b=L}var A=b,w=/^(\d+)x(\d+)$/,P=/(.+?)=(".*?"|.*?)(?:,|$)/g,I=function(){function e(t){"string"==typeof t&&(t=e.parseAttrList(t)),o(this,t)}var t=e.prototype;return t.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.optionalFloat=function(e,t){var r=this[e];return r?parseFloat(r):t},t.enumeratedString=function(e){return this[e]},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=w.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e){var t,r={};for(P.lastIndex=0;null!==(t=P.exec(e));){var i=t[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[t[1].trim()]=i}return r},a(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}]),e}();function C(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}var k=function(){function e(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){var r=t.attr;for(var i in r)if(Object.prototype.hasOwnProperty.call(e,i)&&e[i]!==r[i]){A.warn('DATERANGE tag attribute: "'+i+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=i;break}e=o(new I({}),r,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){var n=new Date(this.attr["END-DATE"]);m(n.getTime())&&(this._endDate=n)}}return a(e,[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){if(this._endDate)return this._endDate;var e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(m(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&m(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}]),e}(),D=function(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}},M="audio",x="video",O="audiovideo",F=function(){function e(e){var t;this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams=((t={})[M]=null,t[x]=null,t[O]=null,t),this.baseurl=e}return e.prototype.setByteRange=function(e,t){var r,i=e.split("@",2);r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]},a(e,[{key:"byteRange",get:function(){return this._byteRange?this._byteRange:[]}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=p.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}}]),e}(),N=function(e){function t(t,r){var i;return(i=e.call(this,r)||this)._decryptdata=null,i.rawProgramDateTime=null,i.programDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.stats=new D,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.urlId=0,i.type=t,i}l(t,e);var r=t.prototype;return r.setKeyFormat=function(e){if(this.levelkeys){var t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}},r.abortRequests=function(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()},r.setElementaryStreamInfo=function(e,t,r,i,n,s){void 0===s&&(s=!1);var a=this.elementaryStreams,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):a[e]={startPTS:t,endPTS:r,startDTS:i,endDTS:n,partial:s}},r.clearElementaryStreamInfo=function(){var e=this.elementaryStreams;e[M]=null,e[x]=null,e[O]=null},a(t,[{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{var t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!m(this.programDateTime))return null;var e=m(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t=Object.keys(this.levelkeys),r=t.length;if(r>1||1===r&&this.levelkeys[t[0]].encrypted)return!0}return!1}}]),t}(F),B=function(e){function t(t,r,i,n,s){var a;(a=e.call(this,i)||this).fragOffset=0,a.duration=0,a.gap=!1,a.independent=!1,a.relurl=void 0,a.fragment=void 0,a.index=void 0,a.stats=new D,a.duration=t.decimalFloatingPoint("DURATION"),a.gap=t.bool("GAP"),a.independent=t.bool("INDEPENDENT"),a.relurl=t.enumeratedString("URI"),a.fragment=r,a.index=n;var o=t.enumeratedString("BYTERANGE");return o&&a.setByteRange(o,s),s&&(a.fragOffset=s.fragOffset+s.duration),a}return l(t,e),a(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}]),t}(F),U=function(){function e(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}return e.prototype.reloaded=function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay},a(e,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&m(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}]),e}();function G(e){return Uint8Array.from(atob(e),(function(e){return e.charCodeAt(0)}))}function H(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(function(e){return e.charCodeAt(0)}))}var $="undefined"!=typeof self?self:void 0,K={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},W="org.w3.clearkey",V="com.apple.streamingkeydelivery",q="com.microsoft.playready",j="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Y(e){switch(e){case V:return K.FAIRPLAY;case q:return K.PLAYREADY;case j:return K.WIDEVINE;case W:return K.CLEARKEY}}var z="edef8ba979d64acea3c827dcd51d21ed";function X(e){switch(e){case K.FAIRPLAY:return V;case K.PLAYREADY:return q;case K.WIDEVINE:return j;case K.CLEARKEY:return W}}function Q(e){var t=e.drmSystems,r=e.widevineLicenseUrl,i=t?[K.FAIRPLAY,K.WIDEVINE,K.PLAYREADY,K.CLEARKEY].filter((function(e){return!!t[e]})):[];return!i[K.WIDEVINE]&&r&&i.push(K.WIDEVINE),i}var J,Z=null!=$&&null!=(J=$.navigator)&&J.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function ee(e,t,r){return Uint8Array.prototype.slice?e.slice(t,r):new Uint8Array(Array.prototype.slice.call(e,t,r))}var te,re=function(e,t){return t+10<=e.length&&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},ie=function(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===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},ne=function(e,t){for(var r=t,i=0;re(e,t);)i+=10,i+=se(e,t+6),ie(e,t+10)&&(i+=10),t+=i;if(i>0)return e.subarray(r,r+i)},se=function(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,(r|=(127&e[t+2])<<7)|127&e[t+3]},ae=function(e,t){return re(e,t)&&se(e,t+6)+10<=e.length-t},oe=function(e){for(var t=ue(e),r=0;r>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:h+=String.fromCharCode(s);break;case 12:case 13:a=e[u++],h+=String.fromCharCode((31&s)<<6|63&a);break;case 14:a=e[u++],o=e[u++],h+=String.fromCharCode((15&s)<<12|(63&a)<<6|63&o)}}return h};var ve=function(e){for(var t="",r=0;r>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function we(e,t){var r=[];if(!t.length)return r;for(var i=e.byteLength,n=0;n1?n+s:i;if(Te(e.subarray(n+4,n+8))===t[0])if(1===t.length)r.push(e.subarray(n+8,a));else{var o=we(e.subarray(n+8,a),t.slice(1));o.length&&Ee.apply(r,o)}n=a}return r}function Pe(e){var t=[],r=e[0],i=8,n=Le(e,i);i+=4;var s=0,a=0;0===r?(s=Le(e,i),a=Le(e,i+4),i+=8):(s=be(e,i),a=be(e,i+8),i+=16),i+=2;var o=e.length+a,l=_e(e,i);i+=2;for(var h=0;h>>31)return A.warn("SIDX has hierarchical references (not supported)"),null;var f=Le(e,u);u+=4,t.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/n,start:o,end:o+c-1}}),o+=c,i=u+=4}return{earliestPresentationTime:s,timescale:n,version:r,referencesCount:l,references:t}}function Ie(e){for(var t=[],r=we(e,["moov","trak"]),n=0;n12){var u=4;if(3!==h[u++])break;u=ke(h,u),u+=2;var d=h[u++];if(128&d&&(u+=2),64&d&&(u+=h[u++]),4!==h[u++])break;u=ke(h,u);var c=h[u++];if(64!==c)break;if(n+="."+De(c),u+=12,5!==h[u++])break;u=ke(h,u);var f=h[u++],g=(248&f)>>3;31===g&&(g+=1+((7&f)<<3)+((224&h[u])>>5)),n+="."+g}break;case"hvc1":case"hev1":var p=we(r,["hvcC"])[0],m=p[1],v=["","A","B","C"][m>>6],y=31&m,E=Le(p,2),S=(32&m)>>5?"H":"L",T=p[12],_=p.subarray(6,12);n+="."+v+y,n+="."+E.toString(16).toUpperCase(),n+="."+S+T;for(var L="",b=_.length;b--;){var R=_[b];(R||L)&&(L="."+R.toString(16).toUpperCase()+L)}n+=L;break;case"dvh1":case"dvhe":var A=we(r,["dvcC"])[0],w=A[2]>>1&127,P=A[2]<<5&32|A[3]>>3&31;n+="."+Me(w)+"."+Me(P);break;case"vp09":var I=we(r,["vpcC"])[0],C=I[4],k=I[5],D=I[6]>>4&15;n+="."+Me(C)+"."+Me(k)+"."+Me(D);break;case"av01":var M=we(r,["av1C"])[0],x=M[1]>>>5,O=31&M[1],F=M[2]>>>7?"H":"M",N=(64&M[2])>>6,B=(32&M[2])>>5,U=2===x&&N?B?12:10:N?10:8,G=(16&M[2])>>4,H=(8&M[2])>>3,$=(4&M[2])>>2,K=3&M[2];n+="."+x+"."+Me(O)+F+"."+Me(U)+"."+G+"."+H+$+K+"."+Me(1)+"."+Me(1)+"."+Me(1)+".0"}return{codec:n,encrypted:s}}function ke(e,t){for(var r=t+5;128&e[t++]&&t>1&63;return 39===r||40===r}return 6==(31&t)}function Ue(e,t,r,i){var n=Ge(e),s=0;s+=t;for(var a=0,o=0,l=0;s=n.length)break;a+=l=n[s++]}while(255===l);o=0;do{if(s>=n.length)break;o+=l=n[s++]}while(255===l);var h=n.length-s,u=s;if(oh){A.error("Malformed SEI payload. "+o+" is too small, only "+h+" bytes left to parse.");break}if(4===a){if(181===n[u++]){var d=_e(n,u);if(u+=2,49===d){var c=Le(n,u);if(u+=4,1195456820===c){var f=n[u++];if(3===f){var g=n[u++],p=64&g,m=p?2+3*(31&g):0,v=new Uint8Array(m);if(p){v[0]=g;for(var y=1;y16){for(var E=[],S=0;S<16;S++){var T=n[u++].toString(16);E.push(1==T.length?"0"+T:T),3!==S&&5!==S&&7!==S&&9!==S||E.push("-")}for(var _=o-16,L=new Uint8Array(_),b=0;b<_;b++)L[b]=n[u++];i.push({payloadType:a,pts:r,uuid:E.join(""),userData:me(L),userDataBytes:L})}}}function Ge(e){for(var t=e.byteLength,r=[],i=1;i>8*(15-r)&255;return t}(t);return new e(this.method,this.uri,"identity",this.keyFormatVersions,r)}var i=function(e){var t,r,i=e.split(":"),n=null;if("data"===i[0]&&2===i.length){var s=i[1].split(";"),a=s[s.length-1].split(",");if(2===a.length){var o="base64"===a[0],l=a[1];o?(s.splice(-1,1),n=G(l)):(t=H(l).subarray(0,16),(r=new Uint8Array(16)).set(t,16-t.length),n=r)}}return n}(this.uri);if(i)switch(this.keyFormat){case j:this.pssh=i,i.length>=22&&(this.keyId=i.subarray(i.length-22,i.length-6));break;case q:var n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t,r){if(16!==e.byteLength)throw new RangeError("Invalid system id");var i,n,s;if(t){i=1,n=new Uint8Array(16*t.length);for(var a=0;a0?(s=new Uint8Array(4),t.length>0&&new DataView(s.buffer).setUint32(0,t.length,!1)):s=new Uint8Array;var l=new Uint8Array(4);return r&&r.byteLength>0&&new DataView(l.buffer).setUint32(0,r.byteLength,!1),function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i>24&255,o[1]=s>>16&255,o[2]=s>>8&255,o[3]=255&s,o.set(e,4),a=0,s=8;a0&&s.length0&&Y.bool("CAN-SKIP-DATERANGES"),u.partHoldBack=Y.optionalFloat("PART-HOLD-BACK",0),u.holdBack=Y.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var z=new I(C);u.partTarget=z.decimalFloatingPoint("PART-TARGET");break;case"PART":var X=u.partList;X||(X=u.partList=[]);var Q=g>0?X[X.length-1]:void 0,J=g++,Z=new I(C);Ve(u,Z,["BYTERANGE","URI"]);var ee=new B(Z,E,t,J,Q);X.push(ee),E.duration+=ee.duration;break;case"PRELOAD-HINT":var te=new I(C);Ve(u,te,["URI"]),u.preloadHint=te;break;case"RENDITION-REPORT":var re=new I(C);Ve(u,re,["URI"]),u.renditionReports=u.renditionReports||[],u.renditionReports.push(re);break;default:A.warn("line parsed but not handled: "+a)}}}y&&!y.relurl?(d.pop(),p-=y.duration,u.partList&&(u.fragmentHint=y)):u.partList&&(mt(E,y),E.cc=v,u.fragmentHint=E,h&&yt(E,h,u));var ie=d.length,ne=d[0],se=d[ie-1];if((p+=u.skippedSegments*u.targetduration)>0&&ie&&se){u.averagetargetduration=p/ie;var ae=se.sn;u.endSN="initSegment"!==ae?ae:0,u.live||(se.endList=!0),ne&&(u.startCC=ne.cc)}else u.endSN=0,u.startCC=0;return u.fragmentHint&&(p+=u.fragmentHint.duration),u.totalduration=p,u.endCC=v,S>0&&function(e,t){for(var r=e[t],i=t;i--;){var n=e[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(d,S),u},e}();function ct(e,t,r){var i,n,s=new I(e);Ve(r,s,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);var a=null!=(i=s.METHOD)?i:"",o=s.URI,l=s.hexadecimalInteger("IV"),h=s.KEYFORMATVERSIONS,u=null!=(n=s.KEYFORMAT)?n:"identity";o&&s.IV&&!l&&A.error("Invalid IV: "+s.IV);var d=o?dt.resolve(o,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new $e(a,d,u,c,l)}function ft(e){var t=new I(e).decimalFloatingPoint("TIME-OFFSET");return m(t)?t:null}function gt(e,t){var r=(e||"").split(/[ ,]+/).filter((function(e){return e}));["video","audio","text"].forEach((function(e){var i=r.filter((function(t){return function(e,t){var r=Xe[t];return!!r&&!!r[e.slice(0,4)]}(t,e)}));i.length&&(t[e+"Codec"]=i.join(","),r=r.filter((function(e){return-1===i.indexOf(e)})))})),t.unknownCodecs=r}function pt(e,t,r){var i=t[r];i&&(e[r]=i)}function mt(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),m(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function vt(e,t,r,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function yt(e,t,r){e.levelkeys=t;var i=r.encryptedFragments;i.length&&i[i.length-1].levelkeys===t||!Object.keys(t).some((function(e){return t[e].isCommonEncryption}))||i.push(e)}var Et="manifest",St="level",Tt="audioTrack",_t="subtitleTrack",Lt="main",bt="audio",Rt="subtitle";function At(e){switch(e.type){case Tt:return bt;case _t:return Rt;default:return Lt}}function wt(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var Pt=function(){function e(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}var t=e.prototype;return t.startLoad=function(e){},t.stopLoad=function(){this.destroyInternalLoaders()},t.registerListeners=function(){var e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},t.unregisterListeners=function(){var e=this.hls;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},t.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return this.loaders[e.type]=n,n},t.getInternalLoader=function(e){return this.loaders[e.type]},t.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},t.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},t.onManifestLoading=function(e,t){var r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Et,url:r,deliveryDirectives:null})},t.onLevelLoading=function(e,t){var r=t.id,i=t.level,n=t.pathwayId,s=t.url,a=t.deliveryDirectives;this.load({id:r,level:i,pathwayId:n,responseType:"text",type:St,url:s,deliveryDirectives:a})},t.onAudioTrackLoading=function(e,t){var r=t.id,i=t.groupId,n=t.url,s=t.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:Tt,url:n,deliveryDirectives:s})},t.onSubtitleTrackLoading=function(e,t){var r=t.id,i=t.groupId,n=t.url,s=t.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:_t,url:n,deliveryDirectives:s})},t.load=function(e){var t,r,i,n=this,s=this.hls.config,a=this.getInternalLoader(e);if(a){var l=a.context;if(l&&l.url===e.url&&l.level===e.level)return void A.trace("[playlist-loader]: playlist request ongoing");A.log("[playlist-loader]: aborting previous loader for type: "+e.type),a.abort()}if(r=e.type===Et?s.manifestLoadPolicy.default:o({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(e),m(null==(t=e.deliveryDirectives)?void 0:t.part)&&(e.type===St&&null!==e.level?i=this.hls.levels[e.level].details:e.type===Tt&&null!==e.id?i=this.hls.audioTracks[e.id].details:e.type===_t&&null!==e.id&&(i=this.hls.subtitleTracks[e.id].details),i)){var h=i.partTarget,u=i.targetduration;if(h&&u){var d=1e3*Math.max(3*h,.8*u);r=o({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}var c=r.errorRetry||r.timeoutRetry||{},f={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:c.maxNumRetry||0,retryDelay:c.retryDelayMs||0,maxRetryDelay:c.maxRetryDelayMs||0},g={onSuccess:function(e,t,r,i){var s=n.getInternalLoader(r);n.resetInternalLoader(r.type);var a=e.data;0===a.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),dt.isMediaPlaylist(a)?n.handleTrackOrLevelPlaylist(e,t,r,i||null,s):n.handleMasterPlaylist(e,t,r,i)):n.handleManifestParsingError(e,r,new Error("no EXTM3U delimiter"),i||null,t)},onError:function(e,t,r,i){n.handleNetworkError(t,r,!1,e,i)},onTimeout:function(e,t,r){n.handleNetworkError(t,r,!0,void 0,e)}};a.load(e,f,g)},t.handleMasterPlaylist=function(e,t,r,i){var n=this.hls,s=e.data,a=wt(e,r),o=dt.parseMasterPlaylist(s,a);if(o.playlistParsingError)this.handleManifestParsingError(e,r,o.playlistParsingError,i,t);else{var l=o.contentSteering,h=o.levels,u=o.sessionData,d=o.sessionKeys,c=o.startTimeOffset,f=o.variableList;this.variableList=f;var g=dt.parseMasterPlaylistMedia(s,a,o),p=g.AUDIO,m=void 0===p?[]:p,v=g.SUBTITLES,y=g["CLOSED-CAPTIONS"];m.length&&(m.some((function(e){return!e.url}))||!h[0].audioCodec||h[0].attrs.AUDIO||(A.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new I({}),bitrate:0,url:""}))),n.trigger(E.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:v,captions:y,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:c,variableList:f})}},t.handleTrackOrLevelPlaylist=function(e,t,r,i,n){var s=this.hls,a=r.id,o=r.level,l=r.type,h=wt(e,r),u=m(o)?o:m(a)?a:0,d=At(r),c=dt.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===Et){var f={attrs:new I({}),bitrate:0,details:c,name:"",url:h};s.trigger(E.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=c,this.handlePlaylistLoaded(c,e,t,r,i,n)},t.handleManifestParsingError=function(e,t,r,i,n){this.hls.trigger(E.ERROR,{type:S.NETWORK_ERROR,details:T.MANIFEST_PARSING_ERROR,fatal:t.type===Et,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:n})},t.handleNetworkError=function(e,t,r,n,s){void 0===r&&(r=!1);var a="A network "+(r?"timeout":"error"+(n?" (status "+n.code+")":""))+" occurred while loading "+e.type;e.type===St?a+=": "+e.level+" id: "+e.id:e.type!==Tt&&e.type!==_t||(a+=" id: "+e.id+' group-id: "'+e.groupId+'"');var o=new Error(a);A.warn("[playlist-loader]: "+a);var l=T.UNKNOWN,h=!1,u=this.getInternalLoader(e);switch(e.type){case Et:l=r?T.MANIFEST_LOAD_TIMEOUT:T.MANIFEST_LOAD_ERROR,h=!0;break;case St:l=r?T.LEVEL_LOAD_TIMEOUT:T.LEVEL_LOAD_ERROR,h=!1;break;case Tt:l=r?T.AUDIO_TRACK_LOAD_TIMEOUT:T.AUDIO_TRACK_LOAD_ERROR,h=!1;break;case _t:l=r?T.SUBTITLE_TRACK_LOAD_TIMEOUT:T.SUBTITLE_LOAD_ERROR,h=!1}u&&this.resetInternalLoader(e.type);var d={type:S.NETWORK_ERROR,details:l,fatal:h,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:s};if(n){var c=(null==t?void 0:t.url)||e.url;d.response=i({url:c,data:void 0},n)}this.hls.trigger(E.ERROR,d)},t.handlePlaylistLoaded=function(e,t,r,i,n,s){var a=this.hls,o=i.type,l=i.level,h=i.id,u=i.groupId,d=i.deliveryDirectives,c=wt(t,i),f=At(i),g="number"==typeof i.level&&f===Lt?l:void 0;if(e.fragments.length){e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));var p=e.playlistParsingError;if(p)a.trigger(E.ERROR,{type:S.NETWORK_ERROR,details:T.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:p,reason:p.message,response:t,context:i,level:g,parent:f,networkDetails:n,stats:r});else switch(e.live&&s&&(s.getCacheAge&&(e.ageHeader=s.getCacheAge()||0),s.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case Et:case St:a.trigger(E.LEVEL_LOADED,{details:e,level:g||0,id:h||0,stats:r,networkDetails:n,deliveryDirectives:d});break;case Tt:a.trigger(E.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:u||"",stats:r,networkDetails:n,deliveryDirectives:d});break;case _t:a.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:u||"",stats:r,networkDetails:n,deliveryDirectives:d})}}else{var m=new Error("No Segments found in Playlist");a.trigger(E.ERROR,{type:S.NETWORK_ERROR,details:T.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:t,context:i,level:g,parent:f,networkDetails:n,stats:r})}},e}();function It(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function Ct(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: "+t)}catch(r){A.debug("[texttrack-utils]: "+r);try{var i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){A.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+e)}}"disabled"===r&&(e.mode=r)}function kt(e){var t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(var r=e.cues.length;r--;)e.removeCue(e.cues[r]);"disabled"===t&&(e.mode=t)}function Dt(e,t,r,i){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var s=function(e,t,r){var i=[],n=function(e,t){if(te[r].endTime)return-1;for(var i=0,n=r;i<=n;){var s=Math.floor((n+i)/2);if(te[s].startTime&&i-1)for(var s=n,a=e.length;s=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),a=0;aBt&&(d=Bt),d-u<=0&&(d=u+.25);for(var c=0;ct.startDate&&(!e||t.startDate.05&&this.forwardBufferLength>1){var l=Math.min(2,Math.max(1,s)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(l,Math.max(1,h))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}}}}},t.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},t.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},a(e,[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config,t=this.levelDetails;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e)return null;var t=e.holdBack,r=e.partHoldBack,i=e.targetduration,n=this.config,s=n.liveSyncDuration,a=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,h=o&&r||t;(l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==s?s:a*i);var u=i;return h+Math.min(1*this.stallCount,u)}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency,r=this.levelDetails;if(null===e||null===t||null===r)return null;var i=r.edge,n=e-t-this.edgeStalled,s=i-r.totalduration,a=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(s,n),a)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}}]),e}(),$t=["NONE","TYPE-0","TYPE-1",null],Kt=["SDR","PQ","HLG"];function Wt(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,i=e.age;return t&&ie.sn?(n=r-e.start,i=e):(n=e.start-r,i=t),i.duration!==n&&(i.duration=n)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration:t.start=Math.max(e.start-t.duration,0)}function zt(e,t,r,i,n,s){i-r<=0&&(A.warn("Fragment should have a positive duration",t),i=r+t.duration,s=n+t.duration);var a=r,o=i,l=t.startPTS,h=t.endPTS;if(m(l)){var u=Math.abs(l-r);m(t.deltaPTS)?t.deltaPTS=Math.max(u,t.deltaPTS):t.deltaPTS=u,a=Math.max(r,l),r=Math.min(r,l),n=Math.min(n,t.startDTS),o=Math.min(i,h),i=Math.max(i,h),s=Math.max(s,t.endDTS)}var d=r-t.start;0!==t.start&&(t.start=r),t.duration=i-t.start,t.startPTS=r,t.maxStartPTS=a,t.startDTS=n,t.endPTS=i,t.minEndPTS=o,t.endDTS=s;var c,f=t.sn;if(!e||fe.endSN)return 0;var g=f-e.startSN,p=e.fragments;for(p[g]=t,c=g;c>0;c--)Yt(p[c],p[c-1]);for(c=g;c=0;n--){var s=i[n].initSegment;if(s){r=s;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;var a,l,h,u,d,c=0;if(function(e,t,r){for(var i=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,s=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,h=n;h<=s;h++){var u=l[a+h],d=o[h];i&&!d&&h=i.length||Jt(t,i[r].start)}function Jt(e,t){if(t){for(var r=e.fragments,i=e.skippedSegments;i499)}(n)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,s):s}var or=function(e,t){for(var r=0,i=e.length-1,n=null,s=null;r<=i;){var a=t(s=e[n=(r+i)/2|0]);if(a>0)r=n+1;else{if(!(a<0))return s;i=n-1}}return null};function lr(e,t,r,i,n){void 0===r&&(r=0),void 0===i&&(i=0),void 0===n&&(n=.005);var s=null;if(e){s=t[e.sn-t[0].sn+1]||null;var a=e.endDTS-r;a>0&&a<15e-7&&(r+=15e-7)}else 0===r&&0===t[0].start&&(s=t[0]);if(s&&((!e||e.level===s.level)&&0===hr(r,i,s)||function(e,t,r){if(t&&0===t.start&&t.level0){var i=t.tagList.reduce((function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e}),r);return e.start<=i}return!1}(s,e,Math.min(n,i))))return s;var o=or(t,hr.bind(null,r,i));return!o||o===e&&s?s:o}function hr(e,t,r){if(void 0===e&&(e=0),void 0===t&&(t=0),r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function ur(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}var dr=function(){function e(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=A.log.bind(A,"[info]:"),this.warn=A.warn.bind(A,"[warning]:"),this.error=A.error.bind(A,"[error]:"),this.registerListeners()}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))},t.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},t.startLoad=function(e){},t.stopLoad=function(){this.playlistError=0},t.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===Lt?e.level:this.hls.loadLevel},t.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},t.onLevelUpdated=function(){this.playlistError=0},t.onError=function(e,t){var r,i;if(!t.fatal){var n=this.hls,s=t.context;switch(t.details){case T.FRAG_LOAD_ERROR:case T.FRAG_LOAD_TIMEOUT:case T.KEY_LOAD_ERROR:case T.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case T.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction={action:0,flags:0});case T.FRAG_GAP:case T.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=2);case T.LEVEL_EMPTY_ERROR:case T.LEVEL_PARSING_ERROR:var a,o,l=t.parent===Lt?t.level:n.loadLevel;return void(t.details===T.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(o=a.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l)));case T.LEVEL_LOAD_ERROR:case T.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level)));case T.AUDIO_TRACK_LOAD_ERROR:case T.AUDIO_TRACK_LOAD_TIMEOUT:case T.SUBTITLE_LOAD_ERROR:case T.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){var h=n.levels[n.loadLevel];if(h&&(s.type===Tt&&h.hasAudioGroup(s.groupId)||s.type===_t&&h.hasSubtitleGroup(s.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=2,void(t.errorAction.flags=1)}return;case T.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var u=n.levels[n.loadLevel],d=null==u?void 0:u.attrs["HDCP-LEVEL"];return void(d?t.errorAction={action:2,flags:2,hdcpLevel:d}:this.keySystemError(t));case T.BUFFER_ADD_CODEC_ERROR:case T.REMUX_ALLOC_ERROR:case T.BUFFER_APPEND_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(i=t.level)?i:n.loadLevel));case T.INTERNAL_EXCEPTION:case T.BUFFER_APPENDING_ERROR:case T.BUFFER_FULL_ERROR:case T.LEVEL_SWITCH_ERROR:case T.BUFFER_STALLED_ERROR:case T.BUFFER_SEEK_OVER_HOLE:case T.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:0,flags:0})}t.type===S.KEY_SYSTEM_ERROR&&this.keySystemError(t)}},t.keySystemError=function(e){var t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)},t.getPlaylistRetryOrSwitchAction=function(e,t){var r=ir(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(ar(r,i,rr(e),e.response))return{action:5,flags:0,retryConfig:r,retryCount:i};var n=this.getLevelSwitchAction(e,t);return r&&(n.retryConfig=r,n.retryCount=i),n},t.getFragRetryOrSwitchAction=function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],n=t.config,s=n.fragLoadPolicy,a=n.keyLoadPolicy,o=ir(e.details.startsWith("key")?a:s,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(i&&(e.details!==T.FRAG_GAP&&i.fragmentError++,ar(o,l,rr(e),e.response)))return{action:5,flags:0,retryConfig:o,retryCount:l};var h=this.getLevelSwitchAction(e,r);return o&&(h.retryConfig=o,h.retryCount=l),h},t.getLevelSwitchAction=function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var n,s,a=e.details;i.loadError++,a===T.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,h=r.loadLevel,u=r.minAutoLevel,d=r.maxAutoLevel;r.autoLevelEnabled||(r.loadLevel=-1);for(var c,f=null==(n=e.frag)?void 0:n.type,g=(f===bt&&a===T.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(a===T.BUFFER_ADD_CODEC_ERROR||a===T.BUFFER_APPEND_ERROR))&&l.some((function(e){var t=e.audioCodec;return i.audioCodec!==t})),p="video"===e.sourceBufferName&&(a===T.BUFFER_ADD_CODEC_ERROR||a===T.BUFFER_APPEND_ERROR)&&l.some((function(e){var t=e.codecSet,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r})),m=null!=(s=e.context)?s:{},v=m.type,y=m.groupId,E=function(){var t=(S+h)%l.length;if(t!==h&&t>=u&&t<=d&&0===l[t].loadError){var r,n,s=l[t];if(a===T.FRAG_GAP&&f===Lt&&e.frag){var c=l[t].details;if(c){var m=lr(e.frag,c.fragments,e.frag.start);if(null!=m&&m.gap)return 0}}else{if(v===Tt&&s.hasAudioGroup(y)||v===_t&&s.hasSubtitleGroup(y))return 0;if(f===bt&&null!=(r=i.audioGroups)&&r.some((function(e){return s.hasAudioGroup(e)}))||f===Rt&&null!=(n=i.subtitleGroups)&&n.some((function(e){return s.hasSubtitleGroup(e)}))||g&&i.audioCodec===s.audioCodec||!g&&i.audioCodec!==s.audioCodec||p&&i.codecSet===s.codecSet)return 0}return o=t,1}},S=l.length;S--&&(0===(c=E())||1!==c););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:o}}return{action:2,flags:1}},t.onErrorOut=function(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===T.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn('MediaSource ended after "'+t.sourceBufferName+'" sourceBuffer append error. Attempting to recover from media error.'),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()},t.sendAlternateToPenaltyBox=function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.flags,n=r.hdcpLevel,s=r.nextAutoLevel;switch(i){case 0:this.switchLevel(e,s);break;case 2:n&&(t.maxHdcpLevel=$t[$t.indexOf(n)-1],r.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower')}r.resolved||this.switchLevel(e,s)}},t.switchLevel=function(e,t){void 0!==t&&e.errorAction&&(this.warn("switching to level "+t+" after "+e.details),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)},e}(),cr=function(){function e(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=A.log.bind(A,t+":"),this.warn=A.warn.bind(A,t+":"),this.hls=e}var t=e.prototype;return t.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},t.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},t.startLoad=function(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()},t.stopLoad=function(){this.canLoad=!1,this.clearTimer()},t.switchParams=function(e,t,r){var i=null==t?void 0:t.renditionReports;if(i){for(var n=-1,s=0;s=0&&d>t.partTarget&&(u+=1)}var c=r&&Wt(r);return new Vt(h,u>=0?u:void 0,c)}}},t.loadPlaylist=function(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())},t.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},t.shouldReloadPlaylist=function(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)},t.playlistLoaded=function(e,t,r){var i=this,n=t.details,s=t.stats,a=self.performance.now(),o=s.loading.first?Math.max(0,a-s.loading.first):0;if(n.advancedDateTime=Date.now()-o,n.live||null!=r&&r.live){if(n.reloaded(r),r&&this.log("live playlist "+e+" "+(n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED")),r&&n.fragments.length>0&&Xt(r,n),!this.canLoad||!n.live)return;var l,h=void 0,u=void 0;if(n.canBlockReload&&n.endSN&&n.advanced){var d=this.hls.config.lowLatencyMode,c=n.lastPartSn,f=n.endSN,g=n.lastPartIndex,p=c===f;-1!==g?(h=p?f+1:c,u=p?d?0:g:g+1):h=f+1;var m=n.age,v=m+n.ageHeader,y=Math.min(v-n.partTarget,1.5*n.targetduration);if(y>0){if(r&&y>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+y+" with playlist age: "+n.age),y=0;else{var E=Math.floor(y/n.targetduration);h+=E,void 0!==u&&(u+=Math.round(y%n.targetduration/n.partTarget)),this.log("CDN Tune-in age: "+n.ageHeader+"s last advanced "+m.toFixed(2)+"s goal: "+y+" skip sn "+E+" to part "+u)}n.tuneInGoal=y}if(l=this.getDeliveryDirectives(n,t.deliveryDirectives,h,u),d||!p)return void this.loadPlaylist(l)}else(n.canBlockReload||n.canSkipUntil)&&(l=this.getDeliveryDirectives(n,t.deliveryDirectives,h,u));var S=this.hls.mainForwardBufferInfo,T=S?S.end-S.len:0,_=function(e,t){void 0===t&&(t=1/0);var r=1e3*e.targetduration;if(e.updated){var i=e.fragments;if(i.length&&4*r>t){var n=1e3*i[i.length-1].duration;nthis.requestScheduled+_&&(this.requestScheduled=s.loading.start),void 0!==h&&n.canBlockReload?this.requestScheduled=s.loading.first+_-(1e3*n.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+_=h.maxNumRetry)return!1;if(i&&null!=(d=e.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+r+'" without delivery-directives'),this.loadPlaylist();else{var c=nr(h,l);this.timer=self.setTimeout((function(){return t.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+h.maxNumRetry+' after "'+r+'" in '+c+"ms")}e.levelRetry=!0,n.resolved=!0}return u},e}(),fr=function(){function e(e,t,r){void 0===t&&(t=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=r}var t=e.prototype;return t.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},e}(),gr=function(){function e(e,t,r,i){void 0===i&&(i=100),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new fr(e),this.fast_=new fr(t),this.defaultTTFB_=i,this.ttfb_=new fr(e)}var t=e.prototype;return t.update=function(e,t){var r=this.slow_,i=this.fast_,n=this.ttfb_;r.halfLife!==e&&(this.slow_=new fr(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new fr(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new fr(e,n.getEstimate(),n.getTotalWeight()))},t.sample=function(e,t){var r=(e=Math.max(e,this.minDelayMs_))/1e3,i=8*t/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},t.sampleTTFB=function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))},t.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},t.destroy=function(){},e}(),pr={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},mr={};function vr(e,t,r){var n=e.videoCodec,s=e.audioCodec;if(!n||!s||!r)return Promise.resolve(pr);var a={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},o=e.videoRange;"SDR"!==o&&(a.transferFunction=o.toLowerCase());var l=n.split(",").map((function(e){return{type:"media-source",video:i(i({},a),{},{contentType:Ze(e,"video")})}}));return s&&e.audioGroups&&e.audioGroups.forEach((function(e){var r;e&&(null==(r=t.groups[e])||r.tracks.forEach((function(t){if(t.groupId===e){var r=t.channels||"",i=parseFloat(r);m(i)&&i>2&&l.push.apply(l,s.split(",").map((function(e){return{type:"media-source",audio:{contentType:Ze(e,"audio"),channels:""+i}}})))}})))})),Promise.all(l.map((function(e){var t=function(e){var t=e.audio,r=e.video,i=r||t;if(i){var n=i.contentType.split('"')[1];if(r)return"r"+r.height+"x"+r.width+"f"+Math.ceil(r.framerate)+(r.transferFunction||"sd")+"_"+n+"_"+Math.ceil(r.bitrate/1e5);if(t)return"c"+t.channels+(t.spatialRendering?"s":"n")+"_"+n}return""}(e);return mr[t]||(mr[t]=r.decodingInfo(e))}))).then((function(e){return{supported:!e.some((function(e){return!e.supported})),configurations:l,decodingInfoResults:e}})).catch((function(e){return{supported:!1,configurations:l,decodingInfoResults:[],error:e}}))}function yr(e,t){A.log('[abr] start candidates with "'+e+'" ignored because '+t)}function Er(e,t,r){if("attrs"in e){var i=t.indexOf(e);if(-1!==i)return i}for(var n=0;n-1,y=t.getBwEstimate(),S=i.levels,T=S[e.level],_=o.total||Math.max(o.loaded,Math.round(l*T.averageBitrate/8)),L=v?h-p:h;L<1&&v&&(L=Math.min(h,8*o.loaded/y));var b=v?1e3*o.loaded/L:0,R=b?(_-o.loaded)/b:8*_/y+c/1e3;if(!(R<=g)){var w,P=b?8*b:y,I=Number.POSITIVE_INFINITY;for(w=e.level-1;w>u;w--){var C=S[w].maxBitrate;if((I=t.getTimeToLoadFrag(c/1e3,P,l*C,!S[w].details))=R||I>10*l)){i.nextLoadLevel=i.nextAutoLevel=w,v?t.bwEstimator.sample(h-Math.min(c,p),o.loaded):t.bwEstimator.sampleTTFB(h);var k=S[w].maxBitrate;t.getBwEstimate()*t.hls.config.abrBandWidthUpFactor>k&&t.resetEstimator(k),t.clearTimer(),A.warn("[abr] Fragment "+e.sn+(r?" part "+r.index:"")+" of level "+e.level+" is loading too slowly;\n Time to underbuffer: "+g.toFixed(3)+" s\n Estimated load time for current fragment: "+R.toFixed(3)+" s\n Estimated load time for down switch fragment: "+I.toFixed(3)+" s\n TTFB estimate: "+(0|p)+" ms\n Current BW estimate: "+(m(y)?0|y:"Unknown")+" bps\n New BW estimate: "+(0|t.getBwEstimate())+" bps\n Switching to level "+w+" @ "+(0|k)+" bps"),i.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:r,stats:o})}}}}}}},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}var t=e.prototype;return t.resetEstimator=function(e){e&&(A.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},t.initEstimator=function(){var e=this.hls.config;return new gr(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},t.registerListeners=function(){var e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))},t.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null},t.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},t.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},t.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},t.onFragLoading=function(e,t){var r,i=t.frag;this.ignoreFragment(i)||(i.bitrateTest||(this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},t.onLevelSwitching=function(e,t){this.clearTimer()},t.onError=function(e,t){if(!t.fatal)switch(t.details){case T.BUFFER_ADD_CODEC_ERROR:case T.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case T.FRAG_LOAD_TIMEOUT:var r=t.frag,i=this.fragCurrent,n=this.partCurrent;if(r&&i&&r.sn===i.sn&&r.level===i.level){var s=performance.now(),a=n?n.stats:r.stats,o=s-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){var h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(h,l),a.loaded)}else this.bwEstimator.sampleTTFB(o)}}},t.getTimeToLoadFrag=function(e,t,r,i){return e+r/t+(i?this.lastLevelLoadSec:0)},t.onLevelLoaded=function(e,t){var r=this.hls.config,i=t.stats.loading,n=i.end-i.start;m(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD)},t.onFragLoaded=function(e,t){var r=t.frag,i=t.part,n=i?i.stats:r.stats;if(r.type===Lt&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var s=i?i.duration:r.duration,a=this.hls.levels[r.level],o=(a.loaded?a.loaded.bytes:0)+n.loaded,l=(a.loaded?a.loaded.duration:0)+s;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(r.bitrateTest){var h={stats:n,frag:r,part:i,id:r.type};this.onFragBuffered(E.FRAG_BUFFERED,h),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}},t.onFragBuffered=function(e,t){var r=t.frag,i=t.part,n=null!=i&&i.stats.loaded?i.stats:r.stats;if(!n.aborted&&!this.ignoreFragment(r)){var s=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(s,n.loaded),n.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=s/1e3:this.bitrateTestDelay=0}},t.ignoreFragment=function(e){return e.type!==Lt||"initSegment"===e.sn},t.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},t.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},t.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls,i=r.maxAutoLevel,n=r.config,s=r.minAutoLevel,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),h=n.abrBandWidthFactor,u=n.abrBandWidthUpFactor;if(l){var d=this.findBestLevel(o,s,i,l,0,h,u);if(d>=0)return d}var c=a?Math.min(a,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var f=this.bitrateTestDelay;f&&(c=(a?Math.min(a,n.maxLoadingDelay):n.maxLoadingDelay)-f,A.info("[abr] bitrate test took "+Math.round(1e3*f)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*c)+" ms"),h=u=1)}var g=this.findBestLevel(o,s,i,l,c,h,u);if(A.info("[abr] "+(l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g),g>-1)return g;var p=r.levels[s],m=r.levels[r.loadLevel];return(null==p?void 0:p.bitrate)<(null==m?void 0:m.bitrate)?s:r.loadLevel},t.getStarvationDelay=function(){var e=this.hls,t=e.media;if(!t)return 1/0;var r=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/r},t.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},t.findBestLevel=function(e,t,r,i,n,s,a){var o,l=this,h=i+n,u=this.lastLoadedFragLevel,d=-1===u?this.hls.firstLevel:u,c=this.fragCurrent,f=this.partCurrent,g=this.hls,p=g.levels,v=g.allAudioTracks,y=g.loadLevel,E=g.config;if(1===p.length)return 0;var S,T=p[d],_=!(null==T||null==(o=T.details)||!o.live),L=-1===y||-1===u,b="SDR",R=(null==T?void 0:T.frameRate)||0,w=E.audioPreference,P=E.videoPreference,I=this.audioTracksByGroup||(this.audioTracksByGroup=function(e){return e.reduce((function(e,t){var r=e.groups[t.groupId];r||(r=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(t);var i=t.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||t.default,r.hasAutoSelect=r.hasAutoSelect||t.autoselect,r.hasDefault&&(e.hasDefaultAudio=!0),r.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(v));if(L){if(-1!==this.firstSelection)return this.firstSelection;var C=this.codecTiers||(this.codecTiers=function(e,t,r,i){return e.slice(r,i+1).reduce((function(e,r){if(!r.codecSet)return e;var i=r.audioGroups,n=e[r.codecSet];n||(e[r.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,r.bitrate);var s=Math.min(r.height,r.width);return n.minHeight=Math.min(n.minHeight,s),n.minFramerate=Math.min(n.minFramerate,r.frameRate),n.maxScore=Math.max(n.maxScore,r.score),n.fragmentError+=r.fragmentError,n.videoRanges[r.videoRange]=(n.videoRanges[r.videoRange]||0)+1,i&&i.forEach((function(e){if(e){var r=t.groups[e];r&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(r.channels).forEach((function(e){n.channels[e]=(n.channels[e]||0)+r.channels[e]})))}})),e}),{})}(p,I,t,r)),k=function(e,t,r,i,n){for(var s=Object.keys(e),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=a&&2===parseInt(a),h=!0,u=!1,d=1/0,c=1/0,f=1/0,g=0,p=[],v=function(e,t){var r=!1,i=[];return e&&(r="SDR"!==e,i=[e]),t&&(i=t.allowedVideoRanges||Kt.slice(0),i=(r=void 0!==t.preferHDR?t.preferHDR:function(){if("function"==typeof matchMedia){var e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())?i.filter((function(e){return"SDR"!==e})):["SDR"]),{preferHDR:r,allowedVideoRanges:i}}(t,n),y=v.preferHDR,E=v.allowedVideoRanges,S=function(){var t=e[s[T]];h=t.channels[2]>0,d=Math.min(d,t.minHeight),c=Math.min(c,t.minFramerate),f=Math.min(f,t.minBitrate);var r=E.filter((function(e){return t.videoRanges[e]>0}));r.length>0&&(u=!0,p=r)},T=s.length;T--;)S();d=m(d)?d:0,c=m(c)?c:0;var _=Math.max(1080,d),L=Math.max(30,c);return f=m(f)?f:r,r=Math.max(f,r),u||(t=void 0,p=[]),{codecSet:s.reduce((function(t,i){var n=e[i];if(i===t)return t;if(n.minBitrate>r)return yr(i,"min bitrate of "+n.minBitrate+" > current estimate of "+r),t;if(!n.hasDefaultAudio)return yr(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return yr(i,'audio codec preference "'+o+'" not found'),t;if(a&&!l){if(!n.channels[a])return yr(i,"no renditions with "+a+" channel sound found (channels options: "+Object.keys(n.channels)+")"),t}else if((!o||l)&&h&&0===n.channels[2])return yr(i,"no renditions with stereo sound found"),t;return n.minHeight>_?(yr(i,"min resolution of "+n.minHeight+" > maximum of "+_),t):n.minFramerate>L?(yr(i,"min framerate of "+n.minFramerate+" > maximum of "+L),t):p.some((function(e){return n.videoRanges[e]>0}))?n.maxScore=tt(t)||n.fragmentError>e[t].fragmentError)?t:(g=n.maxScore,i):(yr(i,"no variants with VIDEO-RANGE of "+JSON.stringify(p)+" found"),t)}),void 0),videoRanges:p,preferHDR:y,minFramerate:c,minBitrate:f}}(C,b,e,w,P),D=k.codecSet,M=k.videoRanges,x=k.minFramerate,O=k.minBitrate,F=k.preferHDR;S=D,b=F?M[M.length-1]:M[0],R=x,e=Math.max(e,O),A.log("[abr] picked start tier "+JSON.stringify(k))}else S=null==T?void 0:T.codecSet,b=null==T?void 0:T.videoRange;for(var N,B=f?f.duration:c?c.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,G=[],H=function(){var t,o=p[$],c=$>d;if(!o)return 0;if(E.useMediaCapabilities&&!o.supportedResult&&!o.supportedPromise){var g=navigator.mediaCapabilities;"function"==typeof(null==g?void 0:g.decodingInfo)&&function(e,t,r,i,n,s){var a=e.audioCodec?e.audioGroups:null,o=null==s?void 0:s.audioCodec,l=null==s?void 0:s.channels,h=l?parseInt(l):o?1/0:2,u=null;if(null!=a&&a.length)try{u=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce((function(e,r){if(r){var i=t.groups[r];if(!i)throw new Error("Audio track group "+r+" not found");Object.keys(i.channels).forEach((function(t){e[t]=(e[t]||0)+i.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(n,8e6))||!!u&&m(h)&&Object.keys(u).some((function(e){return parseInt(e)>h}))}(o,I,b,R,e,w)?(o.supportedPromise=vr(o,I,g),o.supportedPromise.then((function(e){if(l.hls){o.supportedResult=e;var t=l.hls.levels,r=t.indexOf(o);e.error?A.warn('[abr] MediaCapabilities decodingInfo error: "'+e.error+'" for level '+r+" "+JSON.stringify(e)):e.supported||(A.warn("[abr] Unsupported MediaCapabilities decodingInfo result for level "+r+" "+JSON.stringify(e)),r>-1&&t.length>1&&(A.log("[abr] Removing unsupported level "+r),l.hls.removeLevel(r)))}}))):o.supportedResult=pr}if(S&&o.codecSet!==S||b&&o.videoRange!==b||c&&R>o.frameRate||!c&&R>0&&R=2*B&&0===n?p[$].averageBitrate:p[$].maxBitrate,D=l.getTimeToLoadFrag(U,v,k*C,void 0===P);if(v>=k&&($===u||0===o.loadError&&0===o.fragmentError)&&(D<=U||!m(D)||_&&!l.bitrateTestDelay||D"+$+" adjustedbw("+Math.round(v)+")-bitrate="+Math.round(v-k)+" ttfb:"+U.toFixed(1)+" avgDuration:"+C.toFixed(1)+" maxFetchDuration:"+h.toFixed(1)+" fetchDuration:"+D.toFixed(1)+" firstSelection:"+L+" codecSet:"+S+" videoRange:"+b+" hls.loadLevel:"+y)),L&&(l.firstSelection=$),{v:$}}},$=r;$>=t;$--)if(0!==(N=H())&&N)return N.v;return-1},a(e,[{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,r,t,0,n,1,1);if(s>-1)return s;var a=this.hls.firstLevel,o=Math.min(Math.max(a,r),t);return A.warn("[abr] Could not find best starting auto level. Defaulting to first in playlist "+a+" clamped to "+o),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,i)&&n[e].loadError<=n[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel,n=Math.min(Math.max(e,i),r);this._nextAutoLevel!==n&&(this.nextAutoLevelKey="",this._nextAutoLevel=n)}}]),e}(),br=function(){function e(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var t=e.prototype;return t.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},t.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},t.onHandlerDestroyed=function(){},t.hasInterval=function(){return!!this._tickInterval},t.hasNextTick=function(){return!!this._tickTimer},t.setInterval=function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)},t.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},t.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},t.tick=function(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},t.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},t.doTick=function(){},e}(),Rr="NOT_LOADED",Ar="APPENDING",wr="PARTIAL",Pr="OK",Ir=function(){function e(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}var t=e.prototype;return t._registerListeners=function(){var e=this.hls;e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this)},t._unregisterListeners=function(){var e=this.hls;e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this)},t.destroy=function(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},t.getAppendedFrag=function(e,t){var r=this.activePartLists[t];if(r)for(var i=r.length;i--;){var n=r[i];if(!n)break;var s=n.end;if(n.start<=e&&null!==s&&e<=s)return n}return this.getBufferedFrag(e,t)},t.getBufferedFrag=function(e,t){for(var r=this.fragments,i=Object.keys(r),n=i.length;n--;){var s=r[i[n]];if((null==s?void 0:s.body.type)===t&&s.buffered){var a=s.body;if(a.start<=e&&e<=a.end)return a}}return null},t.detectEvictedFragments=function(e,t,r,i){var n=this;this.timeRanges&&(this.timeRanges[e]=t);var s=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(i){var a=n.fragments[i];if(a&&!(s>=a.body.sn))if(a.buffered||a.loaded){var o=a.range[e];o&&o.time.some((function(e){var r=!n.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&n.removeFragment(a.body),r}))}else a.body.type===r&&n.removeFragment(a.body)}))},t.detectPartialFragments=function(e){var t=this,r=this.timeRanges,i=e.frag,n=e.part;if(r&&"initSegment"!==i.sn){var s=kr(i),a=this.fragments[s];if(!(!a||a.buffered&&i.gap)){var o=!i.relurl;Object.keys(r).forEach((function(e){var s=i.elementaryStreams[e];if(s){var l=r[e],h=o||!0===s.partial;a.range[e]=t.getBufferedTimes(i,n,h,l)}})),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),Cr(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.body)}}},t.removeParts=function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=r.filter((function(t){return t.fragment.sn>=e})))},t.fragBuffered=function(e,t){var r=kr(e),i=this.fragments[r];!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)},t.getBufferedTimes=function(e,t,r,i){for(var n={time:[],partial:r},s=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||s,h=0;h=u&&o<=d){n.time.push({startPTS:Math.max(s,i.start(h)),endPTS:Math.min(a,i.end(h))});break}if(su){var c=Math.max(s,i.start(h)),f=Math.min(a,i.end(h));f>c&&(n.partial=!0,n.time.push({startPTS:c,endPTS:f}))}else if(a<=u)break}return n},t.getPartialFragment=function(e){var t,r,i,n=null,s=0,a=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var h=o[l];h&&Cr(h)&&(r=h.body.start-a,i=h.body.end+a,e>=r&&e<=i&&(t=Math.min(e-r,i-e),s<=t&&(n=h.body,s=t)))})),n},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Cr(t))},t.getState=function(e){var t=kr(e),r=this.fragments[t];return r?r.buffered?Cr(r)?wr:Pr:Ar:Rr},t.isTimeBuffered=function(e,t,r){for(var i,n,s=0;s=i&&t<=n)return!0;if(t<=i)return!1}return!1},t.onFragLoaded=function(e,t){var r=t.frag,i=t.part;if("initSegment"!==r.sn&&!r.bitrateTest){var n=i?null:t,s=kr(r);this.fragments[s]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var r=this,i=t.frag,n=t.part,s=t.timeRanges;if("initSegment"!==i.sn){var a=i.type;if(n){var o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(n)}this.timeRanges=s,Object.keys(s).forEach((function(e){var t=s[e];r.detectEvictedFragments(e,t,a,n)}))}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=kr(e);return!!this.fragments[t]},t.hasParts=function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)},t.removeFragmentsInRange=function(e,t,r,i,n){var s=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach((function(a){var o=s.fragments[a];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.starte&&(o.buffered||n)&&s.removeFragment(l)}}))},t.removeFragment=function(e){var t=kr(e);e.stats.loaded=0,e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=r.filter((function(e){return e.fragment.sn!==i}))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]},t.removeAllFragments=function(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1},e}();function Cr(e){var t,r,i;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(r=e.range.audio)?void 0:r.partial)||(null==(i=e.range.audiovideo)?void 0:i.partial))}function kr(e){return e.type+"_"+e.level+"_"+e.sn}var Dr={length:0,start:function(){return 0},end:function(){return 0}},Mr=function(){function e(){}return e.isBuffered=function(t,r){try{if(t)for(var i=e.getBuffered(t),n=0;n=i.start(n)&&r<=i.end(n))return!0}catch(e){}return!1},e.bufferInfo=function(t,r,i){try{if(t){var n,s=e.getBuffered(t),a=[];for(n=0;na&&(i[s-1].end=e[n].end):i.push(e[n])}else i.push(e[n])}else i=e;for(var o,l=0,h=t,u=t,d=0;d=c&&t>>8^255&m^99,e[f]=m,t[m]=f;var v=c[f],y=c[v],E=c[y],S=257*c[m]^16843008*m;i[f]=S<<24|S>>>8,n[f]=S<<16|S>>>16,s[f]=S<<8|S>>>24,a[f]=S,S=16843009*E^65537*y^257*v^16843008*f,l[m]=S<<24|S>>>8,h[m]=S<<16|S>>>16,u[m]=S<<8|S>>>24,d[m]=S,f?(f=v^c[c[c[E^v]]],g^=c[c[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;ia.end){var u=s>h;(s0&&null!=s&&s.key&&s.iv&&"AES-128"===s.method){var a=self.performance.now();return r.decrypter.decrypt(new Uint8Array(n),s.key.buffer,s.iv.buffer).catch((function(t){throw i.trigger(E.ERROR,{type:S.MEDIA_ERROR,details:T.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((function(n){var s=self.performance.now();return i.trigger(E.FRAG_DECRYPTED,{frag:e,payload:n,stats:{tstart:a,tdecrypt:s}}),t.payload=n,r.completeInitSegmentLoad(t)}))}return r.completeInitSegmentLoad(t)})).catch((function(t){r.state!==Yr&&r.state!==ii&&(r.warn(t),r.resetFragmentLoading(e))}))},r.completeInitSegmentLoad=function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state=zr,e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now(),this.tick()},r.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level},r.fragBufferedComplete=function(e,t){var r,i,n,s,a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+(this.playlistType===Lt?"level":"track")+" "+e.level+" (frag:["+(null!=(r=e.startPTS)?r:NaN).toFixed(3)+"-"+(null!=(i=e.endPTS)?i:NaN).toFixed(3)+"] > buffer:"+(a?function(e){for(var t="",r=e.length,i=0;ie.end&&a.fragmentHint&&(e=a.fragmentHint);var h=this.getNextPart(l,e,r);if(h>-1){var u,d=l[h];return this.log("Loading part sn: "+e.sn+" p: "+d.index+" cc: "+e.cc+" of playlist ["+a.startSN+"-"+a.endSN+"] parts [0-"+h+"-"+(l.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+e.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=d.start+d.duration,this.state=Qr,u=o?o.then((function(r){return!r||s.fragContextChanged(r.frag)?null:s.doFragPartsLoad(e,d,t,i)})).catch((function(e){return s.handleFragLoadError(e)})):this.doFragPartsLoad(e,d,t,i).catch((function(e){return s.handleFragLoadError(e)})),this.hls.trigger(E.FRAG_LOADING,{frag:e,part:d,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):u}if(!e.url||this.loadedEndOfParts(l,r))return Promise.resolve(null)}}this.log("Loading fragment "+e.sn+" cc: "+e.cc+" "+(a?"of ["+a.startSN+"-"+a.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+e.level+", target: "+parseFloat(r.toFixed(3))),m(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Qr;var c,f=this.config.progressive;return c=f&&o?o.then((function(t){return!t||s.fragContextChanged(null==t?void 0:t.frag)?null:s.fragmentLoader.load(e,i)})).catch((function(e){return s.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,f?i:void 0),o]).then((function(e){var t=e[0];return!f&&t&&i&&i(t),t})).catch((function(e){return s.handleFragLoadError(e)})),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c},r.doFragPartsLoad=function(e,t,r,i){var n=this;return new Promise((function(s,a){var o,l=[],h=null==(o=r.details)?void 0:o.partList;!function t(o){n.fragmentLoader.loadPart(e,o,i).then((function(i){l[o.index]=i;var a=i.part;n.hls.trigger(E.FRAG_LOADED,i);var u=Zt(r,e.sn,o.index+1)||er(h,e.sn,o.index+1);if(!u)return s({frag:e,part:a,partsLoaded:l});t(u)})).catch(a)}(t)}))},r.handleFragLoadError=function(e){if("data"in e){var t=e.data;e.data&&t.details===T.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:S.OTHER_ERROR,details:T.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},r._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===ei){var r=t.frag,i=t.part,n=t.level,s=self.performance.now();r.stats.parsing.end=s,i&&(i.stats.parsing.end=s),this.updateLevelTiming(r,i,n,e.partial)}else this.fragCurrent||this.state===Yr||this.state===ii||(this.state=zr)},r.getCurrentContext=function(e){var t=this.levels,r=this.fragCurrent,i=e.level,n=e.sn,s=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment "+n+" of level "+i+". The current chunk will not be buffered."),null;var a=t[i],o=s>-1?Zt(a,n,s):null,l=o?o.fragment:function(e,t,r){if(null==e||!e.details)return null;var i=e.details,n=i.fragments[t-i.startSN];return n||((n=i.fragmentHint)&&n.sn===t?n:ts&&this.flushMainBuffer(a,e.start)}else this.flushMainBuffer(0,e.start)},r.getFwdBufferInfo=function(e,t){var r=this.getLoadPosition();return m(r)?this.getFwdBufferInfoAtPos(e,r,t):null},r.getFwdBufferInfoAtPos=function(e,t,r){var i=this.config.maxBufferHole,n=Mr.bufferInfo(e,t,i);if(0===n.len&&void 0!==n.nextStart){var s=this.fragmentTracker.getBufferedFrag(t,r);if(s&&n.nextStart=i&&(r.maxMaxBufferLength=n,this.warn("Reduce max buffer length to "+n+"s"),!0)},r.getAppendedFrag=function(e,t){var r=this.fragmentTracker.getAppendedFrag(e,Lt);return r&&"fragment"in r?r.fragment:r},r.getNextFragment=function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var n,s=this.config,a=r[0].start;if(t.live){var o=s.initialLiveManifestSize;if(it},r.getNextFragmentLoopLoading=function(e,t,r,i,n){var s=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(null===a)return a;if(e=a,s&&e&&!e.gap&&r.nextStart){var o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i);if(null!==o&&r.len+o.len>=n)return this.log('buffer full after gaps in "'+i+'" playlist starting at sn: '+e.sn),null}return e},r.mapToInitFragWhenRequired=function(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment},r.getNextPart=function(e,t,r){for(var i=-1,n=!1,s=!0,a=0,o=e.length;a-1&&rr.start&&r.loaded},r.getInitialLiveFragment=function(e,t){var r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!m(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i=e.startSN&&n<=e.endSN){var s=t[n-e.startSN];r.cc===s.cc&&(i=s,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(e,t){return or(e,(function(e){return e.cct?-1:0}))}(t,r.cc),i&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn))}}else{var a=this.hls.liveSyncPosition;null!==a&&(i=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i},r.getFragmentAtPosition=function(e,t,r){var i,n=this.config,s=this.fragPrevious,a=r.fragments,o=r.endSN,l=r.fragmentHint,h=n.maxFragLookUpTolerance,u=r.partList,d=!!(n.lowLatencyMode&&null!=u&&u.length&&l);if(d&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn),i=et-h?0:h):a[a.length-1]){var c=i.sn-r.startSN,f=this.fragmentTracker.getState(i);if((f===Pr||f===wr&&i.gap)&&(s=i),s&&i.sn===s.sn&&(!d||u[0].fragment.sn>i.sn)&&s&&i.level===s.level){var g=a[c+1];i=i.sn=s-t.maxFragLookUpTolerance&&n<=a;if(null!==i&&r.duration>i&&(nr.startCC||e&&e.cc"+e.startSN+" prev-sn: "+(o?o.sn:"na")+" fragments: "+i),l}return n},r.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},r.setStartPosition=function(e,t){var r=this.startPosition;if(r "+(null==(n=this.fragCurrent)?void 0:n.url))}else{var s=t.details===T.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);var a=t.errorAction,o=a||{},l=o.action,h=o.retryCount,u=void 0===h?0:h,d=o.retryConfig;if(a&&5===l&&d){this.resetStartWhenNotLoaded(this.levelLastLoaded);var c=nr(d,u);this.warn("Fragment "+i.sn+" of "+e+" "+i.level+" errored with "+t.details+", retrying loading "+(u+1)+"/"+d.maxNumRetry+" in "+c+"ms"),a.resolved=!0,this.retryDate=self.performance.now()+c,this.state=Jr}else if(d&&a){if(this.resetFragmentErrors(e),!(u.5;n&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);var s=!n;return s&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+r+" buffer"),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),s}return!1},r.resetFragmentErrors=function(e){e===bt&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Yr&&(this.state=zr)},r.afterBufferFlushed=function(e,t,r){if(e){var i=Mr.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,r),this.state===ri&&this.resetLoadingState()}},r.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=zr},r.resetStartWhenNotLoaded=function(e){if(!this.loadedmetadata){this.startFragRequested=!1;var t=e?e.details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},r.resetWhenMissingContext=function(e){this.warn("The loading context changed while buffering fragment "+e.sn+" of level "+e.level+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()},r.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},r.updateLevelTiming=function(e,t,r,i){var n,s=this,a=r.details;if(a){if(!Object.keys(e.elementaryStreams).reduce((function(t,n){var o=e.elementaryStreams[n];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return s.warn("Could not parse fragment "+e.sn+" "+n+" duration reliably ("+l+")"),t||!1;var h=i?0:zt(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return s.hls.trigger(E.LEVEL_PTS_UPDATED,{details:a,level:r,drift:h,type:n,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)&&null===(null==(n=this.transmuxer)?void 0:n.error)){var o=new Error("Found no media in fragment "+e.sn+" of level "+e.level+" resetting transmuxer to fallback to playlist timing");if(0===r.fragmentError&&(r.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(o.message),this.hls.trigger(E.ERROR,{type:S.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn "+e.sn+' of level "'+r.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=ti,this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")},r.resetTransmuxer=function(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)},r.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},a(t,[{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}]),t}(br),oi=function(){function e(){this.chunks=[],this.dataLength=0}var t=e.prototype;return t.push=function(e){this.chunks.push(e),this.dataLength+=e.length},t.flush=function(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,n=0;n0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:xt,duration:Number.POSITIVE_INFINITY});n>>5}function gi(e,t){return t+1=e.length)return!1;var i=fi(e,t);if(i<=r)return!1;var n=t+i;return n===e.length||gi(e,n)}return!1}function mi(e,t,r,i,n){if(!e.samplerate){var s=function(e,t,r,i){var n,s,a,o,l=navigator.userAgent.toLowerCase(),h=i,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];n=1+((192&t[r+2])>>>6);var d=(60&t[r+2])>>>2;if(!(d>u.length-1))return a=(1&t[r+2])<<2,a|=(192&t[r+3])>>>6,A.log("manifest codec:"+i+", ADTS type:"+n+", samplingIndex:"+d),/firefox/i.test(l)?d>=6?(n=5,o=new Array(4),s=d-3):(n=2,o=new Array(2),s=d):-1!==l.indexOf("android")?(n=2,o=new Array(2),s=d):(n=5,o=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&d>=6?s=d-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(d>=6&&1===a||/vivaldi/i.test(l))||!i&&1===a)&&(n=2,o=new Array(2)),s=d)),o[0]=n<<3,o[0]|=(14&d)>>1,o[1]|=(1&d)<<7,o[1]|=a<<3,5===n&&(o[1]|=(14&s)>>1,o[2]=(1&s)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:u[d],channelCount:a,codec:"mp4a.40."+n,manifestCodec:h};var c=new Error("invalid ADTS sampling index:"+d);e.emit(E.ERROR,E.ERROR,{type:S.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!0,error:c,reason:c.message})}(t,r,i,n);if(!s)return;e.config=s.config,e.samplerate=s.samplerate,e.channelCount=s.channelCount,e.codec=s.codec,e.manifestCodec=s.manifestCodec,A.log("parsed codec:"+e.codec+", rate:"+s.samplerate+", channels:"+s.channelCount)}}function vi(e){return 9216e4/e}function yi(e,t,r,i,n){var s,a=i+n*vi(e.samplerate),o=function(e,t){var r=ci(e,t);if(t+r<=e.length){var i=fi(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,h=o.headerLength,u=h+l,d=Math.max(0,r+u-t.length);d?(s=new Uint8Array(u-h)).set(t.subarray(r+h,t.length),0):s=t.subarray(r+h,r+u);var c={unit:s,pts:a};return d||e.samples.push(c),{sample:c,length:u,missing:d}}var f=t.length-r;return(s=new Uint8Array(f)).set(t.subarray(r,t.length),0),{sample:{unit:s,pts:a},length:f,missing:-1}}var Ei=null,Si=[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],Ti=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],_i=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Li=[0,1,1,4];function bi(e,t,r,i,n){if(!(r+24>t.length)){var s=Ri(t,r);if(s&&r+s.frameLength<=t.length){var a=i+n*(9e4*s.samplesPerFrame/s.sampleRate),o={unit:t.subarray(r,r+s.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=s.channelCount,e.samplerate=s.sampleRate,e.samples.push(o),{sample:o,length:s.frameLength,missing:0}}}}function Ri(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,s=e[t+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==s){var a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Si[14*(3===r?3-i:3===i?3:4)+n-1],h=Ti[3*(3===r?0:2===r?1:2)+s],u=3===o?1:2,d=_i[r][i],c=Li[i],f=8*d*c,g=Math.floor(d*l/h+a)*c;if(null===Ei){var p=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ei=p?parseInt(p[1]):0}return!!Ei&&Ei<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:u,frameLength:g,samplesPerFrame:f}}}function Ai(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function wi(e,t){return t+18&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=i>1?r+i:t}return!1}(e)},t.demux=function(e,t){this.timeOffset=t;var r=e,i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Fe(this.remainderData,e));var s=function(e){var t={valid:null,remainder:null},r=we(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=ee(e,0,i.byteOffset-8),t.remainder=ee(e,i.byteOffset-8),t}(r);this.remainderData=s.remainder,i.samples=s.valid||new Uint8Array}else i.samples=r;var a=this.extractID3Track(i,t);return n.samples=Ne(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}},t.flush=function(){var e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(t,this.timeOffset);return r.samples=Ne(e,t),{videoTrack:t,audioTrack:li(),id3Track:i,textTrack:li()}},t.extractID3Track=function(e,t){var r=this.id3Track;if(e.samples.length){var i=we(e.samples,["emsg"]);i&&i.forEach((function(e){var i=function(e){var t=e[0],r="",i="",n=0,s=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==Te(e.subarray(h,h+1));)r+=Te(e.subarray(h,h+1)),h+=1;for(r+=Te(e.subarray(h,h+1)),h+=1;"\0"!==Te(e.subarray(h,h+1));)i+=Te(e.subarray(h,h+1)),h+=1;i+=Te(e.subarray(h,h+1)),h+=1,n=Le(e,12),s=Le(e,16),o=Le(e,20),l=Le(e,24),h=28}else if(1===t){n=Le(e,h+=4);var u=Le(e,h+=4),d=Le(e,h+=4);for(h+=4,a=Math.pow(2,32)*u+d,v(a)||(a=Number.MAX_SAFE_INTEGER,A.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Le(e,h),l=Le(e,h+=4),h+=4;"\0"!==Te(e.subarray(h,h+1));)r+=Te(e.subarray(h,h+1)),h+=1;for(r+=Te(e.subarray(h,h+1)),h+=1;"\0"!==Te(e.subarray(h,h+1));)i+=Te(e.subarray(h,h+1)),h+=1;i+=Te(e.subarray(h,h+1)),h+=1}return{schemeIdUri:r,value:i,timeScale:n,presentationTime:a,presentationTimeDelta:s,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(Ci.test(i.schemeIdUri)){var n=m(i.presentationTime)?i.presentationTime/i.timeScale:t+i.presentationTimeDelta/i.timeScale,s=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var a=i.payload;r.samples.push({data:a,len:a.byteLength,dts:n,pts:n,type:Ot,duration:s})}}))}return r},t.demuxSampleAes=function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},t.destroy=function(){},e}(),Di=function(e,t){var r=0,i=5;t+=i;for(var n=new Uint32Array(1),s=new Uint32Array(1),a=new Uint8Array(1);i>0;){a[0]=e[t];var o=Math.min(i,8),l=8-o;s[0]=4278190080>>>24+l<>l,r=r?r<t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;var s=t[r+4]>>6;if(s>=3)return-1;var a=[48e3,44100,32e3][s],o=63&t[r+4],l=2*[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][3*o+s];if(r+l>t.length)return-1;var h=t[r+6]>>5,u=0;2===h?u+=2:(1&h&&1!==h&&(u+=2),4&h&&(u+=2));var d=(t[r+6]<<8|t[r+7])>>12-u&1,c=[2,1,2,3,3,4,4,5][h]+d,f=t[r+5]>>3,g=7&t[r+5],p=new Uint8Array([s<<6|f<<1|g>>2,(3&g)<<6|h<<3|d<<2|o>>4,o<<4&224]),m=i+n*(1536/a*9e4),v=t.subarray(r,r+l);return e.config=p,e.channelCount=c,e.samplerate=a,e.samples.push({unit:v,pts:m}),l}var Oi=function(){function e(){this.VideoSample=null}var t=e.prototype;return t.createVideoSample=function(e,t,r,i){return{key:e,frame:!1,pts:t,dts:r,units:[],debug:i,length:0}},t.getLastNalUnit=function(e){var t,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){var n=i.units;r=n[n.length-1]}return r},t.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}e.debug.length&&A.log(e.pts+"/"+e.dts+":"+e.debug)},e}(),Fi=function(){function e(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},t.skipBits=function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;if(e>32&&A.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?r<>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},t.skipScalingList=function(e){for(var t=8,r=8,i=0;i4){var f=new Fi(c).readSliceType();2!==f&&4!==f&&7!==f&&9!==f||(u=!0)}u&&null!=(d=l)&&d.frame&&!l.key&&(a.pushAccessUnit(l,e),l=a.VideoSample=null),l||(l=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts,"")),l.frame=!0,l.key=u;break;case 5:s=!0,null!=(o=l)&&o.frame&&!l.key&&(a.pushAccessUnit(l,e),l=a.VideoSample=null),l||(l=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts,"")),l.key=!0,l.frame=!0;break;case 6:s=!0,Ue(i.data,1,r.pts,t.samples);break;case 7:var g,p;s=!0,h=!0;var m=i.data,v=new Fi(m).readSPS();if(!e.sps||e.width!==v.width||e.height!==v.height||(null==(g=e.pixelRatio)?void 0:g[0])!==v.pixelRatio[0]||(null==(p=e.pixelRatio)?void 0:p[1])!==v.pixelRatio[1]){e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.sps=[m],e.duration=n;for(var y=m.subarray(1,4),E="avc1.",S=0;S<3;S++){var T=y[S].toString(16);T.length<2&&(T="0"+T),E+=T}e.codec=E}break;case 8:s=!0,e.pps=[i.data];break;case 9:s=!0,e.audFound=!0,l&&a.pushAccessUnit(l,e),l=a.VideoSample=a.createVideoSample(!1,r.pts,r.dts,"");break;case 12:s=!0;break;default:s=!1,l&&(l.debug+="unknown NAL "+i.type+" ")}l&&s&&l.units.push(i)})),i&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)},r.parseAVCNALu=function(e,t){var r,i,n=t.byteLength,s=e.naluState||0,a=s,o=[],l=0,h=-1,u=0;for(-1===s&&(h=0,u=31&t[0],s=0,l=1);l=0){var d={data:t.subarray(h,i),type:u};o.push(d)}else{var c=this.getLastNalUnit(e.samples);c&&(a&&l<=4-a&&c.state&&(c.data=c.data.subarray(0,c.data.byteLength-a)),i>0&&(c.data=Fe(c.data,t.subarray(0,i)),c.state=0))}l=0&&s>=0){var f={data:t.subarray(h,n),type:u,state:s};o.push(f)}if(0===o.length){var g=this.getLastNalUnit(e.samples);g&&(g.data=Fe(g.data,t))}return e.naluState=s,o},t}(Oi),Bi=function(){function e(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new jr(t,{removePKCS7Padding:!1})}var t=e.prototype;return t.decryptBuffer=function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)},t.decryptAacSample=function(e,t,r){var i=this,n=e[t].unit;if(!(n.length<=16)){var s=n.subarray(16,n.length-n.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(a).then((function(s){var a=new Uint8Array(s);n.set(a,16),i.decrypter.isSync()||i.decryptAacSamples(e,t+1,r)}))}},t.decryptAacSamples=function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,r),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var s=n[r];if(!(s.data.length<=48||1!==s.type&&5!==s.type||(this.decryptAvcSample(e,t,r,i,s),this.decrypter.isSync())))return}}},e}(),Ui=188,Gi=function(){function e(e,t,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.videoParser=new Ni}e.probe=function(t){var r=e.syncOffset(t);return r>0&&A.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},e.syncOffset=function(e){for(var t=e.length,r=Math.min(940,t-Ui)+1,i=0;i1&&(0===s&&a>2||o+Ui>r))return s}i++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Se[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}};var t=e.prototype;return t.resetInitSegment=function(t,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i,this._duration=n},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,r,i,n){var s;void 0===i&&(i=!1),void 0===n&&(n=!1),i||(this.sampleAes=null);var a=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack,u=a.pid,d=a.pesData,c=o.pid,f=l.pid,g=o.pesData,p=l.pesData,m=null,v=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=Fe(this.remainderData,t)).length,this.remainderData=null),E>4>1){if((R=_+5+t[_+4])===_+Ui)continue}else R=_+4;switch(b){case u:L&&(d&&(s=qi(d))&&this.videoParser.parseAVCPES(a,h,s,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(t.subarray(R,_+Ui)),d.size+=_+Ui-R);break;case c:if(L){if(g&&(s=qi(g)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,s);break;case"mp3":this.parseMPEGPES(o,s);break;case"ac3":this.parseAC3PES(o,s)}g={data:[],size:0}}g&&(g.data.push(t.subarray(R,_+Ui)),g.size+=_+Ui-R);break;case f:L&&(p&&(s=qi(p))&&this.parseID3PES(l,s),p={data:[],size:0}),p&&(p.data.push(t.subarray(R,_+Ui)),p.size+=_+Ui-R);break;case 0:L&&(R+=t[R]+1),y=this._pmtId=$i(t,R);break;case y:L&&(R+=t[R]+1);var w=Ki(t,R,this.typeSupported,i,this.observer);(u=w.videoPid)>0&&(a.pid=u,a.segmentCodec=w.segmentVideoCodec),(c=w.audioPid)>0&&(o.pid=c,o.segmentCodec=w.segmentAudioCodec),(f=w.id3Pid)>0&&(l.pid=f),null===m||v||(A.warn("MPEG-TS PMT found at "+_+" after unknown PID '"+m+"'. Backtracking to sync byte @"+S+" to parse all TS packets."),m=null,_=S-188),v=this.pmtParsed=!0;break;case 17:case 8191:break;default:m=b}}else T++;T>0&&Wi(this.observer,new Error("Found "+T+" TS packet/s that do not start with 0x47")),a.pesData=d,o.pesData=g,l.pesData=p;var P={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return n&&this.extractRemainingSamples(P),P},t.flush=function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e},t.extractRemainingSamples=function(e){var t,r=e.audioTrack,i=e.videoTrack,n=e.id3Track,s=e.textTrack,a=i.pesData,o=r.pesData,l=n.pesData;if(a&&(t=qi(a))?(this.videoParser.parseAVCPES(i,s,t,!0,this._duration),i.pesData=null):i.pesData=a,o&&(t=qi(o))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,t);break;case"mp3":this.parseMPEGPES(r,t);break;case"ac3":this.parseAC3PES(r,t)}r.pesData=null}else null!=o&&o.size&&A.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(t=qi(l))?(this.parseID3PES(n,t),n.pesData=null):n.pesData=l},t.demuxSampleAes=function(e,t,r){var i=this.demux(e,r,!0,!this.config.progressive),n=this.sampleAes=new Bi(this.observer,this.config,t);return this.decrypt(i,n)},t.decrypt=function(e,t){return new Promise((function(r){var i=e.audioTrack,n=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,(function(){n.samples?t.decryptAvcSamples(n.samples,0,0,(function(){r(e)})):r(e)})):n.samples&&t.decryptAvcSamples(n.samples,0,0,(function(){r(e)}))}))},t.destroy=function(){this._duration=0},t.parseAACPES=function(e,t){var r,i,n,s=0,a=this.aacOverFlow,o=t.data;if(a){this.aacOverFlow=null;var l=a.missing,h=a.sample.unit.byteLength;if(-1===l)o=Fe(a.sample.unit,o);else{var u=h-l;a.sample.unit.set(o.subarray(0,l),u),e.samples.push(a.sample),s=a.missing}}for(r=s,i=o.length;r0;)o+=n;else A.warn("[tsdemuxer]: AC3 PES unknown PTS")},t.parseID3PES=function(e,t){if(void 0!==t.pts){var r=o({},t,{type:this._videoTrack?Ot:xt,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else A.warn("[tsdemuxer]: ID3 PES unknown PTS")},e}();function Hi(e,t){return((31&e[t+1])<<8)+e[t+2]}function $i(e,t){return(31&e[t+10])<<8|e[t+11]}function Ki(e,t,r,i,n){var s={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t0)for(var h=t+5,u=l;u>2;){106===e[h]&&(!0!==r.ac3?A.log("AC-3 audio found, not supported in this browser for now"):(s.audioPid=o,s.segmentAudioCodec="ac3"));var d=e[h+1]+2;h+=d,u-=d}break;case 194:case 135:return Wi(n,new Error("Unsupported EC-3 in M2TS found")),s;case 36:return Wi(n,new Error("Unsupported HEVC in M2TS found")),s}t+=l+5}return s}function Wi(e,t,r){A.warn("parsing error: "+t.message),e.emit(E.ERROR,E.ERROR,{type:S.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Vi(e){A.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function qi(e){var t,r,i,n,s,a=0,o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=Fe(o[0],o[1]),o.splice(1,1);if(1===((t=o[0])[0]<<16)+(t[1]<<8)+t[2]){if((r=(t[4]<<8)+t[5])&&r>e.size-6)return null;var l=t[7];192&l&&(n=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?n-(s=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2)>54e5&&(A.warn(Math.round((n-s)/9e4)+"s delta between PTS and DTS, align them"),n=s):s=n);var h=(i=t[8])+9;if(e.size<=h)return null;e.size-=h;for(var u=new Uint8Array(e.size),d=0,c=o.length;df){h-=f;continue}t=t.subarray(h),f-=h,h=0}u.set(t,a),a+=f}return r&&(r-=i+3),{data:u,pts:n,dts:s,len:r}}return null}var ji=function(e){function t(){return e.apply(this,arguments)||this}l(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,n){e.prototype.resetInitSegment.call(this,t,r,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}},t.probe=function(e){if(!e)return!1;var t=ne(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==oe(t)&&Di(e,r)<=16)return!1;for(var i=e.length;r1?r-1:0),n=1;n>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),s=0,t=8;s>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/(zi+1)),n=Math.floor(r%(zi+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,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 e.box(e.types.mvhd,s)},e.sdtp=function(t){var r,i,n=t.samples||[],s=new Uint8Array(4+n.length);for(r=0;r>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(a))),l=t.width,h=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,h>>8&255,255&h,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,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,d>>24,d>>16&255,d>>8&255,255&d])))},e.esds=function(e){var t=e.config.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.config).concat([6,1,2]))},e.audioStsd=function(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])},e.mp4a=function(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){return e.box(e.types[".mp3"],e.audioStsd(t))},e.ac3=function(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))},e.stsd=function(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?e.box(e.types.stsd,e.STSD,e.mp3(t)):"ac3"===t.segmentCodec?e.box(e.types.stsd,e.STSD,e.ac3(t)):e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))},e.tkhd=function(t){var r=t.id,i=t.duration*t.timescale,n=t.width,s=t.height,a=Math.floor(i/(zi+1)),o=Math.floor(i%(zi+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,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]))},e.traf=function(t,r){var i=e.sdtp(t),n=t.id,s=Math.floor(r/(zi+1)),a=Math.floor(r%(zi+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,i.length+16+20+8+16+8+8),i)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,r){var i,n,s,a,o,l,h=t.samples||[],u=h.length,d=12+16*u,c=new Uint8Array(d);for(r+=8+d,c.set(["video"===t.type?1:0,0,15,1,u>>>24&255,u>>>16&255,u>>>8&255,255&u,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,s>>>16&255,s>>>8&255,255&s,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,c)},e.initSegment=function(t){e.types||e.init();var r=e.moov(t);return Fe(e.FTYP,r)},e}();Xi.types=void 0,Xi.HDLR_TYPES=void 0,Xi.STTS=void 0,Xi.STSC=void 0,Xi.STCO=void 0,Xi.STSZ=void 0,Xi.VMHD=void 0,Xi.SMHD=void 0,Xi.STSD=void 0,Xi.FTYP=void 0,Xi.DINF=void 0;function Qi(e,t,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=e*t*r;return i?Math.round(n):n}function Ji(e,t){return void 0===t&&(t=!1),Qi(e,1e3,1/9e4,t)}var Zi=null,en=null,tn=function(){function e(e,t,r,i){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,null===Zi){var n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Zi=n?parseInt(n[1]):0}if(null===en){var s=navigator.userAgent.match(/Safari\/(\d+)/i);en=s?parseInt(s[1]):0}}var t=e.prototype;return t.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},t.resetTimeStamp=function(e){A.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e},t.resetNextTimestamp=function(){A.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},t.resetInitSegment=function(){A.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},t.getVideoStartPts=function(e){var t=!1,r=e.reduce((function(e,r){var i=r.pts-e;return i<-4294967296?(t=!0,rn(e,r.pts)):i>0?e:r.pts}),e[0].pts);return t&&A.debug("PTS rollover detected"),r},t.remux=function(e,t,r,i,n,s,a,o){var l,h,u,d,c,f,g=n,p=n,m=e.pid>-1,v=t.pid>-1,y=t.samples.length,E=e.samples.length>0,S=a&&y>0||y>1;if((!m||E)&&(!v||S)||this.ISGenerated||a){if(this.ISGenerated){var T,_,L,b,R=this.videoTrackConfig;!R||t.width===R.width&&t.height===R.height&&(null==(T=t.pixelRatio)?void 0:T[0])===(null==(_=R.pixelRatio)?void 0:_[0])&&(null==(L=t.pixelRatio)?void 0:L[1])===(null==(b=R.pixelRatio)?void 0:b[1])||this.resetInitSegment()}else u=this.generateIS(e,t,n,s);var w,P=this.isVideoContiguous,I=-1;if(S&&(I=function(e){for(var t=0;t0){A.warn("[mp4-remuxer]: Dropped "+I+" out of "+y+" video samples due to a missing keyframe");var C=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(I),t.dropped+=I,w=p+=(t.samples[0].pts-C)/t.inputTimeScale}else-1===I&&(A.warn("[mp4-remuxer]: No keyframe found out of "+y+" video samples"),f=!1);if(this.ISGenerated){if(E&&S){var k=this.getVideoStartPts(t.samples),D=(rn(e.samples[0].pts,k)-k)/t.inputTimeScale;g+=Math.max(0,D),p+=Math.max(0,-D)}if(E){if(e.samplerate||(A.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,n,s)),h=this.remuxAudio(e,g,this.isAudioContiguous,s,v||S||o===bt?p:void 0),S){var M=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(A.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(e,t,n,s)),l=this.remuxVideo(t,p,P,M)}}else S&&(l=this.remuxVideo(t,p,P,0));l&&(l.firstKeyFrame=I,l.independent=-1!==I,l.firstKeyFramePTS=w)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(c=nn(r,n,this._initPTS,this._initDTS)),i.samples.length&&(d=sn(i,n,this._initPTS))),{audio:h,video:l,initSegment:u,independent:f,text:d,id3:c}},t.generateIS=function(e,t,r,i){var n,s,a,o=e.samples,l=t.samples,h=this.typeSupported,u={},d=this._initPTS,c=!d||i,f="audio/mp4";if(c&&(n=s=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":h.mpeg?(f="audio/mpeg",e.codec=""):h.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}u.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&h.mpeg?new Uint8Array(0):Xi.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(a=e.inputTimeScale,d&&a===d.timescale?c=!1:n=s=o[0].pts-Math.round(a*r))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Xi.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(a=t.inputTimeScale,d&&a===d.timescale)c=!1;else{var g=this.getVideoStartPts(l),p=Math.round(a*r);s=Math.min(s,rn(l[0].dts,g)-p),n=Math.min(n,g-p)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(u).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:n,timescale:a},this._initDTS={baseTime:s,timescale:a}):n=a=void 0,{tracks:u,initPTS:n,timescale:a}},t.remuxVideo=function(e,t,r,i){var n,s,a=e.inputTimeScale,l=e.samples,h=[],u=l.length,d=this._initPTS,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,v=!1;if(!r||null===c){var y=t*a,_=l[0].pts-rn(l[0].dts,l[0].pts);Zi&&null!==c&&Math.abs(y-_-c)<15e3?r=!0:c=y-_}for(var L=d.baseTime*a/d.timescale,b=0;b0?b-1:b].dts&&(v=!0)}v&&l.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i})),n=l[0].dts;var w=l[l.length-1].dts-n,P=w?Math.round(w/(u-1)):g||e.inputTimeScale/30;if(r){var I=n-c,C=I>P,k=I<-1;if((C||k)&&(C?A.warn("AVC: "+Ji(I,!0)+" ms ("+I+"dts) hole between fragments detected at "+t.toFixed(3)):A.warn("AVC: "+Ji(-I,!0)+" ms ("+I+"dts) overlapping between fragments detected at "+t.toFixed(3)),!k||c>=l[0].pts||Zi)){n=c;var D=l[0].pts-I;if(C)l[0].dts=n,l[0].pts=D;else for(var M=0;MD);M++)l[M].dts-=I,l[M].pts-=I;A.log("Video: Initial PTS/DTS adjusted: "+Ji(D,!0)+"/"+Ji(n,!0)+", delta: "+Ji(I,!0)+" ms")}}for(var x=0,O=0,F=n=Math.max(0,n),N=0;N0?J.dts-l[Q-1].dts:P;if(ae=Q>0?J.pts-l[Q-1].pts:P,oe.stretchShortVideoTrack&&null!==this.nextAudioPts){var he=Math.floor(oe.maxBufferHole*a),ue=(i?p+i*a:this.nextAudioPts)-J.pts;ue>he?((g=ue-le)<0?g=le:q=!0,A.log("[mp4-remuxer]: It is approximately "+ue/90+" ms to the next segment; using duration "+g/90+" ms for the last video frame.")):g=le}else g=le}var de=Math.round(J.pts-J.dts);j=Math.min(j,g),z=Math.max(z,g),Y=Math.min(Y,ae),X=Math.max(X,ae),h.push(new on(J.key,g,ee,de))}if(h.length)if(Zi){if(Zi<70){var ce=h[0].flags;ce.dependsOn=2,ce.isNonSync=0}}else if(en&&X-Y0&&(i&&Math.abs(v-m)<9e3||Math.abs(rn(g[0].pts-y,v)-m)<20*h),g.forEach((function(e){e.pts=rn(e.pts-y,v)})),!r||m<0){if(g=g.filter((function(e){return e.pts>=0})),!g.length)return;m=0===n?0:i&&!f?Math.max(0,v):g[0].pts}if("aac"===e.segmentCodec)for(var _=this.config.maxAudioFramesDrift,L=0,b=m;L=_*h&&I<1e4&&f){var C=Math.round(P/h);(b=w-C*h)<0&&(C--,b+=h),0===L&&(this.nextAudioPts=m=b),A.warn("[mp4-remuxer]: Injecting "+C+" audio frame @ "+(b/s).toFixed(3)+"s due to "+Math.round(1e3*P/s)+" ms gap.");for(var k=0;k0))return;N+=p;try{x=new Uint8Array(N)}catch(e){return void this.observer.emit(E.ERROR,E.ERROR,{type:S.MUX_ERROR,details:T.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:N,reason:"fail allocating audio mdat "+N})}d||(new DataView(x.buffer).setUint32(0,N),x.set(Xi.types.mdat,4))}x.set($,p);var W=$.byteLength;p+=W,c.push(new on(!0,l,W,0)),F=K}var V=c.length;if(V){var q=c[c.length-1];this.nextAudioPts=m=F+a*q.duration;var j=d?new Uint8Array(0):Xi.moof(e.sequenceNumber++,O/a,o({},e,{samples:c}));e.samples=[];var Y=O/s,z=m/s,X={data1:j,data2:x,startPTS:Y,endPTS:z,startDTS:Y,endDTS:z,type:"audio",hasAudio:!0,hasVideo:!1,nb:V};return this.isAudioContiguous=!0,X}},t.remuxEmptyAudio=function(e,t,r,i){var n=e.inputTimeScale,s=n/(e.samplerate?e.samplerate:n),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:i.startDTS*n)+l,u=i.endDTS*n+l,d=1024*s,c=Math.ceil((u-h)/d),f=Yi.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(A.warn("[mp4-remuxer]: remux empty Audio"),f){for(var g=[],p=0;p4294967296;)e+=r;return e}function nn(e,t,r,i){var n=e.samples.length;if(n){for(var s=e.inputTimeScale,a=0;a0;n||(i=we(t,["encv"])),i.forEach((function(e){we(n?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var t=xe(e);if(t){var i=t.subarray(8,24);i.some((function(e){return 0!==e}))||(A.log("[eme] Patching keyId in 'enc"+(n?"a":"v")+">sinf>>tenc' box: "+ve(i)+" -> "+ve(r)),t.set(r,8))}}))}))})),e}(e,i)),this.emitInitSegment=!0},t.generateInitSegment=function(e){var t=this.audioCodec,r=this.videoCodec;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=Ie(e);i.audio&&(t=hn(i.audio,M)),i.video&&(r=hn(i.video,x));var n={};i.audio&&i.video?n.audiovideo={container:"video/mp4",codec:t+","+r,initSegment:e,id:"main"}:i.audio?n.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?n.video={container:"video/mp4",codec:r,initSegment:e,id:"main"}:A.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n},t.remux=function(e,t,r,i,n,s){var a,o,l=this.initPTS,h=this.lastEndTime,u={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};m(h)||(h=this.lastEndTime=n||0);var d=t.samples;if(null==d||!d.length)return u;var c={initPTS:void 0,timescale:1},f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return A.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);var g=function(e,t){for(var r=0,i=0,n=0,s=we(e,["moof","traf"]),a=0;an}(l,v,n,g)||c.timescale!==l.timescale&&s)&&(c.initPTS=v-n,l&&1===l.timescale&&A.warn("Adjusting initPTS by "+(c.initPTS-l.baseTime)),this.initPTS=l={baseTime:c.initPTS,timescale:1});var y=e?v-l.baseTime/l.timescale:h,E=y+g;!function(e,t,r){we(t,["moof","traf"]).forEach((function(t){we(t,["tfhd"]).forEach((function(i){var n=Le(i,4),s=e[n];if(s){var a=s.timescale||9e4;we(t,["tfdt"]).forEach((function(e){var t=e[0],i=r*a;if(i){var n=Le(e,4);if(0===t)n-=i,Ae(e,4,n=Math.max(n,0));else{n*=Math.pow(2,32),n+=Le(e,8),n-=i,n=Math.max(n,0);var s=Math.floor(n/(ye+1)),o=Math.floor(n%(ye+1));Ae(e,4,s),Ae(e,8,o)}}}))}}))}))}(f,d,l.baseTime/l.timescale),g>0?this.lastEndTime=E:(A.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var S=!!f.audio,T=!!f.video,_="";S&&(_+="audio"),T&&(_+="video");var L={data1:d,startPTS:y,startDTS:y,endPTS:E,endDTS:E,type:_,hasAudio:S,hasVideo:T,nb:1,dropped:0};return u.audio="audio"===L.type?L:void 0,u.video="audio"!==L.type?L:void 0,u.initSegment=c,u.id3=nn(r,n,l,l),i.samples.length&&(u.text=sn(i,n,l)),u},e}();function hn(e,t){var r=null==e?void 0:e.codec;if(r&&r.length>4)return r;if(t===M){if("ec-3"===r||"ac-3"===r||"alac"===r)return r;if("fLaC"===r||"Opus"===r)return nt(r,!1);var i="mp4a.40.5";return A.info('Parsed audio codec "'+r+'" or audio object type not handled. Using "'+i+'"'),i}return A.warn('Unhandled video codec "'+r+'"'),"hvc1"===r||"hev1"===r?"hvc1.1.6.L120.90":"av01"===r?"av01.0.04M.08":"avc1.42e01e"}try{an=self.performance.now.bind(self.performance)}catch(e){A.debug("Unable to use Performance API on this environment"),an=null==$?void 0:$.Date.now}var un=[{demux:ki,remux:ln},{demux:Gi,remux:tn},{demux:Ii,remux:tn},{demux:ji,remux:tn}];un.splice(2,0,{demux:Mi,remux:tn});var dn=function(){function e(e,t,r,i,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=r,this.vendor=i,this.id=n}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,r,i){var n=this,s=r.transmuxing;s.executeStart=an();var a=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var h=i||o,u=h.contiguous,d=h.discontinuity,c=h.trackSwitch,f=h.accurateTimeOffset,g=h.timeOffset,p=h.initSegmentChange,m=l.audioCodec,v=l.videoCodec,y=l.defaultInitPts,_=l.duration,L=l.initSegmentData,b=function(e,t){var r=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t),r}(a,t);if(b&&"AES-128"===b.method){var R=this.getDecrypter();if(!R.isSync())return this.decryptionPromise=R.webCryptoDecrypt(a,b.key.buffer,b.iv.buffer).then((function(e){var t=n.push(e,null,r);return n.decryptionPromise=null,t})),this.decryptionPromise;var w=R.softwareDecrypt(a,b.key.buffer,b.iv.buffer);if(r.part>-1&&(w=R.flush()),!w)return s.executeEnd=an(),cn(r);a=new Uint8Array(w)}var P=this.needsProbing(d,c);if(P){var I=this.configureTransmuxer(a);if(I)return A.warn("[transmuxer] "+I.message),this.observer.emit(E.ERROR,E.ERROR,{type:S.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),s.executeEnd=an(),cn(r)}(d||c||p||P)&&this.resetInitSegment(L,m,v,_,t),(d||p||P)&&this.resetInitialTimestamp(y),u||this.resetContiguity();var C=this.transmux(a,b,g,f,r),k=this.currentTransmuxState;return k.contiguous=!0,k.discontinuity=!1,k.trackSwitch=!1,s.executeEnd=an(),C},t.flush=function(e){var t=this,r=e.transmuxing;r.executeStart=an();var i=this.decrypter,n=this.currentTransmuxState,s=this.decryptionPromise;if(s)return s.then((function(){return t.flush(e)}));var a=[],o=n.timeOffset;if(i){var l=i.flush();l&&a.push(this.push(l,null,e))}var h=this.demuxer,u=this.remuxer;if(!h||!u)return r.executeEnd=an(),[cn(e)];var d=h.flush(o);return fn(d)?d.then((function(r){return t.flushRemux(a,r,e),a})):(this.flushRemux(a,d,e),a)},t.flushRemux=function(e,t,r){var i=t.audioTrack,n=t.videoTrack,s=t.id3Track,a=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,h=o.timeOffset;A.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var u=this.remuxer.remux(i,n,s,a,h,l,!0,this.id);e.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=an()},t.resetInitialTimestamp=function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,r,i,n){var s=this.demuxer,a=this.remuxer;s&&a&&(s.resetInitSegment(e,t,r,i),a.resetInitSegment(e,t,r,n))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},t.transmux=function(e,t,r,i,n){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,n):this.transmuxUnencrypted(e,r,i,n)},t.transmuxUnencrypted=function(e,t,r,i){var n=this.demuxer.demux(e,t,!1,!this.config.progressive),s=n.audioTrack,a=n.videoTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(s,a,o,l,t,r,!1,this.id),chunkMeta:i}},t.transmuxSampleAes=function(e,t,r,i,n){var s=this;return this.demuxer.demuxSampleAes(e,t,r).then((function(e){return{remuxResult:s.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,s.id),chunkMeta:n}}))},t.configureTransmuxer=function(e){for(var t,r=this.config,i=this.observer,n=this.typeSupported,s=this.vendor,a=0,o=un.length;a1&&l.id===(null==m?void 0:m.stats.chunkCount),_=!y&&(1===E||0===E&&(1===S||T&&S<=0)),L=self.performance.now();(y||E||0===n.stats.parsing.start)&&(n.stats.parsing.start=L),!s||!S&&_||(s.stats.parsing.start=L);var b=!(m&&(null==(u=n.initSegment)?void 0:u.url)===(null==(d=m.initSegment)?void 0:d.url)),R=new pn(v,_,o,y,g,b);if(!_||v||b){A.log("[transmuxer-interface, "+n.type+"]: Starting new transmux session for sn: "+l.sn+" p: "+l.part+" level: "+l.level+" id: "+l.id+"\n discontinuity: "+v+"\n trackSwitch: "+y+"\n contiguous: "+_+"\n accurateTimeOffset: "+o+"\n timeOffset: "+g+"\n initSegmentChange: "+b);var w=new gn(r,i,t,a,h);this.configureTransmuxer(w)}if(this.frag=n,this.part=s,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(f){var P=f.push(e,p,l,R);fn(P)?(f.async=!0,P.then((function(e){c.handleTransmuxComplete(e)})).catch((function(e){c.transmuxerError(e,l,"transmuxer-interface push error")}))):(f.async=!1,this.handleTransmuxComplete(P))}},r.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(r){var i=r.flush(e);fn(i)||r.async?(fn(i)||(i=Promise.resolve(i)),i.then((function(r){t.handleFlushResult(r,e)})).catch((function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")}))):this.handleFlushResult(i,e)}},r.transmuxerError=function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:S.MEDIA_ERROR,details:T.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:r}))},r.handleFlushResult=function(e,t){var r=this;e.forEach((function(e){r.handleTransmuxComplete(e)})),this.onFlush(t)},r.onWorkerMessage=function(e){var t=e.data;if(null!=t&&t.event){var r=this.hls;if(this.hls)switch(t.event){case"init":var i,n=null==(i=this.workerContext)?void 0:i.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":A[t.data.logType]&&A[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data)}}else A.warn("worker message received with no "+(t?"event name":"data"))},r.configureTransmuxer=function(e){var t=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)},r.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},e}();function _n(e,t){if(e.length!==t.length)return!1;for(var r=0;r0&&-1===e?(this.log("Override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t,this.state=zr):(this.loadedmetadata=!1,this.state=Zr),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()},r.doTick=function(){switch(this.state){case zr:this.doTickIdle();break;case Zr:var t,r=this.levels,i=this.trackId,n=null==r||null==(t=r[i])?void 0:t.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=ni}break;case Jr:var s,a=performance.now(),o=this.retryDate;if(!o||a>=o||null!=(s=this.media)&&s.seeking){var l=this.levels,h=this.trackId;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==l?void 0:l[h])||null),this.state=zr}break;case ni:var u=this.waitingData;if(u){var d=u.frag,c=u.part,f=u.cache,g=u.complete;if(void 0!==this.initPTS[d.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=Qr;var p={frag:d,part:c,payload:f.flush(),networkDetails:null};this._handleFragmentLoadProgress(p),g&&e.prototype._handleFragmentLoadComplete.call(this,p)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log("Waiting fragment cc ("+d.cc+") cancelled because video is at cc "+this.videoTrackCC),this.clearWaitingFragment();else{var m=this.getLoadPosition(),v=Mr.bufferInfo(this.mediaBuffer,m,this.config.maxBufferHole);hr(v.end,this.config.maxFragLookUpTolerance,d)<0&&(this.log("Waiting fragment cc ("+d.cc+") @ "+d.start+" cancelled because another fragment at "+v.end+" is needed"),this.clearWaitingFragment())}}else this.state=zr}this.onTickEnd()},r.clearWaitingFragment=function(){var e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=zr)},r.resetLoadingState=function(){this.clearWaitingFragment(),e.prototype.resetLoadingState.call(this)},r.onTickEnd=function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)},r.doTickIdle=function(){var e=this.hls,t=this.levels,r=this.media,i=this.trackId,n=e.config;if((r||!this.startFragRequested&&n.startFragPrefetch)&&null!=t&&t[i]){var s=t[i],a=s.details;if(!a||a.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(a))this.state=Zr;else{var o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,M,bt));var l=this.getFwdBufferInfo(o,bt);if(null!==l){var h=this.bufferedTrack,u=this.switchingTrack;if(!u&&this._streamEnded(l,a))return e.trigger(E.BUFFER_EOS,{type:"audio"}),void(this.state=ri);var d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Lt),c=l.len,f=this.getMaxBufferLength(null==d?void 0:d.len),g=a.fragments,p=g[0].start,m=this.flushing?this.getLoadPosition():l.end;if(u&&r){var v=this.getLoadPosition();h&&!Ln(u.attrs,h.attrs)&&(m=v),a.PTSKnown&&vp||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=p+.05)}if(!(c>=f&&!u&&md.end+a.targetduration;if(T||(null==d||!d.len)&&l.len){var _=this.getAppendedFrag(y.start,Lt);if(null===_)return;if(S||(S=!!_.gap||!!T&&0===d.len),T&&!S||S&&l.nextStart&&l.nextStart<_.end)return}this.loadFragment(y,s,m)}else this.bufferFlushed=!0}}}}},r.getMaxBufferLength=function(t){var r=e.prototype.getMaxBufferLength.call(this);return t?Math.min(Math.max(r,t),this.config.maxMaxBufferLength):r},r.onMediaDetaching=function(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,e.prototype.onMediaDetaching.call(this)},r.onAudioTracksUpdated=function(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map((function(e){return new qt(e)}))},r.onAudioTrackSwitching=function(e,t){var r=!!t.url;this.trackId=t.id;var i=this.fragCurrent;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),r?this.setInterval(100):this.resetTransmuxer(),r?(this.switchingTrack=t,this.state=zr,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=Yr),this.tick()},r.onManifestLoading=function(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1},r.onLevelLoaded=function(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(E.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)},r.onAudioTrackLoaded=function(e,t){var r;if(null!=this.mainDetails){var i=this.levels,n=t.details,s=t.id;if(i){this.log("Audio track "+s+" loaded ["+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+",duration:"+n.totalduration);var a=i[s],o=0;if(n.live||null!=(r=a.details)&&r.live){this.checkLiveUpdate(n);var l,h=this.mainDetails;if(n.deltaUpdateFailed||!h)return;!a.details&&n.hasProgramDateTime&&h.hasProgramDateTime?(Br(n,h),o=n.fragments[0].start):o=this.alignPlaylists(n,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=n,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,o),this.state!==Zr||this.waitForCdnTuneIn(n)||(this.state=zr),this.tick()}else this.warn("Audio tracks were reset while loading level "+s)}else this.cachedTrackLoadedData=t},r._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,n=e.payload,s=this.config,a=this.trackId,o=this.levels;if(o){var l=o[a];if(l){var h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);var u=s.defaultAudioCodec||l.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new Tn(this.hls,bt,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var c=this.initPTS[r.cc],f=null==(t=r.initSegment)?void 0:t.data;if(void 0!==c){var g=i?i.index:-1,p=-1!==g,m=new xr(r.level,r.sn,r.stats.chunkCount,n.byteLength,g,p);d.push(n,f,u,"",r,i,h.totalduration,!1,m,c)}else this.log("Unknown video PTS for cc "+r.cc+", waiting for video PTS before demuxing audio frag "+r.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+a),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new oi,complete:!1}).cache.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=ni}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},r._handleFragmentLoadComplete=function(t){this.waitingData?this.waitingData.complete=!0:e.prototype._handleFragmentLoadComplete.call(this,t)},r.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},r.onBufferCreated=function(e,t){var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)},r.onFragBuffered=function(e,t){var r=t.frag,n=t.part;if(r.type===bt)if(this.fragContextChanged(r))this.warn("Fragment "+r.sn+(n?" p: "+n.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+(this.switchingTrack?this.switchingTrack.name:"false"));else{if("initSegment"!==r.sn){this.fragPrevious=r;var s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(E.AUDIO_TRACK_SWITCHED,i({},s)))}this.fragBufferedComplete(r,n)}else if(!this.loadedmetadata&&r.type===Lt){var a=this.videoBuffer||this.media;a&&Mr.getBuffered(a).length&&(this.loadedmetadata=!0)}},r.onError=function(t,r){var i;if(r.fatal)this.state=ii;else switch(r.details){case T.FRAG_GAP:case T.FRAG_PARSING_ERROR:case T.FRAG_DECRYPT_ERROR:case T.FRAG_LOAD_ERROR:case T.FRAG_LOAD_TIMEOUT:case T.KEY_LOAD_ERROR:case T.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(bt,r);break;case T.AUDIO_TRACK_LOAD_ERROR:case T.AUDIO_TRACK_LOAD_TIMEOUT:case T.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==Zr||(null==(i=r.context)?void 0:i.type)!==Tt||(this.state=zr);break;case T.BUFFER_APPEND_ERROR:case T.BUFFER_FULL_ERROR:if(!r.parent||"audio"!==r.parent)return;if(r.details===T.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case T.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}},r.onBufferFlushing=function(e,t){t.type!==x&&(this.flushing=!0)},r.onBufferFlushed=function(e,t){var r=t.type;if(r!==x){this.flushing=!1,this.bufferFlushed=!0,this.state===ri&&(this.state=zr);var i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,r,bt),this.tick())}},r._handleTransmuxComplete=function(e){var t,r="audio",i=this.hls,n=e.remuxResult,s=e.chunkMeta,a=this.getCurrentContext(s);if(a){var l=a.frag,h=a.part,u=a.level,d=u.details,c=n.audio,f=n.text,g=n.id3,p=n.initSegment;if(!this.fragContextChanged(l)&&d){if(this.state=ei,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){var m=l.initSegment||l;this._bufferInitSegment(u,p.tracks,m,s),i.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:r,tracks:p.tracks})}if(c){var v=c.startPTS,y=c.endPTS,S=c.startDTS,T=c.endDTS;h&&(h.elementaryStreams[M]={startPTS:v,endPTS:y,startDTS:S,endDTS:T}),l.setElementaryStreamInfo(M,v,y,S,T),this.bufferFragmentData(c,l,h,s)}if(null!=g&&null!=(t=g.samples)&&t.length){var _=o({id:r,frag:l,details:d},g);i.trigger(E.FRAG_PARSING_METADATA,_)}if(f){var L=o({id:r,frag:l,details:d},f);i.trigger(E.FRAG_PARSING_USERDATA,L)}}else this.fragmentTracker.removeFragment(l)}else this.resetWhenMissingContext(s)},r._bufferInitSegment=function(e,t,r,i){if(this.state===ei){t.video&&delete t.video;var n=t.audio;if(n){n.id="audio";var s=e.audioCodec;this.log("Init audio buffer, container:"+n.container+", codecs[level/parsed]=["+s+"/"+n.codec+"]"),s&&1===s.split(",").length&&(n.levelCodec=s),this.hls.trigger(E.BUFFER_CODECS,t);var a=n.initSegment;if(null!=a&&a.byteLength){var o={type:"audio",frag:r,part:null,chunkMeta:i,parent:r.type,data:a};this.hls.trigger(E.BUFFER_APPENDING,o)}this.tickImmediate()}}},r.loadFragment=function(t,r,i){var n,s=this.fragmentTracker.getState(t);if(this.fragCurrent=t,this.switchingTrack||s===Rr||s===wr)if("initSegment"===t.sn)this._loadInitSegment(t,r);else if(null!=(n=r.details)&&n.live&&!this.initPTS[t.cc]){this.log("Waiting for video PTS in continuity counter "+t.cc+" of live stream before loading audio fragment "+t.sn+" of level "+this.trackId),this.state=ni;var a=this.mainDetails;a&&a.fragments[0].start!==r.details.fragments[0].start&&Br(r.details,a)}else this.startFragRequested=!0,e.prototype.loadFragment.call(this,t,r,i);else this.clearTrackerIfNeeded(t)},r.flushAudioIfNeeded=function(t){var r=this.media,i=this.bufferedTrack,n=null==i?void 0:i.attrs,s=t.attrs;r&&n&&(n.CHANNELS!==s.CHANNELS||i.name!==t.name||i.lang!==t.lang)&&(this.log("Switching audio track : flushing all audio"),e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)},r.completeAudioSwitch=function(e){var t=this.hls;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(E.AUDIO_TRACK_SWITCHED,i({},e))},t}(ai),An=function(e){function t(t){var r;return(r=e.call(this,t,"[audio-track-controller]")||this).tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.registerListeners(),r}l(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.ERROR,this.onError,this)},r.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,e.prototype.destroy.call(this)},r.onManifestLoading=function(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0},r.onManifestParsed=function(e,t){this.tracks=t.audioTracks||[]},r.onAudioTrackLoaded=function(e,t){var r=t.id,i=t.groupId,n=t.details,s=this.tracksInGroup[r];if(s&&s.groupId===i){var a=s.details;s.details=t.details,this.log("Audio track "+r+' "'+s.name+'" lang:'+s.lang+" group:"+i+" loaded ["+n.startSN+"-"+n.endSN+"]"),r===this.trackId&&this.playlistLoaded(r,t,a)}else this.warn("Audio track with id:"+r+" and group:"+i+" not found in active group "+(null==s?void 0:s.groupId))},r.onLevelLoading=function(e,t){this.switchLevel(t.level)},r.onLevelSwitching=function(e,t){this.switchLevel(t.level)},r.switchLevel=function(e){var t=this.hls.levels[e];if(t){var r=t.audioGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some((function(e){return-1===(null==i?void 0:i.indexOf(e))}))){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var s=this.tracks.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));if(s.length)this.selectDefaultTrack&&!s.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),s.forEach((function(e,t){e.id=t}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=s;var a=this.hls.config.audioPreference;if(!n&&a){var o=Er(a,s,Tr);if(o>-1)n=s[o];else{var l=Er(a,this.tracks);n=this.tracks[l]}}var h=this.findTrackId(n);-1===h&&n&&(h=this.findTrackId(null));var u={audioTracks:s};this.log("Updating audio tracks, "+s.length+" track(s) found in group(s): "+(null==r?void 0:r.join(","))),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,u);var d=this.trackId;if(-1!==h&&-1===d)this.setAudioTrack(h);else if(s.length&&-1===d){var c,f=new Error("No audio track selected for current audio group-ID(s): "+(null==(c=this.groupIds)?void 0:c.join(","))+" track count: "+s.length);this.warn(f.message),this.hls.trigger(E.ERROR,{type:S.MEDIA_ERROR,details:T.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}else this.shouldReloadPlaylist(n)&&this.setAudioTrack(this.trackId)}},r.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==Tt||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||(this.requestScheduled=-1,this.checkRetry(t)))},r.setAudioOption=function(e){var t=this.hls;if(t.config.audioPreference=e,e){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var i=this.currentTrack;if(i&&Sr(e,i,Tr))return i;var n=Er(e,this.tracksInGroup,Tr);if(n>-1){var s=this.tracksInGroup[n];return this.setAudioTrack(n),s}if(i){var a=t.loadLevel;-1===a&&(a=t.firstAutoLevel);var o=function(e,t,r,i,n){var s=t[i],a=t.reduce((function(e,t,r){var i=t.uri;return(e[i]||(e[i]=[])).push(r),e}),{})[s.uri];a.length>1&&(i=Math.max.apply(Math,a));var o=s.videoRange,l=s.frameRate,h=s.codecSet.substring(0,4),u=_r(t,i,(function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;var i=t.audioGroups,s=r.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));return Er(e,s,n)>-1}));return u>-1?u:_r(t,i,(function(t){var i=t.audioGroups,s=r.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));return Er(e,s,n)>-1}))}(e,t.levels,r,a,Tr);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=Er(e,r);if(l>-1)return r[l]}}}return null},r.setAudioTrack=function(e){var t=this.tracksInGroup;if(e<0||e>=t.length)this.warn("Invalid audio track id: "+e);else{this.clearTimer(),this.selectDefaultTrack=!1;var r=this.currentTrack,n=t[e],s=n.details&&!n.details.live;if(!(e===this.trackId&&n===r&&s||(this.log("Switching to audio-track "+e+' "'+n.name+'" lang:'+n.lang+" group:"+n.groupId+" channels:"+n.channels),this.trackId=e,this.currentTrack=n,this.hls.trigger(E.AUDIO_TRACK_SWITCHING,i({},n)),s))){var a=this.switchParams(n.url,null==r?void 0:r.details,n.details);this.loadPlaylist(a)}}},r.findTrackId=function(e){for(var t=this.tracksInGroup,r=0;r=n[o].start&&a<=n[o].end){s=n[o];break}var l=r.start+r.duration;s?s.end=l:(s={start:a,end:l},n.push(s)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null)}}},r.onBufferFlushing=function(e,t){var r=t.startOffset,i=t.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=i-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach((function(e){for(var t=0;t=n.length)&&o){this.log("Subtitle track "+a+" loaded ["+s.startSN+","+s.endSN+"]"+(s.lastPartSn?"[part-"+s.lastPartSn+"-"+s.lastPartIndex+"]":"")+",duration:"+s.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges;var l=0;if(s.live||null!=(r=o.details)&&r.live){var h=this.mainDetails;if(s.deltaUpdateFailed||!h)return;var u,d=h.fragments[0];o.details?0===(l=this.alignPlaylists(s,o.details,null==(u=this.levelLastLoaded)?void 0:u.details))&&d&&Jt(s,l=d.start):s.hasProgramDateTime&&h.hasProgramDateTime?(Br(s,h),l=s.fragments[0].start):d&&Jt(s,l=d.start)}o.details=s,this.levelLastLoaded=o,a===i&&(this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(this.mainDetails||s,l),this.tick(),s.live&&!this.fragCurrent&&this.media&&this.state===zr&&(lr(null,s.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}}else this.warn("Subtitle tracks were reset while loading level "+a)},r._handleFragmentLoadComplete=function(e){var t=this,r=e.frag,i=e.payload,n=r.decryptdata,s=this.hls;if(!this.fragContextChanged(r)&&i&&i.byteLength>0&&null!=n&&n.key&&n.iv&&"AES-128"===n.method){var a=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer).catch((function(e){throw s.trigger(E.ERROR,{type:S.MEDIA_ERROR,details:T.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e})).then((function(e){var t=performance.now();s.trigger(E.FRAG_DECRYPTED,{frag:r,payload:e,stats:{tstart:a,tdecrypt:t}})})).catch((function(e){t.warn(e.name+": "+e.message),t.state=zr}))}},r.doTick=function(){if(this.media){if(this.state===zr){var e=this.currentTrackId,t=this.levels,r=null==t?void 0:t[e];if(!r||!t.length||!r.details)return;var i=this.config,n=this.getLoadPosition(),s=Mr.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,i.maxBufferHole),a=s.end,o=s.len,l=this.getFwdBufferInfo(this.media,Lt),h=r.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;var u=h.fragments,d=u.length,c=h.edge,f=null,g=this.fragPrevious;if(ac-p?0:p;!(f=lr(g,u,Math.max(u[0].start,a),m))&&g&&g.start>>=0)>i-1)throw new DOMException("Failed to execute '"+t+"' on 'TimeRanges': The index provided ("+r+") is greater than the maximum bound ("+i+")");return e[r][t]};this.buffered={get length(){return e.length},end:function(r){return t("end",r,e.length)},start:function(r){return t("start",r,e.length)}}},In=function(e){function t(t){var r;return(r=e.call(this,t,"[subtitle-track-controller]")||this).media=null,r.tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.onTextTracksChanged=function(){if(r.useTextTrackPolling||self.clearInterval(r.subtitlePollingInterval),r.media&&r.hls.config.renderTextTracksNatively){for(var e=null,t=Mt(r.media.textTracks),i=0;i-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))},r.pollTrackChange=function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)},r.onMediaDetaching=function(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Mt(this.media.textTracks).forEach((function(e){kt(e)})),this.subtitleTrack=-1,this.media=null)},r.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},r.onManifestParsed=function(e,t){this.tracks=t.subtitleTracks},r.onSubtitleTrackLoaded=function(e,t){var r=t.id,i=t.groupId,n=t.details,s=this.tracksInGroup[r];if(s&&s.groupId===i){var a=s.details;s.details=t.details,this.log("Subtitle track "+r+' "'+s.name+'" lang:'+s.lang+" group:"+i+" loaded ["+n.startSN+"-"+n.endSN+"]"),r===this.trackId&&this.playlistLoaded(r,t,a)}else this.warn("Subtitle track with id:"+r+" and group:"+i+" not found in active group "+(null==s?void 0:s.groupId))},r.onLevelLoading=function(e,t){this.switchLevel(t.level)},r.onLevelSwitching=function(e,t){this.switchLevel(t.level)},r.switchLevel=function(e){var t=this.hls.levels[e];if(t){var r=t.subtitleGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some((function(e){return-1===(null==i?void 0:i.indexOf(e))}))){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var s=this.tracks.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));if(s.length)this.selectDefaultTrack&&!s.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),s.forEach((function(e,t){e.id=t}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=s;var a=this.hls.config.subtitlePreference;if(!n&&a){this.selectDefaultTrack=!1;var o=Er(a,s);if(o>-1)n=s[o];else{var l=Er(a,this.tracks);n=this.tracks[l]}}var h=this.findTrackId(n);-1===h&&n&&(h=this.findTrackId(null));var u={subtitleTracks:s};this.log("Updating subtitle tracks, "+s.length+' track(s) found in "'+(null==r?void 0:r.join(","))+'" group-id'),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,u),-1!==h&&-1===this.trackId&&this.setSubtitleTrack(h)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId)}},r.findTrackId=function(e){for(var t=this.tracksInGroup,r=this.selectDefaultTrack,i=0;i-1){var n=this.tracksInGroup[i];return this.setSubtitleTrack(i),n}if(r)return null;var s=Er(e,t);if(s>-1)return t[s]}}return null},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this);var r=this.currentTrack;if(this.shouldLoadPlaylist(r)&&r){var i=r.id,n=r.groupId,s=r.url;if(t)try{s=t.addDirectives(s)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}this.log("Loading subtitle playlist for id "+i),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:n,deliveryDirectives:t||null})}},r.toggleTrackModes=function(){var e=this.media;if(e){var t,r=Mt(e.textTracks),i=this.currentTrack;if(i&&((t=r.filter((function(e){return bn(i,e)}))[0])||this.warn('Unable to find subtitle TextTrack with name "'+i.name+'" and language "'+i.lang+'"')),[].slice.call(r).forEach((function(e){"disabled"!==e.mode&&e!==t&&(e.mode="disabled")})),t){var n=this.subtitleDisplay?"showing":"hidden";t.mode!==n&&(t.mode=n)}}},r.setSubtitleTrack=function(e){var t=this.tracksInGroup;if(this.media)if(e<-1||e>=t.length||!m(e))this.warn("Invalid subtitle track id: "+e);else{this.clearTimer(),this.selectDefaultTrack=!1;var r=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),i){var n=!!i.details&&!i.details.live;if(e!==this.trackId||i!==r||!n){this.log("Switching to subtitle-track "+e+(i?' "'+i.name+'" lang:'+i.lang+" group:"+i.groupId:""));var s=i.id,a=i.groupId,o=void 0===a?"":a,l=i.name,h=i.type,u=i.url;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:s,groupId:o,name:l,type:h,url:u});var d=this.switchParams(i.url,null==r?void 0:r.details,i.details);this.loadPlaylist(d)}}else this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:e})}else this.queuedDefaultTrack=e},a(t,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}}]),t}(cr),Cn=function(){function e(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}var t=e.prototype;return t.append=function(e,t,r){var i=this.queues[t];i.push(e),1!==i.length||r||this.executeNext(t)},t.insertAbort=function(e,t){this.queues[t].unshift(e),this.executeNext(t)},t.appendBlocker=function(e){var t,r=new Promise((function(e){t=e})),i={execute:t,onStart:function(){},onComplete:function(){},onError:function(){}};return this.append(i,e),r},t.executeNext=function(e){var t=this.queues[e];if(t.length){var r=t[0];try{r.execute()}catch(t){A.warn('[buffer-operation-queue]: Exception executing "'+e+'" SourceBuffer operation: '+t),r.onError(t);var i=this.buffers[e];null!=i&&i.updating||this.shiftAndExecuteNext(e)}}},t.shiftAndExecuteNext=function(e){this.queues[e].shift(),this.executeNext(e)},t.current=function(e){return this.queues[e][0]},e}(),kn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Dn=function(){function e(e){var t=this;this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=function(e){t.hls&&t.hls.pauseBuffering()},this._onStartStreaming=function(e){t.hls&&t.hls.resumeBuffering()},this._onMediaSourceOpen=function(){var e=t.media,r=t.mediaSource;t.log("Media source opened"),e&&(e.removeEventListener("emptied",t._onMediaEmptied),t.updateMediaElementDuration(),t.hls.trigger(E.MEDIA_ATTACHED,{media:e,mediaSource:r})),r&&r.removeEventListener("sourceopen",t._onMediaSourceOpen),t.checkPendingTracks()},this._onMediaSourceClose=function(){t.log("Media source closed")},this._onMediaSourceEnded=function(){t.log("Media source ended")},this._onMediaEmptied=function(){var e=t.mediaSrc,r=t._objectUrl;e!==r&&A.error("Media element src was set while attaching MediaSource ("+r+" > "+e+")")},this.hls=e;var r,i="[buffer-controller]";this.appendSource=(r=ze(e.config.preferManagedMediaSource),"undefined"!=typeof self&&r===self.ManagedMediaSource),this.log=A.log.bind(A,i),this.warn=A.warn.bind(A,i),this.error=A.error.bind(A,i),this._initSourceBuffer(),this.registerListeners()}var t=e.prototype;return t.hasSourceTypes=function(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0},t.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null},t.registerListeners=function(){var e=this.hls;e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this)},t.unregisterListeners=function(){var e=this.hls;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this)},t._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new Cn(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null},t.onManifestLoading=function(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null},t.onManifestParsed=function(e,t){var r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},t.onMediaAttaching=function(e,t){var r=this.media=t.media,i=ze(this.appendSource);if(r&&i){var n,s=this.mediaSource=new i;this.log("created media source: "+(null==(n=s.constructor)?void 0:n.name)),s.addEventListener("sourceopen",this._onMediaSourceOpen),s.addEventListener("sourceended",this._onMediaSourceEnded),s.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.addEventListener("startstreaming",this._onStartStreaming),s.addEventListener("endstreaming",this._onEndStreaming));var a=this._objectUrl=self.URL.createObjectURL(s);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&s instanceof o,Mn(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,a),r.load()}catch(e){r.src=a}else r.src=a;r.addEventListener("emptied",this._onMediaEmptied)}},t.onMediaDetaching=function(){var e=this.media,t=this.mediaSource,r=this._objectUrl;if(t){if(this.log("media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){this.warn("onMediaDetaching: "+e.message+" while calling endOfStream")}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),r&&self.URL.revokeObjectURL(r),this.mediaSrc===r?(e.removeAttribute("src"),this.appendSource&&Mn(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(E.MEDIA_DETACHED,void 0)},t.onBufferReset=function(){var e=this;this.getSourceBufferTypes().forEach((function(t){e.resetBuffer(t)})),this._initSourceBuffer()},t.resetBuffer=function(e){var t=this.sourceBuffer[e];try{var r;t&&(this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t))}catch(t){this.warn("onBufferReset "+e,t)}},t.onBufferCodecs=function(e,t){var r=this,i=this.getSourceBufferTypes().length,n=Object.keys(t);if(n.forEach((function(e){if(i){var n=r.tracks[e];if(n&&"function"==typeof n.buffer.changeType){var s,a=t[e],o=a.id,l=a.codec,h=a.levelCodec,u=a.container,d=a.metadata,c=st(n.codec,n.levelCodec),f=null==c?void 0:c.replace(kn,"$1"),g=st(l,h),p=null==(s=g)?void 0:s.replace(kn,"$1");if(g&&f!==p){"audio"===e.slice(0,5)&&(g=nt(g,r.appendSource));var m=u+";codecs="+g;r.appendChangeType(e,m),r.log("switching codec "+c+" to "+g),r.tracks[e]={buffer:n.buffer,codec:l,container:u,levelCodec:h,metadata:d,id:o}}}}else r.pendingTracks[e]=t[e]})),!i){var s=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==s&&(this.log(s+" bufferCodec event(s) expected "+n.join(",")),this.bufferCodecEventsExpected=s),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}},t.appendChangeType=function(e,t){var r=this,i=this.operationQueue,n={execute:function(){var n=r.sourceBuffer[e];n&&(r.log("changing "+e+" sourceBuffer type to "+t),n.changeType(t)),i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){r.warn("Failed to change "+e+" SourceBuffer type",t)}};i.append(n,e,!!this.pendingTracks[e])},t.onBufferAppending=function(e,t){var r=this,i=this.hls,n=this.operationQueue,s=this.tracks,a=t.data,o=t.type,l=t.frag,h=t.part,u=t.chunkMeta,d=u.buffering[o],c=self.performance.now();d.start=c;var f=l.stats.buffering,g=h?h.stats.buffering:null;0===f.start&&(f.start=c),g&&0===g.start&&(g.start=c);var p=s.audio,m=!1;"audio"===o&&"audio/mpeg"===(null==p?void 0:p.container)&&(m=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);var v=l.start,y={execute:function(){if(d.executeStart=self.performance.now(),m){var e=r.sourceBuffer[o];if(e){var t=v-e.timestampOffset;Math.abs(t)>=.1&&(r.log("Updating audio SourceBuffer timestampOffset to "+v+" (delta: "+t+") sn: "+l.sn+")"),e.timestampOffset=v)}}r.appendExecutor(a,o)},onStart:function(){},onComplete:function(){var e=self.performance.now();d.executeEnd=d.end=e,0===f.first&&(f.first=e),g&&0===g.first&&(g.first=e);var t=r.sourceBuffer,i={};for(var n in t)i[n]=Mr.getBuffered(t[n]);r.appendErrors[o]=0,"audio"===o||"video"===o?r.appendErrors.audiovideo=0:(r.appendErrors.audio=0,r.appendErrors.video=0),r.hls.trigger(E.BUFFER_APPENDED,{type:o,frag:l,part:h,chunkMeta:u,parent:l.type,timeRanges:i})},onError:function(e){var t={type:S.MEDIA_ERROR,parent:l.type,details:T.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:h,chunkMeta:u,error:e,err:e,fatal:!1};if(e.code===DOMException.QUOTA_EXCEEDED_ERR)t.details=T.BUFFER_FULL_ERROR;else{var n=++r.appendErrors[o];t.details=T.BUFFER_APPEND_ERROR,r.warn("Failed "+n+"/"+i.config.appendErrorMaxRetry+' times to append segment in "'+o+'" sourceBuffer'),n>=i.config.appendErrorMaxRetry&&(t.fatal=!0)}i.trigger(E.ERROR,t)}};n.append(y,o,!!this.pendingTracks[o])},t.onBufferFlushing=function(e,t){var r=this,i=this.operationQueue,n=function(e){return{execute:r.removeExecutor.bind(r,e,t.startOffset,t.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(E.BUFFER_FLUSHED,{type:e})},onError:function(t){r.warn("Failed to remove from "+e+" SourceBuffer",t)}}};t.type?i.append(n(t.type),t.type):this.getSourceBufferTypes().forEach((function(e){i.append(n(e),e)}))},t.onFragParsed=function(e,t){var r=this,i=t.frag,n=t.part,s=[],a=n?n.elementaryStreams:i.elementaryStreams;a[O]?s.push("audiovideo"):(a[M]&&s.push("audio"),a[x]&&s.push("video")),0===s.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var e=self.performance.now();i.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:i.stats;r.hls.trigger(E.FRAG_BUFFERED,{frag:i,part:n,stats:t,id:i.type})}),s)},t.onFragChanged=function(e,t){this.trimBuffers()},t.onBufferEos=function(e,t){var r=this;this.getSourceBufferTypes().reduce((function(e,i){var n=r.sourceBuffer[i];return!n||t.type&&t.type!==i||(n.ending=!0,n.ended||(n.ended=!0,r.log(i+" sourceBuffer now EOS"))),e&&!(n&&!n.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((function(){r.getSourceBufferTypes().forEach((function(e){var t=r.sourceBuffer[e];t&&(t.ending=!1)}));var e=r.mediaSource;e&&"open"===e.readyState?(r.log("Calling mediaSource.endOfStream()"),e.endOfStream()):e&&r.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)})))},t.onLevelUpdated=function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},t.trimBuffers=function(){var e=this.hls,t=this.details,r=this.media;if(r&&null!==t&&this.getSourceBufferTypes().length){var i=e.config,n=r.currentTime,s=t.levelTargetDuration,a=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(m(a)&&a>0){var o=Math.max(a,s),l=Math.floor(n/s)*s-o;this.flushBackBuffer(n,s,l)}if(m(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){var h=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),u=Math.max(h,s),d=Math.floor(n/s)*s+u;this.flushFrontBuffer(n,s,d)}}},t.flushBackBuffer=function(e,t,r){var i=this,n=this.details,s=this.sourceBuffer;this.getSourceBufferTypes().forEach((function(a){var o=s[a];if(o){var l=Mr.getBuffered(o);if(l.length>0&&r>l.start(0)){if(i.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:r}),null!=n&&n.live)i.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(o.ended&&l.end(l.length-1)-e<2*t)return void i.log("Cannot flush "+a+" back buffer while SourceBuffer is in ended state");i.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:a})}}}))},t.flushFrontBuffer=function(e,t,r){var i=this,n=this.sourceBuffer;this.getSourceBufferTypes().forEach((function(s){var a=n[s];if(a){var o=Mr.getBuffered(a),l=o.length;if(l<2)return;var h=o.start(l-1),u=o.end(l-1);if(r>h||e>=h&&e<=u)return;if(a.ended&&e-u<2*t)return void i.log("Cannot flush "+s+" front buffer while SourceBuffer is in ended state");i.hls.trigger(E.BUFFER_FLUSHING,{startOffset:h,endOffset:1/0,type:s})}}))},t.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var e=this.details,t=this.hls,r=this.media,i=this.mediaSource,n=e.fragments[0].start+e.totalduration,s=r.duration,a=m(i.duration)?i.duration:0;e.live&&t.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(e)):(n>a&&n>s||!m(s))&&(this.log("Updating Media Source duration to "+n.toFixed(3)),i.duration=n)}},t.updateSeekableRange=function(e){var t=this.mediaSource,r=e.fragments;if(r.length&&e.live&&null!=t&&t.setLiveSeekableRange){var i=Math.max(0,r[0].start),n=Math.max(i,i+e.totalduration);this.log("Media Source duration is set to "+t.duration+". Setting seekable range to "+i+"-"+n+"."),t.setLiveSeekableRange(i,n)}},t.checkPendingTracks=function(){var e=this.bufferCodecEventsExpected,t=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&(!e||2===i||"audiovideo"in r)){this.createSourceBuffers(r),this.pendingTracks={};var n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(E.BUFFER_CREATED,{tracks:this.tracks}),n.forEach((function(e){t.executeNext(e)}));else{var s=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:S.MEDIA_ERROR,details:T.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:s,reason:s.message})}}},t.createSourceBuffers=function(e){var t=this,r=this.sourceBuffer,i=this.mediaSource;if(!i)throw Error("createSourceBuffers called when mediaSource was null");var n=function(n){if(!r[n]){var s,a=e[n];if(!a)throw Error("source buffer exists for track "+n+", however track does not");var o=-1===(null==(s=a.levelCodec)?void 0:s.indexOf(","))?a.levelCodec:a.codec;o&&"audio"===n.slice(0,5)&&(o=nt(o,t.appendSource));var l=a.container+";codecs="+o;t.log("creating sourceBuffer("+l+")");try{var h=r[n]=i.addSourceBuffer(l),u=n;t.addBufferListener(u,"updatestart",t._onSBUpdateStart),t.addBufferListener(u,"updateend",t._onSBUpdateEnd),t.addBufferListener(u,"error",t._onSBUpdateError),t.appendSource&&t.addBufferListener(u,"bufferedchange",(function(e,r){var i=r.removedRanges;null!=i&&i.length&&t.hls.trigger(E.BUFFER_FLUSHED,{type:n})})),t.tracks[n]={buffer:h,codec:o,container:a.container,levelCodec:a.levelCodec,metadata:a.metadata,id:a.id}}catch(e){t.error("error while trying to add sourceBuffer: "+e.message),t.hls.trigger(E.ERROR,{type:S.MEDIA_ERROR,details:T.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:l})}}};for(var s in e)n(s)},t._onSBUpdateStart=function(e){this.operationQueue.current(e).onStart()},t._onSBUpdateEnd=function(e){var t;if("closed"!==(null==(t=this.mediaSource)?void 0:t.readyState)){var r=this.operationQueue;r.current(e).onComplete(),r.shiftAndExecuteNext(e)}else this.resetBuffer(e)},t._onSBUpdateError=function(e,t){var r,i=new Error(e+" SourceBuffer error. MediaSource readyState: "+(null==(r=this.mediaSource)?void 0:r.readyState));this.error(""+i,t),this.hls.trigger(E.ERROR,{type:S.MEDIA_ERROR,details:T.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});var n=this.operationQueue.current(e);n&&n.onError(i)},t.removeExecutor=function(e,t,r){var i=this.media,n=this.mediaSource,s=this.operationQueue,a=this.sourceBuffer[e];if(!i||!n||!a)return this.warn("Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void s.shiftAndExecuteNext(e);var o=m(i.duration)?i.duration:1/0,l=m(n.duration)?n.duration:1/0,h=Math.max(0,t),u=Math.min(r,o,l);u>h&&(!a.ending||a.ended)?(a.ended=!1,this.log("Removing ["+h+","+u+"] from the "+e+" SourceBuffer"),a.remove(h,u)):s.shiftAndExecuteNext(e)},t.appendExecutor=function(e,t){var r=this.sourceBuffer[t];if(r)r.ended=!1,r.appendBuffer(e);else if(!this.pendingTracks[t])throw new Error("Attempting to append to the "+t+" SourceBuffer, but it does not exist")},t.blockBuffers=function(e,t){var r=this;if(void 0===t&&(t=this.getSourceBufferTypes()),!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);var i=this.operationQueue,n=t.map((function(e){return i.appendBlocker(e)}));Promise.all(n).then((function(){e(),t.forEach((function(e){var t=r.sourceBuffer[e];null!=t&&t.updating||i.shiftAndExecuteNext(e)}))}))},t.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},t.addBufferListener=function(e,t,r){var i=this.sourceBuffer[e];if(i){var n=r.bind(this,e);this.listeners[e].push({event:t,listener:n}),i.addEventListener(t,n)}},t.removeBufferListeners=function(e){var t=this.sourceBuffer[e];t&&this.listeners[e].forEach((function(e){t.removeEventListener(e.event,e.listener)}))},a(e,[{key:"mediaSrc",get:function(){var e,t=(null==(e=this.media)?void 0:e.firstChild)||this.media;return null==t?void 0:t.src}}]),e}();function Mn(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}var xn={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},On=function(e){return String.fromCharCode(xn[e]||e)},Fn=15,Nn=100,Bn={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Un={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Gn={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Hn={25:2,26:4,29:6,30:8,31:10,27:13,28:15},$n=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Kn=function(){function e(){this.time=null,this.verboseLevel=0}return e.prototype.log=function(e,t){if(this.verboseLevel>=e){var r="function"==typeof t?t():t;A.log(this.time+" ["+e+"] "+r)}},e}(),Wn=function(e){for(var t=[],r=0;rNn&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Nn)},t.moveCursor=function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r=144&&this.backSpace();var r=On(e);this.pos>=Nn?this.logger.log(0,(function(){return"Cannot insert "+e.toString(16)+" ("+r+") at position "+t.pos+". Skipping it!"})):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))},t.clearFromPos=function(e){var t;for(t=e;t0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r},t.getTextAndFormat=function(){return this.rows},e}(),zn=function(){function e(e,t,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Yn(r),this.nonDisplayedMemory=new Yn(r),this.lastOutputScreen=new Yn(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var t=e.prototype;return t.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},t.getHandler=function(){return this.outputFilter},t.setHandler=function(e){this.outputFilter=e},t.setPAC=function(e){this.writeScreen.setPAC(e)},t.setBkgData=function(e){this.writeScreen.setBkgData(e)},t.setMode=function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(function(){return"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)},t.insertChars=function(e){for(var t=this,r=0;r=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)},t.outputDataUpdate=function(e){void 0===e&&(e=!1);var t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},t.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),Xn=function(){function e(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;var i=this.logger=new Kn;this.channels=[null,new zn(e,t,i),new zn(e+1,r,i)]}var t=e.prototype;return t.getHandler=function(e){return this.channels[e].getHandler()},t.setHandler=function(e,t){this.channels[e].setHandler(t)},t.addData=function(e,t){var r=this;this.logger.time=e;for(var i=function(e){var i=127&t[e],n=127&t[e+1],s=!1,a=null;if(0===i&&0===n)return 0;r.logger.log(3,(function(){return"["+Wn([t[e],t[e+1]])+"] -> ("+Wn([i,n])+")"}));var o=r.cmdHistory;if(i>=16&&i<=31){if(function(e,t,r){return r.a===e&&r.b===t}(i,n,o))return Qn(null,null,o),r.logger.log(3,(function(){return"Repeated command ("+Wn([i,n])+") is dropped"})),0;Qn(i,n,r.cmdHistory),(s=r.parseCmd(i,n))||(s=r.parseMidrow(i,n)),s||(s=r.parsePAC(i,n)),s||(s=r.parseBackgroundAttributes(i,n))}else Qn(null,null,o);if(!s&&(a=r.parseChars(i,n))){var l=r.currentChannel;l&&l>0?r.channels[l].insertChars(a):r.logger.log(2,"No channel found yet. TEXT-MODE?")}s||a||r.logger.log(2,(function(){return"Couldn't parse cleaned data "+Wn([i,n])+" orig: "+Wn([t[e],t[e+1]])}))},n=0;n=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;var r=20===e||21===e||23===e?1:2,i=this.channels[r];return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=r,!0},t.parseMidrow=function(e,t){var r=0;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(t),this.logger.log(3,(function(){return"MIDROW ("+Wn([e,t])+")"})),!0)}return!1},t.parsePAC=function(e,t){var r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;var i=e<=23?1:2;r=t>=64&&t<=95?1===i?Bn[e]:Gn[e]:1===i?Un[e]:Hn[e];var n=this.channels[i];return!!n&&(n.setPAC(this.interpretPAC(r,t)),this.currentChannel=i,!0)},t.interpretPAC=function(e,t){var r,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=!(1&~r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},t.parseChars=function(e,t){var r,i,n=null,s=null;return e>=25?(r=2,s=e-8):(r=1,s=e),s>=17&&s<=19?(i=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,(function(){return"Special char '"+On(i)+"' in channel "+r})),n=[i]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]),n&&this.logger.log(3,(function(){return"Char codes = "+Wn(n).join(",")})),n},t.parseBackgroundAttributes=function(e,t){var r;if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;var i={};16===e||24===e?(r=Math.floor((t-32)/2),i.background=$n[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var n=e<=23?1:2;return this.channels[n].setBkgData(i),!0},t.reset=function(){for(var e=0;ee)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},t.reset=function(){this.cueRanges=[],this.startTime=null},e}(),Zn=function(){if(null!=$&&$.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var r=t.toLowerCase();return!!~e.indexOf(r)&&r}function i(e){return r(t,e)}function n(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return S},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return _},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");_=t,this.hasBeenReset=!0}})),o.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}(),es=function(){function e(){}return e.prototype.decode=function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))},e}();function ts(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}var r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var rs=function(){function e(){this.values=Object.create(null)}var t=e.prototype;return t.set=function(e,t){this.get(e)||""===t||(this.values[e]=t)},t.get=function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},t.has=function(e){return e in this.values},t.alt=function(e,t,r){for(var i=0;i=0&&r<=100)return this.set(e,r),!0}return!1},e}();function is(e,t,r,i){var n=i?e.split(i):[e];for(var s in n)if("string"==typeof n[s]){var a=n[s].split(r);2===a.length&&t(a[0],a[1])}}var ns=new Zn(0,0,""),ss="middle"===ns.align?"middle":"center";function as(e,t,r){var i=e;function n(){var t=ts(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function s(){e=e.replace(/^\s+/,"")}if(s(),t.startTime=n(),s(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),s(),t.endTime=n(),s(),function(e,t){var i=new rs;is(e,(function(e,t){var n;switch(e){case"region":for(var s=r.length-1;s>=0;s--)if(r[s].id===t){i.set(e,r[s].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),i.integer(e,n[0]),i.percent(e,n[0])&&i.set("snapToLines",!1),i.alt(e,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",ss,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",ss,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",ss,"end","left","right"])}}),/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===ns.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",ss);var s=i.get("position","auto");"auto"===s&&50===ns.position&&(s="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=s}(e,t)}function os(e){return e.replace(//gi,"\n")}var ls=function(){function e(){this.state="INITIAL",this.buffer="",this.decoder=new es,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var t=e.prototype;return t.parse=function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=os(e);r>>0).toString()};function cs(e,t,r){return ds(e.toString())+ds(t.toString())+ds(r)}var fs="stpp.ttml.im1t",gs=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,ps=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ms={left:"start",center:"center",right:"end",start:"start",end:"end"};function vs(e,t,r,i){var n=we(new Uint8Array(e),["mdat"]);if(0!==n.length){var s,a,l,h=n.map((function(e){return me(e)})),u=(s=t.baseTime,1,void 0===(a=t.timescale)&&(a=1),void 0===l&&(l=!1),Qi(s,1,1/a,l));try{h.forEach((function(e){return r(function(e,t){var r=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");var i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(i).reduce((function(e,t){return e[t]=r.getAttribute("ttp:"+t)||i[t],e}),{}),s="preserve"!==r.getAttribute("xml:space"),a=Es(ys(r,"styling","style")),l=Es(ys(r,"layout","region")),h=ys(r,"body","[begin]");return[].map.call(h,(function(e){var r=Ss(e,s);if(!r||!e.hasAttribute("begin"))return null;var i=Ls(e.getAttribute("begin"),n),h=Ls(e.getAttribute("dur"),n),u=Ls(e.getAttribute("end"),n);if(null===i)throw _s(e);if(null===u){if(null===h)throw _s(e);u=i+h}var d=new Zn(i-t,u-t,r);d.id=cs(d.startTime,d.endTime,d.text);var c=function(e,t,r){var i="http://www.w3.org/ns/ttml#styling",n=null,s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return s&&r.hasOwnProperty(s)&&(n=r[s]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((function(r,s){var a=Ts(t,i,s)||Ts(e,i,s)||Ts(n,i,s);return a&&(r[s]=a),r}),{})}(l[e.getAttribute("region")],a[e.getAttribute("style")],a),f=c.textAlign;if(f){var g=ms[f];g&&(d.lineAlign=g),d.align=f}return o(d,c),d})).filter((function(e){return null!==e}))}(e,u))}))}catch(e){i(e)}}else i(new Error("Could not parse IMSC1 mdat"))}function ys(e,t,r){var i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function Es(e){return e.reduce((function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e}),{})}function Ss(e,t){return[].slice.call(e.childNodes).reduce((function(e,r,i){var n;return"br"===r.nodeName&&i?e+"\n":null!=(n=r.childNodes)&&n.length?Ss(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent}),"")}function Ts(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function _s(e){return new Error("Could not parse ttml timestamp "+e)}function Ls(e,t){if(!e)return null;var r=ts(e);return null===r&&(gs.test(e)?r=function(e,t){var r=gs.exec(e),i=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/t.frameRate}(e,t):ps.test(e)&&(r=function(e,t){var r=ps.exec(e),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),r}var bs=function(){function e(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}var t=e.prototype;return t.destroy=function(){var e=this.hls;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0},t.initCea608Parsers=function(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){var e=new Jn(this,"textTrack1"),t=new Jn(this,"textTrack2"),r=new Jn(this,"textTrack3"),i=new Jn(this,"textTrack4");this.cea608Parser1=new Xn(1,e,t),this.cea608Parser2=new Xn(3,r,i)}},t.addCues=function(e,t,r,i,n){for(var s,a,o,l,h=!1,u=n.length;u--;){var d=n[u],c=(s=d[0],a=d[1],o=t,l=r,Math.min(a,l)-Math.max(s,o));if(c>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],r),h=!0,c/(r-t)>.5))return}if(h||n.push([t,r]),this.config.renderTextTracksNatively){var f=this.captionsTracks[e];this.Cues.newCue(f,t,r,i)}else{var g=this.Cues.newCue(null,t,r,i);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:g,track:e})}},t.onInitPtsFound=function(e,t){var r=this,i=t.frag,n=t.id,s=t.initPTS,a=t.timescale,o=this.unparsedVttFrags;"main"===n&&(this.initPTS[i.cc]={baseTime:s,timescale:a}),o.length&&(this.unparsedVttFrags=[],o.forEach((function(e){r.onFragLoaded(E.FRAG_LOADED,e)})))},t.getExistingTrack=function(e,t){var r=this.media;if(r)for(var i=0;i0&&c.push(e)},u.onparsingerror=function(e){h=e},u.onflush=function(){h?a(h):s(c)},d.forEach((function(e){if(y){if(us(e,"X-TIMESTAMP-MAP=")){y=!1,e.slice(16).split(",").forEach((function(e){us(e,"LOCAL:")?g=e.slice(6):us(e,"MPEGTS:")&&(p=parseInt(e.slice(7)))}));try{v=function(e){var t=parseInt(e.slice(-3)),r=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(m(t)&&m(r)&&m(i)&&m(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*r,(t+=6e4*i)+36e5*n}(g)/1e3}catch(e){h=e}return}""===e&&(y=!1)}u.parse(e+"\n")})),u.flush()}(null!=(t=i.initSegment)&&t.data?Fe(i.initSegment.data,new Uint8Array(n)):n,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(function(e){r._appendCues(e,i.level),l.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(function(t){var s="Missing initPTS for VTT MPEGTS"===t.message;s?a.push(e):r._fallbackToIMSC1(i,n),A.log("Failed to parse VTT cue: "+t),s&&o>i.cc||l.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})}))}else a.push(e)},t._fallbackToIMSC1=function(e,t){var r=this,i=this.tracks[e.level];i.textCodec||vs(t,this.initPTS[e.cc],(function(){i.textCodec=fs,r._parseIMSC1(e,t)}),(function(){i.textCodec="wvtt"}))},t._appendCues=function(e,t){var r=this.hls;if(this.config.renderTextTracksNatively){var i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach((function(e){return Ct(i,e)}))}else{var n=this.tracks[t];if(!n)return;var s=n.default?"default":"subtitles"+t;r.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:s})}},t.onFragDecrypted=function(e,t){t.frag.type===Rt&&this.onFragLoaded(E.FRAG_LOADED,t)},t.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},t.onFragParsingUserdata=function(e,t){this.initCea608Parsers();var r=this.cea608Parser1,i=this.cea608Parser2;if(this.enabled&&r&&i){var n=t.frag,s=t.samples;if(n.type!==Lt||"NONE"!==this.closedCaptionsForLevel(n))for(var a=0;athis.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.getMaxLevel=function(t){var r=this,i=this.hls.levels;if(!i.length)return-1;var n=i.filter((function(e,i){return r.isLevelAllowed(e)&&i<=t}));return this.clientRect=null,e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},t.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},t.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},t.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t},t.isLevelAllowed=function(e){return!this.restrictedLevels.some((function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height}))},e.getMaxLevelByMediaSize=function(e,t,r){if(null==e||!e.length)return-1;for(var i,n,s=e.length-1,a=Math.max(t,r),o=0;o=a||l.height>=a)&&(i=l,!(n=e[o+1])||i.width!==n.width||i.height!==n.height)){s=o;break}}return s},a(e,[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return e}}]),e}(),Ps=function(){function e(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.registerListeners=function(){this.hls.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this)},t.unregisterListeners=function(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this)},t.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},t.onMediaAttaching=function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},t.checkFPS=function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,s=r-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*s/n,l=this.hls;if(l.trigger(E.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:r}),o>0&&s>l.config.fpsDroppedMonitoringThreshold*a){var h=l.currentLevel;A.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=h)&&(h-=1,l.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},e}(),Is="[eme]",Cs=function(){function e(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=e.CDMCleanupPromise?[e.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=A.debug.bind(A,Is),this.log=A.log.bind(A,Is),this.warn=A.warn.bind(A,Is),this.error=A.error.bind(A,Is),this.hls=t,this.config=t.config,this.registerListeners()}var t=e.prototype;return t.destroy=function(){this.unregisterListeners(),this.onMediaDetached();var e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null},t.registerListeners=function(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.MANIFEST_LOADED,this.onManifestLoaded,this)},t.unregisterListeners=function(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this)},t.getLicenseServerUrl=function(e){var t=this.config,r=t.drmSystems,i=t.widevineLicenseUrl,n=r[e];if(n)return n.licenseUrl;if(e===K.WIDEVINE&&i)return i;throw new Error('no license server URL configured for key-system "'+e+'"')},t.getServerCertificateUrl=function(e){var t=this.config.drmSystems[e];if(t)return t.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'+e+'"]')},t.attemptKeySystemAccess=function(e){var t=this,r=this.hls.levels,i=function(e,t,r){return!!e&&r.indexOf(e)===t},n=r.map((function(e){return e.audioCodec})).filter(i),s=r.map((function(e){return e.videoCodec})).filter(i);return n.length+s.length===0&&s.push("avc1.42e01e"),new Promise((function(r,i){!function e(a){var o=a.shift();t.getMediaKeysPromise(o,n,s).then((function(e){return r({keySystem:o,mediaKeys:e})})).catch((function(t){a.length?e(a):i(t instanceof Os?t:new Os({type:S.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))}(e)}))},t.requestMediaKeySystemAccess=function(e,t){var r=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof r){var i="Configured requestMediaKeySystemAccess is not a function "+r;return null===Z&&"http:"===self.location.protocol&&(i="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(i))}return r(e,t)},t.getMediaKeysPromise=function(e,t,r){var i=this,n=function(e,t,r,i){var n;switch(e){case K.FAIRPLAY:n=["cenc","sinf"];break;case K.WIDEVINE:case K.PLAYREADY:n=["cenc"];break;case K.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+e)}return function(e,t,r,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map((function(e){return{contentType:'audio/mp4; codecs="'+e+'"',robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}})),videoCapabilities:r.map((function(e){return{contentType:'video/mp4; codecs="'+e+'"',robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}}))}]}(n,t,r,i)}(e,t,r,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e],a=null==s?void 0:s.keySystemAccess;if(!a){this.log('Requesting encrypted media "'+e+'" key-system access with config: '+JSON.stringify(n)),a=this.requestMediaKeySystemAccess(e,n);var o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch((function(t){i.log('Failed to obtain access to key-system "'+e+'": '+t)})),a.then((function(t){i.log('Access for key-system "'+t.keySystem+'" obtained');var r=i.fetchServerCertificate(e);return i.log('Create media-keys for "'+e+'"'),o.mediaKeys=t.createMediaKeys().then((function(t){return i.log('Media-keys created for "'+e+'"'),r.then((function(r){return r?i.setMediaKeysServerCertificate(t,e,r):t}))})),o.mediaKeys.catch((function(t){i.error('Failed to create media-keys for "'+e+'"}: '+t)})),o.mediaKeys}))}return a.then((function(){return s.mediaKeys}))},t.createMediaKeySessionContext=function(e){var t=e.decryptdata,r=e.keySystem,i=e.mediaKeys;this.log('Creating key-system session "'+r+'" keyId: '+ve(t.keyId||[]));var n=i.createSession(),s={decryptdata:t,keySystem:r,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s},t.renewKeySession=function(e){var t=e.decryptdata;if(t.pssh){var r=this.createMediaKeySessionContext(e),i=this.getKeyIdString(t);this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(r,"cenc",t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)},t.getKeyIdString=function(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return ve(e.keyId)},t.updateKeySession=function(e,t){var r,i=e.mediaKeysSession;return this.log('Updating key-session "'+i.sessionId+'" for keyID '+ve((null==(r=e.decryptdata)?void 0:r.keyId)||[])+"\n } (data length: "+(t?t.byteLength:t)+")"),i.update(t)},t.selectKeySystemFormat=function(e){var t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: "+e.sn+" "+e.type+": "+e.level+") key formats "+t.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise},t.getKeyFormatPromise=function(e){var t=this;return new Promise((function(r,i){var n=Q(t.config),s=e.map(Y).filter((function(e){return!!e&&-1!==n.indexOf(e)}));return t.getKeySystemSelectionPromise(s).then((function(e){var t=e.keySystem,n=X(t);n?r(n):i(new Error('Unable to find format for key-system "'+t+'"'))})).catch(i)}))},t.loadKey=function(e){var t=this,r=e.keyInfo.decryptdata,i=this.getKeyIdString(r),n="(keyId: "+i+' format: "'+r.keyFormat+'" method: '+r.method+" uri: "+r.uri+")";this.log("Starting session for key "+n);var s=this.keyIdToKeySessionPromise[i];return s||(s=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(r).then((function(i){var s=i.keySystem,a=i.mediaKeys;return t.throwIfDestroyed(),t.log("Handle encrypted media sn: "+e.frag.sn+" "+e.frag.type+": "+e.frag.level+" using key "+n),t.attemptSetMediaKeys(s,a).then((function(){t.throwIfDestroyed();var e=t.createMediaKeySessionContext({keySystem:s,mediaKeys:a,decryptdata:r});return t.generateRequestWithPreferredKeySession(e,"cenc",r.pssh,"playlist-key")}))}))).catch((function(e){return t.handleError(e)})),s},t.throwIfDestroyed=function(e){if(!this.hls)throw new Error("invalid state")},t.handleError=function(e){this.hls&&(this.error(e.message),e instanceof Os?this.hls.trigger(E.ERROR,e.data):this.hls.trigger(E.ERROR,{type:S.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))},t.getKeySystemForKeyPromise=function(e){var t=this.getKeyIdString(e),r=this.keyIdToKeySessionPromise[t];if(!r){var i=Y(e.keyFormat),n=i?[i]:Q(this.config);return this.attemptKeySystemAccess(n)}return r},t.getKeySystemSelectionPromise=function(e){if(e.length||(e=Q(this.config)),0===e.length)throw new Os({type:S.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+JSON.stringify({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(e)},t._onMediaEncrypted=function(e){var t=this,r=e.initDataType,i=e.initData;if(this.debug('"'+e.type+'" event: init data type: "'+r+'"'),null!==i){var n,s;if("sinf"===r&&this.config.drmSystems[K.FAIRPLAY]){var a=Te(new Uint8Array(i));try{var o=G(JSON.parse(a).sinf),l=xe(new Uint8Array(o));if(!l)return;n=l.subarray(8,24),s=K.FAIRPLAY}catch(e){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{var h=function(e){if(!(e instanceof ArrayBuffer)||e.byteLength<32)return null;var t={version:0,systemId:"",kids:null,data:null},r=new DataView(e),i=r.getUint32(0);if(e.byteLength!==i&&i>44)return null;if(1886614376!==r.getUint32(4))return null;if(t.version=r.getUint32(8)>>>24,t.version>1)return null;t.systemId=ve(new Uint8Array(e,12,16));var n=r.getUint32(28);if(0===t.version){if(i-320)for(var s,a=0,o=n.length;a in key message");return H(atob(f))},t.setupLicenseXHR=function(e,t,r,i){var n=this,s=this.config.licenseXhrSetup;return s?Promise.resolve().then((function(){if(!r.decryptdata)throw new Error("Key removed");return s.call(n.hls,e,t,r,i)})).catch((function(a){if(!r.decryptdata)throw a;return e.open("POST",t,!0),s.call(n.hls,e,t,r,i)})).then((function(r){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:r||i}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))},t.requestLicense=function(e,t){var r=this,i=this.config.keyLoadPolicy.default;return new Promise((function(n,s){var a=r.getLicenseServerUrl(e.keySystem);r.log("Sending license request to URL: "+a);var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!r.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===o.readyState)if(200===o.status){r._requestLicenseFailureCount=0;var l=o.response;r.log("License received "+(l instanceof ArrayBuffer?l.byteLength:l));var h=r.config.licenseResponseCallback;if(h)try{l=h.call(r.hls,o,a,e)}catch(e){r.error(e)}n(l)}else{var u=i.errorRetry,d=u?u.maxNumRetry:0;if(r._requestLicenseFailureCount++,r._requestLicenseFailureCount>d||o.status>=400&&o.status<500)s(new Os({type:S.KEY_SYSTEM_ERROR,details:T.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed ("+a+"). Status: "+o.status+" ("+o.statusText+")"));else{var c=d-r._requestLicenseFailureCount+1;r.warn("Retrying license request, "+c+" attempts left"),r.requestLicense(e,t).then(n,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,r.setupLicenseXHR(o,a,e,t).then((function(t){var i=t.xhr,n=t.licenseChallenge;e.keySystem==K.PLAYREADY&&(n=r.unpackPlayReadyKeyMessage(i,n)),i.send(n)}))}))},t.onMediaAttached=function(e,t){if(this.config.emeEnabled){var r=t.media;this.media=r,r.addEventListener("encrypted",this.onMediaEncrypted),r.addEventListener("waitingforkey",this.onWaitingForKey)}},t.onMediaDetached=function(){var t=this,r=this.media,i=this.mediaKeySessions;r&&(r.removeEventListener("encrypted",this.onMediaEncrypted),r.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},$e.clearKeyUriToKeyIdMap();var n=i.length;e.CDMCleanupPromise=Promise.all(i.map((function(e){return t.removeSession(e)})).concat(null==r?void 0:r.setMediaKeys(null).catch((function(e){t.log("Could not clear media keys: "+e)})))).then((function(){n&&(t.log("finished closing key sessions and clearing media keys"),i.length=0)})).catch((function(e){t.log("Could not close sessions and clear media keys: "+e)}))},t.onManifestLoading=function(){this.keyFormatPromise=null},t.onManifestLoaded=function(e,t){var r=t.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var i=r.reduce((function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e}),[]);this.log("Selecting key-system from session-keys "+i.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(i)}},t.removeSession=function(e){var t=this,r=e.mediaKeysSession,i=e.licenseXhr;if(r){this.log("Remove licenses and keys and close session "+r.sessionId),e._onmessage&&(r.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;var n=this.mediaKeySessions.indexOf(e);return n>-1&&this.mediaKeySessions.splice(n,1),r.remove().catch((function(e){t.log("Could not remove session: "+e)})).then((function(){return r.close()})).catch((function(e){t.log("Could not close session: "+e)}))}},e}();Cs.CDMCleanupPromise=void 0;var ks,Ds,Ms,xs,Os=function(e){function t(t,r){var i;return(i=e.call(this,r)||this).data=void 0,t.error||(t.error=new Error(r)),i.data=t,t.err=t.error,i}return l(t,e),t}(c(Error));!function(e){e.MANIFEST="m",e.AUDIO="a",e.VIDEO="v",e.MUXED="av",e.INIT="i",e.CAPTION="c",e.TIMED_TEXT="tt",e.KEY="k",e.OTHER="o"}(ks||(ks={})),function(e){e.DASH="d",e.HLS="h",e.SMOOTH="s",e.OTHER="o"}(Ds||(Ds={})),function(e){e.OBJECT="CMCD-Object",e.REQUEST="CMCD-Request",e.SESSION="CMCD-Session",e.STATUS="CMCD-Status"}(Ms||(Ms={}));var Fs=((xs={})[Ms.OBJECT]=["br","d","ot","tb"],xs[Ms.REQUEST]=["bl","dl","mtp","nor","nrr","su"],xs[Ms.SESSION]=["cid","pr","sf","sid","st","v"],xs[Ms.STATUS]=["bs","rtp"],xs),Ns=function e(t,r){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map((function(t){return t instanceof e?t:new e(t)}))),this.value=t,this.params=r},Bs=function(e){this.description=void 0,this.description=e},Us="Dict";var Gs="Bare Item",Hs="Boolean",$s="Byte Sequence",Ks="Decimal",Ws="Integer",Vs=/[\x00-\x1f\x7f]+/,qs="Token",js="Key";function Ys(e,t,r){return function(e,t,r,i){return new Error("failed to "+e+' "'+(n=t,(Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n))+'" as ')+r,{cause:i});var n}("serialize",e,t,r)}function zs(e){if(function(e){return e<-999999999999999||99999999999999912)throw Ys(e,Ks);var r=t.toString();return r.includes(".")?r:r+".0"}var Js="String";function Zs(e){var t,r=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r))throw Ys(r,qs);return r}function ea(e){switch(typeof e){case"number":if(!m(e))throw Ys(e,Gs);return Number.isInteger(e)?zs(e):Qs(e);case"string":return function(e){if(Vs.test(e))throw Ys(e,Js);return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}(e);case"symbol":return Zs(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Ys(e,Hs);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@"+zs(e.getTime()/1e3)}(e);if(e instanceof Uint8Array)return function(e){if(!1===ArrayBuffer.isView(e))throw Ys(e,$s);return":"+(t=e,btoa(String.fromCharCode.apply(String,t))+":");var t}(e);if(e instanceof Bs)return Zs(e);default:throw Ys(e,Gs)}}function ta(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Ys(e,js);return e}function ra(e){return null==e?"":Object.entries(e).map((function(e){var t=e[0],r=e[1];return!0===r?";"+ta(t):";"+ta(t)+"="+ea(r)})).join("")}function ia(e){return e instanceof Ns?""+ea(e.value)+ra(e.params):ea(e)}var na=function(e){return"ot"===e||"sf"===e||"st"===e},sa=function(e){return"number"==typeof e?m(e):null!=e&&""!==e&&!1!==e},aa=function(e){return Math.round(e)},oa=function(e){return 100*aa(e/100)},la={br:aa,d:aa,bl:oa,dl:oa,mtp:oa,nor:function(e,t){return null!=t&&t.baseUrl&&(e=function(e,t){var r=new URL(e),i=new URL(t);if(r.origin!==i.origin)return e;for(var n=r.pathname.split("/").slice(1),s=i.pathname.split("/").slice(1,-1);n[0]===s[0];)n.shift(),s.shift();for(;s.length;)s.shift(),n.unshift("..");return n.join("/")}(e,t.baseUrl)),encodeURIComponent(e)},rtp:oa,tb:aa};function ha(e,t){return void 0===t&&(t={}),e?function(e,t){return function(e,t){var r;if(void 0===t&&(t={whitespace:!0}),"object"!=typeof e)throw Ys(e,Us);var i=e instanceof Map?e.entries():Object.entries(e),n=null!=(r=t)&&r.whitespace?" ":"";return Array.from(i).map((function(e){var t=e[0],r=e[1];r instanceof Ns==0&&(r=new Ns(r));var i,n=ta(t);return!0===r.value?n+=ra(r.params):(n+="=",Array.isArray(r.value)?n+="("+(i=r).value.map(ia).join(" ")+")"+ra(i.params):n+=ia(r)),n})).join(","+n)}(e,t)}(function(e,t){var r={};if(null==e||"object"!=typeof e)return r;var i=Object.keys(e).sort(),n=o({},la,null==t?void 0:t.formatters),s=null==t?void 0:t.filter;return i.forEach((function(i){if(null==s||!s(i)){var a=e[i],o=n[i];o&&(a=o(a,t)),"v"===i&&1===a||"pr"==i&&1===a||sa(a)&&(na(i)&&"string"==typeof a&&(a=new Bs(a)),r[i]=a)}})),r}(e,t),o({whitespace:!1},t)):""}var ua=/CMCD=[^&#]+/;var da=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){t.initialized&&(t.starved=!0),t.buffering=!0},this.onPlaying=function(){t.initialized||(t.initialized=!0),t.buffering=!1},this.applyPlaylistData=function(e){try{t.apply(e,{ot:ks.MANIFEST,su:!t.initialized})}catch(e){A.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var r=e.frag,i=t.hls.levels[r.level],n=t.getObjectType(r),s={d:1e3*r.duration,ot:n};n!==ks.VIDEO&&n!==ks.AUDIO&&n!=ks.MUXED||(s.br=i.bitrate/1e3,s.tb=t.getTopBandwidth(n)/1e3,s.bl=t.getBufferLength(n)),t.apply(e,s)}catch(e){A.warn("Could not generate segment CMCD data.",e)}},this.hls=e;var r=this.config=e.config,i=r.cmcd;null!=i&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||function(){try{return crypto.randomUUID()}catch(i){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/16),("x"==e?t:3&t|8).toString(16)}))}}}(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this)},t.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},t.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},t.onBufferCreated=function(e,t){var r,i;this.audioBuffer=null==(r=t.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(i=t.tracks.video)?void 0:i.buffer},t.createData=function(){var e;return{v:1,sf:Ds.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},t.apply=function(e,t){void 0===t&&(t={}),o(t,this.createData());var r=t.ot===ks.INIT||t.ot===ks.VIDEO||t.ot===ks.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var i=this.includeKeys;i&&(t=Object.keys(t).reduce((function(e,r){return i.includes(r)&&(e[r]=t[r]),e}),{})),this.useHeaders?(e.headers||(e.headers={}),function(e,t,r){o(e,function(e,t){var r;if(void 0===t&&(t={}),!e)return{};var i=Object.entries(e),n=Object.entries(Fs).concat(Object.entries((null==(r=t)?void 0:r.customHeaderMap)||{})),s=i.reduce((function(e,t){var r,i=t[0],s=t[1],a=(null==(r=n.find((function(e){return e[1].includes(i)})))?void 0:r[0])||Ms.REQUEST;return null!=e[a]||(e[a]={}),e[a][i]=s,e}),{});return Object.entries(s).reduce((function(e,r){var i=r[0],n=r[1];return e[i]=ha(n,t),e}),{})}(t,r))}(e.headers,t)):e.url=function(e,t,r){var i=function(e,t){if(void 0===t&&(t={}),!e)return"";var r=ha(e,t);return"CMCD="+encodeURIComponent(r)}(t,r);if(!i)return e;if(ua.test(e))return e.replace(ua,i);var n=e.includes("?")?"&":"?";return""+e+n+i}(e.url,t)},t.getObjectType=function(e){var t=e.type;return"subtitle"===t?ks.TIMED_TEXT:"initSegment"===e.sn?ks.INIT:"audio"===t?ks.AUDIO:"main"===t?this.hls.audioTracks.length?ks.VIDEO:ks.MUXED:void 0},t.getTopBandwidth=function(e){var t,r=0,i=this.hls;if(e===ks.AUDIO)t=i.audioTracks;else{var n=i.maxAutoLevel,s=n>-1?n+1:i.levels.length;t=i.levels.slice(0,s)}for(var a,o=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return f(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?f(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(t);!(a=o()).done;){var l=a.value;l.bitrate>r&&(r=l.bitrate)}return r>0?r:NaN},t.getBufferLength=function(e){var t=this.hls.media,r=e===ks.AUDIO?this.audioBuffer:this.videoBuffer;return r&&t?1e3*Mr.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len:NaN},t.createPlaylistLoader=function(){var e=this.config.pLoader,t=this.applyPlaylistData,r=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new r(e)}var i=e.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(e,r,i){t(e),this.loader.load(e,r,i)},a(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),e}()},t.createFragmentLoader=function(){var e=this.config.fLoader,t=this.applyFragmentData,r=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new r(e)}var i=e.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(e,r,i){t(e),this.loader.load(e,r,i)},a(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),e}()},e}(),ca=function(){function e(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=A.log.bind(A,"[content-steering]:"),this.registerListeners()}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.ERROR,this.onError,this))},t.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}},t.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},t.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},t.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},t.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},t.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},t.onManifestLoaded=function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())},t.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},t.onError=function(e,t){var r=t.errorAction;if(2===(null==r?void 0:r.action)&&1===r.flags){var i=this.levels,n=this.pathwayPriority,s=this.pathwayId;if(t.context){var a=t.context,o=a.groupId,l=a.pathwayId,h=a.type;o&&i?s=this.getPathwayForGroupId(o,h,s):l&&(s=l)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!n&&i&&(n=i.reduce((function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e}),[])),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==s),r.resolved||A.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+s+" levels: "+(i?i.length:i)+" priorities: "+JSON.stringify(n)+" penalized: "+JSON.stringify(this.penalizedPathways))}},t.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+r+'"'),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length?(this.log("Found "+t.length+"/"+e.length+' levels in Pathway "'+this.pathwayId+'"'),t):e},t.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},t.updatePathwayPriority=function(e){var t;this.pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach((function(e){i-r[e]>3e5&&delete r[e]}));for(var n=0;n0){this.log('Setting Pathway to "'+s+'"'),this.pathwayId=s,tr(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[a];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate "+o.bitrate+" to "+l.bitrate),this.hls.nextLoadLevel=a);break}}}},t.getPathwayForGroupId=function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),n=0;n=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var s=t.status,a="text"!==t.responseType;if(s>=200&&s<300&&(a&&t.response||null!==t.responseText)){r.loading.end=Math.max(self.performance.now(),r.loading.first);var o=a?t.response:t.responseText,l="arraybuffer"===t.responseType?o.byteLength:o.length;if(r.loaded=r.total=l,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;var h=this.callbacks.onProgress;if(h&&h(r,e,o,t),!this.callbacks)return;var u={url:t.responseURL,data:o,code:s};this.callbacks.onSuccess(u,r,e,t)}else{var d=n.loadPolicy.errorRetry;ar(d,r.retry,!1,{url:e.url,data:void 0,code:s})?this.retry(d):(A.error(s+" while loading "+e.url),this.callbacks.onError({code:s,text:t.statusText},e,t,r))}}}},t.loadtimeout=function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(ar(e,this.stats.retry,!0))this.retry(e);else{var t;A.warn("timeout while loading "+(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}},t.retry=function(e){var t=this.context,r=this.stats;this.retryDelay=nr(e,r.retry),r.retry++,A.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==t?void 0:t.url)+", retrying "+r.retry+"/"+e.maxNumRetry+" in "+this.retryDelay+"ms"),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)},t.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},t.getCacheAge=function(){var e=null;if(this.loader&&pa.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.loader&&new RegExp("^"+e+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null},e}(),va=/(\d+)-(\d+)\/(\d+)/,ya=function(){function e(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Ea,this.controller=new self.AbortController,this.stats=new D}var t=e.prototype;return t.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},t.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},t.load=function(e,t,r){var i=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var s=function(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(o({},e.headers))};return e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),r}(e,this.controller.signal),a=r.onProgress,l="arraybuffer"===e.responseType,h=l?"byteLength":"length",u=t.loadPolicy,d=u.maxTimeToFirstByteMs,c=u.maxLoadTimeMs;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=d&&m(d)?d:c,this.requestTimeout=self.setTimeout((function(){i.abortInternal(),r.onTimeout(n,e,i.response)}),t.timeout),self.fetch(this.request).then((function(s){i.response=i.loader=s;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(i.requestTimeout),t.timeout=c,i.requestTimeout=self.setTimeout((function(){i.abortInternal(),r.onTimeout(n,e,i.response)}),c-(o-n.loading.start)),!s.ok){var h=s.status,u=s.statusText;throw new Ta(u||"fetch, bad network response",h,s)}return n.loading.first=o,n.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=va.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(m(r))return r}var i=e.get("Content-Length");if(i)return parseInt(i)}(s.headers)||n.total,a&&m(t.highWaterMark)?i.loadProgressively(s,n,e,t.highWaterMark,a):l?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((function(s){var o=i.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(i.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var l=s[h];l&&(n.loaded=n.total=l);var u={url:o.url,data:s,code:o.status};a&&!m(t.highWaterMark)&&a(n,e,s,o),r.onSuccess(u,n,e,o)})).catch((function(t){if(self.clearTimeout(i.requestTimeout),!n.aborted){var s=t&&t.code||0,a=t?t.message:null;r.onError({code:s,text:a},e,t?t.details:null,n)}}))},t.getCacheAge=function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.response?this.response.headers.get(e):null},t.loadProgressively=function(e,t,r,i,n){void 0===i&&(i=0);var s=new oi,a=e.body.getReader();return function o(){return a.read().then((function(a){if(a.done)return s.dataLength&&n(t,r,s.flush(),e),Promise.resolve(new ArrayBuffer(0));var l=a.value,h=l.length;return t.loaded+=h,h=i&&n(t,r,s.flush(),e)):n(t,r,l,e),o()})).catch((function(){return Promise.reject()}))}()},e}();function Ea(e,t){return new self.Request(e.url,t)}var Sa,Ta=function(e){function t(t,r,i){var n;return(n=e.call(this,t)||this).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return l(t,e),t}(c(Error)),_a=/\s/,La=i(i({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:ma,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Lr,bufferController:Dn,capLevelController:ws,errorController:dr,fpsController:Ps,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Z,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:{newCue:function(e,t,r,i){for(var n,s,a,o,l,h=[],u=self.VTTCue||self.TextTrackCue,d=0;d=16?o--:o++;var g=os(l.trim()),p=cs(t,r,g);null!=e&&null!=(c=e.cues)&&c.getCueById(p)||((s=new u(t,r,g)).id=p,s.line=d+1,s.align="left",s.position=10+Math.min(80,10*Math.floor(8*o/32)),h.push(s))}return e&&h.length&&(h.sort((function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line})),h.forEach((function(t){return Ct(e,t)}))),h}},enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:wn,subtitleTrackController:In,timelineController:bs,audioStreamController:Rn,audioTrackController:An,emeController:Cs,cmcdController:da,contentSteeringController:ca});function ba(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(ba):Object.keys(e).reduce((function(t,r){return t[r]=ba(e[r]),t}),{}):e}var Ra=function(e){function t(t,r){var i;return(i=e.call(this,t,"[level-controller]")||this)._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}l(t,e);var r=t.prototype;return r._registerListeners=function(){var e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)},r._unregisterListeners=function(){var e=this.hls;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)},r.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},r.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},r.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},r.onManifestLoading=function(e,t){this.resetLevels()},r.onManifestLoaded=function(e,t){var r=this.hls.config.preferManagedMediaSource,i=[],n={},s={},a=!1,o=!1,l=!1;t.levels.forEach((function(e){var t,h,u=e.attrs,d=e.audioCodec,c=e.videoCodec;-1!==(null==(t=d)?void 0:t.indexOf("mp4a.40.34"))&&(Sa||(Sa=/chrome|firefox/i.test(navigator.userAgent)),Sa&&(e.audioCodec=d=void 0)),d&&(e.audioCodec=d=nt(d,r)),0===(null==(h=c)?void 0:h.indexOf("avc1"))&&(c=e.videoCodec=function(e){for(var t=e.split(","),r=0;r2){var n=i.shift()+".";n+=parseInt(i.shift()).toString(16),n+=("000"+parseInt(i.shift()).toString(16)).slice(-4),t[r]=n}}return t.join(",")}(c));var f=e.width,g=e.height,p=e.unknownCodecs;if(a||(a=!(!f||!g)),o||(o=!!c),l||(l=!!d),!(null!=p&&p.length||d&&!Qe(d,"audio",r)||c&&!Qe(c,"video",r))){var m=u.CODECS,v=u["FRAME-RATE"],y=u["HDCP-LEVEL"],E=u["PATHWAY-ID"],S=u.RESOLUTION,T=u["VIDEO-RANGE"],_=(E||".")+"-"+e.bitrate+"-"+S+"-"+v+"-"+m+"-"+T+"-"+y;if(n[_])if(n[_].uri===e.url||e.attrs["PATHWAY-ID"])n[_].addGroupId("audio",u.AUDIO),n[_].addGroupId("text",u.SUBTITLES);else{var L=s[_]+=1;e.attrs["PATHWAY-ID"]=new Array(L+1).join(".");var b=new qt(e);n[_]=b,i.push(b)}else{var R=new qt(e);n[_]=R,s[_]=1,i.push(R)}}})),this.filterAndSortMediaOptions(i,t,a,o,l)},r.filterAndSortMediaOptions=function(e,t,r,i,n){var s=this,a=[],o=[],l=e;if((r||i)&&n&&(l=l.filter((function(e){var t,r=e.videoCodec,i=e.videoRange,n=e.width,s=e.height;return(!!r||!(!n||!s))&&!!(t=i)&&Kt.indexOf(t)>-1}))),0!==l.length){if(t.audioTracks){var h=this.hls.config.preferManagedMediaSource;Aa(a=t.audioTracks.filter((function(e){return!e.audioCodec||Qe(e.audioCodec,"audio",h)})))}t.subtitles&&Aa(o=t.subtitles);var u=l.slice(0);l.sort((function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Kt.indexOf(e.videoRange)-Kt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=et(e.videoCodec),n=et(t.videoCodec);if(i!==n)return n-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var s=tt(e.codecSet),a=tt(t.codecSet);if(s!==a)return a-s}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));var d=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l)).length!==u.length)for(var c=0;cm&&m===La.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}var y=n&&!i,_={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:i,altAudio:!y&&a.some((function(e){return!!e.url}))};this.hls.trigger(E.MANIFEST_PARSED,_),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}else Promise.resolve().then((function(){if(s.hls){t.levels.length&&s.warn("One or more CODECS in variant not supported: "+JSON.stringify(t.levels[0].attrs));var e=new Error("no level with compatible codecs found in manifest");s.hls.trigger(E.ERROR,{type:S.MEDIA_ERROR,details:T.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}))},r.onError=function(e,t){!t.fatal&&t.context&&t.context.type===St&&t.context.level===this.level&&this.checkRetry(t)},r.onFragBuffered=function(e,t){var r=t.frag;if(void 0!==r&&r.type===Lt){var i=r.elementaryStreams;if(!Object.keys(i).some((function(e){return!!i[e]})))return;var n=this._levels[r.level];null!=n&&n.loadError&&(this.log("Resetting level error count of "+n.loadError+" on frag buffered"),n.loadError=0)}},r.onLevelLoaded=function(e,t){var r,i,n=t.level,s=t.details,a=this._levels[n];if(!a)return this.warn("Invalid level index "+n),void(null!=(i=t.deliveryDirectives)&&i.skip&&(s.deltaUpdateFailed=!0));n===this.currentLevelIndex?(0===a.fragmentError&&(a.loadError=0),this.playlistLoaded(n,t,a.details)):null!=(r=t.deliveryDirectives)&&r.skip&&(s.deltaUpdateFailed=!0)},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this);var r=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){var n=i.uri;if(t)try{n=t.addDirectives(n)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}var s=i.attrs["PATHWAY-ID"];this.log("Loading level index "+r+(void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:"")+" with"+(s?" Pathway "+s:"")+" "+n),this.clearTimer(),this.hls.trigger(E.LEVEL_LOADING,{url:n,level:r,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}},r.removeLevel=function(e){var t,r=this,i=this._levels.filter((function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));tr(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(E.LEVELS_UPDATED,{levels:i})},r.onLevelsUpdated=function(e,t){var r=t.levels;this._levels=r},r.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))},a(t,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(E.ERROR,{type:S.OTHER_ERROR,details:T.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}var n=this.currentLevelIndex,s=this.currentLevel,a=s?s.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n!==e||!o.details||!s||a!==l){this.log("Switching to level "+e+" ("+(o.height?o.height+"p ":"")+(o.videoRange?o.videoRange+" ":"")+(o.codecSet?o.codecSet+" ":"")+"@"+o.bitrate+")"+(l?" with Pathway "+l:"")+" from level "+n+(a?" with Pathway "+a:""));var h={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,h);var u=o.details;if(!u||u.live){var d=this.switchParams(o.uri,null==s?void 0:s.details,u);this.loadPlaylist(d)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}]),t}(cr);function Aa(e){var t={};e.forEach((function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}var wa=function(){function e(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}var t=e.prototype;return t.abort=function(e){for(var t in this.keyUriToKeyInfo){var r=this.keyUriToKeyInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}},t.detach=function(){for(var e in this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}},t.destroy=function(){for(var e in this.detach(),this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}},t.createKeyLoadError=function(e,t,r,i,n){return void 0===t&&(t=T.KEY_LOAD_ERROR),new Kr({type:S.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:r,networkDetails:i})},t.loadClear=function(e,t){var r=this;if(this.emeController&&this.config.emeEnabled)for(var i=e.sn,n=e.cc,s=function(){var e=t[a];if(n<=e.cc&&("initSegment"===i||"initSegment"===e.sn||i2,c=!u||t&&t.start<=s||u-s>2&&!this.fragmentTracker.getPartialFragment(s);if(d||c)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var f;if(!(h.len>0||u))return;var g=Math.max(u,h.start||0)-s,p=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,m=(null==p||null==(f=p.details)?void 0:f.live)?2*p.details.targetduration:2,v=this.fragmentTracker.getPartialFragment(s);if(g>0&&(g<=m||v))return void(i.paused||this._trySkipBufferHole(v))}var y=self.performance.now();if(null!==n){var E=y-n;if(a||!(E>=250)||(this._reportStall(h),this.media)){var S=Mr.bufferInfo(i,s,r.maxBufferHole);this._tryFixBufferStall(S,E)}}else this.stalled=y}else if(this.moved=!0,a||(this.nudgeRetry=0),null!==n){if(this.stallReported){var T=self.performance.now()-n;A.warn("playback not stuck anymore @"+s+", after "+Math.round(T)+"ms"),this.stallReported=!1}this.stalled=null}}},t._tryFixBufferStall=function(e,t){var r=this.config,i=this.fragmentTracker,n=this.media;if(null!==n){var s=n.currentTime,a=i.getPartialFragment(s);if(a&&(this._trySkipBufferHole(a)||!this.media))return;(e.len>r.maxBufferHole||e.nextStart&&e.nextStart-s1e3*r.highBufferWatchdogPeriod&&(A.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}},t._reportStall=function(e){var t=this.hls,r=this.media;if(!this.stallReported&&r){this.stallReported=!0;var i=new Error("Playback stalling at @"+r.currentTime+" due to low buffer ("+JSON.stringify(e)+")");A.warn(i.message),t.trigger(E.ERROR,{type:S.MEDIA_ERROR,details:T.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:e.len})}},t._trySkipBufferHole=function(e){var t=this.config,r=this.hls,i=this.media;if(null===i)return 0;var n=i.currentTime,s=Mr.bufferInfo(i,n,0),a=n0&&s.len<1&&i.readyState<3,h=a-n;if(h>0&&(o||l)){if(h>t.maxBufferHole){var u=this.fragmentTracker,d=!1;if(0===n){var c=u.getAppendedFrag(0,Lt);c&&a1?(i=0,this.bitrateTest=!0):i=r.firstAutoLevel),r.nextLoadLevel=i,this.level=r.loadLevel,this.loadedmetadata=!1}t>0&&-1===e&&(this.log("Override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=zr,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=Yr},r.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},r.doTick=function(){switch(this.state){case si:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(i))break;this.state=zr;break}if(this.hls.nextLoadLevel!==this.level){this.state=zr;break}break;case Jr:var n,s=self.performance.now(),a=this.retryDate;if(!a||s>=a||null!=(n=this.media)&&n.seeking){var o=this.levels,l=this.level,h=null==o?void 0:o[l];this.resetStartWhenNotLoaded(h||null),this.state=zr}}this.state===zr&&this.doTickIdle(),this.onTickEnd()},r.onTickEnd=function(){e.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},r.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=e.nextLoadLevel;if(null!=r&&r[n]){var s=r[n],a=this.getMainFwdBufferInfo();if(null!==a){var o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){var l={};return this.altAudio&&(l.type="video"),this.hls.trigger(E.BUFFER_EOS,l),void(this.state=ri)}e.loadLevel!==n&&-1===e.manualLevel&&this.log("Adapting to level "+n+" from level "+this.level),this.level=e.nextLoadLevel=n;var h=s.details;if(!h||this.state===si||h.live&&this.levelLastLoaded!==s)return this.level=n,void(this.state=si);var u=a.len,d=this.getMaxBufferLength(s.maxBitrate);if(!(u>=d)){this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);var c=this.backtrackFragment?this.backtrackFragment.start:a.end,f=this.getNextFragment(c,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==Pr){var g,p=(null!=(g=this.backtrackFragment)?g:f).sn-h.startSN,m=h.fragments[p-1];m&&f.cc===m.cc&&(f=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){var v=this.audioOnly&&!this.altAudio?M:x,y=(v===x?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,v,Lt)}f=this.getNextFragmentLoopLoading(f,h,a,Lt,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,s,c))}}}}},r.loadFragment=function(t,r,i){var n=this.fragmentTracker.getState(t);this.fragCurrent=t,n===Rr||n===wr?"initSegment"===t.sn?this._loadInitSegment(t,r):this.bitrateTest?(this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t,r)):(this.startFragRequested=!0,e.prototype.loadFragment.call(this,t,r,i)):this.clearTrackerIfNeeded(t)},r.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,Lt)},r.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},r.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},r.nextLevelSwitch=function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var r,i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);var n=this.getLevelDetails();if(null!=n&&n.live){var s=this.getMainFwdBufferInfo();if(!s||s.len<2*n.targetduration)return}if(!t.paused&&e){var a=e[this.hls.nextLoadLevel],o=this.fragLastKbps;r=o&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:0}else r=0;var l=this.getBufferedFrag(t.currentTime+r);if(l){var h=this.followingBufferedFrag(l);if(h){this.abortCurrentFrag();var u=h.maxStartPTS?h.maxStartPTS:h.start,d=h.duration,c=Math.max(l.end,u+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}},r.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Xr:case Qr:case Jr:case ei:case ti:this.state=zr}this.nextLoadPosition=this.getLoadPosition()},r.flushMainBuffer=function(t,r){e.prototype.flushMainBuffer.call(this,t,r,this.altAudio?"video":null)},r.onMediaAttached=function(t,r){e.prototype.onMediaAttached.call(this,t,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Ca(this.config,i,this.fragmentTracker,this.hls)},r.onMediaDetaching=function(){var t=this.media;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),e.prototype.onMediaDetaching.call(this)},r.onMediaPlaying=function(){this.tick()},r.onMediaSeeked=function(){var e=this.media,t=e?e.currentTime:null;m(t)&&this.log("Media seeked to "+t.toFixed(3));var r=this.getMainFwdBufferInfo();null!==r&&0!==r.len?this.tick():this.warn('Main forward buffer length on "seeked" event '+(r?r.len:"empty")+")")},r.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1},r.onManifestParsed=function(e,t){var r,i,n=!1,s=!1;t.levels.forEach((function(e){var t=e.audioCodec;t&&(n=n||-1!==t.indexOf("mp4a.40.2"),s=s||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=n&&s&&!("function"==typeof(null==(i=Pa())||null==(r=i.prototype)?void 0:r.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1},r.onLevelLoading=function(e,t){var r=this.levels;if(r&&this.state===zr){var i=r[t.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=si)}},r.onLevelLoaded=function(e,t){var r,i=this.levels,n=t.level,s=t.details,a=s.totalduration;if(i){this.log("Level "+n+" loaded ["+s.startSN+","+s.endSN+"]"+(s.lastPartSn?"[part-"+s.lastPartSn+"-"+s.lastPartIndex+"]":"")+", cc ["+s.startCC+", "+s.endCC+"] duration:"+a);var o=i[n],l=this.fragCurrent;!l||this.state!==Qr&&this.state!==Jr||l.level!==t.level&&l.loader&&this.abortCurrentFrag();var h=0;if(s.live||null!=(r=o.details)&&r.live){var u;if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;h=this.alignPlaylists(s,o.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(o.details=s,this.levelLastLoaded=o,this.hls.trigger(E.LEVEL_UPDATED,{details:s,level:n}),this.state===si){if(this.waitForCdnTuneIn(s))return;this.state=zr}this.startFragRequested?s.live&&this.synchronizeToLiveEdge(s):this.setStartPosition(s,h),this.tick()}else this.warn("Levels were reset while loading level "+n)},r._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,n=e.payload,s=this.levels;if(s){var a=s[r.level],o=a.details;if(!o)return this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset"),void this.fragmentTracker.removeFragment(r);var l=a.videoCodec,h=o.PTSKnown||!o.live,u=null==(t=r.initSegment)?void 0:t.data,d=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Tn(this.hls,Lt,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,p=new xr(r.level,r.sn,r.stats.chunkCount,n.byteLength,f,g),m=this.initPTS[r.cc];c.push(n,u,d,l,r,i,o.totalduration,h,p,m)}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},r.onAudioTrackSwitching=function(e,t){var r=this.altAudio;if(!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i&&(this.log("Switching to main audio track, cancel main fragment load"),i.abortRequests(),this.fragmentTracker.removeFragment(i)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var n=this.hls;r&&(n.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(E.AUDIO_TRACK_SWITCHED,t)}},r.onAudioTrackSwitched=function(e,t){var r=t.id,i=!!this.hls.audioTracks[r].url;if(i){var n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=i,this.tick()},r.onBufferCreated=function(e,t){var r,i,n=t.tracks,s=!1;for(var a in n){var o=n[a];if("main"===o.id){if(i=a,r=o,"video"===a){var l=n[a];l&&(this.videoBuffer=l.buffer)}}else s=!0}s&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part;if(!r||r.type===Lt){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===ti&&(this.state=zr));var n=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},r.onError=function(e,t){var r;if(t.fatal)this.state=ii;else switch(t.details){case T.FRAG_GAP:case T.FRAG_PARSING_ERROR:case T.FRAG_DECRYPT_ERROR:case T.FRAG_LOAD_ERROR:case T.FRAG_LOAD_TIMEOUT:case T.KEY_LOAD_ERROR:case T.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Lt,t);break;case T.LEVEL_LOAD_ERROR:case T.LEVEL_LOAD_TIMEOUT:case T.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==si||(null==(r=t.context)?void 0:r.type)!==St||(this.state=zr);break;case T.BUFFER_APPEND_ERROR:case T.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;if(t.details===T.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case T.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}},r.checkBuffer=function(){var e=this.media,t=this.gapController;if(e&&t&&e.readyState){if(this.loadedmetadata||!Mr.getBuffered(e).length){var r=this.state!==zr?this.fragCurrent:null;t.poll(this.lastCurrentTime,r)}this.lastCurrentTime=e.currentTime}},r.onFragLoadEmergencyAborted=function(){this.state=zr,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},r.onBufferFlushed=function(e,t){var r=t.type;if(r!==M||this.audioOnly&&!this.altAudio){var i=(r===x?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,Lt),this.tick()}},r.onLevelsUpdated=function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels},r.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},r.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t0&&(nT.cc;if(!1!==n.independent){var b=u.startPTS,R=u.endPTS,A=u.startDTS,w=u.endDTS;if(l)l.elementaryStreams[u.type]={startPTS:b,endPTS:R,startDTS:A,endDTS:w};else if(u.firstKeyFrame&&u.independent&&1===s.id&&!L&&(this.couldBacktrack=!0),u.dropped&&u.independent){var P=this.getMainFwdBufferInfo(),I=(P?P.end:this.getLoadPosition())+this.config.maxBufferHole,C=u.firstKeyFramePTS?u.firstKeyFramePTS:b;if(!_&&I2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,b,R,A,w),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,s,_||L)}else{if(!_&&!L)return void this.backtrack(o);o.gap=!0}}if(p){var k=p.startPTS,D=p.endPTS,x=p.startDTS,O=p.endDTS;l&&(l.elementaryStreams[M]={startPTS:k,endPTS:D,startDTS:x,endDTS:O}),o.setElementaryStreamInfo(M,k,D,x,O),this.bufferFragmentData(p,o,l,s)}if(g&&null!=c&&null!=(t=c.samples)&&t.length){var F={id:r,frag:o,details:g,samples:c.samples};i.trigger(E.FRAG_PARSING_METADATA,F)}if(g&&d){var N={id:r,frag:o,details:g,samples:d.samples};i.trigger(E.FRAG_PARSING_USERDATA,N)}}}else this.resetWhenMissingContext(s)},r._bufferInitSegment=function(e,t,r,i){var n=this;if(this.state===ei){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;var s=t.audio,a=t.video,o=t.audiovideo;if(s){var l=e.audioCodec,h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l=-1!==l.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var u=s.metadata;u&&"channelCount"in u&&1!==(u.channelCount||1)&&-1===h.indexOf("firefox")&&(l="mp4a.40.5")}l&&-1!==l.indexOf("mp4a.40.5")&&-1!==h.indexOf("android")&&"audio/mpeg"!==s.container&&(l="mp4a.40.2",this.log("Android: force audio codec to "+l)),e.audioCodec&&e.audioCodec!==l&&this.log('Swapping manifest audio codec "'+e.audioCodec+'" for "'+l+'"'),s.levelCodec=l,s.id="main",this.log("Init audio buffer, container:"+s.container+", codecs[selected/level/parsed]=["+(l||"")+"/"+(e.audioCodec||"")+"/"+s.codec+"]")}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log("Init video buffer, container:"+a.container+", codecs[level/parsed]=["+(e.videoCodec||"")+"/"+a.codec+"]")),o&&this.log("Init audiovideo buffer, container:"+o.container+", codecs[level/parsed]=["+e.codecs+"/"+o.codec+"]"),this.hls.trigger(E.BUFFER_CODECS,t),Object.keys(t).forEach((function(e){var s=t[e].initSegment;null!=s&&s.byteLength&&n.hls.trigger(E.BUFFER_APPENDING,{type:e,data:s,frag:r,part:null,chunkMeta:i,parent:r.type})})),this.tickImmediate()}},r.getMainFwdBufferInfo=function(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Lt)},r.backtrack=function(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=zr},r.checkFragmentChanged=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(Mr.isBuffered(e,r)?t=this.getAppendedFrag(r):Mr.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;var i=this.fragPlaying,n=t.level;i&&t.sn===i.sn&&i.level===n||(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),i&&i.level===n||this.hls.trigger(E.LEVEL_SWITCHED,{level:n}))}}},a(t,[{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}},{key:"currentProgramDateTime",get:function(){var e=this.media;if(e){var t=e.currentTime,r=this.currentFrag;if(r&&m(t)&&m(r.programDateTime)){var i=r.programDateTime+1e3*(t-r.start);return new Date(i)}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}]),t}(ai),Da=function(){function e(t){void 0===t&&(t={}),this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new vn,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,R(t.debug||!1,"Hls instance");var r=this.config=function(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var r=ba(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(e){var i=("level"===e?"playlist":e)+"LoadPolicy",s=void 0===t[i],a=[];n.forEach((function(n){var o=e+"Loading"+n,l=t[o];if(void 0!==l&&s){a.push(o);var h=r[i].default;switch(t[i]={default:h},n){case"TimeOut":h.maxLoadTimeMs=l,h.maxTimeToFirstByteMs=l;break;case"MaxRetry":h.errorRetry.maxNumRetry=l,h.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":h.errorRetry.retryDelayMs=l,h.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=l,h.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&A.warn('hls.js config: "'+a.join('", "')+'" setting(s) are deprecated, use "'+i+'": '+JSON.stringify(t[i]))})),i(i({},r),t)}(e.DefaultConfig,t);this.userConfig=t,r.progressive&&function(e){var t=e.loader;t!==ya&&t!==ma?(A.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=ya,e.progressive=!0,e.enableSoftwareAES=!0,A.log("[config]: Progressive streaming enabled, using FetchLoader"))}(r);var n=r.abrController,s=r.bufferController,a=r.capLevelController,o=r.errorController,l=r.fpsController,h=new o(this),u=this.abrController=new n(this),d=this.bufferController=new s(this),c=this.capLevelController=new a(this),f=new l(this),g=new Pt(this),p=new Gt(this),m=r.contentSteeringController,v=m?new m(this):null,y=this.levelController=new Ra(this,v),S=new Ir(this),T=new wa(this.config),_=this.streamController=new ka(this,S,T);c.setStreamController(_),f.setStreamController(_);var L=[g,y,_];v&&L.splice(1,0,v),this.networkControllers=L;var b=[u,d,c,f,p,S];this.audioTrackController=this.createController(r.audioTrackController,L);var w=r.audioStreamController;w&&L.push(new w(this,S,T)),this.subtitleTrackController=this.createController(r.subtitleTrackController,L);var P=r.subtitleStreamController;P&&L.push(new P(this,S,T)),this.createController(r.timelineController,b),T.emeController=this.emeController=this.createController(r.emeController,b),this.cmcdController=this.createController(r.cmcdController,b),this.latencyController=this.createController(Ht,b),this.coreComponents=b,L.push(h);var I=h.onErrorOut;"function"==typeof I&&this.on(E.ERROR,I,h)}e.isMSESupported=function(){return Ia()},e.isSupported=function(){return function(){if(!Ia())return!1;var e=ze();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((function(t){return e.isTypeSupported(Ze(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Ze(t,"audio"))})))}()},e.getMediaSource=function(){return ze()};var t=e.prototype;return t.createController=function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null},t.on=function(e,t,r){void 0===r&&(r=this),this._emitter.on(e,t,r)},t.once=function(e,t,r){void 0===r&&(r=this),this._emitter.once(e,t,r)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,r,i){void 0===r&&(r=this),this._emitter.off(e,t,r,i)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,r){return this._emitter.emit(e,t,r)},t.trigger=function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(A.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var r=e===E.ERROR;this.trigger(E.ERROR,{type:S.OTHER_ERROR,details:T.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1},t.listenerCount=function(e){return this._emitter.listenerCount(e)},t.destroy=function(){A.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((function(e){return e.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(e){return e.destroy()})),this.coreComponents.length=0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null},t.attachMedia=function(e){A.log("attachMedia"),this._media=e,this.trigger(E.MEDIA_ATTACHING,{media:e})},t.detachMedia=function(){A.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,void 0),this._media=null},t.loadSource=function(e){this.stopLoad();var t=this.media,r=this.url,i=this.url=p.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,A.log("loadSource:"+i),t&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})},t.startLoad=function(e){void 0===e&&(e=-1),A.log("startLoad("+e+")"),this.started=!0,this.networkControllers.forEach((function(t){t.startLoad(e)}))},t.stopLoad=function(){A.log("stopLoad"),this.started=!1,this.networkControllers.forEach((function(e){e.stopLoad()}))},t.resumeBuffering=function(){this.started&&this.networkControllers.forEach((function(e){"fragmentLoader"in e&&e.startLoad(-1)}))},t.pauseBuffering=function(){this.networkControllers.forEach((function(e){"fragmentLoader"in e&&e.stopLoad()}))},t.swapAudioCodec=function(){A.log("swapAudioCodec"),this.streamController.swapAudioCodec()},t.recoverMediaError=function(){A.log("recoverMediaError");var e=this._media;this.detachMedia(),e&&this.attachMedia(e)},t.removeLevel=function(e){this.levelController.removeLevel(e)},t.setAudioOption=function(e){var t;return null==(t=this.audioTrackController)?void 0:t.setAudioOption(e)},t.setSubtitleOption=function(e){var t;return null==(t=this.subtitleTrackController)||t.setSubtitleOption(e),null},a(e,[{key:"levels",get:function(){return this.levelController.levels||[]}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){A.log("set currentLevel:"+e),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){A.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){A.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){A.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){A.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(A.log("set autoLevelCapping:"+e),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return $t.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,i=0;i=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var n=e;n--;){var s=t[n].attrs["HDCP-LEVEL"];if(s&&s<=i)return n}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}],[{key:"version",get:function(){return"1.5.13"}},{key:"Events",get:function(){return E}},{key:"ErrorTypes",get:function(){return S}},{key:"ErrorDetails",get:function(){return T}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:La},set:function(t){e.defaultConfig=t}}]),e}();return Da.defaultConfig=void 0,Da},e.exports=i()}(!1)},424:(e,t)=>{"use strict";t.h=n;var r=2147483647;function i(e){if(e>r)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=n.prototype,t}function n(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return o(e)}return s(e,t,r)}function s(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!n.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var r=0|u(e,t),s=i(r),a=s.write(e,t);a!==r&&(s=s.slice(0,a));return s}(e,t);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(v(e,ArrayBuffer)||e&&v(e.buffer,ArrayBuffer))return function(e,t,r){if(t<0||e.byteLength=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function u(e,t){if(n.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||v(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return m(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;default:if(s)return i?-1:m(e).length;t=(""+t).toLowerCase(),s=!0}}function d(e,t,r,i){r=Number(r)||0;const n=e.length-r;i?(i=Number(i))>n&&(i=n):i=n;const s=t.length;let a;for(i>s/2&&(i=s/2),a=0;a>8,n=r%256,s.push(n),s.push(i);return s}(t,e.length-r),e,r,i)}function p(e,t,r,i){let n;for(n=0;n=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function m(e,t){var r;t=t||1/0;for(var i=e.length,n=null,s=[],a=0;a55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===i){(t-=3)>-1&&s.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&s.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function v(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function y(e){return e!=e}"undefined"!=typeof Symbol&&null!=Symbol.species&&n[Symbol.species]===n&&Object.defineProperty(n,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),n.from=function(e,t,r){return s(e,t,r)},n.prototype.__proto__=Uint8Array.prototype,n.__proto__=Uint8Array,n.alloc=function(e,t,r){return function(e,t,r){return a(e),e<=0?i(e):void 0!==t?"string"==typeof r?i(e).fill(t,r):i(e).fill(t):i(e)}(e,t,r)},n.allocUnsafe=function(e){return o(e)},n.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==n.prototype},n.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},n.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return n.alloc(0);var r;if(void 0===t)for(t=0,r=0;r=e.length&&(t=e.length),t||(t=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t=0;--a)e[a+t]=this[a+r];else Uint8Array.prototype.set.call(e,this.subarray(r,i),t);return s},n.prototype.write=function(e,t,r,i){if(void 0===t)i="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)i=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}const n=this.length-t;if((void 0===r||r>n)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let s=!1;for(;;)switch(i){case"hex":return d(this,e,t,r);case"utf8":case"utf-8":return c(this,e,t,r);case"ascii":case"latin1":case"binary":return f(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return g(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}}},832:function(e,t,r){var i;!function(n){"use strict";function s(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function a(e,t,r,i,n,a){return s((o=s(s(t,e),s(i,a)))<<(l=n)|o>>>32-l,r);var o,l}function o(e,t,r,i,n,s,o){return a(t&r|~t&i,e,t,n,s,o)}function l(e,t,r,i,n,s,o){return a(t&i|r&~i,e,t,n,s,o)}function h(e,t,r,i,n,s,o){return a(t^r^i,e,t,n,s,o)}function u(e,t,r,i,n,s,o){return a(r^(t|~i),e,t,n,s,o)}function d(e,t){var r,i,n,a,d;e[t>>5]|=128<>>9<<4)]=t;var c=1732584193,f=-271733879,g=-1732584194,p=271733878;for(r=0;r>5]>>>t%32&255);return r}function f(e){var t,r=[];for(r[(e.length>>2)-1]=void 0,t=0;t>5]|=(255&e.charCodeAt(t/8))<>>4&15)+i.charAt(15&t);return n}function p(e){return unescape(encodeURIComponent(e))}function m(e){return function(e){return c(d(f(e),8*e.length))}(p(e))}function v(e,t){return function(e,t){var r,i,n=f(e),s=[],a=[];for(s[15]=a[15]=void 0,n.length>16&&(n=d(n,8*e.length)),r=0;r<16;r+=1)s[r]=909522486^n[r],a[r]=1549556828^n[r];return i=d(s.concat(f(t)),512+8*t.length),c(d(a.concat(i),640))}(p(e),p(t))}function y(e,t,r){return t?r?v(t,e):g(v(t,e)):r?m(e):g(m(e))}void 0===(i=function(){return y}.call(t,r,t,e))||(e.exports=i)}()},365:e=>{const t={ANDROID_WEB:"android-web",IOS_WEB:"iOS-web",PC_NATIVE:"PC-web",PC_WEB:"PC-web"};var r={getNetType:function(){let e=(new RegExp("nettype\\/(\\w*)").exec(i())||[,""])[1].toLowerCase();if(!e&&navigator.connection){switch(navigator.connection.type){case"ethernet":e="ethernet";break;case"cellular":e="cellular";break;default:e="wifi"}}return e},getPlatform:function(){return r.isAndroid()||r.isAndroidWebView()?t.ANDROID_WEB:r.isIOS()||r.isIpad()||r.isIOSWebView()?t.IOS_WEB:r.isElectron()?t.PC_NATIVE:t.PC_WEB},isX5:function(){return this.isAndroid()&&/\s(TBS|X5Core)\/[\w\.\-]+/i.test(i())},isPC:function(){return!s(n("os "))&&!s(n("android[/ ]"))},isIOS:function(){return s(n("os "))},isIpad:function(){return i().match(/(ipad)/)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1},isAndroid:function(){return s(n("android[/ ]"))},isIOSSafari:function(){return this.isIOS()&&this.isSafari()},isIpadSafari:function(){return this.isIpad()&&this.isSafari()},isElectron:function(){return/electron/i.test(i())},isMobile:function(){return r.isAndroid()||r.isIOS()},isSafari:function(){return/^((?!chrome|android).)*safari/i.test(i())},isFirefox:function(){return/firefox/i.test(i())},isChrome:function(){return/chrome/i.test(i())},isLocalHost:function(){return"localhost"===location.hostname},isAndroidWebView:function(){const e=i();return e.indexOf("wv")>-1&&e.indexOf("android")>-1},isIOSWebView:function(){const e=i();return/\b(ipad|iphone|macintosh).*applewebKit(?!.*safari)/i.test(e)},isWebView:function(){return r.isAndroidWebView()||r.isIOSWebView()},device:t,getBrowser:function(){return r.isX5()?"X5":r.isAndroidWebView()?"Android-WebView":r.isIOSWebView()?"iOS-WebView":r.isChrome()?"Chrome":r.isFirefox()?"Firefox":r.isIpadSafari()?"iPad-Safari":r.isIOSSafari()?"iPhone-Safari":r.isSafari()?"Mac-Safari":"Unknown"}};function i(){return navigator.userAgent.toLowerCase()}function n(e){return""+(new RegExp(e+"(\\d+((\\.|_)\\d+)*)").exec(i())||[,0])[1]||void 0}function s(e){return parseFloat((e||"").replace(/\_/g,"."))||0}e.exports=r}},t={};function r(i){var n=t[i];if(void 0!==n)return n.exports;var s=t[i]={exports:{}};return e[i].call(s.exports,s,s.exports,r),s.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var i={};return(()=>{"use strict";r.d(i,{default:()=>Or});const e={DC_SIGNAL:"SIGNAL",DC_SIGNAL_BATCH:"SIGNAL_BATCH",DC_OPEN:"OPEN",DC_REQUEST:"REQUEST",DC_PIECE_NOT_FOUND:"PIECE_NOT_FOUND",DC_PIECE_ABORT:"PIECE_ABORT",DC_PIECE_CANCEL:"PIECE_CANCEL",DC_CLOSE:"CLOSE",DC_DISCONNECT:"DISCONNECT",DC_RESPONSE:"RESPONSE",DC_ERROR:"ERROR",DC_PIECE:"PIECE",DC_PIECE_DATA:"PIECE_DATA",DC_TIMEOUT:"TIMEOUT",DC_PIECE_ACK:"PIECE_ACK",DC_METADATA:"METADATA",DC_PLAT_ANDROID:"ANDROID",DC_PLAT_IOS:"IOS",DC_PLAT_WEB:"WEB",DC_CHOKE:"CHOKE",DC_UNCHOKE:"UNCHOKE",DC_HAVE:"HAVE",DC_HAVE_REVERSE:"HAVE_REVERSE",DC_LOST:"LOST",DC_GET_PEERS:"GET_PEERS",DC_PEERS:"PEERS",DC_STATS:"STATS",DC_PEER_SIGNAL:"PEER_SIGNAL",DC_PLAYLIST:"PLAYLIST",BM_LOST:"lost",BM_ADDED_SEG_:"BM_ADDED_SEG_",BM_ADDED_SN_:"BM_ADDED_SN_",BM_SEG_ADDED:"BM_SEG_ADDED",BM_FATAL_ERROR:"BM_FATAL_ERROR",FRAG_CHANGED:"FRAG_CHANGED",FRAG_LOADED:"FRAG_LOADED",FRAG_LOADING:"FRAG_LOADING",RESTART_P2P:"RESTART_P2P",EXCEPTION:"exception",SYN_OUTPUT:"SYN_OUTPUT",SYN_ERROR:"SYN_ERROR",SYN_PROGRESS:"SYN_PROGRESS",MEDIA_REBUFFER:"MEDIA_REBUFFER"},t={...e,SCH_WAIT_PEER:"SCH_WAIT_PEER",SW_PLAYLIST:"SW_PLAYLIST",SW_GET_PLAYLIST:"SW_GET_PLAYLIST",SW_GET_MEDIA:"SW_GET_MEDIA",SW_DEBUG:"SW_DEBUG",LEVEL_LOADED:"LEVEL_LOADED",MANIFEST_PARSED:"MANIFEST_PARSED"};var n=r(415),s=r.n(n),a=r(424),o=r(558),l=r.n(o);const h="__PROXY_IDENTIFIER__";const u=64e3;function d(){return!0}function c(e){return new URL(location.href).searchParams.get(e)}function f(e,t,r){const i=new URL(e);return i.searchParams.append(t,r),i.href}function g(){return Date.parse(new Date)/1e3}function p(e,t){return parseInt(Math.random()*(t-e+1)+e,10)}function m(e){return new Promise((t=>setTimeout(t,e)))}function v(){if("object"!=typeof self)return null;var e={RTCPeerConnection:self.RTCPeerConnection||self.mozRTCPeerConnection||self.webkitRTCPeerConnection,RTCSessionDescription:self.RTCSessionDescription||self.mozRTCSessionDescription||self.webkitRTCSessionDescription,RTCIceCandidate:self.RTCIceCandidate||self.mozRTCIceCandidate||self.webkitRTCIceCandidate};return e.RTCPeerConnection&&e.RTCPeerConnection.prototype?e:null}function y(e){const t=a.h.from(e),r=new a.h(e.byteLength);return t.copy(r),r}function E(){return location.protocol.startsWith("https")}function S(e,t,r){if(e.size<=t)return;const i=[...e.keys()];do{const t=i.shift();r&&r(e.get(t)),e.delete(t)}while(e.size>t)}function T(e,t){if(e.size<=t)return;const r=[...e.values()];do{e.delete(r.shift())}while(e.size>t)}function _(e){return e instanceof ArrayBuffer&&0!==e.byteLength}function L(e){if(!e)return{};const t=(e=e.substring(6)).split("-");if(2!==t.length)return{};const r=Number(t[0]),i=t[1]?Number(t[1]):-1;return{rangeStart:r,rangeEnd:i>=0?i+1:void 0}}function b(e){return e.split("?")[0]}function R(){let e=new Date,t=e.getHours(),r=e.getMinutes(),i=e.getSeconds(),n=e.getMilliseconds();return`${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}.${n}`}function A(e){return e&&"function"==typeof e}function w(e,t,r,i,n,s){e.sendPartialBuffer(r,i,{from:n,incompletes:s}),i.length{i?t.sendMsgPieceAbort(n,r,!0):t.uploading&&t.send(n),s&&(t.uploading=!1)}))}(t,e,!!r.reverse):e.uploading=!1}const P=e=>0===p(0,1)?[null,e]:[e,null];function I(e,t,r){return 1===e.length?t.length>=1&&r.length>=1?t[0].weight>r[0].weight?[t[0],e[0]]:[e[0],r[0]]:t.length>=1?[t[0],e[0]]:r.length>=1?[e[0],r[0]]:P(e[0]):[t.length>=1?t[0]:null,r.length>=1?r[0]:null]}function C(){const e=performance.now();return{trequest:e,tfirst:0,tload:0,aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:e,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}class k{constructor(e,t){this.target=t,this.type=e}}class D extends k{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}class M extends k{constructor(e=1e3,t="",r){super("close",r),this.code=e,this.reason=t,this.wasClean=!0}}const x=()=>{if("undefined"!=typeof WebSocket)return WebSocket},O={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1};class F{constructor(e,t,r={}){this._listeners={error:[],message:[],open:[],close:[]},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._messageQueue=[],this._closeCalled=!1,this._connectLock=!1,this._shouldReconnect=!0,this._retryCount=-1,this._binaryType="blob",this._url=e,this._protocols=t,this._options=r,this._options.startClosed&&(this._shouldReconnect=!1),this._connect(),this._handleOpen=this._handleOpen.bind(this),this._handleClose=this._handleClose.bind(this),this._handleMessage=this._handleMessage.bind(this),this._handleError=this._handleError.bind(this)}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return F.CONNECTING}get OPEN(){return F.OPEN}get CLOSING(){return F.CLOSING}get CLOSED(){return F.CLOSED}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?F.CLOSED:F.CONNECTING}get url(){return this._ws?this._ws.url:""}close(e=1e3,t){this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws&&this._ws.readyState!==this.CLOSED&&this._ws.close(e,t)}reconnect(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()}send(e){if(this._ws&&this._ws.readyState===this.OPEN)this._ws.send(e);else{const{maxEnqueuedMessages:t=O.maxEnqueuedMessages}=this._options;this._messageQueue.lengthe!==t)))}_getNextDelay(){const{reconnectionDelayGrowFactor:e=O.reconnectionDelayGrowFactor,minReconnectionDelay:t=O.minReconnectionDelay,maxReconnectionDelay:r=O.maxReconnectionDelay}=this._options;let i=0;return this._retryCount>0&&(i=t*Math.pow(e,this._retryCount-1),i>r&&(i=r)),i}_wait(){return new Promise((e=>{setTimeout(e,this._getNextDelay())}))}_getNextUrl(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){const t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;const{maxRetries:e=O.maxRetries,connectionTimeout:t=O.connectionTimeout,WebSocket:r=x()}=this._options;if(!(this._retryCount>=e)){if(this._retryCount++,this._removeListeners(),void 0===(i=r)||!i||2!==i.CLOSING)throw Error("No valid WebSocket class provided");var i;this._wait().then((()=>this._getNextUrl(this._url))).then((e=>{this._closeCalled?this._connectLock=!1:(this._ws=this._protocols?new r(e,this._protocols):new r(e),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout((()=>this._handleTimeout()),t))})).catch((e=>{this._connectLock=!1,this._handleError(new D(Error(e.message),this))}))}}_handleTimeout(){this._handleError(new D(Error("TIMEOUT"),this))}_disconnect(e=1e3,t){if(this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new M(e,t,this))}catch(e){}}}_acceptOpen(){this._retryCount=0}_callEventListener(e,t){"handleEvent"in t?t.handleEvent(e):t(e)}_handleOpen(e){const{minUptime:t=O.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout((()=>this._acceptOpen()),t),this._ws.binaryType=this._binaryType,this._messageQueue.forEach((e=>this._ws.send(e))),this._messageQueue=[],this.onopen&&this.onopen(e),this._listeners.open.forEach((t=>this._callEventListener(e,t)))}_handleMessage(e){this.onmessage&&this.onmessage(e),this._listeners.message.forEach((t=>this._callEventListener(e,t)))}_handleError(e){this._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),this.onerror&&this.onerror(e),this._listeners.error.forEach((t=>this._callEventListener(e,t))),this._connect()}_handleClose(e){this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this._listeners.close.forEach((t=>this._callEventListener(e,t)))}_removeListeners(){this._ws&&(this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}}const N={debug:3,info:4,warn:5,error:6};class B{constructor(e,t,r,i){this.wsAddr=`${e}?app=${t}&id=${r}&v=${i}`,this.destroyed=!1;try{this._ws=this._init()}catch(e){console.error(e)}}_init(){const e={maxRetries:3,minReconnectionDelay:p(5e3,15e3),maxReconnectionDelay:6e5,maxEnqueuedMessages:200};return new F(this.wsAddr,void 0,e)}send(e,t){if(this.destroyed)return;const r=N[e];this._ws.send(JSON.stringify({records:[{level:r,text:`${R()}: ${t}`}]}))}sendBatch(e){const t=[];for(let r of e)t.push({level:N[r.levelKey],text:r.message});this._ws.send(JSON.stringify({records:t}))}destroy(){this._ws&&(this._ws.close(1e3),this._ws=null,this.destroyed=!0)}}const U=e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return e.value?e.value:e}catch(e){return t}},G=(e,t,r)=>{((e,t)=>{"object"==typeof t&&(t=JSON.stringify(t)),localStorage.setItem(e,t)})(e,{value:t,duration:r,startTime:Date.now()})},H={debug:0,info:1,warn:2,error:3,none:4};const $=class{constructor(e){this.logLevel=e,this.onlineDebug=!1,this.logCache=[];try{console.debug=console.log}catch(e){console.debug=console.info}"debug"!==e&&"info"!==e||(this.logLevel="error"),U("SW_DEBUG")&&(this.logLevel="debug"),!0===e?this.logLevel="warn":!1===e?this.logLevel="none":e in H||(this.logLevel="error"),this.resetLogger()}enableDebug(){this.onlineDebug=!0;for(let e in H)this[e]=console[e];this._hookLogFunc(((e,t)=>{this.logUploader&&this.logUploader.send(e,t)}))}enableReport(e){this.reportUrl=e,this._hookLogFunc(((e,t)=>{this.reportUrl?(this.logCache.push({levelKey:e,message:`${R()}: ${t}`}),this.logCache.length>350&&this.logCache.shift()):this.reporter&&this.reporter.send(e,t)}))}report(e,t,r,i,n=5e3){this.reportUrl&&(e&&this.logCache.unshift({levelKey:"info",message:e}),this.reporter=new B(this.reportUrl,t,r,i),this.reporter._ws.addEventListener("open",(()=>{this.reportUrl=void 0,this.reporter.sendBatch(this.logCache),setTimeout((()=>{this.reporter.destroy(),this.reporter=null}),n)}),{once:!0}))}_hookLogFunc(e){for(let t in H){const r=this[t];this[t]=i=>{e(t,i),r(i)}}}setUploader(e){this.logUploader=e}resetLogger(){this.onlineDebug=!1;for(let e in H)H[e](K||(K=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0))),V=65536;function q(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class j extends(s()){constructor(e){super(),this.channelName=e.initiator?e.channelName:null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||j.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},j.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:v(),this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._pendingData=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._senderMap=new Map,this._closingInterval=null,this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void W((()=>this.destroy(e)))}this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this._needsNegotiation()}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}signal(e){if(!this.destroyed&&this._pc){if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}if(e.renegotiate&&this.initiator&&this._needsNegotiation(),e.candidate)if(this._pc.remoteDescription&&this._pc.remoteDescription.type)try{this._addIceCandidate(e.candidate)}catch(e){}else this._pendingCandidates.push(e.candidate);e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{try{this._addIceCandidate(e)}catch(e){}})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.destroy(e)})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(new Error("signal() called with invalid signal data"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{var r;!t.address||t.address.endsWith(".local")?(r="Ignoring unsupported ICE candidate.",console.warn(r)):this.destroy(e)}))}send(e){if("string"==typeof e){RTCDataChannel.prototype.send.toString().includes("[native code]")&&this._channel.send(e)}else this._channel.send(e)}_needsNegotiation(){this._batchedNegotiation||(this._batchedNegotiation=!0,W((()=>{this._batchedNegotiation=!1,!this.initiator&&this._firstNegotiation||this.negotiate(),this._firstNegotiation=!1})))}negotiate(){this.initiator?this._isNegotiating?this._queuedNegotiation=!0:setTimeout((()=>{this._createOffer()}),0):this._isNegotiating?this._queuedNegotiation=!0:this.emit("signal",{type:"renegotiate",renegotiate:!0}),this._isNegotiating=!0}destroy(e){this._destroy(e)}_destroy(e){this.destroyed||this.destroying||(this.destroying=!0,W((()=>{if(this.destroyed=!0,this.destroying=!1,this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close")})))}_setupData(e){if(!e.channel)return this.destroy(new Error("Data channel event is missing `channel` property"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=V),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{this.destroy(e)};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}get isBufferedAmountHigh(){return this._channel.bufferedAmount>V}write(e,t){if(this.destroyed)return t(new Error("cannot write after peer is destroyed"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(e)}this.isBufferedAmountHigh?this._cb=t:t(null)}else this._chunk=e,this._cb=t}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=q(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=q(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(e)}))})).catch((e=>{this.destroy(e)}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(new Error("Connection failed."))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(new Error("Ice connection failed.")),"closed"===e&&this.destroy(new Error("Ice connection closed."))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length?this._pc.getStats().then((r=>{const i=[];r.forEach((e=>{i.push(t(e))})),e(null,i)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((r=>{if(this.destroyed)return;const i=[];r.result().forEach((e=>{const r={};e.names().forEach((t=>{r[t]=e.stat(t)})),r.id=e.id,r.type=e.type,r.timestamp=e.timestamp,i.push(t(r))})),e(null,i)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,r)=>{if(this.destroyed)return;t&&(r=[]);const i={},n={},s={};let a=!1;r.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(i[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(n[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(s[e.id]=e)}));const o=e=>{a=!0;let t=n[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let r=i[e.remoteCandidateId];r&&(r.ip||r.address)?(this.remoteAddress=r.ip||r.address,this.remotePort=Number(r.port)):r&&r.ipAddress?(this.remoteAddress=r.ipAddress,this.remotePort=Number(r.portNumber)):"string"==typeof e.googRemoteAddress&&(r=e.googRemoteAddress.split(":"),this.remoteAddress=r[0],this.remotePort=Number(r[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4")};if(r.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&o(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&o(e)})),a||Object.keys(s).length&&!Object.keys(n).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(t)}this._chunk=null;const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this.emit("connect");for(let e of this._pendingData)this.emit("data",e);this._pendingData=[]}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>V||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._queuedNegotiation?(this._queuedNegotiation=!1,this._needsNegotiation()):this.emit("negotiated")),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=a.h.from(t)),this._connected?this.emit("data",t):this._pendingData.length<10&&this._pendingData.push(t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||this.destroy()}}j.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},j.channelConfig={};const Y=j;class z{constructor(e,t,r,i,n=0,s=void 0){this.sn=e,this.segId=t,this.data=r,this.fromPeerId=i,this.level=n||0,this.ext=s}static fromSegment(e){const t=new z(e.sn,e.segId,e.data,e.fromPeerId,e.level,e.ext);return t.from=e.from,t}get size(){return this.data.byteLength}get isSequential(){return this.sn>=0}}var X=r(365),Q=r.n(X);class J extends(s()){static get defaultPacketSize(){return u}static get VERSION(){return"8"}constructor(e,t,r,i,n,s={}){super(),this.channel=e.fetcher.channelId,this.logger=e.logger,this.config=n,this.isInitiator=i,this.options=s,this.intermediator=s.intermediator||null,this.signalMsgs=[],this.assignPeerId(t,r),this.platform="unknown",this.super=!1,this.mobile=!1,this.mobileWeb=!1,this.mobileNet=!1,this.connected=!1,this.msgQueue=[],this.miss=0,this.notifySet=new Set,this.bufArr=[],this.packetSize=u,this.sendReqQueue=[],this.downloading=!1,this.uploading=!1,this.choked=!1,this.streamListeners=[],this.pieceMsg={},this.datasToSend=[],this.bytesUploaded=0,this.dataWriting=!1,this.timeSendRequest=0,this.timeReceivePiece=0,this.timeSendPiece=0,this.weight=0,this.peersConnected=1,this.uploadSpeed=0,this.currentLevel=0,this.currentPos=0,this.useBackupSignal=!1,this.gotPeersTS=0,this.gotAnswer=!1,this.gotOffer=!1,this.gotSignal=!1,this.sentSignal=!1,this.webRTCConfig={};const{stuns:a}=this.options;if(a&&a.length>0){const e=[];a.forEach((t=>{this.logger.info(`use stun ${t}`),e.push({urls:t})})),this.webRTCConfig.iceServers=e}this.config.webRTCConfig&&(this.webRTCConfig={...this.config.webRTCConfig,...this.webRTCConfig}),this.playlistMap=new Map,this._initPeerChannel(),this.notFatalClosed=!1,this.startSN=Number.MAX_SAFE_INTEGER,this.endSN=-1,this._loadedBytes=0}assignPeerId(t,r){this.remotePeerId=r,this.channelId=this.isInitiator?`${t}-${r}`:`${r}-${t}`,r&&this._startTimer(),setTimeout((()=>{this.signalMsgs.length>0&&this.emit(e.DC_SIGNAL_BATCH,this.signalMsgs)}),0)}_startTimer(){this.timeJoin=g(),this.dataExchangeTs=this.timeJoin,this.gotStatsTs=this.timeJoin,this.connTimeout=setTimeout((()=>{const{gotSignal:t,sentSignal:r,signalName:i}=this;this.logger.warn(`dc ${this.channelId} connection timeout, gotSignal ${t} sentSignal ${r} signalName ${i}`),this.emit(e.DC_TIMEOUT,{gotSignal:t,sentSignal:r,data:this.signalMsgs})}),this.isInitiator?15e3:12e3)}get isAvailable(){return this.downloadNum<2&&!this.choked}get isAvailableUrgently(){return!this.downloading&&!this.choked}cancelDownload(t,r,i){return!!this.downloading&&(!(this.bufSN>t)&&(!(this.streamListeners.length>0)&&(this.logger.info(`cancel download ${i} to ${this.remotePeerId} remain packets ${this.remainAttachments}`),this.timeReceivePiece=0,this.sendJson({event:e.DC_PIECE_CANCEL,sn:t,level:r,seg_id:i}))))}addStreamListener(e,t,r){this.streamListeners.push({handler:r,peerId:t})}removeStreamListener(e){this.streamListeners=this.streamListeners.filter((t=>t.peerId!==e||(t.handler(void 0,void 0,!0,"aborted by cancel"),!1)))}_initPeerChannel(){const t=new Y({initiator:this.isInitiator,trickle:this.options.trickle||!1,config:this.webRTCConfig});this._datachannel=t,t.on("error",(t=>{let r=!0;(this.connected||this.notFatalClosed)&&(r=!1),this.emit(e.DC_ERROR,r,t.message)})),t.on("signal",(t=>{t.candidate&&!t.candidate.candidate||(!this.useBackupSignal&&this.signalMsgs.length<10&&this.signalMsgs.push(t),this.sentSignal=!0,this.emit(e.DC_SIGNAL,t))}));t.on("connect",(()=>{for(this.logger.info(`datachannel CONNECTED from ${this.intermediator?"peer":"server "+this.signalName} to ${this.remotePeerId}`),this.connected=!0,clearTimeout(this.connTimeout),this.signalMsgs=[],this.emit(e.DC_OPEN);this.msgQueue.length>0;){let e=this.msgQueue.shift();this.emit(e.event,e)}})),t.on("data",(t=>{const{logger:r}=this;if("string"==typeof t){let i=JSON.parse(t);if(!i)return void r.error("dc received string is null");if(!this.connected)return void this.msgQueue.push(i);let n,s=i.event;switch(n=s!==e.DC_PLAYLIST&&s!==e.DC_PEER_SIGNAL?`string: ${t}`:`event: ${s}`,r.debug(`datachannel receive ${n} from ${this.remotePeerId}`),s){case e.DC_HAVE:if(this.emit(i.event,i),!i.sn)return;this.config.live||(i.snthis.endSN&&(this.endSN=i.sn));break;case e.DC_PIECE:this.downloading=!0,this.dataExchangeTs=g(),this.timeReceivePiece=performance.now(),this.pieceMsg=i,this._prepareForBinary(i.attachments,i.seg_id,i.sn,i.size),this.emit(i.event,i);break;case e.DC_PIECE_CANCEL:r.info(`send queue ${this.datasToSend.length}, uploading ${this.uploading}`),this.emit(i.event,i),this.sendMsgPieceAbort("transfer canceled",i.seg_id);break;case e.DC_PIECE_NOT_FOUND:this._sendNextReq()||(this.downloading=!1),this.emit(i.event,i);break;case e.DC_REQUEST:this._handleRequestMsg(i);break;case e.DC_PIECE_ACK:this._handlePieceAck(i.seg_id,i.size,i.miss);break;case e.DC_STATS:this._handleStats(i);break;case e.DC_PLAYLIST:this.config.sharePlaylist&&this._handlePlaylist(i);break;case e.DC_METADATA:this._handleMetadata(i);break;case e.DC_PIECE_ABORT:this.downloading&&(this._notifyDownloadListenersAbort("aborted by upstream peer"),this.emit(e.DC_PIECE_ABORT,i)),this.downloading=!1;break;case e.DC_CHOKE:r.info(`choke peer ${this.remotePeerId}`),this.choked=!0;break;case e.DC_UNCHOKE:r.info(`unchoke peer ${this.remotePeerId}`),this.choked=!1;break;case e.DC_CLOSE:this.emit(i.event,i.fatal||!1);break;default:this.emit(i.event,i)}}else{if(!t)return void r.error("datachannel on data is undefined!");if(!this.downloading)return void r.warn(`peer ${this.remotePeerId} not downloading, data size ${t.byteLength} pieceMsg ${JSON.stringify(this.pieceMsg)}`);this._handleBinaryMsg(t)}})),t.once("close",(()=>{this.emit(e.DC_CLOSE,!1)})),t.on("iceStateChange",((t,r)=>{this.connected&&"disconnected"===t&&(this.logger.warn(`${this.remotePeerId} disconnected`),this.emit(e.DC_DISCONNECT))}))}sendJson(t){if(!this.remotePeerId)return!1;t.event!==e.DC_PLAYLIST&&t.event!==e.DC_PEER_SIGNAL?this.logger.debug(`dc bufferSize ${this._datachannel.bufferSize} send ${JSON.stringify(t)} to ${this.remotePeerId}`):this.logger.debug(`dc send event ${t.event} to ${this.remotePeerId}`);const r=JSON.stringify(t);return r.length>u?(this.logger.error("string to send is too large"),!1):this.send(r,!1)}send(e,t=!0){return t?(this.datasToSend.push(e),this.dataWriting||this._sendDataSync(),!0):this.sendImmediately(e)}_sendDataSync(){if(!this._datachannel.connected||0===this.datasToSend.length)return void(this.dataWriting=!1);this.dataWriting=!0;const t=this.datasToSend.shift();t?("string"!=typeof t&&(this.bytesUploaded+=t.byteLength),this._datachannel.write(t,(t=>{if(t)return this.dataWriting=!1,void this.emit(e.DC_ERROR,!1,t.message);this._sendDataSync()}))):this.logger.error("sendDataSync data is undefined!")}sendImmediately(t){if(this._datachannel.connected)try{return this._datachannel.send(t),!0}catch(t){const r=`datachannel ${this.channelId} send data failed, close it`;this.emit(e.DC_ERROR,!1,r)}return!1}sendMsgHave(t,r,i={}){const n=i.reverse||void 0;delete i.reverse,this.sendJson({event:n?e.DC_HAVE_REVERSE:e.DC_HAVE,sn:t,seg_id:r,...i})}sendPieceNotFound(t,r,i={}){this.uploading=!1,this.sendJson({event:e.DC_PIECE_NOT_FOUND,seg_id:r||void 0,sn:t,...i})}sendPeers(t){this.sendJson({event:e.DC_PEERS,peers:t})}sendPeersRequest(){this.sendJson({event:e.DC_GET_PEERS})}sendMsgStats(t,r={}){const i={event:e.DC_STATS,total_conns:t,...r};this.sendJson(i)}sendMsgPlaylist(t,r,i){const n=this.playlistMap.get(t);if(n&&n.seq>=i)return;const s={event:e.DC_PLAYLIST,url:t,data:r,seq:i};this.playlistMap.set(t,{data:r,seq:i}),this.sendJson(s)}sendMsgSignal(t,r,i){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"signal",to_peer_id:t,from_peer_id:r,data:i})}sendMsgSignalReject(t,r,i,n=!1){return this.sendJson({event:e.DC_PEER_SIGNAL,action:"reject",to_peer_id:t,from_peer_id:r,reason:i,fatal:n})}sendMetaData(t,r,i,n,s=!1){this.isInitiator&&(this.timeSendRequest=performance.now()),this.sendJson({event:e.DC_METADATA,field:t,platform:e.DC_PLAT_WEB,mobile:!!Q().isMobile(),mobile_net:s,channel:this.channel,version:"2.12.15",sequential:r,peers:i,region:n})}sendPartialBuffer(e,t,r={}){this.sendMsgPiece(e,r);for(let e=0;e=this.minRequiredSpeed(e))}close(t){t||(this.notFatalClosed=!0),this.emit(e.DC_CLOSE,t)}receiveSignal(e){if("answer"===e.type){if(this.gotAnswer||this.gotOffer)return;this.gotAnswer=!0}else if("offer"===e.type){if(this.gotOffer||this.gotAnswer)return;this.gotOffer=!0}this.gotSignal=!0,e&&this._datachannel.signal(e)}_notifyDownloadListenersAbort(e){for(let t of this.streamListeners){const{handler:r}=t;r(void 0,void 0,!0,e)}this.streamListeners=[]}destroy(t=!0){this.logger.info(`destroy datachannel ${this.channelId}`),clearTimeout(this.chokeTimer),clearTimeout(this.connTimeout),this._notifyDownloadListenersAbort("upstream peer is closed");let r={event:e.DC_CLOSE,fatal:t};this.sendJson(r),this._datachannel.removeAllListeners(),this.removeAllListeners(),this._datachannel.destroy()}_handleBinaryMsg(t){const{attachments:r,reverse:i}=this.pieceMsg;this.listenerCount(e.DC_RESPONSE)>0&&this.bufArr.push(t),this._loadedBytes+=t.byteLength,this.remainAttachments--;let n=i?this.remainAttachments+1:r-this.remainAttachments;const s=0===this.remainAttachments;if(this.emit(e.DC_PIECE_DATA,this.bufSN,this.segId,t,n,s,this.pieceMsg),this.streamListeners.length>0)for(let e of this.streamListeners){const{handler:r}=e;r(this.bufSN,this.segId,!1,t,s)}if(s){if(this.streamListeners=[],this.timeSendRequest>0)if(this.super)this.weight=1;else{const e=this.expectedSize/(performance.now()-this.timeSendRequest);this.weight=this.weight>0?.6*this.weight+.4*e:e}this.sendJson({event:e.DC_PIECE_ACK,seg_id:this.segId,size:this.expectedSize,miss:this.miss||void 0}),this.timeSendRequest=0,this.timeReceivePiece=0,this._sendNextReq()||(this.downloading=!1),this._handleBinaryData(i)}}_sendNextReq(){if(this.sendReqQueue.length>0){const e=this.sendReqQueue.shift();return this.logger.info(`get msg from sendReqQueue ${JSON.stringify(e)}`),this._realRequestData(e),!0}return!1}_handlePlaylist(e){const{url:t,data:r,seq:i}=e;this.playlistMap.set(t,{data:r,seq:i})}getLatestPlaylist(e,t){if(!this.playlistMap.has(e))return null;const r=this.playlistMap.get(e);return r.seq<=t||r.seq>t+2?null:r}_handleMetadata(t){const{logger:r}=this;if(this.isInitiator){const e=performance.now()-this.timeSendRequest;e>0&&(this.weight=1e5/e,r.info(`handle Metadata from ${this.remotePeerId} initial weight ${this.weight}`)),this.timeSendRequest=0}const i=t.channel;if(this.channel!==i){const t=`peer channel ${i} not matched!`;return r.error(t),void this.emit(e.DC_ERROR,!0,t)}if(t.super){r.info(`got super peer ${this.remotePeerId}`),this.super=!0;const{token:i}=this.config;if(i&&t.token!==i)return void this.emit(e.DC_ERROR,!0,`super peer token ${t.token} not matched!`)}t.region&&(this.region=t.region);switch(t.platform){case e.DC_PLAT_ANDROID:this.platform=e.DC_PLAT_ANDROID;break;case e.DC_PLAT_IOS:this.platform=e.DC_PLAT_IOS;break;case e.DC_PLAT_WEB:this.platform=e.DC_PLAT_WEB}if(this.mobile=t.mobile||!1,this.mobileNet=t.mobile_net||!1,this.mobileWeb=this.mobile&&this.platform===e.DC_PLAT_WEB||!1,this.sequential=t.sequential,r.info(`${this.remotePeerId} platform ${this.platform} sequential ${this.sequential}`),t.peers&&(this.peersConnected+=t.peers,r.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),this.emit(e.DC_METADATA,t),t.field&&!this.config.live&&t.sequential){const{field:e}=t;if(Array.isArray(e))this._handleField(e);else for(let t in e)this._handleField(e[t])}}_handleField(e){e.forEach((e=>{e>=0&&(ethis.endSN&&(this.endSN=e))}))}_handleStats(e){this.gotStatsTs=g();const t=e.total_conns;t>0&&this.peersConnected!==t&&(this.peersConnected=t,this.logger.info(`${this.remotePeerId} now has ${this.peersConnected} peers`)),e.level&&(this.currentLevel=e.level),e.pos&&(this.currentPos=e.pos)}_handleRequestMsg(t){if(this.dataExchangeTs=g(),this.uploading)return this.logger.warn(`${this.remotePeerId} is uploading when receive request`),void this.sendPieceNotFound(t.sn,t.seg_id,{level:t.level});this.uploading=!0,this.emit(e.DC_REQUEST,t)}_handlePieceAck(t,r,i){0!==this.timeSendPiece&&(this.uploadSpeed=Math.round(r/(performance.now()-this.timeSendPiece)*2),this.timeSendPiece=0,this.logger.info(`${this.remotePeerId} uploadSpeed is ${this.uploadSpeed}`)),i>0&&this.logger.warn(`peer ${this.remotePeerId} miss ${i}`),this.bytesUploaded>0&&this.emit(e.DC_PIECE_ACK,{seg_id:t,size:r})}_prepareForBinary(e,t,r,i){this.bufArr=[],this._loadedBytes=0,this.remainAttachments=e,this.segId=t,this.bufSN=r,this.expectedSize=i}_handleBinaryData(t=!1){if(this.listenerCount(e.DC_RESPONSE)>0){t&&this.bufArr.reverse();let r=a.h.concat(this.bufArr);const i=r.byteLength;if(i===this.expectedSize){let t=r.buffer;const i=new z(this.bufSN,this.segId,t,this.remotePeerId,this.pieceMsg.level);this.emit(e.DC_RESPONSE,i,this.weight)}else this.logger.error(`${this.segId} expectedSize ${this.expectedSize} != byteLength ${i}`)}this.bufArr=[]}checkIfNeedChoke(e=!1){const{logger:t}=this,r=performance.now()-this.timeSendRequest;if((e||!(r<1e3))&&(this.miss++,t.info(`${this.remotePeerId} miss ${this.miss}`),this.miss>=3&&!this.choked)){this.choked=!0;const e=30*this.miss;e<=150?(t.warn(`datachannel ${this.channelId} is choked`),this.chokeTimer=setTimeout((()=>{this.choked=!1,t.warn(`datachannel ${this.channelId} is unchoked`)}),1e3*e)):t.warn(`datachannel ${this.channelId} is choked permanently`)}}get bufArrSize(){return this.downloading?this.pieceMsg.attachments-this.remainAttachments:0}loadtimeout(){const{logger:e,pieceMsg:t}=this;return e.warn(`timeout while downloading from ${this.remotePeerId}, ${this.bufArrSize} of ${t.attachments} packets loaded`),this.checkIfNeedChoke(),!0}sendMsgPieceAbort(t,r,i=!1){if(!i&&!this.uploading&&0===this.datasToSend.length)return;this.uploading=!1,this.datasToSend=[],this._handlePieceAck(r,this.bytesUploaded,0),this.bytesUploaded=0;const n={event:e.DC_PIECE_ABORT,reason:t};return this.sendJson(n)}loadedBytes(){return this._loadedBytes}currentLoadSpeed(){return 0===this.timeReceivePiece?0:this.loadedBytes()/(performance.now()-this.timeReceivePiece)}minRequiredSpeed(e){return(this.pieceMsg.size-this.loadedBytes())/e}}const Z=J,ee={DPlayer:"dplayer",CBPlayer:"cbplayer",jwplayer:"jwplayer",videojs:"videojs",Clappr:"clappr",ckplayer:"ckplayer",MediaElementPlayer:"mediaelement",MediaElement:"mediaelement",TcPlayer:"tcplayer",flowplayer:"flowplayer",Chimee:"chimee",ChimeePlayer:"chimee",HlsJsPlayer:"xgplayer",fluidPlayer:"fluidplayer",OpenPlayer:"openplayer",Plyr:"plyr",Playerjs:"playerjs",Aliplayer:"aliplayer",shaka:"shakaplayer",RadiantMP:"rmp",bitmovin:"bitmovin"};const te="nllL",re="d3NzJ",ie="==",ne="TNBLy9z",se="aWduY",ae="mNvbQ",oe="WwuY2RuY",le={[e.EXCEPTION]:"onException",serverConnected:"onServerConnected",peerId:"getPeerId",p2pDownloaded:"onP2pDownloaded",p2pUploaded:"onP2pUploaded",httpDownloaded:"onHttpDownloaded",bufferStalled:"onBufferStalled",peers:"getPeersInfo"};class he extends(s()){constructor(e={}){if(super(),this.p2pEnabled=!(!1===e.p2pEnabled||"0"===c("_p2p")),e.tag&&e.tag.length>20)throw new Error("Tag is too long");if(e.appName&&e.appName.length>30)throw new Error("appName is too long");if(e.appId&&e.appId.length>30)throw new Error("appId is too long");if(e.token&&e.token.length>20)throw new Error("Token is too long");this.segmentLoadCount=0,this.rangeTested=!1,this.playerName=function(){let e;for(let t in ee)if(self[t]){e=ee[t];break}return e}()}startRangeRequestTimer(){const{config:e,logger:t}=this,r=()=>{this.curTsUri&&function(e,t,r,i=2e3,n=!1){const s=new XMLHttpRequest;let a=e;return n&&(a=f(e,h,!0)),t=t||"bytes=0-0",new Promise(((n,o)=>{s.open("GET",a,!0),s.responseType="arraybuffer",s.timeout=i,s.onreadystatechange=e=>{if(4===s.readyState){const e=s.status;206===e||200===e&&t?n(s.response):o(`status ${e} url ${a} range ${t}`)}},s.onerror=e=>{o("request error")},s.ontimeout=e=>{o("timeout")},s.setRequestHeader("Range",t),r&&r(s,e),s.send()}))}(this.curTsUri,void 0,e.xhrSetup).then((()=>{e.httpRangeSupported=!0,clearTimeout(this.rangeRequestTimer)})).catch((i=>{e.httpRangeSupported=!1,t.warn(i),this.rangeRequestTimer=setTimeout(r,6e4)})).finally((()=>{t.info(`http range is${e.httpRangeSupported?"":" not"} supported`)}))};this.rangeRequestTimer=setTimeout(r,0)}initLogger(){const{config:e}=this;e.showSlogan&&"en"==("zh-CN"===(navigator.language||navigator.userLanguage)?"cn":"en")&&console.log(`%cLet the browsers become your unlimitedly scalable CDN!\n%c${self.atob("aHR0cHM6Ly9zd2FybWNsb3VkLm5ldA==")}`,"color: dodgerblue; padding:20px 0; font-size: x-large","font-size: medium; padding-bottom:15px");const t=new $(e.logLevel);return e.logger=this.logger=t,t}getExtraForStats(){return{}}getExtraForPeersRequest(){const e={};return e.num_want=this._getNumWant(),e}_getNumWant(){const{tracker:e}=this;if(!e.scheduler)return;const t=e.scheduler.peersNum;return t>0&&e.maxConnsActive-t>0?e.maxConnsActive-t:void 0}makeChannelId(e,t){if(!e||"string"!=typeof e){const e="token is required while using customized channelId!";throw console.error(e),new Error(e)}return A(t)?(r,i)=>`${e}-${t(r,i)}`:()=>`${e}-${t}`}makeSignalId(){let e="";const{config:t}=this,r=decodeURIComponent(self.atob(re+ne+se+oe+te+ae+ie));t.signalConfig&&(t.wsSignalerAddr=t.signalConfig);const{wsSignalerAddr:i}=t;if(i){let n;"object"==typeof i?(i.main||(i.main=r),n=i.main):"string"==typeof i&&(n=i,t.wsSignalerAddr={main:n}),n===r&&(n=void 0),n&&!t.wsSignalerAddr.backup&&(e=l().parseURL(n).netLoc.substring(2))}else t.wsSignalerAddr={main:r,byDefault:!0};return e}get commonBrowserInfo(){const e=Q().getPlatform(),t=Q().getNetType()||"wifi";this.netType=t;const{main:r,backup:i,byDefault:n}=this.config.wsSignalerAddr||{};return{signal:n?void 0:r,signal2:i,device:e,netType:t,player:this.playerName}}get isMobileNet(){return"wifi"!==this.netType&&"ethernet"!==this.netType}setupWindowListeners(e){const t=["iPad","iPhone"].indexOf(navigator.platform)>=0?"pagehide":"beforeunload",r=()=>{this.fetcher&&this.fetcher.postStatsWithBeacon(),this.p2pEnabled&&this.disableP2P(),self.removeEventListener(t,r)};e?self.removeEventListener(t,r):self.addEventListener(t,r)}destroy(){clearTimeout(this.rangeRequestTimer),this.disableP2P(!0),this.removeAllListeners(),this.setupWindowListeners(!0)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this.browserInfo?(this._init(this.channel,this.browserInfo),this):null)}get version(){return he.version}static isSupported(){const e=v();return!(!e||void 0===e.RTCPeerConnection.prototype.createDataChannel)}static get TrackerZone(){return{EU:"eu",HK:"hk",USA:"us",CN:"cn"}}determineHttpLoadTime(e,t,r){this.logger&&this.logger.info(`segments in playlist: ${e.length}, targetDuration: ${t} startSN ${r}`);let i=3.5;return t<=2?i=1:t<=3?i=1.5:t<=4?i=2:t<=6?i=2.5:t<=8&&(i=3),i}emitEvent(e,...t){this.emit(e,...t);const r=le[e];r&&A(this.config[r])&&this.config[r](...t)}}he.version="2.12.15",he.protocolVersion=Z.VERSION;const ue=he;function de(){if(!function(){if("object"==typeof self)return self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}())return!1;const e=self.SourceBuffer||self.WebKitSourceBuffer;return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function ce(e,t){let r;if(e&&("string"==typeof e?(r=document.querySelector(e),fe(r)||(r=function(e){const t=document.getElementById(e);if(fe(t))return t;const r=t.getElementsByTagName("*");for(let e=0;ee.src===t))),r||(r=e.find((e=>e.currentTime>0))))}return r}function fe(e){if(!e)return null;const t=e.tagName.toLowerCase();return"video"===t||"audio"===t}function ge(e,t,r,i=0,n=0){const s=u;let a=i,o=n||r-1;const l=Math.floor(r/s),h=r%s>0?l+1:l;if(e>=0&&(a+=(e+1)*s),t>=0&&t{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>r(e.error)})),r=(i=Te,n="indexedDB timeout",new Promise(((e,t)=>setTimeout((()=>{t(n)}),i))));var i,n;return Promise.race([t,r])}function Le(e,t){return t?t("readonly",(t=>_e(t.get(e)))):Promise.reject(Se)}function be(e,t,r){return r?r("readwrite",(r=>(r.put(t,e),_e(r.transaction)))):Promise.reject(Se)}function Re(e,t){return t?t("readwrite",(t=>(t.delete(e),_e(t.transaction)))):Promise.reject(Se)}function Ae(e){return e?e("readwrite",(e=>(e.clear(),_e(e.transaction)))):Promise.reject(Se)}function we(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},_e(e.transaction)}const Pe="size";class Ie extends(s()){constructor(e,t){super(),this.name="SegmentStore",this.logger=t.logger,this.logger.info(`use ${this.name}`),this.engine=e,this.channel=e.channel;const r=e.browserInfo.device;this.isPC=r===Q().device.PC_WEB||r===Q().device.PC_NATIVE,this.maxBufSize=this.isPC?t.diskCacheLimit.pc:t.diskCacheLimit.mobile,this.overflowed=!1,this.countErrors=0,this.isCleared=!0,this.destroyed=!1}async setupStore(){if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate(),t=Math.floor(e.quota-e.usage);t{if(this.isPC&&this.maxBufSize<419430400||!this.isPC&&this.maxBufSize<104857600)return void t("disk storage not enough");const r=this.stores;let i;try{i=function(e,t){const r=indexedDB.open(e);r.onupgradeneeded=()=>{const e=r.result;t.forEach((t=>{e.createObjectStore(t)}))};const i=_e(r);return t.map((e=>(t,r)=>i.then((i=>r(i.transaction(e,t).objectStore(e))))))}(this.channel,r)}catch(e){return void t(e)}this._createStores(i),this._initMetaStore().then(e).catch(t)}))}_initMetaStore(){return be(Pe,0,this.metaStore)}currBufSize(){return new Promise((async(e,t)=>{try{const r=await Le(Pe,this.metaStore);if(isNaN(r))return void t("size is NaN");e(r)}catch(e){t(e)}}))}async putSeg(t){if(this.destroyed)return;this.isCleared=!1;const{logger:r}=this;if(_(t.data))return new Promise((i=>{this._addSeg(t).then((t=>{this._onSegPut(t),this.emit(e.BM_SEG_ADDED,t),i()})).catch((t=>{this._handleFataError(),t&&(r.warn(`putSeg ${t}`),("QuotaExceededError"===t.name||t.inner&&"QuotaExceededError"===t.inner.name)&&this.currBufSize().then((e=>{this._trimDisk(e,!0)})).catch((t=>{this.logger.error(`putSeg ${t}`),this.engine.emit(e.BM_FATAL_ERROR)}))),i()}))}));r.error(`putSeg ${t.segId} is not buffer`)}_handleFataError(){this.countErrors++,this.countErrors>=3&&(this.engine.emit(e.BM_FATAL_ERROR),this.countErrors=0)}_decreaseBufSize(e){this.currBufSize().then((t=>{t&&be(Pe,t-e,this.metaStore)})).catch((e=>{this.logger.warn(`decreaseBufSize ${e}`)}))}_increaseBufSize(t){this.destroyed||this.currBufSize().then((e=>{be(Pe,e+t,this.metaStore),this._trimDisk(e+t)})).catch((t=>{this.logger.warn(`increaseBufSize ${t}`),this.engine.emit(e.BM_FATAL_ERROR)}))}clear(e=!1){if(!this.isCleared){this.logger.warn("clear segment store");try{this._clearDisk(e)}catch(e){}this.isCleared=!0}}_clearDisk(e){Ae(this.segmentsStore),e?this._initMetaStore():Ae(this.metaStore),this.overflowed=!1}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}}const Ce=Ie;const ke=class extends Ce{constructor(e,t){super(e,t),this.loadingSN=-1,this.stores=["segments","id2Sn","metadata"]}_createStores(e){this.segmentsStore=e[0],this.id2SnStore=e[1],this.metaStore=e[2]}async hasSegOfId(e){if(!e)return Promise.resolve(!1);let t;try{t=await Le(e,this.id2SnStore)}catch(e){return Promise.resolve(!1)}return new Promise((r=>{void 0!==t?Le(t,this.segmentsStore).then((t=>{t&&t.length>0&&t.some((t=>t.segId===e))?r(!0):r(!1)})).catch((e=>{this.logger.warn(`hasSegOfId ${e}`),r(!1)})):r(!1)}))}async getSegById(e){if(!e)return null;const{logger:t}=this;let r;try{r=await Le(e,this.id2SnStore)}catch(e){return null}return new Promise((i=>{void 0!==r?Le(r,this.segmentsStore).then((r=>{if(r&&r.length>0){const n=r.find((t=>t.segId===e));if(!n)return void i(null);if(!_(n.data))return t.error(`getSegById ${n.sn} is not buffer`),void i(null);i(z.fromSegment(n))}else i(null)})).catch((e=>{t.warn(`getSegById ${e}`),this._handleFataError(),i(null)})):i(null)}))}getSegIdBySN(e){return new Promise((t=>{Le(e,this.segmentsStore).then((e=>{e&&e.length>0?t(e[0].segId):t(null)})).catch((e=>{this.logger.warn(`getSegIdBySN ${e}`),t(null)}))}))}_addSeg(e){const{segId:t,sn:r,size:i}=e;return be(t,r,this.id2SnStore),new Promise(((n,s)=>{Le(r,this.segmentsStore).then((a=>{a?0===a.filter((e=>e.segId===t)).length?(a.push(this._segmentToCache(e)),be(r,a,this.segmentsStore).then((()=>{this._increaseBufSize(i),n(e)})).catch((e=>{s(e)}))):n(e):be(r,[this._segmentToCache(e)],this.segmentsStore).then((()=>{this._increaseBufSize(i),n(e)})).catch((e=>{s(e)}))})).catch((e=>{s(e)}))}))}async _trimDisk(t,r=!1){if(this.isCleared||this.destroyed)return;let i=this.maxBufSize;const{logger:n}=this;var s;(r&&(i=t-104857600,i<0&&(i=0)),t{if(e.getAllKeys)return _e(e.getAllKeys());const t=[];return we(e,(e=>t.push(e.key))).then((()=>t))})):Promise.reject(Se)).then((async r=>{const s=r.sort(((e,t)=>e-t));let a=0;do{if(a++>10){n.warn("too much loops in SegmentStore");break}const r=s.shift();if(void 0===r){n.warn("lastSN not found");continue}if(r>=this.loadingSN){n.warn(`trimDisk failed, loadingSN ${this.loadingSN}`);break}const i=s[0],o=await Le(r,this.segmentsStore);if(!o){n.warn("lastSeg not found");continue}let l=0;o.forEach((e=>{l+=e.data.byteLength})),Re(r,this.segmentsStore).then((()=>{this._decreaseBufSize(parseInt(l))})),o.forEach((t=>{Re(t.segId,this.id2SnStore),n.info(`pop seg ${t.segId} size ${t.data.byteLength}`),this.emit(e.BM_LOST,{sn:r,segId:t.segId,next:i,level:t.level})})),t-=l,n.info(`pop sn ${r} size ${l} currBufSize ${t}`),this.overflowed||(this.overflowed=!0)}while(t>=i)})))}_segmentToCache(e){return{data:e.data,level:e.level,segId:e.segId,sn:e.sn}}_onSegPut(t){this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t)}_clearDisk(e){try{super._clearDisk(e)}catch(e){}Ae(this.id2SnStore).catch((e=>{}))}};class De extends(s()){constructor(e,t){super(),this.name="SegmentCache",this.logger=t.logger,this.logger.info(`use ${this.name}`);const r=e.browserInfo.device;if(this.maxBufSize=r===Q().device.PC_WEB||r===Q().device.PC_NATIVE?t.memoryCacheLimit.pc:t.memoryCacheLimit.mobile,this.isLive=t.live,this.isLive)this.maxBufSize=47185920;else{if(0===this.maxBufSize)throw new Error("cannot use SegmentCache");const e=function(){const{memory:e}=performance;return e?e.jsHeapSizeLimit-e.usedJSHeapSize:-1}();e>=0&&e{t.forEach((t=>{e+=t.size}))})),e}async putSeg(e){this.destroyed||(this.isCleared=!1,this._currBufSize>=1.5*this.maxBufSize&&(this._currBufSize=this._calSegPoolSize(),this._currBufSize>=1.5*this.maxBufSize&&(this.clear(),this.overflowed=!1)),_(e.data)?this._addSeg(e):this.logger.error(`putSeg ${e.segId} is not buffer`))}clear(){this.isCleared||(this.logger.warn("clear segment cache"),this._segPool.clear(),this._currBufSize=0,this.isCleared=!0,this.overflowed=!1)}destroy(){this.clear(),this.removeAllListeners(),this.destroyed=!0}}const Me=De;const xe=class extends Me{constructor(e,t){super(e,t),this.id2Sn=new Map,this.loadingSN=-1}hasSegOfId(e){return new Promise(((t,r)=>{const i=this.id2Sn.get(e);this._segPool.has(i)?t(this._segPool.get(i).some((t=>t.segId===e))):t(!1)}))}getSegById(e){const t=this.id2Sn.get(e);return new Promise(((r,i)=>{if(!this._segPool.has(t))return void r(null);r(this._segPool.get(t).find((t=>t.segId===e)))}))}getSegIdBySN(e){return new Promise(((t,r)=>{if(this._segPool.has(e)){t(this._segPool.get(e)[0].segId)}else t(null)}))}_addSeg(t){const{logger:r}=this,{segId:i,sn:n,size:s}=t;if(this.id2Sn.set(i,n),this._segPool.has(n)){this._segPool.get(n).push(t)}else this._segPool.set(n,[t]);this._currBufSize+=parseInt(s);const a=this._segPool.size;if(this.emit(`${e.BM_ADDED_SN_}${t.sn}`,t),this.emit(e.BM_SEG_ADDED,t),this._currBufSizee-t)));let l=0;do{if(l++>10){r.error("too much loops in SegmentCache");break}const t=o.shift();if(void 0===t){r.error("lastSN not found");continue}const i=o[0],n=this._segPool.get(t);if(!n){r.error("lastSeg not found");continue}let s=0;n.forEach((e=>{s+=e.size})),this._currBufSize-=parseInt(s),this._segPool.delete(t),n.forEach((r=>{this.id2Sn.delete(r.segId),this.emit(e.BM_LOST,{sn:t,segId:r.segId,next:i,level:r.level})})),r.info(`pop sn ${t} size ${s} currBufSize ${this._currBufSize}`),this.overflowed||(this.overflowed=!0)}while(this._currBufSize>=this.maxBufSize&&this._segPool.size>5)}clear(){super.clear(),this.id2Sn.clear()}};var Oe=r(832),Fe=r.n(Oe);function Ne(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}const Be=function(e,t,r){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");r||(r={}),"object"==typeof t&&(r=t,t=void 0),null!=t&&(r.code=t);try{return Ne(e,r)}catch(t){r.message=e.message,r.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),Ne(new i,r)}};class Ue{constructor(){this.p2p=0,this.share=0,this.http=0}recordP2p(e){this.p2p+=e}recordShare(e){this.share+=e}recordHttp(e){this.http+=e}resetTraffic(){this.p2p=0,this.share=0,this.http=0}get healthRatio(){if(0===this.http)return 1e3;let e=Math.round((this.p2p+this.share)/this.http*100);return e<=0&&(e=1),e}}const Ge="SW_GEOIP_KEY",He=2592e5,$e=432e5,Ke="TRACKER_EXPT",We="IPAPI_ERROR",Ve="ZXU",qe="uY2R",je="LmNv",Ye="uYnll",ze="bQ==",Xe="Z3o",Qe="aGsuc3d",Je="hcm1j",Ze="bG91ZC",et="5uZXQ=",tt=Symbol("httpDownloaded"),rt=Symbol("p2pDownloaded"),it=Symbol("p2pUploaded");class nt extends(s()){constructor(e,t,r,i,n){let s;super(),this.config=e.config;let a=this.config.announceLocation;switch(this.config.trackerZone&&(a=this.config.trackerZone),a){case"hk":s=Qe+Je+Ze+et;break;case"us":s="dXMuaGR0dmNsb3VkLmNvbQ==";break;case"cn":s=Xe+qe+Ye+je+ze;break;default:s=Ve+qe+Ye+je+ze}this.engine=e,this.key=t||void 0,this.baseUrl=i||`https://${self.atob(s)}/v1`,this.channelId=self.btoa(r),this.timestamp=g(),this.health=new Ue;const o=l().parseURL(this.baseUrl).netLoc;this.announce=o.replace(/\/\//,""),function(e,t){function r(e,t,r,i,n){return h(r-219,n)}var i,n,s=e();function a(e,t,r,i,n){return h(n- -994,e)}function o(e,t,r,i,n){return h(i-233,t)}function l(e,t,r,i,n){return h(n-305,r)}for(;;)try{if(156690===-parseInt(o(0,246,0,247))/1*(-parseInt(o(0,243,0,248))/2)+-parseInt(o(0,238,0,245))/3+parseInt(a(-1e3,0,0,0,-989))/4*(-parseInt(r(0,0,225,0,216))/5)+-parseInt((i=-180,n=-173,h(n- -181,i)))/6*(parseInt(l(0,0,324,0,324))/7)+-parseInt(a(-991,0,0,0,-990))/8*(parseInt(l(0,0,313,0,307))/9)+-parseInt(l(0,0,310,0,305))/10+-parseInt(a(-968,0,0,0,-974))/11*(-parseInt(r(0,0,226,0,216))/12))break;s.push(s.shift())}catch(e){s.push(s.shift())}}(d);function h(e,t){var r=d();return(h=function(e,t){return r[e-=0]})(e,t)}const u=function(e,t,r,i,n,s){let a=location.hostname;a===h(-922- -923,-915)&&s&&(a=s+"."+a);return 13,Fe()(a+"2.12.15"+r+i+n,e).substr(0,8)}(this.timestamp,0,this.announce,this.channelId,n.type,this.key);function d(){var e=["13055AgbnUs","2739cfXSxI","CxYEuy093515".split("").reverse().join(""),"localhost","OCXDId9".split("").reverse().join(""),"yek".split("").reverse().join(""),"QyapiZ8635101".split("").reverse().join(""),"scRrUF02".split("").reverse().join(""),"bNcslL58187".split("").reverse().join(""),"QEbZrW65772".split("").reverse().join(""),"12gYmKGR","emantsoh".split("").reverse().join(""),"dIlennahc".split("").reverse().join(""),"pmatsemit".split("").reverse().join(""),"676614MZdLCs","type","hpNRbU1".split("").reverse().join(""),"133332xoUKrS","announce","lmia","substr"];return(d=function(){return e})()}h(895-878,886),this.native=!!n.bundle,this.announceInfo={...n,channel:this.channelId,ts:this.timestamp,version:"2.12.15",v:u,announce:this.announce,k:lt(this.key)},this.announceURL=`${this.baseUrl}/channel`,this.reportFails=0,this.statsRequesting=!1,this.forbidden=!1,this.failConns=0,this.totalHTTPDownloaded=0,this.totalP2PDownloaded=0,this.totalP2PUploaded=0,this[tt]=0,this[rt]=0,this[it]=0,this.speed=0,this.offline=!1,this.errsBufStalled=0,this.mediaRequests=0,this.errsInternalExpt=0}geoipRequest(){const{logger:e}=this.engine;return new Promise(((t,r)=>{if((e=>{const t=localStorage.getItem(e);try{const e=JSON.parse(t);return!(!e.duration||!e.startTime)&&Date.now()-e.startTime{r(e)}))}))}btAnnouncePreflight(){const{logger:e}=this.engine;return this.announceInfo.asn?this.btAnnounce():(e.info("preflight ip-api"),Promise.race([this.geoipRequest(),new Promise(((e,t)=>{setTimeout((()=>{t(Be(new Error("request timeout"),We))}),600)}))]).then((e=>(this._parseGeoResponse(e),this.btAnnounce()))).catch((t=>{if(t.code!==Ke){const t=U(Ge);return t&&(e.info("use expired ipData"),this._parseGeoResponse(t)),this.btAnnounce()}throw t})))}_parseGeoResponse(e){const{lat:t,lon:r,isp:i,as:n,mobile:s,countryCode:a,continentCode:o}=e;s&&(this.announceInfo.netType="cellular");const l=n.split(" ")[0].substr(2);this.announceInfo={...this.announceInfo,lat:t,lon:r,isp:i,asn:l,country:a}}btAnnounce(){const{logger:e}=this.engine;return new Promise(((t,r)=>{fetch(this.announceURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(this.announceInfo)}).then((e=>{if(!e.ok){const t=e.status>=500&&e.status<600;throw Be(new Error(`server response code is ${e.status}`),Ke,{retry:t})}return e.json()})).then((e=>{if(!this.engine)throw Be(new Error("runtime error"),Ke,{retry:!1});const r=e.data;if(r.f&&(this.forbidden=!0),-1===e.ret){const{code:t,msg:r}=e.data;throw Be(new Error(r),Ke,{retry:t>=5e3})}if(r.info&&console.info(`${r.info}`),r.warn&&console.warn(`${r.warn}`),r.min_conns||(r.min_conns=8),(!r.rejected||r.rejected&&r.share_only)&&r.id&&r.report_interval&&r.peers){if(this.peerId=this.id=r.id,r.report_interval<20&&(r.report_interval=20),this.btStats(r.report_interval),this.getPeersURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/peers`,this.statsURL=`${this.baseUrl}/channel/${this.channelId}/node/${this.peerId}/stats`,!this.announceInfo.asn&&r.asn){const{country:e,asn:t,mobile:i,isp:n,lat:s,lon:a}=r;this.announceInfo={...this.announceInfo,country:e,asn:t},G(Ge,{countryCode:e,as:`AS${t}`,mobile:i,isp:n,lat:s,lon:a,status:"success"},i?$e:He)}t(r)}else this.engine&&(this.engine.p2pEnabled=!1)})).catch((t=>{e.error(`btAnnounce error ${t}`);const i=t.code||Ke,n=!t.code||t.retry;r(Be(t,i,{retry:n}))}))}))}btStats(e=10){this.heartbeater=setInterval((()=>{this.postStats()}),1e3*e)}postStatsWithBeacon(){if(this.offline)return;this.offline=!0;let e={off:!0};this.statsRequesting||(e={...e,...this._makeStatsBody()}),this.statsURL&&navigator.sendBeacon&&navigator.sendBeacon(this.statsURL,JSON.stringify(e))}postStats(){const{logger:t}=this.engine;this.statsRequesting=!0,fetch(this.statsURL,{method:"POST",body:JSON.stringify(this._makeStatsBody())}).then((e=>(this.statsRequesting=!1,this.reportFails=0,e.text()))).then((r=>{let i;if(i=r?JSON.parse(r):{ret:0,data:{}},-1===i.ret)clearInterval(this.heartbeater),t.error(`${i.data.msg} code ${i.data.code}`),this.engine.emit(e.RESTART_P2P);else{const{http:e=0,p2p:t=0,share:r=0,failConns:i=0,rebuffers:n=0,requests:s=0,errsInternalExpt:a=0}=this.lastStats||{};this[tt]>=e&&(this[tt]-=e),this[rt]>=t&&(this[rt]-=t),this[it]>=r&&(this[it]-=r),this.failConns>=i&&(this.failConns-=i),this.errsBufStalled>=n&&(this.errsBufStalled-=n),this.mediaRequests>=s&&(this.mediaRequests-=s),this.errsInternalExpt>=a&&(this.errsInternalExpt-=a),this.exptMsg&&(this.exptMsg=void 0)}})).catch((e=>{t.error(`btStats error ${e}`),this.statsRequesting=!1,this.reportFails++,this.reportFails>=3&&clearInterval(this.heartbeater)}))}btGetPeers(e,t=!1){const{logger:r}=this.engine,{asn:i,country:n}=this.announceInfo;let s={exclusions:e,asn:i,country:n,ratio:this.health.healthRatio,urgent:t||void 0},a={};return this.engine.getExtraForPeersRequest&&(a=this.engine.getExtraForPeersRequest()),s=Object.assign({},s,a),new Promise(((e,t)=>{this.reportFails>=3?t(new Error("reportFails >= 3")):fetch(this.getPeersURL,{headers:this._requestHeader,method:"POST",body:JSON.stringify(s)}).then((e=>e.json())).then((r=>{-1===r.ret?t(r.data.msg):e(r.data)})).catch((e=>{r.error(`btGetPeers error ${e}`),t(e)})).finally((()=>{this.health.resetTraffic()}))}))}increFailConns(){this.failConns++}increRebuffers(){this.engine.emitEvent("bufferStalled"),this.errsBufStalled++}increMediaRequests(){this.mediaRequests++,this.engine.emit(e.MEDIA_REBUFFER,this.errsBufStalled>=2)}reportFlow(e){const t=Math.round(e/1024);this.engine.emitEvent("httpDownloaded",t),this[tt]+=t,this.totalHTTPDownloaded+=t,this.health.recordHttp(t),this._emitStats()}reportDCTraffic(e,t){const r=Math.round(e/1024);this[rt]+=r,this.totalP2PDownloaded+=r,this.health.recordP2p(r),this.speed=Math.round(t),this.engine.emitEvent("p2pDownloaded",r,this.speed),this._emitStats()}reportUploaded(e=0){const t=Math.round(e/1024);this.engine.emitEvent("p2pUploaded",t),this.totalP2PUploaded+=t,this.health.recordShare(t),this[it]+=t,this._emitStats()}destroy(){const{logger:e}=this.engine;e.warn("destroy fetcher"),this.removeAllListeners(),clearInterval(this.heartbeater)}_emitStats(){const{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:r}=this;this.engine.emit("stats",{totalHTTPDownloaded:e,totalP2PDownloaded:t,totalP2PUploaded:r,p2pDownloadSpeed:this.speed});const{getStats:i}=this.config;A(i)&&i(t,r,e,this.speed)}_makeStatsBody(){const{asn:e,country:t}=this.announceInfo;let r={totalConns:this.engine.tracker.totalConns,failConns:this.failConns,rebuffers:this.errsBufStalled||void 0,requests:this.mediaRequests||void 0,errsInternalExpt:this.errsInternalExpt,http:Math.round(this[tt])||0,p2p:Math.round(this[rt])||0,share:Math.round(this[it])||0,asn:e,country:t},i={};this.engine.getExtraForStats&&(i=this.engine.getExtraForStats()),r=Object.assign({},r,i),this.lastStats=JSON.parse(JSON.stringify(r)),Object.keys(r).forEach((e=>{0===r[e]&&delete r[e]}));const{logger:n}=this.engine;return n.isDebugLevel&&n.info(`report ${JSON.stringify(r)}`),this.exptMsg&&(r.exptMsg="2.12.15 "+this.exptMsg),r}get _requestHeader(){let e={};return this.native&&(e={...e,"X-SW-Key":lt(this.key),"User-Agent":"electron","X-SW-ID":this.announceInfo.bundle}),e}}const st=nt;function at(e,t){const r=ot();return(at=function(e,t){return r[e-=0]})(e,t)}function ot(){const e=["CsLPpZ8932212".split("").reverse().join(""),"htgnel".split("").reverse().join(""),"UZpUzY5895021".split("").reverse().join(""),"yJZuxA9452121".split("").reverse().join(""),"tAedoCrahc".split("").reverse().join(""),"btoa","q#{this._longPolling()}))}_hello(e){fetch(this.addr+"&hello",{method:"POST"}).then((e=>{if(!e.ok)throw new Error("hello response was not ok");return e.json()})).then((t=>{this.connected=!0,e(),this.onopen&&this.onopen(t.ver)})).catch((e=>{this.closed=!0,this.onerror&&this.onerror(e)}))}send(e){this.msgQueue.push(e),this.posting||this._realSend([...this.msgQueue])}_realSend(e){0!==e.length&&(this.posting=!0,this.msgQueue=[],fetch(this.addr,{method:"POST",body:JSON.stringify(e)}).then((()=>{this.posting=!1,this.msgQueue.length>0&&this._realSend([...this.msgQueue])})).catch((e=>{this.logger.error(e),this.posting=!1})))}close(){this.connected&&(this.closed=!0,this.connected=!1,this.abortController&&(this.abortController.abort(),this.abortController=null),this.onclose&&this.onclose())}destroy(){this.close(),this.removeAllListeners()}_longPolling(){if(this.closed)return;this.abortController=new AbortController;const e=this.abortController.signal;fetch(this.addr,{signal:e}).then((e=>{if(!e.ok)throw new Error("polling response was not ok");return e.text()})).then((e=>{e&&this.onmessage&&this.onmessage(JSON.parse(e)),this.retryCount=0,this._longPolling()})).catch((e=>{this.connected&&(this.retryCount<=3?(this.retryCount++,this._longPolling()):(this.connected=!1,this.onerror&&this.onerror(e)))}))}}const ut=class{constructor(e,t,r,i="main"){this.logger=e,this.config=t,this.wsAddr=r,this.serverVersion=0,this.pingInterval=95e3,this.name=i,this.normalClosed=!1,this.lastSendTs=performance.now(),this.pollingClient=new ht(e,r);try{this._ws=this._init()}catch(t){e.error(t),this._startPolling()}}get batchSupported(){return this.serverVersion>=50}_init(){const e={maxRetries:this.config.wsMaxRetries,minReconnectionDelay:p(15e3,6e4),maxReconnectionDelay:6e5,maxEnqueuedMessages:20,connectionTimeout:7e3};let t=new F(this.wsAddr,void 0,e);return t.addEventListener("open",(()=>{this.logger.info(`signal ${this.name} ${this.wsAddr} connection opened`),this.normalClosed=!1,this.pollingClient.connected?this.pollingClient.close():this.onopen&&this.onopen(),this._startPing(this.pingInterval)})),t.push=t.send,t.send=e=>{this.lastSendTs=performance.now();let r=JSON.stringify(e);t.push(r)},t.addEventListener("message",(e=>{let t=e.data;const r=JSON.parse(t),i=r.action;if("pong"!==i){if("ver"!==i)return"close"===i?(this.logger.warn(`server close signal ${this.name} reason ${r.reason}`),void this.close()):void(this.onmessage&&this.onmessage(r,this.name));this.serverVersion=r.ver}else clearTimeout(this.pongTimer)})),t.addEventListener("close",(e=>{this.logger.warn(`signal ${this.name} ${this.wsAddr} closed ${e.code} ${e.reason}`),e.code>=5e3||e.code<4e3?(this.onclose&&this.onclose(),this._stopPing()):this.close()})),t.addEventListener("error",(e=>{this._stopPing(),this.onerror&&this.onerror(e),this._startPolling()})),t}forcePolling(){this.pollingClient.connected||(this.close(),this.pollingClient=new ht(this.logger,this.wsAddr),this._startPolling())}_startPolling(){this.pollingClient.connected||(this.logger.info(`${this.name} start polling`),this.pollingClient.start(),this._setupPolling(this.pollingClient))}sendDebug(e,t,r){this._send({action:"debug",details:t,ping:r||void 0,to:e})}sendSignal(e,t){const r={action:"signal",to:e,data:t};this._send(r)}sendSignalBatch(e,t){if(this.batchSupported&&t.length>1)this._send({action:"signals",to:e,data:t});else for(let r of t)this.sendSignal(e,r)}sendReject(e,t,r){if(this.rejectIdCache===e)return;this.rejectIdCache=e;const i={action:"reject",to:e,reason:t,fatal:r};this._send(i)}_send(e){this.pollingClient.connected?this.pollingClient.send(e):this._ws&&this._ws.send(e)}_startPing(e){this.connected&&(this.pingTimer=setTimeout((()=>{const e=95e3-(performance.now()-this.lastSendTs);if(e>=0)return this._startPing(e);const t={action:"ping"};this._ws&&this._ws.push(JSON.stringify(t)),this.pongTimer=setTimeout((()=>{this.logger.warn(`signal ${this.name} wait for pong timeout, reconnect`),this.close(),this.reconnect()}),15e3),this._startPing(this.pingInterval)}),e))}_stopPing(){clearTimeout(this.pingTimer),clearTimeout(this.pongTimer)}close(){this.logger.info(`close signal ${this.name}`),this._stopPing(),(()=>{this._ws&&this._ws.close(1e3)})(),this.pollingClient.close(),this.normalClosed=!0}reconnect(){this._ws&&(this.logger.info(`reconnect signal ${this.name}`),this._ws.reconnect())}destroy(){this.close(),this._ws=null,this.pollingClient.destroy()}get connected(){return!!this.pollingClient.connected||this._connected}get _connected(){return!!this._ws&&this._ws.readyState===F.OPEN}_setupPolling(e){e.onopen=e=>{e&&(this.serverVersion=e),this.logger.info(`${this.name} polling opened`),this.onopen&&this.onopen()},e.onerror=e=>{this._connected||this.onerror&&this.onerror(e)},e.onclose=()=>{this._connected||this.onclose&&this.onclose()},e.onmessage=e=>{if(this.onmessage)for(let t of e)this.onmessage(t,this.name)}}},dt=class{constructor(e,t,r,i){this.logger=e,this.config=t,this.mainAddr=r,this.backupAddr=i,this.mainWS=this._init(r),this.backupTimer=setTimeout((()=>{this.destroyed||(this.backupWS=this._init(i,"backup"))}),900),this._connected=!1,this.destroyed=!1,this.normalClosed=!1}_init(e,t){if(!e)return null;let r=new ut(this.logger,this.config,e,t);return r.onopen=()=>{this.normalClosed=!1,!this._connected&&this.onopen&&(this._connected=!0,this.onopen())},r.onmessage=e=>{this.onmessage&&this.onmessage(e,r.name)},r.onclose=()=>{this._connected&&!this.connected&&this.onclose&&(this._connected=!1,this.onclose())},r.onerror=e=>{this.onerror&&this.onerror(e)},r}sendSignalBatch(e,t,r){if(r){const i=this._getWSByName(r);i&&i.sendSignalBatch(e,t)}else this.mainConnected?this.mainWS.sendSignalBatch(e,t):this.backupConnected&&this.backupWS.sendSignalBatch(e,t)}sendSignal(e,t,r){this.sendSignalBatch(e,[t],r)}sendReject(e,t,r,i){if(i){const n=this._getWSByName(i);if(n)return void n.sendReject(e,t,r)}this.mainConnected?this.mainWS.sendReject(e,t,r):this.backupConnected?this.backupWS.sendReject(e,t,r):this.logger.warn("no signal available, send reject failed")}sendDebug(e,t,r){this.mainConnected&&this.mainWS.sendDebug(e,t,r)}close(){this.mainWS&&this.mainWS.close(),this.backupWS&&this.backupWS.close(),this.normalClosed=!0}_getWSByName(e){return this.mainWS&&this.mainWS.name===e?this.mainWS:this.backupWS&&this.backupWS.name===e?this.backupWS:null}reconnect(e){this.mainWS&&"backup"!==e&&this.mainWS.reconnect(),this.backupWS&&"main"!==e&&this.backupWS.reconnect()}forcePolling(e){this.mainWS&&"backup"!==e&&this.mainWS.forcePolling(),this.backupWS&&"main"!==e&&this.backupWS.forcePolling()}destroy(){this.close(),clearTimeout(this.backupTimer),this.mainWS=null,this.backupWS=null,this.destroyed=!0}get connected(){return this.mainConnected||this.backupConnected}get mainConnected(){return this.mainWS&&this.mainWS.connected}get backupConnected(){return this.backupWS&&this.backupWS.connected}};const ct=function(e,t,r=40){var i=null,n=!1,s=r;return function(r=!1){if(r)return clearTimeout(i),void(n=!1);n||(n=!0,i=setTimeout((function(){e.call(t,s),n=!1,i=null}),1e3*s),s*=1.1)}};class ft{constructor(e,t,r=10){this.engine=e,this.config=t,this.trickle=t.trickleICE,this.poolSize=r,this.pool=[],t.ICEPreflight&&this.reset(),this.trickle=!1}reset(){this.destroy();for(let e=0;e0}getPeer(){if(0===this.pool.length)return this._createPeer();const e=this.pool.shift();return this.pool.length<5&&this.pool.push(this._createPeer()),e}destroy(){for(let e of this.pool)e.destroy(!0);this.pool=[]}}const gt=class{static CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";static BITS_PER_BYTE=8;static BITS_PER_BASE64_CHAR=6;static decode(e){let t=0,r=0,i="";for(const n of e){if("="===n)break;const e=this.CHARSET.indexOf(n);for(t=t<=this.BITS_PER_BYTE;){r-=this.BITS_PER_BYTE;i+=(t>>r&(1<(e.startsWith("C")&&(e="candidate:"+e.slice(1)),e.split(" ").map((e=>(e in Lt&&(e=Lt[e]),e))).join(" "));function Pt(e,t){let r=e.split("~"),i=[];r=r.map((e=>{let t=e.slice(0,1),r=e.slice(1);if(t in St&&(t=St[t]),"a="===t){let e=r.slice(0,1);const t=r.slice(1);e in Tt&&(e=Tt[e],r=e+t)}return t+r})),i.push("v=0"),i.push("s=-"),i.push("t=0 0"),i.push("a=msid-semantic: WMS");let n=0;r.forEach((e=>{if(e.startsWith("o=")){let t=e.slice(2).split(" "),r=[];r.push("-");const n=t.shift();if(n&&r.push(n),0===t.length)r.push("2 IN IP4 127.0.0.1");else{const e=t.shift();if(e&&r.push(e),0===t.length)r.push("IN IP4 127.0.0.1");else{r.push("IN");const e=t.shift();e&&r.push(e);const i=t.shift();i&&r.push(i)}}i.splice(1,0,`o=${r.join(" ")}`)}else{if(e.startsWith("m="))return e=function(e){return e.replace(It,(e=>bt[e]))}(e),i.push(e),i.push("a=setup:"+(t?"actpass":"active")),i.push(`a=mid:${n}`),void n++;if(e.startsWith("a=candidate:"))return e=wt(e),void i.push(e);if(e.startsWith("a=fingerprint:")){let[t,r]=e.slice(14).split(" ");return t in _t&&(t=_t[t]),r=gt.decode(r),void i.push(`a=fingerprint:${t} ${r}`)}if(e.startsWith("c=")){let[t,r]=e.slice(2).split(" ");return t in Rt&&(t=Rt[t]),r in At&&(r=At[r]),void i.push(`c=IN ${t} ${r}`)}"I"!==e?"Z"!==e?"B"!==e?i.push(e):i.push("a=sendrecv"):i.push("a=ice-options:ice2,trickle"):i.push("a=ice-options:trickle")}}));const s=i.length-1;return i.splice(s,0,`a=group:BUNDLE ${Array.from(Array(n).keys()).join(" ")}`),i.join("\r\n")}const It=new RegExp(Object.keys(bt).join("|"),"g");class Ct extends(s()){constructor(e,t,r,i){super(),this.engine=e,this.logger=e.logger,this.config=i,this.connected=!1,this.scheduler=r,this.sequential=this.scheduler.sequential,this.DCMap=new Map,this.failedDCMap=new Map,this.notFoundDCSet=new Set;const n=Q().isMobile();this.peerPool=new ft(e,i,15),this.signalerWs=null,this.fetcher=t,this.peers=[],this.requestPeersQueue=[],this.minConns=5,this.stuns=[],this.requestMorePeers=ct(this._requestMorePeers,this,p(35,45)),this.maxConns=n?15:22,this.maxConnsActive=n?10:13,this.peersIncrement=0,this.gotPeersFromTracker=!1,this.requestPeersWaitCount=0,this.gotSignalFails={main:0,backup:0,limit:5},this.fuseRate=-1,this.overloaded=!1}get totalConns(){return this.scheduler.peersNum+1}resumeP2P(){if(!this.fetcher)return;const{engine:t,config:r,fetcher:i}=this,{btAnnounce:n,btAnnouncePreflight:s}=i,{wsSignalerAddr:a,wifiOnly:o,geoIpPreflight:l}=r;(l?s:n).call(i).then((e=>{const{scheduler:r}=this;if(!r)return;t.peerId=this.peerId=e.id,this.minConns=e.min_conns,r.minConns=this.minConns;const n=e.peers;r.notifyPeersLoaded(n.length),n.length>this.gotSignalFails.limit&&(this.gotSignalFails.limit=n.length),t.netType=i.announceInfo.netType,(e.wifi_only||o)&&t.isMobileNet&&(r.downloadOnly=!0,this.logger.info("downloadOnly mode"));const s=a.main;let l=a.backup;function h(e,t){var r=u();return(h=function(e,t){return r[e-=0]})(e,t)}function u(){var e=["IHmzPt4745802".split("").reverse().join(""),"fqbpvJ65672".split("").reverse().join(""),"peerId","evitcAsnnoCxam".split("").reverse().join(""),"0r^EeI@*KS".split("").reverse().join(""),"yGChQi82100203".split("").reverse().join(""),"dIlennahc".split("").reverse().join(""),"qrZmAF0973735".split("").reverse().join(""),"qNTzkD6562665".split("").reverse().join(""),"timestamp","HaovMZ5303011".split("").reverse().join(""),"blnwIB1433257".split("").reverse().join(""),"39zAjEpC","substring"];return(u=function(){return e})()}var d,c;e.signal&&!e.signal2&&(l=void 0),this.signalerWs=this._initSignalerWs(e.signal||s,e.signal2||l,e.token,e.token2),0===n.length?this.requestMorePeers():this.peers=this._filterPeers(n),t.emitEvent("peerId",this.peerId),e.stun&&e.stun.length>0&&(this.stuns=e.stun),e.debug&&(this.logger.enableDebug(),e.log_url&&(this.logUploader=new B(e.log_url,this.fetcher.key||location.hostname,this.peerId,"2.12.15"),this.logger.setUploader(this.logUploader))),t.onTrackerResume&&t.onTrackerResume(e),e.fuse_rate&&(this.fuseRate=e.fuse_rate),e.overload&&(this.overloaded=!0,this.logger.warn("server overloaded, degrade signaling")),this.logger.info(`announce request response ${JSON.stringify(e,null,2)}`),function(e,t){function r(e,t,r,i,n){return h(t- -94,n)}var i=e();function n(e,t,r,i,n){return h(t-586,r)}function s(e,t,r,i,n){return h(i-742,n)}for(;;)try{if(595581===-parseInt(r(0,-83,0,0,-88))/1+-parseInt(n(0,587,588))/2+parseInt(n(0,599,592))/3*(-parseInt(n(0,588,591))/4)+parseInt(r(0,-86,0,0,-83))/5+-parseInt(s(0,0,0,751,751))/6+-parseInt(s(0,0,0,754,760))/7+parseInt(h(403-397,399))/8)break;i.push(i.shift())}catch(e){i.push(i.shift())}}(u),e.v!==Fe()(i.channelId+this.peerId+i.timestamp+(d=701,c=702,h(d-696,c)),"2.12.15").substring(0,8)&&(this.maxConnsActive=1)})).catch((r=>{if(this.scheduler&&("TRACKER_EXPT"===r.code&&t.emitEvent(e.EXCEPTION,r),this.scheduler.notifyPeersLoaded(0),r.retry)){const e=p(15e3,4e4);this.logger.warn(`announce retry after ${e}ms`),this.announceTimer=setTimeout((()=>{this.resumeP2P()}),e)}}))}stopP2P(){this.fetcher.postStatsWithBeacon(),this.fetcher.destroy(),this.fetcher=null,this.requestMorePeers(!0),this.scheduler.destroy(),this.scheduler=null,this.signalerWs&&(this.signalerWs.destroy(),this.signalerWs=null),this.peers=[];for(let e of this.DCMap.values())e.destroy(!0);this.DCMap.clear(),this.peerPool.destroy(),this.peerPool=null,this.failedDCMap.clear(),this.notFoundDCSet.clear(),this.logUploader&&(this.logUploader.destroy(),this.logUploader=null),this.logger.warn("tracker stop p2p")}destroy(){this.stopP2P(),this.removeAllListeners(),clearTimeout(this.announceTimer),clearTimeout(this.requestPeersTimer);const{config:e}=this;e.getStats=e.getPeerId=e.getPeersInfo=null,this.logger.warn("destroy tracker")}isPeerConnectedOrFailed(e){return!e||(this.DCMap.has(e)||this.failedDCMap.has(e)||e===this.peerId)}_filterPeers(e){const t=[];return e.filter((e=>!this.isPeerConnectedOrFailed(e.id))).forEach((e=>{t.push({id:e.id,intermediator:e.intermediator})})),t}_tryConnectToAllPeers(){const{logger:e}=this;if(0!==this.peers.length)for(this._checkDCMap(),e.info(`try connect to ${this.peers.length} peers, map size ${this.DCMap.size} limit ${this.maxConnsActive} peersNum ${this.scheduler.peersNum}`);this.peers.length>0&&!(this.DCMap.size>=this.maxConnsActive);){let t=this.peers.shift();if(this.isPeerConnectedOrFailed(t.id))continue;const r=t.intermediator;this.signalerWs.connected||r&&this.DCMap.has(r)?(e.debug(`create DataChannel ${t.id} intermediator ${r}`),this._createDatachannel(t.id,!0,r)):e.info(`skip peer ${t.id} without intermediator`)}else e.info("no peers after filter")}_handleSendSignal(e,t){const r=e.remotePeerId;if(e.intermediator){const i=this.DCMap.get(e.intermediator);if(i){let n=!0;for(let e of t)i.sendMsgSignal(r,this.peerId,e)||(n=!1);if(n)return;this.logger.warn(`intermediator ${e.intermediator} relay failed`)}}e.intermediator=void 0,this.signalerWs.sendSignalBatch(r,t,e.signalName)}_setupDC(t){t.on(e.DC_SIGNAL,(e=>{this._handleSendSignal(t,[e])})).on(e.DC_SIGNAL_BATCH,(e=>{this._handleSendSignal(t,e)})).on(e.DC_PEER_SIGNAL,(e=>{const r=e.to_peer_id||e.to,i=e.from_peer_id||e.from,n=e.action;if(r&&i&&n)if(r!==this.peerId){this.logger.info(`relay signal for ${i}`);const s=this.DCMap.get(r);if(s){if("signal"!==n)return void s.sendMsgSignalReject(r,i,e.reason,e.fatal);if(s.sendMsgSignal(r,i,e.data))return}t.sendMsgSignal(i,r)}else"signal"===n?this._handleSignalMsg(i,e,t.remotePeerId):this._handSignalRejected(i,e)})).on(e.DC_GET_PEERS,(()=>{const e=g(),r=this.scheduler.getPeers().filter((e=>e.peersConnected<(e.mobileWeb?15:22)&&!e.super));if(r&&r.length>0){const i=[];r.forEach((r=>{if(r.remotePeerId===t.remotePeerId||r.remotePeerId===this.peerId)return;if(!this.config.live&&(r.currentPos-t.currentPos>600||r.currentPos50&&i.push({id:r.remotePeerId,...r.region})})),this.logger.info(`send ${i.length} peers to ${t.remotePeerId}`),t.sendPeers(i)}})).on(e.DC_PEERS,(e=>{const r=e.peers;this.logger.info(`receive ${r.length} peers from ${t.remotePeerId}`),r&&r.length>0&&(r.forEach((e=>{e.intermediator=t.remotePeerId,e.region||(e.region={})})),this.requestPeersQueue.push(...r)),this.requestPeersWaitCount--,this.requestPeersWaitCount<=0&&this._handleRequestedPeers()})).once(e.DC_ERROR,((e,r)=>{this.logger.warn(`datachannel ${t.channelId} failed fatal ${e} ${r}`),this.scheduler&&(this.scheduler.deletePeer(t),this._destroyAndDeletePeer(t.remotePeerId,e),this.fetcher&&(t.connected||e&&this.fetcher.increFailConns(),e&&this.failedDCMap.set(t.remotePeerId,`DC_FAILED ${r}`),this._doSignalFusing(this.scheduler.peersNum),this._doPeersRequest()))})).once(e.DC_TIMEOUT,(({gotSignal:e,sentSignal:r,data:i})=>{const{logger:n,signalerWs:s,gotSignalFails:a}=this,{remotePeerId:o,useBackupSignal:l,isInitiator:h}=t,u=l?"backup":"main";if(e?a[u]=0:(a[u]++,a[u]>=a.limit&&(a[u]=0,n.warn("gotSignalFails many, forcePolling"),s.forcePolling(u))),r&&e&&h&&(this.failedDCMap.set(o,"DC_TIMEOUT"),this.fetcher&&this.fetcher.increFailConns()),!e&&h&&!l&&this._tryBackupSignal(t,o,i))return t._startTimer(),void n.warn(`${o} conn timeout, try backup signal`);this._destroyAndDeletePeer(o,!1),this._doPeersRequest()})).once(e.DC_CLOSE,(e=>{this.logger.info(`datachannel ${t.channelId} closed fatal ${e}`),this.scheduler&&(this.scheduler.deletePeer(t),this._doSignalFusing(this.scheduler.peersNum)),this._destroyAndDeletePeer(t.remotePeerId,e),e&&this.failedDCMap.set(t.remotePeerId,"DC_CLOSE"),this._doPeersRequest()})).once(e.DC_OPEN,(()=>{t.isInitiator&&this.scheduler.handshakePeer(t)})).once(e.DC_METADATA,(e=>{const{scheduler:r}=this;t.isInitiator||r.handshakePeer(t),r.handleMetaData(t,e);const i=this.DCMap.size>=this.maxConnsActive;this.requestMorePeers(i),t.intermediator&&this.peersIncrement++,this._doSignalFusing(r.peersNum)}))}_doPeersRequest(){const e=this.scheduler.peersNum;!this.signalerWs.connected||this.overloaded&&e>this.minConns?this._requestPeersFromPeers(e):this.requestMorePeers(),this._tryConnectToAllPeers()}_doSignalFusing(e){if(this.fuseRate<=0)return;const t=this.signalerWs.connected;t&&e>=this.fuseRate?(this.logger.warn("reach fuseRate, report stats close signaler"),this.totalConns-1>0&&this.fetcher.postStats(),this.signalerWs.close()):!t&&e<=this.minConns&&this.signalerWs.normalClosed&&(this.logger.warn(`low conns ${e}, reconnect signaler`),this.signalerWs.reconnect())}_initSignalerWs(t,r,i,n){const s=(e,t)=>{let r=`${e}?id=${this.peerId}&p=web&v=2.12.15`;return this.config.signalCompact&&(r=`${r}&c=1`),t&&(r=`${r}&token=${t}`),r};let a,o=s(t,i);if(r&&r!==t){let e=s(r,n);a=new dt(this.logger,this.config,o,e)}else a=new ut(this.logger,this.config,o);return a.onopen=()=>{this.connected=!0,this.engine.emitEvent("serverConnected",!0),this._tryConnectToAllPeers()},a.onmessage=(e,t)=>{let r=e.action;const i=e.from_peer_id||e.from;if(i)switch(r){case"signal":this._handleSignalMsg(i,e,null,t);break;case"reject":this._handSignalRejected(i,e);break;default:this.logger.warn(`Signal websocket unknown action ${r}`)}else this.logger.warn("fromPeerId is missed")},a.onclose=()=>{this.connected=!1,this.engine.emitEvent("serverConnected",!1)},a.onerror=t=>{t.message&&this.logger.warn(`signal err: ${t.message}`),t.message&&this.engine.emitEvent(e.EXCEPTION,Be(t,"SIGNAL_EXPT"))},a}_handSignalRejected(e,t){const r=`signaling ${e} rejected`;this.logger.warn(`${r}, reason ${t.reason}`);const i=this.DCMap.get(e);i&&!i.connected&&(i.destroy(t.fatal),this.DCMap.delete(e)),this.requestMorePeers(),t.fatal&&this.failedDCMap.set(e,r),this._tryConnectToAllPeers()}_tryBackupSignal(e,t,r,i="main"){return!(!(this.signalerWs.backupConnected&&e&&r.length>0&&"main"===i)||e.useBackupSignal)&&(e.useBackupSignal=!0,e.signalName="backup",e.intermediator=void 0,this.signalerWs.sendSignalBatch(t,r,"backup"),!0)}_handleSignalMsg(e,t,r,i){if(!this.scheduler)return;const{logger:n}=this;if(t.data){if(this.failedDCMap.has(e))return void this._sendSignalReject(e,`${e} ${this.failedDCMap.get(e)||"unknown"}`,r,i,!0);this._handleSignal(e,t.data,r,i)}else{const t=this.DCMap.get(e);if(!t)return;if(this._tryBackupSignal(t,e,t.signalMsgs,i))return void this.logger.warn(`${e} not found from main, try backup signal`);if(t.useBackupSignal)return;this._destroyAndDeletePeer(e),n.info(`signaling ${e} not found`);const{scheduler:s}=this;s.waitForPeer&&(s.waitingPeers--,0===s.waitingPeers&&s.notifyPeersLoaded(0)),this.requestMorePeers(),this._tryConnectToAllPeers(),r||this.notFoundDCSet.add(e)}}_handleSignal(e,t,r,i){"string"==typeof t&&(t=(e=>{if("C"===e[0])return{type:"candidate",candidate:{candidate:wt(e),sdpMLineIndex:0,sdpMid:"0"}};const t=e.slice(1),r="O"===e[0];return{type:r?"offer":"answer",sdp:Pt(t,r)}})(t));const n=t.type,{logger:s}=this;let a=this.DCMap.get(e);if(a){if(a.connected)return void s.info("datachannel had connected, signal ignored");if("offer"===n&&a.isInitiator){if(!(this.peerId>e))return void s.warn(`${e} signal type wrong ${n}, ignored`);s.warn(`${e} signal type wrong ${n}, convert to non initiator`),this._destroyAndDeletePeer(e,!1),a=this._createDatachannel(e,!1,r)}}else{if("answer"===n){const t=`${e} type wrong ${n}`;return s.warn(t),this._sendSignalReject(e,t,r,i),void this._destroyAndDeletePeer(e,!1)}if(s.debug(`receive node ${e} connection request`),this.DCMap.size>=this.maxConns){const t=`reach limit ${this.maxConns}`;return s.warn(t),void this._sendSignalReject(e,t,r,i)}a=this._createDatachannel(e,!1,r)}a&&(i&&(a.signalName=i),a.receiveSignal(t))}_createDatachannel(e,t,r){if(!this.fetcher)return;let i;if(t&&this.peerPool.available)i=this.peerPool.getPeer(),this.logger.info(`get peer from pool, signal size ${i.signalMsgs.length}`),i.intermediator=r,i.assignPeerId(this.peerId,e);else{let n=this.config.trickleICE;this.overloaded&&(n=!1),i=new Z(this.engine,this.peerId,e,t,this.config,{stuns:this.stuns,intermediator:r,trickle:!r&&n})}return this.DCMap.set(e,i),this._setupDC(i),i}_sendSignalReject(e,t,r,i,n){if(r){const i=this.DCMap.get(r);if(i&&i.sendMsgSignalReject(e,this.peerId,t,n))return}this.signalerWs.sendReject(e,t,n,i)}_requestMorePeers(e){if(!this.fetcher)return;const{logger:t}=this,r=this.scheduler.peersNum;r>=this.maxConnsActive||(t.info(`requestMorePeers after delay ${e}, peersIncrement ${this.peersIncrement}`),r<3||r50&&(this.failedDCMap=new Map([...this.failedDCMap].slice(-50))),this.notFoundDCSet.size>20&&(this.notFoundDCSet=new Set([...this.notFoundDCSet].slice(-20))),this.fetcher.btGetPeers([...this.DCMap.keys(),...this.failedDCMap.keys(),...this.notFoundDCSet.keys()],0===e).then((e=>{e&&e.peers&&(t.info(`requestMorePeers resp ${JSON.stringify(e,null,2)}`),this.peers=this._filterPeers(e.peers),this._tryConnectToAllPeers())})).catch((e=>{t.error(`requestMorePeers error ${e}`)})),this.gotPeersFromTracker=!0}_requestPeersFromPeers(e){return!!this.requestPeersTimer||(e>=this.maxConnsActive||(this.requestPeersWaitCount=this.scheduler.requestPeers(),0!==this.requestPeersWaitCount&&(this.gotPeersFromTracker=!1,this.requestPeersTimer=setTimeout((()=>{this.logger.warn("requestPeersTimer timeout"),this._handleRequestedPeers()}),1e4),!0)))}_handleRequestedPeers(){if(clearTimeout(this.requestPeersTimer),this.requestPeersTimer=void 0,this.fetcher){if(this.requestPeersQueue.length>0){const e=function(e,t){const r=[],i=new Set;for(let t of e)i.has(t.id)||(i.add(t.id),r.push(t));const{asn:n,country:s}=t;if(!n||!s||r.length<2)return r;const a=r.filter((e=>!e.asn&&!e.country)),o=r.filter((e=>e.country===s&&e.asn!==n)),l=r.filter((e=>e.asn===n&&e.country===s)),h=r.filter((e=>!a.includes(e)&&!l.includes(e)&&!o.includes(e)));return l.concat(o).concat(a).concat(h)}(this.requestPeersQueue,this.fetcher.announceInfo);this.peers=this._filterPeers(e),this.requestPeersQueue=[]}this._tryConnectToAllPeers()}}_destroyAndDeletePeer(e,t=!0){const r=this.DCMap.get(e);return!!r&&(r.destroy(t),this.DCMap.delete(e),!0)}_checkDCMap(){const e=g();for(let t of this.DCMap.values()){const r=e-t.timeJoin;e-t.timeJoin>30&&!t.connected&&(this.logger.warn(`delete ${t.remotePeerId} not connected for ${r} in DCMap`),this._destroyAndDeletePeer(t.remotePeerId,!1))}}}const kt=Ct;class Dt extends ue{constructor(e={},t=null){if(super(e),e.validateSegment||(e.validateSegment=function(e,t){return!0}),this.hlsjs=t,this.config=Object.assign({useDiskCache:!e.live},Ee,e),t){this.HLSEvents=t.constructor.Events;const e=t.constructor.version;this.hlsjsVersion=e,this.config.isHlsV0=e&&"0"===e.split(".")[0]}this.lastLevel=0,this.multiBitrate=!1}setup(){let{token:e,channelId:t}=this.config,r=e=>{const t=l().parseURL(e);return`${t.netLoc.substring(2)+t.path.substring(0,t.path.lastIndexOf("."))}`};t&&(r=this.makeChannelId(e,t));return{channelIdMaker:r,signalId:this.makeSignalId(),browserInfo:{...this.commonBrowserInfo}}}setupElectron(){this.browserInfo.device===X.device.PC_NATIVE&&(this.browserInfo={...this.browserInfo,app:this.config.appName,bundle:this.config.appId})}getExtraForStats(){const e=super.getExtraForStats();return!this.config.live&&this.media&&(e.pos=Math.round(this.media.currentTime)),this.multiBitrate&&this.currentLevel!==this.lastLevel&&(e.level=this.currentLevel+"",this.lastLevel=this.currentLevel),e}getExtraForPeersRequest(){const e=super.getExtraForPeersRequest();return this.multiBitrate&&(e.level=this.currentLevel+""),e}destroy(){super.destroy()}async initSegmentManager(e){const{logger:r,config:i}=this;if(self.indexedDB&&i.useDiskCache&&!i.live){const e=new ke(this,i);try{await e.setupStore(),this.bufMgr=e}catch(e){r.warn(e),this.bufMgr=new xe(this,i)}}else this.bufMgr=new xe(this,i);if(this.bufMgr.maxBufSize<=0)throw new Error("bufMgr state is invalid");"SegmentStore"===this.bufMgr.name&&(this.removeAllListeners(t.BM_FATAL_ERROR),this.once(t.BM_FATAL_ERROR,(()=>{const t="SegmentStoreFatalError";r.warn(`${t}, switch to SegmentCache`),this.bufMgr.destroy(),this.bufMgr=new xe(this,i),e&&e(this.bufMgr),r.report(JSON.stringify(this.browserInfo),t,this.peerId,"2.12.15",5e4)})))}generateTag(){let e=(0,X.getBrowser)();return e.includes("iPhone")&&"HlsSwP2pEngine"===this.engineName&&(e=`${e}_p`),this.playerName&&(e=`${e}_${this.playerName}`),e}onTrackerResume(e){e.report_url&&this.logger.enableReport(e.report_url)}async _init(e,t,r){const{logger:i,config:n}=this;await this.initSegmentManager((e=>{if(this.tracker){const{scheduler:t}=this.tracker;t.bufferManager=e,t.bitset.clear()}})),r.live||this.media&&(r.pos=Math.round(this.media.currentTime)),r.tag=void 0===n.tag?this.generateTag():n.tag;let s=new st(this,n.token,encodeURIComponent(e),n.announce||"",r);this.fetcher=s,this.tracker=new kt(this,s,t,n),t.bufferManager=this.bufMgr,this.setupWindowListeners()}_setupSegmentId(){this.config.segmentId||(this.config.segmentId=this.config.strictSegmentId?me:pe)}_onHlsError(e,r){if(!r||!this.hlsjs)return;const{logger:i,tracker:n}=this;if(!i)return;const s=`${r.type} details ${r.details} reason ${r.reason}`;if(r.fatal?i.error(s):i.warn(s),"networkError"===r.type&&"HlsjsP2pEngine"===this.engineName)return;const{player:a}=this.browserInfo,o=`${a||""} hlsjs ${this.hlsjsVersion} ${location.href}`,l=this.hlsjs.constructor.ErrorDetails;switch(r.details){case l.BUFFER_STALLED_ERROR:"HlsjsP2pEngine"===this.engineName&&this.fetcher&&this.fetcher.increRebuffers(),n&&n.scheduler&&i.warn("buffered: "+1e3*n.scheduler.getBufferedDuration());break;case l.INTERNAL_EXCEPTION:if(r.event&&"demuxerWorker"!==r.event){r.error||(r.error={});const e=`${r.error.message} event ${r.event} ${o}`;this.fetcher&&r.fatal&&(this.fetcher.errsInternalExpt++,this.fetcher.exptMsg=e),i.error(`INTERNAL_EXCEPTION event ${r.event} err ${r.error.message}`),this.emitEvent(t.EXCEPTION,Be(r.error,"HLSJS_EXPT")),i.report(e,r.event,this.peerId,"2.12.15")}break;default:if(r.fatal||r.details===l.FRAG_PARSING_ERROR){const e=`${r.type} ${r.details} ${r.err||""} ${o}`;i.report(e,r.details,this.peerId,"2.12.15"),"mediaError"===r.type&&this.tracker&&this.tracker.scheduler&&this.tracker.scheduler.clearCache()}}}}class Mt{constructor(){this.method=null,this.key=null,this.iv=null,this._uri=null}get uri(){return!this._uri&&this.reluri&&(this._uri=o.buildAbsoluteURL(this.baseuri,this.reluri,{alwaysNormalize:!0})),this._uri}}class xt{constructor(){this._url=null,this._byteRange=null,this._decryptdata=null,this.tagList=[],this.programDateTime=null,this.rawProgramDateTime=null,this._elementaryStreams={[xt.ElementaryStreamTypes.AUDIO]:!1,[xt.ElementaryStreamTypes.VIDEO]:!1}}static get ElementaryStreamTypes(){return{AUDIO:"audio",VIDEO:"video"}}get url(){return!this._url&&this.relurl&&(this._url=o.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url}set url(e){this._url=e}get byteRange(){if(!this._byteRange&&!this.rawByteRange)return[];if(this._byteRange)return this._byteRange;let e=[];if(this.rawByteRange){const t=this.rawByteRange.split("@",2);if(1===t.length){const t=this.lastByteRangeEndOffset;e[0]=t||0}else e[0]=parseInt(t[1]);e[1]=parseInt(t[0])+e[0],this._byteRange=e}return e}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get decryptdata(){return this._decryptdata||(this._decryptdata=this.fragmentDecryptdataFromLevelkey(this.levelkey,this.sn)),this._decryptdata}get endProgramDateTime(){if(!Number.isFinite(this.programDateTime))return null;let e=Number.isFinite(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}addElementaryStream(e){this._elementaryStreams[e]=!0}hasElementaryStream(e){return!0===this._elementaryStreams[e]}createInitializationVector(e){let t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}fragmentDecryptdataFromLevelkey(e,t){let r=e;return e&&e.method&&e.uri&&!e.iv&&(r=new Mt,r.method=e.method,r.baseuri=e.baseuri,r.reluri=e.reluri,r.iv=this.createInitializationVector(t)),r}}class Ot{constructor(e){this.endCC=0,this.endSN=0,this.fragments=[],this.initSegment=null,this.live=!0,this.needSidxRanges=!1,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=e,this.version=null}get hasProgramDateTime(){return!(!this.fragments[0]||!Number.isFinite(this.fragments[0].programDateTime))}}const Ft=/^(\d+)x(\d+)$/,Nt=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;class Bt{constructor(e){"string"==typeof e&&(e=Bt.parseAttrList(e));for(let t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const r=new Uint8Array(t.length/2);for(let e=0;eNumber.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}enumeratedString(e){return this[e]}decimalResolution(e){const t=Ft.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,r={};for(Nt.lastIndex=0;null!==(t=Nt.exec(e));){let e=t[2],i='"';0===e.indexOf(i)&&e.lastIndexOf(i)===e.length-1&&(e=e.slice(1,-1)),r[t[1]]=e}return r}}const Ut=Bt,Gt={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0}};const Ht=/#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g,$t=/#EXT-X-MEDIA:(.*)/g,Kt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),Wt=/(?:(?:#(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):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/,Vt=/\.(mp4|m4s|m4v|m4a)$/i;class qt{static findGroup(e,t){if(!e)return null;let r=null;for(let i=0;i2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t}static resolve(e,t){return o.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static parseMasterPlaylist(e,t){let r,i=[];function n(e,t){["video","audio"].forEach((r=>{const i=e.filter((e=>function(e,t){const r=Gt[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)));if(i.length){const n=i.filter((e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)));t[`${r}Codec`]=n.length>0?n[0]:i[0],e=e.filter((e=>-1===i.indexOf(e)))}})),t.unknownCodecs=e}for(Ht.lastIndex=0;null!=(r=Ht.exec(e));){const e={},s=e.attrs=new Ut(r[1]);e.url=qt.resolve(r[2],t);const a=s.decimalResolution("RESOLUTION");a&&(e.width=a.width,e.height=a.height),e.bitrate=s.decimalInteger("AVERAGE-BANDWIDTH")||s.decimalInteger("BANDWIDTH"),e.name=s.NAME,n([].concat((s.CODECS||"").split(/[ ,]+/)),e),e.videoCodec&&-1!==e.videoCodec.indexOf("avc1")&&(e.videoCodec=qt.convertAVC1ToAVCOTI(e.videoCodec)),i.push(e)}return i}static parseMasterPlaylistMedia(e,t,r,i=[]){let n,s=[],a=0;for($t.lastIndex=0;null!==(n=$t.exec(e));){const e={},o=new Ut(n[1]);if(o.TYPE===r){if(e.groupId=o["GROUP-ID"],e.name=o.NAME,e.type=r,e.default="YES"===o.DEFAULT,e.autoselect="YES"===o.AUTOSELECT,e.forced="YES"===o.FORCED,o.URI&&(e.url=qt.resolve(o.URI,t)),e.lang=o.LANGUAGE,e.name||(e.name=e.lang),i.length){const t=qt.findGroup(i,e.groupId);e.audioCodec=t?t.codec:i[0].codec}e.id=a++,s.push(e)}}return s}static parseLevelPlaylist(e,t){let r,i,n=0,s=0,a=new Ot(t),o=new Mt,l=0,h=null,u=new xt,d=null;for(Kt.lastIndex=0;null!==(r=Kt.exec(e));){const e=r[1];if(e){u.duration=parseFloat(e);const t=(" "+r[2]).slice(1);u.title=t||null,u.tagList.push(t?["INF",e,t]:["INF",e])}else if(r[3]){if(Number.isFinite(u.duration)){const e=n++;u.start=s,u.levelkey=o,u.sn=e,u.cc=l,u.baseurl=t,u.relurl=(" "+r[3]).slice(1),jt(u,h),a.fragments.push(u),h=u,s+=u.duration,u=new xt}}else if(r[4]){if(u.rawByteRange=(" "+r[4]).slice(1),h){const e=h.byteRangeEndOffset;e&&(u.lastByteRangeEndOffset=e)}}else if(r[5])u.rawProgramDateTime=(" "+r[5]).slice(1),u.tagList.push(["PROGRAM-DATE-TIME",u.rawProgramDateTime]),null===d&&(d=a.fragments.length);else{for(r=r[0].match(Wt),i=1;i=0&&(o.method=f,o.baseuri=t,o.reluri=g,o.key=null,o.iv=p));break;case"START":let i=new Ut(e).decimalFloatingPoint("TIME-OFFSET");Number.isFinite(i)&&(a.startTimeOffset=i);break;case"MAP":let h=new Ut(e);u.relurl=h.URI,u.rawByteRange=h.BYTERANGE,u.baseurl=t,u.sn="initSegment",a.initSegment=u,u=new xt,u.rawProgramDateTime=a.initSegment.rawProgramDateTime;break;default:console.warn(`line parsed but not handled: ${r}`)}}}return u=h,u&&!u.relurl&&(a.fragments.pop(),s-=u.duration),a.totalduration=s,a.averagetargetduration=s/a.fragments.length,a.endSN=n-1,a.startCC=a.fragments[0]?a.fragments[0].cc:0,a.endCC=l,!a.initSegment&&a.fragments.length&&a.fragments.every((e=>Vt.test(e.relurl)))&&(console.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),u=new xt,u.relurl=a.fragments[0].relurl,u.baseurl=t,u.level=id,u.sn="initSegment",a.initSegment=u,a.needSidxRanges=!0),d&&function(e,t){let r=e[t];for(let i=t-1;i>=0;i--){const t=e[i];t.programDateTime=r.programDateTime-1e3*t.duration,r=t}}(a.fragments,d),a}}function jt(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Number.isFinite(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}const Yt={ANY:0,COMPLETE:1,PARTIAL_FORWARD:2,PARTIAL_REVERSE:3},zt=(e,t,r,i,n=!1)=>{const[s,a,o]=Xt(e,t,r,i);return n&&s.length>=1?P(s[0]):s.length>=2?[s[0],s[1]]:I(s,a,o)},Xt=(e,t,r,i)=>{const n=[],{COMPLETE:s,PARTIAL_FORWARD:a,PARTIAL_REVERSE:o}=Yt;return[s,a,o].forEach((s=>{n.push(Qt(e,s,t,r,i))})),n},Qt=(e,t,r,i,n)=>e.filter((e=>e.bitset.hasWithId(r,i,n,t)));class Jt{constructor(e=!1,t){this.isLive=e,this.levelMap=new Map;for(let e in t){const r=Number(e);if(r<0)continue;const i=new Map;if(t[e])for(let r of t[e])i.set(r,{state:Yt.COMPLETE,segId:void 0});this.levelMap.set(r,i)}}totalLevels(){return this.levelMap.size}hasWithId(e,t,r,i=Yt.ANY){if(t<0)return!1;const n=this._createOrGetSet(t).get(e);return!!n&&((!r||!n.segId||n.segId===r)&&(i===Yt.ANY||n.state===i))}has(e,t,r=Yt.ANY){return this.hasWithId(e,t,void 0,r)}hasCompleteOr(e,t,r=Yt.COMPLETE){const i=this._createOrGetSet(t).get(e);return!!i&&(i.state===Yt.COMPLETE||i.state===r)}getObj(e,t){let r=this._createOrGetSet(t).get(e);return r||(r={}),r}getSegId(e,t){return this.getObj(e,t).segId}getState(e,t){return this.getObj(e,t).state}delete(e,t){return this._createOrGetSet(t).delete(e)}add(e,t,r,i){if("number"!=typeof(n=e)||n%1!=0)return;var n;this._createOrGetSet(t).set(e,{state:i,segId:r}),this.isLive&&this._trimBitset(e)}array(e){const t=this._createOrGetSet(e);return this._keysForStateComplete(t)}allArray(){let e={};return this.levelMap.forEach(((t,r)=>{e[r]=this._keysForStateComplete(t)})),e}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetSet(e).size}_createOrGetSet(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}_trimBitset(e){const t=e-20;t>0&&this.levelMap.forEach((e=>{e.delete(t)}))}_keysForStateComplete(e){const t=[];for(let[r,i]of e)i.state===Yt.COMPLETE&&t.push(r);return t}}class Zt{constructor(){this.levelMap=new Map}totalLevels(){return this.levelMap.size}has(e,t){return this._createOrGetMap(t).has(e)}delete(e,t){return this._createOrGetMap(t).delete(e)}decre(e,t){const r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);1===t?r.delete(e):r.set(e,t-1)}}incre(e,t){const r=this._createOrGetMap(t);if(r.has(e)){let t=r.get(e);r.set(e,t+1)}else r.set(e,1)}clear(){this.levelMap.forEach((e=>{e.clear()}))}size(e){return this._createOrGetMap(e).size}_createOrGetMap(e){"number"!=typeof e&&(e=Number(e));let t=this.levelMap.get(e);return t||(t=new Map,this.levelMap.set(e,t)),t}}const er=class{constructor(){this.peerMap=new Map}isEmpty(){return 0===this.peerMap.size}size(){return this.peerMap.size}clear(){this.peerMap.clear()}getPeers(){return[...this.peerMap.values()]}getPeerValues(){return this.peerMap.values()}hasPeer(e){return this.peerMap.has(e)}addPeer(e,t){this.peerMap.set(e,t)}getPeerIds(){return[...this.peerMap.keys()]}removePeer(e){this.peerMap.delete(e)}getPeersOrderByWeight(){const e=this.getAvailablePeers();return e.sort(((e,t)=>0===t.weight?1:0===e.weight?-1:t.weight-e.weight)),e}getPeer(e){return this.peerMap.get(e)}getAvailablePeers(){return this.getPeers().filter((e=>e.isAvailableUrgently))}},tr=Symbol("shareOnly");class rr extends(s()){constructor(e,t){super(),this.engine=e,this.config=t,this.logger=e.logger,this.bufMgr=null,this.peerManager=new er,this.fragLoading=!1,this._setupEngine&&this._setupEngine(),this.startCheckConnsTimer(),this.dcDownloadTimeout=t.dcDownloadTimeout,this[tr]=!1,this.downloadOnly=!1,this.loadedPeerNum=0,this.minConns=5}get isMobileNet(){return this.engine.isMobileNet}startCheckConnsTimer(){this.checkConnsTimer=setInterval((()=>{this.logger.info("start check conns");const e=this.getStatsForPeer();let t=this.peersNum;const r=g();this.getPeers().forEach((i=>{t>this.minConns+1&&(r-i.dataExchangeTs>120||r-i.gotStatsTs>=83)?(this.logger.warn(`close dead peer ${i.remotePeerId} level ${i.currentLevel}`),i.close(!1),t--):i.connected&&i.sendMsgStats(t,e)}))}),4e4)}get httpRangeSupported(){return this.config.httpRangeSupported}getStatsForPeer(){return{}}_handlePieceAborted(){}requestPeers(){const e=g();let t=0;for(let r of this.getPeers())r.mobileNet||r.super||(e-r.gotPeersTS<60?this.logger.warn(`${r.remotePeerId} just got peers, ignored`):(r.sendPeersRequest(),r.gotPeersTS=e,t++));return t}chokePeerRequest(t){const r={event:e.DC_CHOKE};t?t.sendJson(r):this._broadcastToPeers(r)}unchokePeerRequest(t){const r={event:e.DC_UNCHOKE};t?t.sendJson(r):this._broadcastToPeers(r)}stopRequestFromPeers(){for(let e of this.getPeers())e.choked=!0}resumeRequestFromPeers(){for(let e of this.getPeers())e.choked=!1}setShareOnly(){this[tr]=!0}deletePeer(e){e.downloading&&this._handlePieceAborted(e.remotePeerId),this.peerManager.hasPeer(e.remotePeerId)&&this.peerManager.removePeer(e.remotePeerId),this._peersStats(this.peerManager.getPeerIds())}getPeers(){return[...this.peerManager.getPeerValues()]}addPeer(e){const{logger:t}=this;this.peerManager.addPeer(e.remotePeerId,e),this[tr]&&(e.choked=!0);const r=this.peerManager.getPeerIds();this._peersStats(r);const{asn:i,country:n}=e.region||{};t.info(`add peer ${e.remotePeerId} country ${n||""} asn ${i||""}, now has ${r.length} peers`)}hasPeer(e){return this.peerManager.hasPeer(e)}get hasPeers(){return this.peersNum>0}get peersNum(){return this.peerManager.size()}get hasIdlePeers(){const{logger:e}=this,t=this.getIdlePeer().length;if(e.info(`peers: ${this.peersNum} idle peers: ${t}`),te.downloading));e.warn(`downloading: ${r.length} choked: ${t.filter((e=>e.choked)).length}`);for(let t of r)e.warn(`${t.remotePeerId} loading ${t.segId} remains ${t.remainAttachments} total ${t.pieceMsg.attachments}`)}return t>0}getIdlePeer(){return this.peerManager.getAvailablePeers()}set bufferManager(t){this.bufMgr=t,t.on(e.BM_LOST,(({sn:e,segId:t,next:r,level:i})=>{this._broadcastLost(e,t,i),this.onBufferManagerLost(e,t,r,i)})).on(e.BM_SEG_ADDED,(e=>{this.onBufferManagerSegAdded(e)}))}onBufferManagerSegAdded(e){}_broadcastLost(t,r,i,n){this.config.live||this._broadcastToPeers({event:e.DC_LOST,sn:t,seg_id:r||void 0,level:i},n)}destroy(){const{logger:e}=this;this.peersNum>0&&this.peerManager.clear(),this.removeAllListeners(),clearInterval(this.checkConnsTimer),clearTimeout(this.checkTimer),e.warn("destroy BtScheduler")}notifyPeersLoaded(e){}_setupDC(t){const{logger:r}=this;t.on(e.DC_PIECE_ACK,(e=>{e.size&&(this.engine.fetcher.reportUploaded(e.size),r.info(`uploaded ${e.seg_id} size ${e.size} to ${t.remotePeerId}`))})).on(e.DC_PIECE_ABORT,(e=>{r.warn(`peer ${t.remotePeerId} download aborted, reason ${e.reason}`),this._handlePieceAborted(t.remotePeerId),this.config.live&&this.checkPeers&&this.checkPeers()})).on(e.DC_DISCONNECT,(()=>{this.peersNum>=this.minConns&&(this.logger.warn(`close disconnected peer ${t.remotePeerId}`),t.close(!1))}))}_broadcastToPeers(e,t){for(let r of this.getPeers())t&&r===t||r.sendJson(e)}_peersStats(e){this.engine.emitEvent("peers",e);const t=this.engine.config.getPeersInfo;A(t)&&t(e)}startCheckPeersTimer(){this.logger.info("startCheckPeersTimer");const e=()=>{this.checkPeers();const t=1e3*(0===(r=this.loadedPeerNum)?3:.5*r+1.67);var r;this.loadedPeerNum=0,this.checkTimer=setTimeout(e,t)};this.checkTimer=setTimeout(e,15e3)}removeStreamListener(e,t){const r=this.requestingMap.get(e);if(r)return void r.removeStreamListener(t);const i=this.segmentBuilderMap.get(e);i&&i.removeStreamListener(t)}setTargetPeersFromGroup(e,t,r,i){if(e.hasReversePeer){if((r=t.concat(r)).length>0)return this.targetPeers.forwardPeer=r[0],!0}else if(e.hasForwardPeer&&(i=t.concat(i)).length>0)return this.targetPeers.reversePeer=i[0],!0;return t.length>0?(e.hasForwardBuffer?this.targetPeers.reversePeer=t[0]:this.targetPeers.forwardPeer=t[0],!0):(this.targetPeers=I(t,r,i),this.targetPeers.some((e=>!!e)))}}const ir=rr;class nr extends(s()){constructor(){super(),this.internalMap=new Map}has(e){return this.internalMap.has(e)}set(e,t){this.internalMap.set(e,t),S(this.internalMap,13,(e=>{e&&e.destroy()}))}get(e){return this.internalMap.get(e)}delete(e){const t=this.internalMap.get(e);t&&(t.destroy(),this.internalMap.delete(e))}get size(){return this.internalMap.size}clear(){this.internalMap.clear(),this.removeAllListeners()}}const sr=0,ar=1,or=2,lr=3;class hr extends(s()){constructor(){super(),this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.timeout=0,this.withCredentials=!1,this.status=0,this.readyState=this.UNSENT,this.headers=new Map,this.responseHeaders=null,this.on("load",(e=>{this.onload&&this.onload(e)})),this.on("abort",(e=>{this.onabort&&this.onabort(e)})),this.on("error",(e=>{this.onerror&&this.onerror(e)})),this.on("loadstart",(e=>{this.onloadstart&&this.onloadstart(e)})),this.on("progress",(e=>{this.onprogress&&this.onprogress(e)})),this.on("timeout",(e=>{this.ontimeout&&this.ontimeout(e)})),this.on("loadend",(e=>{this.onloadend&&this.onloadend(e)})),this.on("readystatechange",(()=>{this.onreadystatechange&&this.onreadystatechange()}))}setRequestHeader(e,t){this.headers.set(e,t)}addEventListener(e,t){this.addListener(e,t)}removeEventListener(e,t){this.removeListener(e,t)}overrideMimeType(){}getAllResponseHeaders(){if(!this.responseHeaders)return null;let e="";return this.responseHeaders.forEach(((t,r)=>{e+=`${r}: ${t}\n`})),e}getResponseHeader(e){return this.responseHeaders?this.responseHeaders.get(e):null}open(){this.readyState=this.OPENED,this.emit("loadstart")}abort(){this.readyState=this.DONE,this.status=0,this.emit("loadend")}send(){}_emitEvent(e){this.emit(e,{type:e,target:this})}}function ur(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}class dr{constructor(e){this.fetchSetup=e.fetchSetup||cr,this.xhrSetup=e.xhrSetup,function(e){try{new e}catch(e){return!1}return!0}(self.AbortController)&&(this.controller=new self.AbortController),this.stats=C(),this.packetSize=u,this.fakeXhr=new hr}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;e&&e.ok||(this.stats.aborted=!0,this.callbacks&&this.callbacks.onUpdate&&this.callbacks.onUpdate(void 0,!1,!0),this.controller&&this.controller.abort())}abort(){this.abortInternal(),this.callbacks&&this.callbacks.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const i=this.stats;i.trequest=i.loading.start=performance.now();let n=function(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Object.assign({},e.headers))};e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return r}(e,this.controller?this.controller.signal:void 0);const s="arraybuffer"===e.responseType,a=s?"byteLength":"length",o=r.onUpdate,l=r.onBodyStart;this.context=e,this.config=t,this.callbacks=r,this.xhrSetup&&(this.xhrSetup(this.fakeXhr,e.url),n=function(e,t){e.withCredentials&&(t.credentials="include");for(let[r,i]of e.headers)t.headers.set(r,i);return t}(this.fakeXhr,n)),this.request=this.fetchSetup(e,n),clearTimeout(this.requestTimeout),this.requestTimeout=setTimeout((()=>{this.abortInternal(),this.fakeXhr._emitEvent("timeout"),this.fakeXhr._emitEvent("loadend"),r.onTimeout&&r.onTimeout(i,e,this.response)}),this.fakeXhr.timeout||t.timeout);const h="then"in(u=this.request)&&u.then instanceof Function?this.request.then(self.fetch):self.fetch(this.request);var u;const{fakeXhr:d}=this;d.readyState=d.OPENED,d.emit("readystatechange"),d._emitEvent("loadstart"),h.then((t=>{if(this.response=this.loader=t,!t.ok){const{status:e,statusText:i}=t,n=i||"fetch, bad network response";throw r.onError&&r.onError({text:n}),new fr(n,e,t)}i.tfirst=i.loading.first=Math.max(performance.now(),i.loading.start),i.total=parseInt(t.headers.get("Content-Length")||"0");let n=0;try{const e=t.headers.get("Content-Range").split("/");2===e.length&&(n=parseInt(e[1],10))}catch(e){}const{fakeXhr:a}=this;return a.readyState=a.HEADERS_RECEIVED,a.responseHeaders=t.headers,a.emit("readystatechange"),o&&"0"!==i.total?(l&&l(i.total,n),this.loadProgressively(t,i,e,o)):(a.emit("progress",new ProgressEvent("progress",{lengthComputable:!1})),s?t.arrayBuffer():t.text())})).then((t=>{const{response:n}=this;clearTimeout(this.requestTimeout),i.tload=i.loading.end=Math.max(performance.now(),i.loading.first),i.loaded=i.total=t[a];const s={url:n.url,data:t};r.onProgress&&r.onProgress(i,e,t,n),r.onSuccess&&r.onSuccess(s,i,e,n)})).catch((t=>{if(clearTimeout(this.requestTimeout),i.aborted)return;const n=t&&t.code||0,s=t?t.message:null;r.onError&&r.onError({code:n,text:s},e,t?t.details:null)}))}loadProgressively(e,t,r,i){const n=e.body.getReader();let s=0,o=0,l=(0,a.h)(0),h=!1;const d=()=>n.read().then((({value:r,done:n})=>{const{fakeXhr:c}=this;if(c.readyState!==c.LOADING&&(c.readyState=c.LOADING,c.emit("readystatechange")),r&&(s+=r.length),n){if(l.byteLength>0)if(s<=this.packetSize){const e=(0,a.h)(s);l.copy(e,0,o*this.packetSize,l.byteLength),i(e,!0)}else{const e=function(e,t){const r=e.byteLength-t,i=[];let n=t,s=Math.floor(r/u),o=r%u;for(let t=0;t0){const t=(0,a.h)(o);e.copy(t,0,n,n+o),i.push(t)}return i}(l,o*this.packetSize);for(let t=0;t=this.packetSize){s-=this.packetSize;const e=(0,a.h)(this.packetSize);l.copy(e,0,o*this.packetSize,(o+1)*this.packetSize),o++,i(e,!1)}return d()})).catch((()=>(this.fakeXhr._emitEvent("abort"),this.fakeXhr._emitEvent("loadend"),Promise.reject())));return d()}}function cr(e,t){return new self.Request(e.url,t)}class fr extends Error{constructor(e,t,r){super(e),this.code=t,this.details=r}}class gr extends(s()){constructor(e,t,r=!1){super(),this.coordinator=e,this.logger=t,this.rangeSupported=r,this.rangeStart=0,this.rangeEnd=0,this.httpLoadTime=2e3,this.proxied=!1,this.forwardPeer=null,this.reversePeer=null,this.bufArr=[],this.forwardBufList=[],this.reverseBufList=[],this.forwardOffset=-1,this.reverseOffset=1e4,this.timeStart=0,this.timeReceivePiece=0,this.destroyed=!1,this.forwardStreamListeners=[],this.reverseStreamListeners=[],this.rangeRequesting=!1,this.waitingRemain=!1,this.httpLoaded=0,this.p2pLoaded=0,this.deadline=0,this.forwardCanceled=!1,this.reverseCanceled=!1,this.firstReceived=!1}get isDownloading(){return this.timeReceivePiece>0}get isAlmostDeadline(){if(this.rangeRequesting)return!0;if(this.isEmpty)return!1;if(0===this.deadline)return!0;const e=this.deadline-performance.now();return e<=0||(this.p2pSpeed>3*this.minRequiredSpeed(e)||e<500)}hasPeer(e){return!!e&&(e===this.forwardPeer||e===this.reversePeer)}get streamListeners(){return[...this.reverseStreamListeners,...this.forwardStreamListeners].length}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg,r=[...this.reverseStreamListeners,...this.forwardStreamListeners];for(let i of r){const{handler:r}=i;r(e,t,!0,"aborted by synthesizer")}this._resetStreamListeners()}_resetStreamListeners(){this.reverseStreamListeners.length=0,this.forwardStreamListeners.length=0}_notifyStreamListenersRemain(){if(this.forwardStreamListeners.length>0){for(let e=this.forwardOffset+1;e0){for(let e=this.reverseOffset-1;e>=0;e--)this._notifyStreamListeners(!0,this.bufArr[e],e);this.reverseStreamListeners=[]}}addStreamListener(e,t,r){(e?this.reverseStreamListeners:this.forwardStreamListeners).push({handler:r,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:r}=this.pieceMsg,i=i=>i.filter((i=>i.peerId!==e||(i.handler(t,r,!0,"aborted by cancel"),!1)));this.forwardStreamListeners=i(this.forwardStreamListeners),this.reverseStreamListeners=i(this.reverseStreamListeners)}setTimeout(e=0,t=!1){this.logger.info(`syn setTimeout ${e}`);let r=performance.now();e<=0?setTimeout((()=>{this._handleTimeout(!1,!1)}),0):(this.firstPieceTimer=setTimeout((()=>{if(this.firstReceived)return;const e=()=>{this.logger.warn(`switch to http, firstReceived ${this.firstReceived}`),this._handleTimeout(!1)};if(this.timeReceivePiece>0){const t=(this.timeReceivePiece-r)/2;t>0?this.firstPieceTimer=setTimeout((()=>{this.firstReceived&&!this._shouldSwitch()||e()}),t):e()}else e()}),e/2),this.deadline=r+e,this._startTimer(e,t))}setExtra(e={}){e.url&&(this.url=e.url),e.rangeStart&&(this.rangeStart=e.rangeStart),e.rangeEnd&&(this.rangeEnd=e.rangeEnd),e.httpLoadTime&&(this.httpLoadTime=e.httpLoadTime),e.proxied&&(this.proxied=!0),e.xhrSetup&&(this.xhrSetup=e.xhrSetup),e.headers&&(this.headers=e.headers),e.segId&&!this.pieceMsg.seg_id&&(this.pieceMsg.seg_id=e.segId)}get hasForwardPeer(){return!!this.forwardPeer}get hasReversePeer(){return!!this.reversePeer}hasPeerId(e){return this.forwardPeer&&this.forwardPeer.remotePeerId===e||this.reversePeer&&this.reversePeer.remotePeerId===e}get isEmpty(){return null===this.forwardPeer&&null===this.reversePeer}get isFull(){return this.forwardPeer&&this.reversePeer}setForwardPeer(e){this.forwardPeer=e,this.reversePeer&&this._print(),this._setupPeer(e,!1)}setReversePeer(e){this.reversePeer=e,this.forwardPeer&&this._print(),this._setupPeer(e,!0)}setPeer(e,t){t?this.setReversePeer(e):this.setForwardPeer(e)}deletePeer(e){const t=e===this.reversePeer;this._detachPeer(e),t?this.reversePeer=null:this.forwardPeer=null,(this.isEmpty||this.deadline>0)&&this._handleTimeout(!1,!1)}terminate(){this._handleTimeout(!1,!1)}get hasPartialBuffer(){return this.hasForwardBuffer||this.hasReverseBuffer}get hasForwardBuffer(){return this.forwardOffset>=0}get hasReverseBuffer(){return this.pieceMsg&&this.reverseOffset=this.pieceMsg.attachments-1}get isReverseBufferFull(){return this.reverseOffset<=0}_cancelP2p(e=!1){const{seg_id:t,sn:r,level:i}=this.pieceMsg;!this.forwardPeer||this.isForwardBufferFull||this.forwardCanceled||(this.forwardPeer.cancelDownload(r,i,t),this.forwardCanceled=!0),e||!this.reversePeer||this.isReverseBufferFull||this.reverseCanceled||(this.reversePeer.cancelDownload(r,i,t),this.reverseCanceled=!0)}detachPeers(){this._detachPeer(this.forwardPeer),this._detachPeer(this.reversePeer)}destroy(){clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._notifyStreamListenersAbort(),this._cancelP2p(),this.removeAllListeners(),this.destroyed=!0,this._detachPeer(this.forwardPeer),this.forwardPeer=null,this.forwardOffset=-1,this._detachPeer(this.reversePeer),this.reversePeer=null,this.reverseOffset=1e4,this.bufArr=[],this.forwardStreamListeners=[],this.reverseStreamListeners=[],this.httpLoader&&(this.logger.warn("abort syn httpLoader"),this.httpLoader.abort())}_detachPeer(t){if(!t)return;const r=t===this.reversePeer?this.reverseEvents:this.forwardEvents;r&&r&&t.off(e.DC_PIECE_DATA,r.onPieceData).off(e.DC_PIECE,r.onPiece).off(e.DC_PIECE_NOT_FOUND,r.onPieceNotFound).off(e.DC_PIECE_ABORT,r.onPieceAbort)}_receivePacket(t,r,i,n=!0){const{seg_id:s,sn:o,level:l,size:h,attachments:u}=this.pieceMsg,d=r-1;if(this.bufArr[d]?(this.logger.warn(`syn bufArr ${s} already has ${d} size ${i.byteLength}`),this.bufArr[d]=i):(n?this.p2pLoaded+=i.byteLength:this.httpLoaded+=i.byteLength,this.emit(e.SYN_PROGRESS,{total:h,loaded:this.p2pLoaded+this.httpLoaded,first:!this.firstReceived,segId:s,sn:o}),this.firstReceived=!0,this.bufArr[d]=i,t?this.reverseOffset=d:this.forwardOffset=d,this._notifyStreamListeners(t,i,d)),this.forwardOffset!==this.reverseOffset-1)return!0;this.rangeRequesting||(this.forwardPeer&&(this.forwardPeer.miss=0),this.reversePeer&&(this.reversePeer.miss=0)),clearTimeout(this.timer),this._notifyStreamListenersRemain();const c=h/(performance.now()-this.timeStart);let f=a.h.concat(this.bufArr);const g=f.byteLength;if(g===h){let t=f.buffer;const r=new z(o,s,t,this.getFromPeerId(),l,this.pieceMsg.ext);this.emit(e.SYN_OUTPUT,r,{speed:c,p2p:this.p2pLoaded,http:this.httpLoaded})}else{this.logger.error(`${s} expectedSize ${h} != byteLength ${g} forward ${this.forwardOffset} reverse ${this.reverseOffset}`);for(let e=0;e{t&&t.emit(e.DC_ERROR,!0)}))}_setupPeer(t,r){const{logger:i}=this;0===this.timeStart&&(this.timeStart=performance.now());const n=(r,n,s,a,o,l)=>{if(this.destroyed)return;if(!this._validateMsg(r,l.level,n))return void i.error(`onPieceData ${n||r} not match ${JSON.stringify(this.pieceMsg)} from ${t.remotePeerId}`);if(a0&&this._shouldSwitch()&&(i.warn("should switch to http"),clearTimeout(this.timer),clearTimeout(this.firstPieceTimer),this._handleTimeout(!1,!1))},s=e=>{if(this.destroyed)return;const{attachments:r,size:n,sn:s,level:a,seg_id:o,ext:l}=e;return n&&this._validateMsg(s,a,o)?this.pieceMsg.size&&n!==this.pieceMsg.size?(i.warn(`onPiece ${o} size not match`),t.cancelDownload(s,a,o),void this.deletePeer(t)):void(0===this.bufArr.length&&(this.pieceMsg={...this.pieceMsg,seg_id:o,size:n,attachments:r,ext:l},this.reverseOffset=r,this.bufArr=new Array(r),this.timeReceivePiece=performance.now())):(i.warn(`onPiece ${JSON.stringify(e)} not match ${JSON.stringify(this.pieceMsg)}`),t.cancelDownload(s,a,o),void this.deletePeer(t))},a=e=>{this.destroyed||this.deletePeer(t)},o=()=>{this.destroyed||this.deletePeer(t)},l={onPieceData:n,onPiece:s,onPieceNotFound:a,onPieceAbort:o};r?this.reverseEvents=l:this.forwardEvents=l,t.on(e.DC_PIECE_DATA,n).once(e.DC_PIECE,s).once(e.DC_PIECE_NOT_FOUND,a).once(e.DC_PIECE_ABORT,o)}_shouldSwitch(){const e=u,t=this.pieceMsg.size-e*this.loadedPackets;return this.coordinator.shouldSwitchToHttp(t,this.deadline,this.p2pSpeed,e,this.httpLoadTime)}_startTimer(e,t=!0){this.timer=setTimeout(this._handleTimeout.bind(this,t),e)}get loadedPackets(){return this.pieceMsg.attachments-(this.reverseOffset-this.forwardOffset-1)}_handleTimeout(t=!1,r=!0){if(this.destroyed||this.rangeRequesting)return;const{seg_id:i,size:n,attachments:s}=this.pieceMsg;if(!n||0===this.timeReceivePiece)return this.logger.warn(`syn load timeout ${i} url ${this.url}`),void this.emit(e.SYN_ERROR,this.pieceMsg,sr);if(t&&this.timeReceivePiece>0&&s){this.logger.warn(`syn ${this.loadedPackets} of ${s} packets loaded`);const e=this.httpLoadTime>3e3?3e3:this.httpLoadTime;if(this.shouldWaitForRemain(e))return this.waitingRemain=!0,this.logger.info(`syn wait for remain ${e}`),void this._startTimer(e,!1)}if(r){const e=[this.forwardPeer,this.reversePeer].filter((e=>!!e)).sort(((e,t)=>{const r=e.currentLoadSpeed(),i=t.currentLoadSpeed();return r===i?e.timeSendRequest-t.timeSendRequest:r-i})).shift();e&&e.loadtimeout()}if(this.rangeSupported&&this.url&&(this.hasPartialBuffer||this.hasReversePeer))return this._cancelP2p(!0),this._loadRemainBufferByHttp();this._notifyStreamListenersAbort(),this.emit(e.SYN_ERROR,this.pieceMsg,lr)}shouldWaitForRemain(e){return!this.isEmpty&&this.shouldWaitForRemainUrgent(e)}shouldWaitForRemainUrgent(e){if(0===this.timeReceivePiece||e<=0)return!1;const t=this.p2pSpeed,r=this.minRequiredSpeed(e);return this.logger.info(`syn remainTime ${e} speed ${t} required ${r}`),t>=r}minRequiredSpeed(e){let t=0;return[this.forwardPeer,this.reversePeer].forEach((e=>{e&&(t+=e.loadedBytes())})),(this.pieceMsg.size-t)/e}get p2pSpeed(){let e=0;return[this.forwardPeer,this.reversePeer].forEach((t=>{t&&(e+=t.currentLoadSpeed())})),e}getFromPeerId(){const{forwardPeer:e,reversePeer:t}=this;return this.isFull&&e!==t?`${e.remotePeerId}:${t.remotePeerId}`:e?`${e.remotePeerId}`:t?`${t.remotePeerId}`:""}getStreamInfo(e){const t=e?this.reverseBufList:this.forwardBufList;let r,i;return t.length0?this.rangeEnd-1:0;let s=this.forwardOffset;const a=performance.now();this.rangeRequesting=!0;let o=ge(s,this.reverseOffset,t,this.rangeStart,n);const l=o.rangeEnd-o.rangeStart;i.info(`listeners ${this.streamListeners} continue download ${r} from ${this.url} range: ${o.rangeStart}-${o.rangeEnd}`),this.hasPartialBuffer||(o={});const u=new dr({xhrSetup:this.xhrSetup});this.httpLoader=u;let d={url:this.proxied?f(this.url,h,!0):this.url,...o};let c,g=s+1;const p={onUpdate:(t,r,n)=>{if(!this.destroyed){if(n)return i.warn("httpLoader aborted"),void this.emit(e.SYN_ERROR,this.pieceMsg,ar);if(r){const e=c/(performance.now()-a);this.coordinator.addHttpSpeed(e),this.httpLoader=void 0}this.bufArr[g]||this._receivePacket(!1,g+1,t,!1),g++}},onBodyStart:(t,n)=>{if(0===n&&i.warn(`range request fileSize ${n}`),this.destroyed)return;const{size:s}=this.pieceMsg;if(c=t,t!==s||0!==n&&n!==s){let r=!1;n>0&&n!==s?(i.error(`onBodyStart fileSize ${n} != ${s}`),r=!0):t!==l&&(i.error(`onBodyStart size ${t} != expectedSize ${l}`),r=!0),r&&this.emit(e.SYN_ERROR,this.pieceMsg,ar)}else i.warn(`syn range request ${r} resp whole ts`),g=0},onError:t=>{this.destroyed||(i.error(`httpLoader error ${t.text}`),this.emit(e.SYN_ERROR,this.pieceMsg,ar))},onTimeout:()=>{this.destroyed||(i.warn("httpLoader timeout"),this.emit(e.SYN_ERROR,this.pieceMsg,or))}};u.load(d,{timeout:15e3},p)}_print(){const{seg_id:e,sn:t}=this.pieceMsg;this.logger.info(`syn parallel loading ${e||t}`)}}class pr extends gr{constructor(e,r,i,n,s,a=!1,o){super(e,r,a,o),this.pieceMsg={event:t.DC_PIECE,sn:i,level:n,seg_id:s},o&&this.setExtra(o)}get segId(){return this.pieceMsg.seg_id}_notifyStreamListeners(e,t,r){const{sn:i,seg_id:n,attachments:s}=this.pieceMsg,a=e&&0===r||!e&&r===s-1,o=e?this.reverseStreamListeners:this.forwardStreamListeners;e?this.reverseBufList.push(t):this.forwardBufList.push(t),a&&(this.forwardBufList.push([...this.reverseBufList].reverse()),this.reverseBufList.push([...this.forwardBufList].reverse()));for(let e of o){const{handler:r}=e;r(i,n,!1,t,a)}a&&this._resetStreamListeners()}_validateMsg(e,t,r){return(!this.pieceMsg.seg_id||r===this.pieceMsg.seg_id)&&(e===this.pieceMsg.sn&&t===this.pieceMsg.level)}}class mr{constructor(){this.meanHttpSpeed=0}addHttpSpeed(e){this.meanHttpSpeed=.4*this.meanHttpSpeed+.6*e}shouldSwitchToHttp(e,t,r,i,n){if(this.meanHttpSpeed<=0)return!1;if(r>=this.meanHttpSpeed)return!1;if(this.meanHttpSpeed*n>=e)return!1;return((n+t-performance.now())*this.meanHttpSpeed-e)/(this.meanHttpSpeed-r)*r{if(e.bitset&&t.sn>=0){const{sn:r,level:i,complete:n,seg_id:s}=t,a=n?Yt.COMPLETE:Yt.PARTIAL_FORWARD;e.bitset.add(r,i,s,a),this._receiveDCHave(r,i,s,e),e.isAvailableUrgently&&this._handleDCHave(e,r,i,s,a)}})).on(t.DC_HAVE_REVERSE,(t=>{if(e.bitset&&t.sn>=0){const{sn:r,level:i,seg_id:n}=t;e.bitset.hasCompleteOr(r,i,Yt.PARTIAL_REVERSE)||e.bitset.add(r,i,n,Yt.PARTIAL_REVERSE),this._receiveDCHave(r,i,n,e),e.isAvailableUrgently&&this._handleDCHave(e,r,i,n,Yt.PARTIAL_REVERSE)}})).on(t.DC_LOST,(t=>{if(!e.bitset)return;const{sn:r,level:i}=t;e.bitset.has(r,i)&&(e.bitset.delete(r,i),this.bitCounts.decre(r,i))})).on(t.DC_PIECE,(e=>{e.ext&&e.ext.incompletes>=7||this.notifyAllPeers(e.sn,e.level,e.seg_id,e.reverse?Yt.PARTIAL_REVERSE:Yt.PARTIAL_FORWARD)})).on(t.DC_PIECE_CANCEL,(t=>{const{sn:r,level:i}=t,n=ve(r,i);this.removeStreamListener(n,e.remotePeerId)})).on(t.DC_PIECE_NOT_FOUND,(t=>{const{sn:r,level:i}=t;e.bitset.delete(r,i),this.bitCounts.decre(r,i),e.checkIfNeedChoke(!0)})).on(t.DC_DISCONNECT,(()=>{this.cleanRequestingMap(e.remotePeerId)})).on(t.DC_REQUEST,(async t=>{const{logger:r}=this,{sn:i,level:n,reverse:s}=t;let a=t.seg_id;a||(a=await this.bufMgr.getSegIdBySN(i));const o=()=>{this.bitset.delete(i,n),e.sendPieceNotFound(i,a,{level:n}),this._broadcastLost(i,a,n,e)},l=await this.bufMgr.getSegById(a),h=ve(i,n),u=this.requestingMap.get(h);let d=!1;u&&u.isDownloading&&(d=!0);const c=this.segmentBuilderMap.get(h);if(l)if(r.info(`found seg ${a} from bufMgr`),l.level===n){let t="SegmentStore"===this.bufMgr.name?"Disk":"Cache";l.ext&&l.ext.from&&l.ext.from.length<2500&&(t=`${l.ext.from}-${t}`),e.sendBuffer(l.sn,l.segId,l.data,{from:t,level:l.level,reverse:s})}else o();else if(!s&&c)r.info(`peer request ${i} wait from builder, sent ${c.bufferList.length}`),w(e,c,c.pieceMsg,c.bufferList,c.source,1);else if(d){r.info(`syn had ${u.loadedPackets} packets, wait remain from upstream ${u.getFromPeerId()}`);const t={...u.pieceMsg,reverse:s},{from:i,incompletes:n,bufferList:a}=u.getStreamInfo(s);w(e,u,t,a,i,n)}else o()}))}handleMetaData(e,t){if(t.field){e.bitset=new Jt(this.config.live,t.field);for(let e in t.field){const r=Number(e);if(r<0)continue;t.field[r].forEach((e=>{this.bitset.has(e,r)||this.bitCounts.incre(e,r)}))}this.addPeer(e),this.downloadOnly&&this.chokePeerRequest(e)}}peersHas(e,t){return this.bitCounts.has(e,t)}deletePeer(e){if(this.peerManager.hasPeer(e.remotePeerId)&&e.bitset){const t=e.bitset.allArray();for(let e in t){const r=Number(e),i=t[r];i&&i.forEach((e=>{this.bitCounts.decre(e,r)}))}}this.cleanRequestingMap(e.remotePeerId),super.deletePeer(e)}hasAndSetTargetPeer(e,t,r,i){const{logger:n,config:s}=this;let a=1e3*(i-s.httpLoadTime);this.allowP2pLimit=s.httpLoadTime+1.5,n.info(`bufferedDuration ${1e3*i} remainLoadTime ${a} allowP2pLimit ${1e3*this.allowP2pLimit}`);const o=ve(e,t),l=this.requestingMap.get(o);if(l){const s=l.segId;if(s&&s!==r)return n.warn(`syn segId ${s} not match ${r}`),this.requestingMap.delete(o),this._searchAvailablePeers(e,t,r,i);if(!l.shouldWaitForRemain(a)){if(n.warn(`syn prefetch timeout at ${e}`),l.prefetchTimeout=!0,l.isFull)return this.httpRangeSupported;const i=this.peerManager.getPeersOrderByWeight();let[s,o,h]=Xt(i,e,t,r);return!!this.setTargetPeersFromGroup(l,s,o,h)||(l.hasReversePeer||l.hasPartialBuffer||a>1e3*(this.allowP2pLimit+1))&&this.httpRangeSupported}return n.info(`prefetch ${e} wait for remain`),!0}return this._searchAvailablePeers(e,t,r,i)}_searchAvailablePeers(e,t,r,i){if(i<=this.allowP2pLimit)return!1;if(!this.hasIdlePeers||!this.peersHas(e,t))return!1;const n=this.peerManager.getPeersOrderByWeight(),[s,a]=zt(n,e,t,r);return this.targetPeers={forwardPeer:s,reversePeer:a},[s,a].some((e=>!!e))}reportTraffic(e,t,r){const{fetcher:i}=this.engine;i&&(e>0&&i.reportFlow(e),t>0&&i.reportDCTraffic(t,r))}notifyAllPeers(e,t,r,i=Yt.COMPLETE){if(!r)return void this.logger.error("segId is required");if(this.downloadOnly)return;const{live:n}=this.config;if(this.bitset.has(e,t,i))return;const s=((e,t,r)=>`${e}-${t}-${r}`)(e,t,i);let a;i!==Yt.PARTIAL_REVERSE&&(a=i===Yt.COMPLETE);const o=this.requestingMap.get(ve(e,t));for(let l of this.getPeers())o&&o.hasPeer(l)||l.notifySet.has(s)||l.bitset.hasCompleteOr(e,t,i)||l.uploading||(l.sendMsgHave(e,r,{level:t,reverse:i===Yt.PARTIAL_REVERSE,complete:a}),l.notifySet.add(s),n&&T(l.notifySet,20))}checkPeers(){const{logger:e,config:t,engine:r}=this,i=this.requestingMap.size;if(i>5&&(e.warn(`requestingMap size ${i}`),i>9))return;if(!this.hasPeers)return;const n=t.live;if(this.fragLoading&&!n)return void e.warn("loading urgently, skip prefetch");const{currentLevel:s}=r;if(0===this.bitCounts.size(s))return;if(!n&&this.nextLostSN>=0&&this.nextLostSN>=this.currPlaySN-10)return;let a=this.peerManager.getPeersOrderByWeight();if(0===a.length)return;let o=0,{prefetchNum:l,endSN:h,startSN:u}=t;if(n&&(l=3),this.getBufferedDuration()=h&&!this.bufMgr.overflowed)c=u;else{const e=Math.min(...a.filter((e=>e.endSN>=c)).map((e=>e?e.startSN:1/0)));if(!isFinite(e))return;ch))&&!(n&&c>this.loadingSN+2);){if(this.bitset.has(c,s)){c++;continue}const t=ve(c,s);if(this.bitCounts.has(c,s)&&!this.requestingMap.has(t)){let r=[null,null];if(n)r=zt(a,c,s,void 0,!0);else for(let e of a)if(e.bitset.has(c,s)){const t=e.bitset.getState(c,s);let i;i=t===Yt.COMPLETE?0===p(0,1):t===Yt.PARTIAL_REVERSE,r[i?1:0]=e;break}if(r.some((e=>!!e))){const i=new pr(this.coordinator,this.logger,c,s,void 0,this.httpRangeSupported);this._setupSynthesizer(i),this.requestingMap.set(t,i),r.forEach(((t,r)=>{if(t&&o{for(let r of this.getPeers()){const i=r.getLatestPlaylist(e,t);if(i)return this.playlistInfo.set(e,i),this.gotPlaylist=!0,i}return null};let n=i();return!n&&this.gotPlaylist&&(this.logger.info("getPlaylist wait 240ms"),await m(240),this.gotPlaylist=!1,n=i()),n}getBufferedDuration(){const{config:e}=this;if(this.waitForPeer)return e.waitForPeerTimeout+e.httpLoadTime;let{media:t,currentSrc:r}=this.engine;if(!t||t.src!==r&&0===t.currentTime){if(this.logger.info("try get video element"),t=ce(this.config.mediaElem,r),!t)return 4;this.engine.media=t}let i=function(e){let t=0,r=e.currentTime,i=e.buffered;for(let e=i.length-1;e>=0;e--)if(r>=i.start(e)&&r<=i.end(e)){t=i.end(e)-r;break}return e.playbackRate&&(t/=e.playbackRate),t>0?t:0}(t);return i}destroy(){super.destroy(),this.requestingMap.clear(),this.segmentBuilderMap.clear(),this.engine.removeAllListeners(t.MEDIA_REBUFFER)}clearCache(){"SegmentStore"===this.bufMgr.name?this.engine.emit(t.BM_FATAL_ERROR):this.bufMgr.clear(),this.bitset.clear()}_handleSynOutput(e,t,r,i){this.logger.info(`syn output ${e} http ${t} p2p ${r}`)}_handleSynError(e,t,r,i){const{logger:n,config:s}=this;n.warn(`SYN_ERROR ${t}-${r} code ${i}`),i!==sr&&e.hasPartialBuffer&&r>this.loadingSN?n.warn(`syn abort ${r} with partial buffer`):this.requestingMap.delete(ve(r,t)),s.live&&this.checkPeers()}_notifySynthesizer(e,t,r,i,n,s=!0){const{logger:a}=this,o=this.requestingMap.get(ve(r,i));if(!o)return;const l=o.segId;function h(n,s){s?e.requestDataById(t,r,!0,{level:i,reverse:n}):e.requestDataBySN(r,!1,{level:i,reverse:n})}function u(){return n===Yt.PARTIAL_FORWARD||n===Yt.COMPLETE}function d(){return n===Yt.PARTIAL_REVERSE||n===Yt.COMPLETE}t&&l&&t!==l?a.warn(`notifySynthesizer segId ${t} not match ${l}`):o.isFull||!this.prefetchOnly&&o.isAlmostDeadline||(o.isEmpty?o.hasForwardBuffer&&d()?(o.setReversePeer(e),h(!0,s)):o.hasReverseBuffer&&u()&&(o.setForwardPeer(e),h(!1,s)):!o.hasForwardPeer&&u()?(o.setForwardPeer(e),h(!1,s)):!o.hasReversePeer&&d()&&(o.setReversePeer(e),h(!0,s)))}_setupEngine(){this.engine.on(t.MEDIA_REBUFFER,(e=>{const{prefetchOnly:t,live:r}=this.config;t||r||(e&&!this.prefetchOnly&&this.logger.warn("rebuffer reach limit"),this.prefetchOnly=e)}))}getStatsForPeer(){const{currentLevel:e,media:t}=this.engine,r={level:e};if(t&&!this.config.live){const{currentTime:e}=t;r.pos=Math.round(e)}return r}checkSynthesizer(e,t){const r=ve(e,t),i=this.requestingMap.get(r);i&&(0===i.streamListeners?(this.logger.info(`destroy syn ${r} without listeners`),this.requestingMap.delete(r)):this.logger.info(`keep syn ${r} with listeners`))}setupSynForLoad(e,t,r,i,n){const{forwardPeer:s,reversePeer:a}=this.targetPeers,o=ve(e,t);let l=this.requestingMap.get(o);if(l?l.setExtra(i):(l=new pr(this.coordinator,this.logger,e,t,r,this.httpRangeSupported,i),this._setupSynthesizer(l),this.requestingMap.set(o,l)),l.prefetchTimeout&&n<1e3*this.allowP2pLimit&&!s&&!a)return l.setTimeout(0);let h=!1;n>700&&(s&&(l.setForwardPeer(s),s.requestDataById(r,e,!0,{level:t}),h=!0),a&&(l.setReversePeer(a),a.requestDataById(r,e,!0,{level:t,reverse:!0}),h=!0)),l.setTimeout(l.isEmpty?0:n,h)}}class yr{constructor(t,r,i,n){this.bufferList=[],this.streamListeners=[],this.finished=!1,this.packetSize=u,this.attachments=n%this.packetSize==0?n/this.packetSize:Math.floor(n/this.packetSize)+1,this.pieceMsg={event:e.DC_PIECE,attachments:this.attachments,seg_id:i,sn:t,level:r,size:n,reverse:!1},this.sink=(0,a.h)(0),this.source="HttpStream"}receiveBytes(e,t){e.byteLength&&(this.sink=a.h.concat([this.sink,e]),this.bufferList.push(e),t&&(this.finished=!0),this._notifyStreamListeners(e))}getCompleteBuffer(){return this.sink.buffer}destroy(){this.finished||this._notifyStreamListenersAbort()}addStreamListener(e,t,r){this.streamListeners.push({handler:r,peerId:t})}removeStreamListener(e){const{sn:t,seg_id:r}=this.pieceMsg;this.streamListeners=this.streamListeners.filter((i=>i.peerId!==e||(i.handler(t,r,!0,"aborted by cancel"),!1)))}_notifyStreamListenersAbort(){const{sn:e,seg_id:t}=this.pieceMsg;for(let r of this.streamListeners){const{handler:i}=r;i(e,t,!0,"aborted by httpLoader")}this.streamListeners.length=0}_notifyStreamListeners(e){const{sn:t,seg_id:r}=this.pieceMsg;for(let i of this.streamListeners){const{handler:n}=i;n(t,r,!1,e,this.finished)}this.finished&&(this.streamListeners.length=0)}}const Er=class extends vr{constructor(e,t){super(e,t),this.fragloadTimeout=e.hlsjs?10:6.8,this.resolveMap=new Map,this.segmentBypass=A(t.segmentBypass)?t.segmentBypass:()=>!1,!0===this.config.httpStreamEnabled?this.streamEnabled=ur():this.streamEnabled=!1}async handleGetMediaData(e,r){const{logger:i,engine:n,config:s}=this;let{url:a,range:o}=e;const l=this._getFrag(a,o);if(!l)return i.warn(`cannot get frag ${a}`),r.postMessage({action:t.SW_GET_MEDIA});if(n.segmentLoadCount++,this.segmentBypass(a,l.tagList)||n.segmentLoadCountthis.fragloadTimeout&&(g=this.fragloadTimeout),i.info(`handleGetMediaData sn ${h} bufferedDuration ${g}`);let p=1e3*(g-this.config.httpLoadTime);p<0?p=0:p>4e3&&(p=4e3);const m=ve(h,u);if(this.resolveMap.has(h)||c){let e=this.requestingMap.get(m);if(e||c){e&&this.httpRangeSupported&&(i.warn(`${h} is requesting, terminate syn wait for seg`),e.terminate());let n=setTimeout((()=>{i.info(`notify seg ${h} timeout`),n=-1,r.postMessage({action:t.SW_GET_MEDIA})}),p);this.bufMgr.once(`${t.BM_ADDED_SN_}${h}`,(e=>{n<0||e&&e.level===u&&(clearTimeout(n),i.info(`notify seg ${e.sn}`),r.postMessage({action:t.SW_GET_MEDIA,data:{url:a,buffer:e.data}}))}))}else i.warn(`${h} is requesting, fallback`),r.postMessage({action:t.SW_GET_MEDIA})}else if(this.hasAndSetTargetPeer(h,u,d,g)){await this._loadFragByP2p(l,r,h,d,a,u,o,p)||(i.warn(`p2p timeout switch to http load ${d}`),this._loadFragByHttp(l,r,h,d,a,u,o,1e3*this.fragloadTimeout))}else this._loadFragByHttp(l,r,h,d,a,u,o,1e3*this.fragloadTimeout)}_loadFragByHttp(e,r,i,n,s,a,o,l){const u=ve(i,a),d=f(s,h,!0),c=new dr({});let g={url:d,...L(o)};const p={timeout:l},m={onError:e=>{e.text&&this.logger.warn(e.text),this.fragLoading=!1,r.postMessage({action:t.SW_GET_MEDIA})},onTimeout:()=>{this.logger.warn("http load timeout"),this.fragLoading=!1,r.postMessage({action:t.SW_GET_MEDIA})},onSuccess:async(o,l)=>{this.fragLoading=!1,this.notifyAllPeers(i,a,n);const{data:h}=o;let d=l.tload-l.trequest;if(this.logger.info(`HTTP loaded ${n} time ${d} speed ${h.byteLength/d}`),!await this.bufMgr.hasSegOfId(n)){const e=y(h).buffer,t=new z(i,n,e,"",a);await this.bufMgr.putSeg(t),this.reportTraffic(h.byteLength,0,0)}this.segmentBuilderMap.delete(u),e.segId=n,e.loaded=h.byteLength,this.engine.emit(t.FRAG_LOADED,{url:s,sn:i,level:a,segId:n,loaded:e.loaded,duration:e.duration,byP2p:!1}),this._onFragLoaded(s,e),r.postMessage({action:t.SW_GET_MEDIA,data:{url:s,buffer:h}})}};if(this.streamEnabled){let e;m.onBodyStart=t=>{!e&&t>0&&(this.isMobileNet||this.notifyAllPeers(i,a,n,Yt.PARTIAL_FORWARD),e=new yr(i,a,n,t),this.segmentBuilderMap.has(u)||this.segmentBuilderMap.set(u,e))},m.onUpdate=(t,r,i)=>{if(i)return this.logger.warn(`loadFragByHttp ${n} aborted`),void this.segmentBuilderMap.delete(u);e&&e.receiveBytes(t,r)}}c.load(g,p,m)}async _loadFragByP2p(e,r,i,n,s,a,o,l){const{logger:h}=this;h.info(`p2p load sn ${i} segId ${n} level ${a}`);const u=await this.load(i,n,a,s,o,l);if(u&&u.data){const{data:o,fromPeerId:l,size:d}=u;if(h.info(`p2p loaded segId ${n} level ${a} size ${o.byteLength}`),!await this.bufMgr.hasSegOfId(n)){const e=new z(i,n,o,l,a);h.info(`bufMgr putSeg ${i} level ${a}`),await this.bufMgr.putSeg(e)}return e.loaded=o.byteLength,e.fromPeerId=l,this.engine.emit(t.FRAG_LOADED,{url:s,sn:i,level:a,segId:n,loaded:e.loaded,duration:e.duration,byP2p:!0,fromPeerId:l}),this._onFragLoaded(s,e),r.postMessage({action:t.SW_GET_MEDIA,data:{url:s,buffer:o,size:d}}),!0}h.warn(`P2P timeout load segId ${n}`);const d=await this.bufMgr.getSegById(n);return!!d&&(this.fragLoading=!1,h.info(`already loaded seg sn ${i} segId ${n}`),r.postMessage({action:t.SW_GET_MEDIA,data:{url:s,buffer:d.data}}),!0)}notifySWMessage(e,r,i){if(e===t.SW_GET_MEDIA)this.engine.fetcher&&this.engine.fetcher.increMediaRequests(),this.handleGetMediaData(r,i);else this.logger.warn(`unknown action ${e}`)}_getFrag(e,t){return t&&(e=`${e}|${t}`),this.fragMap.get(e)}destroy(){super.destroy(),this.logger.warn("destroy HlsSwScheduler")}_onFragLoaded(e,t){if(this.updateLoaded(t.sn,t.level,t.segId),!this.engine)return;const{media:r,targetDuration:i}=this.engine;!this.config.live&&r&&i&&(this.currPlaySN=Math.ceil(r.currentTime/i))}load(e,t,r,i,n,s){const{logger:a,config:o}=this;let l={...L(n),proxied:!0,url:i,segId:t,httpLoadTime:1e3*o.httpLoadTime};this.setupSynForLoad(e,r,t,l,s);const h=new Promise((i=>{const n={resolve:i,sn:e,level:r,segId:t};this.resolveMap.set(e,n)}));return this.targetPeers={},h}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,r)=>{const{config:i,logger:n}=this,{segId:s,sn:a,data:o,level:l}=t,{speed:h,http:u,p2p:d,underused:c}=r;this._handleSynOutput(s,u,d,c);const f=this.resolveMap.has(a);f&&(this.fragLoading=!1);if(i.validateSegment(s,new Uint8Array(o))){this.notifyAllPeers(a,l,s),this.bitset.has(a,l)||this.reportTraffic(u,d,h);const r=e.getFromPeerId();if(f){n.info(`receive criticalSeg seg_id ${s}`);const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve({data:o,fromPeerId:r})}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t),this.updateLoaded(a,l,s))}else if(n.error(`segment ${s} validate failed`),f){const e=this.resolveMap.get(a);this.resolveMap.delete(a),e.resolve()}this.requestingMap.delete(ve(a,l)),i.live&&this.checkPeers()})).on(t.SYN_ERROR,((t,r)=>{const{sn:i,level:n}=t;if(this.resolveMap.has(i)){const e=this.resolveMap.get(i);this.resolveMap.delete(i),e.resolve()}this._handleSynError(e,n,i,r)}))}_handleDCHave(e,t,r,i,n){this._notifySynthesizer(e,i,t,r,n,this.resolveMap.has(t)),this.config.live&&W((()=>{this.checkPeers()}))}},Sr="2.7.10";class Tr extends Dt{static get name(){return"HlsSwP2pEngine"}static isServiceWorkerSupported(){return"serviceWorker"in navigator}constructor(e={},r=null){super(e,r),this.swSupported=self.isSecureContext,this.levels=[],this.bypassLevels=[],this.currentLevelIndex=0,this.currentSrc="",this.swVersion="",this.media=ce(this.config.mediaElem),this.workerKeepAliveInterval=null,this.fragMap=new Map,this.engineName=Tr.name,Tr.isServiceWorkerSupported()||(this.swSupported=!1,console.warn("service worker is not supported")),r&&(r.once("hlsDestroying",(()=>{this.destroy(),this.hlsjs=null})),r.on(this.HLSEvents.ERROR,this._onHlsError.bind(this)));const{channelIdMaker:i,signalId:n,browserInfo:s}=this.setup();if(this.onLevelLoaded=e=>{const{config:r}=this,a=e.live;r.live=a,this.targetDuration=e.averagetargetduration,this.browserInfo={...s,live:a,abr:this.multiBitrate||void 0,type:"hls_sw"},this.channel=`${i(this.currentSrc)}|${n}[${Z.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsSwP2pEngine"),o.info(`engine version: ${ue.version} hls-proxy version: ${this.swVersion}`),o.info(`channel ${this.channel}`),a||(r.startSN=e.startSN,r.endSN=e.endSN,o.info(`startSN ${e.startSN} endSN ${e.endSN}`)),this._init(this.channel,this.browserInfo),this.off(t.LEVEL_LOADED,this.onLevelLoaded)},0===this.config.httpLoadTime&&(this.config.live?this.on(t.LEVEL_LOADED,(e=>{const{fragments:t,averagetargetduration:r,startSN:i}=e;this.config.httpLoadTime=this.determineHttpLoadTime(t,r,i)})):this.config.httpLoadTime=3.5),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.onManifestParsed=(e,r)=>{this.multiBitrate=e.length>1,this.currentSrc=r,this.off(t.MANIFEST_PARSED,this.onManifestParsed)},this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.onFragLoaded=({url:e})=>{this.curTsUri=e;const{config:t}=this;!this.rangeTested&&t.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,t.logger&&t.logger.info(JSON.stringify({engine:this.engineName,...this.browserInfo})))},this.on(t.FRAG_LOADED,this.onFragLoaded),this.swSupported){const{serviceWorker:e}=navigator;e.onmessage=e=>{const{action:r,data:i}=e.data;if(!r)return;if(r===t.SW_DEBUG){const{level:e,text:t}=i;return void(this.logger&&this.logger[e](`hls-proxy: ${t}`))}const n=e.ports[0];if(n){if(this.logger&&this.logger.info(`engine onmessage action ${r}`),n.postMessage({action:r,pong:!0}),!this.p2pEnabled||!i)return n.postMessage({action:r});switch(r){case t.SW_PLAYLIST:this.handlePlaylist(i,n);break;case t.SW_GET_PLAYLIST:this.handleGetPlaylist(i,n);break;default:if(!this.scheduler)return n.postMessage({action:r});this.scheduler.notifySWMessage(r,i,n)}}else this.logger&&this.logger.error(`sender not found in action ${r}`)}}this.config.swAutoRegister&&this.registerServiceWorker().then((function(e){})).catch((e=>{console.warn("ServiceWorker registration failed ",e)}))}get currentLevel(){return this.currentLevelIndex}watchRebuffering(e){this.offEventRebuffer=function(e,t){let r=null;const i=()=>{r||(r=setTimeout((()=>{t()}),2500))},n=()=>{null!=r&&(clearTimeout(r),r=null)};return e.addEventListener("waiting",i),e.addEventListener("playing",n),()=>{e.removeEventListener("waiting",i),e.removeEventListener("playing",n)}}(e,(()=>{this.fetcher&&this.fetcher.increRebuffers()}))}handlePlaylist(e,r){const{config:i,logger:n}=this,{url:s,redirectedUrl:a,text:o,ver:l}=e;return this.swVersion=l,-1===function(e,t){for(var r=e.split("."),i=t.split("."),n=0;na)return 1}return 0}(l,Sr)?(console.warn(`hls-proxy.js version should >= ${Sr}`),r.postMessage({action:t.SW_PLAYLIST})):this.bypassLevels.indexOf(b(s))>=0?(n&&n.warn("bypass audio track"),r.postMessage({action:t.SW_PLAYLIST})):(r.postMessage({action:t.SW_PLAYLIST,data:{active:!0,debug:n&&n.isDebugLevel,sharePlaylist:!!i.sharePlaylist}}),this._parsePlaylist(o,b(s),a),void(this.workerKeepAliveInterval||navigator.serviceWorker.getRegistration().then((e=>{const t=()=>e&&e.active&&"activated"===e.active.state;if(!i.live&&t()){const r=new URL(e.scope);this.pathname=r.pathname+h;const i=e=>{clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const t=`keep alive failed ${e}`;n&&(n.error(t),n.report(t,"SWKeepAlive",this.peerId,"2.12.15"))};this.workerKeepAliveInterval=setInterval((()=>{var e;t()?(e=this.pathname,new Promise(((t,r)=>{fetch(`${e}/keepalive/`).then((e=>{if(e.ok)return e.text();throw new Error("keepalive failed")})).then((e=>{if(""!==e.trim())throw new Error("not valid keepalive response");t()})).catch((e=>{r(e)}))}))).catch((e=>{i(e)})):i("sw not activated`")}),15e3)}}))))}_parsePlaylist(e,r,i,n=!1){const s=r;i&&(r=i);const{config:a,logger:o}=this;if(e.indexOf("#EXTINF:")>0||e.indexOf("#EXT-X-TARGETDURATION:")>0){let i=0;const o=qt.parseLevelPlaylist(e,r);this.levels.length>0?(i=this.levels.indexOf(b(o.url)),-1===i?(this.restartP2p(),this.currentSrc=s,i=0):this.currentLevelIndex=i):(""!==this.currentSrc&&s!==this.currentSrc&&this.restartP2p(),this.currentSrc=s,this.levels=[b(r)]),this.emit(t.LEVEL_LOADED,o),a.live&&S(this.fragMap,200),o.fragments.forEach((e=>{e.level=i;let t=l().buildAbsoluteURL(e.baseurl,e.relurl,{alwaysNormalize:!0});const r=e.byteRange;2===r.length&&(t=`${t}|bytes=${r[0]}-${r[1]-1}`),this.fragMap.set(t,e)})),!n&&a.sharePlaylist&&this.scheduler&&!this.scheduler.isMobileNet&&this.scheduler.broadcastPlaylist(b(r),e)}else{const i=qt.parseMasterPlaylist(e,r);""!==this.currentSrc&&this.restartP2p(),i.length>0&&(i.sort(((e,t)=>e.bitrate-t.bitrate)),this.levels=i.map((e=>b(e.url))),["AUDIO","SUBTITLES","CLOSED-CAPTIONS"].forEach((t=>{qt.parseMasterPlaylistMedia(e,r,t).forEach((e=>{e.url&&this.bypassLevels.push(b(e.url))}))}))),this.emit(t.MANIFEST_PARSED,i,s)}this._setupSegmentId()}async handleGetPlaylist(e,r){const{config:i,logger:n}=this;if(!n)return r.postMessage({action:t.SW_GET_PLAYLIST});const{scheduler:s}=this;if(!s)return void n.warn("scheduler not found");const{url:a}=e,o=b(a);if(s.playlistInfo.has(o)){const e=await s.getPlaylistFromPeer(o);if(e&&e.data){const{data:i,seq:s}=e;return n.info(`got playlist from peer seq ${s}`),r.postMessage({action:t.SW_GET_PLAYLIST,data:{text:i}}),void this._parsePlaylist(i,b(a),void 0,!0)}}return r.postMessage({action:t.SW_GET_PLAYLIST})}async registerServiceWorker(){const{logger:e,config:t}=this;if(!this.swSupported){let e="sw is not supported";return E||(e="https is required when using ServiceWorker",console.warn(e)),Promise.reject(e)}return this.media=ce(t.mediaElem),this.media||e&&e.warn("no video element found"),Ir.registerServiceWorker(t)}async unregisterServiceWorker(){clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null;const e="serviceWorker is not registered";return new Promise(((t,r)=>{const{serviceWorker:i}=navigator;i||r(e),i.getRegistration().then((i=>{i?i.unregister().then(t).catch(r):r(e)}))}))}async _init(e,t){const{logger:r,config:i}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.mediaTimer=setInterval((()=>{const e=()=>this.hlsjs&&this.hlsjs.media;if(this.media){const t=e();t&&this.media!==t&&(this.media=t),clearInterval(this.mediaTimer),this.rubufferTimer=setTimeout((()=>{this.watchRebuffering(this.media)}),15e3)}else this.media=e()||ce(i.mediaElem)}),3e3);let n=new Er(this,i);n.fragMap=this.fragMap;try{await super._init(e,n,t)}catch(e){return void(r&&r.error(e))}n.server=this.fetcher,this.scheduler=n,this.p2pEnabled&&!this.tracker.connected&&this.tracker.resumeP2P()}restartP2p(){this.logger&&this.logger.warn("restart P2P"),this.disableP2P(),this.enableP2P(),this.on(t.LEVEL_LOADED,this.onLevelLoaded),this.on(t.MANIFEST_PARSED,this.onManifestParsed),this.on(t.FRAG_LOADED,this.onFragLoaded)}enableP2P(){return this.p2pEnabled?null:(this.logger&&this.logger.info("enable P2P"),this.config.p2pEnabled=this.p2pEnabled=!0,this)}disableP2P(){this.logger&&this.logger.warn("disable P2P"),clearInterval(this.mediaTimer),clearTimeout(this.rubufferTimer),this.offEventRebuffer&&this.offEventRebuffer(),this.p2pEnabled&&(this.config.p2pEnabled=this.p2pEnabled=!1,this.tracker&&this.tracker instanceof kt&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null)),this.levels=[],this.currentLevelIndex=0,this.lastLevel=0,this.multiBitrate=!1,this.rangeTested=!1,this.currentSrc="",this.media=void 0,this.config.live=!1,this.removeAllListeners(t.MANIFEST_PARSED),this.removeAllListeners(t.LEVEL_LOADED),this.removeAllListeners(t.FRAG_LOADED),clearInterval(this.workerKeepAliveInterval),this.workerKeepAliveInterval=null}destroy(){this.swSupported&&(navigator.serviceWorker.onmessage=void 0),super.destroy()}}const _r=Tr;function Lr(e,t,r="main"){return"main"!==r}function br(e,t){let r,i,n,s,a;const o=performance.now();r=o-300,i=o-200,n=o,e.trequest=r,e.tfirst=i,e.tload=n,e.loading={first:r,start:i,end:n},s=a=t,e.loaded=s,e.total=a}const Rr=class extends vr{constructor(e,t){super(e,t),this.isHlsjs=!0,this.waitForPeer=t.waitForPeer||!1,this.waitForPeerTimeout=t.waitForPeerTimeout,this.waitingPeers=0,this.waitingSeg={},this.requestedSet=new Set}startWaitPeerTimer(){this.waitForPeer&&(this.waitForPeerTimer=setTimeout((()=>{this.waitForPeer&&(this.waitForPeer=!1,this.emit(t.SCH_WAIT_PEER))}),1e3*(this.waitForPeerTimeout+0)))}updatePlaySN(e){this.currPlaySN=e}load(e,t,r){const{logger:i,config:n}=this;this.context=e;const{rangeStart:s,rangeEnd:a,url:o}=e,l=e.frag,{segId:h,sn:u,level:d}=l;this.callbacks=r,this.stats=C(),this.criticalSeg={sn:u,level:d,segId:h};let c=e.defaultTimeout-1e3*n.httpLoadTime;const f={rangeStart:Number(s),rangeEnd:Number(a),url:o,httpLoadTime:1e3*n.httpLoadTime,xhrSetup:n.xhrSetup,segId:h,headers:Object.keys(e.headers||{}).length>0?e.headers:void 0};this.setupSynForLoad(u,d,h,f,c),this.targetPeers={}}waitPeerNotifier(){return new Promise((e=>{this.waitForPeer||e(),setTimeout(e,1e3*this.waitForPeerTimeout),this.once(t.SCH_WAIT_PEER,e)}))}addPeer(e){if(super.addPeer(e),this.waitForPeer){const{level:r,sn:i}=this.waitingSeg,n=e.remotePeerId;e.bitset.has(i,r)&&i>0?(this.logger.info(`found initial seg ${r}-${i} from peer ${n}`),this.emit(t.SCH_WAIT_PEER)):this.waitingPeers===this.peersNum&&this.emit(t.SCH_WAIT_PEER)}}notifyPeersLoaded(e){this.logger.info(`notifyPeersLoaded ${e}`),this.waitForPeer&&(0===e?(this.waitForPeer=!1,this.emit(t.SCH_WAIT_PEER)):this.waitingPeers=e)}destroy(){super.destroy(),this.logger.warn("destroy HlsjsScheduler"),clearTimeout(this.waitForPeerTimer)}_setupDC(e){super._setupDC(e)}_setupSynthesizer(e){e.on(t.SYN_OUTPUT,(async(t,r)=>{const{config:i,logger:n}=this,{segId:s,sn:a,data:o,level:l}=t,{speed:h,http:u,p2p:d,underused:c}=r;this._handleSynOutput(s,u,d,c);const f=this.criticalSeg&&this.criticalSeg.segId===s;if(i.validateSegment(s,new Uint8Array(o))){this.notifyAllPeers(a,l,s),this.bitset.has(a,l)||this.reportTraffic(u,d,h);const r=e.getFromPeerId();if(f){n.info(`receive criticalSeg seg_id ${s}`);let{stats:e}=this;e.tload=e.loading.end=performance.now(),e.loaded=e.total=o.byteLength,this.criticalSeg=null;const{frag:t}=this.context;t.fromPeerId=r,t.loadByP2P=!0,this.callbacks.onSuccess({data:o,url:this.context.url},e,this.context),this.callbacks=void 0}else this.bitset.has(a,l)||(e.detachPeers(),await this.bufMgr.putSeg(t),this.updateLoaded(a,l,s))}else n.error(`segment ${s} validate failed`),f&&this.callbacks.onTimeout(this.stats,this.context,null);this.requestingMap.delete(ve(a,l)),i.live&&this.checkPeers()})).on(t.SYN_ERROR,((t,r)=>{const{sn:i,level:n}=t;this.criticalSeg&&this.criticalSeg.sn===i&&(this.criticalSeg=null,this.callbacks.onTimeout(this.stats,this.context,null)),this._handleSynError(e,n,i,r)})).on(t.SYN_PROGRESS,(({total:e,loaded:t,first:r,segId:i})=>{let{stats:n}=this;r&&n&&(n.tfirst=n.loading.first=Math.max(n.trequest,performance.now()));this.criticalSeg&&this.criticalSeg.segId===i&&this.callbacks&&this.callbacks.onLoaded&&this.callbacks.onLoaded({total:e,loaded:t,first:r},this.context)}))}_setupEngine(){super._setupEngine(),this.engine.on(t.FRAG_LOADING,(({sn:e,segId:t,byHttp:r,level:i})=>{this.loadingSN=e,this.loadingSegId=t,this.fragLoading=!0,r&&this.checkSynthesizer(e,i)})).on(t.FRAG_LOADED,(({sn:e,segId:t,byP2p:r,level:i})=>{this.fragLoading=!1,r||this.checkSynthesizer(e,i),this.updateLoaded(e,i,t)})).on(t.FRAG_CHANGED,(({sn:e})=>{this.updatePlaySN(e)}))}_handleDCHave(e,t,r,i,n){this._notifySynthesizer(e,i,t,r,n,this.criticalSeg&&this.criticalSeg.segId===i),this.config.live&&W((()=>{this.checkPeers()}))}};class Ar extends Dt{static get name(){return"HlsjsP2pEngine"}constructor(e,t={}){if(super(t,e),!e)throw new TypeError("hlsjs instance is null");this.config.xhrSetup=e.config.xhrSetup,this.engineName=Ar.name,this._onFragLoading=this._onFragLoading.bind(this),this._onFragLoaded=this._onFragLoaded.bind(this),this._onFragChanged=this._onFragChanged.bind(this),this._onHlsError=this._onHlsError.bind(this),this._onLevelUpdated=this._onLevelUpdated.bind(this);const{channelIdMaker:r,signalId:i,browserInfo:n}=this.setup();this.config.waitForPeer&&this.config.sourceUrl?(this.config.trickleICE=!0,this.config.httpRangeSupported=!0,this._startEngine(this.config.sourceUrl,this.config.live,n,r,i)):this.config.waitForPeer=!1;const s=(t,a)=>{if(!a)return;const{config:o}=this,l=a.details,h=l.live;o.waitForPeer?(this.tracker&&this.tracker.scheduler&&this.tracker.scheduler.startWaitPeerTimer(),this.logger.info("waitForPeer mode")):this._startEngine(this.hlsjs.url,h,n,r,i,l),e.off(this.HLSEvents.LEVEL_LOADED,s)};e.on(this.HLSEvents.LEVEL_LOADED,s);const a=(e,t)=>{if(!t)return;const{config:r}=this,{fragments:i,averagetargetduration:n,startSN:s}=t.details;r.httpLoadTime=this.determineHttpLoadTime(i,n,s)};0===this.config.httpLoadTime&&(this.config.live?e.on(this.HLSEvents.LEVEL_LOADED,a):this.config.httpLoadTime=3.5);const o=(t,r)=>{this._setupSegmentId();const i=r.levels.length;this.multiBitrate=i>1,e.off(this.HLSEvents.MANIFEST_PARSED,o)};e.on(this.HLSEvents.MANIFEST_PARSED,o),e.on(this.HLSEvents.DESTROYING,(()=>{e.off(this.HLSEvents.LEVEL_LOADED,a),this.destroy()}))}_startEngine(e,t,r,i,n,s={}){const{config:a}=this;a.live=t,this.browserInfo={...r,live:t,abr:this.multiBitrate||void 0,type:"hls"},this.channel=`${i(e)}|${n}[${Z.VERSION}]`,this.setupElectron();const o=this.initLogger();o.info("use HlsjsP2pEngine"),this.logger=o,o.info(`channel ${this.channel}`),t||(a.startSN=s.startSN,a.endSN=s.endSN,o.info(`startSN ${s.startSN} endSN ${s.endSN}`)),this.eventListened=!1,this._init(this.channel,this.browserInfo)}async _init(e,t){const{logger:r,config:i}=this;if(!this.p2pEnabled||"object"!=typeof self)return;this.media=this.hlsjs.media,this.media&&(this.currentSrc=this.media.src);const n=new Rr(this,i);this.eventListened||(this._updateHlsEventsHandlers(),this.eventListened=!0);try{await super._init(e,n,t)}catch(e){return void r.error(e)}this.hlsjs.config.fLoader=function(e,t,r,i){return class extends(s()){constructor(n){super(),this.logger=r,this.isHlsV0=i.isHlsV0,this.bufMgr=e.bufMgr,this.streamEnabled=i.httpStreamEnabled&&ur(),this.httpLoader=this.streamEnabled?new dr(n):new n.loader(n),this.p2pEnabled=i.p2pEnabled,this.isLive=i.live,this.scheduler=e,this.fetcher=t,this.segmentId=i.segmentId,this.blockTypes=i.p2pBlackList,this.stats=this.httpLoader.stats||C(),this.enableWorker=n.enableWorker,this.segmentBypass=A(i.segmentBypass)?i.segmentBypass:()=>!1,this.prefetchOnly=i.prefetchOnly,this.startFromSegmentOffset=i.startFromSegmentOffset,e.engine.segmentLoadCount++,this.segmentLoadCount=e.engine.segmentLoadCount}destroy(){this.httpLoader.destroy()}abort(){this.httpLoader.abort()}async load(e,t,r){const{logger:i,scheduler:n}=this,{url:s,frag:a}=e;this.isHlsV0||(a.stats=this.stats);const{level:o,sn:l,type:h,tagList:u}=a;let d=a.segId;if(!d){let t;e.rangeEnd&&(t="bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),d=a.segId=this.segmentId(String(o),l,s,t)}const c=()=>(a.loadByHTTP=!0,this.httpLoader.load(e,t,r));if(!s||!Number.isInteger(l)||Lr(0,this.blockTypes,h)||this.segmentBypass(s,u))return i.info(`HTTP load blockType ${s}`),c();if(this.fetcher.increMediaRequests(),this.isLive&&n.requestedSet.has(d))return i.warn(`HTTP load duplicated ${s}`),c();if(this.segmentLoadCount{!this.isHlsV0&&r.onProgress&&r.onProgress(this.stats,e,n.data),r.onSuccess(n,this.stats,e)}))}!this.prefetchOnly&&this.p2pEnabled&&n.hasAndSetTargetPeer(l,o,d,f)||!this.prefetchOnly&&n.waitForPeer&&(i.warn("waitPeerNotifier start"),n.waitingSeg={sn:l,level:o},await n.waitPeerNotifier(),i.warn("waitPeerNotifier end"),n.waitingSeg={},this.p2pEnabled&&n.hasAndSetTargetPeer(l,o,d,f))?this.loadFragByP2p(e,t,r,d,f):(i.info(`fragLoader load ${d} at ${l} level ${o} buffered ${1e3*f}`),this.loadFragByHttp(e,t,r,d))}loadFragByHttp(e,t,r,i){const{logger:n,scheduler:s}=this,{segmentBuilderMap:a}=s,o=e.frag,{sn:l,level:h}=o,u=ve(l,h);if(this.streamEnabled){let e;r.onUpdate=(t,r,s)=>{if(s)return n.warn(`loadFragByHttp ${i} aborted`),void a.delete(u);e&&e.receiveBytes(t,r)},r.onBodyStart=t=>{!e&&t>0&&(e=new yr(l,h,i,t),a.has(u)||a.set(u,e),s.isMobileNet||s.notifyAllPeers(l,h,i,Yt.PARTIAL_FORWARD))}}const d=r.onSuccess;r.onSuccess=async(e,t,r)=>{const{data:o}=e;let c=t.tload-t.trequest;if(n.info(`HTTP loaded ${i} time ${c} speed ${o.byteLength/c}`),!await this.bufMgr.hasSegOfId(i)){const e=y(o).buffer,t=new z(l,i,e,this.fetcher.peerId,h);await this.bufMgr.putSeg(t)}a.delete(u),this.fetcher.reportFlow(t.total),s.notifyAllPeers(l,h,i),d(e,t,r)};const c=r.onProgress;c&&(r.onProgress=(e,t,r)=>{o.loaded=e.total,c(e,t,r&&this.enableWorker?y(r).buffer:r)}),e.frag.loadByHTTP=!0,this.httpLoader.load(e,t,r)}loadFragByP2p(e,t,r,i,n){const{logger:s}=this,a=e.frag;let o;o=t.loadPolicy?t.loadPolicy.maxTimeToFirstByteMs:t.timeout,(!o||o>1e3*n)&&(o=1e3*n),e.defaultTimeout=o,this.scheduler.load(e,t,r);const l=r.onSuccess,h=r.onTimeout;r.onTimeout=(e,n)=>{s.warn(`P2P timeout switched to HTTP load ${a.relurl} at ${a.sn}`),r.onSuccess=l,this.loadFragByHttp(n,t,r,i),r.onTimeout=h},r.onSuccess=async(e,t,n)=>{if(!await this.bufMgr.hasSegOfId(i)){const t=y(e.data).buffer,r=new z(a.sn,i,t,a.fromPeerId||this.fetcher.peerId,a.level);await this.bufMgr.putSeg(r)}a.loadByP2P||this.fetcher.reportFlow(t.total),a.loaded=t.loaded,s.info(`${a.loadByP2P?"P2P":"HTTP"} loaded segment id ${i}`),!this.isHlsV0&&r.onProgress&&r.onProgress(t,n,e.data),l(e,t,n)}}}}(n,this.fetcher,r,i),i.sharePlaylist&&(this.hlsjs.config.pLoader=function(e,t,r){return class extends(s()){constructor(i){super(),this.logger=t,this.xhrLoader=new i.loader(i),this.p2pEnabled=r.p2pEnabled,this.scheduler=e,this.stats=this.xhrLoader.stats||C()}destroy(){this.xhrLoader.destroy()}abort(){this.xhrLoader.abort()}async load(e,t,r){const{logger:i}=this,{url:n}=e,s=b(n),a=r.onSuccess;if(r.onSuccess=(e,t,r)=>{this.scheduler&&!r.loadedByPeer&&this.scheduler.broadcastPlaylist(s,e.data),a(e,t,r)},this.scheduler&&this.scheduler.playlistInfo.has(s)){const t=await this.scheduler.getPlaylistFromPeer(s);if(t&&t.data){const{data:s,seq:a}=t;i.info(`got playlist from peer seq ${a}`),br(this.stats,s.length);let o={url:n,data:s};return e.loadedByPeer=!0,void W((()=>{r.onSuccess(o,this.stats,e)}))}}this.xhrLoader.load(e,t,r)}}}(n,r,i)),this.trackerTried=!1,this.trackerTried||this.tracker.connected||!i.p2pEnabled||(this.tracker.resumeP2P(),this.trackerTried=!0)}_onFragLoading(e,r){const i=r.frag;let{sn:n,level:s,segId:a}=i;if(!Lr(i.url,this.config.p2pBlackList,i.type)&&Number.isInteger(n)){if(this.logger.info("loading frag "+n),this.bufMgr&&(this.bufMgr.loadingSN=n),!a){let e;i._byteRange&&(e="bytes="+i._byteRange[0]+"-"+i._byteRange[1]);let t=i.url;this._setupSegmentId(),a=i.segId=this.config.segmentId(String(s),i.sn,t,e)}this.emit(t.FRAG_LOADING,{sn:n,segId:a,byHttp:i.loadByHTTP,level:s})}}_onLevelUpdated(e,t){const{details:r}=t,{hlsjs:i,config:n}=this;if(!r.live)return;const s=r.fragments.length,a=s-1;i&&i.config.liveSyncDurationCount!==a&&"main"===r.fragments[0].type&&s>4&&(n.isHlsV0||!i.userConfig.liveSyncDuration&&!i.userConfig.liveSyncDurationCount)&&(this.logger.info(`set liveSyncDurationCount ${a}`),i.config.liveSyncDurationCount=a)}_onFragLoaded(e,r){if(!this.p2pEnabled)return;const{frag:i}=r;this.curTsUri=i.url;const{sn:n,segId:s,loaded:a,duration:o,level:l,fromPeerId:h,loadByP2P:u,url:d}=i,{config:c,logger:f}=this;this.tracker&&this.tracker.scheduler&&(T(this.tracker.scheduler.requestedSet,50),this.tracker.scheduler.requestedSet.add(s)),Lr(i.url,c.p2pBlackList,i.type)||(this.bufMgr&&this.bufMgr.loadingSN>=0&&this.emit(t.FRAG_LOADED,{url:d,sn:n,level:l,segId:s,loaded:a,duration:o,byP2p:!!u,fromPeerId:h}),!this.rangeTested&&c.useHttpRange&&(this.startRangeRequestTimer(),this.rangeTested=!0,f.info(JSON.stringify({engine:this.engineName,hlsjs:this.hlsjsVersion,...this.browserInfo}))))}_onFragChanged(e,r){const{frag:i}=r;if(!Lr(i.url,this.config.p2pBlackList,i.type)){this.logger.info("frag changed: "+i.sn);const{sn:e,duration:r}=i;this.emit(t.FRAG_CHANGED,{sn:e,duration:r})}}get currentLevel(){const{currentLevel:e}=this.hlsjs;return e>=0?e:0}disableP2P(){this.logger&&this.logger.warn("disable P2P"),this.p2pEnabled&&(this.p2pEnabled=!1,this.config.p2pEnabled=this.p2pEnabled,this.tracker&&(this.tracker.stopP2P(),this.tracker={},this.fetcher=null,this.bufMgr.destroy(),this.bufMgr=null,this.hlsjs.config.fLoader=this.hlsjs.config.pLoader=this.hlsjs.constructor.DefaultConfig.loader))}_updateHlsEventsHandlers(e=!1){const t=this.hlsjs;if(!t)return;const r=e?"off":"on";t[r](this.HLSEvents.FRAG_LOADING,this._onFragLoading),t[r](this.HLSEvents.FRAG_LOADED,this._onFragLoaded),t[r](this.HLSEvents.FRAG_CHANGED,this._onFragChanged),t[r](this.HLSEvents.ERROR,this._onHlsError),t[r](this.HLSEvents.LEVEL_UPDATED,this._onLevelUpdated)}destroy(){this._updateHlsEventsHandlers(!0),super.destroy()}}const wr=Ar;class Pr{static get Events(){return t}static get TrackerZone(){return ue.TrackerZone}static isSupported(){return ue.isSupported()&&(de()||_r.isServiceWorkerSupported())}static isServiceWorkerSupported(){return _r.isServiceWorkerSupported()}static isMSESupported(){return de()}static getBrowser(){return Q().getBrowser()}static get ServiceWorkerEngine(){return _r}static get HlsjsEngine(){return wr}static async tryRegisterServiceWorker({swFile:e="./sw.js",swScope:t="./"}={}){return Pr.registerServiceWorker({swFile:e,swScope:t})}static async registerServiceWorker({swFile:e="./sw.js",swScope:t="./",hlsjsInstance:r}={}){const{serviceWorker:i}=navigator;return!i||r?Promise.resolve():i.getRegistration().then((r=>r||Promise.race([i.register(e,{scope:t}).then((e=>function(e){return new Promise(((t,r)=>{const i=e.installing||e.waiting||e.active,n=()=>"activated"===i.state&&(i.removeEventListener("statechange",n),t(e),!0);n()||i.addEventListener("statechange",n)}))}(e))),m(300)]))).catch((()=>{Promise.resolve()}))}constructor(e={}){const{hlsjsInstance:t}=e;delete e.hlsjsInstance;const r=()=>{this._realEngine=new wr(t,e)},i=()=>{this._realEngine=new _r(e,t)};"1"!==c("_sw")?e.proxyFirst&&t?_r.isServiceWorkerSupported()?i():r():!e.proxyOnly&&de()&&t?r():i():i()}get realEngine(){return this._realEngine}get engineName(){return this._realEngine.constructor.name}once(e,t){return this._realEngine.once(e,t)}on(e,t){return this._realEngine.on(e,t)}off(e,t){return this._realEngine.off(e,t)}removeListener(e,t){return this._realEngine.removeListener(e,t)}removeAllListeners(e){return this._realEngine.removeAllListeners(e)}set p2pEnabled(e){this._realEngine.p2pEnabled=e}get p2pEnabled(){return this._realEngine.p2pEnabled}enableP2P(){this._realEngine.enableP2P()}disableP2P(){this._realEngine.disableP2P()}destroy(){this._realEngine.destroy()}async registerServiceWorker(){return A(this._realEngine.registerServiceWorker)?this._realEngine.registerServiceWorker():Promise.reject("Not supported by this engine")}async unregisterServiceWorker(){return A(this._realEngine.unregisterServiceWorker)?this._realEngine.unregisterServiceWorker():Promise.reject("Not supported by this engine")}get version(){return ue.version}}Pr.version=ue.version,Pr.protocolVersion=Z.VERSION,"object"==typeof self&&(self.P2PEngineHls=Pr);const Ir=Pr;var Cr=r(251),kr=r.n(Cr);const Dr={maxBufferLength:12},Mr={maxBufferLength:40};class xr extends(kr()){static get P2PEvents(){return Ir.Events}static get P2pEngine(){return Ir}constructor(e={}){let t=e.p2pConfig||{};const r=!1===t.live?Mr:Dr;let i=JSON.parse(JSON.stringify(r));i.maxBufferSize=0,i.enableWorker=!1;for(let t in e)"p2pConfig"!==t&&(i[t]=e[t]);super(i),this._restartEvent=()=>{this.restartP2P()},Ir.isSupported()&&(this._p2pEngine=new Ir({...t,hlsjsInstance:this}),this._p2pEngine.on(Ir.Events.RESTART_P2P,this._restartEvent)),this.on(kr().Events.DESTROYING,(()=>{this._p2pEngine&&(this._p2pEngine.removeListener(Ir.Events.RESTART_P2P,this._restartEvent),this._p2pEngine.hlsjs=null,this._p2pEngine=null)}))}get p2pEngine(){return this._p2pEngine}enableP2P(){this._p2pEngine&&(this._p2pEngine=this._p2pEngine.enableP2P())}disableP2P(){this._p2pEngine&&this._p2pEngine.disableP2P()}restartP2P(){this._p2pEngine&&(this._p2pEngine.disableP2P(),setTimeout((()=>{this.enableP2P()}),2e3),this._p2pEngine.removeListener(Ir.Events.RESTART_P2P,this._restartEvent))}}xr.engineVersion=Ir.version,xr.protocolVersion=Ir.protocolVersion,xr.WEBRTC_SUPPORT=Ir.isSupported();const Or=xr})(),i=i.default})())); \ No newline at end of file