var $s = Object.defineProperty; var Bs = (lt, tt, vt) => tt in lt ? $s(lt, tt, { enumerable: !0, configurable: !0, writable: !0, value: vt }) : lt[tt] = vt; var Oi = (lt, tt, vt) => (Bs(lt, typeof tt != "symbol" ? tt + "" : tt, vt), vt), ro = (lt, tt, vt) => { if (!tt.has(lt)) throw TypeError("Cannot " + vt) }; var En = (lt, tt, vt) => (ro(lt, tt, "read from private field"), vt ? vt.call(lt) : tt.get(lt)), Fn = (lt, tt, vt) => { if (tt.has(lt)) throw TypeError("Cannot add the same private member more than once"); tt instanceof WeakSet ? tt.add(lt) : tt.set(lt, vt) }, wn = (lt, tt, vt, cn) => (ro(lt, tt, "write to private field"), cn ? cn.call(lt, vt) : tt.set(lt, vt), vt); (function (lt, tt) { typeof exports == "object" && typeof module < "u" ? tt(exports) : typeof define == "function" && define.amd ? define(["exports"], tt) : (lt = typeof globalThis < "u" ? globalThis : lt || self, tt(lt.cmwwPlayer = {})) })(this, function (exports) { var lt, tt, vt, cn, Un, Nn; "use strict"; class Polyfill { static install() { Object.setPrototypeOf = Object.setPrototypeOf || function (t, n) { return t.__proto__ = n, t }, Object.assign = Object.assign || function (t) { if (t == null) throw new TypeError("Cannot convert undefined or null to object"); let n = Object(t); for (let r = 1; r < arguments.length; r++) { let l = arguments[r]; if (l != null) for (let a in l) l.hasOwnProperty(a) && (n[a] = l[a]) } return n } } } Polyfill.install(); var commonjsGlobal = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; function getDefaultExportFromCjs(h) { return h && h.__esModule && Object.prototype.hasOwnProperty.call(h, "default") ? h.default : h } var events = { exports: {} }, R = typeof Reflect == "object" ? Reflect : null, ReflectApply = R && typeof R.apply == "function" ? R.apply : function (t, n, r) { return Function.prototype.apply.call(t, n, r) }, ReflectOwnKeys; R && typeof R.ownKeys == "function" ? ReflectOwnKeys = R.ownKeys : Object.getOwnPropertySymbols ? ReflectOwnKeys = function (t) { return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t)) } : ReflectOwnKeys = function (t) { return Object.getOwnPropertyNames(t) }; function ProcessEmitWarning(h) { console && console.warn && console.warn(h) } var NumberIsNaN = Number.isNaN || function (t) { return t !== t }; function EventEmitter() { EventEmitter.init.call(this) } events.exports = EventEmitter, events.exports.once = once, EventEmitter.EventEmitter = EventEmitter, EventEmitter.prototype._events = void 0, EventEmitter.prototype._eventsCount = 0, EventEmitter.prototype._maxListeners = void 0; var defaultMaxListeners = 10; function checkListener(h) { if (typeof h != "function") throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof h) } Object.defineProperty(EventEmitter, "defaultMaxListeners", { enumerable: !0, get: function () { return defaultMaxListeners }, set: function (h) { if (typeof h != "number" || h < 0 || NumberIsNaN(h)) throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + h + "."); defaultMaxListeners = h } }), EventEmitter.init = function () { (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) && (this._events = Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0 }, EventEmitter.prototype.setMaxListeners = function (t) { if (typeof t != "number" || t < 0 || NumberIsNaN(t)) throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + t + "."); return this._maxListeners = t, this }; function _getMaxListeners(h) { return h._maxListeners === void 0 ? EventEmitter.defaultMaxListeners : h._maxListeners } EventEmitter.prototype.getMaxListeners = function () { return _getMaxListeners(this) }, EventEmitter.prototype.emit = function (t) { for (var n = [], r = 1; r < arguments.length; r++)n.push(arguments[r]); var l = t === "error", a = this._events; if (a !== void 0) l = l && a.error === void 0; else if (!l) return !1; if (l) { var e; if (n.length > 0 && (e = n[0]), e instanceof Error) throw e; var g = new Error("Unhandled error." + (e ? " (" + e.message + ")" : "")); throw g.context = e, g } var _ = a[t]; if (_ === void 0) return !1; if (typeof _ == "function") ReflectApply(_, this, n); else for (var y = _.length, x = arrayClone(_, y), r = 0; r < y; ++r)ReflectApply(x[r], this, n); return !0 }; function _addListener(h, t, n, r) { var l, a, e; if (checkListener(n), a = h._events, a === void 0 ? (a = h._events = Object.create(null), h._eventsCount = 0) : (a.newListener !== void 0 && (h.emit("newListener", t, n.listener ? n.listener : n), a = h._events), e = a[t]), e === void 0) e = a[t] = n, ++h._eventsCount; else if (typeof e == "function" ? e = a[t] = r ? [n, e] : [e, n] : r ? e.unshift(n) : e.push(n), l = _getMaxListeners(h), l > 0 && e.length > l && !e.warned) { e.warned = !0; var g = new Error("Possible EventEmitter memory leak detected. " + e.length + " " + String(t) + " listeners added. Use emitter.setMaxListeners() to increase limit"); g.name = "MaxListenersExceededWarning", g.emitter = h, g.type = t, g.count = e.length, ProcessEmitWarning(g) } return h } EventEmitter.prototype.addListener = function (t, n) { return _addListener(this, t, n, !1) }, EventEmitter.prototype.on = EventEmitter.prototype.addListener, EventEmitter.prototype.prependListener = function (t, n) { return _addListener(this, t, n, !0) }; function onceWrapper() { if (!this.fired) return this.target.removeListener(this.type, this.wrapFn), this.fired = !0, arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments) } function _onceWrap(h, t, n) { var r = { fired: !1, wrapFn: void 0, target: h, type: t, listener: n }, l = onceWrapper.bind(r); return l.listener = n, r.wrapFn = l, l } EventEmitter.prototype.once = function (t, n) { return checkListener(n), this.on(t, _onceWrap(this, t, n)), this }, EventEmitter.prototype.prependOnceListener = function (t, n) { return checkListener(n), this.prependListener(t, _onceWrap(this, t, n)), this }, EventEmitter.prototype.removeListener = function (t, n) { var r, l, a, e, g; if (checkListener(n), l = this._events, l === void 0) return this; if (r = l[t], r === void 0) return this; if (r === n || r.listener === n) --this._eventsCount === 0 ? this._events = Object.create(null) : (delete l[t], l.removeListener && this.emit("removeListener", t, r.listener || n)); else if (typeof r != "function") { for (a = -1, e = r.length - 1; e >= 0; e--)if (r[e] === n || r[e].listener === n) { g = r[e].listener, a = e; break } if (a < 0) return this; a === 0 ? r.shift() : spliceOne(r, a), r.length === 1 && (l[t] = r[0]), l.removeListener !== void 0 && this.emit("removeListener", t, g || n) } return this }, EventEmitter.prototype.off = EventEmitter.prototype.removeListener, EventEmitter.prototype.removeAllListeners = function (t) { var n, r, l; if (r = this._events, r === void 0) return this; if (r.removeListener === void 0) return arguments.length === 0 ? (this._events = Object.create(null), this._eventsCount = 0) : r[t] !== void 0 && (--this._eventsCount === 0 ? this._events = Object.create(null) : delete r[t]), this; if (arguments.length === 0) { var a = Object.keys(r), e; for (l = 0; l < a.length; ++l)e = a[l], e !== "removeListener" && this.removeAllListeners(e); return this.removeAllListeners("removeListener"), this._events = Object.create(null), this._eventsCount = 0, this } if (n = r[t], typeof n == "function") this.removeListener(t, n); else if (n !== void 0) for (l = n.length - 1; l >= 0; l--)this.removeListener(t, n[l]); return this }; function _listeners(h, t, n) { var r = h._events; if (r === void 0) return []; var l = r[t]; return l === void 0 ? [] : typeof l == "function" ? n ? [l.listener || l] : [l] : n ? unwrapListeners(l) : arrayClone(l, l.length) } EventEmitter.prototype.listeners = function (t) { return _listeners(this, t, !0) }, EventEmitter.prototype.rawListeners = function (t) { return _listeners(this, t, !1) }, EventEmitter.listenerCount = function (h, t) { return typeof h.listenerCount == "function" ? h.listenerCount(t) : listenerCount.call(h, t) }, EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(h) { var t = this._events; if (t !== void 0) { var n = t[h]; if (typeof n == "function") return 1; if (n !== void 0) return n.length } return 0 } EventEmitter.prototype.eventNames = function () { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [] }; function arrayClone(h, t) { for (var n = new Array(t), r = 0; r < t; ++r)n[r] = h[r]; return n } function spliceOne(h, t) { for (; t + 1 < h.length; t++)h[t] = h[t + 1]; h.pop() } function unwrapListeners(h) { for (var t = new Array(h.length), n = 0; n < t.length; ++n)t[n] = h[n].listener || h[n]; return t } function once(h, t) { return new Promise(function (n, r) { function l(e) { h.removeListener(t, a), r(e) } function a() { typeof h.removeListener == "function" && h.removeListener("error", l), n([].slice.call(arguments)) } eventTargetAgnosticAddListener(h, t, a, { once: !0 }), t !== "error" && addErrorHandlerIfEventEmitter(h, l, { once: !0 }) }) } function addErrorHandlerIfEventEmitter(h, t, n) { typeof h.on == "function" && eventTargetAgnosticAddListener(h, "error", t, n) } function eventTargetAgnosticAddListener(h, t, n, r) { if (typeof h.on == "function") r.once ? h.once(t, n) : h.on(t, n); else if (typeof h.addEventListener == "function") h.addEventListener(t, function l(a) { r.once && h.removeEventListener(t, l), n(a) }); else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof h) } var eventsExports = events.exports; const EventEmitter$1 = getDefaultExportFromCjs(eventsExports); class Log { static e(t, n) { (!t || Log.FORCE_GLOBAL_TAG) && (t = Log.GLOBAL_TAG); let r = `[${t}] > ${n}`; Log.ENABLE_CALLBACK && Log.emitter.emit("log", "error", r), Log.ENABLE_ERROR && (console.error ? console.error(r) : console.warn ? console.warn(r) : console.log(r)) } static i(t, n) { (!t || Log.FORCE_GLOBAL_TAG) && (t = Log.GLOBAL_TAG); let r = `[${t}] > ${n}`; Log.ENABLE_CALLBACK && Log.emitter.emit("log", "info", r), Log.ENABLE_INFO && (console.info ? console.info(r) : console.log(r)) } static w(t, n) { (!t || Log.FORCE_GLOBAL_TAG) && (t = Log.GLOBAL_TAG); let r = `[${t}] > ${n}`; Log.ENABLE_CALLBACK && Log.emitter.emit("log", "warn", r), Log.ENABLE_WARN && (console.warn ? console.warn(r) : console.log(r)) } static d(t, n) { (!t || Log.FORCE_GLOBAL_TAG) && (t = Log.GLOBAL_TAG); let r = `[${t}] > ${n}`; Log.ENABLE_CALLBACK && Log.emitter.emit("log", "debug", r), Log.ENABLE_DEBUG && (console.debug ? console.debug(r) : console.log(r)) } static v(t, n) { (!t || Log.FORCE_GLOBAL_TAG) && (t = Log.GLOBAL_TAG); let r = `[${t}] > ${n}`; Log.ENABLE_CALLBACK && Log.emitter.emit("log", "verbose", r), Log.ENABLE_VERBOSE } } Log.GLOBAL_TAG = "flv.js", Log.FORCE_GLOBAL_TAG = !1, Log.ENABLE_ERROR = !0, Log.ENABLE_INFO = !0, Log.ENABLE_WARN = !0, Log.ENABLE_DEBUG = !0, Log.ENABLE_VERBOSE = !0, Log.ENABLE_CALLBACK = !1, Log.emitter = new EventEmitter$1; class SpeedSampler { constructor() { this._firstCheckpoint = 0, this._lastCheckpoint = 0, this._intervalBytes = 0, this._totalBytes = 0, this._lastSecondBytes = 0, self.performance && self.performance.now ? this._now = self.performance.now.bind(self.performance) : this._now = Date.now } reset() { this._firstCheckpoint = this._lastCheckpoint = 0, this._totalBytes = this._intervalBytes = 0, this._lastSecondBytes = 0 } addBytes(t) { this._firstCheckpoint === 0 ? (this._firstCheckpoint = this._now(), this._lastCheckpoint = this._firstCheckpoint, this._intervalBytes += t, this._totalBytes += t) : this._now() - this._lastCheckpoint < 1e3 ? (this._intervalBytes += t, this._totalBytes += t) : (this._lastSecondBytes = this._intervalBytes, this._intervalBytes = t, this._totalBytes += t, this._lastCheckpoint = this._now()) } get currentKBps() { this.addBytes(0); let t = (this._now() - this._lastCheckpoint) / 1e3; return t == 0 && (t = 1), this._intervalBytes / t / 1024 } get lastSecondKBps() { return this.addBytes(0), this._lastSecondBytes !== 0 ? this._lastSecondBytes / 1024 : this._now() - this._lastCheckpoint >= 500 ? this.currentKBps : 0 } get averageKBps() { let t = (this._now() - this._firstCheckpoint) / 1e3; return this._totalBytes / t / 1024 } } class RuntimeException { constructor(t) { this._message = t } get name() { return "RuntimeException" } get message() { return this._message } toString() { return this.name + ": " + this.message } } class IllegalStateException extends RuntimeException { constructor(t) { super(t) } get name() { return "IllegalStateException" } } class InvalidArgumentException extends RuntimeException { constructor(t) { super(t) } get name() { return "InvalidArgumentException" } } class NotImplementedException extends RuntimeException { constructor(t) { super(t) } get name() { return "NotImplementedException" } } const LoaderStatus = { kIdle: 0, kConnecting: 1, kBuffering: 2, kError: 3, kComplete: 4 }, LoaderErrors = { OK: "OK", EXCEPTION: "Exception", HTTP_STATUS_CODE_INVALID: "HttpStatusCodeInvalid", CONNECTING_TIMEOUT: "ConnectingTimeout", EARLY_EOF: "EarlyEof", UNRECOVERABLE_EARLY_EOF: "UnrecoverableEarlyEof" }; class BaseLoader { constructor(t) { this._type = t || "undefined", this._status = LoaderStatus.kIdle, this._needStash = !1, this._onContentLengthKnown = null, this._onURLRedirect = null, this._onDataArrival = null, this._onError = null, this._onComplete = null } destroy() { this._status = LoaderStatus.kIdle, this._onContentLengthKnown = null, this._onURLRedirect = null, this._onDataArrival = null, this._onError = null, this._onComplete = null } isWorking() { return this._status === LoaderStatus.kConnecting || this._status === LoaderStatus.kBuffering } get type() { return this._type } get status() { return this._status } get needStashBuffer() { return this._needStash } get onContentLengthKnown() { return this._onContentLengthKnown } set onContentLengthKnown(t) { this._onContentLengthKnown = t } get onURLRedirect() { return this._onURLRedirect } set onURLRedirect(t) { this._onURLRedirect = t } get onDataArrival() { return this._onDataArrival } set onDataArrival(t) { this._onDataArrival = t } get onError() { return this._onError } set onError(t) { this._onError = t } get onComplete() { return this._onComplete } set onComplete(t) { this._onComplete = t } open(t, n) { throw new NotImplementedException("Unimplemented abstract function!") } abort() { throw new NotImplementedException("Unimplemented abstract function!") } } let Browser = {}; function detect() { let h = self.navigator.userAgent.toLowerCase(), t = /(edge)\/([\w.]+)/.exec(h) || /(opr)[\/]([\w.]+)/.exec(h) || /(chrome)[ \/]([\w.]+)/.exec(h) || /(iemobile)[\/]([\w.]+)/.exec(h) || /(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(h) || /(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(h) || /(webkit)[ \/]([\w.]+)/.exec(h) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(h) || /(msie) ([\w.]+)/.exec(h) || h.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec(h) || h.indexOf("compatible") < 0 && /(firefox)[ \/]([\w.]+)/.exec(h) || [], n = /(ipad)/.exec(h) || /(ipod)/.exec(h) || /(windows phone)/.exec(h) || /(iphone)/.exec(h) || /(kindle)/.exec(h) || /(android)/.exec(h) || /(windows)/.exec(h) || /(mac)/.exec(h) || /(linux)/.exec(h) || /(cros)/.exec(h) || [], r = { browser: t[5] || t[3] || t[1] || "", version: t[2] || t[4] || "0", majorVersion: t[4] || t[2] || "0", platform: n[0] || "" }, l = {}; if (r.browser) { l[r.browser] = !0; let a = r.majorVersion.split("."); l.version = { major: parseInt(r.majorVersion, 10), string: r.version }, a.length > 1 && (l.version.minor = parseInt(a[1], 10)), a.length > 2 && (l.version.build = parseInt(a[2], 10)) } if (r.platform && (l[r.platform] = !0), (l.chrome || l.opr || l.safari) && (l.webkit = !0), l.rv || l.iemobile) { l.rv && delete l.rv; let a = "msie"; r.browser = a, l[a] = !0 } if (l.edge) { delete l.edge; let a = "msedge"; r.browser = a, l[a] = !0 } if (l.opr) { let a = "opera"; r.browser = a, l[a] = !0 } if (l.safari && l.android) { let a = "android"; r.browser = a, l[a] = !0 } l.name = r.browser, l.platform = r.platform; for (let a in Browser) Browser.hasOwnProperty(a) && delete Browser[a]; Object.assign(Browser, l) } detect(); class FetchStreamLoader extends BaseLoader { static isSupported() { try { let t = Browser.msedge && Browser.version.minor >= 15048, n = Browser.msedge ? t : !0; return self.fetch && self.ReadableStream && n } catch { return !1 } } constructor(t, n) { super("fetch-stream-loader"), this.TAG = "FetchStreamLoader", this._seekHandler = t, this._config = n, this._needStash = !0, this._requestAbort = !1, this._contentLength = null, this._receivedLength = 0 } destroy() { this.isWorking() && this.abort(), super.destroy() } open(t, n) { this._dataSource = t, this._range = n; let r = t.url; this._config.reuseRedirectedURL && t.redirectedURL != null && (r = t.redirectedURL); let l = this._seekHandler.getConfig(r, n), a = new self.Headers; if (typeof l.headers == "object") { let g = l.headers; for (let _ in g) g.hasOwnProperty(_) && a.append(_, g[_]) } let e = { method: "GET", headers: a, mode: "cors", cache: "default", referrerPolicy: "no-referrer-when-downgrade" }; if (typeof this._config.headers == "object") for (let g in this._config.headers) a.append(g, this._config.headers[g]); t.cors === !1 && (e.mode = "same-origin"), t.withCredentials && (e.credentials = "include"), t.referrerPolicy && (e.referrerPolicy = t.referrerPolicy), self.AbortController && (this._abortController = new self.AbortController, e.signal = this._abortController.signal), this._status = LoaderStatus.kConnecting, self.fetch(l.url, e).then(g => { if (this._requestAbort) { this._status = LoaderStatus.kIdle, g.body.cancel(); return } if (g.ok && g.status >= 200 && g.status <= 299) { if (g.url !== l.url && this._onURLRedirect) { let y = this._seekHandler.removeURLParameters(g.url); this._onURLRedirect(y) } let _ = g.headers.get("Content-Length"); return _ != null && (this._contentLength = parseInt(_), this._contentLength !== 0 && this._onContentLengthKnown && this._onContentLengthKnown(this._contentLength)), this._pump.call(this, g.body.getReader()) } else if (this._status = LoaderStatus.kError, this._onError) this._onError(LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: g.status, msg: g.statusText }); else throw new RuntimeException("FetchStreamLoader: Http code invalid, " + g.status + " " + g.statusText) }).catch(g => { if (!(this._abortController && this._abortController.signal.aborted)) if (this._status = LoaderStatus.kError, this._onError) this._onError(LoaderErrors.EXCEPTION, { code: -1, msg: g.message }); else throw g }) } abort() { if (this._requestAbort = !0, (this._status !== LoaderStatus.kBuffering || !Browser.chrome) && this._abortController) try { this._abortController.abort() } catch { } } _pump(t) { return t.read().then(n => { if (n.done) if (this._contentLength !== null && this._receivedLength < this._contentLength) { this._status = LoaderStatus.kError; let r = LoaderErrors.EARLY_EOF, l = { code: -1, msg: "Fetch stream meet Early-EOF" }; if (this._onError) this._onError(r, l); else throw new RuntimeException(l.msg) } else this._status = LoaderStatus.kComplete, this._onComplete && this._onComplete(this._range.from, this._range.from + this._receivedLength - 1); else { if (this._abortController && this._abortController.signal.aborted) { this._status = LoaderStatus.kComplete; return } else if (this._requestAbort === !0) return this._status = LoaderStatus.kComplete, t.cancel(); this._status = LoaderStatus.kBuffering; let r = n.value.buffer, l = this._range.from + this._receivedLength; this._receivedLength += r.byteLength, this._onDataArrival && this._onDataArrival(r, l, this._receivedLength), this._pump(t) } }).catch(n => { if (this._abortController && this._abortController.signal.aborted) { this._status = LoaderStatus.kComplete; return } if (n.code === 11 && Browser.msedge) return; this._status = LoaderStatus.kError; let r = 0, l = null; if ((n.code === 19 || n.message === "network error") && (this._contentLength === null || this._contentLength !== null && this._receivedLength < this._contentLength) ? (r = LoaderErrors.EARLY_EOF, l = { code: n.code, msg: "Fetch stream meet Early-EOF" }) : (r = LoaderErrors.EXCEPTION, l = { code: n.code, msg: n.message }), this._onError) this._onError(r, l); else throw new RuntimeException(l.msg) }) } } class MozChunkedLoader extends BaseLoader { static isSupported() { try { let t = new XMLHttpRequest; return t.open("GET", "https://example.com", !0), t.responseType = "moz-chunked-arraybuffer", t.responseType === "moz-chunked-arraybuffer" } catch (t) { return Log.w("MozChunkedLoader", t.message), !1 } } constructor(t, n) { super("xhr-moz-chunked-loader"), this.TAG = "MozChunkedLoader", this._seekHandler = t, this._config = n, this._needStash = !0, this._xhr = null, this._requestAbort = !1, this._contentLength = null, this._receivedLength = 0 } destroy() { this.isWorking() && this.abort(), this._xhr && (this._xhr.onreadystatechange = null, this._xhr.onprogress = null, this._xhr.onloadend = null, this._xhr.onerror = null, this._xhr = null), super.destroy() } open(t, n) { this._dataSource = t, this._range = n; let r = t.url; this._config.reuseRedirectedURL && t.redirectedURL != null && (r = t.redirectedURL); let l = this._seekHandler.getConfig(r, n); this._requestURL = l.url; let a = this._xhr = new XMLHttpRequest; if (a.open("GET", l.url, !0), a.responseType = "moz-chunked-arraybuffer", a.onreadystatechange = this._onReadyStateChange.bind(this), a.onprogress = this._onProgress.bind(this), a.onloadend = this._onLoadEnd.bind(this), a.onerror = this._onXhrError.bind(this), t.withCredentials && (a.withCredentials = !0), typeof l.headers == "object") { let e = l.headers; for (let g in e) e.hasOwnProperty(g) && a.setRequestHeader(g, e[g]) } if (typeof this._config.headers == "object") { let e = this._config.headers; for (let g in e) e.hasOwnProperty(g) && a.setRequestHeader(g, e[g]) } this._status = LoaderStatus.kConnecting, a.send() } abort() { this._requestAbort = !0, this._xhr && this._xhr.abort(), this._status = LoaderStatus.kComplete } _onReadyStateChange(t) { let n = t.target; if (n.readyState === 2) { if (n.responseURL != null && n.responseURL !== this._requestURL && this._onURLRedirect) { let r = this._seekHandler.removeURLParameters(n.responseURL); this._onURLRedirect(r) } if (n.status !== 0 && (n.status < 200 || n.status > 299)) if (this._status = LoaderStatus.kError, this._onError) this._onError(LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: n.status, msg: n.statusText }); else throw new RuntimeException("MozChunkedLoader: Http code invalid, " + n.status + " " + n.statusText); else this._status = LoaderStatus.kBuffering } } _onProgress(t) { if (this._status === LoaderStatus.kError) return; this._contentLength === null && t.total !== null && t.total !== 0 && (this._contentLength = t.total, this._onContentLengthKnown && this._onContentLengthKnown(this._contentLength)); let n = t.target.response, r = this._range.from + this._receivedLength; this._receivedLength += n.byteLength, this._onDataArrival && this._onDataArrival(n, r, this._receivedLength) } _onLoadEnd(t) { if (this._requestAbort === !0) { this._requestAbort = !1; return } else if (this._status === LoaderStatus.kError) return; this._status = LoaderStatus.kComplete, this._onComplete && this._onComplete(this._range.from, this._range.from + this._receivedLength - 1) } _onXhrError(t) { this._status = LoaderStatus.kError; let n = 0, r = null; if (this._contentLength && t.loaded < this._contentLength ? (n = LoaderErrors.EARLY_EOF, r = { code: -1, msg: "Moz-Chunked stream meet Early-Eof" }) : (n = LoaderErrors.EXCEPTION, r = { code: -1, msg: t.constructor.name + " " + t.type }), this._onError) this._onError(n, r); else throw new RuntimeException(r.msg) } } class RangeLoader extends BaseLoader { static isSupported() { try { let t = new XMLHttpRequest; return t.open("GET", "https://example.com", !0), t.responseType = "arraybuffer", t.responseType === "arraybuffer" } catch (t) { return Log.w("RangeLoader", t.message), !1 } } constructor(t, n) { super("xhr-range-loader"), this.TAG = "RangeLoader", this._seekHandler = t, this._config = n, this._needStash = !1, this._chunkSizeKBList = [128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 5120, 6144, 7168, 8192], this._currentChunkSizeKB = 384, this._currentSpeedNormalized = 0, this._zeroSpeedChunkCount = 0, this._xhr = null, this._speedSampler = new SpeedSampler, this._requestAbort = !1, this._waitForTotalLength = !1, this._totalLengthReceived = !1, this._currentRequestURL = null, this._currentRedirectedURL = null, this._currentRequestRange = null, this._totalLength = null, this._contentLength = null, this._receivedLength = 0, this._lastTimeLoaded = 0 } destroy() { this.isWorking() && this.abort(), this._xhr && (this._xhr.onreadystatechange = null, this._xhr.onprogress = null, this._xhr.onload = null, this._xhr.onerror = null, this._xhr = null), super.destroy() } get currentSpeed() { return this._speedSampler.lastSecondKBps } open(t, n) { this._dataSource = t, this._range = n, this._status = LoaderStatus.kConnecting; let r = !1; this._dataSource.filesize != null && this._dataSource.filesize !== 0 && (r = !0, this._totalLength = this._dataSource.filesize), !this._totalLengthReceived && !r ? (this._waitForTotalLength = !0, this._internalOpen(this._dataSource, { from: 0, to: -1 })) : this._openSubRange() } _openSubRange() { let t = this._currentChunkSizeKB * 1024, n = this._range.from + this._receivedLength, r = n + t; this._contentLength != null && r - this._range.from >= this._contentLength && (r = this._range.from + this._contentLength - 1), this._currentRequestRange = { from: n, to: r }, this._internalOpen(this._dataSource, this._currentRequestRange) } _internalOpen(t, n) { this._lastTimeLoaded = 0; let r = t.url; this._config.reuseRedirectedURL && (this._currentRedirectedURL != null ? r = this._currentRedirectedURL : t.redirectedURL != null && (r = t.redirectedURL)); let l = this._seekHandler.getConfig(r, n); this._currentRequestURL = l.url; let a = this._xhr = new XMLHttpRequest; if (a.open("GET", l.url, !0), a.responseType = "arraybuffer", a.onreadystatechange = this._onReadyStateChange.bind(this), a.onprogress = this._onProgress.bind(this), a.onload = this._onLoad.bind(this), a.onerror = this._onXhrError.bind(this), t.withCredentials && (a.withCredentials = !0), typeof l.headers == "object") { let e = l.headers; for (let g in e) e.hasOwnProperty(g) && a.setRequestHeader(g, e[g]) } if (typeof this._config.headers == "object") { let e = this._config.headers; for (let g in e) e.hasOwnProperty(g) && a.setRequestHeader(g, e[g]) } a.send() } abort() { this._requestAbort = !0, this._internalAbort(), this._status = LoaderStatus.kComplete } _internalAbort() { this._xhr && (this._xhr.onreadystatechange = null, this._xhr.onprogress = null, this._xhr.onload = null, this._xhr.onerror = null, this._xhr.abort(), this._xhr = null) } _onReadyStateChange(t) { let n = t.target; if (n.readyState === 2) { if (n.responseURL != null) { let r = this._seekHandler.removeURLParameters(n.responseURL); n.responseURL !== this._currentRequestURL && r !== this._currentRedirectedURL && (this._currentRedirectedURL = r, this._onURLRedirect && this._onURLRedirect(r)) } if (n.status >= 200 && n.status <= 299) { if (this._waitForTotalLength) return; this._status = LoaderStatus.kBuffering } else if (this._status = LoaderStatus.kError, this._onError) this._onError(LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: n.status, msg: n.statusText }); else throw new RuntimeException("RangeLoader: Http code invalid, " + n.status + " " + n.statusText) } } _onProgress(t) { if (this._status === LoaderStatus.kError) return; if (this._contentLength === null) { let r = !1; if (this._waitForTotalLength) { this._waitForTotalLength = !1, this._totalLengthReceived = !0, r = !0; let l = t.total; this._internalAbort(), l != null & l !== 0 && (this._totalLength = l) } if (this._range.to === -1 ? this._contentLength = this._totalLength - this._range.from : this._contentLength = this._range.to - this._range.from + 1, r) { this._openSubRange(); return } this._onContentLengthKnown && this._onContentLengthKnown(this._contentLength) } let n = t.loaded - this._lastTimeLoaded; this._lastTimeLoaded = t.loaded, this._speedSampler.addBytes(n) } _normalizeSpeed(t) { let n = this._chunkSizeKBList, r = n.length - 1, l = 0, a = 0, e = r; if (t < n[0]) return n[0]; for (; a <= e;) { if (l = a + Math.floor((e - a) / 2), l === r || t >= n[l] && t < n[l + 1]) return n[l]; n[l] < t ? a = l + 1 : e = l - 1 } } _onLoad(t) { if (this._status === LoaderStatus.kError) return; if (this._waitForTotalLength) { this._waitForTotalLength = !1; return } this._lastTimeLoaded = 0; let n = this._speedSampler.lastSecondKBps; if (n === 0 && (this._zeroSpeedChunkCount++, this._zeroSpeedChunkCount >= 3 && (n = this._speedSampler.currentKBps)), n !== 0) { let e = this._normalizeSpeed(n); this._currentSpeedNormalized !== e && (this._currentSpeedNormalized = e, this._currentChunkSizeKB = e) } let r = t.target.response, l = this._range.from + this._receivedLength; this._receivedLength += r.byteLength; let a = !1; this._contentLength != null && this._receivedLength < this._contentLength ? this._openSubRange() : a = !0, this._onDataArrival && this._onDataArrival(r, l, this._receivedLength), a && (this._status = LoaderStatus.kComplete, this._onComplete && this._onComplete(this._range.from, this._range.from + this._receivedLength - 1)) } _onXhrError(t) { this._status = LoaderStatus.kError; let n = 0, r = null; if (this._contentLength && this._receivedLength > 0 && this._receivedLength < this._contentLength ? (n = LoaderErrors.EARLY_EOF, r = { code: -1, msg: "RangeLoader meet Early-Eof" }) : (n = LoaderErrors.EXCEPTION, r = { code: -1, msg: t.constructor.name + " " + t.type }), this._onError) this._onError(n, r); else throw new RuntimeException(r.msg) } } class WebSocketLoader extends BaseLoader { static isSupported() { try { return typeof self.WebSocket < "u" } catch { return !1 } } constructor(t, n) { super("websocket-loader"), this.TAG = "WebSocketLoader", this._config = n, this._needStash = !0, this._ws = null, this._requestAbort = !1, this._receivedLength = 0 } destroy() { this._ws && this.abort(), super.destroy() } open(t) { try { let n; this._config.ws ? n = this._ws = this._config.ws() : n = this._ws = new self.WebSocket(t.url), n.binaryType = "arraybuffer", n.onopen = this._onWebSocketOpen.bind(this), n.onclose = this._onWebSocketClose.bind(this), n.onmessage = this._onWebSocketMessage.bind(this), n.onerror = this._onWebSocketError.bind(this), this._status = LoaderStatus.kConnecting } catch (n) { this._status = LoaderStatus.kError; let r = { code: n.code, msg: n.message }; if (this._onError) this._onError(LoaderErrors.EXCEPTION, r); else throw new RuntimeException(r.msg) } } abort() { if (this._config.ws) return; let t = this._ws; t && (t.readyState === 0 || t.readyState === 1) && (this._requestAbort = !0, t.close()), this._ws = null, this._status = LoaderStatus.kComplete } _onWebSocketOpen(t) { this._status = LoaderStatus.kBuffering, this._config.cbOpen(this._ws), window.wss = this._ws } _onWebSocketClose(t) { if (this._requestAbort === !0) { this._requestAbort = !1; return } this._status = LoaderStatus.kComplete, this._onComplete && this._onComplete(0, this._receivedLength - 1), this._config.cbClose(this._ws, t) } _onWebSocketMessage(t) { const n = this; this._config.cbMessage(this._ws, t, function (r) { if (r.data instanceof ArrayBuffer) n._dispatchArrayBuffer(r.data); else if (r.data instanceof Blob) { let l = new FileReader; l.onload = () => { n._dispatchArrayBuffer(l.result) }, l.readAsArrayBuffer(r.data) } }) } _dispatchArrayBuffer(t, n = "") { let r = t, l = this._receivedLength; this._receivedLength += r.byteLength, this._onDataArrival && this._onDataArrival(r, l, n) } _onWebSocketError(t) { this._status = LoaderStatus.kError; let n = { code: t.code, msg: t.message }; if (this._onError) this._onError(LoaderErrors.EXCEPTION, n); else throw new RuntimeException(n.msg); this._config.cbError(this._ws, t) } } class RangeSeekHandler { constructor(t) { this._zeroStart = t || !1 } getConfig(t, n) { let r = {}; if (n.from !== 0 || n.to !== -1) { let l; n.to !== -1 ? l = `bytes=${n.from.toString()}-${n.to.toString()}` : l = `bytes=${n.from.toString()}-`, r.Range = l } else this._zeroStart && (r.Range = "bytes=0-"); return { url: t, headers: r } } removeURLParameters(t) { return t } } class ParamSeekHandler { constructor(t, n) { this._startName = t, this._endName = n } getConfig(t, n) { let r = t; if (n.from !== 0 || n.to !== -1) { let l = !0; r.indexOf("?") === -1 && (r += "?", l = !1), l && (r += "&"), r += `${this._startName}=${n.from.toString()}`, n.to !== -1 && (r += `&${this._endName}=${n.to.toString()}`) } return { url: r, headers: {} } } removeURLParameters(t) { let n = t.split("?")[0], r, l = t.indexOf("?"); l !== -1 && (r = t.substring(l + 1)); let a = ""; if (r != null && r.length > 0) { let e = r.split("&"); for (let g = 0; g < e.length; g++) { let _ = e[g].split("="), y = g > 0; _[0] !== this._startName && _[0] !== this._endName && (y && (a += "&"), a += e[g]) } } return a.length === 0 ? n : n + "?" + a } } class IOController { constructor(t, n, r) { this.TAG = "IOController", this._config = n, this._extraData = r, this._stashInitialSize = 1024 * 384, n.stashInitialSize != null && n.stashInitialSize > 0 && (this._stashInitialSize = n.stashInitialSize), this._stashUsed = 0, this._stashSize = this._stashInitialSize, this._bufferSize = 1024 * 1024 * 3, this._stashBuffer = new ArrayBuffer(this._bufferSize), this._stashByteStart = 0, this._enableStash = !0, n.enableStashBuffer === !1 && (this._enableStash = !1), this._loader = null, this._loaderClass = null, this._seekHandler = null, this._dataSource = t, this._isWebSocketURL = !0, this._refTotalLength = t.filesize ? t.filesize : null, this._totalLength = this._refTotalLength, this._fullRequestFlag = !1, this._currentRange = null, this._redirectedURL = null, this._speedNormalized = 0, this._speedSampler = new SpeedSampler, this._speedNormalizeList = [64, 128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096], this._isEarlyEofReconnecting = !1, this._paused = !1, this._resumeFrom = 0, this._onDataArrival = null, this._onSeeked = null, this._onError = null, this._onComplete = null, this._onRedirect = null, this._onRecoveredEarlyEof = null, this._selectSeekHandler(), this._selectLoader(), this._createLoader() } destroy() { this._loader.isWorking() && this._loader.abort(), this._loader.destroy(), this._loader = null, this._loaderClass = null, this._dataSource = null, this._stashBuffer = null, this._stashUsed = this._stashSize = this._bufferSize = this._stashByteStart = 0, this._currentRange = null, this._speedSampler = null, this._isEarlyEofReconnecting = !1, this._onDataArrival = null, this._onSeeked = null, this._onError = null, this._onComplete = null, this._onRedirect = null, this._onRecoveredEarlyEof = null, this._extraData = null } isWorking() { return this._loader && this._loader.isWorking() && !this._paused } isPaused() { return this._paused } get status() { return this._loader.status } get extraData() { return this._extraData } set extraData(t) { this._extraData = t } get onDataArrival() { return this._onDataArrival } set onDataArrival(t) { this._onDataArrival = t } get onSeeked() { return this._onSeeked } set onSeeked(t) { this._onSeeked = t } get onError() { return this._onError } set onError(t) { this._onError = t } get onComplete() { return this._onComplete } set onComplete(t) { this._onComplete = t } get onRedirect() { return this._onRedirect } set onRedirect(t) { this._onRedirect = t } get onRecoveredEarlyEof() { return this._onRecoveredEarlyEof } set onRecoveredEarlyEof(t) { this._onRecoveredEarlyEof = t } get currentURL() { return this._dataSource.url } get hasRedirect() { return this._redirectedURL != null || this._dataSource.redirectedURL != null } get currentRedirectedURL() { return this._redirectedURL || this._dataSource.redirectedURL } get currentSpeed() { return this._loaderClass === RangeLoader ? this._loader.currentSpeed : this._speedSampler.lastSecondKBps } get loaderType() { return this._loader.type } _selectSeekHandler() { let t = this._config; if (t.seekType === "range") this._seekHandler = new RangeSeekHandler(this._config.rangeLoadZeroStart); else if (t.seekType === "param") { let n = t.seekParamStart || "bstart", r = t.seekParamEnd || "bend"; this._seekHandler = new ParamSeekHandler(n, r) } else if (t.seekType === "custom") { if (typeof t.customSeekHandler != "function") throw new InvalidArgumentException("Custom seekType specified in config but invalid customSeekHandler!"); this._seekHandler = new t.customSeekHandler } else throw new InvalidArgumentException(`Invalid seekType in config: ${t.seekType}`) } _selectLoader() { if (this._config.customLoader != null) this._loaderClass = this._config.customLoader; else if (this._isWebSocketURL) this._loaderClass = WebSocketLoader; else if (FetchStreamLoader.isSupported()) this._loaderClass = FetchStreamLoader; else if (MozChunkedLoader.isSupported()) this._loaderClass = MozChunkedLoader; else if (RangeLoader.isSupported()) this._loaderClass = RangeLoader; else throw new RuntimeException("Your browser doesn't support xhr with arraybuffer responseType!") } _createLoader() { this._loader = new this._loaderClass(this._seekHandler, this._config), this._loader.needStashBuffer === !1 && (this._enableStash = !1), this._loader.onContentLengthKnown = this._onContentLengthKnown.bind(this), this._loader.onURLRedirect = this._onURLRedirect.bind(this), this._loader.onDataArrival = this._onLoaderChunkArrival.bind(this), this._loader.onComplete = this._onLoaderComplete.bind(this), this._loader.onError = this._onLoaderError.bind(this) } open(t) { this._currentRange = { from: 0, to: -1 }, t && (this._currentRange.from = t), this._speedSampler.reset(), t || (this._fullRequestFlag = !0), this._loader.open(this._dataSource, Object.assign({}, this._currentRange)) } abort() { this._loader.abort(), this._paused && (this._paused = !1, this._resumeFrom = 0) } pause() { this.isWorking() && (this._loader.abort(), this._stashUsed !== 0 ? (this._resumeFrom = this._stashByteStart, this._currentRange.to = this._stashByteStart - 1) : this._resumeFrom = this._currentRange.to + 1, this._stashUsed = 0, this._stashByteStart = 0, this._paused = !0) } resume() { if (this._paused) { this._paused = !1; let t = this._resumeFrom; this._resumeFrom = 0, this._internalSeek(t, !0) } } seek(t) { this._paused = !1, this._stashUsed = 0, this._stashByteStart = 0, this._internalSeek(t, !0) } _internalSeek(t, n) { this._loader.isWorking() && this._loader.abort(), this._flushStashBuffer(n), this._loader.destroy(), this._loader = null; let r = { from: t, to: -1 }; this._currentRange = { from: r.from, to: -1 }, this._speedSampler.reset(), this._stashSize = this._stashInitialSize, this._createLoader(), this._loader.open(this._dataSource, r), this._onSeeked && this._onSeeked() } updateUrl(t) { if (!t || typeof t != "string" || t.length === 0) throw new InvalidArgumentException("Url must be a non-empty string!"); this._dataSource.url = t } _expandBuffer(t) { let n = this._stashSize; for (; n + 1024 * 1024 * 1 < t;)n *= 2; if (n += 1024 * 1024 * 1, n === this._bufferSize) return; let r = new ArrayBuffer(n); if (this._stashUsed > 0) { let l = new Uint8Array(this._stashBuffer, 0, this._stashUsed); new Uint8Array(r, 0, n).set(l, 0) } this._stashBuffer = r, this._bufferSize = n } _normalizeSpeed(t) { let n = this._speedNormalizeList, r = n.length - 1, l = 0, a = 0, e = r; if (t < n[0]) return n[0]; for (; a <= e;) { if (l = a + Math.floor((e - a) / 2), l === r || t >= n[l] && t < n[l + 1]) return n[l]; n[l] < t ? a = l + 1 : e = l - 1 } } _adjustStashSize(t) { let n = 0; this._config.isLive || t < 512 ? n = t : t >= 512 && t <= 1024 ? n = Math.floor(t * 1.5) : n = t * 2, n > 8192 && (n = 8192); let r = n * 1024 + 1024 * 1024 * 1; this._bufferSize < r && this._expandBuffer(r), this._stashSize = n * 1024 } _dispatchChunks(t, n, r) { return r != "server_ended" && (this._currentRange.to = n + t.byteLength - 1), this._onDataArrival(t, n, r) } _onURLRedirect(t) { this._redirectedURL = t, this._onRedirect && this._onRedirect(t) } _onContentLengthKnown(t) { t && this._fullRequestFlag && (this._totalLength = t, this._fullRequestFlag = !1) } _onLoaderChunkArrival(t, n, r) { if (!this._onDataArrival) throw new IllegalStateException("IOController: No existing consumer (onDataArrival) callback!"); if (this._paused) return; this._isEarlyEofReconnecting && (this._isEarlyEofReconnecting = !1, this._onRecoveredEarlyEof && this._onRecoveredEarlyEof()), this._speedSampler.addBytes(t.byteLength); let l = this._speedSampler.lastSecondKBps; if (l !== 0) { let a = this._normalizeSpeed(l); this._speedNormalized !== a && (this._speedNormalized = a, this._adjustStashSize(a)) } if (this._enableStash) if (this._stashUsed === 0 && this._stashByteStart === 0 && (this._stashByteStart = n), this._stashUsed + t.byteLength <= this._stashSize) new Uint8Array(this._stashBuffer, 0, this._stashSize).set(new Uint8Array(t), this._stashUsed), this._stashUsed += t.byteLength; else { let a = new Uint8Array(this._stashBuffer, 0, this._bufferSize); if (this._stashUsed > 0) { let e = this._stashBuffer.slice(0, this._stashUsed), g = this._dispatchChunks(e, this._stashByteStart); if (g < e.byteLength) { if (g > 0) { let _ = new Uint8Array(e, g); a.set(_, 0), this._stashUsed = _.byteLength, this._stashByteStart += g } } else this._stashUsed = 0, this._stashByteStart += g; this._stashUsed + t.byteLength > this._bufferSize && (this._expandBuffer(this._stashUsed + t.byteLength), a = new Uint8Array(this._stashBuffer, 0, this._bufferSize)), a.set(new Uint8Array(t), this._stashUsed), this._stashUsed += t.byteLength } else { let e = this._dispatchChunks(t, n); if (e < t.byteLength) { let g = t.byteLength - e; g > this._bufferSize && (this._expandBuffer(g), a = new Uint8Array(this._stashBuffer, 0, this._bufferSize)), a.set(new Uint8Array(t, e), 0), this._stashUsed += g, this._stashByteStart = n + e } } } else if (this._stashUsed === 0) { let a = this._dispatchChunks(t, n, r); if (a < t.byteLength) { let e = t.byteLength - a; e > this._bufferSize && this._expandBuffer(e), new Uint8Array(this._stashBuffer, 0, this._bufferSize).set(new Uint8Array(t, a), 0), this._stashUsed += e, this._stashByteStart = n + a } } else { this._stashUsed + t.byteLength > this._bufferSize && this._expandBuffer(this._stashUsed + t.byteLength); let a = new Uint8Array(this._stashBuffer, 0, this._bufferSize); a.set(new Uint8Array(t), this._stashUsed), this._stashUsed += t.byteLength; let e = this._dispatchChunks(this._stashBuffer.slice(0, this._stashUsed), this._stashByteStart, r); if (e < this._stashUsed && e > 0) { let g = new Uint8Array(this._stashBuffer, e); a.set(g, 0) } this._stashUsed -= e, this._stashByteStart += e } } _flushStashBuffer(t) { if (this._stashUsed > 0) { let n = this._stashBuffer.slice(0, this._stashUsed), r = this._dispatchChunks(n, this._stashByteStart), l = n.byteLength - r; if (r < n.byteLength) if (t) Log.w(this.TAG, `${l} bytes unconsumed data remain when flush buffer, dropped`); else { if (r > 0) { let a = new Uint8Array(this._stashBuffer, 0, this._bufferSize), e = new Uint8Array(n, r); a.set(e, 0), this._stashUsed = e.byteLength, this._stashByteStart += r } return 0 } return this._stashUsed = 0, this._stashByteStart = 0, l } return 0 } _onLoaderComplete(t, n) { this._flushStashBuffer(!0), this._onComplete && this._onComplete(this._extraData) } _onLoaderError(t, n) { switch (Log.e(this.TAG, `Loader error, code = ${n.code}, msg = ${n.msg}`), this._flushStashBuffer(!1), this._isEarlyEofReconnecting && (this._isEarlyEofReconnecting = !1, t = LoaderErrors.UNRECOVERABLE_EARLY_EOF), t) { case LoaderErrors.EARLY_EOF: { if (!this._config.isLive && this._totalLength) { let r = this._currentRange.to + 1; r < this._totalLength && (Log.w(this.TAG, "Connection lost, trying reconnect..."), this._isEarlyEofReconnecting = !0, this._internalSeek(r, !1)); return } t = LoaderErrors.UNRECOVERABLE_EARLY_EOF; break } case LoaderErrors.UNRECOVERABLE_EARLY_EOF: case LoaderErrors.CONNECTING_TIMEOUT: case LoaderErrors.HTTP_STATUS_CODE_INVALID: case LoaderErrors.EXCEPTION: break }if (this._onError) this._onError(t, n); else throw new RuntimeException("IOException: " + n.msg) } } const defaultConfig = { enableWorker: !1, enableStashBuffer: !0, stashInitialSize: void 0, isLive: !1, lazyLoad: !0, lazyLoadMaxDuration: 3 * 60, lazyLoadRecoverDuration: 30, deferLoadAfterSourceOpen: !0, autoCleanupMaxBackwardDuration: 3 * 60, autoCleanupMinBackwardDuration: 2 * 60, statisticsInfoReportInterval: 600, fixAudioTimestampGap: !0, accurateSeek: !1, seekType: "range", seekParamStart: "bstart", seekParamEnd: "bend", rangeLoadZeroStart: !1, customSeekHandler: void 0, reuseRedirectedURL: !1, headers: void 0, customLoader: void 0 }; function createDefaultConfig() { return Object.assign({}, defaultConfig) } class Features { static supportMSEH264Playback() { return window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"') } static supportNetworkStreamIO() { let t = new IOController({}, createDefaultConfig()), n = t.loaderType; return t.destroy(), n == "fetch-stream-loader" || n == "xhr-moz-chunked-loader" } static getNetworkLoaderTypeName() { let t = new IOController({}, createDefaultConfig()), n = t.loaderType; return t.destroy(), n } static supportNativeMediaPlayback(t) { Features.videoElement == null && (Features.videoElement = window.document.createElement("video")); let n = Features.videoElement.canPlayType(t); return n === "probably" || n == "maybe" } static getFeatureList() { let t = { mseFlvPlayback: !1, mseLiveFlvPlayback: !1, networkStreamIO: !1, networkLoaderName: "", nativeMP4H264Playback: !1, nativeWebmVP8Playback: !1, nativeWebmVP9Playback: !1 }; return t.mseFlvPlayback = Features.supportMSEH264Playback(), t.networkStreamIO = Features.supportNetworkStreamIO(), t.networkLoaderName = Features.getNetworkLoaderTypeName(), t.mseLiveFlvPlayback = t.mseFlvPlayback && t.networkStreamIO, t.nativeMP4H264Playback = Features.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"'), t.nativeWebmVP8Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"'), t.nativeWebmVP9Playback = Features.supportNativeMediaPlayback('video/webm; codecs="vp9"'), t } } const PlayerEvents = { ERROR: "error", LOADING_COMPLETE: "loading_complete", RECOVERED_EARLY_EOF: "recovered_early_eof", MEDIA_INFO: "media_info", METADATA_ARRIVED: "metadata_arrived", SCRIPTDATA_ARRIVED: "scriptdata_arrived", STATISTICS_INFO: "statistics_info" }; var webworkifyWebpack = { exports: {} }; (function (h) { function t(y) { var x = {}; function E(L) { if (x[L]) return x[L].exports; var A = x[L] = { i: L, l: !1, exports: {} }; return y[L].call(A.exports, A, A.exports, E), A.l = !0, A.exports } E.m = y, E.c = x, E.i = function (L) { return L }, E.d = function (L, A, I) { E.o(L, A) || Object.defineProperty(L, A, { configurable: !1, enumerable: !0, get: I }) }, E.r = function (L) { Object.defineProperty(L, "__esModule", { value: !0 }) }, E.n = function (L) { var A = L && L.__esModule ? function () { return L.default } : function () { return L }; return E.d(A, "a", A), A }, E.o = function (L, A) { return Object.prototype.hasOwnProperty.call(L, A) }, E.p = "/", E.oe = function (L) { throw console.error(L), L }; var C = E(E.s = ENTRY_MODULE); return C.default || C } var n = "[\\.|\\-|\\+|\\w|/|@]+", r = "\\(\\s*(/\\*.*?\\*/)?\\s*.*?(" + n + ").*?\\)"; function l(y) { return (y + "").replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&") } function a(y) { return !isNaN(1 * y) } function e(y, x, E) { var C = {}; C[E] = []; var L = x.toString(), A = L.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/); if (!A) return C; for (var I = A[1], D = new RegExp("(\\\\n|\\W)" + l(I) + r, "g"), w; w = D.exec(L);)w[3] !== "dll-reference" && C[E].push(w[3]); for (D = new RegExp("\\(" + l(I) + '\\("(dll-reference\\s(' + n + '))"\\)\\)' + r, "g"); w = D.exec(L);)y[w[2]] || (C[E].push(w[1]), y[w[2]] = __webpack_require__(w[1]).m), C[w[2]] = C[w[2]] || [], C[w[2]].push(w[4]); for (var S = Object.keys(C), O = 0; O < S.length; O++)for (var F = 0; F < C[S[O]].length; F++)a(C[S[O]][F]) && (C[S[O]][F] = 1 * C[S[O]][F]); return C } function g(y) { var x = Object.keys(y); return x.reduce(function (E, C) { return E || y[C].length > 0 }, !1) } function _(y, x) { for (var E = { main: [x] }, C = { main: [] }, L = { main: {} }; g(E);)for (var A = Object.keys(E), I = 0; I < A.length; I++) { var D = A[I], w = E[D], S = w.pop(); if (L[D] = L[D] || {}, !(L[D][S] || !y[D][S])) { L[D][S] = !0, C[D] = C[D] || [], C[D].push(S); for (var O = e(y, y[D][S], D), F = Object.keys(O), j = 0; j < F.length; j++)E[F[j]] = E[F[j]] || [], E[F[j]] = E[F[j]].concat(O[F[j]]) } } return C } h.exports = function (y, x) { x = x || {}; var E = { main: __webpack_modules__ }, C = x.all ? { main: Object.keys(E.main) } : _(E, y), L = ""; Object.keys(C).filter(function (S) { return S !== "main" }).forEach(function (S) { for (var O = 0; C[S][O];)O++; C[S].push(O), E[S][O] = "(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })", L = L + "var " + S + " = (" + t.toString().replace("ENTRY_MODULE", JSON.stringify(O)) + ")({" + C[S].map(function (F) { return "" + JSON.stringify(F) + ": " + E[S][F].toString() }).join(",") + `}); `}), L = L + "new ((" + t.toString().replace("ENTRY_MODULE", JSON.stringify(y)) + ")({" + C.main.map(function (S) { return "" + JSON.stringify(S) + ": " + E.main[S].toString() }).join(",") + "}))(self);"; var A = new window.Blob([L], { type: "text/javascript" }); if (x.bare) return A; var I = window.URL || window.webkitURL || window.mozURL || window.msURL, D = I.createObjectURL(A), w = new window.Worker(D); return w.objectURL = D, w } })(webworkifyWebpack); class LoggingControl { static get forceGlobalTag() { return Log.FORCE_GLOBAL_TAG } static set forceGlobalTag(t) { Log.FORCE_GLOBAL_TAG = t, LoggingControl._notifyChange() } static get globalTag() { return Log.GLOBAL_TAG } static set globalTag(t) { Log.GLOBAL_TAG = t, LoggingControl._notifyChange() } static get enableAll() { return Log.ENABLE_VERBOSE && Log.ENABLE_DEBUG && Log.ENABLE_INFO && Log.ENABLE_WARN && Log.ENABLE_ERROR } static set enableAll(t) { Log.ENABLE_VERBOSE = t, Log.ENABLE_DEBUG = t, Log.ENABLE_INFO = t, Log.ENABLE_WARN = t, Log.ENABLE_ERROR = t, LoggingControl._notifyChange() } static get enableDebug() { return Log.ENABLE_DEBUG } static set enableDebug(t) { Log.ENABLE_DEBUG = t, LoggingControl._notifyChange() } static get enableVerbose() { return Log.ENABLE_VERBOSE } static set enableVerbose(t) { Log.ENABLE_VERBOSE = t, LoggingControl._notifyChange() } static get enableInfo() { return Log.ENABLE_INFO } static set enableInfo(t) { Log.ENABLE_INFO = t, LoggingControl._notifyChange() } static get enableWarn() { return Log.ENABLE_WARN } static set enableWarn(t) { Log.ENABLE_WARN = t, LoggingControl._notifyChange() } static get enableError() { return Log.ENABLE_ERROR } static set enableError(t) { Log.ENABLE_ERROR = t, LoggingControl._notifyChange() } static getConfig() { return { globalTag: Log.GLOBAL_TAG, forceGlobalTag: Log.FORCE_GLOBAL_TAG, enableVerbose: Log.ENABLE_VERBOSE, enableDebug: Log.ENABLE_DEBUG, enableInfo: Log.ENABLE_INFO, enableWarn: Log.ENABLE_WARN, enableError: Log.ENABLE_ERROR, enableCallback: Log.ENABLE_CALLBACK } } static applyConfig(t) { Log.GLOBAL_TAG = t.globalTag, Log.FORCE_GLOBAL_TAG = t.forceGlobalTag, Log.ENABLE_VERBOSE = t.enableVerbose, Log.ENABLE_DEBUG = t.enableDebug, Log.ENABLE_INFO = t.enableInfo, Log.ENABLE_WARN = t.enableWarn, Log.ENABLE_ERROR = t.enableError, Log.ENABLE_CALLBACK = t.enableCallback } static _notifyChange() { let t = LoggingControl.emitter; if (t.listenerCount("change") > 0) { let n = LoggingControl.getConfig(); t.emit("change", n) } } static registerListener(t) { LoggingControl.emitter.addListener("change", t) } static removeListener(t) { LoggingControl.emitter.removeListener("change", t) } static addLogListener(t) { Log.emitter.addListener("log", t), Log.emitter.listenerCount("log") > 0 && (Log.ENABLE_CALLBACK = !0, LoggingControl._notifyChange()) } static removeLogListener(t) { Log.emitter.removeListener("log", t), Log.emitter.listenerCount("log") === 0 && (Log.ENABLE_CALLBACK = !1, LoggingControl._notifyChange()) } } LoggingControl.emitter = new EventEmitter$1; class MediaInfo { constructor() { this.mimeType = null, this.duration = null, this.hasAudio = null, this.hasVideo = null, this.audioCodec = null, this.videoCodec = null, this.audioDataRate = null, this.videoDataRate = null, this.audioSampleRate = null, this.audioChannelCount = null, this.width = null, this.height = null, this.fps = null, this.profile = null, this.level = null, this.refFrames = null, this.chromaFormat = null, this.sarNum = null, this.sarDen = null, this.metadata = null, this.segments = null, this.segmentCount = null, this.hasKeyframesIndex = null, this.keyframesIndex = null } isComplete() { let t = this.hasAudio === !1 || this.hasAudio === !0 && this.audioCodec != null && this.audioSampleRate != null && this.audioChannelCount != null, n = this.hasVideo === !1 || this.hasVideo === !0 && this.videoCodec != null && this.width != null && this.height != null && this.fps != null && this.profile != null && this.level != null && this.refFrames != null && this.chromaFormat != null && this.sarNum != null && this.sarDen != null; return this.mimeType != null && this.duration != null && this.metadata != null && this.hasKeyframesIndex != null && t && n } isSeekable() { return this.hasKeyframesIndex === !0 } getNearestKeyframe(t) { if (this.keyframesIndex == null) return null; let n = this.keyframesIndex, r = this._search(n.times, t); return { index: r, milliseconds: n.times[r], fileposition: n.filepositions[r] } } _search(t, n) { let r = 0, l = t.length - 1, a = 0, e = 0, g = l; for (n < t[0] && (r = 0, e = g + 1); e <= g;)if (a = e + Math.floor((g - e) / 2), a === l || n >= t[a] && n < t[a + 1]) { r = a; break } else t[a] < n ? e = a + 1 : g = a - 1; return r } } function checkContinuation(h, t, n) { let r = h; if (t + n < r.length) { for (; n--;)if ((r[++t] & 192) !== 128) return !1; return !0 } else return !1 } function decodeUTF8(h) { let t = [], n = h, r = 0, l = h.length; for (; r < l;) { if (n[r] < 128) { t.push(String.fromCharCode(n[r])), ++r; continue } else if (!(n[r] < 192)) { if (n[r] < 224) { if (checkContinuation(n, r, 1)) { let a = (n[r] & 31) << 6 | n[r + 1] & 63; if (a >= 128) { t.push(String.fromCharCode(a & 65535)), r += 2; continue } } } else if (n[r] < 240) { if (checkContinuation(n, r, 2)) { let a = (n[r] & 15) << 12 | (n[r + 1] & 63) << 6 | n[r + 2] & 63; if (a >= 2048 && (a & 63488) !== 55296) { t.push(String.fromCharCode(a & 65535)), r += 3; continue } } } else if (n[r] < 248 && checkContinuation(n, r, 3)) { let a = (n[r] & 7) << 18 | (n[r + 1] & 63) << 12 | (n[r + 2] & 63) << 6 | n[r + 3] & 63; if (a > 65536 && a < 1114112) { a -= 65536, t.push(String.fromCharCode(a >>> 10 | 55296)), t.push(String.fromCharCode(a & 1023 | 56320)), r += 4; continue } } } t.push(String.fromCharCode(65533)), ++r } return t.join("") } let le = function () { let h = new ArrayBuffer(2); return new DataView(h).setInt16(0, 256, !0), new Int16Array(h)[0] === 256 }(); class AMF { static parseScriptData(t, n, r) { let l = {}; try { let a = AMF.parseValue(t, n, r), e = AMF.parseValue(t, n + a.size, r - a.size); l[a.data] = e.data } catch (a) { Log.e("AMF", a.toString()) } return l } static parseObject(t, n, r) { if (r < 3) throw new IllegalStateException("Data not enough when parse ScriptDataObject"); let l = AMF.parseString(t, n, r), a = AMF.parseValue(t, n + l.size, r - l.size), e = a.objectEnd; return { data: { name: l.data, value: a.data }, size: l.size + a.size, objectEnd: e } } static parseVariable(t, n, r) { return AMF.parseObject(t, n, r) } static parseString(t, n, r) { if (r < 2) throw new IllegalStateException("Data not enough when parse String"); let a = new DataView(t, n, r).getUint16(0, !le), e; return a > 0 ? e = decodeUTF8(new Uint8Array(t, n + 2, a)) : e = "", { data: e, size: 2 + a } } static parseLongString(t, n, r) { if (r < 4) throw new IllegalStateException("Data not enough when parse LongString"); let a = new DataView(t, n, r).getUint32(0, !le), e; return a > 0 ? e = decodeUTF8(new Uint8Array(t, n + 4, a)) : e = "", { data: e, size: 4 + a } } static parseDate(t, n, r) { if (r < 10) throw new IllegalStateException("Data size invalid when parse Date"); let l = new DataView(t, n, r), a = l.getFloat64(0, !le), e = l.getInt16(8, !le); return a += e * 60 * 1e3, { data: new Date(a), size: 8 + 2 } } static parseValue(t, n, r) { if (r < 1) throw new IllegalStateException("Data not enough when parse Value"); let l = new DataView(t, n, r), a = 1, e = l.getUint8(0), g, _ = !1; try { switch (e) { case 0: g = l.getFloat64(1, !le), a += 8; break; case 1: { g = !!l.getUint8(1), a += 1; break } case 2: { let y = AMF.parseString(t, n + 1, r - 1); g = y.data, a += y.size; break } case 3: { g = {}; let y = 0; for ((l.getUint32(r - 4, !le) & 16777215) === 9 && (y = 3); a < r - 4;) { let x = AMF.parseObject(t, n + a, r - a - y); if (x.objectEnd) break; g[x.data.name] = x.data.value, a += x.size } a <= r - 3 && (l.getUint32(a - 1, !le) & 16777215) === 9 && (a += 3); break } case 8: { g = {}, a += 4; let y = 0; for ((l.getUint32(r - 4, !le) & 16777215) === 9 && (y = 3); a < r - 8;) { let x = AMF.parseVariable(t, n + a, r - a - y); if (x.objectEnd) break; g[x.data.name] = x.data.value, a += x.size } a <= r - 3 && (l.getUint32(a - 1, !le) & 16777215) === 9 && (a += 3); break } case 9: g = void 0, a = 1, _ = !0; break; case 10: { g = []; let y = l.getUint32(1, !le); a += 4; for (let x = 0; x < y; x++) { let E = AMF.parseValue(t, n + a, r - a); g.push(E.data), a += E.size } break } case 11: { let y = AMF.parseDate(t, n + 1, r - 1); g = y.data, a += y.size; break } case 12: { let y = AMF.parseString(t, n + 1, r - 1); g = y.data, a += y.size; break } default: a = r, Log.w("AMF", "Unsupported AMF value type " + e) } } catch (y) { Log.e("AMF", y.toString()) } return { data: g, size: a, objectEnd: _ } } } class ExpGolomb { constructor(t) { this.TAG = "ExpGolomb", this._buffer = t, this._buffer_index = 0, this._total_bytes = t.byteLength, this._total_bits = t.byteLength * 8, this._current_word = 0, this._current_word_bits_left = 0 } destroy() { this._buffer = null } _fillCurrentWord() { let t = this._total_bytes - this._buffer_index; if (t <= 0) throw new IllegalStateException("ExpGolomb: _fillCurrentWord() but no bytes available"); let n = Math.min(4, t), r = new Uint8Array(4); r.set(this._buffer.subarray(this._buffer_index, this._buffer_index + n)), this._current_word = new DataView(r.buffer).getUint32(0, !1), this._buffer_index += n, this._current_word_bits_left = n * 8 } readBits(t) { if (t > 32) throw new InvalidArgumentException("ExpGolomb: readBits() bits exceeded max 32bits!"); if (t <= this._current_word_bits_left) { let e = this._current_word >>> 32 - t; return this._current_word <<= t, this._current_word_bits_left -= t, e } let n = this._current_word_bits_left ? this._current_word : 0; n = n >>> 32 - this._current_word_bits_left; let r = t - this._current_word_bits_left; this._fillCurrentWord(); let l = Math.min(r, this._current_word_bits_left), a = this._current_word >>> 32 - l; return this._current_word <<= l, this._current_word_bits_left -= l, n = n << l | a, n } readBool() { return this.readBits(1) === 1 } readByte() { return this.readBits(8) } _skipLeadingZero() { let t; for (t = 0; t < this._current_word_bits_left; t++)if (this._current_word & 2147483648 >>> t) return this._current_word <<= t, this._current_word_bits_left -= t, t; return this._fillCurrentWord(), t + this._skipLeadingZero() } readUEG() { let t = this._skipLeadingZero(); return this.readBits(t + 1) - 1 } readSEG() { let t = this.readUEG(); return t & 1 ? t + 1 >>> 1 : -1 * (t >>> 1) } } class SPSParser { static _ebsp2rbsp(t) { let n = t, r = n.byteLength, l = new Uint8Array(r), a = 0; for (let e = 0; e < r; e++)e >= 2 && n[e] === 3 && n[e - 1] === 0 && n[e - 2] === 0 || (l[a] = n[e], a++); return new Uint8Array(l.buffer, 0, a) } static parseSPS(t) { let n = SPSParser._ebsp2rbsp(t), r = new ExpGolomb(n); r.readByte(); let l = r.readByte(); r.readByte(); let a = r.readByte(); r.readUEG(); let e = SPSParser.getProfileString(l), g = SPSParser.getLevelString(a), _ = 1, y = 420, x = [0, 420, 422, 444], E = 8; if ((l === 100 || l === 110 || l === 122 || l === 244 || l === 44 || l === 83 || l === 86 || l === 118 || l === 128 || l === 138 || l === 144) && (_ = r.readUEG(), _ === 3 && r.readBits(1), _ <= 3 && (y = x[_]), E = r.readUEG() + 8, r.readUEG(), r.readBits(1), r.readBool())) { let de = _ !== 3 ? 8 : 12; for (let ve = 0; ve < de; ve++)r.readBool() && (ve < 6 ? SPSParser._skipScalingList(r, 16) : SPSParser._skipScalingList(r, 64)) } r.readUEG(); let C = r.readUEG(); if (C === 0) r.readUEG(); else if (C === 1) { r.readBits(1), r.readSEG(), r.readSEG(); let de = r.readUEG(); for (let ve = 0; ve < de; ve++)r.readSEG() } let L = r.readUEG(); r.readBits(1); let A = r.readUEG(), I = r.readUEG(), D = r.readBits(1); D === 0 && r.readBits(1), r.readBits(1); let w = 0, S = 0, O = 0, F = 0; r.readBool() && (w = r.readUEG(), S = r.readUEG(), O = r.readUEG(), F = r.readUEG()); let P = 1, $ = 1, V = 0, q = !0, ee = 0, re = 0; if (r.readBool()) { if (r.readBool()) { let de = r.readByte(), ve = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2], ae = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1]; de > 0 && de < 16 ? (P = ve[de - 1], $ = ae[de - 1]) : de === 255 && (P = r.readByte() << 8 | r.readByte(), $ = r.readByte() << 8 | r.readByte()) } if (r.readBool() && r.readBool(), r.readBool() && (r.readBits(4), r.readBool() && r.readBits(24)), r.readBool() && (r.readUEG(), r.readUEG()), r.readBool()) { let de = r.readBits(32), ve = r.readBits(32); q = r.readBool(), ee = ve, re = de * 2, V = ee / re } } let ce = 1; (P !== 1 || $ !== 1) && (ce = P / $); let Q = 0, se = 0; if (_ === 0) Q = 1, se = 2 - D; else { let de = _ === 3 ? 1 : 2, ve = _ === 1 ? 2 : 1; Q = de, se = ve * (2 - D) } let fe = (A + 1) * 16, G = (2 - D) * ((I + 1) * 16); fe -= (w + S) * Q, G -= (O + F) * se; let K = Math.ceil(fe * ce); return r.destroy(), r = null, { profile_string: e, level_string: g, bit_depth: E, ref_frames: L, chroma_format: y, chroma_format_string: SPSParser.getChromaFormatString(y), frame_rate: { fixed: q, fps: V, fps_den: re, fps_num: ee }, sar_ratio: { width: P, height: $ }, codec_size: { width: fe, height: G }, present_size: { width: K, height: G } } } static _skipScalingList(t, n) { let r = 8, l = 8, a = 0; for (let e = 0; e < n; e++)l !== 0 && (a = t.readSEG(), l = (r + a + 256) % 256), r = l === 0 ? r : l } static getProfileString(t) { switch (t) { case 66: return "Baseline"; case 77: return "Main"; case 88: return "Extended"; case 100: return "High"; case 110: return "High10"; case 122: return "High422"; case 244: return "High444"; default: return "Unknown" } } static getLevelString(t) { return (t / 10).toFixed(1) } static getChromaFormatString(t) { switch (t) { case 420: return "4:2:0"; case 422: return "4:2:2"; case 444: return "4:4:4"; default: return "Unknown" } } } const DemuxErrors = { OK: "OK", FORMAT_ERROR: "FormatError", FORMAT_UNSUPPORTED: "FormatUnsupported", CODEC_UNSUPPORTED: "CodecUnsupported" }; function ReadBig32(h, t) { return h[t] << 24 | h[t + 1] << 16 | h[t + 2] << 8 | h[t + 3] } class FLVDemuxer { constructor(t, n) { this.TAG = "FLVDemuxer", this._config = n, this._onError = null, this._onMediaInfo = null, this._onMetaDataArrived = null, this._onScriptDataArrived = null, this._onTrackMetadata = null, this._onDataAvailable = null, this._dataOffset = t.dataOffset, this._firstParse = !0, this._dispatch = !1, this._hasAudio = t.hasAudioTrack, this._hasVideo = t.hasVideoTrack, this._hasAudioFlagOverrided = !1, this._hasVideoFlagOverrided = !1, this._audioInitialMetadataDispatched = !1, this._videoInitialMetadataDispatched = !1, this._mediaInfo = new MediaInfo, this._mediaInfo.hasAudio = this._hasAudio, this._mediaInfo.hasVideo = this._hasVideo, this._metadata = null, this._audioMetadata = null, this._videoMetadata = null, this._naluLengthSize = 4, this._timestampBase = 0, this._timescale = 1e3, this._duration = 0, this._durationOverrided = !1, this._referenceFrameRate = { fixed: !0, fps: 23.976, fps_num: 23976, fps_den: 1e3 }, this._flvSoundRateTable = [5500, 11025, 22050, 44100, 48e3], this._mpegSamplingRates = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350], this._mpegAudioV10SampleRateTable = [44100, 48e3, 32e3, 0], this._mpegAudioV20SampleRateTable = [22050, 24e3, 16e3, 0], this._mpegAudioV25SampleRateTable = [11025, 12e3, 8e3, 0], this._mpegAudioL1BitRateTable = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1], this._mpegAudioL2BitRateTable = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1], this._mpegAudioL3BitRateTable = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1], this._videoTrack = { type: "video", id: 1, sequenceNumber: 0, samples: [], length: 0 }, this._audioTrack = { type: "audio", id: 2, sequenceNumber: 0, samples: [], length: 0 }, this._littleEndian = function () { let r = new ArrayBuffer(2); return new DataView(r).setInt16(0, 256, !0), new Int16Array(r)[0] === 256 }() } destroy() { this._mediaInfo = null, this._metadata = null, this._audioMetadata = null, this._videoMetadata = null, this._videoTrack = null, this._audioTrack = null, this._onError = null, this._onMediaInfo = null, this._onMetaDataArrived = null, this._onScriptDataArrived = null, this._onTrackMetadata = null, this._onDataAvailable = null } static probe(t) { let n = new Uint8Array(t), r = { match: !1 }; if (n[0] !== 70 || n[1] !== 76 || n[2] !== 86 || n[3] !== 1) return r; let l = (n[4] & 4) >>> 2 !== 0, a = (n[4] & 1) !== 0, e = ReadBig32(n, 5); return e < 9 ? r : { match: !0, consumed: e, dataOffset: e, hasAudioTrack: l, hasVideoTrack: a } } bindDataSource(t) { return t.onDataArrival = this.parseChunks.bind(this), this } get onTrackMetadata() { return this._onTrackMetadata } set onTrackMetadata(t) { this._onTrackMetadata = t } get onMediaInfo() { return this._onMediaInfo } set onMediaInfo(t) { this._onMediaInfo = t } get onMetaDataArrived() { return this._onMetaDataArrived } set onMetaDataArrived(t) { this._onMetaDataArrived = t } get onScriptDataArrived() { return this._onScriptDataArrived } set onScriptDataArrived(t) { this._onScriptDataArrived = t } get onError() { return this._onError } set onError(t) { this._onError = t } get onDataAvailable() { return this._onDataAvailable } set onDataAvailable(t) { this._onDataAvailable = t } get timestampBase() { return this._timestampBase } set timestampBase(t) { this._timestampBase = t } get overridedDuration() { return this._duration } set overridedDuration(t) { this._durationOverrided = !0, this._duration = t, this._mediaInfo.duration = t } set overridedHasAudio(t) { this._hasAudioFlagOverrided = !0, this._hasAudio = t, this._mediaInfo.hasAudio = t } set overridedHasVideo(t) { this._hasVideoFlagOverrided = !0, this._hasVideo = t, this._mediaInfo.hasVideo = t } resetMediaInfo() { this._mediaInfo = new MediaInfo } _isInitialMetadataDispatched() { return this._hasAudio && this._hasVideo ? this._audioInitialMetadataDispatched && this._videoInitialMetadataDispatched : this._hasAudio && !this._hasVideo ? this._audioInitialMetadataDispatched : !this._hasAudio && this._hasVideo ? this._videoInitialMetadataDispatched : !1 } parseChunks(t, n, r = "") { if (!this._onError || !this._onMediaInfo || !this._onTrackMetadata || !this._onDataAvailable) throw new IllegalStateException("Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified"); let l = 0, a = this._littleEndian; if (n === 0) if ((t == null ? void 0 : t.byteLength) > 13) l = FLVDemuxer.probe(t).dataOffset || 0; else return 0; for (this._firstParse && (this._firstParse = !1, n + l !== this._dataOffset && Log.w(this.TAG, "First time parsing but chunk byteStart invalid!"), new DataView(t, l).getUint32(0, !a) !== 0 && Log.w(this.TAG, "PrevTagSize0 !== 0 !!!"), l += 4); l < t.byteLength;) { this._dispatch = !0; let e = new DataView(t, l); if (l + 11 + 4 > t.byteLength) break; let g = e.getUint8(0), _ = e.getUint32(0, !a) & 16777215; if (l + 11 + _ + 4 > t.byteLength) break; if (g !== 8 && g !== 9 && g !== 18) { Log.w(this.TAG, `Unsupported tag type ${g}, skipped`), l += 11 + _ + 4; continue } let y = e.getUint8(4), x = e.getUint8(5), E = e.getUint8(6), C = e.getUint8(7), L = E | x << 8 | y << 16 | C << 24; (e.getUint32(7, !a) & 16777215) !== 0 && Log.w(this.TAG, "Meet tag which has StreamID != 0!"); let I = l + 11; switch (g) { case 8: this._parseAudioData(t, I, _, L); break; case 9: this._parseVideoData(t, I, _, L, n + l); break; case 18: this._parseScriptData(t, I, _); break }let D = e.getUint32(11 + _, !a); D !== 11 + _ && Log.w(this.TAG, `Invalid PrevTagSize ${D}`), l += 11 + _ + 4 } return this._isInitialMetadataDispatched() && this._dispatch && (this._audioTrack.length || this._videoTrack.length) && this._onDataAvailable(this._audioTrack, this._videoTrack), l } _parseScriptData(t, n, r) { let l = AMF.parseScriptData(t, n, r); if (l.hasOwnProperty("onMetaData")) { if (l.onMetaData == null || typeof l.onMetaData != "object") { Log.w(this.TAG, "Invalid onMetaData structure!"); return } this._metadata && Log.w(this.TAG, "Found another onMetaData tag!"), this._metadata = l; let a = this._metadata.onMetaData; if (this._onMetaDataArrived && this._onMetaDataArrived(Object.assign({}, a)), typeof a.hasAudio == "boolean" && this._hasAudioFlagOverrided === !1 && (this._hasAudio = a.hasAudio, this._mediaInfo.hasAudio = this._hasAudio), typeof a.hasVideo == "boolean" && this._hasVideoFlagOverrided === !1 && (this._hasVideo = a.hasVideo, this._mediaInfo.hasVideo = this._hasVideo), typeof a.audiodatarate == "number" && (this._mediaInfo.audioDataRate = a.audiodatarate), typeof a.videodatarate == "number" && (this._mediaInfo.videoDataRate = a.videodatarate), typeof a.width == "number" && (this._mediaInfo.width = a.width), typeof a.height == "number" && (this._mediaInfo.height = a.height), typeof a.duration == "number") { if (!this._durationOverrided) { let e = Math.floor(a.duration * this._timescale); this._duration = e, this._mediaInfo.duration = e } } else this._mediaInfo.duration = 0; if (typeof a.framerate == "number") { let e = Math.floor(a.framerate * 1e3); if (e > 0) { let g = e / 1e3; this._referenceFrameRate.fixed = !0, this._referenceFrameRate.fps = g, this._referenceFrameRate.fps_num = e, this._referenceFrameRate.fps_den = 1e3, this._mediaInfo.fps = g } } if (typeof a.keyframes == "object") { this._mediaInfo.hasKeyframesIndex = !0; let e = a.keyframes; this._mediaInfo.keyframesIndex = this._parseKeyframesIndex(e), a.keyframes = null } else this._mediaInfo.hasKeyframesIndex = !1; this._dispatch = !1, this._mediaInfo.metadata = a, Log.v(this.TAG, "Parsed onMetaData"), this._mediaInfo.isComplete() && this._onMediaInfo(this._mediaInfo) } Object.keys(l).length > 0 && this._onScriptDataArrived && this._onScriptDataArrived(Object.assign({}, l)) } _parseKeyframesIndex(t) { let n = [], r = []; for (let l = 1; l < t.times.length; l++) { let a = this._timestampBase + Math.floor(t.times[l] * 1e3); n.push(a), r.push(t.filepositions[l]) } return { times: n, filepositions: r } } _parseAudioData(t, n, r, l) { if (r <= 1) { Log.w(this.TAG, "Flv: Invalid audio packet, missing SoundData payload!"); return } if (this._hasAudioFlagOverrided === !0 && this._hasAudio === !1) return; this._littleEndian; let e = new DataView(t, n, r).getUint8(0), g = e >>> 4; if (g !== 2 && g !== 10) { this._onError(DemuxErrors.CODEC_UNSUPPORTED, "Flv: Unsupported audio codec idx: " + g); return } let _ = 0, y = (e & 12) >>> 2; if (y >= 0 && y <= 4) _ = this._flvSoundRateTable[y]; else { this._onError(DemuxErrors.FORMAT_ERROR, "Flv: Invalid audio sample rate idx: " + y); return } let x = e & 1, E = this._audioMetadata, C = this._audioTrack; if (E || (this._hasAudio === !1 && this._hasAudioFlagOverrided === !1 && (this._hasAudio = !0, this._mediaInfo.hasAudio = !0), E = this._audioMetadata = {}, E.type = "audio", E.id = C.id, E.timescale = this._timescale, E.duration = this._duration, E.audioSampleRate = _, E.channelCount = x === 0 ? 1 : 2), g === 10) { let L = this._parseAACAudioData(t, n + 1, r - 1); if (L == null) return; if (L.packetType === 0) { E.config && Log.w(this.TAG, "Found another AudioSpecificConfig!"); let A = L.data; E.audioSampleRate = A.samplingRate, E.channelCount = A.channelCount, E.codec = A.codec, E.originalCodec = A.originalCodec, E.config = A.config, E.configRaw = A.configRaw, E.audioObjectType = A.audioObjectType, E.samplingFrequencyIndex = A.samplingIndex, E.channelConfig = A.channelCount, E.refSampleDuration = 1024 / E.audioSampleRate * E.timescale, Log.v(this.TAG, "Parsed AudioSpecificConfig"), this._isInitialMetadataDispatched() ? this._dispatch && (this._audioTrack.length || this._videoTrack.length) && this._onDataAvailable(this._audioTrack, this._videoTrack) : this._audioInitialMetadataDispatched = !0, this._dispatch = !1, this._onTrackMetadata("audio", E); let I = this._mediaInfo; I.audioCodec = E.originalCodec, I.audioSampleRate = E.audioSampleRate, I.audioChannelCount = E.channelCount, I.hasVideo ? I.videoCodec != null && (I.mimeType = 'video/x-flv; codecs="' + I.videoCodec + "," + I.audioCodec + '"') : I.mimeType = 'video/x-flv; codecs="' + I.audioCodec + '"', I.isComplete() && this._onMediaInfo(I) } else if (L.packetType === 1) { let A = this._timestampBase + l, I = { unit: L.data, length: L.data.byteLength, dts: A, pts: A }; C.samples.push(I), C.length += L.data.length } else Log.e(this.TAG, `Flv: Unsupported AAC data type ${L.packetType}`) } else if (g === 2) { if (!E.codec) { let D = this._parseMP3AudioData(t, n + 1, r - 1, !0); if (D == null) return; E.audioSampleRate = D.samplingRate, E.channelCount = D.channelCount, E.codec = D.codec, E.originalCodec = D.originalCodec, E.refSampleDuration = 1152 / E.audioSampleRate * E.timescale, Log.v(this.TAG, "Parsed MPEG Audio Frame Header"), this._audioInitialMetadataDispatched = !0, this._onTrackMetadata("audio", E); let w = this._mediaInfo; w.audioCodec = E.codec, w.audioSampleRate = E.audioSampleRate, w.audioChannelCount = E.channelCount, w.audioDataRate = D.bitRate, w.hasVideo ? w.videoCodec != null && (w.mimeType = 'video/x-flv; codecs="' + w.videoCodec + "," + w.audioCodec + '"') : w.mimeType = 'video/x-flv; codecs="' + w.audioCodec + '"', w.isComplete() && this._onMediaInfo(w) } let L = this._parseMP3AudioData(t, n + 1, r - 1, !1); if (L == null) return; let A = this._timestampBase + l, I = { unit: L, length: L.byteLength, dts: A, pts: A }; C.samples.push(I), C.length += L.length } } _parseAACAudioData(t, n, r) { if (r <= 1) { Log.w(this.TAG, "Flv: Invalid AAC packet, missing AACPacketType or/and Data!"); return } let l = {}, a = new Uint8Array(t, n, r); return l.packetType = a[0], a[0] === 0 ? l.data = this._parseAACAudioSpecificConfig(t, n + 1, r - 1) : l.data = a.subarray(1), l } _parseAACAudioSpecificConfig(t, n, r) { let l = new Uint8Array(t, n, r), a = null, e = 0, g = 0, _ = 0, y = null; if (e = g = l[0] >>> 3, _ = (l[0] & 7) << 1 | l[1] >>> 7, _ < 0 || _ >= this._mpegSamplingRates.length) { this._onError(DemuxErrors.FORMAT_ERROR, "Flv: AAC invalid sampling frequency index!"); return } let x = this._mpegSamplingRates[_], E = (l[1] & 120) >>> 3; if (E < 0 || E >= 8) { this._onError(DemuxErrors.FORMAT_ERROR, "Flv: AAC invalid channel configuration"); return } e === 5 && (y = (l[1] & 7) << 1 | l[2] >>> 7, (l[2] & 124) >>> 2); let C = self.navigator.userAgent.toLowerCase(); return C.indexOf("firefox") !== -1 ? _ >= 6 ? (e = 5, a = new Array(4), y = _ - 3) : (e = 2, a = new Array(2), y = _) : C.indexOf("android") !== -1 ? (e = 2, a = new Array(2), y = _) : (e = 5, y = _, a = new Array(4), _ >= 6 ? y = _ - 3 : E === 1 && (e = 2, a = new Array(2), y = _)), a[0] = e << 3, a[0] |= (_ & 15) >>> 1, a[1] = (_ & 15) << 7, a[1] |= (E & 15) << 3, e === 5 && (a[1] |= (y & 15) >>> 1, a[2] = (y & 1) << 7, a[2] |= 8, a[3] = 0), { config: a, samplingRate: x, channelCount: E, codec: "mp4a.40." + e, originalCodec: "mp4a.40." + g } } _parseMP3AudioData(t, n, r, l) { if (r < 4) { Log.w(this.TAG, "Flv: Invalid MP3 packet, header missing!"); return } this._littleEndian; let a = new Uint8Array(t, n, r), e = null; if (l) { if (a[0] !== 255) return; let g = a[1] >>> 3 & 3, _ = (a[1] & 6) >> 1, y = (a[2] & 240) >>> 4, x = (a[2] & 12) >>> 2, C = (a[3] >>> 6 & 3) !== 3 ? 2 : 1, L = 0, A = 0, I = "mp3"; switch (g) { case 0: L = this._mpegAudioV25SampleRateTable[x]; break; case 2: L = this._mpegAudioV20SampleRateTable[x]; break; case 3: L = this._mpegAudioV10SampleRateTable[x]; break }switch (_) { case 1: y < this._mpegAudioL3BitRateTable.length && (A = this._mpegAudioL3BitRateTable[y]); break; case 2: y < this._mpegAudioL2BitRateTable.length && (A = this._mpegAudioL2BitRateTable[y]); break; case 3: y < this._mpegAudioL1BitRateTable.length && (A = this._mpegAudioL1BitRateTable[y]); break }e = { bitRate: A, samplingRate: L, channelCount: C, codec: I, originalCodec: I } } else e = a; return e } _parseVideoData(t, n, r, l, a) { if (r <= 1) { Log.w(this.TAG, "Flv: Invalid video packet, missing VideoData payload!"); return } if (this._hasVideoFlagOverrided === !0 && this._hasVideo === !1) return; let e = new Uint8Array(t, n, r)[0], g = (e & 240) >>> 4, _ = e & 15; if (_ !== 7) { this._onError(DemuxErrors.CODEC_UNSUPPORTED, `Flv: Unsupported codec in video frame: ${_}`); return } this._parseAVCVideoPacket(t, n + 1, r - 1, l, a, g) } _parseAVCVideoPacket(t, n, r, l, a, e) { if (r < 4) { Log.w(this.TAG, "Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime"); return } let g = this._littleEndian, _ = new DataView(t, n, r), y = _.getUint8(0), E = (_.getUint32(0, !g) & 16777215) << 8 >> 8; if (y === 0) this._parseAVCDecoderConfigurationRecord(t, n + 4, r - 4); else if (y === 1) this._parseAVCVideoData(t, n + 4, r - 4, l, a, e, E); else if (y !== 2) { this._onError(DemuxErrors.FORMAT_ERROR, `Flv: Invalid video packet type ${y}`); return } } _parseAVCDecoderConfigurationRecord(t, n, r) { if (r < 7) { Log.w(this.TAG, "Flv: Invalid AVCDecoderConfigurationRecord, lack of data!"); return } let l = this._videoMetadata, a = this._videoTrack, e = this._littleEndian, g = new DataView(t, n, r); l ? typeof l.avcc < "u" && Log.w(this.TAG, "Found another AVCDecoderConfigurationRecord!") : (this._hasVideo === !1 && this._hasVideoFlagOverrided === !1 && (this._hasVideo = !0, this._mediaInfo.hasVideo = !0), l = this._videoMetadata = {}, l.type = "video", l.id = a.id, l.timescale = this._timescale, l.duration = this._duration); let _ = g.getUint8(0), y = g.getUint8(1); if (g.getUint8(2), g.getUint8(3), _ !== 1 || y === 0) { this._onError(DemuxErrors.FORMAT_ERROR, "Flv: Invalid AVCDecoderConfigurationRecord"); return } if (this._naluLengthSize = (g.getUint8(4) & 3) + 1, this._naluLengthSize !== 3 && this._naluLengthSize !== 4) { this._onError(DemuxErrors.FORMAT_ERROR, `Flv: Strange NaluLengthSizeMinusOne: ${this._naluLengthSize - 1}`); return } let x = g.getUint8(5) & 31; if (x === 0) { this._onError(DemuxErrors.FORMAT_ERROR, "Flv: Invalid AVCDecoderConfigurationRecord: No SPS"); return } else x > 1 && Log.w(this.TAG, `Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ${x}`); let E = 6; for (let L = 0; L < x; L++) { let A = g.getUint16(E, !e); if (E += 2, A === 0) continue; let I = new Uint8Array(t, n + E, A); E += A; let D = SPSParser.parseSPS(I); if (L !== 0) continue; l.codecWidth = D.codec_size.width, l.codecHeight = D.codec_size.height, l.presentWidth = D.present_size.width, l.presentHeight = D.present_size.height, l.profile = D.profile_string, l.level = D.level_string, l.bitDepth = D.bit_depth, l.chromaFormat = D.chroma_format, l.sarRatio = D.sar_ratio, l.frameRate = D.frame_rate, (D.frame_rate.fixed === !1 || D.frame_rate.fps_num === 0 || D.frame_rate.fps_den === 0) && (l.frameRate = this._referenceFrameRate); let w = l.frameRate.fps_den, S = l.frameRate.fps_num; l.refSampleDuration = l.timescale * (w / S); let O = I.subarray(1, 4), F = "avc1."; for (let P = 0; P < 3; P++) { let $ = O[P].toString(16); $.length < 2 && ($ = "0" + $), F += $ } l.codec = F; let j = this._mediaInfo; j.width = l.codecWidth, j.height = l.codecHeight, j.fps = l.frameRate.fps, j.profile = l.profile, j.level = l.level, j.refFrames = D.ref_frames, j.chromaFormat = D.chroma_format_string, j.sarNum = l.sarRatio.width, j.sarDen = l.sarRatio.height, j.videoCodec = F, j.hasAudio ? j.audioCodec != null && (j.mimeType = 'video/x-flv; codecs="' + j.videoCodec + "," + j.audioCodec + '"') : j.mimeType = 'video/x-flv; codecs="' + j.videoCodec + '"', j.isComplete() && this._onMediaInfo(j) } let C = g.getUint8(E); if (C === 0) { this._onError(DemuxErrors.FORMAT_ERROR, "Flv: Invalid AVCDecoderConfigurationRecord: No PPS"); return } else C > 1 && Log.w(this.TAG, `Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ${C}`); E++; for (let L = 0; L < C; L++) { let A = g.getUint16(E, !e); E += 2, A !== 0 && (E += A) } l.avcc = new Uint8Array(r), l.avcc.set(new Uint8Array(t, n, r), 0), Log.v(this.TAG, "Parsed AVCDecoderConfigurationRecord"), this._isInitialMetadataDispatched() ? this._dispatch && (this._audioTrack.length || this._videoTrack.length) && this._onDataAvailable(this._audioTrack, this._videoTrack) : this._videoInitialMetadataDispatched = !0, this._dispatch = !1, this._onTrackMetadata("video", l) } _parseAVCVideoData(t, n, r, l, a, e, g) { let _ = this._littleEndian, y = new DataView(t, n, r), x = [], E = 0, C = 0; const L = this._naluLengthSize; let A = this._timestampBase + l, I = e === 1; for (; C < r;) { if (C + 4 >= r) { Log.w(this.TAG, `Malformed Nalu near timestamp ${A}, offset = ${C}, dataSize = ${r}`); break } let D = y.getUint32(C, !_); if (L === 3 && (D >>>= 8), D > r - L) { Log.w(this.TAG, `Malformed Nalus near timestamp ${A}, NaluSize > DataSize!`); return } let w = y.getUint8(C + L) & 31; w === 5 && (I = !0); let S = new Uint8Array(t, n + C, L + D), O = { type: w, data: S }; x.push(O), E += S.byteLength, C += L + D } if (x.length) { let D = this._videoTrack, w = { units: x, length: E, isKeyframe: I, dts: A, cts: g, pts: A + g }; I && (w.fileposition = a), D.samples.push(w), D.length += E } } } class MP4 { static init() { MP4.types = { avc1: [], avcC: [], btrt: [], dinf: [], dref: [], esds: [], ftyp: [], hdlr: [], mdat: [], mdhd: [], mdia: [], mfhd: [], minf: [], moof: [], moov: [], mp4a: [], mvex: [], mvhd: [], sdtp: [], stbl: [], stco: [], stsc: [], stsd: [], stsz: [], stts: [], tfdt: [], tfhd: [], traf: [], trak: [], trun: [], trex: [], tkhd: [], vmhd: [], smhd: [], ".mp3": [] }; for (let n in MP4.types) MP4.types.hasOwnProperty(n) && (MP4.types[n] = [n.charCodeAt(0), n.charCodeAt(1), n.charCodeAt(2), n.charCodeAt(3)]); let t = MP4.constants = {}; t.FTYP = new Uint8Array([105, 115, 111, 109, 0, 0, 0, 1, 105, 115, 111, 109, 97, 118, 99, 49]), t.STSD_PREFIX = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1]), t.STTS = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]), t.STSC = t.STCO = t.STTS, t.STSZ = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), t.HDLR_VIDEO = 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]), t.HDLR_AUDIO = 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]), t.DREF = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 12, 117, 114, 108, 32, 0, 0, 0, 1]), t.SMHD = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]), t.VMHD = new Uint8Array([0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]) } static box(t) { let n = 8, r = null, l = Array.prototype.slice.call(arguments, 1), a = l.length; for (let g = 0; g < a; g++)n += l[g].byteLength; r = new Uint8Array(n), r[0] = n >>> 24 & 255, r[1] = n >>> 16 & 255, r[2] = n >>> 8 & 255, r[3] = n & 255, r.set(t, 4); let e = 8; for (let g = 0; g < a; g++)r.set(l[g], e), e += l[g].byteLength; return r } static generateInitSegment(t) { let n = MP4.box(MP4.types.ftyp, MP4.constants.FTYP), r = MP4.moov(t), l = new Uint8Array(n.byteLength + r.byteLength); return l.set(n, 0), l.set(r, n.byteLength), l } static moov(t) { let n = MP4.mvhd(t.timescale, t.duration), r = MP4.trak(t), l = MP4.mvex(t); return MP4.box(MP4.types.moov, n, r, l) } static mvhd(t, n) { return MP4.box(MP4.types.mvhd, new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, t >>> 24 & 255, t >>> 16 & 255, t >>> 8 & 255, t & 255, n >>> 24 & 255, n >>> 16 & 255, n >>> 8 & 255, n & 255, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255])) } static trak(t) { return MP4.box(MP4.types.trak, MP4.tkhd(t), MP4.mdia(t)) } static tkhd(t) { let n = t.id, r = t.duration, l = t.presentWidth, a = t.presentHeight; return MP4.box(MP4.types.tkhd, new Uint8Array([0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, n >>> 24 & 255, n >>> 16 & 255, n >>> 8 & 255, n & 255, 0, 0, 0, 0, r >>> 24 & 255, r >>> 16 & 255, r >>> 8 & 255, r & 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, l >>> 8 & 255, l & 255, 0, 0, a >>> 8 & 255, a & 255, 0, 0])) } static mdia(t) { return MP4.box(MP4.types.mdia, MP4.mdhd(t), MP4.hdlr(t), MP4.minf(t)) } static mdhd(t) { let n = t.timescale, r = t.duration; return MP4.box(MP4.types.mdhd, new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, n >>> 24 & 255, n >>> 16 & 255, n >>> 8 & 255, n & 255, r >>> 24 & 255, r >>> 16 & 255, r >>> 8 & 255, r & 255, 85, 196, 0, 0])) } static hdlr(t) { let n = null; return t.type === "audio" ? n = MP4.constants.HDLR_AUDIO : n = MP4.constants.HDLR_VIDEO, MP4.box(MP4.types.hdlr, n) } static minf(t) { let n = null; return t.type === "audio" ? n = MP4.box(MP4.types.smhd, MP4.constants.SMHD) : n = MP4.box(MP4.types.vmhd, MP4.constants.VMHD), MP4.box(MP4.types.minf, n, MP4.dinf(), MP4.stbl(t)) } static dinf() { return MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, MP4.constants.DREF)) } static stbl(t) { return MP4.box(MP4.types.stbl, MP4.stsd(t), MP4.box(MP4.types.stts, MP4.constants.STTS), MP4.box(MP4.types.stsc, MP4.constants.STSC), MP4.box(MP4.types.stsz, MP4.constants.STSZ), MP4.box(MP4.types.stco, MP4.constants.STCO)) } static stsd(t) { return t.type === "audio" ? t.codec === "mp3" ? MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp3(t)) : MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.mp4a(t)) : MP4.box(MP4.types.stsd, MP4.constants.STSD_PREFIX, MP4.avc1(t)) } static mp3(t) { let n = t.channelCount, r = t.audioSampleRate, l = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, n, 0, 16, 0, 0, 0, 0, r >>> 8 & 255, r & 255, 0, 0]); return MP4.box(MP4.types[".mp3"], l) } static mp4a(t) { let n = t.channelCount, r = t.audioSampleRate, l = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, n, 0, 16, 0, 0, 0, 0, r >>> 8 & 255, r & 255, 0, 0]); return MP4.box(MP4.types.mp4a, l, MP4.esds(t)) } static esds(t) { let n = t.config || [], r = n.length, l = new Uint8Array([0, 0, 0, 0, 3, 23 + r, 0, 1, 0, 4, 15 + r, 64, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5].concat([r]).concat(n).concat([6, 1, 2])); return MP4.box(MP4.types.esds, l) } static avc1(t) { let n = t.avcc, r = t.codecWidth, l = t.codecHeight, a = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, r >>> 8 & 255, r & 255, l >>> 8 & 255, l & 255, 0, 72, 0, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 1, 10, 120, 113, 113, 47, 102, 108, 118, 46, 106, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 255, 255]); return MP4.box(MP4.types.avc1, a, MP4.box(MP4.types.avcC, n)) } static mvex(t) { return MP4.box(MP4.types.mvex, MP4.trex(t)) } static trex(t) { let n = t.id, r = new Uint8Array([0, 0, 0, 0, n >>> 24 & 255, n >>> 16 & 255, n >>> 8 & 255, n & 255, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1]); return MP4.box(MP4.types.trex, r) } static moof(t, n) { return MP4.box(MP4.types.moof, MP4.mfhd(t.sequenceNumber), MP4.traf(t, n)) } static mfhd(t) { let n = new Uint8Array([0, 0, 0, 0, t >>> 24 & 255, t >>> 16 & 255, t >>> 8 & 255, t & 255]); return MP4.box(MP4.types.mfhd, n) } static traf(t, n) { let r = t.id, l = MP4.box(MP4.types.tfhd, new Uint8Array([0, 0, 0, 0, r >>> 24 & 255, r >>> 16 & 255, r >>> 8 & 255, r & 255])), a = MP4.box(MP4.types.tfdt, new Uint8Array([0, 0, 0, 0, n >>> 24 & 255, n >>> 16 & 255, n >>> 8 & 255, n & 255])), e = MP4.sdtp(t), g = MP4.trun(t, e.byteLength + 16 + 16 + 8 + 16 + 8 + 8); return MP4.box(MP4.types.traf, l, a, g, e) } static sdtp(t) { let n = t.samples || [], r = n.length, l = new Uint8Array(4 + r); for (let a = 0; a < r; a++) { let e = n[a].flags; l[a + 4] = e.isLeading << 6 | e.dependsOn << 4 | e.isDependedOn << 2 | e.hasRedundancy } return MP4.box(MP4.types.sdtp, l) } static trun(t, n) { let r = t.samples || [], l = r.length, a = 12 + 16 * l, e = new Uint8Array(a); n += 8 + a, e.set([0, 0, 15, 1, l >>> 24 & 255, l >>> 16 & 255, l >>> 8 & 255, l & 255, n >>> 24 & 255, n >>> 16 & 255, n >>> 8 & 255, n & 255], 0); for (let g = 0; g < l; g++) { let _ = r[g].duration, y = r[g].size, x = r[g].flags, E = r[g].cts; e.set([_ >>> 24 & 255, _ >>> 16 & 255, _ >>> 8 & 255, _ & 255, y >>> 24 & 255, y >>> 16 & 255, y >>> 8 & 255, y & 255, x.isLeading << 2 | x.dependsOn, x.isDependedOn << 6 | x.hasRedundancy << 4 | x.isNonSync, 0, 0, E >>> 24 & 255, E >>> 16 & 255, E >>> 8 & 255, E & 255], 12 + 16 * g) } return MP4.box(MP4.types.trun, e) } static mdat(t) { return MP4.box(MP4.types.mdat, t) } } MP4.init(); class AAC { static getSilentFrame(t, n) { if (t === "mp4a.40.2") { if (n === 1) return new Uint8Array([0, 200, 0, 128, 35, 128]); if (n === 2) return new Uint8Array([33, 0, 73, 144, 2, 25, 0, 35, 128]); if (n === 3) return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 142]); if (n === 4) return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 128, 44, 128, 8, 2, 56]); if (n === 5) return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 56]); if (n === 6) return new Uint8Array([0, 200, 0, 128, 32, 132, 1, 38, 64, 8, 100, 0, 130, 48, 4, 153, 0, 33, 144, 2, 0, 178, 0, 32, 8, 224]) } else { if (n === 1) return new Uint8Array([1, 64, 34, 128, 163, 78, 230, 128, 186, 8, 0, 0, 0, 28, 6, 241, 193, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]); if (n === 2) return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]); if (n === 3) return new Uint8Array([1, 64, 34, 128, 163, 94, 230, 128, 186, 8, 0, 0, 0, 0, 149, 0, 6, 241, 161, 10, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94]) } return null } } class SampleInfo { constructor(t, n, r, l, a) { this.dts = t, this.pts = n, this.duration = r, this.originalDts = l, this.isSyncPoint = a, this.fileposition = null } } class MediaSegmentInfo { constructor() { this.beginDts = 0, this.endDts = 0, this.beginPts = 0, this.endPts = 0, this.originalBeginDts = 0, this.originalEndDts = 0, this.syncPoints = [], this.firstSample = null, this.lastSample = null } appendSyncPoint(t) { t.isSyncPoint = !0, this.syncPoints.push(t) } } class IDRSampleList { constructor() { this._list = [] } clear() { this._list = [] } appendArray(t) { let n = this._list; t.length !== 0 && (n.length > 0 && t[0].originalDts < n[n.length - 1].originalDts && this.clear(), Array.prototype.push.apply(n, t)) } getLastSyncPointBeforeDts(t) { if (this._list.length == 0) return null; let n = this._list, r = 0, l = n.length - 1, a = 0, e = 0, g = l; for (t < n[0].dts && (r = 0, e = g + 1); e <= g;)if (a = e + Math.floor((g - e) / 2), a === l || t >= n[a].dts && t < n[a + 1].dts) { r = a; break } else n[a].dts < t ? e = a + 1 : g = a - 1; return this._list[r] } } class MediaSegmentInfoList { constructor(t) { this._type = t, this._list = [], this._lastAppendLocation = -1 } get type() { return this._type } get length() { return this._list.length } isEmpty() { return this._list.length === 0 } clear() { this._list = [], this._lastAppendLocation = -1 } _searchNearestSegmentBefore(t) { let n = this._list; if (n.length === 0) return -2; let r = n.length - 1, l = 0, a = 0, e = r, g = 0; if (t < n[0].originalBeginDts) return g = -1, g; for (; a <= e;)if (l = a + Math.floor((e - a) / 2), l === r || t > n[l].lastSample.originalDts && t < n[l + 1].originalBeginDts) { g = l; break } else n[l].originalBeginDts < t ? a = l + 1 : e = l - 1; return g } _searchNearestSegmentAfter(t) { return this._searchNearestSegmentBefore(t) + 1 } append(t) { let n = this._list, r = t, l = this._lastAppendLocation, a = 0; l !== -1 && l < n.length && r.originalBeginDts >= n[l].lastSample.originalDts && (l === n.length - 1 || l < n.length - 1 && r.originalBeginDts < n[l + 1].originalBeginDts) ? a = l + 1 : n.length > 0 && (a = this._searchNearestSegmentBefore(r.originalBeginDts) + 1), this._lastAppendLocation = a, this._list.splice(a, 0, r) } getLastSegmentBefore(t) { let n = this._searchNearestSegmentBefore(t); return n >= 0 ? this._list[n] : null } getLastSampleBefore(t) { let n = this.getLastSegmentBefore(t); return n != null ? n.lastSample : null } getLastSyncPointBefore(t) { let n = this._searchNearestSegmentBefore(t), r = this._list[n].syncPoints; for (; r.length === 0 && n > 0;)n--, r = this._list[n].syncPoints; return r.length > 0 ? r[r.length - 1] : null } } class MP4Remuxer { constructor(t) { this.TAG = "MP4Remuxer", this._config = t, this._isLive = t.isLive === !0, this._dtsBase = -1, this._dtsBaseInited = !1, this._audioDtsBase = 1 / 0, this._videoDtsBase = 1 / 0, this._audioNextDts = void 0, this._videoNextDts = void 0, this._audioStashedLastSample = null, this._videoStashedLastSample = null, this._audioMeta = null, this._videoMeta = null, this._audioSegmentInfoList = new MediaSegmentInfoList("audio"), this._videoSegmentInfoList = new MediaSegmentInfoList("video"), this._onInitSegment = null, this._onMediaSegment = null, this._forceFirstIDR = !!(Browser.chrome && (Browser.version.major < 50 || Browser.version.major === 50 && Browser.version.build < 2661)), this._fillSilentAfterSeek = Browser.msedge || Browser.msie, this._mp3UseMpegAudio = !Browser.firefox, this._fillAudioTimestampGap = this._config.fixAudioTimestampGap } destroy() { this._dtsBase = -1, this._dtsBaseInited = !1, this._audioMeta = null, this._videoMeta = null, this._audioSegmentInfoList.clear(), this._audioSegmentInfoList = null, this._videoSegmentInfoList.clear(), this._videoSegmentInfoList = null, this._onInitSegment = null, this._onMediaSegment = null } bindDataSource(t) { return t.onDataAvailable = this.remux.bind(this), t.onTrackMetadata = this._onTrackMetadataReceived.bind(this), this } get onInitSegment() { return this._onInitSegment } set onInitSegment(t) { this._onInitSegment = t } get onMediaSegment() { return this._onMediaSegment } set onMediaSegment(t) { this._onMediaSegment = t } insertDiscontinuity() { this._audioNextDts = this._videoNextDts = void 0 } seek(t) { this._audioStashedLastSample = null, this._videoStashedLastSample = null, this._videoSegmentInfoList.clear(), this._audioSegmentInfoList.clear() } remux(t, n) { if (!this._onMediaSegment) throw new IllegalStateException("MP4Remuxer: onMediaSegment callback must be specificed!"); this._dtsBaseInited || this._calculateDtsBase(t, n), this._remuxVideo(n), this._remuxAudio(t) } _onTrackMetadataReceived(t, n) { let r = null, l = "mp4", a = n.codec; if (t === "audio") this._audioMeta = n, n.codec === "mp3" && this._mp3UseMpegAudio ? (l = "mpeg", a = "", r = new Uint8Array) : r = MP4.generateInitSegment(n); else if (t === "video") this._videoMeta = n, r = MP4.generateInitSegment(n); else return; if (!this._onInitSegment) throw new IllegalStateException("MP4Remuxer: onInitSegment callback must be specified!"); this._onInitSegment(t, { type: t, data: r.buffer, codec: a, container: `${t}/${l}`, mediaDuration: n.duration }) } _calculateDtsBase(t, n) { this._dtsBaseInited || (t.samples && t.samples.length && (this._audioDtsBase = t.samples[0].dts), n.samples && n.samples.length && (this._videoDtsBase = n.samples[0].dts), this._dtsBase = Math.min(this._audioDtsBase, this._videoDtsBase), this._dtsBaseInited = !0) } flushStashedSamples() { let t = this._videoStashedLastSample, n = this._audioStashedLastSample, r = { type: "video", id: 1, sequenceNumber: 0, samples: [], length: 0 }; t != null && (r.samples.push(t), r.length = t.length); let l = { type: "audio", id: 2, sequenceNumber: 0, samples: [], length: 0 }; n != null && (l.samples.push(n), l.length = n.length), this._videoStashedLastSample = null, this._audioStashedLastSample = null, this._remuxVideo(r, !0), this._remuxAudio(l, !0) } _remuxAudio(t, n) { if (this._audioMeta == null) return; let r = t, l = r.samples, a, e = -1, g = -1, _ = this._audioMeta.refSampleDuration, y = this._audioMeta.codec === "mp3" && this._mp3UseMpegAudio, x = this._dtsBaseInited && this._audioNextDts === void 0, E = !1; if (!l || l.length === 0 || l.length === 1 && !n) return; let C = 0, L = null, A = 0; y ? (C = 0, A = r.length) : (C = 8, A = 8 + r.length); let I = null; if (l.length > 1 && (I = l.pop(), A -= I.length), this._audioStashedLastSample != null) { let P = this._audioStashedLastSample; this._audioStashedLastSample = null, l.unshift(P), A += P.length } I != null && (this._audioStashedLastSample = I); let D = l[0].dts - this._dtsBase; if (this._audioNextDts) a = D - this._audioNextDts; else if (this._audioSegmentInfoList.isEmpty()) a = 0, this._fillSilentAfterSeek && !this._videoSegmentInfoList.isEmpty() && this._audioMeta.originalCodec !== "mp3" && (E = !0); else { let P = this._audioSegmentInfoList.getLastSampleBefore(D); if (P != null) { let $ = D - (P.originalDts + P.duration); $ <= 3 && ($ = 0); let V = P.dts + P.duration + $; a = D - V } else a = 0 } if (E) { let P = D - a, $ = this._videoSegmentInfoList.getLastSegmentBefore(D); if ($ != null && $.beginDts < P) { let V = AAC.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount); if (V) { let q = $.beginDts, ee = P - $.beginDts; Log.v(this.TAG, `InsertPrefixSilentAudio: dts: ${q}, duration: ${ee}`), l.unshift({ unit: V, dts: q, pts: q }), A += V.byteLength } } else E = !1 } let w = []; for (let P = 0; P < l.length; P++) { let $ = l[P], V = $.unit, q = $.dts - this._dtsBase, ee = q, re = !1, ye = null, ce = 0; if (!(q < -.001)) { if (this._audioMeta.codec !== "mp3") { let Q = q; const se = 3; if (this._audioNextDts && (Q = this._audioNextDts), a = q - Q, a <= -se * _) Log.w(this.TAG, `Dropping 1 audio frame (originalDts: ${q} ms ,curRefDts: ${Q} ms) due to dtsCorrection: ${a} ms overlap.`); else if (a >= se * _ && this._fillAudioTimestampGap && !Browser.safari) { re = !0; let fe = Math.floor(a / _); Log.w(this.TAG, `Large audio timestamp gap detected, may cause AV sync to drift. Silent frames will be generated to avoid unsync. originalDts: ${q} ms, curRefDts: ${Q} ms, dtsCorrection: ${Math.round(a)} ms, generate: ${fe} frames`), ee = Math.floor(Q), ce = Math.floor(Q + _) - ee; let G = AAC.getSilentFrame(this._audioMeta.originalCodec, this._audioMeta.channelCount); G == null && (Log.w(this.TAG, `Unable to generate silent frame for ${this._audioMeta.originalCodec} with ${this._audioMeta.channelCount} channels, repeat last frame`), G = V), ye = []; for (let K = 0; K < fe; K++) { Q = Q + _; let de = Math.floor(Q), ve = Math.floor(Q + _) - de, ae = { dts: de, pts: de, cts: 0, unit: G, size: G.byteLength, duration: ve, originalDts: q, flags: { isLeading: 0, dependsOn: 1, isDependedOn: 0, hasRedundancy: 0 } }; ye.push(ae), A += ae.size } this._audioNextDts = Q + _ } else ee = Math.floor(Q), ce = Math.floor(Q + _) - ee, this._audioNextDts = Q + _ } else ee = q - a, P !== l.length - 1 ? ce = l[P + 1].dts - this._dtsBase - a - ee : I != null ? ce = I.dts - this._dtsBase - a - ee : w.length >= 1 ? ce = w[w.length - 1].duration : ce = Math.floor(_), this._audioNextDts = ee + ce; e === -1 && (e = ee), w.push({ dts: ee, pts: ee, cts: 0, unit: $.unit, size: $.unit.byteLength, duration: ce, originalDts: q, flags: { isLeading: 0, dependsOn: 1, isDependedOn: 0, hasRedundancy: 0 } }), re && w.push.apply(w, ye) } } if (w.length === 0) { r.samples = [], r.length = 0; return } y ? L = new Uint8Array(A) : (L = new Uint8Array(A), L[0] = A >>> 24 & 255, L[1] = A >>> 16 & 255, L[2] = A >>> 8 & 255, L[3] = A & 255, L.set(MP4.types.mdat, 4)); for (let P = 0; P < w.length; P++) { let $ = w[P].unit; L.set($, C), C += $.byteLength } let S = w[w.length - 1]; g = S.dts + S.duration; let O = new MediaSegmentInfo; O.beginDts = e, O.endDts = g, O.beginPts = e, O.endPts = g, O.originalBeginDts = w[0].originalDts, O.originalEndDts = S.originalDts + S.duration, O.firstSample = new SampleInfo(w[0].dts, w[0].pts, w[0].duration, w[0].originalDts, !1), O.lastSample = new SampleInfo(S.dts, S.pts, S.duration, S.originalDts, !1), this._isLive || this._audioSegmentInfoList.append(O), r.samples = w, r.sequenceNumber++; let F = null; y ? F = new Uint8Array : F = MP4.moof(r, e), r.samples = [], r.length = 0; let j = { type: "audio", data: this._mergeBoxes(F, L).buffer, sampleCount: w.length, info: O }; y && x && (j.timestampOffset = e), this._onMediaSegment("audio", j) } _remuxVideo(t, n) { if (this._videoMeta == null) return; let r = t, l = r.samples, a, e = -1, g = -1, _ = -1, y = -1; if (!l || l.length === 0 || l.length === 1 && !n) return; let x = 8, E = null, C = 8 + t.length, L = null; if (l.length > 1 && (L = l.pop(), C -= L.length), this._videoStashedLastSample != null) { let O = this._videoStashedLastSample; this._videoStashedLastSample = null, l.unshift(O), C += O.length } L != null && (this._videoStashedLastSample = L); let A = l[0].dts - this._dtsBase; if (this._videoNextDts) a = A - this._videoNextDts; else if (this._videoSegmentInfoList.isEmpty()) a = 0; else { let O = this._videoSegmentInfoList.getLastSampleBefore(A); if (O != null) { let F = A - (O.originalDts + O.duration); F <= 3 && (F = 0); let j = O.dts + O.duration + F; a = A - j } else a = 0 } let I = new MediaSegmentInfo, D = []; for (let O = 0; O < l.length; O++) { let F = l[O], j = F.dts - this._dtsBase, P = F.isKeyframe, $ = j - a, V = F.cts, q = $ + V; e === -1 && (e = $, _ = q); let ee = 0; if (O !== l.length - 1 ? ee = l[O + 1].dts - this._dtsBase - a - $ : L != null ? ee = L.dts - this._dtsBase - a - $ : D.length >= 1 ? ee = D[D.length - 1].duration : ee = Math.floor(this._videoMeta.refSampleDuration), P) { let re = new SampleInfo($, q, ee, F.dts, !0); re.fileposition = F.fileposition, I.appendSyncPoint(re) } D.push({ dts: $, pts: q, cts: V, units: F.units, size: F.length, isKeyframe: P, duration: ee, originalDts: j, flags: { isLeading: 0, dependsOn: P ? 2 : 1, isDependedOn: P ? 1 : 0, hasRedundancy: 0, isNonSync: P ? 0 : 1 } }) } E = new Uint8Array(C), E[0] = C >>> 24 & 255, E[1] = C >>> 16 & 255, E[2] = C >>> 8 & 255, E[3] = C & 255, E.set(MP4.types.mdat, 4); for (let O = 0; O < D.length; O++) { let F = D[O].units; for (; F.length;) { let P = F.shift().data; E.set(P, x), x += P.byteLength } } let w = D[D.length - 1]; if (g = w.dts + w.duration, y = w.pts + w.duration, this._videoNextDts = g, I.beginDts = e, I.endDts = g, I.beginPts = _, I.endPts = y, I.originalBeginDts = D[0].originalDts, I.originalEndDts = w.originalDts + w.duration, I.firstSample = new SampleInfo(D[0].dts, D[0].pts, D[0].duration, D[0].originalDts, D[0].isKeyframe), I.lastSample = new SampleInfo(w.dts, w.pts, w.duration, w.originalDts, w.isKeyframe), this._isLive || this._videoSegmentInfoList.append(I), r.samples = D, r.sequenceNumber++, this._forceFirstIDR) { let O = D[0].flags; O.dependsOn = 2, O.isNonSync = 0 } let S = MP4.moof(r, e); r.samples = [], r.length = 0, this._onMediaSegment("video", { type: "video", data: this._mergeBoxes(S, E).buffer, sampleCount: D.length, info: I }) } _mergeBoxes(t, n) { let r = new Uint8Array(t.byteLength + n.byteLength); return r.set(t, 0), r.set(n, t.byteLength), r } } const TransmuxingEvents = { IO_ERROR: "io_error", DEMUX_ERROR: "demux_error", INIT_SEGMENT: "init_segment", MEDIA_SEGMENT: "media_segment", LOADING_COMPLETE: "loading_complete", RECOVERED_EARLY_EOF: "recovered_early_eof", MEDIA_INFO: "media_info", METADATA_ARRIVED: "metadata_arrived", SCRIPTDATA_ARRIVED: "scriptdata_arrived", STATISTICS_INFO: "statistics_info", RECOMMEND_SEEKPOINT: "recommend_seekpoint" }; class TransmuxingController { constructor(t, n) { this.TAG = "TransmuxingController", this._emitter = new EventEmitter$1, this._config = n, t.segments || (t.segments = [{ duration: t.duration, filesize: t.filesize, url: t.url }]), typeof t.cors != "boolean" && (t.cors = !0), typeof t.withCredentials != "boolean" && (t.withCredentials = !1), this._mediaDataSource = t, this._currentSegmentIndex = 0; let r = 0; this._mediaDataSource.segments.forEach(l => { l.timestampBase = r, r += l.duration, l.cors = t.cors, l.withCredentials = t.withCredentials, n.referrerPolicy && (l.referrerPolicy = n.referrerPolicy) }), !isNaN(r) && this._mediaDataSource.duration !== r && (this._mediaDataSource.duration = r), this._mediaInfo = null, this._demuxer = null, this._remuxer = null, this._ioctl = null, this._pendingSeekTime = null, this._pendingResolveSeekPoint = null, this._statisticsReporter = null } destroy() { var t, n; this._mediaInfo = null, this._mediaDataSource = null, this._statisticsReporter && this._disableStatisticsReporter(), this._ioctl && (this._ioctl.destroy(), this._ioctl = null), this._demuxer && ((t = this._demuxer) != null && t.destroy && this._demuxer.destroy(), this._demuxer = null), this._remuxer && ((n = this._remuxer) != null && n.destroy && this._remuxer.destroy(), this._remuxer = null), this._emitter.removeAllListeners(), this._emitter = null } on(t, n) { this._emitter.addListener(t, n) } off(t, n) { this._emitter.removeListener(t, n) } start() { this._loadSegment(0), this._enableStatisticsReporter() } _loadSegment(t, n) { this._currentSegmentIndex = t; let r = this._mediaDataSource.segments[t], l = this._ioctl = new IOController(r, this._config, t); l.onError = this._onIOException.bind(this), l.onSeeked = this._onIOSeeked.bind(this), l.onComplete = this._onIOComplete.bind(this), l.onRedirect = this._onIORedirect.bind(this), l.onRecoveredEarlyEof = this._onIORecoveredEarlyEof.bind(this), n ? this._demuxer.bindDataSource(this._ioctl) : l.onDataArrival = this._onInitChunkArrival.bind(this), l.open(n) } stop() { this._internalAbort(), this._disableStatisticsReporter() } _internalAbort() { this._ioctl && (this._ioctl.destroy(), this._ioctl = null) } pause() { this._ioctl && this._ioctl.isWorking() && (this._ioctl.pause(), this._disableStatisticsReporter()) } resume() { this._ioctl && this._ioctl.isPaused() && (this._ioctl.resume(), this._enableStatisticsReporter()) } seek(t) { if (this._mediaInfo == null || !this._mediaInfo.isSeekable()) return; let n = this._searchSegmentIndexContains(t); if (n === this._currentSegmentIndex) { let r = this._mediaInfo.segments[n]; if (r == null) this._pendingSeekTime = t; else { let l = r.getNearestKeyframe(t); this._remuxer.seek(l.milliseconds), this._ioctl.seek(l.fileposition), this._pendingResolveSeekPoint = l.milliseconds } } else { let r = this._mediaInfo.segments[n]; if (r == null) this._pendingSeekTime = t, this._internalAbort(), this._remuxer.seek(), this._remuxer.insertDiscontinuity(), this._loadSegment(n); else { let l = r.getNearestKeyframe(t); this._internalAbort(), this._remuxer.seek(t), this._remuxer.insertDiscontinuity(), this._demuxer.resetMediaInfo(), this._demuxer.timestampBase = this._mediaDataSource.segments[n].timestampBase, this._loadSegment(n, l.fileposition), this._pendingResolveSeekPoint = l.milliseconds, this._reportSegmentMediaInfo(n) } } this._enableStatisticsReporter() } _searchSegmentIndexContains(t) { let n = this._mediaDataSource.segments, r = n.length - 1; for (let l = 0; l < n.length; l++)if (t < n[l].timestampBase) { r = l - 1; break } return r } _onInitChunkArrival(t, n, r = "") { let l = null, a = 0; if (n > 0) this._demuxer.bindDataSource(this._ioctl), this._demuxer.timestampBase = this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase, a = this._demuxer.parseChunks(t, n); else if ((l = FLVDemuxer.probe(t)).match) { console.error(l, "probeData", this._config, "FLVDemuxer"), this._demuxer = new FLVDemuxer(l, this._config), this._remuxer || (this._remuxer = new MP4Remuxer(this._config)); let e = this._mediaDataSource; e.duration != null && !isNaN(e.duration) && (this._demuxer.overridedDuration = e.duration), typeof e.hasAudio == "boolean" && (this._demuxer.overridedHasAudio = e.hasAudio), typeof e.hasVideo == "boolean" && (this._demuxer.overridedHasVideo = e.hasVideo), this._demuxer.timestampBase = e.segments[this._currentSegmentIndex].timestampBase, this._demuxer.onError = this._onDemuxException.bind(this), this._demuxer.onMediaInfo = this._onMediaInfo.bind(this), this._demuxer.onMetaDataArrived = this._onMetaDataArrived.bind(this), this._demuxer.onScriptDataArrived = this._onScriptDataArrived.bind(this), this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl)), this._remuxer.onInitSegment = this._onRemuxerInitSegmentArrival.bind(this), this._remuxer.onMediaSegment = this._onRemuxerMediaSegmentArrival.bind(this), a = this._demuxer.parseChunks(t, n, r) } else l = null, Log.e(this.TAG, "Non-FLV, Unsupported media type!"), Promise.resolve().then(() => { this._internalAbort() }), this._emitter.emit(TransmuxingEvents.DEMUX_ERROR, DemuxErrors.FORMAT_UNSUPPORTED, "Non-FLV, Unsupported media type"), a = 0; return a } _onMediaInfo(t) { console.error(t, "mediaInfo"), this._mediaInfo == null && (this._mediaInfo = Object.assign({}, t), this._mediaInfo.keyframesIndex = null, this._mediaInfo.segments = [], this._mediaInfo.segmentCount = this._mediaDataSource.segments.length, Object.setPrototypeOf(this._mediaInfo, MediaInfo.prototype)); let n = Object.assign({}, t); Object.setPrototypeOf(n, MediaInfo.prototype), this._mediaInfo.segments[this._currentSegmentIndex] = n, this._reportSegmentMediaInfo(this._currentSegmentIndex), this._pendingSeekTime != null && Promise.resolve().then(() => { let r = this._pendingSeekTime; this._pendingSeekTime = null, this.seek(r) }) } _onMetaDataArrived(t) { console.error(t, "metadata"), this._emitter.emit(TransmuxingEvents.METADATA_ARRIVED, t) } _onScriptDataArrived(t) { console.error(t, "data"), this._emitter.emit(TransmuxingEvents.SCRIPTDATA_ARRIVED, t) } _onIOSeeked() { this._remuxer.insertDiscontinuity() } _onIOComplete(t) { let r = t + 1; r < this._mediaDataSource.segments.length ? (this._internalAbort(), this._remuxer && this._remuxer.flushStashedSamples(), this._loadSegment(r)) : (this._remuxer && this._remuxer.flushStashedSamples(), this._emitter.emit(TransmuxingEvents.LOADING_COMPLETE), this._disableStatisticsReporter()) } _onIORedirect(t) { let n = this._ioctl.extraData; this._mediaDataSource.segments[n].redirectedURL = t } _onIORecoveredEarlyEof() { this._emitter.emit(TransmuxingEvents.RECOVERED_EARLY_EOF) } _onIOException(t, n) { Log.e(this.TAG, `IOException: type = ${t}, code = ${n.code}, msg = ${n.msg}`), this._emitter.emit(TransmuxingEvents.IO_ERROR, t, n), this._disableStatisticsReporter() } _onDemuxException(t, n) { Log.e(this.TAG, `DemuxException: type = ${t}, info = ${n}`), this._emitter.emit(TransmuxingEvents.DEMUX_ERROR, t, n) } _onRemuxerInitSegmentArrival(t, n) { this._emitter.emit(TransmuxingEvents.INIT_SEGMENT, t, n) } _onRemuxerMediaSegmentArrival(t, n) { if (this._pendingSeekTime == null && (this._emitter.emit(TransmuxingEvents.MEDIA_SEGMENT, t, n), this._pendingResolveSeekPoint != null && t === "video")) { let r = n.info.syncPoints, l = this._pendingResolveSeekPoint; this._pendingResolveSeekPoint = null, Browser.safari && r.length > 0 && r[0].originalDts === l && (l = r[0].pts), this._emitter.emit(TransmuxingEvents.RECOMMEND_SEEKPOINT, l) } } _enableStatisticsReporter() { this._statisticsReporter == null && (this._statisticsReporter = self.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval)) } _disableStatisticsReporter() { this._statisticsReporter && (self.clearInterval(this._statisticsReporter), this._statisticsReporter = null) } _reportSegmentMediaInfo(t) { let n = this._mediaInfo.segments[t], r = Object.assign({}, n); r.duration = this._mediaInfo.duration, r.segmentCount = this._mediaInfo.segmentCount, delete r.segments, delete r.keyframesIndex, this._emitter.emit(TransmuxingEvents.MEDIA_INFO, r) } _reportStatisticsInfo() { } } class Transmuxer { constructor(t, n) { if (this.TAG = "Transmuxer", this._emitter = new EventEmitter$1, this._controller = new TransmuxingController(t, n), this._controller) { let r = this._controller; r.on(TransmuxingEvents.IO_ERROR, this._onIOError.bind(this)), r.on(TransmuxingEvents.DEMUX_ERROR, this._onDemuxError.bind(this)), r.on(TransmuxingEvents.INIT_SEGMENT, this._onInitSegment.bind(this)), r.on(TransmuxingEvents.MEDIA_SEGMENT, this._onMediaSegment.bind(this)), r.on(TransmuxingEvents.LOADING_COMPLETE, this._onLoadingComplete.bind(this)), r.on(TransmuxingEvents.RECOVERED_EARLY_EOF, this._onRecoveredEarlyEof.bind(this)), r.on(TransmuxingEvents.MEDIA_INFO, this._onMediaInfo.bind(this)), r.on(TransmuxingEvents.METADATA_ARRIVED, this._onMetaDataArrived.bind(this)), r.on(TransmuxingEvents.SCRIPTDATA_ARRIVED, this._onScriptDataArrived.bind(this)), r.on(TransmuxingEvents.STATISTICS_INFO, this._onStatisticsInfo.bind(this)), r.on(TransmuxingEvents.RECOMMEND_SEEKPOINT, this._onRecommendSeekpoint.bind(this)) } } destroy() { var t; this._worker ? this._workerDestroying || (this._workerDestroying = !0, this._worker.postMessage({ cmd: "destroy" }), LoggingControl.removeListener(this.e.onLoggingConfigChanged), this.e = null) : ((t = this._controller) == null || t.destroy(), this._controller = null), this._emitter.removeAllListeners(), this._emitter = null } on(t, n) { this._emitter.addListener(t, n) } off(t, n) { this._emitter.removeListener(t, n) } hasWorker() { return this._worker != null } open() { this._worker ? this._worker.postMessage({ cmd: "start" }) : this._controller.start() } close() { this._worker ? this._worker.postMessage({ cmd: "stop" }) : this._controller.stop() } seek(t) { this._worker ? this._worker.postMessage({ cmd: "seek", param: t }) : this._controller.seek(t) } pause() { this._worker ? this._worker.postMessage({ cmd: "pause" }) : this._controller.pause() } resume() { this._worker ? this._worker.postMessage({ cmd: "resume" }) : this._controller.resume() } _onInitSegment(t, n) { Promise.resolve().then(() => { this._emitter.emit(TransmuxingEvents.INIT_SEGMENT, t, n) }) } _onMediaSegment(t, n) { Promise.resolve().then(() => { this._emitter.emit(TransmuxingEvents.MEDIA_SEGMENT, t, n) }) } _onLoadingComplete() { Promise.resolve().then(() => { this._emitter.emit(TransmuxingEvents.LOADING_COMPLETE) }) } _onRecoveredEarlyEof() { Promise.resolve().then(() => { this._emitter.emit(TransmuxingEvents.RECOVERED_EARLY_EOF) }) } _onMediaInfo(t) { Promise.resolve().then(() => { this._emitter.emit(TransmuxingEvents.MEDIA_INFO, t) }) } _onMetaDataArrived(t) { Promise.resolve().then(() => { this._emitter.emit(TransmuxingEvents.METADATA_ARRIVED, t) }) } _onScriptDataArrived(t) { Promise.resolve().then(() => { this._emitter.emit(TransmuxingEvents.SCRIPTDATA_ARRIVED, t) }) } _onStatisticsInfo(t) { Promise.resolve().then(() => { this._emitter.emit(TransmuxingEvents.STATISTICS_INFO, t) }) } _onIOError(t, n) { Promise.resolve().then(() => { this._emitter.emit(TransmuxingEvents.IO_ERROR, t, n) }) } _onDemuxError(t, n) { Promise.resolve().then(() => { this._emitter.emit(TransmuxingEvents.DEMUX_ERROR, t, n) }) } _onRecommendSeekpoint(t) { Promise.resolve().then(() => { this._emitter.emit(TransmuxingEvents.RECOMMEND_SEEKPOINT, t) }) } _onLoggingConfigChanged(t) { this._worker && this._worker.postMessage({ cmd: "logging_config", param: t }) } _onWorkerMessage(t) { let n = t.data, r = n.data; if (n.msg === "destroyed" || this._workerDestroying) { this._workerDestroying = !1, this._worker.terminate(), this._worker = null; return } switch (n.msg) { case TransmuxingEvents.INIT_SEGMENT: case TransmuxingEvents.MEDIA_SEGMENT: this._emitter.emit(n.msg, r.type, r.data); break; case TransmuxingEvents.LOADING_COMPLETE: case TransmuxingEvents.RECOVERED_EARLY_EOF: this._emitter.emit(n.msg); break; case TransmuxingEvents.MEDIA_INFO: Object.setPrototypeOf(r, MediaInfo.prototype), this._emitter.emit(n.msg, r); break; case TransmuxingEvents.METADATA_ARRIVED: case TransmuxingEvents.SCRIPTDATA_ARRIVED: case TransmuxingEvents.STATISTICS_INFO: this._emitter.emit(n.msg, r); break; case TransmuxingEvents.IO_ERROR: case TransmuxingEvents.DEMUX_ERROR: this._emitter.emit(n.msg, r.type, r.info); break; case TransmuxingEvents.RECOMMEND_SEEKPOINT: this._emitter.emit(n.msg, r); break; case "logcat_callback": Log.emitter.emit("log", r.type, r.logcat); break } } } const MSEEvents = { ERROR: "error", SOURCE_OPEN: "source_open", UPDATE_END: "update_end", BUFFER_FULL: "buffer_full" }; class MSEController { constructor(t) { this.TAG = "MSEController", this._config = t, this._emitter = new EventEmitter$1, this._config.isLive && this._config.autoCleanupSourceBuffer == null && (this._config.autoCleanupSourceBuffer = !0), this.e = { onSourceOpen: this._onSourceOpen.bind(this), onSourceEnded: this._onSourceEnded.bind(this), onSourceClose: this._onSourceClose.bind(this), onSourceBufferError: this._onSourceBufferError.bind(this), onSourceBufferUpdateEnd: this._onSourceBufferUpdateEnd.bind(this) }, this._mediaSource = null, this._mediaSourceObjectURL = null, this._mediaElement = null, this._isBufferFull = !1, this._hasPendingEos = !1, this._requireSetMediaDuration = !1, this._pendingMediaDuration = 0, this._pendingSourceBufferInit = [], this._mimeTypes = { video: null, audio: null }, this._sourceBuffers = { video: null, audio: null }, this._lastInitSegments = { video: null, audio: null }, this._pendingSegments = { video: [], audio: [] }, this._pendingRemoveRanges = { video: [], audio: [] }, this._idrList = new IDRSampleList } destroy() { (this._mediaElement || this._mediaSource) && this.detachMediaElement(), this.e = null, this._emitter.removeAllListeners(), this._emitter = null } on(t, n) { this._emitter.addListener(t, n) } off(t, n) { this._emitter.removeListener(t, n) } attachMediaElement(t) { if (this._mediaSource) throw new IllegalStateException("MediaSource has been attached to an HTMLMediaElement!"); let n = this._mediaSource = new window.MediaSource; n.addEventListener("sourceopen", this.e.onSourceOpen), n.addEventListener("sourceended", this.e.onSourceEnded), n.addEventListener("sourceclose", this.e.onSourceClose), this._mediaElement = t, this._mediaSourceObjectURL = window.URL.createObjectURL(this._mediaSource), t.src = this._mediaSourceObjectURL } detachMediaElement() { if (this._mediaSource) { let t = this._mediaSource; for (let n in this._sourceBuffers) { let r = this._pendingSegments[n]; r.splice(0, r.length), this._pendingSegments[n] = null, this._pendingRemoveRanges[n] = null, this._lastInitSegments[n] = null; let l = this._sourceBuffers[n]; if (l) { if (t.readyState !== "closed") { try { t.removeSourceBuffer(l) } catch (a) { Log.e(this.TAG, a.message) } l.removeEventListener("error", this.e.onSourceBufferError), l.removeEventListener("updateend", this.e.onSourceBufferUpdateEnd) } this._mimeTypes[n] = null, this._sourceBuffers[n] = null } } if (t.readyState === "open") try { t.endOfStream() } catch (n) { Log.e(this.TAG, n.message) } t.removeEventListener("sourceopen", this.e.onSourceOpen), t.removeEventListener("sourceended", this.e.onSourceEnded), t.removeEventListener("sourceclose", this.e.onSourceClose), this._pendingSourceBufferInit = [], this._isBufferFull = !1, this._idrList.clear(), this._mediaSource = null } this._mediaElement && (this._mediaElement.src = "", this._mediaElement.removeAttribute("src"), this._mediaElement = null), this._mediaSourceObjectURL && (window.URL.revokeObjectURL(this._mediaSourceObjectURL), this._mediaSourceObjectURL = null) } appendInitSegment(t, n) { if (!this._mediaSource || this._mediaSource.readyState !== "open") { this._pendingSourceBufferInit.push(t), this._pendingSegments[t.type].push(t); return } let r = t, l = `${r.container}`; r.codec && r.codec.length > 0 && (l += `;codecs=${r.codec}`); let a = !1; if (Log.v(this.TAG, "Received Initialization Segment, mimeType: " + l), this._lastInitSegments[r.type] = r, l !== this._mimeTypes[r.type]) { if (this._mimeTypes[r.type]) Log.v(this.TAG, `Notice: ${r.type} mimeType changed, origin: ${this._mimeTypes[r.type]}, target: ${l}`); else { a = !0; try { let e = this._sourceBuffers[r.type] = this._mediaSource.addSourceBuffer(l); e.addEventListener("error", this.e.onSourceBufferError), e.addEventListener("updateend", this.e.onSourceBufferUpdateEnd) } catch (e) { Log.e(this.TAG, e.message), this._emitter.emit(MSEEvents.ERROR, { code: e.code, msg: e.message }); return } } this._mimeTypes[r.type] = l } n || this._pendingSegments[r.type].push(r), a || this._sourceBuffers[r.type] && !this._sourceBuffers[r.type].updating && this._doAppendSegments(), Browser.safari && r.container === "audio/mpeg" && r.mediaDuration > 0 && (this._requireSetMediaDuration = !0, this._pendingMediaDuration = r.mediaDuration / 1e3, this._updateMediaSourceDuration()) } appendMediaSegment(t) { let n = t; this._pendingSegments[n.type].push(n), this._config.autoCleanupSourceBuffer && this._needCleanupSourceBuffer() && this._doCleanupSourceBuffer(); let r = this._sourceBuffers[n.type]; r && !r.updating && !this._hasPendingRemoveRanges() && this._doAppendSegments() } seek(t) { for (let n in this._sourceBuffers) { if (!this._sourceBuffers[n]) continue; let r = this._sourceBuffers[n]; if (this._mediaSource.readyState === "open") try { r.abort() } catch (a) { Log.e(this.TAG, a.message) } this._idrList.clear(); let l = this._pendingSegments[n]; if (l.splice(0, l.length), this._mediaSource.readyState !== "closed") { for (let a = 0; a < r.buffered.length; a++) { let e = r.buffered.start(a), g = r.buffered.end(a); this._pendingRemoveRanges[n].push({ start: e, end: g }) } if (r.updating || this._doRemoveRanges(), Browser.safari) { let a = this._lastInitSegments[n]; a && (this._pendingSegments[n].push(a), r.updating || this._doAppendSegments()) } } } } endOfStream() { let t = this._mediaSource, n = this._sourceBuffers; if (!t || t.readyState !== "open") { t && t.readyState === "closed" && this._hasPendingSegments() && (this._hasPendingEos = !0); return } n.video && n.video.updating || n.audio && n.audio.updating ? this._hasPendingEos = !0 : (this._hasPendingEos = !1, t.endOfStream()) } getNearestKeyframe(t) { return this._idrList.getLastSyncPointBeforeDts(t) } _needCleanupSourceBuffer() { if (!this._config.autoCleanupSourceBuffer) return !1; let t = this._mediaElement.currentTime; for (let n in this._sourceBuffers) { let r = this._sourceBuffers[n]; if (r) { let l = r.buffered; if (l.length >= 1 && t - l.start(0) >= this._config.autoCleanupMaxBackwardDuration) return !0 } } return !1 } _doCleanupSourceBuffer() { let t = this._mediaElement.currentTime; for (let n in this._sourceBuffers) { let r = this._sourceBuffers[n]; if (r) { let l = r.buffered, a = !1; for (let e = 0; e < l.length; e++) { let g = l.start(e), _ = l.end(e); if (g <= t && t < _ + 3) { if (t - g >= this._config.autoCleanupMaxBackwardDuration) { a = !0; let y = t - this._config.autoCleanupMinBackwardDuration; this._pendingRemoveRanges[n].push({ start: g, end: y }) } } else _ < t && (a = !0, this._pendingRemoveRanges[n].push({ start: g, end: _ })) } a && !r.updating && this._doRemoveRanges() } } } _updateMediaSourceDuration() { let t = this._sourceBuffers; if (this._mediaElement.readyState === 0 || this._mediaSource.readyState !== "open" || t.video && t.video.updating || t.audio && t.audio.updating) return; let n = this._mediaSource.duration, r = this._pendingMediaDuration; r > 0 && (isNaN(n) || r > n) && (Log.v(this.TAG, `Update MediaSource duration from ${n} to ${r}`), this._mediaSource.duration = r), this._requireSetMediaDuration = !1, this._pendingMediaDuration = 0 } _doRemoveRanges() { for (let t in this._pendingRemoveRanges) { if (!this._sourceBuffers[t] || this._sourceBuffers[t].updating) continue; let n = this._sourceBuffers[t], r = this._pendingRemoveRanges[t]; for (; r.length && !n.updating;) { let l = r.shift(); n.remove(l.start, l.end) } } } _doAppendSegments() { let t = this._pendingSegments; for (let n in t) if (!(!this._sourceBuffers[n] || this._sourceBuffers[n].updating) && t[n].length > 0) { let r = t[n].shift(); if (r.timestampOffset) { let l = this._sourceBuffers[n].timestampOffset, a = r.timestampOffset / 1e3; Math.abs(l - a) > .1 && (Log.v(this.TAG, `Update MPEG audio timestampOffset from ${l} to ${a}`), this._sourceBuffers[n].timestampOffset = a), delete r.timestampOffset } if (!r.data || r.data.byteLength === 0) continue; try { this._sourceBuffers[n].appendBuffer(r.data), this._isBufferFull = !1, n === "video" && r.hasOwnProperty("info") && this._idrList.appendArray(r.info.syncPoints) } catch (l) { this._pendingSegments[n].unshift(r), l.code === 22 ? (this._isBufferFull || this._emitter.emit(MSEEvents.BUFFER_FULL), this._isBufferFull = !0) : (Log.e(this.TAG, l.message), this._emitter.emit(MSEEvents.ERROR, { code: l.code, msg: l.message })) } } } _onSourceOpen() { if (Log.v(this.TAG, "MediaSource onSourceOpen"), this._mediaSource.removeEventListener("sourceopen", this.e.onSourceOpen), this._pendingSourceBufferInit.length > 0) { let t = this._pendingSourceBufferInit; for (; t.length;) { let n = t.shift(); this.appendInitSegment(n, !0) } } this._hasPendingSegments() && this._doAppendSegments(), this._emitter.emit(MSEEvents.SOURCE_OPEN) } _onSourceEnded() { Log.v(this.TAG, "MediaSource onSourceEnded") } _onSourceClose() { Log.v(this.TAG, "MediaSource onSourceClose"), this._mediaSource && this.e != null && (this._mediaSource.removeEventListener("sourceopen", this.e.onSourceOpen), this._mediaSource.removeEventListener("sourceended", this.e.onSourceEnded), this._mediaSource.removeEventListener("sourceclose", this.e.onSourceClose)) } _hasPendingSegments() { let t = this._pendingSegments; return t.video.length > 0 || t.audio.length > 0 } _hasPendingRemoveRanges() { let t = this._pendingRemoveRanges; return t.video.length > 0 || t.audio.length > 0 } _onSourceBufferUpdateEnd() { this._requireSetMediaDuration ? this._updateMediaSourceDuration() : this._hasPendingRemoveRanges() ? this._doRemoveRanges() : this._hasPendingSegments() ? this._doAppendSegments() : this._hasPendingEos && this.endOfStream(), this._emitter.emit(MSEEvents.UPDATE_END) } _onSourceBufferError(t) { Log.e(this.TAG, `SourceBuffer Error: ${t}`) } } const ErrorTypes = { NETWORK_ERROR: "NetworkError", MEDIA_ERROR: "MediaError", OTHER_ERROR: "OtherError" }, ErrorDetails = { NETWORK_EXCEPTION: LoaderErrors.EXCEPTION, NETWORK_STATUS_CODE_INVALID: LoaderErrors.HTTP_STATUS_CODE_INVALID, NETWORK_TIMEOUT: LoaderErrors.CONNECTING_TIMEOUT, NETWORK_UNRECOVERABLE_EARLY_EOF: LoaderErrors.UNRECOVERABLE_EARLY_EOF, MEDIA_MSE_ERROR: "MediaMSEError", MEDIA_FORMAT_ERROR: DemuxErrors.FORMAT_ERROR, MEDIA_FORMAT_UNSUPPORTED: DemuxErrors.FORMAT_UNSUPPORTED, MEDIA_CODEC_UNSUPPORTED: DemuxErrors.CODEC_UNSUPPORTED }; class FlvPlayer { constructor(t, n) { if (this.TAG = "FlvPlayer", this._type = "FlvPlayer", this._emitter = new EventEmitter$1, this._config = createDefaultConfig(), typeof n == "object" && Object.assign(this._config, n), t.type.toLowerCase() !== "flv") throw new InvalidArgumentException("FlvPlayer requires an flv MediaDataSource input!"); t.isLive === !0 && (this._config.isLive = !0), this.e = { onvLoadedMetadata: this._onvLoadedMetadata.bind(this), onvSeeking: this._onvSeeking.bind(this), onvCanPlay: this._onvCanPlay.bind(this), onvStalled: this._onvStalled.bind(this), onvProgress: this._onvProgress.bind(this) }, self.performance && self.performance.now ? this._now = self.performance.now.bind(self.performance) : this._now = Date.now, this._pendingSeekTime = null, this._requestSetTime = !1, this._seekpointRecord = null, this._progressChecker = null, this._mediaDataSource = t, this._mediaElement = null, this._msectl = null, this._transmuxer = null, this._mseSourceOpened = !1, this._hasPendingLoad = !1, this._receivedCanPlay = !1, this._mediaInfo = null, this._statisticsInfo = null; let r = Browser.chrome && (Browser.version.major < 50 || Browser.version.major === 50 && Browser.version.build < 2661); this._alwaysSeekKeyframe = !!(r || Browser.msedge || Browser.msie), this._alwaysSeekKeyframe && (this._config.accurateSeek = !1) } destroy() { this._progressChecker != null && (window.clearInterval(this._progressChecker), this._progressChecker = null), this._transmuxer && this.unload(), this._mediaElement && this.detachMediaElement(), this.e = null, this._mediaDataSource = null, this._emitter.removeAllListeners(), this._emitter = null } on(t, n) { t === PlayerEvents.MEDIA_INFO ? this._mediaInfo != null && Promise.resolve().then(() => { this._emitter.emit(PlayerEvents.MEDIA_INFO, this.mediaInfo) }) : t === PlayerEvents.STATISTICS_INFO && this._statisticsInfo != null && Promise.resolve().then(() => { this._emitter.emit(PlayerEvents.STATISTICS_INFO, this.statisticsInfo) }), this._emitter.addListener(t, n) } off(t, n) { this._emitter.removeListener(t, n) } attachMediaElement(t) { if (this._mediaElement = t, t.addEventListener("loadedmetadata", this.e.onvLoadedMetadata), t.addEventListener("seeking", this.e.onvSeeking), t.addEventListener("canplay", this.e.onvCanPlay), t.addEventListener("stalled", this.e.onvStalled), t.addEventListener("progress", this.e.onvProgress), this._msectl = new MSEController(this._config), this._msectl.on(MSEEvents.UPDATE_END, this._onmseUpdateEnd.bind(this)), this._msectl.on(MSEEvents.BUFFER_FULL, this._onmseBufferFull.bind(this)), this._msectl.on(MSEEvents.SOURCE_OPEN, () => { this._mseSourceOpened = !0, this._hasPendingLoad && (this._hasPendingLoad = !1, this.load()) }), this._msectl.on(MSEEvents.ERROR, n => { this._emitter.emit(PlayerEvents.ERROR, ErrorTypes.MEDIA_ERROR, ErrorDetails.MEDIA_MSE_ERROR, n) }), this._msectl.attachMediaElement(t), this._pendingSeekTime != null) try { t.currentTime = this._pendingSeekTime, this._pendingSeekTime = null } catch { } } detachMediaElement() { this._mediaElement && (this._msectl.detachMediaElement(), this._mediaElement.removeEventListener("loadedmetadata", this.e.onvLoadedMetadata), this._mediaElement.removeEventListener("seeking", this.e.onvSeeking), this._mediaElement.removeEventListener("canplay", this.e.onvCanPlay), this._mediaElement.removeEventListener("stalled", this.e.onvStalled), this._mediaElement.removeEventListener("progress", this.e.onvProgress), this._mediaElement = null), this._msectl && (this._msectl.destroy(), this._msectl = null) } load() { if (!this._mediaElement) throw new IllegalStateException("HTMLMediaElement must be attached before load()!"); if (this._transmuxer) throw new IllegalStateException("FlvPlayer.load() has been called, please call unload() first!"); if (this._hasPendingLoad) return; if (this._config.deferLoadAfterSourceOpen && this._mseSourceOpened === !1) { this._hasPendingLoad = !0; return } this._mediaElement.readyState > 0 && (this._requestSetTime = !0, this._mediaElement.currentTime = 0), this._transmuxer = new Transmuxer(this._mediaDataSource, this._config), this._transmuxer.on(TransmuxingEvents.INIT_SEGMENT, (l, a) => { this._msectl.appendInitSegment(a) }), this._transmuxer.on(TransmuxingEvents.MEDIA_SEGMENT, (l, a) => { if (this._msectl.appendMediaSegment(a), this._config.lazyLoad && !this._config.isLive) { let e = this._mediaElement.currentTime; a.info.endDts >= (e + this._config.lazyLoadMaxDuration) * 1e3 && this._progressChecker == null && (Log.v(this.TAG, "Maximum buffering duration exceeded, suspend transmuxing task"), this._suspendTransmuxer()) } }), this._transmuxer.on(TransmuxingEvents.LOADING_COMPLETE, () => { this._msectl.endOfStream(), this._emitter.emit(PlayerEvents.LOADING_COMPLETE) }), this._transmuxer.on(TransmuxingEvents.RECOVERED_EARLY_EOF, () => { this._emitter.emit(PlayerEvents.RECOVERED_EARLY_EOF) }), this._transmuxer.on(TransmuxingEvents.IO_ERROR, (l, a) => { this._emitter.emit(PlayerEvents.ERROR, ErrorTypes.NETWORK_ERROR, l, a) }), this._transmuxer.on(TransmuxingEvents.DEMUX_ERROR, (l, a) => { this._emitter.emit(PlayerEvents.ERROR, ErrorTypes.MEDIA_ERROR, l, { code: -1, msg: a }) }), this._transmuxer.on(TransmuxingEvents.MEDIA_INFO, l => { this._mediaInfo = l, this._emitter.emit(PlayerEvents.MEDIA_INFO, Object.assign({}, l)) }), this._transmuxer.on(TransmuxingEvents.METADATA_ARRIVED, l => { this._emitter.emit(PlayerEvents.METADATA_ARRIVED, l) }), this._transmuxer.on(TransmuxingEvents.SCRIPTDATA_ARRIVED, l => { this._emitter.emit(PlayerEvents.SCRIPTDATA_ARRIVED, l) }), this._transmuxer.on(TransmuxingEvents.STATISTICS_INFO, l => { this._statisticsInfo = this._fillStatisticsInfo(l), this._emitter.emit(PlayerEvents.STATISTICS_INFO, Object.assign({}, this._statisticsInfo)) }), this._transmuxer.on(TransmuxingEvents.RECOMMEND_SEEKPOINT, l => { this._mediaElement && !this._config.accurateSeek && (this._requestSetTime = !0, this._mediaElement.currentTime = l / 1e3) }), this._transmuxer.open(); let t = this._transmuxer._controller, n = t._ioctl._loader; var r = n._onComplete; n._onComplete = function () { t._remuxer || (t._remuxer = { flushStashedSamples: function () { console.log("flushStashedSamples") } }), r() } } unload() { this._mediaElement && this._mediaElement.pause(), this._msectl && this._msectl.seek(0), this._transmuxer && (this._transmuxer.close(), this._transmuxer.destroy(), this._transmuxer = null) } play() { return this._mediaElement.play() } pause() { this._mediaElement.pause() } get type() { return this._type } get buffered() { return this._mediaElement.buffered } get duration() { return this._mediaElement.duration } get volume() { return this._mediaElement.volume } set volume(t) { this._mediaElement.volume = t } get muted() { return this._mediaElement.muted } set muted(t) { this._mediaElement.muted = t } get currentTime() { return this._mediaElement ? this._mediaElement.currentTime : 0 } set currentTime(t) { this._mediaElement ? this._internalSeek(t) : this._pendingSeekTime = t } get mediaInfo() { return Object.assign({}, this._mediaInfo) } get statisticsInfo() { return this._statisticsInfo == null && (this._statisticsInfo = {}), this._statisticsInfo = this._fillStatisticsInfo(this._statisticsInfo), Object.assign({}, this._statisticsInfo) } _fillStatisticsInfo(t) { if (t.playerType = this._type, !(this._mediaElement instanceof HTMLVideoElement)) return t; let n = !0, r = 0, l = 0; if (this._mediaElement.getVideoPlaybackQuality) { let a = this._mediaElement.getVideoPlaybackQuality(); r = a.totalVideoFrames, l = a.droppedVideoFrames } else this._mediaElement.webkitDecodedFrameCount != null ? (r = this._mediaElement.webkitDecodedFrameCount, l = this._mediaElement.webkitDroppedFrameCount) : n = !1; return n && (t.decodedFrames = r, t.droppedFrames = l), t } _onmseUpdateEnd() { if (!this._config.lazyLoad || this._config.isLive) return; let t = this._mediaElement.buffered, n = this._mediaElement.currentTime, r = 0; for (let l = 0; l < t.length; l++) { let a = t.start(l), e = t.end(l); if (a <= n && n < e) { r = e; break } } r >= n + this._config.lazyLoadMaxDuration && this._progressChecker == null && (Log.v(this.TAG, "Maximum buffering duration exceeded, suspend transmuxing task"), this._suspendTransmuxer()) } _onmseBufferFull() { Log.v(this.TAG, "MSE SourceBuffer is full, suspend transmuxing task"), this._progressChecker == null && this._suspendTransmuxer() } _suspendTransmuxer() { this._transmuxer && (this._transmuxer.pause(), this._progressChecker == null && (this._progressChecker = window.setInterval(this._checkProgressAndResume.bind(this), 1e3))) } _checkProgressAndResume() { let t = this._mediaElement.currentTime, n = this._mediaElement.buffered, r = !1; for (let l = 0; l < n.length; l++) { let a = n.start(l), e = n.end(l); if (t >= a && t < e) { t >= e - this._config.lazyLoadRecoverDuration && (r = !0); break } } r && (window.clearInterval(this._progressChecker), this._progressChecker = null, r && (Log.v(this.TAG, "Continue loading from paused position"), this._transmuxer.resume())) } _isTimepointBuffered(t) { let n = this._mediaElement.buffered; for (let r = 0; r < n.length; r++) { let l = n.start(r), a = n.end(r); if (t >= l && t < a) return !0 } return !1 } _internalSeek(t) { let n = this._isTimepointBuffered(t), r = !1, l = 0; if (t < 1 && this._mediaElement.buffered.length > 0) { let a = this._mediaElement.buffered.start(0); (a < 1 && t < a || Browser.safari) && (r = !0, l = Browser.safari ? .1 : a) } if (r) this._requestSetTime = !0, this._mediaElement.currentTime = l; else if (n) { if (!this._alwaysSeekKeyframe) this._requestSetTime = !0, this._mediaElement.currentTime = t; else { let a = this._msectl.getNearestKeyframe(Math.floor(t * 1e3)); this._requestSetTime = !0, a != null ? this._mediaElement.currentTime = a.dts / 1e3 : this._mediaElement.currentTime = t } this._progressChecker != null && this._checkProgressAndResume() } else this._progressChecker != null && (window.clearInterval(this._progressChecker), this._progressChecker = null), this._msectl.seek(t), this._transmuxer.seek(Math.floor(t * 1e3)), this._config.accurateSeek && (this._requestSetTime = !0, this._mediaElement.currentTime = t) } _checkAndApplyUnbufferedSeekpoint() { if (this._seekpointRecord) if (this._seekpointRecord.recordTime <= this._now() - 100) { let t = this._mediaElement.currentTime; this._seekpointRecord = null, this._isTimepointBuffered(t) || (this._progressChecker != null && (window.clearTimeout(this._progressChecker), this._progressChecker = null), this._msectl.seek(t), this._transmuxer.seek(Math.floor(t * 1e3)), this._config.accurateSeek && (this._requestSetTime = !0, this._mediaElement.currentTime = t)) } else window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50) } _checkAndResumeStuckPlayback(t) { let n = this._mediaElement; if (t || !this._receivedCanPlay || n.readyState < 2) { let r = n.buffered; r.length > 0 && n.currentTime < r.start(0) && (Log.w(this.TAG, `Playback seems stuck at ${n.currentTime}, seek to ${r.start(0)}`), this._requestSetTime = !0, this._mediaElement.currentTime = r.start(0), this._mediaElement.removeEventListener("progress", this.e.onvProgress)) } else this._mediaElement.removeEventListener("progress", this.e.onvProgress) } _onvLoadedMetadata(t) { this._pendingSeekTime != null && (this._mediaElement.currentTime = this._pendingSeekTime, this._pendingSeekTime = null) } _onvSeeking(t) { let n = this._mediaElement.currentTime, r = this._mediaElement.buffered; if (this._requestSetTime) { this._requestSetTime = !1; return } if (n < 1 && r.length > 0) { let l = r.start(0); if (l < 1 && n < l || Browser.safari) { this._requestSetTime = !0, this._mediaElement.currentTime = Browser.safari ? .1 : l; return } } if (this._isTimepointBuffered(n)) { if (this._alwaysSeekKeyframe) { let l = this._msectl.getNearestKeyframe(Math.floor(n * 1e3)); l != null && (this._requestSetTime = !0, this._mediaElement.currentTime = l.dts / 1e3) } this._progressChecker != null && this._checkProgressAndResume(); return } this._seekpointRecord = { seekPoint: n, recordTime: this._now() }, window.setTimeout(this._checkAndApplyUnbufferedSeekpoint.bind(this), 50) } _onvCanPlay(t) { this._receivedCanPlay = !0, this._mediaElement.removeEventListener("canplay", this.e.onvCanPlay) } _onvStalled(t) { this._checkAndResumeStuckPlayback(!0) } _onvProgress(t) { this._checkAndResumeStuckPlayback() } flush(t) { this._msectl.seek(0), window.clearInterval(this._progressChecker), this._internalSeek(0), this._mediaElement.currentTime = 0, this._requestSetTime = !0, this._pendingSeekTime = null, this._transmuxer._controller._remuxer.seek(0), this._transmuxer._controller._remuxer.insertDiscontinuity() } } class NativePlayer { constructor(t, n) { if (this.TAG = "NativePlayer", this._type = "NativePlayer", this._emitter = new EventEmitter$1, this._config = createDefaultConfig(), typeof n == "object" && Object.assign(this._config, n), t.type.toLowerCase() === "flv") throw new InvalidArgumentException("NativePlayer does't support flv MediaDataSource input!"); if (t.hasOwnProperty("segments")) throw new InvalidArgumentException(`NativePlayer(${t.type}) doesn't support multipart playback!`); this.e = { onvLoadedMetadata: this._onvLoadedMetadata.bind(this) }, this._pendingSeekTime = null, this._statisticsReporter = null, this._mediaDataSource = t, this._mediaElement = null } destroy() { this._mediaElement && (this.unload(), this.detachMediaElement()), this.e = null, this._mediaDataSource = null, this._emitter.removeAllListeners(), this._emitter = null } on(t, n) { t === PlayerEvents.MEDIA_INFO ? this._mediaElement != null && this._mediaElement.readyState !== 0 && Promise.resolve().then(() => { this._emitter.emit(PlayerEvents.MEDIA_INFO, this.mediaInfo) }) : t === PlayerEvents.STATISTICS_INFO && this._mediaElement != null && this._mediaElement.readyState !== 0 && Promise.resolve().then(() => { this._emitter.emit(PlayerEvents.STATISTICS_INFO, this.statisticsInfo) }), this._emitter.addListener(t, n) } off(t, n) { this._emitter.removeListener(t, n) } attachMediaElement(t) { if (this._mediaElement = t, t.addEventListener("loadedmetadata", this.e.onvLoadedMetadata), this._pendingSeekTime != null) try { t.currentTime = this._pendingSeekTime, this._pendingSeekTime = null } catch { } } detachMediaElement() { this._mediaElement && (this._mediaElement.src = "", this._mediaElement.removeAttribute("src"), this._mediaElement.removeEventListener("loadedmetadata", this.e.onvLoadedMetadata), this._mediaElement = null), this._statisticsReporter != null && (window.clearInterval(this._statisticsReporter), this._statisticsReporter = null) } load() { if (!this._mediaElement) throw new IllegalStateException("HTMLMediaElement must be attached before load()!"); this._mediaElement.src = this._mediaDataSource.url, this._mediaElement.readyState > 0 && (this._mediaElement.currentTime = 0), this._mediaElement.preload = "auto", this._mediaElement.load(), this._statisticsReporter = window.setInterval(this._reportStatisticsInfo.bind(this), this._config.statisticsInfoReportInterval) } unload() { this._mediaElement && (this._mediaElement.src = "", this._mediaElement.removeAttribute("src")), this._statisticsReporter != null && (window.clearInterval(this._statisticsReporter), this._statisticsReporter = null) } play() { return this._mediaElement.play() } pause() { this._mediaElement.pause() } get type() { return this._type } get buffered() { return this._mediaElement.buffered } get duration() { return this._mediaElement.duration } get volume() { return this._mediaElement.volume } set volume(t) { this._mediaElement.volume = t } get muted() { return this._mediaElement.muted } set muted(t) { this._mediaElement.muted = t } get currentTime() { return this._mediaElement ? this._mediaElement.currentTime : 0 } set currentTime(t) { this._mediaElement ? this._mediaElement.currentTime = t : this._pendingSeekTime = t } get mediaInfo() { let n = { mimeType: (this._mediaElement instanceof HTMLAudioElement ? "audio/" : "video/") + this._mediaDataSource.type }; return this._mediaElement && (n.duration = Math.floor(this._mediaElement.duration * 1e3), this._mediaElement instanceof HTMLVideoElement && (n.width = this._mediaElement.videoWidth, n.height = this._mediaElement.videoHeight)), n } get statisticsInfo() { let t = { playerType: this._type, url: this._mediaDataSource.url }; if (!(this._mediaElement instanceof HTMLVideoElement)) return t; let n = !0, r = 0, l = 0; if (this._mediaElement.getVideoPlaybackQuality) { let a = this._mediaElement.getVideoPlaybackQuality(); r = a.totalVideoFrames, l = a.droppedVideoFrames } else this._mediaElement.webkitDecodedFrameCount != null ? (r = this._mediaElement.webkitDecodedFrameCount, l = this._mediaElement.webkitDroppedFrameCount) : n = !1; return n && (t.decodedFrames = r, t.droppedFrames = l), t } _onvLoadedMetadata(t) { this._pendingSeekTime != null && (this._mediaElement.currentTime = this._pendingSeekTime, this._pendingSeekTime = null), this._emitter.emit(PlayerEvents.MEDIA_INFO, this.mediaInfo) } _reportStatisticsInfo() { this._emitter.emit(PlayerEvents.STATISTICS_INFO, this.statisticsInfo) } } Polyfill.install(); function createPlayer(h, t) { let n = h; if (n == null || typeof n != "object") throw new InvalidArgumentException("MediaDataSource must be an javascript object!"); if (!n.hasOwnProperty("type")) throw new InvalidArgumentException("MediaDataSource must has type field to indicate video file type!"); switch (n.type) { case "flv": return new FlvPlayer(n, t); default: return new NativePlayer(n, t) } } function isSupported() { return Features.supportMSEH264Playback() } function getFeatureList() { return Features.getFeatureList() } let flvjs = {}; flvjs.createPlayer = createPlayer, flvjs.isSupported = isSupported, flvjs.getFeatureList = getFeatureList, flvjs.BaseLoader = BaseLoader, flvjs.LoaderStatus = LoaderStatus, flvjs.LoaderErrors = LoaderErrors, flvjs.Events = PlayerEvents, flvjs.ErrorTypes = ErrorTypes, flvjs.ErrorDetails = ErrorDetails, flvjs.FlvPlayer = FlvPlayer, flvjs.NativePlayer = NativePlayer, flvjs.LoggingControl = LoggingControl, console.error = () => { }, Object.defineProperty(flvjs, "version", { enumerable: !0, get: function () { return __VERSION__ } }); class Resampler { constructor(t, n, r, l) { if (!t || !n || !r) throw new Error("Invalid settings specified for the resampler."); this.resampler = null, this.fromSampleRate = t, this.toSampleRate = n, this.channels = r || 0, this.inputBufferSize = l, this.initialize() } initialize() { this.fromSampleRate == this.toSampleRate ? (this.resampler = t => t, this.ratioWeight = 1) : (this.fromSampleRate < this.toSampleRate ? (this.linearInterpolation(), this.lastWeight = 1) : (this.multiTap(), this.tailExists = !1, this.lastWeight = 0), this.initializeBuffers(), this.ratioWeight = this.fromSampleRate / this.toSampleRate) } bufferSlice(t) { try { return this.outputBuffer.subarray(0, t) } catch { try { return this.outputBuffer.length = t, this.outputBuffer } catch { return this.outputBuffer.slice(0, t) } } } initializeBuffers() { this.outputBufferSize = Math.ceil(this.inputBufferSize * this.toSampleRate / this.fromSampleRate / this.channels * 1.0000004768371582) + this.channels + this.channels; try { this.outputBuffer = new Float32Array(this.outputBufferSize), this.lastOutput = new Float32Array(this.channels) } catch { this.outputBuffer = [], this.lastOutput = [] } } linearInterpolation() { this.resampler = t => { let n = t.length; const r = this.channels; let l, a, e, g, _, y; if (n % r !== 0) throw new Error("Buffer was of incorrect sample length."); if (n <= 0) return []; const x = this.outputBufferSize, E = this.ratioWeight; l = this.lastWeight, a = 0, e = 0, g = 0, _ = 0; const C = this.outputBuffer; for (; l < 1; l += E)for (e = l % 1, a = 1 - e, this.lastWeight = l % 1, y = 0; y < this.channels; ++y)C[_++] = this.lastOutput[y] * a + t[y] * e; for (l -= 1, n -= r, g = Math.floor(l) * r; _ < x && g < n;) { for (e = l % 1, a = 1 - e, y = 0; y < this.channels; ++y)C[_++] = t[g + (y > 0 ? y : 0)] * a + t[g + (r + y)] * e; l += E, g = Math.floor(l) * r } for (y = 0; y < r; ++y)this.lastOutput[y] = t[g++]; return this.bufferSlice(_) } } multiTap() { this.resampler = t => { const n = t.length, r = this.channels; let l, a, e, g, _, y, x; if (n % r !== 0) throw new Error("Buffer was of incorrect sample length."); if (n <= 0) return []; const E = this.outputBufferSize, C = [], L = this.ratioWeight; l = 0, e = 0, g = 0, _ = !this.tailExists, this.tailExists = !1; const A = this.outputBuffer; for (y = 0, x = 0, a = 0; a < r; ++a)C[a] = 0; do { if (_) for (l = L, a = 0; a < r; ++a)C[a] = 0; else { for (l = this.lastWeight, a = 0; a < r; ++a)C[a] = this.lastOutput[a]; _ = !0 } for (; l > 0 && e < n;)if (g = 1 + e - x, l >= g) { for (a = 0; a < r; ++a)C[a] += t[e++] * g; x = e, l -= g } else { for (a = 0; a < r; ++a)C[a] += t[e + (a > 0 ? a : 0)] * l; x += l, l = 0; break } if (l === 0) for (a = 0; a < r; ++a)A[y++] = C[a] / L; else { for (this.lastWeight = l, a = 0; a < r; ++a)this.lastOutput[a] = C[a]; this.tailExists = !0; break } } while (e < n && y < E); return this.bufferSlice(y) } } resample(t) { return this.fromSampleRate == this.toSampleRate ? this.ratioWeight = 1 : (this.fromSampleRate < this.toSampleRate ? this.lastWeight = 1 : (this.tailExists = !1, this.lastWeight = 0), this.initializeBuffers(), this.ratioWeight = this.fromSampleRate / this.toSampleRate), this.resampler(t) } } window.URL = window.URL || window.webkitURL; const navigator$1 = window.navigator; navigator$1.mediaDevices && (navigator$1.mediaDevices.getUserMedia = navigator$1.mediaDevices.getUserMedia || navigator$1.webkitGetUserMedia || navigator$1.mozGetUserMedia || navigator$1.msGetUserMedia); class HZRecorderReal { constructor(t, n) { let r; this.config = n || {}, this.config.sampleBits = 16, this.config.sampleRate = 16e3, this.config.channelCount = 1; const l = new (window.webkitAudioContext || window.AudioContext), a = l.createMediaStreamSource(t), g = (l.createScriptProcessor || l.createJavaScriptNode).apply(l, [4096, 1, 1]), _ = { size: 0, buffer: [], sampleRate: l.sampleRate, input: function (y) { this.buffer.push(new Float32Array(y)), this.size += y.length }, resample: function (y, x = 16e3) { return new Resampler(this.sampleRate, x, 1, y.length).resample(y) }, resampleAndEncodeWAV: function (y = 16e3, x = 16, E = 0, C = -1) { let L = this.buffer.map(P => this.resample(P, y)).reduce((P, $) => [...P, ...$], []); const A = y * E; let I = L.length; C >= 0 && (I = y * C), L = L.slice(A, I); const D = L.length * (x / 8), w = new ArrayBuffer(44 + D), S = new DataView(w), O = 1; let F = 0; const j = function (P) { for (let $ = 0; $ < P.length; $++)S.setUint8(F + $, P.charCodeAt($)) }; if (j("RIFF"), F += 4, S.setUint32(F, 36 + D, !0), F += 4, j("WAVE"), F += 4, j("fmt "), F += 4, S.setUint32(F, 16, !0), F += 4, S.setUint16(F, 1, !0), F += 2, S.setUint16(F, O, !0), F += 2, S.setUint32(F, y, !0), F += 4, S.setUint32(F, O * y * (x / 8), !0), F += 4, S.setUint16(F, O * (x / 8), !0), F += 2, S.setUint16(F, x, !0), F += 2, j("data"), F += 4, S.setUint32(F, D, !0), F += 4, x === 8) for (let P = 0; P < L.length; P++, F++) { const $ = Math.max(-1, Math.min(1, L[P])); let V = $ < 0 ? $ * 32768 : $ * 32767; V = 255 / (65535 / (V + 32768)), S.setInt8(F, V) } else for (let P = 0; P < L.length; P++, F += 2) { const $ = Math.max(-1, Math.min(1, L[P])); S.setInt16(F, $ < 0 ? $ * 32768 : $ * 32767, !0) } return new Blob([S], { type: "audio/wav" }) }, quantize: function (y, x = 16) { const E = y.length * (x / 8), C = new DataView(new ArrayBuffer(E)); let L = 0; if (x === 8) for (let A = 0; A < y.length; A++, L++) { const I = Math.max(-1, Math.min(1, y[A])); let D = I < 0 ? I * 32768 : I * 32767; D = 255 / (65535 / (D + 32768)), C.setInt8(L, D) } else for (let A = 0; A < y.length; A++, L += 2) { const I = Math.max(-1, Math.min(1, y[A])); C.setInt16(L, I < 0 ? I * 32768 : I * 32767, !0) } return C } }; this.start = function () { r = !0, a.connect(g), g.connect(l.destination) }, this.pause = function () { r = !1, g.disconnect(), l.suspend() }, this.resume = function () { r = !0, l.resume(), a.connect(g), g.connect(l.destination) }, this.stop = function () { r = !1, g.disconnect(), l.close(), t == null || t.getTracks().forEach(y => y.stop()), console.log("stop") }, this.getTrimBlob = function (y = 0, x = -1) { return this.stop(), console.log("getTrimBlob"), _.resampleAndEncodeWAV(16e3, 16, y, x) }, this.getBlob = function () { return this.stop(), _.resampleAndEncodeWAV() }, this.upload = function (y) { new window.FormData().append("file", this.getBlob()) }, this.play = function () { const y = document.querySelector("audio"); y && (y.src = window.URL.createObjectURL(this.getBlob())) }, this.asrCallback = function (y) { console.log(y) }, g.onaudioprocess = function (y) { if (!r) return; const x = y.inputBuffer.getChannelData(0), E = _.resample(x), C = _.quantize(E, 16); n.blobSend(C.buffer) } } } HZRecorderReal.prototype.throwError = function (h) { throw console.log(h), Error(h) }, HZRecorderReal.prototype.canRecording = ((lt = navigator$1.mediaDevices) == null ? void 0 : lt.getUserMedia) != null, HZRecorderReal.prototype.get = function (h, t) { if (h) if (navigator$1.mediaDevices && navigator$1.mediaDevices.getUserMedia) navigator$1.mediaDevices.getUserMedia({ audio: !0 }).then(n => { const r = new HZRecorderReal(n, t); h(r) }).catch(n => { switch (t.openErr && t.openErr(), n.code || n.name) { case "PERMISSION_DENIED": case "PermissionDeniedError": HZRecorderReal.prototype.throwError("用户拒绝提供信息。"); break; case "NOT_SUstreamBlobPPORTED_ERROR": case "NotSupportedError": HZRecorderReal.prototype.throwError("浏览器不支持硬件设备。"); break; case "MANDATORY_UNSATISFIED_ERROR": case "MandatoryUnsatisfiedError": HZRecorderReal.prototype.throwError("无法发现指定的硬件设备。"); break; default: HZRecorderReal.prototype.throwError("无法打开麦克风。异常信息:" + n); break } }); else { HZRecorderReal.prototype.throwError("当前浏览器不支持录音功能。"); return } }; function jsRecorder(h, t, n) { var r; function l() { HZRecorderReal.prototype.get(g => { console.log("send-success"), r = g, r == null || r.start(), t() }, { blobSend: g => { h(g) }, openErr: n }) } function a() { r == null || r.stop() } function e() { r == null || r.stop(), setTimeout(() => { r == null || r.start() }, 40) } return { recStart: l, recStop: a, recRecord: e } } const micro$1 = (h, t) => { if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { let { recStart: n, recStop: r, recRecord: l } = jsRecorder(function (a) { h(a) }, () => { t({ type: "1", val: "获取麦克权限成功" }) }, () => { t({ type: "0", val: "获取麦克权限失败" }) }); return { recStart: n, recStop: r, recRecord: l } } else t({ type: "0", val: "环境不支持!" }) }; function asrWs(h) { let t = null; const { recStart: n, recStop: r, recRecord: l } = micro$1(function (_) { try { if ((t == null ? void 0 : t.readyState) == 1) { let y = new ArrayBuffer(_.byteLength + 3), x = new Uint8Array(y), E = new Uint8Array(_); x.set(new Uint8Array([65, 83, 82]), 0), x.set(E, 3), t.send(x) } } catch (y) { console.log(y) } }, function (_) { _.type == "1" && h(_) }) || {}; return { asrDestroy: () => { r && r(), t = null }, asrWsAppoint: _ => { t = _ }, asrStart: () => { n && n() } } } const slientVideoLength = (h, t) => { let n = null; function r() { h.buffered.length > 0 && h.buffered.end(0) > .6 ? t() : n = setTimeout(r, 100) } return { start: function () { n && clearTimeout(n), r() }, end: function () { n && clearTimeout(n), n = null } } }, webglCut$1 = { status: !0, curVideo: null, lastTime: null, load(h, t, n, r, l) { this.curVideo = this.video = h, this.slient = t, this.canvas = n, this.gl = this.canvas.getContext("webgl2") || this.canvas.getContext("webgl") || this.canvas.getContext("experimental-webgl"); const a = this; this.slientVideoClient = slientVideoLength(t, () => { a.slient && a.slient.getAttribute("src") && (a.endWebcam(), a.slient && a.slient.play().then(I => { console.log("切换静音视频播放成功") }).catch(I => { console.log("切换静音视频播放失败", I) }), a.slient && (a.curVideo = a.slient), a.curVideo && a.startWebcam()) }); const e = this.gl, g = e.createShader(e.VERTEX_SHADER); e.shaderSource(g, "attribute vec2 c; void main(void) { gl_Position=vec4(c, 0.0, 1.0); }"), e.compileShader(g); const _ = e.createShader(e.FRAGMENT_SHADER); let y = ` precision mediump float; uniform sampler2D tex; uniform float texWidth; uniform float texHeight; const vec3 keyColor = vec3(0.47, 1.0, 0.47); uniform float similarity; uniform float smoothness; uniform float spill; vec2 RGBtoUV(vec3 rgb) { return vec2( rgb.r * -0.169 + rgb.g * -0.331 + rgb.b * 0.5 + 0.5, rgb.r * 0.5 + rgb.g * -0.419 + rgb.b * -0.081 + 0.5 ); } vec4 GetRgba(float detaX, float detaY) { vec2 texCoord = vec2((gl_FragCoord.x + detaX)/texWidth, 1.0 - (gl_FragCoord.y + detaY)/texHeight); vec4 rgba = texture2D(tex, texCoord); float green = rgba.g - max(rgba.r, rgba.b); float greenKey = keyColor.g - max(keyColor.r, keyColor.b); float mask = smoothstep(greenKey-0.1, 0.0, green); rgba.a = mask; return rgba; } vec4 ProcessChromaKey() { vec4 rgba = GetRgba(0.0, 0.0); if (rgba.a > 0.0 && rgba.a < 1.0) { vec4 rgbas[9]; float maxMask = 0.0; vec4 minRgba = rgba; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { vec4 tmp; if (i == 0 && j == 0) { tmp = rgba; } else { tmp = GetRgba(float(i), float(j)); } rgbas[(i+1)*3 + (j+1)] = tmp; if (tmp.a > maxMask) { maxMask = tmp.a; minRgba = tmp; } } } rgbas[4] = minRgba; rgbas[4].a = rgba.a; vec4 dest = vec4(0.0, 0.0, 0.0, 0.0); float gs[9]; gs[0] = gs[2] = gs[6] = gs[8] = 0.05; gs[1] = gs[3] = gs[5] = gs[7] = 0.05; gs[4] = 0.6; for(int i = 0; i < 9; i++) { dest.rgb = dest.rgb + rgbas[i].rgb * gs[i]; } gs[0] = gs[2] = gs[6] = gs[8] = 0.05; gs[1] = gs[3] = gs[5] = gs[7] = 0.15; gs[4] = 0.2; for(int i = 0; i < 9; i++) { dest.a = dest.a + rgbas[i].a* gs[i]; } rgba.rgb = dest.rgb; rgba.a = dest.a; if (rgba.g > rgba.r && rgba.g > rgba.b) { rgba.g = max(rgba.r, rgba.b); } rgba.rgb = rgba.rgb * rgba.a; } else { rgba.rgb = rgba.rgb * rgba.a; } return rgba; } void main(void) { gl_FragColor = ProcessChromaKey(); } `; l == "fragment-shader-nocut" && (y = ` precision mediump float; uniform sampler2D tex; uniform float texWidth; uniform float texHeight; void main(void) { vec2 texCoord = vec2(gl_FragCoord.x/texWidth, 1.0 - (gl_FragCoord.y/texHeight)); gl_FragColor =texture2D(tex, texCoord); } `), e.shaderSource(_, y), e.compileShader(_); const x = e.createProgram(); e.attachShader(x, g), e.attachShader(x, _), e.linkProgram(x), e.useProgram(x); const E = e.createBuffer(); e.bindBuffer(e.ARRAY_BUFFER, E), e.bufferData(e.ARRAY_BUFFER, new Float32Array([-1, 1, -1, -1, 1, -1, 1, 1]), e.STATIC_DRAW); const C = e.getAttribLocation(x, "c"); e.vertexAttribPointer(C, 2, e.FLOAT, !1, 0, 0), e.enableVertexAttribArray(C), e.activeTexture(e.TEXTURE0); const L = e.createTexture(); e.bindTexture(e.TEXTURE_2D, L), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_S, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_T, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MIN_FILTER, e.LINEAR), this.texLoc = e.getUniformLocation(x, "tex"), this.texWidthLoc = e.getUniformLocation(x, "texWidth"), this.texHeightLoc = e.getUniformLocation(x, "texHeight"), this.keyColorLoc = e.getUniformLocation(x, "keyColor"), this.similarityLoc = e.getUniformLocation(x, "similarity"), this.smoothnessLoc = e.getUniformLocation(x, "smoothness"), this.spillLoc = e.getUniformLocation(x, "spill"), r() }, slicePlay() { this.slientVideoClient.start() }, videoPlay() { this.endWebcam(), this.slient && this.slient.pause(), this.video && (this.curVideo = this.video), this.curVideo && this.startWebcam() }, startWebcam() { const h = this; h.status = !0; const t = this.gl; function n(r, l) { if (!h.curVideo) { h.status && requestAnimationFrame(n); return } let a = parseInt(performance.now()); if (h.lastTime && a - h.lastTime <= 30) { requestAnimationFrame(n); return } h.lastTime = a; const e = (h.curVideo || h.slient).getAttribute("width"), g = (h.curVideo || h.slient).getAttribute("height"); t.viewport(0, 0, e, g), t.texImage2D(t.TEXTURE_2D, 0, t.RGBA, t.RGBA, t.UNSIGNED_BYTE, h.curVideo), t.uniform1i(h.texLoc, 0), t.uniform1f(h.texWidthLoc, e), t.uniform1f(h.texHeightLoc, g); const _ = "00ff00"; t.uniform3f(h.keyColorLoc, parseInt(_.substr(0, 2), 16) / 255, parseInt(_.substr(2, 2), 16) / 255, parseInt(_.substr(4, 2), 16) / 255), t.uniform1f(h.similarityLoc, parseFloat(.4)), t.uniform1f(h.smoothnessLoc, parseFloat(.1)), t.uniform1f(h.spillLoc, parseFloat(.2)), t.drawArrays(t.TRIANGLE_FAN, 0, 4), h.status && requestAnimationFrame(n) } requestAnimationFrame(n) }, startWebcamOutline(h, t) { this.canvas; const n = this.video, r = this.gl, l = this; l.status = !0; function a(e, g) { r.viewport(0, 0, h, t), r.texImage2D(r.TEXTURE_2D, 0, r.RGB, r.RGB, r.UNSIGNED_BYTE, n), r.uniform1i(l.texLoc, 0), r.uniform1f(l.texWidthLoc, h), r.uniform1f(l.texHeightLoc, t); const _ = "00ff00"; r.uniform3f(l.keyColorLoc, parseInt(_.substr(0, 2), 16) / 255, parseInt(_.substr(2, 2), 16) / 255, parseInt(_.substr(4, 2), 16) / 255), r.uniform1f(l.similarityLoc, parseFloat(.4)), r.uniform1f(l.smoothnessLoc, parseFloat(.1)), r.uniform1f(l.spillLoc, parseFloat(.1)), r.drawArrays(r.TRIANGLE_FAN, 0, 4), l.status && requestAnimationFrame(a) } requestAnimationFrame(a) }, endWebcam() { var h; this.status = !1, (h = this.slientVideoClient) == null || h.end() }, destroy() { var h; this.status = !1, (h = this.slientVideoClient) == null || h.end(), this.slientVideoClient = null, this.curVideo = this.video = null, this.slient = null, this.canvas = null, this.gl = null } }; window.webglCut = webglCut$1; let Emitter$2 = class { on(t, n, r) { const l = this.e || (this.e = {}); return (l[t] || (l[t] = [])).push({ fn: n, ctx: r }), this } once(t, n, r) { const l = this; function a(...e) { l.off(t, a), n.apply(r, e) } return a._ = n, this.on(t, a, r) } emit(t, ...n) { const r = ((this.e || (this.e = {}))[t] || []).slice(); for (let l = 0; l < r.length; l += 1)r[l].fn.apply(r[l].ctx, n); return this } off(t, n) { const r = this.e || (this.e = {}), l = r[t], a = []; if (l && n) for (let e = 0, g = l.length; e < g; e += 1)l[e].fn !== n && l[e].fn._ !== n && a.push(l[e]); return a.length ? r[t] = a : delete r[t], this } }; new Blob([new Uint8Array([255, 227, 24, 196, 0, 0, 0, 3, 72, 1, 64, 0, 0, 4, 132, 16, 31, 227, 192, 225, 76, 255, 67, 12, 255, 221, 27, 255, 228, 97, 73, 63, 255, 195, 131, 69, 192, 232, 223, 255, 255, 207, 102, 239, 255, 255, 255, 101, 158, 206, 70, 20, 59, 255, 254, 95, 70, 149, 66, 4, 16, 128, 0, 2, 2, 32, 240, 138, 255, 36, 106, 183, 255, 227, 24, 196, 59, 11, 34, 62, 80, 49, 135, 40, 0, 253, 29, 191, 209, 200, 141, 71, 7, 255, 252, 152, 74, 15, 130, 33, 185, 6, 63, 255, 252, 195, 70, 203, 86, 53, 15, 255, 255, 247, 103, 76, 121, 64, 32, 47, 255, 34, 227, 194, 209, 138, 76, 65, 77, 69, 51, 46, 57, 55, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 255, 227, 24, 196, 73, 13, 153, 210, 100, 81, 135, 56, 0, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170])], { type: "audio/mpeg" }), new Blob([new Uint8Array([0, 0, 0, 28, 102, 116, 121, 112, 105, 115, 111, 109, 0, 0, 2, 0, 105, 115, 111, 109, 105, 115, 111, 50, 109, 112, 52, 49, 0, 0, 0, 8, 102, 114, 101, 101, 0, 0, 2, 239, 109, 100, 97, 116, 33, 16, 5, 32, 164, 27, 255, 192, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 55, 167, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 112, 33, 16, 5, 32, 164, 27, 255, 192, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 55, 167, 128, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 112, 0, 0, 2, 194, 109, 111, 111, 118, 0, 0, 0, 108, 109, 118, 104, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 232, 0, 0, 0, 47, 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, 0, 0, 0, 3, 0, 0, 1, 236, 116, 114, 97, 107, 0, 0, 0, 92, 116, 107, 104, 100, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 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, 36, 101, 100, 116, 115, 0, 0, 0, 28, 101, 108, 115, 116, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 47, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 100, 109, 100, 105, 97, 0, 0, 0, 32, 109, 100, 104, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 172, 68, 0, 0, 8, 0, 85, 196, 0, 0, 0, 0, 0, 45, 104, 100, 108, 114, 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, 0, 0, 1, 15, 109, 105, 110, 102, 0, 0, 0, 16, 115, 109, 104, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 100, 105, 110, 102, 0, 0, 0, 28, 100, 114, 101, 102, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 12, 117, 114, 108, 32, 0, 0, 0, 1, 0, 0, 0, 211, 115, 116, 98, 108, 0, 0, 0, 103, 115, 116, 115, 100, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 87, 109, 112, 52, 97, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 16, 0, 0, 0, 0, 172, 68, 0, 0, 0, 0, 0, 51, 101, 115, 100, 115, 0, 0, 0, 0, 3, 128, 128, 128, 34, 0, 2, 0, 4, 128, 128, 128, 20, 64, 21, 0, 0, 0, 0, 1, 244, 0, 0, 1, 243, 249, 5, 128, 128, 128, 2, 18, 16, 6, 128, 128, 128, 1, 2, 0, 0, 0, 24, 115, 116, 116, 115, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 28, 115, 116, 115, 99, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 28, 115, 116, 115, 122, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 115, 0, 0, 1, 116, 0, 0, 0, 20, 115, 116, 99, 111, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 44, 0, 0, 0, 98, 117, 100, 116, 97, 0, 0, 0, 90, 109, 101, 116, 97, 0, 0, 0, 0, 0, 0, 0, 33, 104, 100, 108, 114, 0, 0, 0, 0, 0, 0, 0, 0, 109, 100, 105, 114, 97, 112, 112, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 45, 105, 108, 115, 116, 0, 0, 0, 37, 169, 116, 111, 111, 0, 0, 0, 29, 100, 97, 116, 97, 0, 0, 0, 1, 0, 0, 0, 0, 76, 97, 118, 102, 53, 54, 46, 52, 48, 46, 49, 48, 49])], { type: "video/mp4" }); const viewMap = { 1: { 1: { width: 1920, height: 1080 }, 2: { width: 1280, height: 720 }, 3: { width: 960, height: 540 }, 4: { width: 640, height: 360 } }, 2: { 1: { width: 1080, height: 1920 }, 2: { width: 720, height: 1280 }, 3: { width: 540, height: 960 }, 4: { width: 360, height: 640 } } }; function querySelectorEl(h) { return document.querySelector(h) } function get_text$1(h) { return String.fromCharCode.apply(null, new Uint8Array(h.slice(0, 5))) == "text:" ? new TextDecoder("utf-8").decode(new Uint8Array(h.slice(5))) : "" } function debounce(h, t = 1e3) { let n = null; return function (r) { n && clearTimeout(n), n = setTimeout(function () { h(r) }, t) } } const canTypeVideoWebm = () => document.createElement("video").canPlayType("video/webm") != "", isFunction = h => Object.prototype.toString.call(h) == "[object Function]"; function is_weixin(h) { var t = h.toLowerCase(); return t.match(/MicroMessenger/i) == "micromessenger" } const environment = () => { const { userAgent: h } = navigator; let t = h.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [], n; if (/trident/i.test(t[1])) return n = /\brv[ :]+(\d+)/g.exec(h) || [], `IE ${n[1] || ""}`; if (t[1] === "Chrome") { if (n = h.match(/\b(OPR|Edge)\/(\d+)/), n !== null) return n.slice(1).join(" ").replace("OPR", "Opera"); if (n = h.match(/\b(Edg)\/(\d+)/), n !== null) return n.slice(1).join(" ").replace("Edg", "Edge (Chromium)") } return t = t[2] ? [t[1], t[2]] : [navigator.appName, navigator.appVersion, "-?"], n = h.match(/version\/(\d+)/i), n !== null && t.splice(1, 1, n[1]), t.join(" ") }, judgeEnvironment = (() => { const { userAgent: h } = navigator; let t = environment(); return h.includes("Mobile") && (t = t + " mobile", is_weixin(h) && (t = t + " wx")), () => t })(); function createWorker(h) { return new Worker(URL.createObjectURL(new Blob([h], { type: "application/javascript" }))) } const wsUrl = { dev: "ws://10.1.204.12:9316", prd: "wss://aiask365.com" }, httpUrl = { dev: "http://10.1.204.12:9316", prd: "https://aiask365.com" }; let curWebsocket; const commonObj = { _sign: "", _projectId: "", _drivertype: "tts", _clientId: "", scene: "", _env: "", _url: "", _volume: 1, _asr: !1 }, requestConf = (h, t, n, r) => { console.log("--------requestConf--------"); let l = ""; commonObj._url ? l = `${commonObj._url}` : l = httpUrl[commonObj._env], console.log(`${l}/avatar/avatarProject/id?id=${h}&isWebm=${t}`), fetch(`${l}/avatar/avatarProject/id?id=${h}&isWebm=${t}`, { method: "GET", headers: { "Content-type": "application/json;charset=UTF-8", Token: n } }).then(a => a.json()).then(a => { r(!0, a) }).catch(a => { console.log(a), r(!1, a) }) }, websocketInit$1 = ({ _projectId: h, _sign: t, isPlat: n, type: r, _drivertype: l, requestVideo: a }) => { let e = commonObj._url.includes("https") ? "wss:" : "ws:", g = ""; commonObj._url ? g = `${e}//${commonObj._url.split("//")[1]}` : g = wsUrl[commonObj._env]; const _ = Date.now() + Math.random().toString(36).substr(2); let y = `${g}/websocket/wenyan/avatar/${h}/${t}?sendText=${n ? "1" : "0"}&sendFlv=${r}&isSdk=1&clientId=${_}`; if (a && (y += "&" + a), r == 0) return y; let x; return () => (x || (x = new WebSocket(y), x.binaryType = "arraybuffer", curWebsocket = x), x) }, heartPing = { timer: null, pong: null, start(h) { this.timer || this.end(), this.clearTime(h) }, clearTime(h) { const t = this; t.timer = setTimeout(() => { h(), console.log("ping!"), t.clearTime(h) }, 2e4) }, pongTimer(h = 3) { const t = this; console.log("pong!"), t.pong && clearTimeout(t.pong), t.pong = setTimeout(() => { console.log("未收到pong!停止ping,重新链接") }, h * 1e3) }, clearPong() { clearTimeout(this.pong) }, end() { clearTimeout(this.pong), clearTimeout(this.timer), this.pong = null, this.timer = null } }, Json2str = h => JSON.stringify(h), SendMsg = { interrupt: () => Json2str({ signal: "interrupt" }), qa: (h, t) => Json2str({ signal: "tts", text: t, query: h, interrupt: !0 }), text: h => Json2str({ signal: "tts", text: h, interrupt: !1 }), streamText: h => Json2str({ signal: "ttsStream", text: h, interrupt: !1 }), streamTextStart: (h, t) => Json2str({ signal: "ttsStream", text: h, query: t, interrupt: !0 }), streamTextEnd: () => SendMsg.streamText(""), streamAudio: h => h, streamAudioEnd: () => new ArrayBuffer(1), pausePlay: () => Json2str({ signal: "pausePlay" }), resumePlay: () => Json2str({ signal: "resumePlay" }), startAsr: () => Json2str({ signal: "startAsr" }) }; window == null || window.addEventListener("unload", () => { console.log("page unload"), curWebsocket == null || curWebsocket.close() }); const isPlat$3 = judgeEnvironment().includes("Chrome"); let flvPlayer = null, pacemaker$3 = !1, websocket$3 = null, videoPlayerInit$2 = !1, interval$3 = 5, c2$1 = null, video = null, silentVideo$2 = null, videoWidth$3 = "", videoHeight$3 = "", reqRes$3 = null, playStatus$1 = !1, serverEnded$1 = !1, videoFlow$1 = "", videoIsStart = !1, emitter$3 = new Emitter$2; const checkVideoStatus$1 = debounce(() => { console.log("checkVideoStatus", playStatus$1, videoFlow$1, serverEnded$1), playStatus$1 && videoFlow$1 == "waiting" && serverEnded$1 && (serverEnded$1 = !1, console.log("视频播完了"), emitter$3.emit("videoEnd"), videoIsStart = !1, websocket$3 == null || websocket$3.send(SendMsg.startAsr())) }, 500), checkCondition$3 = h => { "WebSocket" in window ? flvjs.isSupported() ? h(!0, "success") : h(!1, "不支持flv") : h(!1, "当前浏览器不支持websocketio连接") }; let startTime = 0; const tryPlay = (() => { let h = null; function t() { const n = video, r = new Date().getTime() - startTime; if (n) { if (n.buffered.length > 0 && n.buffered.end(0) > .8) { videoFlow$1 = "canplay", videoIsStart || (videoIsStart = !0, emitter$3.emit("videoStart")), n.play().then(l => { console.log("数字人播放成功") }).catch(l => { console.log("数字人播放失败", l) }), webglCut.videoPlay(); return } else if (r > 500) { videoFlow$1 = "canplay", videoIsStart || (videoIsStart = !0, emitter$3.emit("videoStart"), console.log("------videoStart", 22)), n.play().then(l => { console.log("数字人播放成功") }).catch(l => { console.log("数字人播放失败", l) }), webglCut.videoPlay(); return } h = setTimeout(t, 100) } } return function () { h && clearTimeout(h), t() } })(), webReconnect$2 = (h = !1) => { if (h && flvPlayer) { flvPlayer.pause(), flvPlayer.unload(), flvPlayer.detachMediaElement(), videoPlayerInit$2 = !0, flvPlayer.attachMediaElement(video), flvPlayer.load(); return } }, loopConnect$3 = () => { uninstallEvent$3(!1), startPlayer$3() }, pageAcitveStatusGet$3 = () => { (() => { setTimeout(() => { interval$3 += 5, interval$3 > 30 && (interval$3 = 30), loopConnect$3() }, interval$3 * 1e3) })() }, uninstallEvent$3 = (h = !0) => { pacemaker$3 = h, videoPlayerInit$2 = !1, videoIsStart = !1, heartPing.end(), flvPlayer && (flvPlayer.pause(), flvPlayer.unload(), flvPlayer.detachMediaElement(), flvPlayer.destroy(), flvPlayer = null), websocket$3 && (websocket$3.close(), websocket$3 = null) }; let asrWsApp$3 = null; const startPlayer$3 = () => { let { _sign: h, _projectId: t, _drivertype: n, _volume: r, _asr: l } = commonObj; flvPlayer = flvjs.createPlayer({ type: "flv", isLive: !0, hasAudio: !0, hasVideo: !0, cors: !0 }, { enableWorker: !1, enableStashBuffer: !1, autoCleanupSourceBuffer: !0, stashInitialSize: 128, cbOpen: function (a) { console.log("flv-建立websocket", a), websocket$3 = a, l && asrWsApp$3 && asrWsApp$3(a), heartPing.start(() => { (websocket$3 == null ? void 0 : websocket$3.readyState) == 1 && (websocket$3 == null || websocket$3.send(JSON.stringify({ signal: "ping" }))) }) }, cbMessage: isPlat$3 ? function (a, e, g) { if (typeof e.data == "object") { const _ = new Uint8Array(e.data); _[0] !== 70 || _[1] !== 76 || _[2] !== 86 || _[3] !== 1 || (videoPlayerInit$2 = !1, console.log("——————————loop new——————————————")), videoPlayerInit$2 || (_.byteLength == 1 && _[0] == 0 && (console.log("视频发送完成"), playStatus$1 = !0, serverEnded$1 = !0, checkVideoStatus$1()), g(e)) } else if (e.data != "ppg-end") { if (e.data.includes("requests overload")) pacemaker$3 = !0, emitter$3.emit("wsMessage", { type: "requests overload" }); else if (e.data.includes("{")) { const _ = JSON.parse(e.data); _.type == "asr-part" ? emitter$3.emit("wsMessage", _) : _.type == "asr" ? (emitter$3.emit("wsMessage", _), playStatus$1 = !1) : _.type == "answer" ? emitter$3.emit("wsMessage", _) : _.type == "startAsr" || _.type == "startSleep" || _.type == "wakeup" || (_.type == "server_ready" ? emitter$3.emit("wsMessage", _) : _.type == "server_ended" || (_.type == "error" ? (emitter$3.emit("wsMessage", _), console.error(_.content)) : _.type == "node" || _.type == "tts_mills")) } } } : function (a, e, g) { const _ = new Uint8Array(e.data); if (_[0] === 116 && _[1] === 101 && _[2] === 120 && _[3] === 116) { const y = get_text$1(_); if (y != "ppg-end") { if (y != "pong") { if (y.includes("requests overload")) pacemaker$3 = !0, emitter$3.emit("wsMessage", { type: "requests overload" }); else if (y.includes("{")) { const x = JSON.parse(y); x.type == "asr-part" ? emitter$3.emit("wsMessage", x) : x.type == "asr" ? (emitter$3.emit("wsMessage", x), playStatus$1 = !1) : x.type == "answer" ? emitter$3.emit("wsMessage", x) : x.type == "startAsr" || x.type == "startSleep" || x.type == "wakeup" || (x.type == "server_ready" ? emitter$3.emit("wsMessage", x) : x.type == "server_ended" || (x.type == "error" ? (emitter$3.emit("wsMessage", x), console.error(x.content)) : x.type == "node" || x.type == "tts_mills")) } } } } else _[0] !== 70 || _[1] !== 76 || _[2] !== 86 || _[3] !== 1 || (videoPlayerInit$2 = !1, console.log("——————————loop new——————————————")), videoPlayerInit$2 || (_.byteLength == 1 && _[0] == 0 && (console.log("视频发送完成"), playStatus$1 = !0, serverEnded$1 = !0, checkVideoStatus$1()), g(e)) }, cbError: function (a, e) { console.error("websocket错误:", e), emitter$3.emit("wsMessage", { type: "websocket Error", value: e }) }, cbClose: function (a, e) { console.error("websocket关闭:", e), pacemaker$3 ? emitter$3.emit("wsMessage", { type: "websocket close" }) : (pageAcitveStatusGet$3(), emitter$3.emit("wsMessage", { type: "websocket reLoop" })) }, ws: websocketInit$1({ _projectId: t, _sign: h, isPlat: isPlat$3, type: 1, _drivertype: n, requestVideo: requestVideo$3 }) }), flvPlayer.attachMediaElement(video), flvPlayer.load(), videoPlayerInit$2 = !0 }; let requestVideo$3 = ""; function player$3(h, t, n, r, l = 1) { videoWidth$3 = viewMap[t][r].width, videoHeight$3 = viewMap[t][r].height, requestVideo$3 = `requestWidth=${videoWidth$3}&requestHeight=${videoHeight$3}`, document.querySelector(h).innerHTML = ` `, c2$1 = querySelectorEl("#flvcanvas"), video = querySelectorEl("#digitalPlayer"), silentVideo$2 = querySelectorEl("#silentVideo") } let xxPlayer$3 = class extends Emitter$2 { constructor({ environment: t, containerLable: n, token: r, projectId: l, quality: a, zoom: e, clientId: g, volume: _, asr: y }, x) { if (super(), y) { const { asrDestroy: E, asrWsAppoint: C, asrStart: L } = asrWs(A => { console.log(A, "mic") }); asrWsApp$3 = C, L() } emitter$3 = new Emitter$2, this.containerLable = n, commonObj._sign = r, commonObj._projectId = l, this.quality = a || 1, this.zoom = e || 1, commonObj._env = t || "prd", commonObj._volume = _ || 1, commonObj._asr = y || !1, reqRes$3 = x, this.streamImg = !1 } init() { checkCondition$3((t, n) => { if (t) { let { avatarSilenceUrl: r, avatarDirection: l } = reqRes$3.data; player$3(this.containerLable, l, r, this.quality, this.zoom), emitter$3.on("videoEnd", () => { this.emit("message", { type: "videoEnd", data: {} }) }), emitter$3.on("videoStart", () => { this.emit("message", { type: "videoStart", data: {} }) }), emitter$3.on("wsMessage", a => { this.emit("message", { type: "wsMessage", data: a }) }), emitter$3.on("initAnd", () => { this.emit("intialSucccess", { type: "2" }) }), this.emit("intialSucccess", { type: "1" }) } else this.emit("intialError", n) }) } playSilentvideo() { video && video.play().then(t => { console.log("交互数字人视频播放") }).catch(t => { console.log("交互数字人视频播放失败-", t) }), silentVideo$2 && silentVideo$2.play().then(t => { console.log("交互静音视频播放") }).catch(t => { console.log("交互静音视频播放失败-", t) }) } startPlay() { const t = this; webglCut.load(video, silentVideo$2, c2$1, n => { webglCut.slicePlay(), startPlayer$3() }), video == null || video.addEventListener("canplay", function () { startTime = new Date().getTime(), console.log("canplay-----"), tryPlay(), t.streamImg = !0 }), video == null || video.addEventListener("waiting", function () { console.log("waiting--------"), videoFlow$1 = "waiting", webglCut.slicePlay(), checkVideoStatus$1() }), video == null || video.addEventListener("ended", function () { console.log("_____ended________"), videoFlow$1 = "waiting", webglCut.slicePlay(), checkVideoStatus$1() }), video == null || video.addEventListener("loadedmetadata", n => { video.pause(), console.log("_____loadedmetadata________", n) }), emitter$3.emit("initAnd") } setClientId(t) { t ? commonObj._clientId = t : console.log("clientId不能为空") } stopPlay() { uninstallEvent$3(), emitter$3 = null, c2$1 = null, video = null, silentVideo$2 = null, videoWidth$3 = "", videoHeight$3 = "", reqRes$3 = null, this.streamImg = !1 } playQA(t, n) { flvPlayer == null || flvPlayer.play(), websocket$3 == null || websocket$3.send(SendMsg.qa(t, n)) } interrupt() { websocket$3 == null || websocket$3.send(SendMsg.interrupt()), webglCut.slicePlay(), webReconnect$2(!0), this.streamImg = !1, videoIsStart = !1 } playText(t) { flvPlayer == null || flvPlayer.play(), websocket$3 == null || websocket$3.send(SendMsg.text(t)) } playStreamText(t) { websocket$3 == null || websocket$3.send(SendMsg.streamText(t)) } playStreamTextStart(t, n) { flvPlayer == null || flvPlayer.play(), websocket$3 == null || websocket$3.send(SendMsg.streamTextStart(t, n)) } playStreamTextEnd() { websocket$3 == null || websocket$3.send(SendMsg.streamTextEnd()) } playAudio(t) { websocket$3 == null || websocket$3.send(SendMsg.streamAudio(t)) } playAudioEnd() { websocket$3 == null || websocket$3.send(SendMsg.streamAudioEnd()) } playCurVideo() { this.streamImg && (websocket$3 == null || websocket$3.send(SendMsg.resumePlay()), flvPlayer.play(), webglCut.videoPlay()) } stopCurVideo() { this.streamImg && (websocket$3 == null || websocket$3.send(SendMsg.pausePlay()), webglCut.slicePlay(), flvPlayer.pause()) } }; function getNowTime$1() { return performance && typeof performance.now == "function" ? performance.now() : Date.now() } let Emitter$1 = class { on(t, n, r) { const l = this.e || (this.e = {}); return (l[t] || (l[t] = [])).push({ fn: n, ctx: r }), this } once(t, n, r) { const l = this; function a(...e) { l.off(t, a), n.apply(r, e) } return a._ = n, this.on(t, a, r) } emit(t, ...n) { const r = ((this.e || (this.e = {}))[t] || []).slice(); for (let l = 0; l < r.length; l += 1)r[l].fn.apply(r[l].ctx, n); return this } off(t, n) { const r = this.e || (this.e = {}), l = r[t], a = []; if (l && n) for (let e = 0, g = l.length; e < g; e += 1)l[e].fn !== n && l[e].fn._ !== n && a.push(l[e]); return a.length ? r[t] = a : delete r[t], this } }; const kn = class kn { constructor(t, n) { Fn(this, tt, null); Fn(this, vt, null); Fn(this, cn, null); Fn(this, Un, null); Fn(this, Nn, null); wn(this, tt, n); const r = wn(this, vt, n.getContext("webgl2") || n.getContext("webgl") || n.getContext("experimental-webgl")), l = r.createShader(r.VERTEX_SHADER); if (r.shaderSource(l, kn.vertexShaderSource), r.compileShader(l), !r.getShaderParameter(l, r.COMPILE_STATUS)) throw r.getShaderInfoLog(l); const a = r.createShader(r.FRAGMENT_SHADER); if (r.shaderSource(a, kn.fragmentShaderSource), r.compileShader(a), !r.getShaderParameter(a, r.COMPILE_STATUS)) throw r.getShaderInfoLog(a); const e = r.createProgram(); if (r.attachShader(e, l), r.attachShader(e, a), r.linkProgram(e), !r.getProgramParameter(e, r.LINK_STATUS)) throw r.getProgramInfoLog(e); r.useProgram(e); const g = r.createBuffer(); r.bindBuffer(r.ARRAY_BUFFER, g), r.bufferData(r.ARRAY_BUFFER, new Float32Array([-1, -1, -1, 1, 1, 1, 1, -1]), r.STATIC_DRAW); const _ = r.getAttribLocation(e, "xy"); r.vertexAttribPointer(_, 2, r.FLOAT, !1, 0, 0), r.enableVertexAttribArray(_); const y = r.createTexture(); r.bindTexture(r.TEXTURE_2D, y), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_MAG_FILTER, r.NEAREST), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_MIN_FILTER, r.NEAREST), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_WRAP_S, r.CLAMP_TO_EDGE), r.texParameteri(r.TEXTURE_2D, r.TEXTURE_WRAP_T, r.CLAMP_TO_EDGE), wn(this, Un, r.getUniformLocation(e, "texWidth")), wn(this, Nn, r.getUniformLocation(e, "texHeight")) } draw(t, n, r) { En(this, tt).width = n, En(this, tt).height = r; const l = En(this, vt); l.uniform1f(En(this, Un), n), l.uniform1f(En(this, Nn), r), l.texImage2D(l.TEXTURE_2D, 0, l.RGBA, l.RGBA, l.UNSIGNED_BYTE, t), En(this, cn) != null && En(this, cn).close(), wn(this, cn, t), l.viewport(0, 0, l.drawingBufferWidth, l.drawingBufferHeight), l.clearColor(1, 0, 0, 1), l.clear(l.COLOR_BUFFER_BIT), l.drawArrays(l.TRIANGLE_FAN, 0, 4) } destroy() { wn(this, tt, null), wn(this, vt, null) } }; tt = new WeakMap, vt = new WeakMap, cn = new WeakMap, Un = new WeakMap, Nn = new WeakMap, Oi(kn, "vertexShaderSource", ` attribute vec2 xy; void main(void) { gl_Position = vec4(xy, 0.0, 1.0); } `), Oi(kn, "fragmentShaderSource", ` precision mediump float; uniform sampler2D tex; uniform float texWidth; uniform float texHeight; const vec3 keyColor = vec3(0.47, 1.0, 0.47); uniform float similarity; uniform float smoothness; uniform float spill; vec2 RGBtoUV(vec3 rgb) { return vec2( rgb.r * -0.169 + rgb.g * -0.331 + rgb.b * 0.5 + 0.5, rgb.r * 0.5 + rgb.g * -0.419 + rgb.b * -0.081 + 0.5 ); } vec4 GetRgba(float detaX, float detaY) { vec2 texCoord = vec2((gl_FragCoord.x + detaX)/texWidth, 1.0 - (gl_FragCoord.y + detaY)/texHeight); vec4 rgba = texture2D(tex, texCoord); float green = rgba.g - max(rgba.r, rgba.b); float greenKey = keyColor.g - max(keyColor.r, keyColor.b); float mask = smoothstep(greenKey-0.1, 0.0, green); rgba.a = mask; return rgba; } vec4 ProcessChromaKey() { vec4 rgba = GetRgba(0.0, 0.0); if (rgba.a > 0.0 && rgba.a < 1.0) { vec4 rgbas[9]; float maxMask = 0.0; vec4 minRgba = rgba; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { vec4 tmp; if (i == 0 && j == 0) { tmp = rgba; } else { tmp = GetRgba(float(i), float(j)); } rgbas[(i+1)*3 + (j+1)] = tmp; if (tmp.a > maxMask) { maxMask = tmp.a; minRgba = tmp; } } } rgbas[4] = minRgba; rgbas[4].a = rgba.a; vec4 dest = vec4(0.0, 0.0, 0.0, 0.0); float gs[9]; gs[0] = gs[2] = gs[6] = gs[8] = 0.05; gs[1] = gs[3] = gs[5] = gs[7] = 0.05; gs[4] = 0.6; for(int i = 0; i < 9; i++) { dest.rgb = dest.rgb + rgbas[i].rgb * gs[i]; } gs[0] = gs[2] = gs[6] = gs[8] = 0.05; gs[1] = gs[3] = gs[5] = gs[7] = 0.15; gs[4] = 0.2; for(int i = 0; i < 9; i++) { dest.a = dest.a + rgbas[i].a* gs[i]; } rgba.rgb = dest.rgb; rgba.a = dest.a; if (rgba.g > rgba.r && rgba.g > rgba.b) { rgba.g = max(rgba.r, rgba.b); } rgba.rgb = rgba.rgb * rgba.a; } else { rgba.rgb = rgba.rgb * rgba.a; } return rgba; } void main(void) { gl_FragColor = ProcessChromaKey(); } `); let WebGLRenderer = kn; class Render { constructor(t) { this.flv = t; const { container: n } = t.options; this.canvas = n, this.renderer = new WebGLRenderer("", n) } drawFrame(t) { const n = this, r = this.canvas.getAttribute("width"), l = this.canvas.getAttribute("height"); n.renderer.draw(t, r, l) } destroy() { this.renderer.destroy() } } var FrameSink = { exports: {} }; (function () { function h(t, n) { throw new Error("abstract") } h.prototype.drawFrame = function (t) { throw new Error("abstract") }, h.prototype.clear = function () { throw new Error("abstract") }, FrameSink.exports = h })(); var FrameSinkExports = FrameSink.exports, YCbCr = { exports: {} }, depower = { exports: {} }; (function () {/** * Convert a ratio into a bit-shift count; for instance a ratio of 2 * becomes a bit-shift of 1, while a ratio of 1 is a bit-shift of 0. * * @author Brion Vibber * @copyright 2016 * @license MIT-style * * @param {number} ratio - the integer ratio to convert. * @returns {number} - number of bits to shift to multiply/divide by the ratio. * @throws exception if given a non-power-of-two */function h(t) { for (var n = 0, r = t >> 1; r != 0;)r = r >> 1, n++; if (t !== 1 << n) throw "chroma plane dimensions must be power of 2 ratio to luma plane dimensions; got " + t; return n } depower.exports = h })(); var depowerExports = depower.exports; (function () { var h = depowerExports;/** * Basic YCbCr->RGB conversion * * @author Brion Vibber * @copyright 2014-2019 * @license MIT-style * * @param {YUVFrame} buffer - input frame buffer * @param {Uint8ClampedArray} output - array to draw RGBA into * Assumes that the output array already has alpha channel set to opaque. */function t(n, r) { var l = n.format.width | 0, a = n.format.height | 0, e = h(n.format.width / n.format.chromaWidth) | 0, g = h(n.format.height / n.format.chromaHeight) | 0, _ = n.y.bytes, y = n.u.bytes, x = n.v.bytes, E = n.y.stride | 0, C = n.u.stride | 0, L = n.v.stride | 0, A = l << 2, I = 0, D = 0, w = 0, S = 0, O = 0, F = 0, j = 0, P = 0, $ = 0, V = 0, q = 0, ee = 0, re = 0, ye = 0, ce = 0, Q = 0, se = 0, fe = 0; if (e == 1 && g == 1) for (j = 0, P = A, fe = 0, Q = 0; Q < a; Q += 2) { for (D = Q * E | 0, w = D + E | 0, S = fe * C | 0, O = fe * L | 0, ce = 0; ce < l; ce += 2)$ = y[S++] | 0, V = x[O++] | 0, ee = (409 * V | 0) - 57088 | 0, re = (100 * $ | 0) + (208 * V | 0) - 34816 | 0, ye = (516 * $ | 0) - 70912 | 0, q = 298 * _[D++] | 0, r[j] = q + ee >> 8, r[j + 1] = q - re >> 8, r[j + 2] = q + ye >> 8, j += 4, q = 298 * _[D++] | 0, r[j] = q + ee >> 8, r[j + 1] = q - re >> 8, r[j + 2] = q + ye >> 8, j += 4, q = 298 * _[w++] | 0, r[P] = q + ee >> 8, r[P + 1] = q - re >> 8, r[P + 2] = q + ye >> 8, P += 4, q = 298 * _[w++] | 0, r[P] = q + ee >> 8, r[P + 1] = q - re >> 8, r[P + 2] = q + ye >> 8, P += 4; j += A, P += A, fe++ } else for (F = 0, Q = 0; Q < a; Q++)for (se = 0, fe = Q >> g, I = Q * E | 0, S = fe * C | 0, O = fe * L | 0, ce = 0; ce < l; ce++)se = ce >> e, $ = y[S + se] | 0, V = x[O + se] | 0, ee = (409 * V | 0) - 57088 | 0, re = (100 * $ | 0) + (208 * V | 0) - 34816 | 0, ye = (516 * $ | 0) - 70912 | 0, q = 298 * _[I++] | 0, r[F] = q + ee >> 8, r[F + 1] = q - re >> 8, r[F + 2] = q + ye >> 8, F += 4 } YCbCr.exports = { convertYCbCr: t } })(); var YCbCrExports = YCbCr.exports; (function () { var h = FrameSinkExports, t = YCbCrExports; function n(r) { var l = this, a = r.getContext("2d"), e = null, g = null, _ = null; function y(E, C) { e = a.createImageData(E, C); for (var L = e.data, A = E * C * 4, I = 0; I < A; I += 4)L[I + 3] = 255 } function x(E, C) { g = document.createElement("canvas"), g.width = E, g.height = C, _ = g.getContext("2d") } return l.drawFrame = function (C) { var L = C.format; (r.width !== L.displayWidth || r.height !== L.displayHeight) && (r.width = L.displayWidth, r.height = L.displayHeight), (e === null || e.width != L.width || e.height != L.height) && y(L.width, L.height), t.convertYCbCr(C, e.data); var A = L.cropWidth != L.displayWidth || L.cropHeight != L.displayHeight, I; A ? (g || x(L.cropWidth, L.cropHeight), I = _) : I = a, I.putImageData(e, -L.cropLeft, -L.cropTop, L.cropLeft, L.cropTop, L.cropWidth, L.cropHeight), A && a.drawImage(g, 0, 0, L.displayWidth, L.displayHeight) }, l.clear = function () { a.clearRect(0, 0, r.width, r.height) }, l } n.prototype = Object.create(h.prototype) })(); var shaders = { vertex: `precision mediump float; attribute vec2 aPosition; attribute vec2 aLumaPosition; attribute vec2 aChromaPosition; varying vec2 vLumaPosition; varying vec2 vChromaPosition; void main() { gl_Position = vec4(aPosition, 0, 1); vLumaPosition = aLumaPosition; vChromaPosition = aChromaPosition; } `, fragment: `// inspired by https://github.com/mbebenita/Broadway/blob/master/Player/canvas.js precision mediump float; uniform sampler2D uTextureY; uniform sampler2D uTextureCb; uniform sampler2D uTextureCr; varying vec2 vLumaPosition; varying vec2 vChromaPosition; void main() { // Y, Cb, and Cr planes are uploaded as ALPHA textures. float fY = texture2D(uTextureY, vLumaPosition).w; float fCb = texture2D(uTextureCb, vChromaPosition).w; float fCr = texture2D(uTextureCr, vChromaPosition).w; // Premultipy the Y... float fYmul = fY * 1.1643828125; // And convert that to RGB! gl_FragColor = vec4( fYmul + 1.59602734375 * fCr - 0.87078515625, fYmul - 0.39176171875 * fCb - 0.81296875 * fCr + 0.52959375, fYmul + 2.017234375 * fCb - 1.081390625, 1 ); } `, vertexStripe: `precision mediump float; attribute vec2 aPosition; attribute vec2 aTexturePosition; varying vec2 vTexturePosition; void main() { gl_Position = vec4(aPosition, 0, 1); vTexturePosition = aTexturePosition; } `, fragmentStripe: `// extra 'stripe' texture fiddling to work around IE 11's poor performance on gl.LUMINANCE and gl.ALPHA textures precision mediump float; uniform sampler2D uStripe; uniform sampler2D uTexture; varying vec2 vTexturePosition; void main() { // Y, Cb, and Cr planes are mapped into a pseudo-RGBA texture // so we can upload them without expanding the bytes on IE 11 // which doesn't allow LUMINANCE or ALPHA textures // The stripe textures mark which channel to keep for each pixel. // Each texture extraction will contain the relevant value in one // channel only. float fLuminance = dot( texture2D(uStripe, vTexturePosition), texture2D(uTexture, vTexturePosition) ); gl_FragColor = vec4(0, 0, 0, fLuminance); } `}; (function () { var h = FrameSinkExports, t = shaders; function n(r) { var l = this, a = n.contextForCanvas(r); if (a === null) throw new Error("WebGL unavailable"); function e(Q, se) { var fe = a.createShader(Q); if (a.shaderSource(fe, se), a.compileShader(fe), !a.getShaderParameter(fe, a.COMPILE_STATUS)) { var G = a.getShaderInfoLog(fe); throw a.deleteShader(fe), new Error("GL shader compilation for " + Q + " failed: " + G) } return fe } var g, _, y = new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]), x = {}, E = {}, C = {}, L, A, I, D, w, S, O, F, j, P; function $(Q, se) { return (!x[Q] || se) && (x[Q] = a.createTexture()), x[Q] } function V(Q, se, fe, G, K) { var de = !x[Q] || se, ve = $(Q, se); if (a.activeTexture(a.TEXTURE0), n.stripe) { var ae = !x[Q + "_temp"] || se, J = $(Q + "_temp", se); a.bindTexture(a.TEXTURE_2D, J), ae ? (a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_S, a.CLAMP_TO_EDGE), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_T, a.CLAMP_TO_EDGE), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MIN_FILTER, a.NEAREST), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MAG_FILTER, a.NEAREST), a.texImage2D(a.TEXTURE_2D, 0, a.RGBA, fe / 4, G, 0, a.RGBA, a.UNSIGNED_BYTE, K)) : a.texSubImage2D(a.TEXTURE_2D, 0, 0, 0, fe / 4, G, a.RGBA, a.UNSIGNED_BYTE, K); var U = x[Q + "_stripe"], X = !U || se; X && (U = $(Q + "_stripe", se)), a.bindTexture(a.TEXTURE_2D, U), X && (a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_S, a.CLAMP_TO_EDGE), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_T, a.CLAMP_TO_EDGE), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MIN_FILTER, a.NEAREST), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MAG_FILTER, a.NEAREST), a.texImage2D(a.TEXTURE_2D, 0, a.RGBA, fe, 1, 0, a.RGBA, a.UNSIGNED_BYTE, re(fe))) } else a.bindTexture(a.TEXTURE_2D, ve), de ? (a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_S, a.CLAMP_TO_EDGE), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_T, a.CLAMP_TO_EDGE), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MIN_FILTER, a.LINEAR), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MAG_FILTER, a.LINEAR), a.texImage2D(a.TEXTURE_2D, 0, a.ALPHA, fe, G, 0, a.ALPHA, a.UNSIGNED_BYTE, K)) : a.texSubImage2D(a.TEXTURE_2D, 0, 0, 0, fe, G, a.ALPHA, a.UNSIGNED_BYTE, K) } function q(Q, se, fe, G) { var K = x[Q]; a.useProgram(_); var de = E[Q]; (!de || se) && (a.activeTexture(a.TEXTURE0), a.bindTexture(a.TEXTURE_2D, K), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_S, a.CLAMP_TO_EDGE), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_T, a.CLAMP_TO_EDGE), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MIN_FILTER, a.LINEAR), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MAG_FILTER, a.LINEAR), a.texImage2D(a.TEXTURE_2D, 0, a.RGBA, fe, G, 0, a.RGBA, a.UNSIGNED_BYTE, null), de = E[Q] = a.createFramebuffer()), a.bindFramebuffer(a.FRAMEBUFFER, de), a.framebufferTexture2D(a.FRAMEBUFFER, a.COLOR_ATTACHMENT0, a.TEXTURE_2D, K, 0); var ve = x[Q + "_temp"]; a.activeTexture(a.TEXTURE1), a.bindTexture(a.TEXTURE_2D, ve), a.uniform1i(S, 1); var ae = x[Q + "_stripe"]; a.activeTexture(a.TEXTURE2), a.bindTexture(a.TEXTURE_2D, ae), a.uniform1i(w, 2), a.bindBuffer(a.ARRAY_BUFFER, L), a.enableVertexAttribArray(A), a.vertexAttribPointer(A, 2, a.FLOAT, !1, 0, 0), a.bindBuffer(a.ARRAY_BUFFER, I), a.enableVertexAttribArray(D), a.vertexAttribPointer(D, 2, a.FLOAT, !1, 0, 0), a.viewport(0, 0, fe, G), a.drawArrays(a.TRIANGLES, 0, y.length / 2), a.bindFramebuffer(a.FRAMEBUFFER, null) } function ee(Q, se, fe) { a.activeTexture(se), a.bindTexture(a.TEXTURE_2D, x[Q]), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_S, a.CLAMP_TO_EDGE), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_T, a.CLAMP_TO_EDGE), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MIN_FILTER, a.LINEAR), a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MAG_FILTER, a.LINEAR), a.uniform1i(a.getUniformLocation(g, Q), fe) } function re(Q) { if (C[Q]) return C[Q]; for (var se = Q, fe = new Uint32Array(se), G = 0; G < se; G += 4)fe[G] = 255, fe[G + 1] = 65280, fe[G + 2] = 16711680, fe[G + 3] = 4278190080; return C[Q] = new Uint8Array(fe.buffer) } function ye(Q, se) { var fe = e(a.VERTEX_SHADER, Q), G = e(a.FRAGMENT_SHADER, se), K = a.createProgram(); if (a.attachShader(K, fe), a.attachShader(K, G), a.linkProgram(K), !a.getProgramParameter(K, a.LINK_STATUS)) { var de = a.getProgramInfoLog(K); throw a.deleteProgram(K), new Error("GL program linking failed: " + de) } return K } function ce() { if (n.stripe) { _ = ye(t.vertexStripe, t.fragmentStripe), a.getAttribLocation(_, "aPosition"), I = a.createBuffer(); var Q = new Float32Array([0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1]); a.bindBuffer(a.ARRAY_BUFFER, I), a.bufferData(a.ARRAY_BUFFER, Q, a.STATIC_DRAW), D = a.getAttribLocation(_, "aTexturePosition"), w = a.getUniformLocation(_, "uStripe"), S = a.getUniformLocation(_, "uTexture") } g = ye(t.vertex, t.fragment), L = a.createBuffer(), a.bindBuffer(a.ARRAY_BUFFER, L), a.bufferData(a.ARRAY_BUFFER, y, a.STATIC_DRAW), A = a.getAttribLocation(g, "aPosition"), O = a.createBuffer(), F = a.getAttribLocation(g, "aLumaPosition"), j = a.createBuffer(), P = a.getAttribLocation(g, "aChromaPosition") } return l.drawFrame = function (Q) { var se = Q.format, fe = !g || r.width !== se.displayWidth || r.height !== se.displayHeight; if (fe && (r.width = se.displayWidth, r.height = se.displayHeight, l.clear()), g || ce(), fe) { var G = function (K, de, ve) { var ae = se.cropLeft / ve, J = (se.cropLeft + se.cropWidth) / ve, U = (se.cropTop + se.cropHeight) / se.height, X = se.cropTop / se.height, ne = new Float32Array([ae, U, J, U, ae, X, ae, X, J, U, J, X]); a.bindBuffer(a.ARRAY_BUFFER, K), a.bufferData(a.ARRAY_BUFFER, ne, a.STATIC_DRAW) }; G(O, F, Q.y.stride), G(j, P, Q.u.stride * se.width / se.chromaWidth) } V("uTextureY", fe, Q.y.stride, se.height, Q.y.bytes), V("uTextureCb", fe, Q.u.stride, se.chromaHeight, Q.u.bytes), V("uTextureCr", fe, Q.v.stride, se.chromaHeight, Q.v.bytes), n.stripe && (q("uTextureY", fe, Q.y.stride, se.height), q("uTextureCb", fe, Q.u.stride, se.chromaHeight), q("uTextureCr", fe, Q.v.stride, se.chromaHeight)), a.useProgram(g), a.viewport(0, 0, r.width, r.height), ee("uTextureY", a.TEXTURE0, 0), ee("uTextureCb", a.TEXTURE1, 1), ee("uTextureCr", a.TEXTURE2, 2), a.bindBuffer(a.ARRAY_BUFFER, L), a.enableVertexAttribArray(A), a.vertexAttribPointer(A, 2, a.FLOAT, !1, 0, 0), a.bindBuffer(a.ARRAY_BUFFER, O), a.enableVertexAttribArray(F), a.vertexAttribPointer(F, 2, a.FLOAT, !1, 0, 0), a.bindBuffer(a.ARRAY_BUFFER, j), a.enableVertexAttribArray(P), a.vertexAttribPointer(P, 2, a.FLOAT, !1, 0, 0), a.drawArrays(a.TRIANGLES, 0, y.length / 2) }, l.clear = function () { a.viewport(0, 0, r.width, r.height), a.clearColor(0, 0, 0, 0), a.clear(a.COLOR_BUFFER_BIT) }, l.clear(), l } n.stripe = !1, n.contextForCanvas = function (r) { var l = { preferLowPowerToHighPerformance: !0, powerPreference: "low-power", failIfMajorPerformanceCaveat: !0, preserveDrawingBuffer: !0 }; return r.getContext("webgl", l) || r.getContext("experimental-webgl", l) }, n.isAvailable = function () { var r = document.createElement("canvas"), l; r.width = 1, r.height = 1; try { l = n.contextForCanvas(r) } catch { return !1 } if (l) { var a = l.TEXTURE0, e = 4, g = 4, _ = l.createTexture(), y = new Uint8Array(e * g), x = n.stripe ? e / 4 : e, E = n.stripe ? l.RGBA : l.ALPHA, C = n.stripe ? l.NEAREST : l.LINEAR; l.activeTexture(a), l.bindTexture(l.TEXTURE_2D, _), l.texParameteri(l.TEXTURE_2D, l.TEXTURE_WRAP_S, l.CLAMP_TO_EDGE), l.texParameteri(l.TEXTURE_2D, l.TEXTURE_WRAP_T, l.CLAMP_TO_EDGE), l.texParameteri(l.TEXTURE_2D, l.TEXTURE_MIN_FILTER, C), l.texParameteri(l.TEXTURE_2D, l.TEXTURE_MAG_FILTER, C), l.texImage2D(l.TEXTURE_2D, 0, E, x, g, 0, E, l.UNSIGNED_BYTE, y); var L = l.getError(); return !L } else return !1 }, n.prototype = Object.create(h.prototype) })(); function Texture(h) { this.gl = h, this.texture = h.createTexture(), h.bindTexture(h.TEXTURE_2D, this.texture), h.texParameteri(h.TEXTURE_2D, h.TEXTURE_MAG_FILTER, h.LINEAR), h.texParameteri(h.TEXTURE_2D, h.TEXTURE_MIN_FILTER, h.LINEAR), h.texParameteri(h.TEXTURE_2D, h.TEXTURE_WRAP_S, h.CLAMP_TO_EDGE), h.texParameteri(h.TEXTURE_2D, h.TEXTURE_WRAP_T, h.CLAMP_TO_EDGE) } Texture.prototype.bind = function (h, t, n) { let r = this.gl; r.activeTexture([r.TEXTURE0, r.TEXTURE1, r.TEXTURE2][h]), r.bindTexture(r.TEXTURE_2D, this.texture), r.uniform1i(r.getUniformLocation(t, n), h) }, Texture.prototype.fill = function (h, t, n) { let r = this.gl; r.bindTexture(r.TEXTURE_2D, this.texture), r.texImage2D(r.TEXTURE_2D, 0, r.LUMINANCE, h, t, 0, r.LUMINANCE, r.UNSIGNED_BYTE, n) }; class Renderer { constructor(t) { this.flv = t; const { container: n } = t.options; this.canvas = n, this.gl = n.getContext("webgl2") || n.getContext("webgl") || n.getContext("experimental-webgl"), this.initGL({ preserveDrawingBuffer: !1 }) } initGL(t) { if (!this.gl) { console.log("[ER] WebGL not supported."); return } let n = this.gl; n.pixelStorei(n.UNPACK_ALIGNMENT, 1); let r = n.createProgram(), l = ` attribute highp vec4 aVertexPosition; attribute vec2 aTextureCoord; varying highp vec2 vTextureCoord; void main(void) { gl_Position = aVertexPosition; vTextureCoord = aTextureCoord; }`, a = n.createShader(n.VERTEX_SHADER); n.shaderSource(a, l), n.compileShader(a); let e = ` precision mediump float; uniform sampler2D tex; uniform sampler2D YTexture; uniform sampler2D UTexture; uniform sampler2D VTexture; uniform float texWidth; uniform float texHeight; const vec3 keyColor = vec3(0.47, 1.0, 0.47); uniform float similarity; uniform float smoothness; uniform float spill; vec2 RGBtoUV(vec3 rgb) { return vec2( rgb.r * -0.169 + rgb.g * -0.331 + rgb.b * 0.5 + 0.5, rgb.r * 0.5 + rgb.g * -0.419 + rgb.b * -0.081 + 0.5 ); } const mat4 YUV2RGB = mat4 ( 1.1643828125, 0, 1.59602734375, -.87078515625, 1.1643828125, -.39176171875, -.81296875, .52959375, 1.1643828125, 2.017234375, 0, -1.081390625, 0, 0, 0, 1 ); vec4 GetRgba(float detaX, float detaY) { vec2 texCoord = vec2((gl_FragCoord.x + detaX)/texWidth, 1.0 - (gl_FragCoord.y + detaY)/texHeight); vec4 rgba = vec4( texture2D(YTexture, texCoord).x, texture2D(UTexture, texCoord).x, texture2D(VTexture, texCoord).x, 1) * YUV2RGB; float green = rgba.g - max(rgba.r, rgba.b); float greenKey = keyColor.g - max(keyColor.r, keyColor.b); float mask = smoothstep(greenKey-0.1, 0.0, green); rgba.a = mask; return rgba; } vec4 ProcessChromaKey() { vec4 rgba = GetRgba(0.0, 0.0); if (rgba.a > 0.0 && rgba.a < 1.0) { vec4 rgbas[9]; float maxMask = 0.0; vec4 minRgba = rgba; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { vec4 tmp; if (i == 0 && j == 0) { tmp = rgba; } else { tmp = GetRgba(float(i), float(j)); } rgbas[(i+1)*3 + (j+1)] = tmp; if (tmp.a > maxMask) { maxMask = tmp.a; minRgba = tmp; } } } rgbas[4] = minRgba; rgbas[4].a = rgba.a; vec4 dest = vec4(0.0, 0.0, 0.0, 0.0); float gs[9]; gs[0] = gs[2] = gs[6] = gs[8] = 0.05; gs[1] = gs[3] = gs[5] = gs[7] = 0.05; gs[4] = 0.6; for(int i = 0; i < 9; i++) { dest.rgb = dest.rgb + rgbas[i].rgb * gs[i]; } gs[0] = gs[2] = gs[6] = gs[8] = 0.05; gs[1] = gs[3] = gs[5] = gs[7] = 0.15; gs[4] = 0.2; for(int i = 0; i < 9; i++) { dest.a = dest.a + rgbas[i].a* gs[i]; } rgba.rgb = dest.rgb; rgba.a = dest.a; if (rgba.g > rgba.r && rgba.g > rgba.b) { rgba.g = max(rgba.r, rgba.b); } rgba.rgb = rgba.rgb * rgba.a; } else { rgba.rgb = rgba.rgb * rgba.a; } return rgba; } void main(void) { gl_FragColor = ProcessChromaKey(); } `, g = n.createShader(n.FRAGMENT_SHADER); n.shaderSource(g, e), n.compileShader(g), n.attachShader(r, a), n.attachShader(r, g), n.linkProgram(r), n.useProgram(r), n.getProgramParameter(r, n.LINK_STATUS) || console.log("[ER] Shader link failed."); let _ = n.getAttribLocation(r, "aVertexPosition"); n.enableVertexAttribArray(_); let y = n.getAttribLocation(r, "aTextureCoord"); n.enableVertexAttribArray(y); let x = n.createBuffer(); n.bindBuffer(n.ARRAY_BUFFER, x), n.bufferData(n.ARRAY_BUFFER, new Float32Array([1, 1, 0, -1, 1, 0, 1, -1, 0, -1, -1, 0]), n.STATIC_DRAW), n.vertexAttribPointer(_, 3, n.FLOAT, !1, 0, 0); let E = n.createBuffer(); n.bindBuffer(n.ARRAY_BUFFER, E), n.bufferData(n.ARRAY_BUFFER, new Float32Array([1, 0, 0, 0, 1, 1, 0, 1]), n.STATIC_DRAW), n.vertexAttribPointer(y, 2, n.FLOAT, !1, 0, 0), n.y = new Texture(n), n.u = new Texture(n), n.v = new Texture(n), n.y.bind(0, r, "YTexture"), n.u.bind(1, r, "UTexture"), n.v.bind(2, r, "VTexture"); let C = n.getUniformLocation(r, "texWidth"), L = n.getUniformLocation(r, "texHeight"); n.uniform1f(C, this.canvas.width), n.uniform1f(L, this.canvas.height) } drawFrame(t) { if (!this.gl) { console.log("[ER] Render frame failed due to WebGL not supported."); return } const { data: n, width: r, height: l, yLength: a, uvLength: e } = t, g = new Uint8Array(n), _ = this.gl; _.viewport(0, 0, _.canvas.width, _.canvas.height), _.clearColor(0, 0, 0, 0), _.clear(_.COLOR_BUFFER_BIT), _.y.fill(r, l, g.subarray(0, a)), _.u.fill(r >> 1, l >> 1, g.subarray(a, a + e)), _.v.fill(r >> 1, l >> 1, g.subarray(a + e, g.length)), _.drawArrays(_.TRIANGLE_STRIP, 0, 4) } fullscreen() { let t = this.canvas; t.RequestFullScreen ? t.RequestFullScreen() : t.webkitRequestFullScreen ? t.webkitRequestFullScreen() : t.mozRequestFullScreen ? t.mozRequestFullScreen() : t.msRequestFullscreen ? t.msRequestFullscreen() : alert("This browser doesn't supporter fullscreen") } exitfullscreen() { document.exitFullscreen ? document.exitFullscreen() : document.webkitExitFullscreen ? document.webkitExitFullscreen() : document.mozCancelFullScreen ? document.mozCancelFullScreen() : document.msExitFullscreen ? document.msExitFullscreen() : alert("Exit fullscreen doesn't work") } destroy() { this.flv = null, this.canvas = null, this.gl = null } } let Decoder$1 = class { constructor(t) { return window.VideoDecoder ? new Render(t, this) : new Renderer(t, this) } }; class VideoBasic { constructor(t) { const { flv: n } = t; this.flv = n, this.playing = !1, this.inputVideoIndex = 0, this.outVideoIndex = 0, this.videoFrames = [], this.lastTime = 0; const r = this; n.on("destroy", () => { r.playing = !1, r.videoFrames = null }), n.on("timeupdate", l => { var a; ((a = r.videoFrames[0]) == null ? void 0 : a.pts) <= l + 20 && (parseInt(performance.now()), this.lastTime = parseInt(performance.now()), r.draw(0)) }) } get decoding() { return this.outVideoIndex !== this.inputVideoIndex } framePlay() { return !!((this.lastTime > 0 && this.videoFrames.length > 0 || this.videoFrames.length > 10) && this.playing) } reset() { this.playing = !1, this.workerReset(), window.VideoDecoder && this.videoFrames.forEach(t => { var n; (n = t.data) == null || n.close() }), this.videoFrames = [], this.inputVideoIndex = 0, this.outVideoIndex = 0, this.lastTime = 0 } clearList() { console.log("---clearList---"), window.VideoDecoder && this.videoFrames.forEach(t => { var n; (n = t.data) == null || n.close() }), this.videoFrames = [], this.inputVideoIndex = 0, this.outVideoIndex = 0, this.lastTime = 0 } draw(t) { const n = this.videoFrames[t]; if (!n) return !1; if (this.videoFrames.shift(), window.VideoDecoder) { n.type != "videoEnd" ? this.flv.render.drawFrame(n.data) : (this.flv.playAudioLastFrame(), this.flv.options.wxServerEnd()); return } n.type != "videoEnd" ? this.flv.render.drawFrame(n) : (this.flv.playAudioLastFrame(), this.flv.options.wxServerEnd()) } play() { this.videoFrames.length > 0 ? this.playing = !0 : this.playing = !1 } stop() { this.playing = !1 } } class Wasm extends VideoBasic { constructor(t) { super(t); const { flv: n } = t; this.flv = n, this.firstTarget = !1, this.animationFrameTimer = null, this.list = [], this.loop = !1, this.workerInit(), this.animationFrame(), n.on("videoData", (r, l) => { this.list.push({ buffer: r, timestamp: l }) }), n.on("destroy", () => { this.animationFrameTimer && cancelAnimationFrame(this.animationFrameTimer), this.animationFrameTimer = null, this.decoderWorker.postMessage({ type: "stop" }), this.decoderWorker.terminate(), this.decoderWorker = null }) } workerInit() { const t = this; this.decoderWorker = new Worker("ffmpegWorker.js"), this.decoderWorker.onmessage = n => { const r = n.data; switch (r.type) { case "video": this.outVideoIndex++, this.videoFrames.push(r); break; case "videoEnd": this.outVideoIndex++, this.videoFrames.push(r); break; case "loaded": this.firstTarget ? (console.log("重启wasm"), setTimeout(() => { t.loop = !0 }, 100)) : (this.firstTarget = !0, this.flv.emit("workOn"), setTimeout(() => { t.loop = !0 }, 100)); break } } } workerReset() { this.loop = !1, this.list = [], console.log("wasm restart"), this.decoderWorker.postMessage({ type: "stop" }), this.decoderWorker.terminate(), this.workerInit() } animationFrame() { const t = this; this.animationFrameTimer = requestAnimationFrame(() => { if (t.list[0] && t.loop) { const r = t.list.shift(); t.inputVideoIndex++, t.decoderWorker.postMessage({ data: r.buffer, pts: r.timestamp }, [r.buffer.buffer]) } this.animationFrame() }) } } const webCodecsText = `let renderer = null; let pendingFrame = null; let startTime = null; let frameCount = 0; let width = 1080; let height = 1920; let videoDecoder = null; let h264Arr = []; let decoding = false; let playing = false; let animationFrameTimer = null; let fpsTime = 0; let fpsCount = 0; let missCount = 0; function animationFrame() { animationFrameTimer = requestAnimationFrame(() => { const h264Len = h264Arr.length; if (h264Len > 0 && decoding == false && playing) { let nowTime = getNowTime(); if (fpsTime == 0 || fpsTime < nowTime - 1000) { if (fpsTime == 0) { console.info(nowTime, "start decode"); missCount = 10; } else { if (fpsCount < 25) { missCount += 25 - fpsCount; } else { missCount = missCount - (fpsCount - 25); } console.info(fpsTime, "decode fps", fpsCount, ", miss", missCount); } fpsTime = nowTime; fpsCount = 0; } if (fpsCount < 25 + missCount) { try { const buffer = h264Arr.shift(); // console.log(h264Arr.length, buffer, h264Arr[0]) if (h264Len <= 2 && h264Arr[0]?.byteLength == 1) { self.postMessage({ type: "videoEnd", pts: buffer.timestamp, }); h264Arr = []; } else if (buffer.byteLength != 1) { // console.log("解码") decoding = true; videoDecoder.decode(buffer); fpsCount = fpsCount + 1; } } catch (e) { console.info(e); decoding = false; } } } animationFrame(); }); } // Startup. function webCodes() { videoDecoder = new VideoDecoder({ output: (videoFrame) => { if (!playing) return; self.postMessage( { type: "video", data: videoFrame, pts: videoFrame.timestamp, }, [videoFrame] ); decoding = false; }, error: (error) => { console.error(error); }, }); videoDecoder.configure({ codec: "avc1.64001E", codecWidth: width, //解码数据宽度 codecHeight: height, //解码数据高度 hardwareAcceleration: "prefer-hardware", }); animationFrame(); playing = true; decoding = false; fpsTime = 0; } function start() { webCodes(); console.log("webcodes success"); self.postMessage({ type: "loaded", }); } function reStart() { webCodes(); console.log("reStart webcodes"); } function getNowTime() { if (performance && typeof performance.now === "function") { return parseInt(performance.now()); } return Date.now(); } self.addEventListener( "message", function (e) { var data = e.data; switch (data.type) { case "start": width = data.width; height = data.height; start(); break; case "reStart": playing = false; cancelAnimationFrame(animationFrameTimer); videoDecoder.flush(); h264Arr = []; missCount = 10; reStart(); break; case "destroy": playing = false; videoDecoder.flush(); cancelAnimationFrame(animationFrameTimer); self.close(); // Terminates the worker. break; default: if (playing) { const chunk = new EncodedVideoChunk({ timestamp: data.timestamp, //视频帧的时间戳 type: true ? "key" : "delta", //是否是关键帧 data: data.buffer, //视频数据 }); h264Arr.push(chunk); } } }, false ); `; class WebCode extends VideoBasic { constructor(t) { super(t); const { flv: n } = t, { container: r } = n.options; this.canvas = r, this.worker = createWorker(webCodecsText), this.worker.onmessage = a => { const e = a.data; switch (e.type) { case "video": this.outVideoIndex++, this.videoFrames.push(e); break; case "videoEnd": this.outVideoIndex++, this.videoFrames.push(e); break; case "loaded": n.emit("workOn"); break } }, this.worker.postMessage({ type: "start" }); const l = this; n.on("destroy", () => { l.worker.postMessage({ type: "destroy" }), l.worker.terminate(), l.worker = null }), n.on("videoData", (a, e) => { this.inputVideoIndex++, l.worker.postMessage({ buffer: a, timestamp: e }, [a.buffer]) }) } workerReset() { console.log("webcodes restart"), this.worker.postMessage({ type: "reStart" }) } } class Decoder { constructor(t) { return window.VideoDecoder ? (console.info("Webcodec decode"), new WebCode(t)) : (console.info("wasm decode"), new Wasm(t)) } } var dist = { exports: {} }; (function (h, t) { (function (n, r) { h.exports = r() })(commonjsGlobal, function () { class n { constructor(l) { this.init(l) } init(l) { const a = { inputCodec: "Int16", channels: 1, sampleRate: 8e3, flushTime: 1e3 }; this.option = Object.assign({}, a, l), this.samples = new Float32Array, this.interval = setInterval(this.flush.bind(this), this.option.flushTime), this.convertValue = this.getConvertValue(), this.typedArray = this.getTypedArray(), this.initAudioContext(), this.bindAudioContextEvent() } getConvertValue() { const l = { Int8: 128, Int16: 32768, Int32: 2147483648, Float32: 1 }; if (!l[this.option.inputCodec]) throw new Error("wrong codec.please input one of these codecs:Int8,Int16,Int32,Float32"); return l[this.option.inputCodec] } getTypedArray() { const l = { Int8: Int8Array, Int16: Int16Array, Int32: Int32Array, Float32: Float32Array }; if (!l[this.option.inputCodec]) throw new Error("wrong codec.please input one of these codecs:Int8,Int16,Int32,Float32"); return l[this.option.inputCodec] } initAudioContext() { this.audioCtx = new (window.AudioContext || window.webkitAudioContext), this.gainNode = this.audioCtx.createGain(), this.gainNode.gain.value = .1, this.gainNode.connect(this.audioCtx.destination), this.startTime = this.audioCtx.currentTime } static isTypedArray(l) { return l.byteLength && l.buffer && l.buffer.constructor == ArrayBuffer || l.constructor == ArrayBuffer } isSupported(l) { if (!n.isTypedArray(l)) throw new Error("请传入ArrayBuffer或者任意TypedArray"); return !0 } feed(l) { this.isSupported(l), l = this.getFormattedValue(l); const a = new Float32Array(this.samples.length + l.length); a.set(this.samples, 0), a.set(l, this.samples.length), this.samples = a } getFormattedValue(l) { l.constructor == ArrayBuffer ? l = new this.typedArray(l) : l = new this.typedArray(l.buffer); let a = new Float32Array(l.length); for (let e = 0; e < l.length; e++)a[e] = l[e] / this.convertValue; return a } volume(l) { this.gainNode.gain.value = l } destroy() { this.interval && clearInterval(this.interval), this.samples = null, this.audioCtx.close(), this.audioCtx = null } flush() { if (!this.samples.length) return; const l = this; var a = this.audioCtx.createBufferSource(); typeof this.option.onended == "function" && (a.onended = function (_) { l.option.onended(this, _) }); const e = this.samples.length / this.option.channels, g = this.audioCtx.createBuffer(this.option.channels, e, this.option.sampleRate); for (let _ = 0; _ < this.option.channels; _++) { const y = g.getChannelData(_); let x = _, E = 50; for (let C = 0; C < e; C++)y[C] = this.samples[x], C < 50 && (y[C] = y[C] * C / 50), C >= e - 51 && (y[C] = y[C] * E-- / 50), x += this.option.channels } this.startTime < this.audioCtx.currentTime && (this.startTime = this.audioCtx.currentTime), a.buffer = g, a.connect(this.gainNode), a.start(this.startTime), this.startTime += g.duration, this.samples = new Float32Array } async pause() { await this.audioCtx.suspend() } async continue() { await this.audioCtx.resume() } bindAudioContextEvent() { const l = this; typeof l.option.onstatechange == "function" && (this.audioCtx.onstatechange = function (a) { l.audioCtx && l.option.onstatechange(this, a, l.audioCtx.state) }) } } return n }) })(dist); var distExports = dist.exports; const PCMPlayer$1 = getDefaultExportFromCjs(distExports); let AudioPlayer$1 = class { constructor(t) { const { flv: n } = t; this.playing = !1, this.paused = !1, this.audioPts = [], this.outAudioIndex = 0, this.inputAudioIndex = 0, this.volume = 1, this.audioCtrl = new PCMPlayer$1({ inputCodec: "Int16", channels: 1, sampleRate: 16e3, flushTime: 240, endCallback: () => { this.playing = !1 } }), this.audioCtrl.volume(this.volume), n.on("audioData", (r, l) => { this.audioPts.push({ pts: l, buffer: r }) }), n.on("destroy", () => { this.audioPts = null, this.audioCtrl.destroy(), this.audioCtrl = null }), n.on("timeupdate", r => { this.resume(); let l = 10; for (let a = 0; a < l; a++)this.feed(0) }) } get decoding() { return this.outAudioIndex !== this.inputAudioIndex } get framePlay() { return this.audioPts.length > 0 && this.playing } get getTimestamp() { var t; return (t = this.audioCtrl) == null ? void 0 : t.getTimestamp() } feed(t) { const n = this.audioPts[t]; if (!n) return !1; this.audioCtrl.feed(n.buffer), this.audioPts.shift() } play() { this.audioPts.length > 0 ? this.playing = !0 : this.playing = !1 } reset() { this.playing = !1, this.audioCtrl.destroy(), this.audioCtrl = new PCMPlayer$1({ inputCodec: "Int16", channels: 1, sampleRate: 16e3, flushTime: 240, endCallback: () => { this.playing = !1 } }), this.audioCtrl.volume(this.volume), this.audioPts = [], this.outAudioIndex = 0, this.inputAudioIndex = 0 } clearList() { this.audioPts = [], this.outAudioIndex = 0, this.inputAudioIndex = 0 } stop() { this.playing = !1, this.audioCtrl.pause() } pause() { this.paused == !1 && (console.log("audio pause......."), this.paused = !0, this.audioCtrl.pause()) } resume() { this.paused == !0 && (console.log("audio resume......."), this.paused = !1, this.audioCtrl.continue()) } playLastFrame() { console.log("playLastFrame", this.audioPts.length), this.audioPts.length > 0 && (this.audioPts.some(t => { this.audioCtrl.feed(t.buffer) }), this.audioPts = []) } }, Play$1 = class { constructor(t) { this.flv = t, this.streaming = !1, this.ended = !0, this.animationFrameTimer = null, this.decoder = new Decoder(this), this.audioDecoder = new AudioPlayer$1(this), this.sign = 0, this.resultSign = 0, this.playerStatus = "", this.currentTime = 0, this.lastUpdateTime = 0, t.on("destroy", () => { this.waitingTimer && clearTimeout(this.waitingTimer), this.waitingTimer = null, this.animationFrameTimer && cancelAnimationFrame(this.animationFrameTimer), this.animationFrameTimer = null, this.ended = !0 }), t.on("streaming", () => { this.streaming = !0 }), t.on("streamEnd", () => { this.streaming = !1, this.waitingTimer && clearTimeout(this.waitingTimer), this.waitingTimer = null }) } init() { this.waitingTimer && clearTimeout(this.waitingTimer), this.waitingTimer = null, this.currentTime = 0, this.lastUpdateTime = 0, this.animationFrame(), this.ended = !1 } animationFrame() { this.animationFrameTimer = requestAnimationFrame(() => { if (this.decoder.framePlay()) { const t = parseInt(getNowTime$1()); this.flv.stearmPtsH || (this.flv.stearmPtsH = !0, this.currentTime = 0, this.lastUpdateTime = t), this.currentTime += t - this.lastUpdateTime, this.lastUpdateTime = t, this.flv.emit("timeupdate", this.currentTime), this.playerStatus != "canplay" && (this.playerStatus = "canplay", this.flv.options.canPlay()) } else if (this.streaming || this.decoder.decoding || this.audioDecoder.decoding) { this.audioDecoder.pause(), this.waitingTimer = setTimeout(() => { !this.decoder.framePlay() && !this.audioDecoder.framePlay && this.playerStatus != "waiting" && (this.playerStatus = "waiting", this.flv.options.waiting()), this.lastUpdateTime = getNowTime$1(), this.play() }, 300); return } this.animationFrame() }) } play() { this.decoder.play(), this.audioDecoder.play(), this.animationFrame() } restart() { this.decoder.reset(), this.audioDecoder.reset(), this.currentTime = 0, this.lastUpdateTime = 0, this.playerStatus = "" } clearList() { this.decoder.clearList(), this.audioDecoder.clearList() } continue() { this.animationFrameTimer || (this.playerStatus = "canplay", this.lastUpdateTime = getNowTime$1(), this.animationFrame(), this.audioDecoder.resume(), this.flv.options.canPlay()) } stop() { this.playerStatus = "waiting", this.flv.options.waiting(), this.audioDecoder.pause(), this.waitingTimer && clearTimeout(this.waitingTimer), this.waitingTimer = null, this.animationFrameTimer && cancelAnimationFrame(this.animationFrameTimer), this.animationFrameTimer = null } }, flvStearmLoad$1 = class extends Emitter$1 { constructor(t) { super(), this.options = Object.assign({ url: "", ...t }), this.timestamp = 0, this.audioTimestamp = 0, this.init(), this.stearmPtsH = !1 } init() { this.options.webcodeDisabled && (window.VideoDecoder = !1), this.render = new Decoder$1(this), this.player = new Play$1(this), this.on("workOn", () => { this.stearmInit(), this.player.init() }), this.timestamp = 0, this.audioTimestamp = 0 } stearmInit() { const t = this; this.socket = new WebSocket(this.options.url), this.socket.binaryType = "arraybuffer", this.socket.onopen = () => { t.options.cbOpen(t.socket), t.emit("streamStart") }, this.socket.onmessage = n => { t.options.cbMessage(t.socket, n, function (r, l) { if (l) { t.clearList(); return } t.emit("streaming"), r[0] === 80 && r[1] === 67 && r[2] === 77 ? (t.audioTimestamp += 40, t.emit("audioData", r.slice(3), t.audioTimestamp)) : (t.timestamp += 40, t.emit("videoData", r, t.timestamp)) }) }, this.socket.onerror = n => { throw t.options.cbError(t.socket, n), t.emit("streamError", n), n }, this.socket.onclose = () => { this.stearmPtsH = !1, t.options.cbClose(t.socket), t.emit("streamEnd") }, console.log(this.options.url) } destroy() { this.emit("destroy"), this.socket && (this.socket.close(), this.socket = null), this.render.destroy(), this.render = null } restart() { console.error("restart stream"), this.timestamp = 80, this.audioTimestamp = 0, this.stearmPtsH = !1, this.player.restart() } clearList() { this.player.clearList() } changeVolume(t) { console.log(this.player.audioDecoder), t ? (this.player.audioDecoder.volume = 0, this.player.audioDecoder.audioCtrl.volume(0)) : (this.player.audioDecoder.volume = 1, this.player.audioDecoder.audioCtrl.volume(1)) } playAudioLastFrame() { this.player.audioDecoder.playLastFrame() } }; const isPlat$2 = judgeEnvironment().includes("Chrome"); let ffmPlayer = null, pacemaker$2 = !1, websocket$2 = null, videoPlayerInit$1 = !1, interval$2 = 5, ffmcanvas = null, c2 = null, silentVideo$1 = null, videoWidth$2 = "", videoHeight$2 = "", reqRes$2 = null, playStatus = !1, serverEnded = !1, videoFlow = "", emitter$2 = new Emitter$2; const checkVideoStatus = debounce(() => { console.log("checkVideoStatus"), playStatus && videoFlow == "waiting" && serverEnded && (serverEnded = !1, emitter$2.emit("videoEnd"), websocket$2 == null || websocket$2.send(SendMsg.startAsr())) }, 280), checkCondition$2 = h => { "WebSocket" in window ? h(!0, "success") : h(!1, "当前浏览器不支持websocketio连接") }, webReconnect$1 = (h = !1) => { slientShowTarget(!0), ffmPlayer.restart(), videoPlayerInit$1 = !0 }, loopConnect$2 = () => { uninstallEvent$2(!1), startPlayer$2() }, pageAcitveStatusGet$2 = () => { (() => { setTimeout(() => { interval$2 += 5, interval$2 > 30 && (interval$2 = 30), loopConnect$2() }, interval$2 * 1e3) })() }, uninstallEvent$2 = (h = !0) => { pacemaker$2 = h, videoPlayerInit$1 = !1, heartPing.end(), ffmPlayer && (ffmPlayer.destroy(), ffmPlayer = null) }; let asrWsApp$2 = null; const startPlayer$2 = () => { let { _sign: h, _projectId: t, _drivertype: n, _volume: r, _asr: l, decodeType: a } = commonObj; ffmPlayer = new flvStearmLoad$1({ url: websocketInit$1({ _projectId: t, _sign: h, isPlat: isPlat$2, type: 0, _drivertype: n, requestVideo: requestVideo$2 }), width: videoWidth$2, height: videoHeight$2, container: ffmcanvas, webcodeDisabled: a == 2, cbOpen: function (e) { console.log("建立websocket", e), websocket$2 = e, l && asrWsApp$2 && asrWsApp$2(e), heartPing.start(() => { (websocket$2 == null ? void 0 : websocket$2.readyState) == 1 && (websocket$2 == null || websocket$2.send(JSON.stringify({ signal: "ping" }))) }) }, cbMessage: isPlat$2 ? function (e, g, _) { if (typeof g.data == "object") { const y = new Uint8Array(g.data); if (!(y[0] !== 72 || y[1] !== 80 || y[2] !== 67 || y[3] !== 77)) { videoPlayerInit$1 = !1, console.log("——————————loop new——————————————"), _(null, !0); return } videoPlayerInit$1 || _(y, videoPlayerInit$1) } else if (g.data != "ppg-end") { if (g.data.includes("requests overload")) pacemaker$2 = !0, emitter$2.emit("wsMessage", { type: "requests overload" }); else if (g.data.includes("{")) { const y = JSON.parse(g.data); y.type == "asr-part" || y.type == "asr" || y.type == "answer" ? emitter$2.emit("wsMessage", y) : y.type == "startAsr" || y.type == "startSleep" || y.type == "wakeup" || (y.type == "server_ready" ? emitter$2.emit("wsMessage", y) : y.type == "server_ended" || (y.type == "error" ? (emitter$2.emit("wsMessage", y), console.error(y.content)) : y.type == "node")) } } } : function (e, g, _) { const y = new Uint8Array(g.data); if (y[0] === 116 && y[1] === 101 && y[2] === 120 && y[3] === 116) { const x = get_text$1(y); if (x != "ppg-end") { if (x != "pong") { if (x.includes("requests overload")) pacemaker$2 = !0, emitter$2.emit("wsMessage", { type: "requests overload" }); else if (x.includes("{")) { const E = JSON.parse(x); E.type == "asr-part" || E.type == "asr" || E.type == "answer" ? emitter$2.emit("wsMessage", E) : E.type == "startAsr" || E.type == "startSleep" || E.type == "wakeup" || (E.type == "server_ready" ? emitter$2.emit("wsMessage", E) : E.type == "server_ended" || (E.type == "error" ? (emitter$2.emit("wsMessage", E), console.error(E.content)) : E.type == "node")) } } } } else { if (!(y[0] !== 72 || y[1] !== 80 || y[2] !== 67 || y[3] !== 77)) { videoPlayerInit$1 = !1, console.log("——————————loop new——————————————"), _(null, !0); return } videoPlayerInit$1 || _(y, videoPlayerInit$1) } }, cbError: function (e, g) { console.error("websocket错误:", g), emitter$2.emit("wsMessage", { type: "websocket Error", value: g }) }, cbClose: function (e) { console.error("websocket关闭!"), pacemaker$2 ? emitter$2.emit("wsMessage", { type: "websocket close" }) : (pageAcitveStatusGet$2(), emitter$2.emit("wsMessage", { type: "websocket reLoop" })) }, cbDestroy: function (e) { console.error("websocket销毁!") }, wxServerEnd: function () { console.log("-----wxServerEnd"), playStatus = !0, serverEnded = !0, checkVideoStatus() }, canPlay: function () { console.log("-----canPlay"), slientShowTarget(!1), webglCut.videoPlay(), videoFlow = "canplay", emitter$2.emit("videoStart") }, waiting: function () { console.log("-----waiting"), slientShowTarget(!0), webglCut.slicePlay(), videoFlow = "waiting", checkVideoStatus() } }) }; function displayEle$1(h, t) { h.style.display = t } const slientShowTarget = debounce(h => { h ? (displayEle$1(ffmcanvas, "none"), displayEle$1(c2, "inline")) : (displayEle$1(ffmcanvas, "inline"), displayEle$1(c2, "none")) }, 120); let requestVideo$2 = ""; function player$2(h, t, n, r, l = 1) { videoWidth$2 = viewMap[t][r].width, videoHeight$2 = viewMap[t][r].height, requestVideo$2 = `requestWidth=${videoWidth$2}&requestHeight=${videoHeight$2}`, document.querySelector(h).innerHTML = ` `, ffmcanvas = querySelectorEl("#ffmcanvas"), c2 = querySelectorEl("#digitalPlayer"), silentVideo$1 = querySelectorEl("#silentVideo"), displayEle$1(ffmcanvas, "none"), displayEle$1(c2, "none") } let xxPlayer$2 = class extends Emitter$2 { constructor({ environment: t, containerLable: n, token: r, projectId: l, quality: a, zoom: e, clientId: g, volume: _, asr: y }, x) { if (super(), y) { const { asrDestroy: E, asrWsAppoint: C, asrStart: L } = asrWs(A => { console.log(A, "mic") }); asrWsApp$2 = C, L() } emitter$2 = new Emitter$2, this.containerLable = n, commonObj._sign = r, commonObj._projectId = l, this.quality = a || 1, this.zoom = e || 1, commonObj._env = t || "prd", commonObj._volume = _ || 1, commonObj._asr = y || !1, commonObj.decodeType = x.data.decodeType, reqRes$2 = x, this.streamImg = !1 } init() { checkCondition$2(t => { if (t) { let { avatarSilenceUrl: n, avatarDirection: r } = reqRes$2.data; player$2(this.containerLable, r, n, this.quality, this.zoom), emitter$2.on("videoEnd", () => { this.emit("message", { type: "videoEnd", data: {} }) }), emitter$2.on("videoStart", () => { this.emit("message", { type: "videoStart", data: {} }) }), emitter$2.on("wsMessage", l => { this.emit("message", { type: "wsMessage", data: l }) }), emitter$2.on("initIos", () => { this.emit("intialSucccess", { type: "2" }) }), this.emit("intialSucccess", { type: "1" }) } else this.emit("intialError", msg) }) } playSilentvideo() { silentVideo$1 && silentVideo$1.play().then(t => { console.log("ffm交互静音视频播放") }).catch(t => { console.log("ffm交互静音视频播放失败-", t) }) } startPlay() { ffmcanvas && (console.log("xiaohui"), displayEle$1(ffmcanvas, "none")), webglCut.load(null, silentVideo$1, c2, t => { videoPlayerInit$1 = !0, webglCut.slicePlay(), displayEle$1(c2, "inline"), startPlayer$2(this.direction, this.quality), emitter$2.emit("initIos") }) } setClientId(t) { t ? commonObj._clientId = t : console.log("clientId不能为空") } stopPlay() { uninstallEvent$2(), emitter$2 = null, ffmcanvas = null, c2 = null, silentVideo$1 = null, videoWidth$2 = "", videoHeight$2 = "", reqRes$2 = null, this.streamImg = !1 } playQA(t, n) { websocket$2 == null || websocket$2.send(SendMsg.qa(t, n)), this.streamImg = !0 } interrupt() { websocket$2 == null || websocket$2.send(SendMsg.interrupt()), webglCut.slicePlay(), webReconnect$1(!0), this.streamImg = !1 } playText(t) { websocket$2 == null || websocket$2.send(SendMsg.text(t)) } playStreamText(t) { websocket$2 == null || websocket$2.send(SendMsg.streamText(t)) } playStreamTextStart(t, n) { websocket$2 == null || websocket$2.send(SendMsg.streamTextStart(t, n)), this.streamImg = !0 } playStreamTextEnd() { websocket$2 == null || websocket$2.send(SendMsg.streamTextEnd()) } playAudio(t) { websocket$2 == null || websocket$2.send(SendMsg.streamAudio(t)), this.streamImg = !0 } playAudioEnd() { websocket$2 == null || websocket$2.send(SendMsg.streamAudioEnd()) } playCurVideo() { this.streamImg && (websocket$2 == null || websocket$2.send(SendMsg.resumePlay()), ffmPlayer.player.continue()) } stopCurVideo() { this.streamImg && (websocket$2 == null || websocket$2.send(SendMsg.pausePlay()), ffmPlayer.player.stop()) } }; function webRtcPlayer(h) { h = typeof h < "u" ? h : {}; var t = this; this.cfg = typeof h.peerConnectionOptions < "u" ? h.peerConnectionOptions : {}, this.cfg.sdpSemantics = "unified-plan", this.cfg.offerExtmapAllowMixed = !1, this.pcClient = null, this.dcClient = null, this.tnClient = null, this._audio = null, this._volume = 1, this.sdpConstraints = { offerToReceiveAudio: 1, offerToReceiveVideo: 1, voiceActivityDetection: !1 }, this.dataChannelOptions = { ordered: !0 }, this.startVideoMuted = typeof h.startVideoMuted < "u" ? h.startVideoMuted : !1, this.autoPlayAudio = typeof h.autoPlayAudio < "u" ? h.autoPlayAudio : !0; const n = new URLSearchParams(window.location.search); this.useMic = n.has("useMic"), this.useMic; let r = location.hostname === "localhost" || location.hostname === "127.0.0.1", l = location.protocol === "https:"; this.useMic && !r && !l && (this.useMic = !1), this.latencyTestTimings = { TestStartTimeMs: null, UEReceiptTimeMs: null, UEPreCaptureTimeMs: null, UEPostCaptureTimeMs: null, UEPreEncodeTimeMs: null, UEPostEncodeTimeMs: null, UETransmissionTimeMs: null, BrowserReceiptTimeMs: null, FrameDisplayDeltaTimeMs: null, Reset: function () { this.TestStartTimeMs = null, this.UEReceiptTimeMs = null, this.UEPreCaptureTimeMs = null, this.UEPostCaptureTimeMs = null, this.UEPreEncodeTimeMs = null, this.UEPostEncodeTimeMs = null, this.UETransmissionTimeMs = null, this.BrowserReceiptTimeMs = null, this.FrameDisplayDeltaTimeMs = null }, SetUETimings: function (w) { this.UEReceiptTimeMs = w.ReceiptTimeMs, this.UEPreCaptureTimeMs = w.PreCaptureTimeMs, this.UEPostCaptureTimeMs = w.PostCaptureTimeMs, this.UEPreEncodeTimeMs = w.PreEncodeTimeMs, this.UEPostEncodeTimeMs = w.PostEncodeTimeMs, this.UETransmissionTimeMs = w.TransmissionTimeMs, this.BrowserReceiptTimeMs = Date.now(), this.OnAllLatencyTimingsReady(this) }, SetFrameDisplayDeltaTime: function (w) { this.FrameDisplayDeltaTimeMs == null && (this.FrameDisplayDeltaTimeMs = Math.round(w), this.OnAllLatencyTimingsReady(this)) }, OnAllLatencyTimingsReady: function (w) { } }, this.createWebRtcVideo = function () { var w = document.createElement("video"); if (w.id = "digital3DPlayer", w.playsInline = !0, w.disablepictureinpicture = !0, w.muted = t.startVideoMuted, w.autoplay = "autoplay", w.hidden = !0, w.addEventListener("loadedmetadata", function (S) { t.onVideoInitialised && t.onVideoInitialised() }, !0), "requestVideoFrameCallback" in HTMLVideoElement.prototype) { const S = (O, F) => { if (F.receiveTime && F.expectedDisplayTime) { const j = F.presentationTime - F.receiveTime; t.aggregatedStats.receiveToCompositeMs = j } w.requestVideoFrameCallback(S) }; w.requestVideoFrameCallback(S) } return w }, this.video = this.createWebRtcVideo(); const a = function (w) { }, e = function (w) { }, g = function (w) { }, _ = function (w) { if (w.track, w.track.kind == "audio") { y(w.streams[0]); return } else w.track.kind == "video" && (t.video.srcObject, w.streams[0]); { t.video.srcObject = w.streams[0]; return } }, y = function (w) { if (t.video.srcObject != w && t.video.srcObject && t.video.srcObject !== w) { let S = document.createElement("Audio"); if (t._audio = S, S.volume = t._volume, S.srcObject = w, t.autoPlayAudio) S.play(); else { let O = function () { S.play(), t.video.removeEventListener("click", O) }; t.video.addEventListener("click", O) } } }, x = function (w, S, O) { try { let F = w.createDataChannel(S, O); return F.binaryType = "arraybuffer", F.onopen = function (j) { t.onDataChannelConnected && t.onDataChannelConnected() }, F.onclose = function (j) { }, F.onmessage = function (j) { t.onDataChannelMessage && t.onDataChannelMessage(j.data) }, F } catch { return null } }, E = function (w) { w.candidate && w.candidate.candidate && t.onWebRtcCandidate(w.candidate) }, C = function (w) { w.createOffer(t.sdpConstraints).then(function (S) { L(S), w.setLocalDescription(S), t.onWebRtcOffer && t.onWebRtcOffer(S) }, function () { console.warn("Couldn't create offer") }) }, L = function (w) { w.sdp = w.sdp.replace("useinbandfec=1", "useinbandfec=1;stereo=1;sprop-maxcapturerate=48000") }, A = function (w) { w.SetBitrate && (w.onsignalingstatechange = a), w.oniceconnectionstatechange = e, w.onicegatheringstatechange = g, w.ontrack = _, w.onicecandidate = E }, I = function () { return t.aggregatedStats || (t.aggregatedStats = {}), function (w) { let S = {}; w.forEach(O => { O.type == "inbound-rtp" && !O.isRemote && (O.mediaType == "video" || O.id.toLowerCase().includes("video")) && (S.timestamp = O.timestamp, S.bytesReceived = O.bytesReceived, S.framesDecoded = O.framesDecoded, S.packetsLost = O.packetsLost, S.bytesReceivedStart = t.aggregatedStats && t.aggregatedStats.bytesReceivedStart ? t.aggregatedStats.bytesReceivedStart : O.bytesReceived, S.framesDecodedStart = t.aggregatedStats && t.aggregatedStats.framesDecodedStart ? t.aggregatedStats.framesDecodedStart : O.framesDecoded, S.timestampStart = t.aggregatedStats && t.aggregatedStats.timestampStart ? t.aggregatedStats.timestampStart : O.timestamp, t.aggregatedStats && t.aggregatedStats.timestamp && (t.aggregatedStats.bytesReceived && (S.bitrate = 8 * (S.bytesReceived - t.aggregatedStats.bytesReceived) / (S.timestamp - t.aggregatedStats.timestamp), S.bitrate = Math.floor(S.bitrate), S.lowBitrate = t.aggregatedStats.lowBitrate && t.aggregatedStats.lowBitrate < S.bitrate ? t.aggregatedStats.lowBitrate : S.bitrate, S.highBitrate = t.aggregatedStats.highBitrate && t.aggregatedStats.highBitrate > S.bitrate ? t.aggregatedStats.highBitrate : S.bitrate), t.aggregatedStats.bytesReceivedStart && (S.avgBitrate = 8 * (S.bytesReceived - t.aggregatedStats.bytesReceivedStart) / (S.timestamp - t.aggregatedStats.timestampStart), S.avgBitrate = Math.floor(S.avgBitrate)), t.aggregatedStats.framesDecoded && (S.framerate = (S.framesDecoded - t.aggregatedStats.framesDecoded) / ((S.timestamp - t.aggregatedStats.timestamp) / 1e3), S.framerate = Math.floor(S.framerate), S.lowFramerate = t.aggregatedStats.lowFramerate && t.aggregatedStats.lowFramerate < S.framerate ? t.aggregatedStats.lowFramerate : S.framerate, S.highFramerate = t.aggregatedStats.highFramerate && t.aggregatedStats.highFramerate > S.framerate ? t.aggregatedStats.highFramerate : S.framerate), t.aggregatedStats.framesDecodedStart && (S.avgframerate = (S.framesDecoded - t.aggregatedStats.framesDecodedStart) / ((S.timestamp - t.aggregatedStats.timestampStart) / 1e3), S.avgframerate = Math.floor(S.avgframerate)))), O.type == "track" && (O.trackIdentifier == "video_label" || O.kind == "video") && (S.framesDropped = O.framesDropped, S.framesReceived = O.framesReceived, S.framesDroppedPercentage = O.framesDropped / O.framesReceived * 100, S.frameHeight = O.frameHeight, S.frameWidth = O.frameWidth, S.frameHeightStart = t.aggregatedStats && t.aggregatedStats.frameHeightStart ? t.aggregatedStats.frameHeightStart : O.frameHeight, S.frameWidthStart = t.aggregatedStats && t.aggregatedStats.frameWidthStart ? t.aggregatedStats.frameWidthStart : O.frameWidth), O.type == "candidate-pair" && O.hasOwnProperty("currentRoundTripTime") && O.currentRoundTripTime != 0 && (S.currentRoundTripTime = O.currentRoundTripTime) }), t.aggregatedStats.receiveToCompositeMs && (S.receiveToCompositeMs = t.aggregatedStats.receiveToCompositeMs, t.latencyTestTimings.SetFrameDisplayDeltaTime(t.aggregatedStats.receiveToCompositeMs)), t.aggregatedStats = S, t.onAggregatedStats && t.onAggregatedStats(S) } }, D = async function (w) { if (w.addTransceiver("video", { direction: "recvonly" }), !t.useMic) w.addTransceiver("audio", { direction: "recvonly" }); else { let S = t.useMic ? { autoGainControl: !1, channelCount: 1, echoCancellation: !1, latency: 0, noiseSuppression: !1, sampleRate: 16e3, volume: 1 } : !1; const O = await navigator.mediaDevices.getUserMedia({ video: !1, audio: S }); if (O) for (const F of O.getTracks()) F.kind && F.kind == "audio" && w.addTransceiver(F, { direction: "sendrecv" }); else w.addTransceiver("audio", { direction: "recvonly" }) } }; this.setVideoEnabled = function (w) { t.video.srcObject.getTracks().forEach(S => S.enabled = w) }, this.startLatencyTest = function (w) { t.video && (t.latencyTestTimings.Reset(), t.latencyTestTimings.TestStartTimeMs = Date.now(), w(t.latencyTestTimings.TestStartTimeMs)) }, this.handleCandidateFromServer = function (w) { let S = new RTCIceCandidate(w); t.pcClient.addIceCandidate(S).then(O => { }) }, this.createOffer = function () { t.pcClient && (t.pcClient.close(), t.pcClient = null), t.pcClient = new RTCPeerConnection(t.cfg), D(t.pcClient).finally(function () { A(t.pcClient), t.dcClient = x(t.pcClient, "cirrus", t.dataChannelOptions), C(t.pcClient) }) }, this.receiveAnswer = function (w) { var S = new RTCSessionDescription(w); t.pcClient.setRemoteDescription(S); let O = t.pcClient.getReceivers(); for (let F of O) F.playoutDelayHint = 0 }, this.close = function () { t.pcClient && (t.pcClient.close(), t.pcClient = null), t.aggregateStatsIntervalId && clearInterval(t.aggregateStatsIntervalId) }, this.send = function (w) { t.dcClient && t.dcClient.readyState == "open" && t.dcClient.send(w) }, this.getStats = function (w) { t.pcClient && w && t.pcClient.getStats(null).then(S => { w(S) }) }, this.aggregateStats = function (w) { let S = I(), O = () => { t.getStats(S) }; t.aggregateStatsIntervalId = setInterval(O, w) }, this.changeVol = function (w) { this._volume = w, this._audio && (this._audio.volume = w) } } let webSocketUrl = null, successCallback = () => { }, failCallback = () => { }, interactiveTimeExpiredCallback = () => { }, kbEvent = document.createEvent("KeyboardEvent"); typeof kbEvent.initKeyboardEvent < "u"; let webRtcPlayerObj = null, ws; const WS_OPEN_STATE = 1; let lastTimeResized = new Date().getTime(), resizeTimeout, responseEventListeners = new Map, freezeFrameOverlay = null, shouldShowPlayOverlay = !0, freezeFrame = { receiving: !1, size: 0, jpeg: void 0, height: 0, width: 0, valid: !1 }, afk = { enabled: !0, warnTimeout: 9999999, closeTimeout: 10, active: !1, overlay: void 0, warnTimer: void 0, countdown: 0, countdownTimer: void 0 }, editTextButton, hiddenInput; function setOverlay(h, t, n) { let r = document.getElementById("videoPlayOverlay"); if (!r) { let a = document.getElementById("player"); r = document.createElement("div"), r.id = "videoPlayOverlay", a && a.appendChild(r) } for (; r.lastChild;)r.removeChild(r.lastChild); t && r.appendChild(t), n && r.addEventListener("click", function a(e) { n(e), r.removeEventListener("click", a) }); let l = r.classList; for (let a = l.length - 1; a >= 0; a--)l.remove(l[a]); r.classList.add(h) } function showConnectOverlay() { connect(), startAfkWarningTimer() } function showTextOverlay(h) { let t = document.createElement("div"); t.id = "messageOverlay", t.innerHTML = h || "", setOverlay("textDisplayState", t) } function showAfkOverlay() { stopAfkWarningTimer(), afk.overlay = document.createElement("div"), afk.overlay.id = "afkOverlay", setOverlay("clickableState", afk.overlay, h => { hideOverlay(), clearInterval(afk.countdownTimer), startAfkWarningTimer() }), afk.countdown = afk.closeTimeout, document.exitPointerLock(), afk.countdownTimer = setInterval(function () { afk.countdown--, afk.countdown == 0 && (hideOverlay(), ws.close(), clearInterval(afk.countdownTimer)) }, 1e3) } function hideOverlay() { setOverlay("hiddenState") } function startAfkWarningTimer() { afk.active = afk.enabled, resetAfkWarningTimer() } function stopAfkWarningTimer() { afk.active = !1 } let num = afk.warnTimeout, fiveMinuteTimer = null; function resetAfkWarningTimer() { afk.active && (num = afk.warnTimeout, clearTimeout(afk.warnTimer), clearInterval(afk.countdownTimer), clearInterval(fiveMinuteTimer), fiveMinuteTimer = setInterval(() => { num--, num === 0 && interactiveTimeExpiredCallback && interactiveTimeExpiredCallback(!0) }, 1e3), afk.warnTimer = setTimeout(function () { showAfkOverlay() }, afk.warnTimeout * 1e3)) } function createWebRtcOffer() { webRtcPlayerObj ? (console.log("Creating offer"), webRtcPlayerObj.createOffer()) : (console.log("WebRTC player not setup, cannot create offer"), showTextOverlay("Unable to setup video")) } function sendInputData(h) { webRtcPlayerObj && (interactiveTimeExpiredCallback && interactiveTimeExpiredCallback(!1), afk.active = afk.enabled, resetAfkWarningTimer(), webRtcPlayerObj.send(h)) } const ToClientMessageType = { QualityControlOwnership: 0, Response: 1, Command: 2, FreezeFrame: 3, UnfreezeFrame: 4, VideoEncoderAvgQP: 5, LatencyTest: 6, InitialSettings: 7 }; let VideoEncoderQP = "N/A"; function setupWebRtcPlayer(h, t) { webRtcPlayerObj = new webRtcPlayer(t), h.appendChild(webRtcPlayerObj.video), webRtcPlayerObj.onWebRtcOffer = function (l) { if (ws && ws.readyState === WS_OPEN_STATE) { let a = JSON.stringify(l); ws.send(a) } }, webRtcPlayerObj.onWebRtcCandidate = function (l) { ws && ws.readyState === WS_OPEN_STATE && ws.send(JSON.stringify({ type: "iceCandidate", candidate: l })) }, webRtcPlayerObj.onVideoInitialised = function () { ws && ws.readyState === WS_OPEN_STATE && shouldShowPlayOverlay && resizePlayerStyle() }, webRtcPlayerObj.onDataChannelConnected = function () { ws && ws.readyState === WS_OPEN_STATE && webRtcPlayerObj.video && webRtcPlayerObj.video.srcObject && webRtcPlayerObj.onVideoInitialised && (webRtcPlayerObj.onVideoInitialised(), successCallback && successCallback(ws)) }; function n() { let l = btoa(freezeFrame.jpeg.reduce((e, g) => e + String.fromCharCode(g), "")), a = document.getElementById("freezeFrameOverlay").childNodes[0]; a.src = "data:image/jpeg;base64," + l, a.onload = function () { freezeFrame.height = a.naturalHeight, freezeFrame.width = a.naturalWidth, resizeFreezeFrameOverlay(), shouldShowPlayOverlay ? resizePlayerStyle() : showFreezeFrameOverlay(), webRtcPlayerObj.setVideoEnabled(!1) } } function r(l) { freezeFrame.receiving || (freezeFrame.receiving = !0, freezeFrame.valid = !1, freezeFrame.size = 0, freezeFrame.jpeg = void 0), freezeFrame.size = new DataView(l.slice(1, 5).buffer).getInt32(0, !0); let a = l.slice(1 + 4); if (freezeFrame.jpeg) { let e = new Uint8Array(freezeFrame.jpeg.length + a.length); e.set(freezeFrame.jpeg, 0), e.set(a, freezeFrame.jpeg.length), freezeFrame.jpeg = e } else freezeFrame.jpeg = a, freezeFrame.receiving = !0, console.log(`received first chunk of freeze frame: ${freezeFrame.jpeg.length}/${freezeFrame.size}`); freezeFrame.jpeg.length === freezeFrame.size ? (freezeFrame.receiving = !1, freezeFrame.valid = !0, console.log(`received complete freeze frame ${freezeFrame.size}`), n()) : freezeFrame.jpeg.length > freezeFrame.size && (console.error(`received bigger freeze frame than advertised: ${freezeFrame.jpeg.length}/${freezeFrame.size}`), freezeFrame.jpeg = void 0, freezeFrame.receiving = !1) } return webRtcPlayerObj.onDataChannelMessage = function (l) { let a = new Uint8Array(l); if (a[0] === ToClientMessageType.QualityControlOwnership) { let e = a[1] !== 0; console.log("Received quality controller message, will control quality: " + e) } else if (a[0] === ToClientMessageType.Response) { let e = new TextDecoder("utf-16").decode(l.slice(1)); for (let g of responseEventListeners.values()) g(e) } else if (a[0] === ToClientMessageType.Command) { let e = new TextDecoder("utf-16").decode(l.slice(1)); console.log(e); let g = JSON.parse(e); g.command === "onScreenKeyboard" && showOnScreenKeyboard(g) } else if (a[0] === ToClientMessageType.FreezeFrame) r(a); else if (a[0] === ToClientMessageType.UnfreezeFrame) invalidateFreezeFrameOverlay(); else if (a[0] === ToClientMessageType.VideoEncoderAvgQP) VideoEncoderQP = new TextDecoder("utf-16").decode(l.slice(1)); else if (a[0] == ToClientMessageType.LatencyTest) { let e = new TextDecoder("utf-16").decode(l.slice(1)); console.log("Got latency timings from UE."), console.log(e); let g = JSON.parse(e); webRtcPlayerObj && webRtcPlayerObj.latencyTestTimings.SetUETimings(g) } else if (a[0] == ToClientMessageType.InitialSettings) { let e = new TextDecoder("utf-16").decode(l.slice(1)); JSON.parse(e) } else console.error(`unrecognized data received, packet ID ${a[0]}`) }, createWebRtcOffer(), webRtcPlayerObj.video } function onWebRtcAnswer(h) { webRtcPlayerObj.receiveAnswer(h), webRtcPlayerObj.onAggregatedStats = t => { let n = new Intl.NumberFormat(window.navigator.language, { maximumFractionDigits: 0 }), r = new Intl.NumberFormat(window.navigator.language, { maximumFractionDigits: 0, minimumIntegerDigits: 2 }), l = (t.timestamp - t.timestampStart) / 1e3, a = [], e = [60, 60]; for (let w = 0; w < e.length; w++)a.push(l % e[w]), l = l / e[w]; a.push(l); let g = a[0], _ = Math.floor(a[1]), y = Math.floor([a[2]]), x = "B", E = t.hasOwnProperty("bytesReceived") ? t.bytesReceived : 0, C = ["kB", "MB", "GB"]; for (let w = 0; w < C.length && !(E < 100 * 1e3); w++)E = E / 1e3, x = C[w]; document.getElementById("qualityStatus"); const L = 26, A = 35; let I = "", D = "lime"; VideoEncoderQP > A ? (D = "red", I += `
Bad network connection
`) : VideoEncoderQP > L && (D = "orange", I += `
Spotty network connection
`), I += `
Duration: ${r.format(y)}:${r.format(_)}:${r.format(g)}
`, I += `
Video Resolution: ${t.hasOwnProperty("frameWidth") && t.frameWidth && t.hasOwnProperty("frameHeight") && t.frameHeight ? t.frameWidth + "x" + t.frameHeight : "Chrome only"}
`, I += `
Received (${x}): ${n.format(E)}
`, I += `
Frames Decoded: ${t.hasOwnProperty("framesDecoded") ? n.format(t.framesDecoded) : "Chrome only"}
`, I += `
Packets Lost: ${t.hasOwnProperty("packetsLost") ? n.format(t.packetsLost) : "Chrome only"}
`, I += `
Bitrate (kbps): ${t.hasOwnProperty("bitrate") ? n.format(t.bitrate) : "Chrome only"}
`, I += `
Framerate: ${t.hasOwnProperty("framerate") ? n.format(t.framerate) : "Chrome only"}
`, I += `
Frames dropped: ${t.hasOwnProperty("framesDropped") ? n.format(t.framesDropped) : "Chrome only"}
`, I += `
Net RTT (ms): ${t.hasOwnProperty("currentRoundTripTime") ? n.format(t.currentRoundTripTime * 1e3) : "Can't calculate"}
`, I += `
Browser receive to composite (ms): ${t.hasOwnProperty("receiveToCompositeMs") ? n.format(t.receiveToCompositeMs) : "Chrome only"}
`, I += `
Video Quantization Parameter: ${VideoEncoderQP}
` }, webRtcPlayerObj.aggregateStats(1 * 1e3), webRtcPlayerObj.latencyTestTimings.OnAllLatencyTimingsReady = function (t) { if (!t.BrowserReceiptTimeMs) return; let n = t.BrowserReceiptTimeMs - t.TestStartTimeMs, r = t.UEPreEncodeTimeMs == 0 || t.UEPreCaptureTimeMs == 0 ? "???" : t.UEPostEncodeTimeMs - t.UEPreCaptureTimeMs, l = t.UEPostCaptureTimeMs - t.UEPreCaptureTimeMs, a = t.UEPostEncodeTimeMs - t.UEPreEncodeTimeMs, e = t.UETransmissionTimeMs - t.UEReceiptTimeMs, g = n - e, _ = n - g - e, y = null, x = null; t.FrameDisplayDeltaTimeMs && t.BrowserReceiptTimeMs && (y = t.FrameDisplayDeltaTimeMs + n, x = y - g - e); let E = ""; E += `
Net latency RTT (ms): ${g}
`, E += `
UE Capture+Encode (ms): ${r}
`, E += `
UE Capture (ms): ${l}
`, E += `
UE Encode (ms): ${a}
`, E += `
Total UE latency (ms): ${e}
`, E += `
Browser send latency (ms): ${_}
`, E += t.FrameDisplayDeltaTimeMs && t.BrowserReceiptTimeMs ? `
Browser receive latency (ms): ${t.FrameDisplayDeltaTimeMs}
` : "", E += x ? `
Total browser latency (ms): ${x}
` : "", E += `
Total latency (excluding browser) (ms): ${n}
`, E += y ? `
Total latency (ms): ${y}
` : "", document.getElementById("LatencyStats").innerHTML = E } } function onWebRtcIce(h) { webRtcPlayerObj && webRtcPlayerObj.handleCandidateFromServer(h) } let styleWidth, styleHeight, styleTop, styleLeft, styleCursor = "default", styleAdditional; function resizePlayerStyleToFillWindow(h) { let t = h.getElementsByTagName("VIDEO"), n = window.innerHeight / window.innerWidth, r = h.clientHeight / h.clientWidth, l = t.videoHeight / t.videoWidth; isNaN(l) ? (styleWidth = window.innerWidth, styleHeight = window.innerHeight, styleTop = 0, styleLeft = 0, h.style = "top: " + styleTop + "px; left: " + styleLeft + "px; width: " + styleWidth + "px; height: " + styleHeight + "px; cursor: " + styleCursor + "; " + styleAdditional) : n < r ? (styleWidth = Math.floor(window.innerHeight / l), styleHeight = window.innerHeight, styleTop = 0, styleLeft = Math.floor((window.innerWidth - styleWidth) * .5), h.style = "top: " + styleTop + "px; left: " + styleLeft + "px; width: " + styleWidth + "px; height: " + styleHeight + "px; cursor: " + styleCursor + "; " + styleAdditional) : (styleWidth = window.innerWidth, styleHeight = Math.floor(window.innerWidth * l), styleTop = Math.floor((window.innerHeight - styleHeight) * .5), styleLeft = 0, h.style = "top: " + styleTop + "px; left: " + styleLeft + "px; width: " + styleWidth + "px; height: " + styleHeight + "px; cursor: " + styleCursor + "; " + styleAdditional) } function resizePlayerStyleToActualSize(h) { let t = h.getElementsByTagName("VIDEO"); if (t.length > 0) { styleWidth = t[0].videoWidth, styleHeight = t[0].videoHeight; let n = Math.floor((window.innerHeight - styleHeight) * .5), r = Math.floor((window.innerWidth - styleWidth) * .5); styleTop = n > 0 ? n : 0, styleLeft = r > 0 ? r : 0, h.style = "top: " + styleTop + "px; left: " + styleLeft + "px; width: " + styleWidth + "px; height: " + styleHeight + "px; cursor: " + styleCursor + "; " + styleAdditional } } function resizePlayerStyleToArbitrarySize(h) { h.getElementsByTagName("VIDEO"), h.style = "top: 0px; left: 0px; width: " + styleWidth + "px; height: " + styleHeight + "px; cursor: " + styleCursor + "; " + styleAdditional } function showFreezeFrameOverlay() { freezeFrame.valid && (freezeFrameOverlay.classList.add("freezeframeBackground"), freezeFrameOverlay.style.display = "block") } function invalidateFreezeFrameOverlay() { freezeFrameOverlay.style.display = "none", freezeFrame.valid = !1, freezeFrameOverlay.classList.remove("freezeframeBackground"), webRtcPlayerObj && webRtcPlayerObj.setVideoEnabled(!0) } function resizeFreezeFrameOverlay() { if (freezeFrame.width !== 0 && freezeFrame.height !== 0) { let h = 0, t = 0, n = 0, r = 0, l = document.getElementById("enlarge-display-to-fill-window-tgl"), a = document.getElementById("player"); if (l !== null && l.checked) { let g = window.innerWidth / window.innerHeight, _ = freezeFrame.width / freezeFrame.height; g < _ ? (h = window.innerWidth, t = Math.floor(window.innerWidth / _), n = Math.floor((window.innerHeight - t) * .5), r = 0) : (h = Math.floor(window.innerHeight * _), t = window.innerHeight, n = 0, r = Math.floor((window.innerWidth - h) * .5)) } else { let g = a.offsetWidth / a.offsetHeight, _ = freezeFrame.width / freezeFrame.height; g < _ ? (h = a.offsetWidth, t = Math.floor(a.offsetWidth / _), n = Math.floor((a.offsetHeight - t) * .5), r = 0) : (h = Math.floor(a.offsetHeight * _), t = a.offsetHeight, n = 0, r = Math.floor((a.offsetWidth - h) * .5)) } let e = document.getElementById("freezeFrameOverlay").childNodes[0]; freezeFrameOverlay.style.width = a.offsetWidth + "px", freezeFrameOverlay.style.height = a.offsetHeight + "px", freezeFrameOverlay.style.left = "0px", freezeFrameOverlay.style.top = "0px", e.style.width = h + "px", e.style.height = t + "px", e.style.left = r + "px", e.style.top = n + "px" } } function resizePlayerStyle(h) { let t = document.getElementById("player"); if (!t) return; if (updateVideoStreamSize(), t.classList.contains("fixed-size")) { setupMouseAndFreezeFrame(t); return } let n = document.getElementById("enlarge-display-to-fill-window-tgl"), r = window.innerWidth < t.videoWidth || window.innerHeight < t.videoHeight; n !== null ? n.checked || r ? resizePlayerStyleToFillWindow(t) : resizePlayerStyleToActualSize(t) : resizePlayerStyleToArbitrarySize(t), setupMouseAndFreezeFrame(t) } function setupMouseAndFreezeFrame(h) { h.getBoundingClientRect(), setupNormalizeAndQuantize(), resizeFreezeFrameOverlay() } function updateVideoStreamSize() { if (new Date().getTime() - lastTimeResized > 1e3) { if (!document.getElementById("player")) return; lastTimeResized = new Date().getTime() } else console.log("Resizing too often - skipping"), clearTimeout(resizeTimeout), resizeTimeout = setTimeout(updateVideoStreamSize, 1e3) } const MessageType = { IFrameRequest: 0, RequestQualityControl: 1, MaxFpsRequest: 2, AverageBitrateRequest: 3, StartStreaming: 4, StopStreaming: 5, LatencyTest: 6, RequestInitialSettings: 7, UIInteraction: 50, Command: 51, KeyDown: 60, KeyUp: 61, KeyPress: 62, MouseEnter: 70, MouseLeave: 71, MouseDown: 72, MouseUp: 73, MouseMove: 74, MouseWheel: 75, TouchStart: 80, TouchEnd: 81, TouchMove: 82, GamepadButtonPressed: 90, GamepadButtonReleased: 91, GamepadAnalog: 92 }; function emitDescriptor(h, t) { let n = JSON.stringify(t), r = new DataView(new ArrayBuffer(1 + 2 + 2 * n.length)), l = 0; r.setUint8(l, h), l++, r.setUint16(l, n.length, !0), l += 2; for (let a = 0; a < n.length; a++)r.setUint16(l, n.charCodeAt(a), !0), l += 2; sendInputData(r.buffer) } function emitUIInteraction(h) { emitDescriptor(MessageType.UIInteraction, h) } function setupNormalizeAndQuantize() { let h = document.getElementById("player"), t = h.getElementsByTagName("video"); h && t.length > 0 && (h.clientHeight / h.clientWidth, t[0].videoHeight / t[0].videoWidth) } function showOnScreenKeyboard(h) { if (h.showOnScreenKeyboard) { editTextButton.classList.remove("hiddenState"); let t = unquantizeAndDenormalizeUnsigned(h.x, h.y); editTextButton.style.top = t.y.toString() + "px", editTextButton.style.left = (t.x - 40).toString() + "px" } else editTextButton.classList.add("hiddenState"), hiddenInput.blur() } function start() { let h = document.getElementById("qualityStatus"); h && (h.className = "grey-status"); let t = document.getElementById("stats"); t && (t.innerHTML = "Not connected"), showConnectOverlay(), shouldShowPlayOverlay = !0, resizePlayerStyle(), updateKickButton(0) } function updateKickButton(h) { let t = document.getElementById("kick-other-players-button"); t && (t.value = `Kick (${h})`) } function get_text(h) { return String.fromCharCode.apply(null, new Uint8Array(h.slice(0, 5))) == "text:" ? new TextDecoder("utf-8").decode(new Uint8Array(h.slice(5))) : "" } function connect() { if (window.WebSocket = window.WebSocket || window.MozWebSocket, !window.WebSocket) { alert("Your browser doesn't support WebSocket"); return } console.log("webSocketUrl:", webSocketUrl), ws = new WebSocket(webSocketUrl), ws.binaryType = "arraybuffer", ws.onmessage = function (t) { let n = t.data; const r = new Uint8Array(t.data); r[0] === 116 && r[1] === 101 && r[2] === 120 && r[3] === 116 && (n = get_text(r)); let l = JSON.parse(n); l.type === "config" ? onConfig(l) : l.type === "playerCount" ? updateKickButton(l.count - 1) : l.type === "answer" ? onWebRtcAnswer(l) : l.type === "iceCandidate" && onWebRtcIce(l.candidate) }, ws.onerror = function (t) { console.log(`WS error: ${JSON.stringify(t)}`) }; let h = null; ws.onclose = function (t) { clearInterval(fiveMinuteTimer), clearTimeout(afk.warnTimer), clearInterval(afk.countdownTimer), ws = void 0; let n = document.getElementById("player"); webRtcPlayerObj && (n && n.removeChild(webRtcPlayerObj.video), webRtcPlayerObj.close(), webRtcPlayerObj = void 0), failCallback && failCallback(), h = setTimeout(start, 4e3), clearTimeout(h) } } function onConfig(h) { let t = document.getElementById("player"); setupWebRtcPlayer(t, h), resizePlayerStyle() } function close$1() { ws && ws.close() } function load(h) { h.successCallback && (successCallback = h.successCallback), h.failCallback && (failCallback = h.failCallback), h.totalTimeExpiredCallback && h.totalTimeExpiredCallback, h.interactiveTimeExpiredCallback && (interactiveTimeExpiredCallback = h.interactiveTimeExpiredCallback), h.webSocketUrl && (webSocketUrl = h.webSocketUrl), start() } function changeVol(h) { webRtcPlayerObj.video.volume = h, webRtcPlayerObj.changeVol(h) } let webrtc = { load, resizePlayerStyle, emitUIInteraction, close: close$1, changeVol }; const isPlat$1 = judgeEnvironment().includes("Chrome"); let pacemaker$1 = !1, websocket$1 = null, rtccanvas = null, digital3D = null, interval$1 = 5, videoWidth$1 = "", videoHeight$1 = "", reqRes$1 = null, emitter$1 = new Emitter$2; const lvCutInitStart = () => { const h = commonObj.scene == "1" || commonObj.scene == null || commonObj.sceneId >= 1e3 ? "" : "fragment-shader-nocut"; digital3D = querySelectorEl("#digital3DPlayer"), console.log("---digital3D", digital3D), digital3D.width = videoWidth$1, digital3D.height = videoHeight$1, webglCut.load(digital3D, null, rtccanvas, () => { webglCut.videoPlay() }, h), emitter$1.emit("init3d") }, checkCondition$1 = h => { "WebSocket" in window ? h(!0, "success") : h(!1, "当前浏览器不支持websocketio连接") }, loopConnect$1 = () => { uninstallEvent$1(!1), startPlayer$1() }, pageAcitveStatusGet$1 = () => { (() => { setTimeout(() => { interval$1 += 5, interval$1 > 30 && (interval$1 = 30), loopConnect$1() }, interval$1 * 1e3) })() }, uninstallEvent$1 = (h = !0) => { pacemaker$1 = h, heartPing.end(), close(), websocket$1 && (websocket$1.close(), websocket$1 = null) }, initWebSocket = h => { const t = h.ws(); websocket$1 = t, t.binaryType = "arraybuffer", t.onopen = h.cbOpen, t.onclose = h.cbClose, t.onmessage = h.cbMessage, t.onerror = h.cbError }; let asrWsApp$1 = null; const startPlayer$1 = () => { let { _sign: h, _projectId: t, _drivertype: n, _volume: r, _asr: l } = commonObj; initWebSocket({ cbOpen: function (a) { console.log("建立websocket", a), l && asrWsApp$1 && asrWsApp$1(websocket$1), heartPing.start(() => { (websocket$1 == null ? void 0 : websocket$1.readyState) == 1 && (websocket$1 == null || websocket$1.send(JSON.stringify({ signal: "ping" }))) }), pacemaker$1 = !1 }, cbMessage: isPlat$1 ? function (a) { if (typeof a.data == "object") new Uint8Array(a.data); else if (a.data != "ppg-end") { if (a.data.includes("requests overload")) pacemaker$1 = !0, emitter$1.emit("wsMessage", { type: "requests overload" }); else if (a.data.includes("{")) { const e = JSON.parse(a.data); e.type == "asr-part" ? emitter$1.emit("wsMessage", e) : e.type == "asr" ? e != null && e.resultType ? emitter$1.emit("wsMessage", e) : emitter$1.emit("videoStart") : e.type == "answer" ? emitter$1.emit("wsMessage", e) : e.type == "startAsr" ? (emitter$1.emit("videoEnd"), websocket$1 == null || websocket$1.send(SendMsg.startAsr())) : e.type == "startSleep" || e.type == "wakeup" || (e.type == "server_ready" ? (console.error("可以发送语音文件"), emitter$1.emit("wsMessage", e)) : e.type == "server_ended" || (e.type == "error" ? (emitter$1.emit("wsMessage", e), console.error(e.content)) : e.type == "node" || e.type == "server_url" && (console.log("2----------3d---到这里"), treeDOpen(`wss://${e.content}`)))) } } } : function (a) { const e = new Uint8Array(a.data); if (e[0] === 116 && e[1] === 101 && e[2] === 120 && e[3] === 116) { const g = get_text$1(e); if (g != "ppg-end") { if (g != "pong") { if (g.includes("requests overload")) pacemaker$1 = !0, emitter$1.emit("wsMessage", { type: "requests overload" }); else if (g.includes("{")) { const _ = JSON.parse(g); _.type == "asr-part" ? emitter$1.emit("wsMessage", _) : _.type == "asr" ? _ != null && _.resultType ? emitter$1.emit("wsMessage", _) : emitter$1.emit("videoStart") : _.type == "answer" ? emitter$1.emit("wsMessage", _) : _.type == "startAsr" ? emitter$1.emit("videoEnd") : _.type == "startSleep" || _.type == "wakeup" || (_.type == "server_ready" ? (console.error("可以发送语音文件"), emitter$1.emit("wsMessage", _)) : _.type == "server_ended" || (_.type == "error" ? (emitter$1.emit("wsMessage", _), console.error(_.content)) : _.type == "node" || _.type == "server_url" && (console.log("1----------3d---到这里"), treeDOpen(`wss://${_.content}`)))) } } } } }, cbError: function (a) { console.error("websocket错误:", a), emitter$1.emit("wsMessage", { type: "websocket Error", value: a }) }, cbClose: function (a) { console.error("websocket关闭:", a), pacemaker$1 ? emitter$1.emit("wsMessage", { type: "websocket close" }) : (pageAcitveStatusGet$1(), emitter$1.emit("wsMessage", { type: "websocket reLoop" })) }, ws: websocketInit$1({ _projectId: t, _sign: h, isPlat: isPlat$1, type: 1, _drivertype: n, requestVideo: requestVideo$1 }) }) }, treeDOpen = h => { setTimeout(() => { webrtc.load({ webSocketUrl: h, successCallback: t => { console.log("回调成功"), lvCutInitStart(); let n = setInterval(() => { (t == null ? void 0 : t.readyState) == 3 ? clearInterval(n) : t == null || t.send(JSON.stringify({ signal: "ping" })) }, 1e4) }, totalTimeExpiredCallback: t => { console.log("totalTimeExpiredCallback") }, interactiveTimeExpiredCallback: t => { console.log("interactiveTimeExpiredCallback") }, failCallback: t => { console.log("failCallback") } }) }) }, close = () => { webrtc.close() }; let requestVideo$1 = ""; function player$1(h, t, n, r, l = 1) { videoWidth$1 = viewMap[t][r].width, videoHeight$1 = viewMap[t][r].height, requestVideo$1 = `requestWidth=${videoWidth$1}&requestHeight=${videoHeight$1}`, document.querySelector(h).innerHTML = `
`, rtccanvas = querySelectorEl("#rtccanvas") } let xxPlayer$1 = class extends Emitter$2 { constructor({ environment: t, containerLable: n, token: r, projectId: l, quality: a, zoom: e, volume: g, asr: _ }, y) { if (super(), _) { const { asrDestroy: x, asrWsAppoint: E, asrStart: C } = asrWs(L => { console.log(L, "mic") }); asrWsApp$1 = E, C() } emitter$1 = new Emitter$2, this.containerLable = n, commonObj._sign = r, commonObj._projectId = l, this.quality = a || 1, this.zoom = e || 1, commonObj._env = t || "prd", commonObj._volume = g || 1, commonObj._asr = _ || !1, reqRes$1 = y } init() { checkCondition$1(t => { if (t) { let { avatarSilenceUrl: n, avatarDirection: r, scene: l } = reqRes$1.data, a = l; if (l.trim().startsWith("{")) { let e = JSON.parse(l); e.id && (a = e.id) } commonObj.scene = a == 1 || a >= 1e3 ? "1" : "2", player$1(this.containerLable, r, n, this.quality, this.zoom), emitter$1.on("videoEnd", () => { this.emit("message", { type: "videoEnd", data: {} }) }), emitter$1.on("videoStart", () => { this.emit("message", { type: "videoStart", data: {} }) }), emitter$1.on("wsMessage", e => { this.emit("message", { type: "wsMessage", data: e }) }), emitter$1.on("init3d", e => { this.emit("intialSucccess", { type: "2" }) }), this.emit("intialSucccess", { type: "1" }) } else this.emit("intialError", msg) }) } playSilentvideo() { const t = document.querySelector("#digital3DPlayer"); return t == null ? void 0 : t.play() } startPlay() { startPlayer$1() } setClientId(t) { t ? commonObj._clientId = t : console.log("clientId不能为空") } stopPlay() { uninstallEvent$1(), emitter$1 = null, rtccanvas = null, digital3D = null, reqRes$1 = null } playQA(t, n) { websocket$1 == null || websocket$1.send(SendMsg.qa(t, n)) } interrupt() { websocket$1 == null || websocket$1.send(SendMsg.interrupt()) } playText(t) { websocket$1 == null || websocket$1.send(SendMsg.text(t)) } playStreamText(t) { websocket$1 == null || websocket$1.send(SendMsg.streamText(t)) } playStreamTextStart(t, n) { websocket$1 == null || websocket$1.send(SendMsg.streamTextStart(t, n)) } playStreamTextEnd() { websocket$1 == null || websocket$1.send(SendMsg.streamTextEnd()) } playAudio(t) { websocket$1 == null || websocket$1.send(SendMsg.streamAudio(t)) } playAudioEnd() { websocket$1 == null || websocket$1.send(SendMsg.streamAudioEnd()) } playCurVideo() { websocket$1 == null || websocket$1.send(SendMsg.resumePlay()) } stopCurVideo() { websocket$1 == null || websocket$1.send(SendMsg.pausePlay()) } }; const websocketInit = (h, t, n, r) => { h && !h.includes("ws") && (h = `${h.includes("https") ? "wss:" : "ws:"}//${h.split("//")[1]}`); let l = `${h || "wss://wenyan-avatar.mobvoi.com"}/websocket/wenyan/asr/${n}?projectId=${t}&holdTalk=1`, a = new WebSocket(l); return a.binaryType = "arraybuffer", a.onopen = function (e) { console.log("客户端连接成功"), a.send(JSON.stringify({ signal: "start" })) }, a.onmessage = function (e) { const g = e.data ? JSON.parse(e.data) : {}; r(g), g.type == "asr" && a.close() }, a.onerror = function (e) { console.log("连接失败了", e) }, a.onclose = function () { a = null }, a }, micro = (h, t) => { if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { let { recStart: n, recStop: r, recRecord: l } = jsRecorder(function (a) { h(a) }, () => { t({ type: "1", val: "获取麦克权限成功" }) }, () => { t({ type: "0", val: "获取麦克权限失败" }) }); return { recStart: n, recStop: r, recRecord: l } } else t({ type: "0", val: "环境不支持!" }) }; function asrPlayer({ host: h, _projectId: t, token: n, cb: r }) { if (!t || !n) { r({ type: "error", value: "参数缺失" }); return } let l = null, a = !1; const { recStart: e, recStop: g, recRecord: _ } = micro(function (A) { try { (l == null ? void 0 : l.readyState) == 1 && l.send(A) } catch (I) { console.log(I) } }, function (A) { A.type == "1" && r(A) }) || {}; return { asrStart: () => { if (e) { if (a) return r({ type: "0", val: "请先stop" }); a = !0, e(), l = websocketInit(h, t, n, A => { r(A) }) } }, asrStop: () => { if (g) { if (!a) return r({ type: "0", val: "请误重复stop" }); a = !1, l.send(JSON.stringify({ signal: "end" })), g() } }, asrSignStart: () => { l.send(JSON.stringify({ signal: "start" })) }, asrSignEnd: () => { l.send(JSON.stringify({ signal: "end" })) }, asrDestroy: () => { l && l.close(), l = null, console.log("ws 关闭") } } } class Emitter { on(t, n, r) { const l = this.e || (this.e = {}); return (l[t] || (l[t] = [])).push({ fn: n, ctx: r }), this } once(t, n, r) { const l = this; function a(...e) { l.off(t, a), n.apply(r, e) } return a._ = n, this.on(t, a, r) } emit(t, ...n) { const r = ((this.e || (this.e = {}))[t] || []).slice(); for (let l = 0; l < r.length; l += 1)r[l].fn.apply(r[l].ctx, n); return this } off(t, n) { const r = this.e || (this.e = {}), l = r[t], a = []; if (l && n) for (let e = 0, g = l.length; e < g; e += 1)l[e].fn !== n && l[e].fn._ !== n && a.push(l[e]); return a.length ? r[t] = a : delete r[t], this } } function getNowTime() { return performance && typeof performance.now == "function" ? performance.now() : Date.now() } const PCMPlayer = function () { function h(t) { this.init(t) } return h.prototype.init = function (t) { var n = { encoding: "16bitInt", channels: 1, sampleRate: 16e3, flushingTime: 240 }; this.option = Object.assign({}, n, t), this.samples = new Float32Array, this.flush = this.flush.bind(this), this.interval = setInterval(this.flush, this.option.flushingTime), this.maxValue = this.getMaxValue(), this.typedArray = this.getTypedArray(), this.createContext() }, h.prototype.getMaxValue = function () { var t = { "8bitInt": 128, "16bitInt": 32768, "32bitInt": 2147483648, "32bitFloat": 1 }; return t[this.option.encoding] ? t[this.option.encoding] : t["16bitInt"] }, h.prototype.getTypedArray = function () { var t = { "8bitInt": Int8Array, "16bitInt": Int16Array, "32bitInt": Int32Array, "32bitFloat": Float32Array }; return t[this.option.encoding] ? t[this.option.encoding] : t["16bitInt"] }, h.prototype.createContext = function () { this.audioCtx = new (window.AudioContext || window.webkitAudioContext), this.gainNode = this.audioCtx.createGain(), this.gainNode.gain.value = 1, this.gainNode.connect(this.audioCtx.destination), this.startTime = this.audioCtx.currentTime }, h.prototype.isTypedArray = function (t) { return t.byteLength && t.buffer && t.buffer.constructor == ArrayBuffer }, h.prototype.feed = function (t) { if (this.isTypedArray(t)) { t = this.getFormatedValue(t); var n = new Float32Array(this.samples.length + t.length); n.set(this.samples, 0), n.set(t, this.samples.length), this.samples = n } }, h.prototype.getFormatedValue = function (n) { var n = new this.typedArray(n.buffer), r = new Float32Array(n.length), l; for (l = 0; l < n.length; l++)r[l] = n[l] / this.maxValue; return r }, h.prototype.volume = function (t) { this.gainNode.gain.value = t }, h.prototype.destroy = function () { this.interval && clearInterval(this.interval), this.samples = null, this.audioCtx.close(), this.audioCtx = null }, h.prototype.flush = function () { if (this.samples.length) { var t = this.audioCtx.createBufferSource(), n = this.samples.length / this.option.channels, r = this.audioCtx.createBuffer(this.option.channels, n, this.option.sampleRate), l, a, e, g, _; for (a = 0; a < this.option.channels; a++)for (l = r.getChannelData(a), e = a, _ = 50, g = 0; g < n; g++)l[g] = this.samples[e], g < 50 && (l[g] = l[g] * g / 50), g >= n - 51 && (l[g] = l[g] * _-- / 50), e += this.option.channels; this.startTime < this.audioCtx.currentTime && (this.startTime = this.audioCtx.currentTime), t.buffer = r, t.connect(this.gainNode), t.start(this.startTime), this.startTime += r.duration, this.samples = new Float32Array } }, h.prototype.getTimestamp = function () { return this.audioCtx ? this.audioCtx.currentTime : 0 }, h.prototype.play = function (t) { if (this.isTypedArray(t) && (t = this.getFormatedValue(t), !!t.length)) { var n = this.audioCtx.createBufferSource(), r = t.length / this.option.channels, l = this.audioCtx.createBuffer(this.option.channels, r, this.option.sampleRate), a, e, g, _, y; for (e = 0; e < this.option.channels; e++)for (a = l.getChannelData(e), g = e, y = 50, _ = 0; _ < r; _++)a[_] = t[g], _ < 50 && (a[_] = a[_] * _ / 50), _ >= r - 51 && (a[_] = a[_] * y-- / 50), g += this.option.channels; this.startTime < this.audioCtx.currentTime && (this.startTime = this.audioCtx.currentTime), n.buffer = l, n.connect(this.gainNode), n.start(this.startTime), n.onended = () => { this.option.endCallback() }, this.startTime += l.duration } }, h.prototype.pause = function () { this.audioCtx.state === "running" && this.audioCtx.suspend() }, h.prototype.resume = function () { this.audioCtx.state === "suspended" && this.audioCtx.resume() }, h }(); class AudioPlayer { constructor(t) { const { flv: n } = t; this.playing = !1, this.audioPts = [], this.outAudioIndex = 0, this.inputAudioIndex = 0, this.volume = n.options.volume, this.audioCtrl = new PCMPlayer({ encoding: "16bitInt", channels: 1, sampleRate: 16e3, endCallback: () => { this.playing = !1 } }), this.audioCtrl.volume(this.volume), n.on("audioData", (r, l) => { this.outAudioIndex++, this.audioCtrl.feed(r), this.audioPts.push({ pts: l }) }), n.on("destroy", () => { this.audioPts = [], this.audioCtrl.destroy() }), n.on("timeupdate", r => { const l = this.audioPts[0].pts; l && r > l && this.feed(0) }) } get decoding() { return this.outAudioIndex !== this.inputAudioIndex } get framePlay() { return this.audioPts.length > 0 && this.playing } get getTimestamp() { var t; return (t = this.audioCtrl) == null ? void 0 : t.getTimestamp() } feed(t) { if (this.inputAudioIndex++, !this.audioPts[t]) return !1; this.audioPts.shift() } play() { this.audioPts.length > 0 ? (this.playing = !0, this.audioCtrl.resume()) : this.playing = !1 } reset() { this.playing = !1, this.audioCtrl.destroy(), this.audioCtrl = new PCMPlayer({ encoding: "16bitInt", channels: 1, sampleRate: 16e3, endCallback: () => { this.playing = !1 } }), this.audioCtrl.volume(this.volume), this.audioPts = [], this.outAudioIndex = 0, this.inputAudioIndex = 0 } stop() { this.playing = !1, this.audioCtrl.pause() } resume() { this.playing = !0, this.audioCtrl.resume() } } class Play { constructor(t) { this.flv = t, this.streaming = !1, this.ended = !0, this.animationFrameTimer = null, this.audioDecoder = new AudioPlayer(this), this.sign = 0, this.resultSign = 0, this.playerStatus = "", this.currentTime = 0, this.lastUpdateTime = 0, t.on("destroy", () => { this.waitingTimer && clearTimeout(this.waitingTimer), this.waitingTimer = null, this.animationFrameTimer && cancelAnimationFrame(this.animationFrameTimer), this.animationFrameTimer = null, this.ended = !0 }), t.on("streaming", () => { this.streaming = !0 }), t.on("streamEnd", () => { this.streaming = !1, this.waitingTimer && clearTimeout(this.waitingTimer), this.waitingTimer = null }) } init() { this.waitingTimer && clearTimeout(this.waitingTimer), this.waitingTimer = null, this.currentTime = 0, this.lastUpdateTime = 0, this.animationFrame(), this.ended = !1 } animationFrame() { this.animationFrameTimer = requestAnimationFrame(() => { if (this.audioDecoder.framePlay) { this.flv.stearmPtsH || (this.flv.stearmPtsH = !0, this.currentTime = 0, this.flv.options.canPlay()); const t = getNowTime(); this.currentTime += t - this.lastUpdateTime, this.lastUpdateTime = t, this.flv.emit("timeupdate", this.currentTime) } else if (this.streaming || this.audioDecoder.decoding) { this.audioDecoder.stop(), this.waitingTimer = setTimeout(() => { this.lastUpdateTime = getNowTime(), this.play(), this.audioDecoder.framePlay ? this.playerStatus != "canplay" && (this.playerStatus = "canplay", this.flv.options.canPlay(), this.flv.stearmPtsH = !0) : this.playerStatus != "waiting" && (this.playerStatus = "waiting", this.flv.options.waiting()) }, 200); return } this.animationFrame() }) } play() { this.audioDecoder.play(), this.animationFrame() } restart() { this.audioDecoder.reset(), this.currentTime = 0, this.lastUpdateTime = 0, this.playerStatus = "" } continue() { this.lastUpdateTime = getNowTime(), this.audioDecoder.resume(), this.animationFrame() } stop() { this.audioDecoder.stop(), this.waitingTimer && clearTimeout(this.waitingTimer), this.waitingTimer = null, this.animationFrameTimer && cancelAnimationFrame(this.animationFrameTimer), this.animationFrameTimer = null } } class flvStearmLoad extends Emitter { constructor(t) { super(), this.options = Object.assign({ url: "", volume: 1, ...t }), this.audioTimestamp = 0, this.init(), this.stearmPtsH = !1 } init() { this.options.webcodeDisabled && (window.VideoDecoder = !1), this.player = new Play(this), this.stearmInit(), this.player.init(), this.audioTimestamp = 0 } stearmInit() { const t = this; this.socket = new WebSocket(this.options.url), this.socket.binaryType = "arraybuffer", this.socket.onopen = () => { t.options.cbOpen(t.socket), t.emit("streamStart") }, this.socket.onmessage = n => { t.options.cbMessage(t.socket, n, function (r, l) { if (r.byteLength == 1) { t.options.wxServerEnd(); return } t.emit("streaming"), r[0] === 80 && r[1] === 67 && r[2] === 77 && (t.audioTimestamp += 40, t.emit("audioData", r.slice(3), t.audioTimestamp)) }) }, this.socket.onerror = n => { throw t.options.cbError(t.socket, n), t.emit("streamError", n), n }, this.socket.onclose = () => { this.stearmPtsH = !1, t.options.cbClose(t.socket), t.emit("streamEnd") }, console.log(this.options.url) } destroy() { this.emit("destroy") } restart() { console.error("restart"), this.audioTimestamp = 0, this.stearmPtsH = !1, this.player.restart() } changeVolume(t) { t ? this.player.audioDecoder.audioCtrl.volume(0) : this.player.audioDecoder.audioCtrl.volume(this.options.volume) } } const isPlat = judgeEnvironment().includes("Chrome"); let cartoonPlayer = null, pacemaker = !1, websocket = null, videoPlayerInit = !1, interval = 5, screenCanvas = null, avatarVideo = null, silentVideo = null, videoWidth = "", videoHeight = "", reqRes = null, emitter = new Emitter$2; const checkCondition = h => { "WebSocket" in window ? h(!0, "success") : h(!1, "当前浏览器不支持websocketio连接") }, webReconnect = (h = !1) => { videoPlayerInit = !0, cartoonPlayer.restart() }, loopConnect = () => { uninstallEvent(!1), startPlayer() }, pageAcitveStatusGet = () => { (() => { setTimeout(() => { interval += 5, interval > 30 && (interval = 30), loopConnect() }, interval * 1e3) })() }, uninstallEvent = (h = !0) => { pacemaker = h, videoPlayerInit = !1, heartPing.end(), cartoonPlayer && (cartoonPlayer == null || cartoonPlayer.destroy(), cartoonPlayer = null), websocket && (websocket.close(), websocket = null) }; let asrWsApp = null; const startPlayer = () => { let { _sign: h, _projectId: t, _drivertype: n, _volume: r, _asr: l } = commonObj; cartoonPlayer = new flvStearmLoad({ url: websocketInit$1({ _projectId: t, _sign: h, isPlat, type: 0, _drivertype: n, requestVideo }), volume: r, cbOpen: function (a) { console.error("建立websocket", a), websocket = a, l && asrWsApp && asrWsApp(a), heartPing.start(() => { (websocket == null ? void 0 : websocket.readyState) == 1 && (websocket == null || websocket.send(JSON.stringify({ signal: "ping" }))) }) }, cbMessage: isPlat ? function (a, e, g) { if (typeof e.data == "object") { const _ = new Uint8Array(e.data); _[0] !== 72 || _[1] !== 80 || _[2] !== 67 || _[3] !== 77 || (videoPlayerInit = !1, console.log("——————————loop new——————————————")), g(_, videoPlayerInit) } else if (e.data != "ppg-end") { if (e.data.includes("requests overload")) pacemaker = !0, emitter.emit("wsMessage", { type: "requests overload" }); else if (e.data.includes("{")) { const _ = JSON.parse(e.data); _.type == "asr-part" || _.type == "asr" || _.type == "answer" ? emitter.emit("wsMessage", _) : _.type == "startAsr" || _.type == "startSleep" || _.type == "wakeup" || (_.type == "server_ready" ? (console.error("可以发送语音文件"), emitter.emit("wsMessage", _)) : _.type == "server_ended" || _.type == "error" && emitter.emit("wsMessage", _)) } } } : function (a, e, g) { const _ = new Uint8Array(e.data); if (_[0] === 116 && _[1] === 101 && _[2] === 120 && _[3] === 116) { const y = get_text$1(_); if (console.log(y, "string"), y != "ppg-end") { if (y != "pong") { if (y.includes("requests overload")) pacemaker = !0, emitter.emit("wsMessage", { type: "requests overload" }); else if (y.includes("{")) { const x = JSON.parse(y); x.type == "asr-part" || x.type == "asr" || x.type == "answer" ? emitter.emit("wsMessage", x) : x.type == "startAsr" || x.type == "startSleep" || x.type == "wakeup" || (x.type == "server_ready" ? (console.error("可以发送语音文件"), emitter.emit("wsMessage", x)) : x.type == "server_ended" || x.type == "error" && emitter.emit("wsMessage", x)) } } } } else _[0] !== 72 || _[1] !== 80 || _[2] !== 67 || _[3] !== 77 || (videoPlayerInit = !1, console.log("——————————loop new——————————————")), g(_, videoPlayerInit) }, cbError: function (a, e) { console.error("websocket错误:", e), pacemaker = !0, heartPing.end() }, cbClose: function (a) { console.error("websocket关闭!"), pacemaker || pageAcitveStatusGet() }, wxServerEnd: function () { }, canPlay: function () { webglCut.videoPlay(), emitter.emit("videoStart"), this.streamImg = !0 }, waiting: function () { webglCut.slicePlay(), emitter.emit("videoEnd"), this.streamImg = !1, websocket == null || websocket.send(SendMsg.startAsr()) } }) }; function displayEle(h, t) { h.style.display = t } let requestVideo = ""; function player(h, t, n, r, l, a = 1) { videoWidth = viewMap[t][l].width, videoHeight = viewMap[t][l].height, requestVideo = `requestWidth=${videoWidth}&requestHeight=${videoHeight}`, document.querySelector(h).innerHTML = ` `, screenCanvas = querySelectorEl("#screenPlayer"), avatarVideo = querySelectorEl("#avatarVideo"), silentVideo = querySelectorEl("#silentVideo"), displayEle(silentVideo, "none"), displayEle(avatarVideo, "none") } class xxPlayer extends Emitter$2 { constructor({ environment: t, containerLable: n, token: r, projectId: l, quality: a, zoom: e, clientId: g, volume: _, asr: y }, x) { if (super(), y) { const { asrDestroy: E, asrWsAppoint: C, asrStart: L } = asrWs(A => { console.log(A, "mic") }); asrWsApp = C, L() } emitter = new Emitter$2, this.containerLable = n, commonObj._sign = r, commonObj._projectId = l, this.quality = a || 1, this.zoom = e || 1, commonObj._env = t || "prd", commonObj._volume = _ || 1, commonObj._asr = y || !1, reqRes = x, this.streamImg = !1 } init() { checkCondition(t => { if (t) { let { avatarSilenceUrl: n, avatarDirection: r, avatarChatUrl: l } = reqRes.data; player(this.containerLable, r, n, l, this.quality, this.zoom), emitter.on("videoEnd", () => { this.emit("message", { type: "videoEnd", data: {} }) }), emitter.on("videoStart", () => { this.emit("message", { type: "videoStart", data: {} }) }), emitter.on("wsMessage", a => { this.emit("message", { type: "wsMessage", data: a }) }), emitter.on("initCartoon", () => { this.emit("intialSucccess", { type: "2" }) }), this.emit("intialSucccess", { type: "1" }) } else this.emit("intialError", msg) }) } playSilentvideo() { silentVideo && silentVideo.play().then(t => { console.log("ffm交互静音视频播放") }).catch(t => { console.log("ffm交互静音视频播放失败-", t) }), avatarVideo && avatarVideo.play().then(t => { console.log("ffm交互静音视频播放") }).catch(t => { console.log("ffm交互静音视频播放失败-", t) }) } startPlay() { webglCut.load(avatarVideo, silentVideo, screenCanvas, t => { videoPlayerInit = !0, webglCut.slicePlay(), startPlayer(this.direction, this.quality), emitter.emit("initCartoon") }, isPlat ? "fragment-shader-nocut" : "") } setClientId(t) { t ? commonObj._clientId = t : console.log("clientId不能为空") } stopPlay() { uninstallEvent(), emitter = null, screenCanvas = null, avatarVideo = null, silentVideo = null, videoWidth = "", videoHeight = "", reqRes = null, asrWsApp = null, this.streamImg = !1 } playQA(t, n) { this.streamImg = !0, webglCut.slicePlay(), webReconnect(), websocket == null || websocket.send(SendMsg.qa(t, n)) } interrupt() { websocket == null || websocket.send(SendMsg.interrupt()), webglCut.slicePlay(), webReconnect(!0), this.streamImg = !1 } playText(t) { websocket == null || websocket.send(SendMsg.text(t)) } playStreamText(t) { websocket == null || websocket.send(SendMsg.streamText(t)) } playStreamTextStart(t, n) { websocket == null || websocket.send(SendMsg.streamTextStart(t, n)), this.streamImg = !0 } playStreamTextEnd() { websocket == null || websocket.send(SendMsg.streamTextEnd()) } playAudio(t) { websocket == null || websocket.send(SendMsg.streamAudio(t)), this.streamImg = !0 } playAudioEnd() { websocket == null || websocket.send(SendMsg.streamAudioEnd()) } playCurVideo() { this.streamImg && (websocket == null || websocket.send(SendMsg.resumePlay()), webglCut.videoPlay(), cartoonPlayer.player.continue()) } stopCurVideo() { this.streamImg && (websocket == null || websocket.send(SendMsg.pausePlay()), cartoonPlayer.player.stop(), webglCut.slicePlay()) } } var vconsole_min = { exports: {} };/*! * vConsole v3.15.1 (https://github.com/Tencent/vConsole) * * Tencent is pleased to support the open source community by making vConsole available. * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */(function (module, exports) { (function (h, t) { module.exports = t() })(commonjsGlobal || self, function () { return function () { var __webpack_modules__ = { 4264: function (h, t, n) { h.exports = n(7588) }, 5036: function (h, t, n) { n(1719), n(5677), n(6394), n(5334), n(6969), n(2021), n(8328), n(2129); var r = n(1287); h.exports = r.Promise }, 2582: function (h, t, n) { n(1646), n(6394), n(2004), n(462), n(8407), n(2429), n(1172), n(8288), n(1274), n(8201), n(6626), n(3211), n(9952), n(15), n(9831), n(7521), n(2972), n(6956), n(5222), n(2257); var r = n(1287); h.exports = r.Symbol }, 8257: function (h, t, n) { var r = n(7583), l = n(9212), a = n(5637), e = r.TypeError; h.exports = function (g) { if (l(g)) return g; throw e(a(g) + " is not a function") } }, 1186: function (h, t, n) { var r = n(7583), l = n(2097), a = n(5637), e = r.TypeError; h.exports = function (g) { if (l(g)) return g; throw e(a(g) + " is not a constructor") } }, 9882: function (h, t, n) { var r = n(7583), l = n(9212), a = r.String, e = r.TypeError; h.exports = function (g) { if (typeof g == "object" || l(g)) return g; throw e("Can't set " + a(g) + " as a prototype") } }, 6288: function (h, t, n) { var r = n(3649), l = n(3590), a = n(4615), e = r("unscopables"), g = Array.prototype; g[e] == null && a.f(g, e, { configurable: !0, value: l(null) }), h.exports = function (_) { g[e][_] = !0 } }, 4761: function (h, t, n) { var r = n(7583), l = n(2447), a = r.TypeError; h.exports = function (e, g) { if (l(g, e)) return e; throw a("Incorrect invocation") } }, 2569: function (h, t, n) { var r = n(7583), l = n(794), a = r.String, e = r.TypeError; h.exports = function (g) { if (l(g)) return g; throw e(a(g) + " is not an object") } }, 5766: function (h, t, n) { var r = n(2977), l = n(6782), a = n(1825), e = function (g) { return function (_, y, x) { var E, C = r(_), L = a(C), A = l(x, L); if (g && y != y) { for (; L > A;)if ((E = C[A++]) != E) return !0 } else for (; L > A; A++)if ((g || A in C) && C[A] === y) return g || A || 0; return !g && -1 } }; h.exports = { includes: e(!0), indexOf: e(!1) } }, 4805: function (h, t, n) { var r = n(2938), l = n(7386), a = n(5044), e = n(1324), g = n(1825), _ = n(4822), y = l([].push), x = function (E) { var C = E == 1, L = E == 2, A = E == 3, I = E == 4, D = E == 6, w = E == 7, S = E == 5 || D; return function (O, F, j, P) { for (var $, V, q = e(O), ee = a(q), re = r(F, j), ye = g(ee), ce = 0, Q = P || _, se = C ? Q(O, ye) : L || w ? Q(O, 0) : void 0; ye > ce; ce++)if ((S || ce in ee) && (V = re($ = ee[ce], ce, q), E)) if (C) se[ce] = V; else if (V) switch (E) { case 3: return !0; case 5: return $; case 6: return ce; case 2: y(se, $) } else switch (E) { case 4: return !1; case 7: y(se, $) }return D ? -1 : A || I ? I : se } }; h.exports = { forEach: x(0), map: x(1), filter: x(2), some: x(3), every: x(4), find: x(5), findIndex: x(6), filterReject: x(7) } }, 9269: function (h, t, n) { var r = n(6544), l = n(3649), a = n(4061), e = l("species"); h.exports = function (g) { return a >= 51 || !r(function () { var _ = []; return (_.constructor = {})[e] = function () { return { foo: 1 } }, _[g](Boolean).foo !== 1 }) } }, 4546: function (h, t, n) { var r = n(7583), l = n(6782), a = n(1825), e = n(5999), g = r.Array, _ = Math.max; h.exports = function (y, x, E) { for (var C = a(y), L = l(x, C), A = l(E === void 0 ? C : E, C), I = g(_(A - L, 0)), D = 0; L < A; L++, D++)e(I, D, y[L]); return I.length = D, I } }, 6917: function (h, t, n) { var r = n(7386); h.exports = r([].slice) }, 5289: function (h, t, n) { var r = n(7583), l = n(4521), a = n(2097), e = n(794), g = n(3649)("species"), _ = r.Array; h.exports = function (y) { var x; return l(y) && (x = y.constructor, (a(x) && (x === _ || l(x.prototype)) || e(x) && (x = x[g]) === null) && (x = void 0)), x === void 0 ? _ : x } }, 4822: function (h, t, n) { var r = n(5289); h.exports = function (l, a) { return new (r(l))(a === 0 ? 0 : a) } }, 3616: function (h, t, n) { var r = n(3649)("iterator"), l = !1; try { var a = 0, e = { next: function () { return { done: !!a++ } }, return: function () { l = !0 } }; e[r] = function () { return this }, Array.from(e, function () { throw 2 }) } catch { } h.exports = function (g, _) { if (!_ && !l) return !1; var y = !1; try { var x = {}; x[r] = function () { return { next: function () { return { done: y = !0 } } } }, g(x) } catch { } return y } }, 9624: function (h, t, n) { var r = n(7386), l = r({}.toString), a = r("".slice); h.exports = function (e) { return a(l(e), 8, -1) } }, 3058: function (h, t, n) { var r = n(7583), l = n(8191), a = n(9212), e = n(9624), g = n(3649)("toStringTag"), _ = r.Object, y = e(function () { return arguments }()) == "Arguments"; h.exports = l ? e : function (x) { var E, C, L; return x === void 0 ? "Undefined" : x === null ? "Null" : typeof (C = function (A, I) { try { return A[I] } catch { } }(E = _(x), g)) == "string" ? C : y ? e(E) : (L = e(E)) == "Object" && a(E.callee) ? "Arguments" : L } }, 1509: function (h, t, n) { var r = n(7386)("".replace), l = String(Error("zxcasd").stack), a = /\n\s*at [^:]*:[^\n]*/, e = a.test(l); h.exports = function (g, _) { if (e && typeof g == "string") for (; _--;)g = r(g, a, ""); return g } }, 3478: function (h, t, n) { var r = n(2870), l = n(929), a = n(6683), e = n(4615); h.exports = function (g, _, y) { for (var x = l(_), E = e.f, C = a.f, L = 0; L < x.length; L++) { var A = x[L]; r(g, A) || y && r(y, A) || E(g, A, C(_, A)) } } }, 926: function (h, t, n) { var r = n(6544); h.exports = !r(function () { function l() { } return l.prototype.constructor = null, Object.getPrototypeOf(new l) !== l.prototype }) }, 4683: function (h, t, n) { var r = n(2365).IteratorPrototype, l = n(3590), a = n(4677), e = n(8821), g = n(339), _ = function () { return this }; h.exports = function (y, x, E, C) { var L = x + " Iterator"; return y.prototype = l(r, { next: a(+!C, E) }), e(y, L, !1, !0), g[L] = _, y } }, 57: function (h, t, n) { var r = n(8494), l = n(4615), a = n(4677); h.exports = r ? function (e, g, _) { return l.f(e, g, a(1, _)) } : function (e, g, _) { return e[g] = _, e } }, 4677: function (h) { h.exports = function (t, n) { return { enumerable: !(1 & t), configurable: !(2 & t), writable: !(4 & t), value: n } } }, 5999: function (h, t, n) { var r = n(8734), l = n(4615), a = n(4677); h.exports = function (e, g, _) { var y = r(g); y in e ? l.f(e, y, a(0, _)) : e[y] = _ } }, 9012: function (h, t, n) { var r = n(7263), l = n(8262), a = n(6268), e = n(4340), g = n(9212), _ = n(4683), y = n(729), x = n(7496), E = n(8821), C = n(57), L = n(1270), A = n(3649), I = n(339), D = n(2365), w = e.PROPER, S = e.CONFIGURABLE, O = D.IteratorPrototype, F = D.BUGGY_SAFARI_ITERATORS, j = A("iterator"), P = "keys", $ = "values", V = "entries", q = function () { return this }; h.exports = function (ee, re, ye, ce, Q, se, fe) { _(ye, re, ce); var G, K, de, ve = function (Oe) { if (Oe === Q && ne) return ne; if (!F && Oe in U) return U[Oe]; switch (Oe) { case P: case $: case V: return function () { return new ye(this, Oe) } }return function () { return new ye(this) } }, ae = re + " Iterator", J = !1, U = ee.prototype, X = U[j] || U["@@iterator"] || Q && U[Q], ne = !F && X || ve(Q), we = re == "Array" && U.entries || X; if (we && (G = y(we.call(new ee))) !== Object.prototype && G.next && (a || y(G) === O || (x ? x(G, O) : g(G[j]) || L(G, j, q)), E(G, ae, !0, !0), a && (I[ae] = q)), w && Q == $ && X && X.name !== $ && (!a && S ? C(U, "name", $) : (J = !0, ne = function () { return l(X, this) })), Q) if (K = { values: ve($), keys: se ? ne : ve(P), entries: ve(V) }, fe) for (de in K) (F || J || !(de in U)) && L(U, de, K[de]); else r({ target: re, proto: !0, forced: F || J }, K); return a && !fe || U[j] === ne || L(U, j, ne, { name: Q }), I[re] = ne, K } }, 2219: function (h, t, n) { var r = n(1287), l = n(2870), a = n(491), e = n(4615).f; h.exports = function (g) { var _ = r.Symbol || (r.Symbol = {}); l(_, g) || e(_, g, { value: a.f(g) }) } }, 8494: function (h, t, n) { var r = n(6544); h.exports = !r(function () { return Object.defineProperty({}, 1, { get: function () { return 7 } })[1] != 7 }) }, 6668: function (h, t, n) { var r = n(7583), l = n(794), a = r.document, e = l(a) && l(a.createElement); h.exports = function (g) { return e ? a.createElement(g) : {} } }, 6778: function (h) { h.exports = { CSSRuleList: 0, CSSStyleDeclaration: 0, CSSValueList: 0, ClientRectList: 0, DOMRectList: 0, DOMStringList: 0, DOMTokenList: 1, DataTransferItemList: 0, FileList: 0, HTMLAllCollection: 0, HTMLCollection: 0, HTMLFormElement: 0, HTMLSelectElement: 0, MediaList: 0, MimeTypeArray: 0, NamedNodeMap: 0, NodeList: 1, PaintRequestList: 0, Plugin: 0, PluginArray: 0, SVGLengthList: 0, SVGNumberList: 0, SVGPathSegList: 0, SVGPointList: 0, SVGStringList: 0, SVGTransformList: 0, SourceBufferList: 0, StyleSheetList: 0, TextTrackCueList: 0, TextTrackList: 0, TouchList: 0 } }, 9307: function (h, t, n) { var r = n(6668)("span").classList, l = r && r.constructor && r.constructor.prototype; h.exports = l === Object.prototype ? void 0 : l }, 2274: function (h) { h.exports = typeof window == "object" }, 3256: function (h, t, n) { var r = n(6918), l = n(7583); h.exports = /ipad|iphone|ipod/i.test(r) && l.Pebble !== void 0 }, 7020: function (h, t, n) { var r = n(6918); h.exports = /(?:ipad|iphone|ipod).*applewebkit/i.test(r) }, 5354: function (h, t, n) { var r = n(9624), l = n(7583); h.exports = r(l.process) == "process" }, 6846: function (h, t, n) { var r = n(6918); h.exports = /web0s(?!.*chrome)/i.test(r) }, 6918: function (h, t, n) { var r = n(5897); h.exports = r("navigator", "userAgent") || "" }, 4061: function (h, t, n) { var r, l, a = n(7583), e = n(6918), g = a.process, _ = a.Deno, y = g && g.versions || _ && _.version, x = y && y.v8; x && (l = (r = x.split("."))[0] > 0 && r[0] < 4 ? 1 : +(r[0] + r[1])), !l && e && (!(r = e.match(/Edge\/(\d+)/)) || r[1] >= 74) && (r = e.match(/Chrome\/(\d+)/)) && (l = +r[1]), h.exports = l }, 5690: function (h) { h.exports = ["constructor", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "toLocaleString", "toString", "valueOf"] }, 1178: function (h, t, n) { var r = n(6544), l = n(4677); h.exports = !r(function () { var a = Error("a"); return !("stack" in a) || (Object.defineProperty(a, "stack", l(1, 7)), a.stack !== 7) }) }, 7263: function (h, t, n) { var r = n(7583), l = n(6683).f, a = n(57), e = n(1270), g = n(460), _ = n(3478), y = n(4451); h.exports = function (x, E) { var C, L, A, I, D, w = x.target, S = x.global, O = x.stat; if (C = S ? r : O ? r[w] || g(w, {}) : (r[w] || {}).prototype) for (L in E) { if (I = E[L], A = x.noTargetGet ? (D = l(C, L)) && D.value : C[L], !y(S ? L : w + (O ? "." : "#") + L, x.forced) && A !== void 0) { if (typeof I == typeof A) continue; _(I, A) } (x.sham || A && A.sham) && a(I, "sham", !0), e(C, L, I, x) } } }, 6544: function (h) { h.exports = function (t) { try { return !!t() } catch { return !0 } } }, 1611: function (h, t, n) { var r = n(8987), l = Function.prototype, a = l.apply, e = l.call; h.exports = typeof Reflect == "object" && Reflect.apply || (r ? e.bind(a) : function () { return e.apply(a, arguments) }) }, 2938: function (h, t, n) { var r = n(7386), l = n(8257), a = n(8987), e = r(r.bind); h.exports = function (g, _) { return l(g), _ === void 0 ? g : a ? e(g, _) : function () { return g.apply(_, arguments) } } }, 8987: function (h, t, n) { var r = n(6544); h.exports = !r(function () { var l = (function () { }).bind(); return typeof l != "function" || l.hasOwnProperty("prototype") }) }, 8262: function (h, t, n) { var r = n(8987), l = Function.prototype.call; h.exports = r ? l.bind(l) : function () { return l.apply(l, arguments) } }, 4340: function (h, t, n) { var r = n(8494), l = n(2870), a = Function.prototype, e = r && Object.getOwnPropertyDescriptor, g = l(a, "name"), _ = g && (function () { }).name === "something", y = g && (!r || r && e(a, "name").configurable); h.exports = { EXISTS: g, PROPER: _, CONFIGURABLE: y } }, 7386: function (h, t, n) { var r = n(8987), l = Function.prototype, a = l.bind, e = l.call, g = r && a.bind(e, e); h.exports = r ? function (_) { return _ && g(_) } : function (_) { return _ && function () { return e.apply(_, arguments) } } }, 5897: function (h, t, n) { var r = n(7583), l = n(9212), a = function (e) { return l(e) ? e : void 0 }; h.exports = function (e, g) { return arguments.length < 2 ? a(r[e]) : r[e] && r[e][g] } }, 8272: function (h, t, n) { var r = n(3058), l = n(911), a = n(339), e = n(3649)("iterator"); h.exports = function (g) { if (g != null) return l(g, e) || l(g, "@@iterator") || a[r(g)] } }, 6307: function (h, t, n) { var r = n(7583), l = n(8262), a = n(8257), e = n(2569), g = n(5637), _ = n(8272), y = r.TypeError; h.exports = function (x, E) { var C = arguments.length < 2 ? _(x) : E; if (a(C)) return e(l(C, x)); throw y(g(x) + " is not iterable") } }, 911: function (h, t, n) { var r = n(8257); h.exports = function (l, a) { var e = l[a]; return e == null ? void 0 : r(e) } }, 7583: function (h, t, n) { var r = function (l) { return l && l.Math == Math && l }; h.exports = r(typeof globalThis == "object" && globalThis) || r(typeof window == "object" && window) || r(typeof self == "object" && self) || r(typeof n.g == "object" && n.g) || function () { return this }() || Function("return this")() }, 2870: function (h, t, n) { var r = n(7386), l = n(1324), a = r({}.hasOwnProperty); h.exports = Object.hasOwn || function (e, g) { return a(l(e), g) } }, 4639: function (h) { h.exports = {} }, 2716: function (h, t, n) { var r = n(7583); h.exports = function (l, a) { var e = r.console; e && e.error && (arguments.length == 1 ? e.error(l) : e.error(l, a)) } }, 482: function (h, t, n) { var r = n(5897); h.exports = r("document", "documentElement") }, 275: function (h, t, n) { var r = n(8494), l = n(6544), a = n(6668); h.exports = !r && !l(function () { return Object.defineProperty(a("div"), "a", { get: function () { return 7 } }).a != 7 }) }, 5044: function (h, t, n) { var r = n(7583), l = n(7386), a = n(6544), e = n(9624), g = r.Object, _ = l("".split); h.exports = a(function () { return !g("z").propertyIsEnumerable(0) }) ? function (y) { return e(y) == "String" ? _(y, "") : g(y) } : g }, 9734: function (h, t, n) { var r = n(7386), l = n(9212), a = n(1314), e = r(Function.toString); l(a.inspectSource) || (a.inspectSource = function (g) { return e(g) }), h.exports = a.inspectSource }, 4402: function (h, t, n) { var r = n(794), l = n(57); h.exports = function (a, e) { r(e) && "cause" in e && l(a, "cause", e.cause) } }, 2743: function (h, t, n) { var r, l, a, e = n(9491), g = n(7583), _ = n(7386), y = n(794), x = n(57), E = n(2870), C = n(1314), L = n(9137), A = n(4639), I = "Object already initialized", D = g.TypeError, w = g.WeakMap; if (e || C.state) { var S = C.state || (C.state = new w), O = _(S.get), F = _(S.has), j = _(S.set); r = function ($, V) { if (F(S, $)) throw new D(I); return V.facade = $, j(S, $, V), V }, l = function ($) { return O(S, $) || {} }, a = function ($) { return F(S, $) } } else { var P = L("state"); A[P] = !0, r = function ($, V) { if (E($, P)) throw new D(I); return V.facade = $, x($, P, V), V }, l = function ($) { return E($, P) ? $[P] : {} }, a = function ($) { return E($, P) } } h.exports = { set: r, get: l, has: a, enforce: function ($) { return a($) ? l($) : r($, {}) }, getterFor: function ($) { return function (V) { var q; if (!y(V) || (q = l(V)).type !== $) throw D("Incompatible receiver, " + $ + " required"); return q } } } }, 114: function (h, t, n) { var r = n(3649), l = n(339), a = r("iterator"), e = Array.prototype; h.exports = function (g) { return g !== void 0 && (l.Array === g || e[a] === g) } }, 4521: function (h, t, n) { var r = n(9624); h.exports = Array.isArray || function (l) { return r(l) == "Array" } }, 9212: function (h) { h.exports = function (t) { return typeof t == "function" } }, 2097: function (h, t, n) { var r = n(7386), l = n(6544), a = n(9212), e = n(3058), g = n(5897), _ = n(9734), y = function () { }, x = [], E = g("Reflect", "construct"), C = /^\s*(?:class|function)\b/, L = r(C.exec), A = !C.exec(y), I = function (w) { if (!a(w)) return !1; try { return E(y, x, w), !0 } catch { return !1 } }, D = function (w) { if (!a(w)) return !1; switch (e(w)) { case "AsyncFunction": case "GeneratorFunction": case "AsyncGeneratorFunction": return !1 }try { return A || !!L(C, _(w)) } catch { return !0 } }; D.sham = !0, h.exports = !E || l(function () { var w; return I(I.call) || !I(Object) || !I(function () { w = !0 }) || w }) ? D : I }, 4451: function (h, t, n) { var r = n(6544), l = n(9212), a = /#|\.prototype\./, e = function (E, C) { var L = _[g(E)]; return L == x || L != y && (l(C) ? r(C) : !!C) }, g = e.normalize = function (E) { return String(E).replace(a, ".").toLowerCase() }, _ = e.data = {}, y = e.NATIVE = "N", x = e.POLYFILL = "P"; h.exports = e }, 794: function (h, t, n) { var r = n(9212); h.exports = function (l) { return typeof l == "object" ? l !== null : r(l) } }, 6268: function (h) { h.exports = !1 }, 5871: function (h, t, n) { var r = n(7583), l = n(5897), a = n(9212), e = n(2447), g = n(7786), _ = r.Object; h.exports = g ? function (y) { return typeof y == "symbol" } : function (y) { var x = l("Symbol"); return a(x) && e(x.prototype, _(y)) } }, 4026: function (h, t, n) { var r = n(7583), l = n(2938), a = n(8262), e = n(2569), g = n(5637), _ = n(114), y = n(1825), x = n(2447), E = n(6307), C = n(8272), L = n(7093), A = r.TypeError, I = function (w, S) { this.stopped = w, this.result = S }, D = I.prototype; h.exports = function (w, S, O) { var F, j, P, $, V, q, ee, re = O && O.that, ye = !(!O || !O.AS_ENTRIES), ce = !(!O || !O.IS_ITERATOR), Q = !(!O || !O.INTERRUPTED), se = l(S, re), fe = function (K) { return F && L(F, "normal", K), new I(!0, K) }, G = function (K) { return ye ? (e(K), Q ? se(K[0], K[1], fe) : se(K[0], K[1])) : Q ? se(K, fe) : se(K) }; if (ce) F = w; else { if (!(j = C(w))) throw A(g(w) + " is not iterable"); if (_(j)) { for (P = 0, $ = y(w); $ > P; P++)if ((V = G(w[P])) && x(D, V)) return V; return new I(!1) } F = E(w, j) } for (q = F.next; !(ee = a(q, F)).done;) { try { V = G(ee.value) } catch (K) { L(F, "throw", K) } if (typeof V == "object" && V && x(D, V)) return V } return new I(!1) } }, 7093: function (h, t, n) { var r = n(8262), l = n(2569), a = n(911); h.exports = function (e, g, _) { var y, x; l(e); try { if (!(y = a(e, "return"))) { if (g === "throw") throw _; return _ } y = r(y, e) } catch (E) { x = !0, y = E } if (g === "throw") throw _; if (x) throw y; return l(y), _ } }, 2365: function (h, t, n) { var r, l, a, e = n(6544), g = n(9212), _ = n(3590), y = n(729), x = n(1270), E = n(3649), C = n(6268), L = E("iterator"), A = !1;[].keys && ("next" in (a = [].keys()) ? (l = y(y(a))) !== Object.prototype && (r = l) : A = !0), r == null || e(function () { var I = {}; return r[L].call(I) !== I }) ? r = {} : C && (r = _(r)), g(r[L]) || x(r, L, function () { return this }), h.exports = { IteratorPrototype: r, BUGGY_SAFARI_ITERATORS: A } }, 339: function (h) { h.exports = {} }, 1825: function (h, t, n) { var r = n(97); h.exports = function (l) { return r(l.length) } }, 2095: function (h, t, n) { var r, l, a, e, g, _, y, x, E = n(7583), C = n(2938), L = n(6683).f, A = n(8117).set, I = n(7020), D = n(3256), w = n(6846), S = n(5354), O = E.MutationObserver || E.WebKitMutationObserver, F = E.document, j = E.process, P = E.Promise, $ = L(E, "queueMicrotask"), V = $ && $.value; V || (r = function () { var q, ee; for (S && (q = j.domain) && q.exit(); l;) { ee = l.fn, l = l.next; try { ee() } catch (re) { throw l ? e() : a = void 0, re } } a = void 0, q && q.enter() }, I || S || w || !O || !F ? !D && P && P.resolve ? ((y = P.resolve(void 0)).constructor = P, x = C(y.then, y), e = function () { x(r) }) : S ? e = function () { j.nextTick(r) } : (A = C(A, E), e = function () { A(r) }) : (g = !0, _ = F.createTextNode(""), new O(r).observe(_, { characterData: !0 }), e = function () { _.data = g = !g })), h.exports = V || function (q) { var ee = { fn: q, next: void 0 }; a && (a.next = ee), l || (l = ee, e()), a = ee } }, 783: function (h, t, n) { var r = n(7583); h.exports = r.Promise }, 8640: function (h, t, n) { var r = n(4061), l = n(6544); h.exports = !!Object.getOwnPropertySymbols && !l(function () { var a = Symbol(); return !String(a) || !(Object(a) instanceof Symbol) || !Symbol.sham && r && r < 41 }) }, 9491: function (h, t, n) { var r = n(7583), l = n(9212), a = n(9734), e = r.WeakMap; h.exports = l(e) && /native code/.test(a(e)) }, 5084: function (h, t, n) { var r = n(8257), l = function (a) { var e, g; this.promise = new a(function (_, y) { if (e !== void 0 || g !== void 0) throw TypeError("Bad Promise constructor"); e = _, g = y }), this.resolve = r(e), this.reject = r(g) }; h.exports.f = function (a) { return new l(a) } }, 2764: function (h, t, n) { var r = n(8320); h.exports = function (l, a) { return l === void 0 ? arguments.length < 2 ? "" : a : r(l) } }, 3590: function (h, t, n) { var r, l = n(2569), a = n(8728), e = n(5690), g = n(4639), _ = n(482), y = n(6668), x = n(9137), E = x("IE_PROTO"), C = function () { }, L = function (D) { return "