diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..dc8a447 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,46 @@ +--- +name: Bug report +about: 创建报告以帮助我们改进( Create a report to help us improve) +title: '' +labels: '' +assignees: '' +--- + +**bug 描述(Describe the bug)** + +对bug是什么的清晰简洁的描述。 (A clear and concise description of what the bug is.) + +**复现(To Reproduce)** + +再现步骤(Steps to reproduce the behavior): + +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**预期行为(Expected behavior)** + +对你期望发生的事情的清晰简洁的描述。 (A clear and concise description of what you expected to happen.) + +**截图(Screenshots)** + +如果适用,请添加屏幕截图以帮助解释您的问题。 (If applicable, add screenshots to help explain your problem.) + +**PC 请填写以下信息 (please complete the following information):** + +- OS: [e.g. iOS] +- Browser [e.g. chrome, safari] +- Version [e.g. 22] + +**mobile 请填写以下信息 (please complete the following information):** + +- Device: [e.g. iPhone6] +- OS: [e.g. iOS8.1] +- Browser [e.g. stock browser, safari] +- Version [e.g. 22] + +**附加上下文(Additional context)** + +在此处添加有关该问题的任何其他上下文。 (Add any other context about the problem here.) + diff --git a/.github/workflows/build-demos.yml b/.github/workflows/build-demos.yml new file mode 100644 index 0000000..4b00605 --- /dev/null +++ b/.github/workflows/build-demos.yml @@ -0,0 +1,37 @@ +name: build-demos + +on: + push: + branches: ["main", "develop"] + pull_request: + branches: ["main"] + +jobs: + build: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [16.x, 18.x, 20.x, 21.x, 22.x] + + steps: + - uses: actions/checkout@v4 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + - uses: pnpm/action-setup@v3 + with: + version: 8 + + - name: Build react-demo + working-directory: ./examples/react-app + run: | + pnpm install + pnpm run build + + - name: Build vue-demo + working-directory: ./examples/vue-app + run: | + pnpm install + pnpm run build diff --git a/.github/workflows/install.yml b/.github/workflows/install.yml new file mode 100644 index 0000000..adc2fa6 --- /dev/null +++ b/.github/workflows/install.yml @@ -0,0 +1,32 @@ +# 整个流程的名字 +name: install dependencies +# 触发时机,在 tag 被 push 操作触发 +on: + push: + branches: ["main", "develop"] + pull_request: + branches: ["main"] + +# 任务,定义个changelog 的任务 +jobs: + changelog: + name: install dependencies + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + # 设置 Node + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 18 + cache: npm + registry-url: https://registry.npmjs.org + # 安装依赖 + - uses: pnpm/action-setup@v3 + with: + version: 8 + + - name: Install dependencies + run: pnpm install + diff --git a/.github/workflows/relese.yml b/.github/workflows/relese.yml new file mode 100644 index 0000000..0b79d5f --- /dev/null +++ b/.github/workflows/relese.yml @@ -0,0 +1,43 @@ +# 整个流程的名字 +name: Release +# 触发时机,在 tag 被 push 操作触发 +on: + push: + tags: + - "v*" +# 任务,定义个changelog 的任务 +jobs: + changelog: + name: Release + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + # # 设置 pnpm + # - name: Setup PNPM + # uses: pnpm/action-setup@v2 + # with: + # version: 8 + # 设置 Node + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 18 + cache: npm + registry-url: https://registry.npmjs.org + # 安装依赖 + - uses: pnpm/action-setup@v3 + with: + version: 8 + + - name: Install dependencies + run: pnpm install + # # 打包 + # - name: Build Packages + # run: pnpm run build + # 发布npm 发布前执行了prepublishOnly + - name: Publish npm + run: npm publish + env: + # 这里需要几个 Token 变量 + # NPM_TOKEN 需要在 npm 网站生成 + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.gitignore b/.gitignore index fee95f6..3258ab8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ node_modules/ -dist/ +examples/**/dist/ build/ .cache # misc diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4b8b2d3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +## v0.1.0 + +- 支持hls h264/h265直播播放 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a9407ef --- /dev/null +++ b/LICENSE @@ -0,0 +1,33 @@ + + +https://github.com/numberwolf/h265web.js/blob/master/LICENSE-Free_CN.MD + + +Copyright (c) 2017 Dailymotion (http://www.dailymotion.com) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +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. + +src/remux/mp4-generator.js and src/demux/exp-golomb.ts implementation in this project +are derived from the HLS library for video.js (https://github.com/videojs/videojs-contrib-hls) + +That work is also covered by the Apache 2 License, following copyright: +Copyright (c) 2013-2015 Brightcove + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md index b29d28a..867c91f 100644 --- a/README.md +++ b/README.md @@ -1 +1,52 @@ -# EZUIKit-hls \ No newline at end of file +## @ezuikit/player-hls + +hls 直播播放器, 支持视频H264, H265, 音频 AAC 播放。 + +## 安装 + +```bash +# npm +npm install @ezuikit/player-hls + +# yarn +npm add @ezuikit/player-hls + +# pnpm +pnpm add @ezuikit/player-hls +``` + +### 支持 script 引入 + +```html + + +``` + +## 使用 + +```ts +// 推荐 +import HlsPlayer from '@ezuikit/player-hls'; + +// 默认自动播放 +const player = new HlsPlayer({ + id: 'app', + url: 'https://open.ys7.com/v3/openlive/E71992743_1_1.m3u8', + staticPath: "/" // decoder静态资源文件夹 默认根目录 +}); + +// 不会立即生效 +// 1. 需要等待静态资源加载完成(js, wasm) +// 2. 需要视频返回并且有视频帧 +player.play(); // + +// 暂停 +player.pause(); +``` + + +注意: 暂不提供CDN地址,decoder静态资源需要放置在自己的服务器下(node_modules/@ezuikit/player-hls/dist 下 decoder.wasm 和 decoder.worker.js 文件, 这两个文件需要在同一个文件夹下) + +注意: 暂不提供CDN地址,decoder静态资源需要放置在自己的服务器下(node_modules/@ezuikit/player-hls/dist 下 decoder.wasm 和 decoder.worker.js 文件, 这两个文件需要在同一个文件夹下) + +注意: 暂不提供CDN地址,decoder静态资源需要放置在自己的服务器下(node_modules/@ezuikit/player-hls/dist 下 decoder.wasm 和 decoder.worker.js 文件, 这两个文件需要在同一个文件夹下) diff --git a/dist/decoder.wasm b/dist/decoder.wasm new file mode 100644 index 0000000..5c0c2fa Binary files /dev/null and b/dist/decoder.wasm differ diff --git a/dist/decoder.worker.js b/dist/decoder.worker.js new file mode 100644 index 0000000..4b8dbac --- /dev/null +++ b/dist/decoder.worker.js @@ -0,0 +1,8 @@ +/* +* +* DecoderWorker.js v0.1.0 +* Copyright (c) 2024-8-1 Ezviz-OpenBiz +* . +* +*/ +!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";var e={DEFAULT_SAMPLERATE:44100,DEFAULT_CHANNEL:1,H264AUD:[0,0,0,1,9,224],H265AUD:[0,0,0,1,70,1,80],DEF_AAC:"aac",DEF_MP3:"mp3",DEF_H265:"h265",DEF_HEVC:"hevc",DEF_H264:"h264",DEF_AVC:"avc",CODEC_OFFSET_TABLE:["hevc","h265","avc","h264","aac","mp3"]};function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t={exports:{}};!function(e,r){function t(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var d,f,p=(f="undefined"!=typeof document?null==(d=document.currentScript)?void 0:d.src:void 0,function(e){var r,t=function(){var r=dr.value;r in e||Object.defineProperty(e,r,{configurable:!0,get:function(){q("Access to module property ('"+r+"') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.")}})};void 0===e&&(e={});var n,i,d=Object.assign({},e),p=new Promise((function(e,r){n=e,i=r}));["_malloc","_free","_memory","_registerWasmPlayer","_setCodecType","_exitWasmPlayer","_initDecoder","_decodeCodecContext","_destroy","_demuxTsStream","_getPacket","_getVLCLen","_getVLC","_getVPSLen","_getVPS","_getSPSLen","_getSPS","_getPPSLen","_getPPS","_getSEILen","_getSEI","___indirect_function_table","_ff_h264_cabac_tables","onRuntimeInitialized"].forEach((function(e){Object.getOwnPropertyDescriptor(p,e)||Object.defineProperty(p,e,{get:function(){return q("You are getting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")},set:function(){return q("You are setting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")}})}));var m="object"==("undefined"==typeof window?"undefined":u(window)),h="function"==typeof importScripts,g="object"==("undefined"==typeof process?"undefined":u(process))&&"object"==u(process.versions)&&"string"==typeof process.versions.node,v=!m&&!g&&!h;if(d.ENVIRONMENT)throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");var E,y,w,b=Object.assign({},d),_="./this.program",S="";if(v){if("object"==("undefined"==typeof process?"undefined":u(process))||"object"==("undefined"==typeof window?"undefined":u(window))||"function"==typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)")}else{if(!m&&!h)throw new Error("environment detection error");if(h?S=self.location.href:"undefined"!=typeof document&&document.currentScript&&(S=document.currentScript.src),f&&(S=f),S=S.startsWith("blob:")?"":S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1),"object"!=("undefined"==typeof window?"undefined":u(window))&&"function"!=typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");E=function(e){var r=new XMLHttpRequest;return r.open("GET",e,!1),r.send(null),r.responseText},h&&(w=function(e){var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),y=function(e,r,t){var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=function(){200==n.status||0==n.status&&n.response?r(n.response):t()},n.onerror=t,n.send(null)}}var O,T,k,A=d.print||console.log.bind(console),M=d.printErr||console.error.bind(console);Object.assign(d,b),b=null,O="fetchSettings",Object.getOwnPropertyDescriptor(d,O)&&q("`Module."+O+"` was supplied but `"+O+"` not included in INCOMING_MODULE_JS_API"),d.arguments&&d.arguments,ie("arguments","arguments_"),d.thisProgram&&(_=d.thisProgram),ie("thisProgram","thisProgram"),d.quit&&d.quit,ie("quit","quit_"),L(void 0===d.memoryInitializerPrefixURL,"Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.pthreadMainPrefixURL,"Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.cdInitializerPrefixURL,"Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.filePackagePrefixURL,"Module.filePackagePrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.read,"Module.read option was removed (modify read_ in JS)"),L(void 0===d.readAsync,"Module.readAsync option was removed (modify readAsync in JS)"),L(void 0===d.readBinary,"Module.readBinary option was removed (modify readBinary in JS)"),L(void 0===d.setWindowTitle,"Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"),L(void 0===d.TOTAL_MEMORY,"Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"),ie("asm","wasmExports"),ie("read","read_"),ie("readAsync","readAsync"),ie("readBinary","readBinary"),ie("setWindowTitle","setWindowTitle"),L(!g,"node environment detected but not enabled at build time. Add `node` to `-sENVIRONMENT` to enable."),L(!v,"shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable."),d.wasmBinary&&(T=d.wasmBinary),ie("wasmBinary","wasmBinary"),"object"!=("undefined"==typeof WebAssembly?"undefined":u(WebAssembly))&&M("no native wasm support detected");var P,F,C,D,x,I=!1;function L(e,r){e||q("Assertion failed"+(r?": "+r:""))}function N(){var e=k.buffer;d.HEAP8=P=new Int8Array(e),d.HEAP16=C=new Int16Array(e),d.HEAPU8=F=new Uint8Array(e),d.HEAPU16=new Uint16Array(e),d.HEAP32=D=new Int32Array(e),d.HEAPU32=x=new Uint32Array(e),d.HEAPF32=new Float32Array(e),d.HEAPF64=new Float64Array(e)}function R(){if(!I){var e=ir();0==e&&(e+=4);var r=x[e>>2],t=x[e+4>>2];34821223==r&&2310721022==t||q("Stack overflow! Stack cookie has been overwritten at "+le(e)+", expected hex dwords 0x89BACDFE and 0x2135467, but received "+le(t)+" "+le(r)),1668509029!=x[0]&&q("Runtime error: The application has corrupted its heap memory area (address zero)!")}}L(!d.STACK_SIZE,"STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"),L("undefined"!=typeof Int32Array&&"undefined"!=typeof Float64Array&&null!=Int32Array.prototype.subarray&&null!=Int32Array.prototype.set,"JS engine does not provide full typed array support"),L(!d.wasmMemory,"Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"),L(!d.INITIAL_MEMORY,"Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically"),function(){var e=new Int16Array(1),r=new Int8Array(e.buffer);if(e[0]=25459,115!==r[0]||99!==r[1])throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"}();var U=[],B=[],j=[],$=!1;L(Math.imul,"This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.fround,"This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.clz32,"This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.trunc,"This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");var W=0,H=null,z=null,V={};function G(e){for(var r=e;;){if(!V[e])return e;e=r+Math.random()}}function Y(e){var r;W++,null==(r=d.monitorRunDependencies)||r.call(d,W),e?(L(!V[e]),V[e]=1,null===H&&"undefined"!=typeof setInterval&&(H=setInterval((function(){if(I)return clearInterval(H),void(H=null);var e=!1;for(var r in V)e||(e=!0,M("still waiting on run dependencies:")),M("dependency: "+r);e&&M("(end of list)")}),1e4))):M("warning: run dependency added without ID")}function Q(e){var r;if(W--,null==(r=d.monitorRunDependencies)||r.call(d,W),e?(L(V[e]),delete V[e]):M("warning: run dependency removed without ID"),0==W&&(null!==H&&(clearInterval(H),H=null),z)){var t=z;z=null,t()}}function q(e){var r;null==(r=d.onAbort)||r.call(d,e),M(e="Aborted("+e+")"),I=!0;var t=new WebAssembly.RuntimeError(e);throw i(t),t}var K,X,J,Z=function(e){return e.startsWith("data:application/octet-stream;base64,")},ee=function(e){return e.startsWith("file://")};function re(e,r){return function(){for(var t=arguments.length,n=new Array(t),o=0;o0;)e.shift()(d)};d.noExitRuntime;var le=function(e){return L("number"==typeof e),"0x"+(e>>>=0).toString(16).padStart(8,"0")},de=function(e){var r;(r=de).shown||(r.shown={}),de.shown[e]||(de.shown[e]=1,M(e))};function fe(){L(null!=xe.varargs);var e=D[+xe.varargs>>2];return xe.varargs+=4,e}var pe=fe,me={isAbs:function(e){return"/"===e.charAt(0)},splitPath:function(e){return/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1)},normalizeArray:function(e,r){for(var t=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),t++):t&&(e.splice(n,1),t--)}if(r)for(;t;t--)e.unshift("..");return e},normalize:function(e){var r=me.isAbs(e),t="/"===e.substr(-1);return(e=me.normalizeArray(e.split("/").filter((function(e){return!!e})),!r).join("/"))||r||(e="."),e&&t&&(e+="/"),(r?"/":"")+e},dirname:function(e){var r=me.splitPath(e),t=r[0],n=r[1];return t||n?(n&&(n=n.substr(0,n.length-1)),t+n):"."},basename:function(e){if("/"===e)return"/";var r=(e=(e=me.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===r?e:e.substr(r+1)},join:function(){for(var e=arguments.length,r=new Array(e),t=0;t { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };")}())(e)},ge={resolve:function(){for(var e=arguments.length,r=new Array(e),t=0;t=-1&&!o;i--){var a=i>=0?r[i]:Ce.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");if(!a)return"";n=a+"/"+n,o=me.isAbs(a)}return(o?"/":"")+(n=me.normalizeArray(n.split("/").filter((function(e){return!!e})),!o).join("/"))||"."},relative:function(e,r){var t=function(e){for(var r=0;r=0&&""===e[t];t--);return r>t?[]:e.slice(r,t-r+1)};e=ge.resolve(e).substr(1),r=ge.resolve(r).substr(1);for(var n=t(e.split("/")),o=t(r.split("/")),i=Math.min(n.length,o.length),a=i,s=0;s=n);)++o;if(o-r>16&&e.buffer&&ve)return ve.decode(e.subarray(r,o));for(var i="";r>10,56320|1023&c)}}else i+=String.fromCharCode((31&a)<<6|s)}else i+=String.fromCharCode(a)}return i},ye=[],we=function(e){for(var r=0,t=0;t=55296&&n<=57343?(r+=4,++t):r+=3}return r},be=function(e,r,t,n){if(L("string"==typeof e,"stringToUTF8Array expects a string (got "+(void 0===e?"undefined":u(e))+")"),!(n>0))return 0;for(var o=t,i=t+n-1,a=0;a=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),s<=127){if(t>=i)break;r[t++]=s}else if(s<=2047){if(t+1>=i)break;r[t++]=192|s>>6,r[t++]=128|63&s}else if(s<=65535){if(t+2>=i)break;r[t++]=224|s>>12,r[t++]=128|s>>6&63,r[t++]=128|63&s}else{if(t+3>=i)break;s>1114111&&de("Invalid Unicode code point "+le(s)+" encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."),r[t++]=240|s>>18,r[t++]=128|s>>12&63,r[t++]=128|s>>6&63,r[t++]=128|63&s}}return r[t]=0,t-o};function _e(e,r,t){var n=we(e)+1,o=new Array(n),i=be(e,o,0,o.length);return o.length=i,o}var Se,Oe={ttys:[],init:function(){},shutdown:function(){},register:function(e,r){Oe.ttys[e]={input:[],output:[],ops:r},Ce.registerDevice(e,Oe.stream_ops)},stream_ops:{open:function(e){var r=Oe.ttys[e.node.rdev];if(!r)throw new Ce.ErrnoError(43);e.tty=r,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,r,t,n,o){if(!e.tty||!e.tty.ops.get_char)throw new Ce.ErrnoError(60);for(var i=0,a=0;a0&&(A(Ee(e.output,0)),e.output=[])},ioctl_tcgets:function(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(e,r,t){return 0},ioctl_tiocgwinsz:function(e){return[24,80]}},default_tty1_ops:{put_char:function(e,r){null===r||10===r?(M(Ee(e.output,0)),e.output=[]):0!=r&&e.output.push(r)},fsync:function(e){e.output&&e.output.length>0&&(M(Ee(e.output,0)),e.output=[])}}},Te=function(e){q("internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported")},ke={ops_table:null,mount:function(e){return ke.createNode(null,"/",16895,0)},createNode:function(e,r,t,n){var o;if(Ce.isBlkdev(t)||Ce.isFIFO(t))throw new Ce.ErrnoError(63);(o=ke).ops_table||(o.ops_table={dir:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr,lookup:ke.node_ops.lookup,mknod:ke.node_ops.mknod,rename:ke.node_ops.rename,unlink:ke.node_ops.unlink,rmdir:ke.node_ops.rmdir,readdir:ke.node_ops.readdir,symlink:ke.node_ops.symlink},stream:{llseek:ke.stream_ops.llseek}},file:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr},stream:{llseek:ke.stream_ops.llseek,read:ke.stream_ops.read,write:ke.stream_ops.write,allocate:ke.stream_ops.allocate,mmap:ke.stream_ops.mmap,msync:ke.stream_ops.msync}},link:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr,readlink:ke.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr},stream:Ce.chrdev_stream_ops}});var i=Ce.createNode(e,r,t,n);return Ce.isDir(i.mode)?(i.node_ops=ke.ops_table.dir.node,i.stream_ops=ke.ops_table.dir.stream,i.contents={}):Ce.isFile(i.mode)?(i.node_ops=ke.ops_table.file.node,i.stream_ops=ke.ops_table.file.stream,i.usedBytes=0,i.contents=null):Ce.isLink(i.mode)?(i.node_ops=ke.ops_table.link.node,i.stream_ops=ke.ops_table.link.stream):Ce.isChrdev(i.mode)&&(i.node_ops=ke.ops_table.chrdev.node,i.stream_ops=ke.ops_table.chrdev.stream),i.timestamp=Date.now(),e&&(e.contents[r]=i,e.timestamp=i.timestamp),i},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,r){var t=e.contents?e.contents.length:0;if(!(t>=r)){r=Math.max(r,t*(t<1048576?2:1.125)>>>0),0!=t&&(r=Math.max(r,256));var n=e.contents;e.contents=new Uint8Array(r),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,r){if(e.usedBytes!=r)if(0==r)e.contents=null,e.usedBytes=0;else{var t=e.contents;e.contents=new Uint8Array(r),t&&e.contents.set(t.subarray(0,Math.min(r,e.usedBytes))),e.usedBytes=r}},node_ops:{getattr:function(e){var r={};return r.dev=Ce.isChrdev(e.mode)?e.id:1,r.ino=e.id,r.mode=e.mode,r.nlink=1,r.uid=0,r.gid=0,r.rdev=e.rdev,Ce.isDir(e.mode)?r.size=4096:Ce.isFile(e.mode)?r.size=e.usedBytes:Ce.isLink(e.mode)?r.size=e.link.length:r.size=0,r.atime=new Date(e.timestamp),r.mtime=new Date(e.timestamp),r.ctime=new Date(e.timestamp),r.blksize=4096,r.blocks=Math.ceil(r.size/r.blksize),r},setattr:function(e,r){void 0!==r.mode&&(e.mode=r.mode),void 0!==r.timestamp&&(e.timestamp=r.timestamp),void 0!==r.size&&ke.resizeFileStorage(e,r.size)},lookup:function(e,r){throw Ce.genericErrors[44]},mknod:function(e,r,t,n){return ke.createNode(e,r,t,n)},rename:function(e,r,t){if(Ce.isDir(e.mode)){var n;try{n=Ce.lookupNode(r,t)}catch(e){}if(n)for(var o in n.contents)throw new Ce.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=t,r.contents[t]=e,r.timestamp=e.parent.timestamp,e.parent=r},unlink:function(e,r){delete e.contents[r],e.timestamp=Date.now()},rmdir:function(e,r){var t=Ce.lookupNode(e,r);for(var n in t.contents)throw new Ce.ErrnoError(55);delete e.contents[r],e.timestamp=Date.now()},readdir:function(e){for(var r,t=[".",".."],n=l(Object.keys(e.contents));!(r=n()).done;){var o=r.value;t.push(o)}return t},symlink:function(e,r,t){var n=ke.createNode(e,r,41471,0);return n.link=t,n},readlink:function(e){if(!Ce.isLink(e.mode))throw new Ce.ErrnoError(28);return e.link}},stream_ops:{read:function(e,r,t,n,o){var i=e.node.contents;if(o>=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,n);if(L(a>=0),a>8&&i.subarray)r.set(i.subarray(o,o+a),t);else for(var s=0;s0||t+r8)throw new Ce.ErrnoError(32);for(var t=e.split("/").filter((function(e){return!!e})),n=Ce.root,o="/",i=0;i40)throw new Ce.ErrnoError(32)}}return{path:o,node:n}},getPath:function(e){for(var r;;){if(Ce.isRoot(e)){var t=e.mount.mountpoint;return r?"/"!==t[t.length-1]?t+"/"+r:t+r:t}r=r?e.name+"/"+r:e.name,e=e.parent}},hashName:function(e,r){for(var t=0,n=0;n>>0)%Ce.nameTable.length},hashAddNode:function(e){var r=Ce.hashName(e.parent.id,e.name);e.name_next=Ce.nameTable[r],Ce.nameTable[r]=e},hashRemoveNode:function(e){var r=Ce.hashName(e.parent.id,e.name);if(Ce.nameTable[r]===e)Ce.nameTable[r]=e.name_next;else for(var t=Ce.nameTable[r];t;){if(t.name_next===e){t.name_next=e.name_next;break}t=t.name_next}},lookupNode:function(e,r){var t=Ce.mayLookup(e);if(t)throw new Ce.ErrnoError(t);for(var n=Ce.hashName(e.id,r),o=Ce.nameTable[n];o;o=o.name_next){var i=o.name;if(o.parent.id===e.id&&i===r)return o}return Ce.lookup(e,r)},createNode:function(e,r,t,n){L("object"==(void 0===e?"undefined":u(e)));var o=new Ce.FSNode(e,r,t,n);return Ce.hashAddNode(o),o},destroyNode:function(e){Ce.hashRemoveNode(e)},isRoot:function(e){return e===e.parent},isMountpoint:function(e){return!!e.mounted},isFile:function(e){return 32768==(61440&e)},isDir:function(e){return 16384==(61440&e)},isLink:function(e){return 40960==(61440&e)},isChrdev:function(e){return 8192==(61440&e)},isBlkdev:function(e){return 24576==(61440&e)},isFIFO:function(e){return 4096==(61440&e)},isSocket:function(e){return!(49152&~e)},flagsToPermissionString:function(e){var r=["r","w","rw"][3&e];return 512&e&&(r+="w"),r},nodePermissions:function(e,r){return Ce.ignorePermissions||(!r.includes("r")||292&e.mode)&&(!r.includes("w")||146&e.mode)&&(!r.includes("x")||73&e.mode)?0:2},mayLookup:function(e){if(!Ce.isDir(e.mode))return 54;var r=Ce.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate:function(e,r){try{return Ce.lookupNode(e,r),20}catch(e){}return Ce.nodePermissions(e,"wx")},mayDelete:function(e,r,t){var n;try{n=Ce.lookupNode(e,r)}catch(e){return e.errno}var o=Ce.nodePermissions(e,"wx");if(o)return o;if(t){if(!Ce.isDir(n.mode))return 54;if(Ce.isRoot(n)||Ce.getPath(n)===Ce.cwd())return 10}else if(Ce.isDir(n.mode))return 31;return 0},mayOpen:function(e,r){return e?Ce.isLink(e.mode)?32:Ce.isDir(e.mode)&&("r"!==Ce.flagsToPermissionString(r)||512&r)?31:Ce.nodePermissions(e,Ce.flagsToPermissionString(r)):44},MAX_OPEN_FDS:4096,nextfd:function(){for(var e=0;e<=Ce.MAX_OPEN_FDS;e++)if(!Ce.streams[e])return e;throw new Ce.ErrnoError(33)},getStreamChecked:function(e){var r=Ce.getStream(e);if(!r)throw new Ce.ErrnoError(8);return r},getStream:function(e){return Ce.streams[e]},createStream:function(e,r){return void 0===r&&(r=-1),e=Object.assign(new Ce.FSStream,e),-1==r&&(r=Ce.nextfd()),e.fd=r,Ce.streams[r]=e,e},closeStream:function(e){Ce.streams[e]=null},dupStream:function(e,r){var t,n;void 0===r&&(r=-1);var o=Ce.createStream(e,r);return null==(n=o.stream_ops)||null==(t=n.dup)||t.call(n,o),o},chrdev_stream_ops:{open:function(e){var r=Ce.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,null==e.stream_ops.open||e.stream_ops.open.call(e.stream_ops,e)},llseek:function(){throw new Ce.ErrnoError(70)}},major:function(e){return e>>8},minor:function(e){return 255&e},makedev:function(e,r){return e<<8|r},registerDevice:function(e,r){Ce.devices[e]={stream_ops:r}},getDevice:function(e){return Ce.devices[e]},getMounts:function(e){for(var r=[],t=[e];t.length;){var n,o=t.pop();r.push(o),(n=t).push.apply(n,[].concat(o.mounts))}return r},syncfs:function(e,r){"function"==typeof e&&(r=e,e=!1),Ce.syncFSRequests++,Ce.syncFSRequests>1&&M("warning: "+Ce.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var t=Ce.getMounts(Ce.root.mount),n=0;function o(e){return L(Ce.syncFSRequests>0),Ce.syncFSRequests--,r(e)}function i(e){if(e)return i.errored?void 0:(i.errored=!0,o(e));++n>=t.length&&o(null)}t.forEach((function(r){if(!r.type.syncfs)return i(null);r.type.syncfs(r,e,i)}))},mount:function(e,r,t){if("string"==typeof e)throw e;var n,o="/"===t,i=!t;if(o&&Ce.root)throw new Ce.ErrnoError(10);if(!o&&!i){var a=Ce.lookupPath(t,{follow_mount:!1});if(t=a.path,n=a.node,Ce.isMountpoint(n))throw new Ce.ErrnoError(10);if(!Ce.isDir(n.mode))throw new Ce.ErrnoError(54)}var s={type:e,opts:r,mountpoint:t,mounts:[]},u=e.mount(s);return u.mount=s,s.root=u,o?Ce.root=u:n&&(n.mounted=s,n.mount&&n.mount.mounts.push(s)),u},unmount:function(e){var r=Ce.lookupPath(e,{follow_mount:!1});if(!Ce.isMountpoint(r.node))throw new Ce.ErrnoError(28);var t=r.node,n=t.mounted,o=Ce.getMounts(n);Object.keys(Ce.nameTable).forEach((function(e){for(var r=Ce.nameTable[e];r;){var t=r.name_next;o.includes(r.mount)&&Ce.destroyNode(r),r=t}})),t.mounted=null;var i=t.mount.mounts.indexOf(n);L(-1!==i),t.mount.mounts.splice(i,1)},lookup:function(e,r){return e.node_ops.lookup(e,r)},mknod:function(e,r,t){var n=Ce.lookupPath(e,{parent:!0}).node,o=me.basename(e);if(!o||"."===o||".."===o)throw new Ce.ErrnoError(28);var i=Ce.mayCreate(n,o);if(i)throw new Ce.ErrnoError(i);if(!n.node_ops.mknod)throw new Ce.ErrnoError(63);return n.node_ops.mknod(n,o,r,t)},create:function(e,r){return r=void 0!==r?r:438,r&=4095,r|=32768,Ce.mknod(e,r,0)},mkdir:function(e,r){return r=void 0!==r?r:511,r&=1023,r|=16384,Ce.mknod(e,r,0)},mkdirTree:function(e,r){for(var t=e.split("/"),n="",o=0;o=0),n<0||o<0)throw new Ce.ErrnoError(28);if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(1==(2097155&e.flags))throw new Ce.ErrnoError(8);if(Ce.isDir(e.node.mode))throw new Ce.ErrnoError(31);if(!e.stream_ops.read)throw new Ce.ErrnoError(28);var i=void 0!==o;if(i){if(!e.seekable)throw new Ce.ErrnoError(70)}else o=e.position;var a=e.stream_ops.read(e,r,t,n,o);return i||(e.position+=a),a},write:function(e,r,t,n,o,i){if(L(t>=0),n<0||o<0)throw new Ce.ErrnoError(28);if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(!(2097155&e.flags))throw new Ce.ErrnoError(8);if(Ce.isDir(e.node.mode))throw new Ce.ErrnoError(31);if(!e.stream_ops.write)throw new Ce.ErrnoError(28);e.seekable&&1024&e.flags&&Ce.llseek(e,0,2);var a=void 0!==o;if(a){if(!e.seekable)throw new Ce.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,r,t,n,o,i);return a||(e.position+=s),s},allocate:function(e,r,t){if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(r<0||t<=0)throw new Ce.ErrnoError(28);if(!(2097155&e.flags))throw new Ce.ErrnoError(8);if(!Ce.isFile(e.node.mode)&&!Ce.isDir(e.node.mode))throw new Ce.ErrnoError(43);if(!e.stream_ops.allocate)throw new Ce.ErrnoError(138);e.stream_ops.allocate(e,r,t)},mmap:function(e,r,t,n,o){if(2&n&&!(2&o)&&2!=(2097155&e.flags))throw new Ce.ErrnoError(2);if(1==(2097155&e.flags))throw new Ce.ErrnoError(2);if(!e.stream_ops.mmap)throw new Ce.ErrnoError(43);return e.stream_ops.mmap(e,r,t,n,o)},msync:function(e,r,t,n,o){return L(t>=0),e.stream_ops.msync?e.stream_ops.msync(e,r,t,n,o):0},ioctl:function(e,r,t){if(!e.stream_ops.ioctl)throw new Ce.ErrnoError(59);return e.stream_ops.ioctl(e,r,t)},readFile:function(e,r){if(void 0===r&&(r={}),r.flags=r.flags||0,r.encoding=r.encoding||"binary","utf8"!==r.encoding&&"binary"!==r.encoding)throw new Error('Invalid encoding type "'+r.encoding+'"');var t,n=Ce.open(e,r.flags),o=Ce.stat(e).size,i=new Uint8Array(o);return Ce.read(n,i,0,o,0),"utf8"===r.encoding?t=Ee(i,0):"binary"===r.encoding&&(t=i),Ce.close(n),t},writeFile:function(e,r,t){void 0===t&&(t={}),t.flags=t.flags||577;var n=Ce.open(e,t.flags,t.mode);if("string"==typeof r){var o=new Uint8Array(we(r)+1),i=be(r,o,0,o.length);Ce.write(n,o,0,i,void 0,t.canOwn)}else{if(!ArrayBuffer.isView(r))throw new Error("Unsupported data type");Ce.write(n,r,0,r.byteLength,void 0,t.canOwn)}Ce.close(n)},cwd:function(){return Ce.currentPath},chdir:function(e){var r=Ce.lookupPath(e,{follow:!0});if(null===r.node)throw new Ce.ErrnoError(44);if(!Ce.isDir(r.node.mode))throw new Ce.ErrnoError(54);var t=Ce.nodePermissions(r.node,"x");if(t)throw new Ce.ErrnoError(t);Ce.currentPath=r.path},createDefaultDirectories:function(){Ce.mkdir("/tmp"),Ce.mkdir("/home"),Ce.mkdir("/home/web_user")},createDefaultDevices:function(){Ce.mkdir("/dev"),Ce.registerDevice(Ce.makedev(1,3),{read:function(){return 0},write:function(e,r,t,n,o){return n}}),Ce.mkdev("/dev/null",Ce.makedev(1,3)),Oe.register(Ce.makedev(5,0),Oe.default_tty_ops),Oe.register(Ce.makedev(6,0),Oe.default_tty1_ops),Ce.mkdev("/dev/tty",Ce.makedev(5,0)),Ce.mkdev("/dev/tty1",Ce.makedev(6,0));var e=new Uint8Array(1024),r=0,t=function(){return 0===r&&(r=he(e).byteLength),e[--r]};Ce.createDevice("/dev","random",t),Ce.createDevice("/dev","urandom",t),Ce.mkdir("/dev/shm"),Ce.mkdir("/dev/shm/tmp")},createSpecialDirectories:function(){Ce.mkdir("/proc");var e=Ce.mkdir("/proc/self");Ce.mkdir("/proc/self/fd"),Ce.mount({mount:function(){var r=Ce.createNode(e,"fd",16895,73);return r.node_ops={lookup:function(e,r){var t=+r,n=Ce.getStreamChecked(t),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:function(){return n.path}}};return o.parent=o,o}},r}},{},"/proc/self/fd")},createStandardStreams:function(){d.stdin?Ce.createDevice("/dev","stdin",d.stdin):Ce.symlink("/dev/tty","/dev/stdin"),d.stdout?Ce.createDevice("/dev","stdout",null,d.stdout):Ce.symlink("/dev/tty","/dev/stdout"),d.stderr?Ce.createDevice("/dev","stderr",null,d.stderr):Ce.symlink("/dev/tty1","/dev/stderr");var e=Ce.open("/dev/stdin",0),r=Ce.open("/dev/stdout",1),t=Ce.open("/dev/stderr",1);L(0===e.fd,"invalid handle for stdin ("+e.fd+")"),L(1===r.fd,"invalid handle for stdout ("+r.fd+")"),L(2===t.fd,"invalid handle for stderr ("+t.fd+")")},staticInit:function(){[44].forEach((function(e){Ce.genericErrors[e]=new Ce.ErrnoError(e),Ce.genericErrors[e].stack=""})),Ce.nameTable=new Array(4096),Ce.mount(ke,{},"/"),Ce.createDefaultDirectories(),Ce.createDefaultDevices(),Ce.createSpecialDirectories(),Ce.filesystems={MEMFS:ke}},init:function(e,r,t){L(!Ce.init.initialized,"FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"),Ce.init.initialized=!0,d.stdin=e||d.stdin,d.stdout=r||d.stdout,d.stderr=t||d.stderr,Ce.createStandardStreams()},quit:function(){Ce.init.initialized=!1,tr(0);for(var e=0;ethis.length-1||e<0)){var r=e%this.chunkSize,t=e/this.chunkSize|0;return this.getter(t)[r]}},r.setDataGetter=function(e){this.getter=e},r.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",t,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+t+". Status: "+e.status);var r,n=Number(e.getResponseHeader("Content-length")),o=(r=e.getResponseHeader("Accept-Ranges"))&&"bytes"===r,i=(r=e.getResponseHeader("Content-Encoding"))&&"gzip"===r,a=1048576;o||(a=n);var s=this;s.setDataGetter((function(e){var r=e*a,o=(e+1)*a-1;if(o=Math.min(o,n-1),void 0===s.chunks[e]&&(s.chunks[e]=function(e,r){if(e>r)throw new Error("invalid range ("+e+", "+r+") or no bytes requested!");if(r>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",t,!1),n!==a&&o.setRequestHeader("Range","bytes="+e+"-"+r),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+t+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):_e(o.responseText||"")}(r,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]})),!i&&n||(a=n=1,n=this.getter(0).length,a=n,A("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=a,this.lengthKnown=!0},o(e,[{key:"length",get:function(){return this.lengthKnown||this.cacheLength(),this._length}},{key:"chunkSize",get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}]),e}();if("undefined"!=typeof XMLHttpRequest){if(!h)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s={isDevice:!1,contents:new a}}else s={isDevice:!1,url:t};var u=Ce.createFile(e,r,s,n,i);s.contents?u.contents=s.contents:s.url&&(u.contents=null,u.url=s.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var c={};function l(e,r,t,n,o){var i=e.node.contents;if(o>=i.length)return 0;var a=Math.min(i.length-o,n);if(L(a>=0),i.slice)for(var s=0;s>2]=n.dev,D[t+4>>2]=n.mode,x[t+8>>2]=n.nlink,D[t+12>>2]=n.uid,D[t+16>>2]=n.gid,D[t+20>>2]=n.rdev,J=[n.size>>>0,(X=n.size,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+24>>2]=J[0],D[t+28>>2]=J[1],D[t+32>>2]=4096,D[t+36>>2]=n.blocks;var o=n.atime.getTime(),i=n.mtime.getTime(),a=n.ctime.getTime();return J=[Math.floor(o/1e3)>>>0,(X=Math.floor(o/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+40>>2]=J[0],D[t+44>>2]=J[1],x[t+48>>2]=o%1e3*1e3,J=[Math.floor(i/1e3)>>>0,(X=Math.floor(i/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+56>>2]=J[0],D[t+60>>2]=J[1],x[t+64>>2]=i%1e3*1e3,J=[Math.floor(a/1e3)>>>0,(X=Math.floor(a/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+72>>2]=J[0],D[t+76>>2]=J[1],x[t+80>>2]=a%1e3*1e3,J=[n.ino>>>0,(X=n.ino,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+88>>2]=J[0],D[t+92>>2]=J[1],0},doMsync:function(e,r,t,n,o){if(!Ce.isFile(r.node.mode))throw new Ce.ErrnoError(43);if(2&n)return 0;var i=F.slice(e,e+t);Ce.msync(r,i,o,t,n)},getStreamFromFD:function(e){return Ce.getStreamChecked(e)},varargs:void 0,getStr:function(e){return De(e)}},Ie=function(e,r){return L(e==e>>>0||e==(0|e)),L(r===(0|r)),r+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*r:NaN},Le=[0,31,60,91,121,152,182,213,244,274,305,335],Ne=[0,31,59,90,120,151,181,212,243,273,304,334],Re=function(e){var r;return((r=e.getFullYear())%4!=0||r%100==0&&r%400!=0?Ne:Le)[e.getMonth()]+e.getDate()-1},Ue=function(e,r,t){return L("number"==typeof t,"stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),be(e,F,r,t)};Se=function(){return performance.now()};var Be,je,$e=function(e){var r=k.buffer,t=(e-r.byteLength+65535)/65536;try{return k.grow(t),N(),1}catch(t){M("growMemory: Attempted to grow heap from "+r.byteLength+" bytes to "+e+" bytes, but got error: "+t)}},We={},He=function(){if(!He.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==("undefined"==typeof navigator?"undefined":u(navigator))&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:_||"./this.program"};for(var r in We)void 0===We[r]?delete e[r]:e[r]=We[r];var t=[];for(var r in e)t.push(r+"="+e[r]);He.strings=t}return He.strings},ze=function(e){return sr(e)},Ve=function(e,r,t,n,o){var i={string:function(e){var r=0;return null!=e&&0!==e&&(r=function(e){var r=we(e)+1,t=ze(r);return Ue(e,t,r),t}(e)),r},array:function(e){var r,t,n=ze(e.length);return t=n,L((r=e).length>=0,"writeArrayToMemory array must have a length (should be an array or typed array)"),P.set(r,t),n}},a=function(e){var r=d["_"+e];return L(r,"Cannot call unknown function "+e+", make sure it is exported"),r}(e),s=[],u=0;if(L("array"!==r,'Return type should not be "array".'),n)for(var c=0;c>7)},Ye=function(e,r){var t;if(L(!r.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled"),"function"==typeof WebAssembly.Function)return new WebAssembly.Function(function(e){L(!e.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled");for(var r={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},t={parameters:[],results:"v"==e[0]?[]:[r[e[0]]]},n=1;n=Qe.length&&(Qe.length=e+1),Qe[e]=r=Be.get(e)),L(Be.get(e)==r,"JavaScript-side Wasm function table mirror is out of date!"),r},Ke=function(e){return je||(je=new WeakMap,function(e,r){if(je)for(var t=e;t>1]=2,0}return-28}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_openat:function(e,r,t,n){xe.varargs=n;try{r=xe.getStr(r),r=xe.calculateAt(e,r);var o=n?fe():0;return Ce.open(r,t,o).fd}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return-e.errno}},_abort_js:function(){q("native code called abort()")},_emscripten_get_now_is_monotonic:function(){return 1},_emscripten_memcpy_js:function(e,r,t){return F.copyWithin(e,r,r+t)},_gmtime_js:function(e,r,t){var n=Ie(e,r),o=new Date(1e3*n);D[t>>2]=o.getUTCSeconds(),D[t+4>>2]=o.getUTCMinutes(),D[t+8>>2]=o.getUTCHours(),D[t+12>>2]=o.getUTCDate(),D[t+16>>2]=o.getUTCMonth(),D[t+20>>2]=o.getUTCFullYear()-1900,D[t+24>>2]=o.getUTCDay();var i=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),a=(o.getTime()-i)/864e5|0;D[t+28>>2]=a},_localtime_js:function(e,r,t){var n=Ie(e,r),o=new Date(1e3*n);D[t>>2]=o.getSeconds(),D[t+4>>2]=o.getMinutes(),D[t+8>>2]=o.getHours(),D[t+12>>2]=o.getDate(),D[t+16>>2]=o.getMonth(),D[t+20>>2]=o.getFullYear()-1900,D[t+24>>2]=o.getDay();var i=0|Re(o);D[t+28>>2]=i,D[t+36>>2]=-60*o.getTimezoneOffset();var a=new Date(o.getFullYear(),0,1),s=new Date(o.getFullYear(),6,1).getTimezoneOffset(),u=a.getTimezoneOffset(),c=0|(s!=u&&o.getTimezoneOffset()==Math.min(u,s));D[t+32>>2]=c},_mktime_js:function(e){var r,t=function(){var r=new Date(D[e+20>>2]+1900,D[e+16>>2],D[e+12>>2],D[e+8>>2],D[e+4>>2],D[e>>2],0),t=D[e+32>>2],n=r.getTimezoneOffset(),o=new Date(r.getFullYear(),0,1),i=new Date(r.getFullYear(),6,1).getTimezoneOffset(),a=o.getTimezoneOffset(),s=Math.min(a,i);if(t<0)D[e+32>>2]=Number(i!=a&&s==n);else if(t>0!=(s==n)){var u=Math.max(a,i),c=t>0?s:u;r.setTime(r.getTime()+6e4*(c-n))}D[e+24>>2]=r.getDay();var l=0|Re(r);D[e+28>>2]=l,D[e>>2]=r.getSeconds(),D[e+4>>2]=r.getMinutes(),D[e+8>>2]=r.getHours(),D[e+12>>2]=r.getDate(),D[e+16>>2]=r.getMonth(),D[e+20>>2]=r.getYear();var d=r.getTime();return isNaN(d)?-1:d/1e3}();return X=t,r=+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0,nr(r),t>>>0},_tzset_js:function(e,r,t,n){var o=(new Date).getFullYear(),i=new Date(o,0,1),a=new Date(o,6,1),s=i.getTimezoneOffset(),u=a.getTimezoneOffset(),c=Math.max(s,u);x[e>>2]=60*c,D[r>>2]=Number(s!=u);var l=function(e){return e.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1]},d=l(i),f=l(a);L(d),L(f),L(we(d)<=16,"timezone name truncated to fit in TZNAME_MAX ("+d+")"),L(we(f)<=16,"timezone name truncated to fit in TZNAME_MAX ("+f+")"),u>>=0)>r);var t=2147483648;if(e>t)return M("Cannot enlarge memory, requested "+e+" bytes, but the limit is "+t+" bytes!"),!1;for(var n,o,i=1;i<=4;i*=2){var a=r*(1+.2/i);a=Math.min(a,e+100663296);var s=Math.min(t,(n=Math.max(e,a))+((o=65536)-n%o)%o);if($e(s))return!0}return M("Failed to grow the heap from "+r+" bytes to "+s+" bytes, not enough memory!"),!1},environ_get:function(e,r){var t=0;return He().forEach((function(n,o){var i=r+t;x[e+4*o>>2]=i,function(e,r){for(var t=0;t>2]=t.length;var n=0;return t.forEach((function(e){return n+=e.length+1})),x[r>>2]=n,0},fd_close:function(e){try{var r=xe.getStreamFromFD(e);return Ce.close(r),0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_fdstat_get:function(e,r){try{var t=xe.getStreamFromFD(e),n=t.tty?2:Ce.isDir(t.mode)?3:Ce.isLink(t.mode)?7:4;return P[r]=n,C[r+2>>1]=0,J=[0,(X=0,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[r+8>>2]=J[0],D[r+12>>2]=J[1],J=[0,(X=0,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[r+16>>2]=J[0],D[r+20>>2]=J[1],0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_read:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,i=0;i>2],s=x[r+4>>2];r+=8;var u=Ce.read(e,P,a,s,n);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_seek:function(e,r,t,n,o){var i=Ie(r,t);try{if(isNaN(i))return 61;var a=xe.getStreamFromFD(e);return Ce.llseek(a,i,n),J=[a.position>>>0,(X=a.position,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[o>>2]=J[0],D[o+4>>2]=J[1],a.getdents&&0===i&&0===n&&(a.getdents=null),0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_write:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,i=0;i>2],s=x[r+4>>2];r+=8;var u=Ce.write(e,P,a,s,n);if(u<0)return-1;o+=u}return o}(xe.getStreamFromFD(e),r,t);return x[n>>2]=o,0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}}},er=function(){var e={env:Ze,wasi_snapshot_preview1:Ze};function r(e,r){var t;return er=e.exports,L(k=er.memory,"memory not found in wasm exports"),N(),L(Be=er.__indirect_function_table,"table not found in wasm exports"),t=er.__wasm_call_ctors,B.unshift(t),Q("wasm-instantiate"),er}Y("wasm-instantiate");var t,n,o,a,s=d;if(d.instantiateWasm)try{return d.instantiateWasm(e,r)}catch(e){M("Module.instantiateWasm callback failed with error: "+e),i(e)}return K||(K=te()),(t=T,n=K,o=e,a=function(e){L(d===s,"the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"),s=null,r(e.instance)},t||"function"!=typeof WebAssembly.instantiateStreaming||Z(n)||"function"!=typeof fetch?oe(n,o,a):fetch(n,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,o).then(a,(function(e){return M("wasm streaming compile failed: "+e),M("falling back to ArrayBuffer instantiation"),oe(n,o,a)}))}))).catch(i),{}}();d._malloc=re("malloc",1),d._free=re("free",1),d._registerWasmPlayer=re("registerWasmPlayer",0),d._setCodecType=re("setCodecType",4),d._exitWasmPlayer=re("exitWasmPlayer",1),d._initDecoder=re("initDecoder",1),d._decodeCodecContext=re("decodeCodecContext",5),d._destroy=re("destroy",1),d._demuxTsStream=re("demuxTsStream",3),d._getPacket=re("getPacket",0),d._getVLCLen=re("getVLCLen",0),d._getVLC=re("getVLC",0),d._getVPSLen=re("getVPSLen",0),d._getVPS=re("getVPS",0),d._getSPSLen=re("getSPSLen",0),d._getSPS=re("getSPS",0),d._getPPSLen=re("getPPSLen",0),d._getPPS=re("getPPS",0),d._getSEILen=re("getSEILen",0),d._getSEI=re("getSEI",0);var rr,tr=re("fflush",1),nr=re("_emscripten_tempret_set",1),or=function(){return(or=er.emscripten_stack_init)()},ir=function(){return(ir=er.emscripten_stack_get_end)()},ar=function(e){return(ar=er._emscripten_stack_restore)(e)},sr=function(e){return(sr=er._emscripten_stack_alloc)(e)},ur=function(){return(ur=er.emscripten_stack_get_current)()};function cr(){var e;or(),L(!(3&(e=ir()))),0==e&&(e+=4),x[e>>2]=34821223,x[e+4>>2]=2310721022,x[0]=1668509029}function lr(){function e(){rr||(rr=!0,d.calledRun=!0,I||(L(!$),$=!0,R(),d.noFSInit||Ce.init.initialized||Ce.init(),Ce.ignorePermissions=!1,ce(B),n(d),d.onRuntimeInitialized&&d.onRuntimeInitialized(),L(!d._main,'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'),function(){if(R(),d.postRun)for("function"==typeof d.postRun&&(d.postRun=[d.postRun]);d.postRun.length;)e=d.postRun.shift(),j.unshift(e);var e;ce(j)}()))}W>0||(cr(),function(){if(d.preRun)for("function"==typeof d.preRun&&(d.preRun=[d.preRun]);d.preRun.length;)e=d.preRun.shift(),U.unshift(e);var e;ce(U)}(),W>0||(d.setStatus?(d.setStatus("Running..."),setTimeout((function(){setTimeout((function(){d.setStatus("")}),1),e()}),1)):e(),R()))}if(d.dynCall_jiji=re("dynCall_jiji",5),d.dynCall_iiiiij=re("dynCall_iiiiij",7),d.dynCall_jiiij=re("dynCall_jiiij",6),d._ff_h264_cabac_tables=113148,d.run=lr,d.ccall=Ve,d.cwrap=function(e,r,t,n){return function(){for(var n=arguments.length,o=new Array(n),i=0;i0;)d.preInit.pop()();lr(),r=p;for(var dr,fr=l(Object.keys(d));!(dr=fr()).done;)t();return r});"object"===u(r)&&"object"===u(e)&&(e.exports=p)}(t,t.exports);var n,o,i,a,s=r(t.exports),u="wasmLoading",c="wasmLoaded",l="wasmFailed",d="registerWasmPlayer",f="videoCallback",p="decodeCodecContext",m="destroy",h="demuxTsStream",g="demuxCoreReceive",v="readPacket",E="readPacketEnd",y="mediaInfo",w=function(e,r){return{cmd:e,data:r}},b=(n="undefined"!=typeof self?self:window,o={navigator:void 0!==n.navigator?n.navigator:{userAgent:""},infoMap:{engine:["WebKit","Trident","Gecko","Presto"],browser:["Safari","Chrome","Edge","IE","Firefox","Firefox Focus","Chromium","Opera","Vivaldi","Yandex","Arora","Lunascape","QupZilla","Coc Coc","Kindle","Iceweasel","Konqueror","Iceape","SeaMonkey","Epiphany","360","360SE","360EE","UC","QQBrowser","QQ","Baidu","Maxthon","Sogou","LBBROWSER","2345Explorer","TheWorld","XiaoMi","Quark","Qiyu","Wechat","Taobao","Alipay","Weibo","Douban","Suning","iQiYi"],os:["Windows","Linux","Mac OS","Android","Ubuntu","FreeBSD","Debian","iOS","Windows Phone","BlackBerry","MeeGo","Symbian","Chrome OS","WebOS"],device:["Mobile","Tablet","iPad"]}},i={getMatchMap:function(e){return{Trident:e.indexOf("Trident")>-1||e.indexOf("NET CLR")>-1,Presto:e.indexOf("Presto")>-1,WebKit:e.indexOf("AppleWebKit")>-1,Gecko:e.indexOf("Gecko/")>-1,Safari:e.indexOf("Safari")>-1,Chrome:e.indexOf("Chrome")>-1||e.indexOf("CriOS")>-1,IE:e.indexOf("MSIE")>-1||e.indexOf("Trident")>-1,Edge:e.indexOf("Edge")>-1,Firefox:e.indexOf("Firefox")>-1||e.indexOf("FxiOS")>-1,"Firefox Focus":e.indexOf("Focus")>-1,Chromium:e.indexOf("Chromium")>-1,Opera:e.indexOf("Opera")>-1||e.indexOf("OPR")>-1,Vivaldi:e.indexOf("Vivaldi")>-1,Yandex:e.indexOf("YaBrowser")>-1,Arora:e.indexOf("Arora")>-1,Lunascape:e.indexOf("Lunascape")>-1,QupZilla:e.indexOf("QupZilla")>-1,"Coc Coc":e.indexOf("coc_coc_browser")>-1,Kindle:e.indexOf("Kindle")>-1||e.indexOf("Silk/")>-1,Iceweasel:e.indexOf("Iceweasel")>-1,Konqueror:e.indexOf("Konqueror")>-1,Iceape:e.indexOf("Iceape")>-1,SeaMonkey:e.indexOf("SeaMonkey")>-1,Epiphany:e.indexOf("Epiphany")>-1,360:e.indexOf("QihooBrowser")>-1||e.indexOf("QHBrowser")>-1,"360EE":e.indexOf("360EE")>-1,"360SE":e.indexOf("360SE")>-1,UC:e.indexOf("UC")>-1||e.indexOf(" UBrowser")>-1,QQBrowser:e.indexOf("QQBrowser")>-1,QQ:e.indexOf("QQ/")>-1,Baidu:e.indexOf("Baidu")>-1||e.indexOf("BIDUBrowser")>-1,Maxthon:e.indexOf("Maxthon")>-1,Sogou:e.indexOf("MetaSr")>-1||e.indexOf("Sogou")>-1,LBBROWSER:e.indexOf("LBBROWSER")>-1,"2345Explorer":e.indexOf("2345Explorer")>-1,TheWorld:e.indexOf("TheWorld")>-1,XiaoMi:e.indexOf("MiuiBrowser")>-1,Quark:e.indexOf("Quark")>-1,Qiyu:e.indexOf("Qiyu")>-1,Wechat:e.indexOf("MicroMessenger")>-1,Taobao:e.indexOf("AliApp(TB")>-1,Alipay:e.indexOf("AliApp(AP")>-1,Weibo:e.indexOf("Weibo")>-1,Douban:e.indexOf("com.douban.frodo")>-1,Suning:e.indexOf("SNEBUY-APP")>-1,iQiYi:e.indexOf("IqiyiApp")>-1,Windows:e.indexOf("Windows")>-1,Linux:e.indexOf("Linux")>-1||e.indexOf("X11")>-1,"Mac OS":e.indexOf("Macintosh")>-1,Android:e.indexOf("Android")>-1||e.indexOf("Adr")>-1,Ubuntu:e.indexOf("Ubuntu")>-1,FreeBSD:e.indexOf("FreeBSD")>-1,Debian:e.indexOf("Debian")>-1,"Windows Phone":e.indexOf("IEMobile")>-1||e.indexOf("Windows Phone")>-1,BlackBerry:e.indexOf("BlackBerry")>-1||e.indexOf("RIM")>-1,MeeGo:e.indexOf("MeeGo")>-1,Symbian:e.indexOf("Symbian")>-1,iOS:e.indexOf("like Mac OS X")>-1,"Chrome OS":e.indexOf("CrOS")>-1,WebOS:e.indexOf("hpwOS")>-1,Mobile:e.indexOf("Mobi")>-1||e.indexOf("iPh")>-1||e.indexOf("480")>-1,Tablet:e.indexOf("Tablet")>-1||e.indexOf("Nexus 7")>-1,iPad:e.indexOf("iPad")>-1}},matchInfoMap:function(e){var r,t=(null==(r=o.navigator)?void 0:r.userAgent)||"",n=i.getMatchMap(t);for(var a in o.infoMap)for(var s=0;s36&&n.showModalDialog?s=!0:+u>45&&(s=t("type","application/vnd.chromium.remoting-viewer"))}if(a.Baidu&&a.Opera&&(a.Baidu=!1),a.Mobile&&(a.Mobile=!r.includes("iPad")),s&&(t("type","application/gameplugin")||o.navigator&&void 0===o.navigator.connection.saveData?a["360SE"]=!0:a["360EE"]=!0),a.IE||a.Edge)switch(window.screenTop-window.screenY){case 71:case 74:case 99:case 75:case 105:break;case 102:a["360EE"]=!0;break;case 104:a["360SE"]=!0}var c={Safari:function(){return r.replace(/^.*Version\/([\d.]+).*$/,"$1")},Chrome:function(){return r.replace(/^.*Chrome\/([\d.]+).*$/,"$1").replace(/^.*CriOS\/([\d.]+).*$/,"$1")},IE:function(){return r.replace(/^.*MSIE ([\d.]+).*$/,"$1").replace(/^.*rv:([\d.]+).*$/,"$1")},Edge:function(){return r.replace(/^.*Edge\/([\d.]+).*$/,"$1")},Firefox:function(){return r.replace(/^.*Firefox\/([\d.]+).*$/,"$1").replace(/^.*FxiOS\/([\d.]+).*$/,"$1")},"Firefox Focus":function(){return r.replace(/^.*Focus\/([\d.]+).*$/,"$1")},Chromium:function(){return r.replace(/^.*Chromium\/([\d.]+).*$/,"$1")},Opera:function(){return r.replace(/^.*Opera\/([\d.]+).*$/,"$1").replace(/^.*OPR\/([\d.]+).*$/,"$1")},Vivaldi:function(){return r.replace(/^.*Vivaldi\/([\d.]+).*$/,"$1")},Yandex:function(){return r.replace(/^.*YaBrowser\/([\d.]+).*$/,"$1")},Arora:function(){return r.replace(/^.*Arora\/([\d.]+).*$/,"$1")},Lunascape:function(){return r.replace(/^.*Lunascape[\/\s]([\d.]+).*$/,"$1")},QupZilla:function(){return r.replace(/^.*QupZilla[\/\s]([\d.]+).*$/,"$1")},"Coc Coc":function(){return r.replace(/^.*coc_coc_browser\/([\d.]+).*$/,"$1")},Kindle:function(){return r.replace(/^.*Version\/([\d.]+).*$/,"$1")},Iceweasel:function(){return r.replace(/^.*Iceweasel\/([\d.]+).*$/,"$1")},Konqueror:function(){return r.replace(/^.*Konqueror\/([\d.]+).*$/,"$1")},Iceape:function(){return r.replace(/^.*Iceape\/([\d.]+).*$/,"$1")},SeaMonkey:function(){return r.replace(/^.*SeaMonkey\/([\d.]+).*$/,"$1")},Epiphany:function(){return r.replace(/^.*Epiphany\/([\d.]+).*$/,"$1")},360:function(){return r.replace(/^.*QihooBrowser\/([\d.]+).*$/,"$1")},"360SE":function(){return{63:"10.0",55:"9.1",45:"8.1",42:"8.0",31:"7.0",21:"6.3"}[+r.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"360EE":function(){return{69:"11.0",63:"9.5",55:"9.0",50:"8.7",30:"7.5"}[+r.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},Maxthon:function(){return r.replace(/^.*Maxthon\/([\d.]+).*$/,"$1")},QQBrowser:function(){return r.replace(/^.*QQBrowser\/([\d.]+).*$/,"$1")},QQ:function(){return r.replace(/^.*QQ\/([\d.]+).*$/,"$1")},Baidu:function(){return r.replace(/^.*BIDUBrowser[\s\/]([\d.]+).*$/,"$1")},UC:function(){return r.replace(/^.*UC?Browser\/([\d.]+).*$/,"$1")},Sogou:function(){return r.replace(/^.*SE ([\d.X]+).*$/,"$1").replace(/^.*SogouMobileBrowser\/([\d.]+).*$/,"$1")},LBBROWSER:function(){return{57:"6.5",49:"6.0",46:"5.9",42:"5.3",39:"5.2",34:"5.0",29:"4.5",21:"4.0"}[+navigator.userAgent.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"2345Explorer":function(){return r.replace(/^.*2345Explorer\/([\d.]+).*$/,"$1")},TheWorld:function(){return r.replace(/^.*TheWorld ([\d.]+).*$/,"$1")},XiaoMi:function(){return r.replace(/^.*MiuiBrowser\/([\d.]+).*$/,"$1")},Quark:function(){return r.replace(/^.*Quark\/([\d.]+).*$/,"$1")},Qiyu:function(){return r.replace(/^.*Qiyu\/([\d.]+).*$/,"$1")},Wechat:function(){return r.replace(/^.*MicroMessenger\/([\d.]+).*$/,"$1")},Taobao:function(){return r.replace(/^.*AliApp\(TB\/([\d.]+).*$/,"$1")},Alipay:function(){return r.replace(/^.*AliApp\(AP\/([\d.]+).*$/,"$1")},Weibo:function(){return r.replace(/^.*weibo__([\d.]+).*$/,"$1")},Douban:function(){return r.replace(/^.*com.douban.frodo\/([\d.]+).*$/,"$1")},Suning:function(){return r.replace(/^.*SNEBUY-APP([\d.]+).*$/,"$1")},iQiYi:function(){return r.replace(/^.*IqiyiVersion\/([\d.]+).*$/,"$1")}};return e.browserVersion="",c[e.browser]&&(e.browserVersion=c[e.browser](),e.browserVersion==r&&(e.browserVersion="")),"Edge"==e.browser&&(e.engine="EdgeHTML"),"Chrome"==e.browser&&parseInt(e.browserVersion)>27&&(e.engine="Blink"),"Opera"==e.browser&&parseInt(e.browserVersion)>12&&(e.engine="Blink"),"Yandex"==e.browser&&(e.engine="Blink"),e.browser+" (version: "+e.browserVersion+"; kernel: "+e.engine+")"}},a={DeviceInfoObj:function(e){var r,t=function(r){var t;null==(t=e.info)||t.forEach((function(e){e.toLowerCase()===r.toLowerCase()&&(s[r]=a[r])}))};e=e||{domain:""};var a={deviceType:i.getDeviceType(),OS:i.getOS(),OSVersion:i.getOSVersion(),sh:n.screen.height,sw:n.screen.width,lang:i.getLanguage(),netWork:i.getNetwork(),orientation:i.getOrientationStatu(),browserInfo:i.getBrowserInfo(),fingerprint:i.createFingerprint(e.domain),userAgent:null==(r=o.navigator)?void 0:r.userAgent};if(!e.info||0===e.info.length)return a;var s={};for(var u in a)t(u);return s}},{getDeviceInfo:function(e){return a.DeviceInfoObj(e)}}),_=function(){function e(){}return e.add=function(r,t){e.queues.push({url:r,data:t})},e.fire=function(){if(e.queues&&0!==e.queues.length){e.isStop=!1;var r=e.queues[0];r.url&&e.api.report(r.data),e.queues.splice(0,1),e.fire()}else e.isStop=!0},e}();_.isStop=!0,_.queues=[];var S=function(){function e(e){this.url=e}var r=e.prototype;return r.report=function(e){this.checkUrl(this.url)&&this.sendInfo(e)},r.sendInfo=function(e){navigator.sendBeacon?this.sendBeacon(this.url,e):this.sendImage(this.url,e)},r.sendImage=function(e,r){var t=this.changeJSON2Query(r),n=new Image;n.onload=n.onerror=function(){n=null},n.src=e+"?"+t+"&random="+Math.random()},r.sendBeacon=function(e,r){try{navigator.sendBeacon(e,this.formatParamsByURLSearchParams(r))}catch(e){}},r.formatParamsByURLSearchParams=function(e){var r=new URLSearchParams;for(var t in e)"object"==typeof e[t]&&(e[t]=JSON.stringify(e[t])),r.append(t,e[t]);return r},r.changeJSON2Query=function(e){var r="";for(var t in e){""!=r&&(r+="&");var n=e[t];r+=t+"="+encodeURIComponent("object"==typeof n?JSON.stringify(n):n)}return r},r.checkUrl=function(e){return!!e&&/^[hH][tT][tT][pP]([sS]?):\/\//.test(e)},e}();function O(){return O=Object.assign||function(e){for(var r=1;r0&&(r._free(l),l=null),{};var d=r.HEAPU8.subarray(l,l+c);s.sps=new Uint8Array(c),null==(n=s.sps)||n.set(d,0);var f=r.cwrap("getPPSLen","number",[])(),p=r.cwrap("getPPS","number",[])(),m=r.HEAPU8.subarray(p,p+f);s.pps=new Uint8Array(f),null==(o=s.pps)||o.set(m,0);var h=r.cwrap("getSEILen","number",[])(),g=r.cwrap("getSEI","number",[])(),v=r.HEAPU8.subarray(g,g+h);s.sei=new Uint8Array(h),null==(i=s.sei)||i.set(v,0);var E=r.cwrap("getVLCLen","number",[])(),y=r.cwrap("getVLC","number",[])(),w=r.HEAPU8.subarray(y,y+E);if(u.vlc=new Uint8Array(E),null==(a=u.vlc)||a.set(w,0),(null==t?void 0:t.vCodec)===e.DEF_HEVC||(null==t?void 0:t.vCodec)===e.DEF_H265){var b,_=r.cwrap("getVPSLen","number",[])(),S=r.cwrap("getVPS","number",[])(),O=r.HEAPU8.subarray(S,S+_);s.vps=new Uint8Array(_),null==(b=s.vps)||b.set(O,0),r._free(O),O=null}try{r._free(l)}catch(e){k.send("worker",{name:"readPacket",free:"spsPtr"})}l=null;try{r._free(d)}catch(e){k.send("worker",{name:"readPacket",free:"spsSubPtr"})}d=null;try{r._free(m)}catch(e){k.send("worker",{name:"readPacket",free:"ppsSubPtr"})}m=null;try{r._free(v)}catch(e){k.send("worker",{name:"readPacket",free:"seiSubPtr"})}v=null;try{r._free(w)}catch(e){k.send("worker",{name:"readPacket",free:"vlcSubPtr"})}return w=null,{nalu:s,vlc:u}};function F(){return F=Object.assign||function(e){for(var r=1;r0?r:e.DEFAULT_SAMPLERATE,sampleChannel:t>=0?t:e.DEFAULT_CHANNEL}:{sampleRate:0,sampleChannel:0,audioNone:!0})))}),"viiddddiiiii"),t._setCodecType(n,0,o,i),t.cwrap("initDecoder","number",["number"])(n);break;case p:var u=s.data,c=u.nalBuf,l=u.pts,b=u.flushDecoder,_=t._malloc(c.length);t.HEAP8.set(c,_);var S=parseInt(1e3*l+"");t._decodeCodecContext(n,_,c.length,S,b),t._free(_),_=null;break;case h:var O=s.data,T=O.buff;O.tsUrl,function(e,r,t,n){null!=M&&(e._free(M),M=null),M=e._malloc(r.length),e.HEAP8.set(r,M);try{var o=e.cwrap("demuxTsStream","number",["number","number","number"])(M,r.length,t);e._free(M),M=null,o>=0&&postMessage(w(g))}catch(e){k.send("worker",{name:"demuxTsStream",msg:e})}}(t,T,n);break;case v:!function(e,r){for(;;){var t=e.cwrap("getPacket","number",[])(),n=e.HEAPU32[t/4],o=e.HEAPU32[t/4+1],i=e.HEAPF64[t/8+1],a=e.HEAPF64[t/8+1+1],s=e.HEAPU32[t/4+1+1+2+2],u=e.HEAPU32[t/4+1+1+2+2+1],c=e.HEAPU8.subarray(u,u+o),l=null,d=[0,1].includes(n);if(d)try{l=P(e,r)}catch(e){}if(!d||o<=0)break;var f=a>0?a:i;f<0||0===t||(self.postMessage(w(v,{type:n,size:o,ptime:i,dtime:a,keyframe:s,data:Array.from(c),pts:f,layer:l})),c=null,l=null,t=null)}postMessage(w(E))}(t,a);break;case m:null!==o&&t.removeFunction(o),o=null,null!==i&&t.removeFunction(i),i=null,t.cwrap("destroy","number",["number"])(n),self.close()}}})).catch((function(e){self.postMessage(w(l,{data:e}))}))})); diff --git a/dist/index.esm.js b/dist/index.esm.js new file mode 100644 index 0000000..aa87c8a --- /dev/null +++ b/dist/index.esm.js @@ -0,0 +1,8 @@ +/* +* +* HlsPlayer.js v0.1.0 +* Copyright (c) 2024-8-1 Ezviz-OpenBiz +* . +* +*/ +import e,{Video as t}from"@ezuikit/player-base";import i from"@ezuikit/utils-collect";import n from"hls.js";import{addVc as s,getStaticPath as r}from"@ezuikit/utils-tools";import o from"@ezuikit/utils-logger";import{merge as a}from"lodash-es";import l from"eventemitter3";var u=1,h=2,c=3,d="aac",p="h265",f="hevc",m="m3u8",v="hls",g=0,y=1,_=600,T=400,w=30,P=40,C=!1,x=44100,S=20,L="ONCE",b="SWAP",R=0,D=265,E=1001,k=1002,M=1003;var A,I=function(){return window.WebAssembly&&"object"==("undefined"==typeof WebAssembly?"undefined":(e=WebAssembly)&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e);var e};function B(){return(new Date).getTime()}var F=window.AudioContext||(null==(A=window)?void 0:A.webkitAudioContext),N=function(){function e(e){var t=this;this.options={sampleRate:e.sampleRate||x,appendType:e.appendType||g,playMode:e.playMode||b,isLive:e.isLive},this.logger=null==e?void 0:e.logger,this.sourceChannel=-1,this.audioCtx=new F({latencyHint:"interactive",sampleRate:e.sampleRate}),this.gainNode=null,this.sourceList=[],this.startStatus=!1,this.sampleQueue=[],this.nextBuffer=null,this.playTimestamp=0,this.playStartTime=0,this.durationMs=-1,this.volume=e.volume||0,this.onLoadCache=null,this.sourceList.push(this.audioCtx.createBufferSource()),this.sourceList.push(this.audioCtx.createBufferSource()),this.sourceList[0].onended=function(){t.swapSource(0,1)},this.sourceList[1].onended=function(){t.swapSource(1,0)},this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.audioCtx.destination),this.runNextBuffer()}var t=e.prototype;return t.resetStartParam=function(){this.playTimestamp=0,this.playStartTime=0},t.setOnLoadCache=function(e){this.onLoadCache=e},t.setDurationMs=function(e){void 0===e&&(e=-1),this.durationMs=e},t.setVolume=function(e){void 0===e&&(e=0),this.volume=e,this.gainNode.gain.value=e},t.getAlignVPTS=function(){return this.playTimestamp+(B()-this.playStartTime)/1e3},t.swapSource=function(e,t){if(void 0===e&&(e=-1),void 0===t&&(t=-1),!this.startStatus)return null;if(e<0||e>=this.sourceList.length)return null;if(t<0||t>=this.sourceList.length)return null;try{this.sourceChannel===e&&null!==this.sourceList[e]&&(this.sourceList[e].disconnect(this.gainNode),this.sourceList[e]=null)}catch(t){this.logger.error("[DEFINE ERROR] this audioCore disconnect source Index:"+e+" error happened!",t)}(this.sourceChannel=t,-2===this.decodeSample(t,e)&&this.options.isLive)&&(this.getAlignVPTS()>=this.durationMs/1e3-.04?this.pause():null==this||this.onLoadCache());return null},t.addSample=function(e){return void 0===e&&(e=null),!(null==e||!e||void 0===e)&&(0===this.sampleQueue.length&&(this.seekPos=null==e?void 0:e.pts),this.sampleQueue.push(e),!0)},t.runNextBuffer=function(){var e=this;window.setInterval((function(){if(!(null!=e.nextBuffer||e.sampleQueue.length=this.sourceList.length)return-1;if(null!=this.sourceList[e]&&void 0!==this.sourceList[e]&&this.sourceList[e]||(this.sourceList[e]=this.audioCtx.createBufferSource(),this.sourceList[e].onended=function(){s.swapSource(e,t)}),0===this.sampleQueue.length)return this.options.isLive?(this.sourceList[e].connect(this.gainNode),this.sourceList[e].startState||null==(n=this.sourceList[e])||null==(i=n.start)||i.call(n),this.sourceList[e].onended=function(){s.swapSource(e,t)},this.sourceList[e].stop(),0):-2;if(this.sourceList[e].buffer)return this.swapSource(e,t),0;if(null==this.nextBuffer||this.nextBuffer.data.length<1){var r,o,a=this.sourceList[e];return a.connect(this.gainNode),(null==a?void 0:a.startState)||null==(o=this.sourceList[e])||null==(r=o.start)||r.call(o),a.startState=!0,a.stop(),1}var l=this.nextBuffer.data.buffer;this.playTimestamp=this.nextBuffer.pts,this.playStartTime=B();try{this.audioCtx.decodeAudioData(l,(function(t){var i,n;null!==s.sourceList[e]&&(s.sourceList[e].buffer=t,s.sourceList[e].connect(s.gainNode),s.sourceList[e].startState||null==(n=s.sourceList[e])||null==(i=n.start)||i.call(n),s.sourceList[e].startState=!0)}),(function(e){s.logger.error("Error audioCore with decoding audio data",e)}))}catch(e){return this.nextBuffer=null,this.logger.log("decodeAudioData error",e),-3}return this.nextBuffer=null,0},t.decodeWholeSamples=function(e){var t=this;if(void 0===e&&(e=-1),this.sourceChannel=e,e<0||e>=this.sourceList.length)return-1;if(null!=this.sourceList[e]&&void 0!==this.sourceList[e]&&this.sourceList[e]||(this.sourceList[e]=this.audioCtx.createBufferSource(),this.sourceList[e].onended=function(){}),0===this.sampleQueue.length)return-2;for(var i=null,n=null,s=0;s",e)}},e}(),O=function(){function e(e){this.limit=e.limit||200,this.logger=null==e?void 0:e.logger,this.yuvCache=[]}var t=e.prototype;return t.appendCacheByCacheYuv=function(e){return this.yuvCache.push(e),this.yuvCache.length>=this.limit?(this.shiftYuv(),h):u},t.getState=function(){return this.yuvCache.length<=0?c:this.yuvCache.length>=this.limit?h:u},t.cleanPipeline=function(){this.yuvCache=[],this.yuvCache.length=0},t.shiftYuv=function(){return this.yuvCache.length<=0?null:this.yuvCache.shift()},e}(),U=function(){function e(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r}return e.prototype.setYuv=function(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r},e}(),$=function(){function e(e){this.gl=e,this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),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)}var t=e.prototype;return t.bind=function(e,t,i){var n=this.gl;n.activeTexture([n.TEXTURE0,n.TEXTURE1,n.TEXTURE2][e]),n.bindTexture(n.TEXTURE_2D,this.texture),n.uniform1i(n.getUniformLocation(t,i),e)},t.fill=function(e,t,i){var n=this.gl;n.bindTexture(n.TEXTURE_2D,this.texture),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,e,t,0,n.LUMINANCE,n.UNSIGNED_BYTE,i)},e}(),W=function(){function e(e,t){this.gl=null,this.gl=e.getContext("webgl")||e.getContext("experimental-webgl"),this.program=this.gl.createProgram();var i=["attribute highp vec4 aVertexPosition;","attribute vec2 aTextureCoord;","varying highp vec2 vTextureCoord;","void main(void) {"," gl_Position = aVertexPosition;"," vTextureCoord = aTextureCoord;","}"].join("\n"),n=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(n,i),this.gl.compileShader(n);var s=["precision highp float;","varying lowp vec2 vTextureCoord;","uniform sampler2D YTexture;","uniform sampler2D UTexture;","uniform sampler2D VTexture;","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",");","void main(void) {"," gl_FragColor = vec4( texture2D(YTexture, vTextureCoord).x, texture2D(UTexture, vTextureCoord).x, texture2D(VTexture, vTextureCoord).x, 1) * YUV2RGB;","}"].join("\n"),r=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(r,s),this.gl.compileShader(r),this.gl.attachShader(this.program,n),this.gl.attachShader(this.program,r),this.gl.linkProgram(this.program),this.gl.useProgram(this.program),this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS);var o=this.gl.getAttribLocation(this.program,"aVertexPosition");this.gl.enableVertexAttribArray(o);var a=this.gl.getAttribLocation(this.program,"aTextureCoord");this.gl.enableVertexAttribArray(a),this.verticesBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.verticesBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(o,3,this.gl.FLOAT,!1,0,0),this.texCoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([1,0,0,0,1,1,0,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,0,0),this.gl.y=new $(this.gl),this.gl.u=new $(this.gl),this.gl.v=new $(this.gl),this.gl.y.bind(0,this.program,"YTexture"),this.gl.u.bind(1,this.program,"UTexture"),this.gl.v.bind(2,this.program,"VTexture")}var t=e.prototype;return t.renderFrame=function(e,t,i,n,s){this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height),this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.y.fill(n,s,e),this.gl.u.fill(n>>1,s>>1,t),this.gl.v.fill(n>>1,s>>1,i),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)},t.destroyContext=function(){try{this.gl.deleteProgram(this.program),this.gl.deleteBuffer(this.verticesBuffer),this.gl.deleteBuffer(this.texCoordBuffer),this.gl.deleteTexture(this.gl.y.texture),this.gl.deleteTexture(this.gl.u.texture),this.gl.deleteTexture(this.gl.v.texture),this.gl=null,this.program=null,this.verticesBuffer=null,this.texCoordBuffer=null}catch(e){}},e}(),V=function(e,t){return{cmd:e,data:t}},j="wasmLoading",Y="wasmLoaded",H="wasmFailed",X="videoCallback",Q="decodeCodecContext",z="destroy",G="demuxTsStream",J="demuxCoreReceive",q="readPacket",K="readPacketEnd",Z="mediaInfo",ee="ezui-hls",te={width:600,height:400,volume:0,retry:20,autoPlay:!0,staticPath:"",isLive:!0,loggerOptions:{name:"HLS",level:"INFO",showTime:!0}},ie={disableContextmenu:!0},ne=function(){function e(e){void 0===e&&(e={}),this.options=Object.assign({},ie,e),this.logger=this.options.logger,this.event=this.options.event,this._classVideo=ee+"-video",this._$container=document.getElementById(this.options.id),this._render()}var i=e.prototype;return i._render=function(){var e,i;if("video"===this.options.nodeName)this.$video=new t(this._$container,this.options).$video;else{var n;if(this.$video=document.createElement(this.options.nodeName),this._$container.innerHTML="",this._$container.appendChild(this.$video),this.options.disableContextmenu)null==(n=this.$video)||n.addEventListener("contextmenu",(function(e){return e.preventDefault(),!1}));this.$video.classList.add(this._classVideo),this.$video.style.cssText+="object-fit: contain; z-index:1;"}null==(i=this.event)||null==(e=i.emit)||e.call(i,"rendered")},i._isVideo=function(){return"VIDEO"===this.$video.nodeName},i.destroy=function(){if(this.$video&&this._$container&&this.$video){try{this._$container.removeChild(this.$video)}catch(e){}this.$video=null}},e}();function se(e,t,i){return t&&function(e,t){for(var i=0;i=1&&(null==(i=e)||null==(t=i.onLoadCacheFinished)||t.call(i),window.clearInterval(e.cacheInterval),e.cacheInterval=null,e.isCaching===k&&e.play(e.playParams),e.isCaching=E)}),40))}},i._playFunc=function(){var e=!1;if(B()-this.calculateStartTime>=this.frameTime-this.preCostTime){e=!0;var t=!0;if(this.calculateStartTime=B(),this.options.audioNone)this.playFrameYUV(t);else{this.fix_poc_err_skip>0&&(this.fix_poc_err_skip--,t=!1);var i=this.videoPTS-this.audio.getAlignVPTS();if(i>0)return void(this.playParams.seekEvent&&!this.options.audioNone&&this.audio.setVolume(0));if(t){if(!(t=-1*i<=1*this.frameTimeSec)){for(var n=parseInt(i/this.frameTimeSec+""),s=0;s",e,n,i),n>=i&&(t.playFrameYUV(!0),i+=1)}),this.frameTime||5)}else(this.videoPTS>=this.playParams.seekPos&&!this.isNewSeek||0===this.playParams.seekPos||0===this.playParams.seekPos)&&(this.frameTime=1e3/this.options.fps,this.frameTimeSec=this.frameTime/1e3,this.options.audioNone||this.audio.play(),this._volume=this.options.audioNone?0:this.audio.volume,this.loop=window.setInterval((function(){var e=B();t._playFunc(),t.preCostTime=B()-e}),this.frameTime||5));return this.setVolume(this._volume),Promise.resolve()},i.stop=function(){this.destroy(),this.stream=new Uint8Array},i.destroy=function(){return void 0!==this.gl&&null!==this.gl&&(this.gl.destroyContext(),this.gl=null),this.endAudio(),this.cacheLoop&&window.clearInterval(this.cacheLoop),this.cacheLoop=null,this.loop&&window.clearInterval(this.loop),this.loop=null,this.pause(),this.decoderWorker.postMessage(V(z)),this.stream=null,this.frameList=null,this.durationMs=-1,this.videoPTS=0,this.isPlaying=!1,this.$video.remove(),!0},i.nextNalu=function(e){if(void 0===e&&(e=1),this.stream.length<=4)return!1;for(var t=-1,i=0;i=this.stream.length){if(-1===t)return!1;var n=this.stream.subarray(t);return this.stream=new Uint8Array,n}var s="0 0 1"===this.stream.slice(0,3).join(" "),r="0 0 0 1"===this.stream.slice(0,4).join(" ");if(s||r){if(-1===t)t=i;else{if(e<=1){var o=this.stream.subarray(t,i);return this.stream=this.stream.subarray(i),o}e-=1}i+=3}}return!1},i.playFrameYUV=function(e){void 0===e&&(e=!1);var t=this.cacheYuvBuf.shiftYuv();if(!t)return this.noCacheFrame+=1,e&&!this.playParams.seekEvent&&this.loadCache(),!1;this.noCacheFrame=0;var i=t.pts;return this.videoPTS=i,this.drawImage(t.width,t.height,t.imageBufferY,t.imageBufferB,t.imageBufferR),t=null,e&&!this.playParams.seekEvent&&this.isPlaying&&this.loadCache(),!0},i.drawImage=function(e,t,i,n,s){this.$video.width===e&&this.$video.height===t||(this.$video.width=e,this.$video.height=t),this.isCheckDisplay||this.checkDisplaySize(e,t);var r=e*t,o=e/2*(t/2),a=new Uint8Array(r+2*o);a.set(i,0),a.set(n,r),a.set(s,r+o),this.gl.renderFrame(i,n,s,e,t),a=null},i.checkDisplaySize=function(e,t){var i,n=e/(null==(i=this.options)?void 0:i.width)>t/this.options.height,s=+(this.options.width/e).toFixed(2),r=+(this.options.height/t).toFixed(2),o=n?s:r,a=this.options.fixed,l=a?this.options.width:parseInt(e*o+""),u=a?this.options.height:parseInt(t*o+"");return this.$video.style.maxWidth="100%",this.$video.style.maxHeight="100%",this.options.width/this.options.height>=1&&l/u>=1?this.$video.style.width="100%":this.$video.style.height="100%",this.isCheckDisplay=!0,[l,u]},i._onWorkerMessage=function(){var e=this;this.decoderWorker.onmessage=function(t){var i=t.data;if(i.cmd===X){var n=i.data,s=n.ptsSec,r=n.strideY,o=n.height;n.width;var a=n.bufY,l=n.bufU,u=n.bufV,h=new U(s,r,o,a,l,u);e.cacheYuvBuf.appendCacheByCacheYuv(h),h=null}}},i.initVideoAndAudio=function(){this.$video.width=this.options.width,this.$video.height=this.options.height,this.gl=new W(this.$video,{preserveDrawingBuffer:!1}),this.options.audioNone||(this.audio=new N({logger:this.logger,sampleRate:this.options.sampleRate,appendType:this.options.appendHevcType,volume:this.options.volume,isLive:this.options.isLive})),this.isPlayLoadingFinish=1},se(t,[{key:"volume",get:function(){var e;return(null==(e=this.audio)?void 0:e.volume)||this._volume},set:function(e){this.setVolume(e)}}]),t}(ne),le=[/#EXT-X-PROGRAM-DATE-TIME.+\n/g],ue={lineDelimiter:/\r?\n/,extensionHeader:"#EXTM3U",tagPrefix:"#EXT",segmentPrefix:"#EXTINF",segmentParse:/^#EXTINF: *([0-9.]+)(, *(.+?)?)?$/,tagParse:/^#EXT-X-([A-Z-]+)(:(.+))?$/,version:"VERSION",allowCache:"ALLOW-CACHE",combined:"COMBINED",endList:"ENDLIST",targetDuration:"TARGETDURATION",mediaSequence:"MEDIA-SEQUENCE",discontinuity:"DISCONTINUITY",streamInf:"STREAM-INF",isComment:function(e){return e&&"#"===e[0]&&!e.startsWith(ue.tagPrefix)},isBlank:function(e){return""===e},canStrip:function(e){return ue.isBlank(e)||ue.isComment(e)},defaultMinDur:99999},he=function(){function e(e){this._retry=10,this.logger=null==e?void 0:e.logger,this.initState=!0,this.controller=new AbortController,this._slices=[],this._type=v,this._preURI="",this.duration=-1,this.onTransportStream=null,this.onFinished=null}var t=e.prototype;return t.destroy=function(){this.initState=!1},t.fetchM3u8=function(e){var t=this,i=this;if(this.initState){var n=function(t){return new Promise((function(i,n){var s=new XMLHttpRequest;s.open("GET",t),s.onload=function(){this.status>=200&&this.status<300&&(t!==this.responseURL?(e=this.responseURL,i(this.responseURL)):i(""))},s.onreadystatechange=function(){4===s.readyState&&200===s.status&&i(s.responseText)},s.onerror=function(){n(new Error("Network error."))},s.send()}))};n(e).then((function(s){if(t._retry=10,i._uriParse(e)){var r=i._m3u8Parse(s);if("number"==typeof r&&r>=0)var o=setTimeout((function(){i.fetchM3u8(e),clearTimeout(o)}),200*r)}return n=null,s})).catch((function(s){if(t.logger.error("[M3u8Base] fetch m3u8 url Error ==> ",s),n=null,t._retry>=1)var r=setTimeout((function(){i.fetchM3u8(e),clearTimeout(r)}),500);t._retry--}))}},t._uriParse=function(e){this._preURI="";var t=e.split("://"),i=null,n=null;if(t.length<1)return this.logger.log("HLS URI ERROR : "+e),!1;t.length>1?(i=t[0],n=t[1].split("/"),this._preURI=i+"://"):n=t[0].split("/");for(var s=0;sc&&(s=c);var d,p=n[o+=1],f=null;if(p.includes("http"))f=p;else{if("/"===p[0]){var v=this._preURI.split("//"),g=v[v.length-1].split("/");this._preURI=v[0]+"//"+g[0]}f=this._preURI+p}if(!this._slices.includes(f))this._slices.push(f),null==this||null==(d=this.onTransportStream)||d.call(this,f,c)}}}this._slices.length>500&&(this._slices=this._slices.slice(-500));var y={type:this._type,duration:-1};return null==this||null==(t=this.onFinished)||t.call(this,y),s},t._readTag=function(e){var t=ue.tagParse.exec(e);return null!==t?{key:t[1],value:t[3]}:null},e}(),ce=function(){function e(e){this.sampleRate=e.sampleRate,this.frameDurMs=Math.floor(1024e3/this.sampleRate),this.frameDurSec=this.frameDurMs/1e3}var t=e.prototype;return t.updateOptions=function(e){this.sampleRate=e.sampleRate,this.frameDurMs=1024e3/this.sampleRate,this.frameDurSec=this.frameDurMs/1e3},t._getPktLen=function(e,t,i){return((3&e)<<11)+(t<<3)+((224&i)>>5)},t.sliceAACFrames=function(e,t){for(var i=[],n=e,s=0;s>4==15){var r=this._getPktLen(t[s+3],t[s+4],t[s+5]);if(r<=0)continue;var o=t.subarray(s,s+r),a=new Uint8Array(r);a.set(o,0),i.push({ptime:n,data:a}),n+=this.frameDurSec,s+=r}else s+=1;return i},e}(),de="M3U8",pe="TS",fe="FETCH",me=function(){function e(){}return e.init=function(t){e.collect=new i(t)},e.send=function(t,i){var n,s;null==(s=e.collect)||null==(n=s.send)||n.call(s,{action:t,logInfo:i})},e.updateParams=function(t){e.collect.updateExtendsInfo(t)},e}();function ve(e,t,i){return t&&function(e,t){for(var i=0;i ",e),s=null})).catch((function(n){var s,r,o,a;t.logger.error("[MpegTsDemux] demuxerTsInit ERROR fetch ERROR ==> ",n),null==(r=t.event)||null==(s=r.emit)||s.call(r,pe,{data:n}),null==(a=t.event)||null==(o=a.emit)||o.call(a,fe,{data:n,type:pe}),null==i||i.onDemuxedFailed(n,e),me.send(100,{url:e,msg:"fetch error"})}))},t._demuxCore=function(e,t){e.length<=0||this.decoderWorker.postMessage(V(G,{buff:e,tsUrl:t}))},t.readMediaInfo=function(){return this.mediaInfo},t.readAudioNone=function(){var e;return null==(e=this.mediaInfo)?void 0:e.audioNone},t.isHEVC=function(){return this.mediaInfo.vCodec===f||this.mediaInfo.vCodec===p},t.destroy=function(){this.controller&&this.controller.abort(),this.controller=null,this.mediaInfo=null,this.aacDec=null},t._onWorkerMessage=function(){var e=this;e.logger.log("[demuxer] register _onWorkerMessage"),e.decoderWorker.addEventListener("message",(function(t){var i=t.data;switch(i.cmd){case Z:var n,s;if(e.mediaInfo=i.data,e.mediaInfo)null==(s=e.event)||null==(n=s.emit)||n.call(s,"mediaInfo",e.mediaInfo);break;case J:var r;if(e.mediaInfo.vCodec)null==e.aacDec?e.aacDec=new ce(e.mediaInfo):e.aacDec.updateOptions(e.mediaInfo),null==e||null==(r=e.onDemuxed)||r.call(e)}}))},ve(e,[{key:"vCodec",get:function(){return this.mediaInfo.vCodec}}]),e}(),_e=function(){function e(e,t,i,n){this.pts=e,this.dts=e,this.isKey=t,this.data=i,this.video=n}return e.prototype.setFrame=function(e,t,i,n){this.pts=e,this.isKey=t,this.data=i,this.video=n},e}(),Te=function(){function e(e){this.logger=null==e?void 0:e.logger,this.event=null==e?void 0:e.event,this.decoderWorker=e.decoderWorker,this.m3u8Base=new he(e),this.mpegTsDemux=new ye(e),this.tsList=[],this._startTime=0,this._aStartTime=0,this.lockWait={state:!1,lockMember:{dur:0}},this._timerFeed=null,this.seekPos=-1,this.vPreFramePTS=0,this.aPreFramePTS=0,this.audioNone=!1,this.isHevcParam=!1,this.vCodec="",this.aCodec=null,this.aChannel=0,this.durationMs=-1,this.fps=-1,this.sampleRate=-1,this.size={width:-1,height:-1},this.mediaInfo=null,this._onWorkerMessage(),this.onReadyOBJ=null,this.onFinished=null,this.onDemuxed=null,this.onSamples=null,this.onCacheProcess=null}var t=e.prototype;return t.getCachePTS=function(){return Math.max(this.vPreFramePTS,this.aPreFramePTS)},t.demux=function(e){var t=this,i=this;this.vPreFramePTS=0,this.aPreFramePTS=0,this.m3u8Base.onTransportStream=function(e,t){i.tsList.push({streamURI:e,streamDur:t}),i.lockWait.state=!1},this.m3u8Base.onFinished=function(e){var t;e.type===m?i.durationMs=1e3*e.duration:i.durationMs=-1,null==i||null==(t=i.onFinished)||t.call(i,i.onReadyOBJ,e)},this.mpegTsDemux.onDemuxedFailed=function(e,n){t.logger.error("[M3u8] onDemuxedFailed: ",e,n),i.lockWait.state=!1},this.mpegTsDemux.onDemuxed=function(){var e;t.logger.log("[M3u8] onDemuxed"),null==i.mediaInfo&&(i.mediaInfo=i.mpegTsDemux.readMediaInfo(),t.logger.log("[M3u8] mediaInfo: ",i.mediaInfo),i.isHevcParam=i.mpegTsDemux.isHEVC(),i.vCodec=i.mpegTsDemux.vCodec,i.aCodec=i.mediaInfo.aCodec,i.aChannel=i.mediaInfo.sampleChannel,i.fps=i.mediaInfo.fps,i.sampleRate=i.mediaInfo.sampleRate,(null===i.aCodec||""===i.aCodec||i.aChannel<=0)&&(i.audioNone=!0),i.mediaInfo.width>0&&i.mediaInfo.height>0&&(t.size.width=t.mediaInfo.width,t.size.height=t.mediaInfo.height)),null==i||null==(e=i.onDemuxed)||e.call(i,i.onReadyOBJ),i.mpegTsDemux&&t.decoderWorker.postMessage(V(q))},this.mpegTsDemux.onReady=function(){i._fetchM3u8AndIntervalTs(e)},this._timerTsWasm=window.setInterval((function(){1===Ae.__HLS_WASM_DecoderState__&&(i._fetchM3u8AndIntervalTs(e),window.clearInterval(i._timerTsWasm),i._timerTsWasm=null)}),500)},t._fetchM3u8AndIntervalTs=function(e){var t=this,i=this;this.logger.log("[M3u8] start fetch m3u8 url"),i.m3u8Base.fetchM3u8(e),i._timerFeed=window.setInterval((function(){if(i.tsList.length>0&&!i.lockWait.state)try{var e=i.tsList.shift();if(null!=e){var n=e.streamURI,s=e.streamDur;i.lockWait.state=!0,i.lockWait.lockMember.dur=+s,i.mpegTsDemux.demuxURL(n)}else t.logger.error("[M3u8] onTsReady need wait ")}catch(e){var r,o,a,l;t.logger.error("[M3u8] onTsReady ERROR:",e),null==(o=t.event)||null==(r=o.emit)||r.call(o,de,{data:e}),null==(l=t.event)||null==(a=l.emit)||a.call(l,fe,{data:e,type:de}),i.lockWait.state=!1}}),50)},t.destroy=function(){var e;this.m3u8Base&&(null==(e=this.m3u8Base)||e.destroy(),this.m3u8Base=null);this._timerFeed&&(window.clearInterval(this._timerFeed),this._timerFeed=null),this.mpegTsDemux&&(this.mpegTsDemux.destroy(),this.mpegTsDemux=null)},t.bindReady=function(e){this.onReadyOBJ=e},t.getACodec=function(){return this.aCodec},t.getVCodec=function(){return this.vCodec},t.getDurationMs=function(){return this.durationMs},t.getFPS=function(){return this.fps},t.getSampleRate=function(){return this.sampleRate},t.getSampleChannel=function(){return this.aChannel},t.getSize=function(){return this.size},t._onWorkerMessage=function(){this.logger.log("[M3U8] register _onWorkerMessage");var e=this;e.decoderWorker.addEventListener("message",(function(t){var i=t.data;switch(i.cmd){case q:var n,s=i.data,r=s.type,o=s.pts,a=s.ptime,l=s.keyframe,u=s.data,h=s.layer;if(u=new Uint8Array(u),1===r&&e.mpegTsDemux.mediaInfo.aCodec===d&&(u=e.mpegTsDemux.aacDec.sliceAACFrames(a,u)),0===r){var c=function(e){var t=e.nalu,i=e.vlc.vlc;null==t.vps&&(t.vps=new Uint8Array);var n=new Uint8Array(t.vps.length+t.sps.length+t.pps.length+t.sei.length+i.length);return n.set(t.vps,0),n.set(t.sps,t.vps.length),n.set(t.pps,t.vps.length+t.sps.length),n.set(t.sei,t.vps.length+t.sps.length+t.pps.length),n.set(i,t.vps.length+t.sps.length+t.pps.length+t.sei.length),n}(h),p=o,f=new _e(p,1===l,c,!0);e.vPreFramePTS=p,null==e||e.onSamples(e.onReadyOBJ,f)}else if(1===r){var m;if("aac"===(null==(m=e.mediaInfo)?void 0:m.aCodec)){for(var v=u,g=0;g0&&(e.$video.volume=e._options.volume)}),1e3)})),e.event.emit("parsed")}))}))}else if(this.$video.canPlayType("application/vnd.apple.mpegurl")){this.logger.log("Browser support application/vnd.apple.mpegurl : ",this.$video.canPlayType("application/vnd.apple.mpegurl")),this.$video.src=this._options.url;var i=!1;this.$video.addEventListener("canplay",(function(){!i&&e._options.autoPlay&&setTimeout((function(){e.$video.play().then((function(){e.logger.log("autoPlay video!"),setTimeout((function(){e._options.volume>0&&e.setVolume(e._options.volume)}),1e3),i=!0}))}),200)}))}else this.logger.warn("Browser not support hls")},i.isPlayingState=function(){return!this.$video.paused},i.play=function(){if(this.isPlayingState())return Promise.resolve();if(this._options.isLive&&(this.$video.buffered.length>=1&&this.$video.buffered.end(0)>1)){var e=this.$video.buffered.end(0)-1;this.$video.currentTime=e}return this.$video.play()},i.pause=function(){this.$video.pause()},i.setVolume=function(e){this.$video.muted&&(this.$video.muted=!1),this._volume=+(e||0),0===this._volume&&(this.$video.muted=!0),this.$video.volume=this._volume},i.destroy=function(){this.$video&&this.$video.pause(),this._hls&&(this._hls.destroy(),this._hls=null),e.prototype.destroy.call(this)},i._onEvent=function(){var e;(e=this).$video&&(e.$video.addEventListener("canplay",(function(){e.event.emit("canplay")})),e.$video.addEventListener("loadeddata",(function(){e.event.emit("loadeddata")})),e.$video.addEventListener("volumechange",(function(){e.event.emit("volumechange",{data:e.$video.volume})})),e.$video.addEventListener("waiting",(function(){e.event.emit("waiting")})),e.$video.addEventListener("timeupdate",(function(){var t;null==(t=e.event)||t.emit("timeupdate")})),e.$video.addEventListener("seeking",(function(){e.event.emit("seeking",{data:e.$video.currentTime})})),e.$video.addEventListener("seeked",(function(){e.event.emit("seeked")})),e.$video.addEventListener("abort",(function(){e.event.emit("abort")})),e.$video.addEventListener("error",(function(){var t;null==(t=e.event)||t.emit("error",{data:e.$video.error})})),e.$video.addEventListener("ended",(function(){e.event.emit("ended")})))},we(t,[{key:"volume",get:function(){return this._volume},set:function(e){this.setVolume(e)}}]),t}(ne);var Se="wasm_loaded",Le="wasm_failed",be="init";function Re(e,t){return Re=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Re(e,t)}var De=function(e){function t(t){var i;return void 0===t&&(t={}),i=e.call(this,t)||this,t.url=s(null==t?void 0:t.url,["h264","h265"]),function(e,t){if(((null==t?void 0:t.volume)||0)>1?e._volume=1:((null==t?void 0:t.volume)||0)<=0?e._volume=0:e._volume=+((null==t?void 0:t.volume)||0),t.volume=e._volume,e.options=a({},te,t),"string"!=typeof e.options.id)throw new Error("id is required!");e.logger=o(e.options.loggerOptions),e.event=new l,e.logger.log("HlsPlayer version: ",Ae.version),e.logger.log("HlsPlayer options: ",e.options),e.options.logger=e.logger}(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(i),t),i._containerClassName=ee+"-container",i._render(),i}!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&Re(e,t)}(t,e);var i=t.prototype;return i._render=function(){this.$container.classList.add(this._containerClassName)},i.destroy=function(){this.$container&&(this.$container.classList.remove(this._containerClassName),this.$container.innerHTML="",this.$container=null)},t}(e);function Ee(e,t,i){return t&&function(e,t){for(var i=0;i0&&(e=!0),this.playParam={durationMs:0,fps:0,sampleRate:0,size:{width:0,height:0},audioNone:e,videoCodec:R},!I())throw new Error("Browser not support WebAssembly!");this._onWorkerMessage()},i.play=function(){if(me.send(1,{name:"play"}),null===this.player)return Promise.resolve();if(this.playParam.videoCodec===R){var e={seekPos:0,isLive:this.options.isLive,accurateSeek:!0,seekEvent:!1,realPlay:!0};return this.player.play(e)}return this.player.play()},i.pause=function(){return me.send(1,{name:"pause"}),null!==this.player&&(this.player.pause(),!0)},i.destroy=function(){var t,i;return me.send(1,{name:"destroy"}),void 0!==this.player&&null!==this.player&&(this.playParam.videoCodec===R&&this._m3u8Obj&&(this._m3u8Obj.destroy(),this._m3u8Obj=null),this.player.destroy(),this._decoderWorker&&(this._decoderWorker.postMessage(V(z)),this._decoderWorker.terminate(),this._decoderWorker=null),this.logger.log("destroy"),null==(i=this.event)||null==(t=i.emit)||t.call(i,"destroy"),this.player=null,e.prototype.destroy.call(this),!0)},i.isPlaying=function(){return null!==this.player&&this.player.isPlayingState()},i.setVolume=function(e){var t;(e=+e)>1||e<0?this.logger.warn("volume volume value 0.0 ~ 1.0!"):((t=this).player||(t.event.emit("playerIsNull"),t.logger.warn("Player instance does not exist!"),0))&&(this.player.setVolume(e),this.event.emit("volumeChange",{data:e}))},i.getVersion=function(){return me.send(1,{name:"getVersion"}),"0.1.0"},i._m3u8Entry=function(){var e=this;this._m3u8Obj=new Te({logger:this.logger,decoderWorker:this._decoderWorker,event:this.event}),this._m3u8Obj.bindReady(this),this._m3u8Obj.onFinished=function(e,t){},this._m3u8Obj.onCacheProcess=function(t){e.options.isLive||null==e.onCacheProcess||e.onCacheProcess.call(e,t)},this._m3u8Obj.onDemuxed=this._checkPlayer.bind(this),this._m3u8Obj.onSamples=this._hlsOnSamples.bind(this),this._m3u8Obj.demux(this.url)},i._checkPlayer=function(e,t){var i=this;if(null==i.player){var n,s,r;if(!(null==i||null==(n=i._m3u8Obj)?void 0:n.isHevcParam)||t)return null==i||null==(r=i._m3u8Obj)||null==(s=r.destroy)||s.call(r),i._m3u8Obj=null,this._decoderWorker.terminate(),this._decoderWorker=null,void(i.player=new xe(ke({},this.options,{event:this.event,logger:this.logger})));var o=i._m3u8Obj.getACodec(),a=i._m3u8Obj.getFPS(),l=i._m3u8Obj.getSampleRate(),u=i._m3u8Obj.getSize(),h=!1;h=i._m3u8Obj.getSampleChannel()<=0||""===o,i._softPlayer(0,a,l,u,h)}},i._hlsOnSamples=function(e,t){var i,n,s,r=this;if(t.video)null==(s=r.player)||null==(n=s.appendHevcFrame)||n.call(s,t);else if(!(null==(i=r._m3u8Obj)?void 0:i.audioNone)){var o,a;null==(a=r.player)||null==(o=a.appendAACFrame)||o.call(a,t)}},i._onWorkerMessage=function(){var e=this,i=this;this._decoderWorker.onmessage=function(n){var s=n.data;switch(s.cmd){case j:t.__HLS_WASM_DecoderState__=0;break;case Y:t.__HLS_WASM_DecoderState__=1,e.logger.log("Wasm already init over!"),i.event.emit(Se),i._decoderWorker.postMessage(V("registerWasmPlayer")),i._m3u8Entry();break;case H:t.__HLS_WASM_DecoderState__=-1,e.logger.error("Wasm init failed!",s),i.event.emit(Le,s),me.send("wasm",{name:"wasm loading failed"}),i._checkPlayer(!0)}}},i._softPlayer=function(e,t,i,n,s,r){var o,a,l=this;void 0===s&&(s=!1),void 0===r&&(r=null);var u,h=this;(this.playParam.durationMs=e,this.playParam.fps=t,this.playParam.sampleRate=i,this.playParam.size=n,this.playParam.audioNone=s,this.playParam.videoCodec=r||R,this.logger.log("this.playParam: ",this.playParam),this.logger.log("start init soft player"),this.player=new ae(ke({},h.options,{sampleRate:i,fps:t,appendHevcType:y,fixed:!1,id:this.options.id,audioNone:s,videoCodec:r,logger:this.logger,event:this.event,decoderWorker:this._decoderWorker})),this.player.onPlayingTime=function(e){var t;null==h||null==(t=h.onPlayTime)||t.call(h,e)},this.player.onPlayingFinish=function(){var e,t;(l.pause(),null!=l.onPlayFinish)&&(null==(t=l)||null==(e=t.onPlayFinish)||e.call(t))},this.player.onLoadCache=function(){var e,t;null==(t=l)||null==(e=t.onLoadCache)||e.call(t)},this.player.onLoadCacheFinished=function(){var e,t;null==(t=l)||null==(e=t.onLoadCacheFinished)||e.call(t)},null==(o=h.player)||o.setDurationMs(e),null==(a=h.player)||a.setFrameRate(t),null!=h.onReadyShowDone)&&(null==h||null==(u=h.onReadyShowDone)||u.call(h));this.event.emit("parsed"),this.player&&this.options.autoPlay&&this.play()},t.supportType=function(e){if(me.send(1,{name:"supportType",options:e}),"hls"===e.type)return!0;if(e.url){var t=e.url;t.startsWith("http://")||t.startsWith("https://")||(t=/^\/\//.test(t)?"http:"+t:location.origin+location.pathname+t);try{return/\.m3u8$/i.test(new URL(t).pathname)}catch(e){}}return!1},Ee(t,[{key:"volume",get:function(){return this.player?this.player.volume:this.options.volume},set:function(e){e=+e,this.setVolume(e)}}]),t}(De);Ae.__HLS_WASM_DecoderState__=0,Ae.version="0.1.0";export{Ae as default}; diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..7cc4cad --- /dev/null +++ b/dist/index.js @@ -0,0 +1,8 @@ +/* +* +* HlsPlayer.js v0.1.0 +* Copyright (c) 2024-8-1 Ezviz-OpenBiz +* . +* +*/ +"use strict";var e=require("@ezuikit/player-base"),t=require("@ezuikit/utils-collect"),i=require("hls.js"),n=require("@ezuikit/utils-tools"),s=require("@ezuikit/utils-logger"),r=require("lodash-es"),o=require("eventemitter3"),a=1,l=2,u=3,h="aac",c="h265",d="hevc",p="m3u8",f="hls",m=0,v=1,g=600,y=400,_=30,T=40,P=!1,w=44100,C=20,x="ONCE",S="SWAP",L=0,b=265,R=1001,D=1002,E=1003;var k,M=function(){return window.WebAssembly&&"object"==("undefined"==typeof WebAssembly?"undefined":(e=WebAssembly)&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e);var e};function A(){return(new Date).getTime()}var I=window.AudioContext||(null==(k=window)?void 0:k.webkitAudioContext),B=function(){function e(e){var t=this;this.options={sampleRate:e.sampleRate||w,appendType:e.appendType||m,playMode:e.playMode||S,isLive:e.isLive},this.logger=null==e?void 0:e.logger,this.sourceChannel=-1,this.audioCtx=new I({latencyHint:"interactive",sampleRate:e.sampleRate}),this.gainNode=null,this.sourceList=[],this.startStatus=!1,this.sampleQueue=[],this.nextBuffer=null,this.playTimestamp=0,this.playStartTime=0,this.durationMs=-1,this.volume=e.volume||0,this.onLoadCache=null,this.sourceList.push(this.audioCtx.createBufferSource()),this.sourceList.push(this.audioCtx.createBufferSource()),this.sourceList[0].onended=function(){t.swapSource(0,1)},this.sourceList[1].onended=function(){t.swapSource(1,0)},this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.audioCtx.destination),this.runNextBuffer()}var t=e.prototype;return t.resetStartParam=function(){this.playTimestamp=0,this.playStartTime=0},t.setOnLoadCache=function(e){this.onLoadCache=e},t.setDurationMs=function(e){void 0===e&&(e=-1),this.durationMs=e},t.setVolume=function(e){void 0===e&&(e=0),this.volume=e,this.gainNode.gain.value=e},t.getAlignVPTS=function(){return this.playTimestamp+(A()-this.playStartTime)/1e3},t.swapSource=function(e,t){if(void 0===e&&(e=-1),void 0===t&&(t=-1),!this.startStatus)return null;if(e<0||e>=this.sourceList.length)return null;if(t<0||t>=this.sourceList.length)return null;try{this.sourceChannel===e&&null!==this.sourceList[e]&&(this.sourceList[e].disconnect(this.gainNode),this.sourceList[e]=null)}catch(t){this.logger.error("[DEFINE ERROR] this audioCore disconnect source Index:"+e+" error happened!",t)}(this.sourceChannel=t,-2===this.decodeSample(t,e)&&this.options.isLive)&&(this.getAlignVPTS()>=this.durationMs/1e3-.04?this.pause():null==this||this.onLoadCache());return null},t.addSample=function(e){return void 0===e&&(e=null),!(null==e||!e||void 0===e)&&(0===this.sampleQueue.length&&(this.seekPos=null==e?void 0:e.pts),this.sampleQueue.push(e),!0)},t.runNextBuffer=function(){var e=this;window.setInterval((function(){if(!(null!=e.nextBuffer||e.sampleQueue.length=this.sourceList.length)return-1;if(null!=this.sourceList[e]&&void 0!==this.sourceList[e]&&this.sourceList[e]||(this.sourceList[e]=this.audioCtx.createBufferSource(),this.sourceList[e].onended=function(){s.swapSource(e,t)}),0===this.sampleQueue.length)return this.options.isLive?(this.sourceList[e].connect(this.gainNode),this.sourceList[e].startState||null==(n=this.sourceList[e])||null==(i=n.start)||i.call(n),this.sourceList[e].onended=function(){s.swapSource(e,t)},this.sourceList[e].stop(),0):-2;if(this.sourceList[e].buffer)return this.swapSource(e,t),0;if(null==this.nextBuffer||this.nextBuffer.data.length<1){var r,o,a=this.sourceList[e];return a.connect(this.gainNode),(null==a?void 0:a.startState)||null==(o=this.sourceList[e])||null==(r=o.start)||r.call(o),a.startState=!0,a.stop(),1}var l=this.nextBuffer.data.buffer;this.playTimestamp=this.nextBuffer.pts,this.playStartTime=A();try{this.audioCtx.decodeAudioData(l,(function(t){var i,n;null!==s.sourceList[e]&&(s.sourceList[e].buffer=t,s.sourceList[e].connect(s.gainNode),s.sourceList[e].startState||null==(n=s.sourceList[e])||null==(i=n.start)||i.call(n),s.sourceList[e].startState=!0)}),(function(e){s.logger.error("Error audioCore with decoding audio data",e)}))}catch(e){return this.nextBuffer=null,this.logger.log("decodeAudioData error",e),-3}return this.nextBuffer=null,0},t.decodeWholeSamples=function(e){var t=this;if(void 0===e&&(e=-1),this.sourceChannel=e,e<0||e>=this.sourceList.length)return-1;if(null!=this.sourceList[e]&&void 0!==this.sourceList[e]&&this.sourceList[e]||(this.sourceList[e]=this.audioCtx.createBufferSource(),this.sourceList[e].onended=function(){}),0===this.sampleQueue.length)return-2;for(var i=null,n=null,s=0;s",e)}},e}(),F=function(){function e(e){this.limit=e.limit||200,this.logger=null==e?void 0:e.logger,this.yuvCache=[]}var t=e.prototype;return t.appendCacheByCacheYuv=function(e){return this.yuvCache.push(e),this.yuvCache.length>=this.limit?(this.shiftYuv(),l):a},t.getState=function(){return this.yuvCache.length<=0?u:this.yuvCache.length>=this.limit?l:a},t.cleanPipeline=function(){this.yuvCache=[],this.yuvCache.length=0},t.shiftYuv=function(){return this.yuvCache.length<=0?null:this.yuvCache.shift()},e}(),N=function(){function e(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r}return e.prototype.setYuv=function(e,t,i,n,s,r){this.pts=e,this.width=t,this.height=i,this.imageBufferY=n,this.imageBufferB=s,this.imageBufferR=r},e}(),O=function(){function e(e){this.gl=e,this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),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)}var t=e.prototype;return t.bind=function(e,t,i){var n=this.gl;n.activeTexture([n.TEXTURE0,n.TEXTURE1,n.TEXTURE2][e]),n.bindTexture(n.TEXTURE_2D,this.texture),n.uniform1i(n.getUniformLocation(t,i),e)},t.fill=function(e,t,i){var n=this.gl;n.bindTexture(n.TEXTURE_2D,this.texture),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,e,t,0,n.LUMINANCE,n.UNSIGNED_BYTE,i)},e}(),U=function(){function e(e,t){this.gl=null,this.gl=e.getContext("webgl")||e.getContext("experimental-webgl"),this.program=this.gl.createProgram();var i=["attribute highp vec4 aVertexPosition;","attribute vec2 aTextureCoord;","varying highp vec2 vTextureCoord;","void main(void) {"," gl_Position = aVertexPosition;"," vTextureCoord = aTextureCoord;","}"].join("\n"),n=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(n,i),this.gl.compileShader(n);var s=["precision highp float;","varying lowp vec2 vTextureCoord;","uniform sampler2D YTexture;","uniform sampler2D UTexture;","uniform sampler2D VTexture;","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",");","void main(void) {"," gl_FragColor = vec4( texture2D(YTexture, vTextureCoord).x, texture2D(UTexture, vTextureCoord).x, texture2D(VTexture, vTextureCoord).x, 1) * YUV2RGB;","}"].join("\n"),r=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(r,s),this.gl.compileShader(r),this.gl.attachShader(this.program,n),this.gl.attachShader(this.program,r),this.gl.linkProgram(this.program),this.gl.useProgram(this.program),this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS);var o=this.gl.getAttribLocation(this.program,"aVertexPosition");this.gl.enableVertexAttribArray(o);var a=this.gl.getAttribLocation(this.program,"aTextureCoord");this.gl.enableVertexAttribArray(a),this.verticesBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.verticesBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(o,3,this.gl.FLOAT,!1,0,0),this.texCoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([1,0,0,0,1,1,0,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,0,0),this.gl.y=new O(this.gl),this.gl.u=new O(this.gl),this.gl.v=new O(this.gl),this.gl.y.bind(0,this.program,"YTexture"),this.gl.u.bind(1,this.program,"UTexture"),this.gl.v.bind(2,this.program,"VTexture")}var t=e.prototype;return t.renderFrame=function(e,t,i,n,s){this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height),this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.y.fill(n,s,e),this.gl.u.fill(n>>1,s>>1,t),this.gl.v.fill(n>>1,s>>1,i),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)},t.destroyContext=function(){try{this.gl.deleteProgram(this.program),this.gl.deleteBuffer(this.verticesBuffer),this.gl.deleteBuffer(this.texCoordBuffer),this.gl.deleteTexture(this.gl.y.texture),this.gl.deleteTexture(this.gl.u.texture),this.gl.deleteTexture(this.gl.v.texture),this.gl=null,this.program=null,this.verticesBuffer=null,this.texCoordBuffer=null}catch(e){}},e}(),$=function(e,t){return{cmd:e,data:t}},W="wasmLoading",V="wasmLoaded",j="wasmFailed",Y="videoCallback",H="decodeCodecContext",X="destroy",Q="demuxTsStream",z="demuxCoreReceive",q="readPacket",G="readPacketEnd",J="mediaInfo",K="ezui-hls",Z={width:600,height:400,volume:0,retry:20,autoPlay:!0,staticPath:"",isLive:!0,loggerOptions:{name:"HLS",level:"INFO",showTime:!0}},ee={disableContextmenu:!0},te=function(){function t(e){void 0===e&&(e={}),this.options=Object.assign({},ee,e),this.logger=this.options.logger,this.event=this.options.event,this._classVideo=K+"-video",this._$container=document.getElementById(this.options.id),this._render()}var i=t.prototype;return i._render=function(){var t,i;if("video"===this.options.nodeName)this.$video=new e.Video(this._$container,this.options).$video;else{var n;if(this.$video=document.createElement(this.options.nodeName),this._$container.innerHTML="",this._$container.appendChild(this.$video),this.options.disableContextmenu)null==(n=this.$video)||n.addEventListener("contextmenu",(function(e){return e.preventDefault(),!1}));this.$video.classList.add(this._classVideo),this.$video.style.cssText+="object-fit: contain; z-index:1;"}null==(i=this.event)||null==(t=i.emit)||t.call(i,"rendered")},i._isVideo=function(){return"VIDEO"===this.$video.nodeName},i.destroy=function(){if(this.$video&&this._$container&&this.$video){try{this._$container.removeChild(this.$video)}catch(e){}this.$video=null}},t}();function ie(e,t,i){return t&&function(e,t){for(var i=0;i=1&&(null==(i=e)||null==(t=i.onLoadCacheFinished)||t.call(i),window.clearInterval(e.cacheInterval),e.cacheInterval=null,e.isCaching===D&&e.play(e.playParams),e.isCaching=R)}),40))}},i._playFunc=function(){var e=!1;if(A()-this.calculateStartTime>=this.frameTime-this.preCostTime){e=!0;var t=!0;if(this.calculateStartTime=A(),this.options.audioNone)this.playFrameYUV(t);else{this.fix_poc_err_skip>0&&(this.fix_poc_err_skip--,t=!1);var i=this.videoPTS-this.audio.getAlignVPTS();if(i>0)return void(this.playParams.seekEvent&&!this.options.audioNone&&this.audio.setVolume(0));if(t){if(!(t=-1*i<=1*this.frameTimeSec)){for(var n=parseInt(i/this.frameTimeSec+""),s=0;s",e,n,i),n>=i&&(t.playFrameYUV(!0),i+=1)}),this.frameTime||5)}else(this.videoPTS>=this.playParams.seekPos&&!this.isNewSeek||0===this.playParams.seekPos||0===this.playParams.seekPos)&&(this.frameTime=1e3/this.options.fps,this.frameTimeSec=this.frameTime/1e3,this.options.audioNone||this.audio.play(),this._volume=this.options.audioNone?0:this.audio.volume,this.loop=window.setInterval((function(){var e=A();t._playFunc(),t.preCostTime=A()-e}),this.frameTime||5));return this.setVolume(this._volume),Promise.resolve()},i.stop=function(){this.destroy(),this.stream=new Uint8Array},i.destroy=function(){return void 0!==this.gl&&null!==this.gl&&(this.gl.destroyContext(),this.gl=null),this.endAudio(),this.cacheLoop&&window.clearInterval(this.cacheLoop),this.cacheLoop=null,this.loop&&window.clearInterval(this.loop),this.loop=null,this.pause(),this.decoderWorker.postMessage($(X)),this.stream=null,this.frameList=null,this.durationMs=-1,this.videoPTS=0,this.isPlaying=!1,this.$video.remove(),!0},i.nextNalu=function(e){if(void 0===e&&(e=1),this.stream.length<=4)return!1;for(var t=-1,i=0;i=this.stream.length){if(-1===t)return!1;var n=this.stream.subarray(t);return this.stream=new Uint8Array,n}var s="0 0 1"===this.stream.slice(0,3).join(" "),r="0 0 0 1"===this.stream.slice(0,4).join(" ");if(s||r){if(-1===t)t=i;else{if(e<=1){var o=this.stream.subarray(t,i);return this.stream=this.stream.subarray(i),o}e-=1}i+=3}}return!1},i.playFrameYUV=function(e){void 0===e&&(e=!1);var t=this.cacheYuvBuf.shiftYuv();if(!t)return this.noCacheFrame+=1,e&&!this.playParams.seekEvent&&this.loadCache(),!1;this.noCacheFrame=0;var i=t.pts;return this.videoPTS=i,this.drawImage(t.width,t.height,t.imageBufferY,t.imageBufferB,t.imageBufferR),t=null,e&&!this.playParams.seekEvent&&this.isPlaying&&this.loadCache(),!0},i.drawImage=function(e,t,i,n,s){this.$video.width===e&&this.$video.height===t||(this.$video.width=e,this.$video.height=t),this.isCheckDisplay||this.checkDisplaySize(e,t);var r=e*t,o=e/2*(t/2),a=new Uint8Array(r+2*o);a.set(i,0),a.set(n,r),a.set(s,r+o),this.gl.renderFrame(i,n,s,e,t),a=null},i.checkDisplaySize=function(e,t){var i,n=e/(null==(i=this.options)?void 0:i.width)>t/this.options.height,s=+(this.options.width/e).toFixed(2),r=+(this.options.height/t).toFixed(2),o=n?s:r,a=this.options.fixed,l=a?this.options.width:parseInt(e*o+""),u=a?this.options.height:parseInt(t*o+"");return this.$video.style.maxWidth="100%",this.$video.style.maxHeight="100%",this.options.width/this.options.height>=1&&l/u>=1?this.$video.style.width="100%":this.$video.style.height="100%",this.isCheckDisplay=!0,[l,u]},i._onWorkerMessage=function(){var e=this;this.decoderWorker.onmessage=function(t){var i=t.data;if(i.cmd===Y){var n=i.data,s=n.ptsSec,r=n.strideY,o=n.height;n.width;var a=n.bufY,l=n.bufU,u=n.bufV,h=new N(s,r,o,a,l,u);e.cacheYuvBuf.appendCacheByCacheYuv(h),h=null}}},i.initVideoAndAudio=function(){this.$video.width=this.options.width,this.$video.height=this.options.height,this.gl=new U(this.$video,{preserveDrawingBuffer:!1}),this.options.audioNone||(this.audio=new B({logger:this.logger,sampleRate:this.options.sampleRate,appendType:this.options.appendHevcType,volume:this.options.volume,isLive:this.options.isLive})),this.isPlayLoadingFinish=1},ie(t,[{key:"volume",get:function(){var e;return(null==(e=this.audio)?void 0:e.volume)||this._volume},set:function(e){this.setVolume(e)}}]),t}(te),oe=[/#EXT-X-PROGRAM-DATE-TIME.+\n/g],ae={lineDelimiter:/\r?\n/,extensionHeader:"#EXTM3U",tagPrefix:"#EXT",segmentPrefix:"#EXTINF",segmentParse:/^#EXTINF: *([0-9.]+)(, *(.+?)?)?$/,tagParse:/^#EXT-X-([A-Z-]+)(:(.+))?$/,version:"VERSION",allowCache:"ALLOW-CACHE",combined:"COMBINED",endList:"ENDLIST",targetDuration:"TARGETDURATION",mediaSequence:"MEDIA-SEQUENCE",discontinuity:"DISCONTINUITY",streamInf:"STREAM-INF",isComment:function(e){return e&&"#"===e[0]&&!e.startsWith(ae.tagPrefix)},isBlank:function(e){return""===e},canStrip:function(e){return ae.isBlank(e)||ae.isComment(e)},defaultMinDur:99999},le=function(){function e(e){this._retry=10,this.logger=null==e?void 0:e.logger,this.initState=!0,this.controller=new AbortController,this._slices=[],this._type=f,this._preURI="",this.duration=-1,this.onTransportStream=null,this.onFinished=null}var t=e.prototype;return t.destroy=function(){this.initState=!1},t.fetchM3u8=function(e){var t=this,i=this;if(this.initState){var n=function(t){return new Promise((function(i,n){var s=new XMLHttpRequest;s.open("GET",t),s.onload=function(){this.status>=200&&this.status<300&&(t!==this.responseURL?(e=this.responseURL,i(this.responseURL)):i(""))},s.onreadystatechange=function(){4===s.readyState&&200===s.status&&i(s.responseText)},s.onerror=function(){n(new Error("Network error."))},s.send()}))};n(e).then((function(s){if(t._retry=10,i._uriParse(e)){var r=i._m3u8Parse(s);if("number"==typeof r&&r>=0)var o=setTimeout((function(){i.fetchM3u8(e),clearTimeout(o)}),200*r)}return n=null,s})).catch((function(s){if(t.logger.error("[M3u8Base] fetch m3u8 url Error ==> ",s),n=null,t._retry>=1)var r=setTimeout((function(){i.fetchM3u8(e),clearTimeout(r)}),500);t._retry--}))}},t._uriParse=function(e){this._preURI="";var t=e.split("://"),i=null,n=null;if(t.length<1)return this.logger.log("HLS URI ERROR : "+e),!1;t.length>1?(i=t[0],n=t[1].split("/"),this._preURI=i+"://"):n=t[0].split("/");for(var s=0;sc&&(s=c);var d,f=n[o+=1],m=null;if(f.includes("http"))m=f;else{if("/"===f[0]){var v=this._preURI.split("//"),g=v[v.length-1].split("/");this._preURI=v[0]+"//"+g[0]}m=this._preURI+f}if(!this._slices.includes(m))this._slices.push(m),null==this||null==(d=this.onTransportStream)||d.call(this,m,c)}}}this._slices.length>500&&(this._slices=this._slices.slice(-500));var y={type:this._type,duration:-1};return null==this||null==(t=this.onFinished)||t.call(this,y),s},t._readTag=function(e){var t=ae.tagParse.exec(e);return null!==t?{key:t[1],value:t[3]}:null},e}(),ue=function(){function e(e){this.sampleRate=e.sampleRate,this.frameDurMs=Math.floor(1024e3/this.sampleRate),this.frameDurSec=this.frameDurMs/1e3}var t=e.prototype;return t.updateOptions=function(e){this.sampleRate=e.sampleRate,this.frameDurMs=1024e3/this.sampleRate,this.frameDurSec=this.frameDurMs/1e3},t._getPktLen=function(e,t,i){return((3&e)<<11)+(t<<3)+((224&i)>>5)},t.sliceAACFrames=function(e,t){for(var i=[],n=e,s=0;s>4==15){var r=this._getPktLen(t[s+3],t[s+4],t[s+5]);if(r<=0)continue;var o=t.subarray(s,s+r),a=new Uint8Array(r);a.set(o,0),i.push({ptime:n,data:a}),n+=this.frameDurSec,s+=r}else s+=1;return i},e}(),he="M3U8",ce="TS",de="FETCH",pe=function(){function e(){}return e.init=function(i){e.collect=new t(i)},e.send=function(t,i){var n,s;null==(s=e.collect)||null==(n=s.send)||n.call(s,{action:t,logInfo:i})},e.updateParams=function(t){e.collect.updateExtendsInfo(t)},e}();function fe(e,t,i){return t&&function(e,t){for(var i=0;i ",e),s=null})).catch((function(n){var s,r,o,a;t.logger.error("[MpegTsDemux] demuxerTsInit ERROR fetch ERROR ==> ",n),null==(r=t.event)||null==(s=r.emit)||s.call(r,ce,{data:n}),null==(a=t.event)||null==(o=a.emit)||o.call(a,de,{data:n,type:ce}),null==i||i.onDemuxedFailed(n,e),pe.send(100,{url:e,msg:"fetch error"})}))},t._demuxCore=function(e,t){e.length<=0||this.decoderWorker.postMessage($(Q,{buff:e,tsUrl:t}))},t.readMediaInfo=function(){return this.mediaInfo},t.readAudioNone=function(){var e;return null==(e=this.mediaInfo)?void 0:e.audioNone},t.isHEVC=function(){return this.mediaInfo.vCodec===d||this.mediaInfo.vCodec===c},t.destroy=function(){this.controller&&this.controller.abort(),this.controller=null,this.mediaInfo=null,this.aacDec=null},t._onWorkerMessage=function(){var e=this;e.logger.log("[demuxer] register _onWorkerMessage"),e.decoderWorker.addEventListener("message",(function(t){var i=t.data;switch(i.cmd){case J:var n,s;if(e.mediaInfo=i.data,e.mediaInfo)null==(s=e.event)||null==(n=s.emit)||n.call(s,"mediaInfo",e.mediaInfo);break;case z:var r;if(e.mediaInfo.vCodec)null==e.aacDec?e.aacDec=new ue(e.mediaInfo):e.aacDec.updateOptions(e.mediaInfo),null==e||null==(r=e.onDemuxed)||r.call(e)}}))},fe(e,[{key:"vCodec",get:function(){return this.mediaInfo.vCodec}}]),e}(),ge=function(){function e(e,t,i,n){this.pts=e,this.dts=e,this.isKey=t,this.data=i,this.video=n}return e.prototype.setFrame=function(e,t,i,n){this.pts=e,this.isKey=t,this.data=i,this.video=n},e}(),ye=function(){function e(e){this.logger=null==e?void 0:e.logger,this.event=null==e?void 0:e.event,this.decoderWorker=e.decoderWorker,this.m3u8Base=new le(e),this.mpegTsDemux=new ve(e),this.tsList=[],this._startTime=0,this._aStartTime=0,this.lockWait={state:!1,lockMember:{dur:0}},this._timerFeed=null,this.seekPos=-1,this.vPreFramePTS=0,this.aPreFramePTS=0,this.audioNone=!1,this.isHevcParam=!1,this.vCodec="",this.aCodec=null,this.aChannel=0,this.durationMs=-1,this.fps=-1,this.sampleRate=-1,this.size={width:-1,height:-1},this.mediaInfo=null,this._onWorkerMessage(),this.onReadyOBJ=null,this.onFinished=null,this.onDemuxed=null,this.onSamples=null,this.onCacheProcess=null}var t=e.prototype;return t.getCachePTS=function(){return Math.max(this.vPreFramePTS,this.aPreFramePTS)},t.demux=function(e){var t=this,i=this;this.vPreFramePTS=0,this.aPreFramePTS=0,this.m3u8Base.onTransportStream=function(e,t){i.tsList.push({streamURI:e,streamDur:t}),i.lockWait.state=!1},this.m3u8Base.onFinished=function(e){var t;e.type===p?i.durationMs=1e3*e.duration:i.durationMs=-1,null==i||null==(t=i.onFinished)||t.call(i,i.onReadyOBJ,e)},this.mpegTsDemux.onDemuxedFailed=function(e,n){t.logger.error("[M3u8] onDemuxedFailed: ",e,n),i.lockWait.state=!1},this.mpegTsDemux.onDemuxed=function(){var e;t.logger.log("[M3u8] onDemuxed"),null==i.mediaInfo&&(i.mediaInfo=i.mpegTsDemux.readMediaInfo(),t.logger.log("[M3u8] mediaInfo: ",i.mediaInfo),i.isHevcParam=i.mpegTsDemux.isHEVC(),i.vCodec=i.mpegTsDemux.vCodec,i.aCodec=i.mediaInfo.aCodec,i.aChannel=i.mediaInfo.sampleChannel,i.fps=i.mediaInfo.fps,i.sampleRate=i.mediaInfo.sampleRate,(null===i.aCodec||""===i.aCodec||i.aChannel<=0)&&(i.audioNone=!0),i.mediaInfo.width>0&&i.mediaInfo.height>0&&(t.size.width=t.mediaInfo.width,t.size.height=t.mediaInfo.height)),null==i||null==(e=i.onDemuxed)||e.call(i,i.onReadyOBJ),i.mpegTsDemux&&t.decoderWorker.postMessage($(q))},this.mpegTsDemux.onReady=function(){i._fetchM3u8AndIntervalTs(e)},this._timerTsWasm=window.setInterval((function(){1===ke.__HLS_WASM_DecoderState__&&(i._fetchM3u8AndIntervalTs(e),window.clearInterval(i._timerTsWasm),i._timerTsWasm=null)}),500)},t._fetchM3u8AndIntervalTs=function(e){var t=this,i=this;this.logger.log("[M3u8] start fetch m3u8 url"),i.m3u8Base.fetchM3u8(e),i._timerFeed=window.setInterval((function(){if(i.tsList.length>0&&!i.lockWait.state)try{var e=i.tsList.shift();if(null!=e){var n=e.streamURI,s=e.streamDur;i.lockWait.state=!0,i.lockWait.lockMember.dur=+s,i.mpegTsDemux.demuxURL(n)}else t.logger.error("[M3u8] onTsReady need wait ")}catch(e){var r,o,a,l;t.logger.error("[M3u8] onTsReady ERROR:",e),null==(o=t.event)||null==(r=o.emit)||r.call(o,he,{data:e}),null==(l=t.event)||null==(a=l.emit)||a.call(l,de,{data:e,type:he}),i.lockWait.state=!1}}),50)},t.destroy=function(){var e;this.m3u8Base&&(null==(e=this.m3u8Base)||e.destroy(),this.m3u8Base=null);this._timerFeed&&(window.clearInterval(this._timerFeed),this._timerFeed=null),this.mpegTsDemux&&(this.mpegTsDemux.destroy(),this.mpegTsDemux=null)},t.bindReady=function(e){this.onReadyOBJ=e},t.getACodec=function(){return this.aCodec},t.getVCodec=function(){return this.vCodec},t.getDurationMs=function(){return this.durationMs},t.getFPS=function(){return this.fps},t.getSampleRate=function(){return this.sampleRate},t.getSampleChannel=function(){return this.aChannel},t.getSize=function(){return this.size},t._onWorkerMessage=function(){this.logger.log("[M3U8] register _onWorkerMessage");var e=this;e.decoderWorker.addEventListener("message",(function(t){var i=t.data;switch(i.cmd){case q:var n,s=i.data,r=s.type,o=s.pts,a=s.ptime,l=s.keyframe,u=s.data,c=s.layer;if(u=new Uint8Array(u),1===r&&e.mpegTsDemux.mediaInfo.aCodec===h&&(u=e.mpegTsDemux.aacDec.sliceAACFrames(a,u)),0===r){var d=function(e){var t=e.nalu,i=e.vlc.vlc;null==t.vps&&(t.vps=new Uint8Array);var n=new Uint8Array(t.vps.length+t.sps.length+t.pps.length+t.sei.length+i.length);return n.set(t.vps,0),n.set(t.sps,t.vps.length),n.set(t.pps,t.vps.length+t.sps.length),n.set(t.sei,t.vps.length+t.sps.length+t.pps.length),n.set(i,t.vps.length+t.sps.length+t.pps.length+t.sei.length),n}(c),p=o,f=new ge(p,1===l,d,!0);e.vPreFramePTS=p,null==e||e.onSamples(e.onReadyOBJ,f)}else if(1===r){var m;if("aac"===(null==(m=e.mediaInfo)?void 0:m.aCodec)){for(var v=u,g=0;g0&&(e.$video.volume=e._options.volume)}),1e3)})),e.event.emit("parsed")}))}))}else if(this.$video.canPlayType("application/vnd.apple.mpegurl")){this.logger.log("Browser support application/vnd.apple.mpegurl : ",this.$video.canPlayType("application/vnd.apple.mpegurl")),this.$video.src=this._options.url;var n=!1;this.$video.addEventListener("canplay",(function(){!n&&e._options.autoPlay&&setTimeout((function(){e.$video.play().then((function(){e.logger.log("autoPlay video!"),setTimeout((function(){e._options.volume>0&&e.setVolume(e._options.volume)}),1e3),n=!0}))}),200)}))}else this.logger.warn("Browser not support hls")},n.isPlayingState=function(){return!this.$video.paused},n.play=function(){if(this.isPlayingState())return Promise.resolve();if(this._options.isLive&&(this.$video.buffered.length>=1&&this.$video.buffered.end(0)>1)){var e=this.$video.buffered.end(0)-1;this.$video.currentTime=e}return this.$video.play()},n.pause=function(){this.$video.pause()},n.setVolume=function(e){this.$video.muted&&(this.$video.muted=!1),this._volume=+(e||0),0===this._volume&&(this.$video.muted=!0),this.$video.volume=this._volume},n.destroy=function(){this.$video&&this.$video.pause(),this._hls&&(this._hls.destroy(),this._hls=null),e.prototype.destroy.call(this)},n._onEvent=function(){var e;(e=this).$video&&(e.$video.addEventListener("canplay",(function(){e.event.emit("canplay")})),e.$video.addEventListener("loadeddata",(function(){e.event.emit("loadeddata")})),e.$video.addEventListener("volumechange",(function(){e.event.emit("volumechange",{data:e.$video.volume})})),e.$video.addEventListener("waiting",(function(){e.event.emit("waiting")})),e.$video.addEventListener("timeupdate",(function(){var t;null==(t=e.event)||t.emit("timeupdate")})),e.$video.addEventListener("seeking",(function(){e.event.emit("seeking",{data:e.$video.currentTime})})),e.$video.addEventListener("seeked",(function(){e.event.emit("seeked")})),e.$video.addEventListener("abort",(function(){e.event.emit("abort")})),e.$video.addEventListener("error",(function(){var t;null==(t=e.event)||t.emit("error",{data:e.$video.error})})),e.$video.addEventListener("ended",(function(){e.event.emit("ended")})))},_e(t,[{key:"volume",get:function(){return this._volume},set:function(e){this.setVolume(e)}}]),t}(te);var Ce="wasm_loaded",xe="wasm_failed",Se="init";function Le(e,t){return Le=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Le(e,t)}var be=function(e){function t(t){var i;return void 0===t&&(t={}),i=e.call(this,t)||this,t.url=n.addVc(null==t?void 0:t.url,["h264","h265"]),function(e,t){if(((null==t?void 0:t.volume)||0)>1?e._volume=1:((null==t?void 0:t.volume)||0)<=0?e._volume=0:e._volume=+((null==t?void 0:t.volume)||0),t.volume=e._volume,e.options=r.merge({},Z,t),"string"!=typeof e.options.id)throw new Error("id is required!");e.logger=s(e.options.loggerOptions),e.event=new o,e.logger.log("HlsPlayer version: ",ke.version),e.logger.log("HlsPlayer options: ",e.options),e.options.logger=e.logger}(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(i),t),i._containerClassName=K+"-container",i._render(),i}!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&Le(e,t)}(t,e);var i=t.prototype;return i._render=function(){this.$container.classList.add(this._containerClassName)},i.destroy=function(){this.$container&&(this.$container.classList.remove(this._containerClassName),this.$container.innerHTML="",this.$container=null)},t}(e);function Re(e,t,i){return t&&function(e,t){for(var i=0;i0&&(e=!0),this.playParam={durationMs:0,fps:0,sampleRate:0,size:{width:0,height:0},audioNone:e,videoCodec:L},!M())throw new Error("Browser not support WebAssembly!");this._onWorkerMessage()},i.play=function(){if(pe.send(1,{name:"play"}),null===this.player)return Promise.resolve();if(this.playParam.videoCodec===L){var e={seekPos:0,isLive:this.options.isLive,accurateSeek:!0,seekEvent:!1,realPlay:!0};return this.player.play(e)}return this.player.play()},i.pause=function(){return pe.send(1,{name:"pause"}),null!==this.player&&(this.player.pause(),!0)},i.destroy=function(){var t,i;return pe.send(1,{name:"destroy"}),void 0!==this.player&&null!==this.player&&(this.playParam.videoCodec===L&&this._m3u8Obj&&(this._m3u8Obj.destroy(),this._m3u8Obj=null),this.player.destroy(),this._decoderWorker&&(this._decoderWorker.postMessage($(X)),this._decoderWorker.terminate(),this._decoderWorker=null),this.logger.log("destroy"),null==(i=this.event)||null==(t=i.emit)||t.call(i,"destroy"),this.player=null,e.prototype.destroy.call(this),!0)},i.isPlaying=function(){return null!==this.player&&this.player.isPlayingState()},i.setVolume=function(e){var t;(e=+e)>1||e<0?this.logger.warn("volume volume value 0.0 ~ 1.0!"):((t=this).player||(t.event.emit("playerIsNull"),t.logger.warn("Player instance does not exist!"),0))&&(this.player.setVolume(e),this.event.emit("volumeChange",{data:e}))},i.getVersion=function(){return pe.send(1,{name:"getVersion"}),"0.1.0"},i._m3u8Entry=function(){var e=this;this._m3u8Obj=new ye({logger:this.logger,decoderWorker:this._decoderWorker,event:this.event}),this._m3u8Obj.bindReady(this),this._m3u8Obj.onFinished=function(e,t){},this._m3u8Obj.onCacheProcess=function(t){e.options.isLive||null==e.onCacheProcess||e.onCacheProcess.call(e,t)},this._m3u8Obj.onDemuxed=this._checkPlayer.bind(this),this._m3u8Obj.onSamples=this._hlsOnSamples.bind(this),this._m3u8Obj.demux(this.url)},i._checkPlayer=function(e,t){var i=this;if(null==i.player){var n,s,r;if(!(null==i||null==(n=i._m3u8Obj)?void 0:n.isHevcParam)||t)return null==i||null==(r=i._m3u8Obj)||null==(s=r.destroy)||s.call(r),i._m3u8Obj=null,this._decoderWorker.terminate(),this._decoderWorker=null,void(i.player=new we(De({},this.options,{event:this.event,logger:this.logger})));var o=i._m3u8Obj.getACodec(),a=i._m3u8Obj.getFPS(),l=i._m3u8Obj.getSampleRate(),u=i._m3u8Obj.getSize(),h=!1;h=i._m3u8Obj.getSampleChannel()<=0||""===o,i._softPlayer(0,a,l,u,h)}},i._hlsOnSamples=function(e,t){var i,n,s,r=this;if(t.video)null==(s=r.player)||null==(n=s.appendHevcFrame)||n.call(s,t);else if(!(null==(i=r._m3u8Obj)?void 0:i.audioNone)){var o,a;null==(a=r.player)||null==(o=a.appendAACFrame)||o.call(a,t)}},i._onWorkerMessage=function(){var e=this,i=this;this._decoderWorker.onmessage=function(n){var s=n.data;switch(s.cmd){case W:t.__HLS_WASM_DecoderState__=0;break;case V:t.__HLS_WASM_DecoderState__=1,e.logger.log("Wasm already init over!"),i.event.emit(Ce),i._decoderWorker.postMessage($("registerWasmPlayer")),i._m3u8Entry();break;case j:t.__HLS_WASM_DecoderState__=-1,e.logger.error("Wasm init failed!",s),i.event.emit(xe,s),pe.send("wasm",{name:"wasm loading failed"}),i._checkPlayer(!0)}}},i._softPlayer=function(e,t,i,n,s,r){var o,a,l=this;void 0===s&&(s=!1),void 0===r&&(r=null);var u,h=this;(this.playParam.durationMs=e,this.playParam.fps=t,this.playParam.sampleRate=i,this.playParam.size=n,this.playParam.audioNone=s,this.playParam.videoCodec=r||L,this.logger.log("this.playParam: ",this.playParam),this.logger.log("start init soft player"),this.player=new re(De({},h.options,{sampleRate:i,fps:t,appendHevcType:v,fixed:!1,id:this.options.id,audioNone:s,videoCodec:r,logger:this.logger,event:this.event,decoderWorker:this._decoderWorker})),this.player.onPlayingTime=function(e){var t;null==h||null==(t=h.onPlayTime)||t.call(h,e)},this.player.onPlayingFinish=function(){var e,t;(l.pause(),null!=l.onPlayFinish)&&(null==(t=l)||null==(e=t.onPlayFinish)||e.call(t))},this.player.onLoadCache=function(){var e,t;null==(t=l)||null==(e=t.onLoadCache)||e.call(t)},this.player.onLoadCacheFinished=function(){var e,t;null==(t=l)||null==(e=t.onLoadCacheFinished)||e.call(t)},null==(o=h.player)||o.setDurationMs(e),null==(a=h.player)||a.setFrameRate(t),null!=h.onReadyShowDone)&&(null==h||null==(u=h.onReadyShowDone)||u.call(h));this.event.emit("parsed"),this.player&&this.options.autoPlay&&this.play()},t.supportType=function(e){if(pe.send(1,{name:"supportType",options:e}),"hls"===e.type)return!0;if(e.url){var t=e.url;t.startsWith("http://")||t.startsWith("https://")||(t=/^\/\//.test(t)?"http:"+t:location.origin+location.pathname+t);try{return/\.m3u8$/i.test(new URL(t).pathname)}catch(e){}}return!1},Re(t,[{key:"volume",get:function(){return this.player?this.player.volume:this.options.volume},set:function(e){e=+e,this.setVolume(e)}}]),t}(be);ke.__HLS_WASM_DecoderState__=0,ke.version="0.1.0",module.exports=ke; diff --git a/dist/index.umd.js b/dist/index.umd.js new file mode 100644 index 0000000..b67e92b --- /dev/null +++ b/dist/index.umd.js @@ -0,0 +1,60 @@ +/* +* +* HlsPlayer.js v0.1.0 +* Copyright (c) 2024-8-1 Ezviz-OpenBiz +* . +* +*/ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).HlsPlayer=t()}(this,(function(){"use strict";var e=1,t=2,i=3,r="aac",s="h265",n="hevc",a="m3u8",o="hls",l=0,h=1,c=600,d=400,u=30,f=40,g=!1,m=44100,p=20,v="ONCE",y="SWAP",T=0,E=265,S=1001,b=1002,L=1003;var w,A=function(){return window.WebAssembly&&"object"==("undefined"==typeof WebAssembly?"undefined":(e=WebAssembly)&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e);var e};function R(){return(new Date).getTime()}var k=window.AudioContext||(null==(w=window)?void 0:w.webkitAudioContext),_=function(){function e(e){var t=this;this.options={sampleRate:e.sampleRate||m,appendType:e.appendType||l,playMode:e.playMode||y,isLive:e.isLive},this.logger=null==e?void 0:e.logger,this.sourceChannel=-1,this.audioCtx=new k({latencyHint:"interactive",sampleRate:e.sampleRate}),this.gainNode=null,this.sourceList=[],this.startStatus=!1,this.sampleQueue=[],this.nextBuffer=null,this.playTimestamp=0,this.playStartTime=0,this.durationMs=-1,this.volume=e.volume||0,this.onLoadCache=null,this.sourceList.push(this.audioCtx.createBufferSource()),this.sourceList.push(this.audioCtx.createBufferSource()),this.sourceList[0].onended=function(){t.swapSource(0,1)},this.sourceList[1].onended=function(){t.swapSource(1,0)},this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.audioCtx.destination),this.runNextBuffer()}var t=e.prototype;return t.resetStartParam=function(){this.playTimestamp=0,this.playStartTime=0},t.setOnLoadCache=function(e){this.onLoadCache=e},t.setDurationMs=function(e){void 0===e&&(e=-1),this.durationMs=e},t.setVolume=function(e){void 0===e&&(e=0),this.volume=e,this.gainNode.gain.value=e},t.getAlignVPTS=function(){return this.playTimestamp+(R()-this.playStartTime)/1e3},t.swapSource=function(e,t){if(void 0===e&&(e=-1),void 0===t&&(t=-1),!this.startStatus)return null;if(e<0||e>=this.sourceList.length)return null;if(t<0||t>=this.sourceList.length)return null;try{this.sourceChannel===e&&null!==this.sourceList[e]&&(this.sourceList[e].disconnect(this.gainNode),this.sourceList[e]=null)}catch(t){this.logger.error("[DEFINE ERROR] this audioCore disconnect source Index:"+e+" error happened!",t)}(this.sourceChannel=t,-2===this.decodeSample(t,e)&&this.options.isLive)&&(this.getAlignVPTS()>=this.durationMs/1e3-.04?this.pause():null==this||this.onLoadCache());return null},t.addSample=function(e){return void 0===e&&(e=null),!(null==e||!e||void 0===e)&&(0===this.sampleQueue.length&&(this.seekPos=null==e?void 0:e.pts),this.sampleQueue.push(e),!0)},t.runNextBuffer=function(){var e=this;window.setInterval((function(){if(!(null!=e.nextBuffer||e.sampleQueue.length=this.sourceList.length)return-1;if(null!=this.sourceList[e]&&void 0!==this.sourceList[e]&&this.sourceList[e]||(this.sourceList[e]=this.audioCtx.createBufferSource(),this.sourceList[e].onended=function(){s.swapSource(e,t)}),0===this.sampleQueue.length)return this.options.isLive?(this.sourceList[e].connect(this.gainNode),this.sourceList[e].startState||null==(r=this.sourceList[e])||null==(i=r.start)||i.call(r),this.sourceList[e].onended=function(){s.swapSource(e,t)},this.sourceList[e].stop(),0):-2;if(this.sourceList[e].buffer)return this.swapSource(e,t),0;if(null==this.nextBuffer||this.nextBuffer.data.length<1){var n,a,o=this.sourceList[e];return o.connect(this.gainNode),(null==o?void 0:o.startState)||null==(a=this.sourceList[e])||null==(n=a.start)||n.call(a),o.startState=!0,o.stop(),1}var l=this.nextBuffer.data.buffer;this.playTimestamp=this.nextBuffer.pts,this.playStartTime=R();try{this.audioCtx.decodeAudioData(l,(function(t){var i,r;null!==s.sourceList[e]&&(s.sourceList[e].buffer=t,s.sourceList[e].connect(s.gainNode),s.sourceList[e].startState||null==(r=s.sourceList[e])||null==(i=r.start)||i.call(r),s.sourceList[e].startState=!0)}),(function(e){s.logger.error("Error audioCore with decoding audio data",e)}))}catch(e){return this.nextBuffer=null,this.logger.log("decodeAudioData error",e),-3}return this.nextBuffer=null,0},t.decodeWholeSamples=function(e){var t=this;if(void 0===e&&(e=-1),this.sourceChannel=e,e<0||e>=this.sourceList.length)return-1;if(null!=this.sourceList[e]&&void 0!==this.sourceList[e]&&this.sourceList[e]||(this.sourceList[e]=this.audioCtx.createBufferSource(),this.sourceList[e].onended=function(){}),0===this.sampleQueue.length)return-2;for(var i=null,r=null,s=0;s",e)}},e}(),D=function(){function r(e){this.limit=e.limit||200,this.logger=null==e?void 0:e.logger,this.yuvCache=[]}var s=r.prototype;return s.appendCacheByCacheYuv=function(i){return this.yuvCache.push(i),this.yuvCache.length>=this.limit?(this.shiftYuv(),t):e},s.getState=function(){return this.yuvCache.length<=0?i:this.yuvCache.length>=this.limit?t:e},s.cleanPipeline=function(){this.yuvCache=[],this.yuvCache.length=0},s.shiftYuv=function(){return this.yuvCache.length<=0?null:this.yuvCache.shift()},r}(),x=function(){function e(e,t,i,r,s,n){this.pts=e,this.width=t,this.height=i,this.imageBufferY=r,this.imageBufferB=s,this.imageBufferR=n}return e.prototype.setYuv=function(e,t,i,r,s,n){this.pts=e,this.width=t,this.height=i,this.imageBufferY=r,this.imageBufferB=s,this.imageBufferR=n},e}(),C=function(){function e(e){this.gl=e,this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),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)}var t=e.prototype;return t.bind=function(e,t,i){var r=this.gl;r.activeTexture([r.TEXTURE0,r.TEXTURE1,r.TEXTURE2][e]),r.bindTexture(r.TEXTURE_2D,this.texture),r.uniform1i(r.getUniformLocation(t,i),e)},t.fill=function(e,t,i){var r=this.gl;r.bindTexture(r.TEXTURE_2D,this.texture),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,i)},e}(),I=function(){function e(e,t){this.gl=null,this.gl=e.getContext("webgl")||e.getContext("experimental-webgl"),this.program=this.gl.createProgram();var i=["attribute highp vec4 aVertexPosition;","attribute vec2 aTextureCoord;","varying highp vec2 vTextureCoord;","void main(void) {"," gl_Position = aVertexPosition;"," vTextureCoord = aTextureCoord;","}"].join("\n"),r=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(r,i),this.gl.compileShader(r);var s=["precision highp float;","varying lowp vec2 vTextureCoord;","uniform sampler2D YTexture;","uniform sampler2D UTexture;","uniform sampler2D VTexture;","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",");","void main(void) {"," gl_FragColor = vec4( texture2D(YTexture, vTextureCoord).x, texture2D(UTexture, vTextureCoord).x, texture2D(VTexture, vTextureCoord).x, 1) * YUV2RGB;","}"].join("\n"),n=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(n,s),this.gl.compileShader(n),this.gl.attachShader(this.program,r),this.gl.attachShader(this.program,n),this.gl.linkProgram(this.program),this.gl.useProgram(this.program),this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS);var a=this.gl.getAttribLocation(this.program,"aVertexPosition");this.gl.enableVertexAttribArray(a);var o=this.gl.getAttribLocation(this.program,"aTextureCoord");this.gl.enableVertexAttribArray(o),this.verticesBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.verticesBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(a,3,this.gl.FLOAT,!1,0,0),this.texCoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([1,0,0,0,1,1,0,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,0,0),this.gl.y=new C(this.gl),this.gl.u=new C(this.gl),this.gl.v=new C(this.gl),this.gl.y.bind(0,this.program,"YTexture"),this.gl.u.bind(1,this.program,"UTexture"),this.gl.v.bind(2,this.program,"VTexture")}var t=e.prototype;return t.renderFrame=function(e,t,i,r,s){this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height),this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.y.fill(r,s,e),this.gl.u.fill(r>>1,s>>1,t),this.gl.v.fill(r>>1,s>>1,i),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)},t.destroyContext=function(){try{this.gl.deleteProgram(this.program),this.gl.deleteBuffer(this.verticesBuffer),this.gl.deleteBuffer(this.texCoordBuffer),this.gl.deleteTexture(this.gl.y.texture),this.gl.deleteTexture(this.gl.u.texture),this.gl.deleteTexture(this.gl.v.texture),this.gl=null,this.program=null,this.verticesBuffer=null,this.texCoordBuffer=null}catch(e){}},e}(),P=function(e,t){return{cmd:e,data:t}},O="wasmLoading",M="wasmLoaded",F="wasmFailed",N="videoCallback",U="decodeCodecContext",B="destroy",$="demuxTsStream",G="demuxCoreReceive",K="readPacket",V="readPacketEnd",H="mediaInfo",j={info:"",log:"background: #4096ff; color: #FFF;",warn:"background: yellow; color: #FFF;",error:"background: red; color: #FFF;"},W=function(){function e(e){void 0===e&&(e={}),this._options={level:"INFO",showTime:!1},this._levelNum=3,this.info=this._loggerFactory("info",this._levelNum>=3),this.log=this._loggerFactory("log",this._levelNum>=2),this.warn=this._loggerFactory("warn",this._levelNum>=1),this.error=this._loggerFactory("error",this._levelNum>=0),this.setOptions(e)}var t=e.prototype;return t.setOptions=function(e){var t;this._options=Object.assign({},this._options,e),this._levelNum=this._matchLevel(null!=(t=this._options.level)?t:"INFO"),this.info=this._loggerFactory("info",this._levelNum>=3),this.log=this._loggerFactory("log",this._levelNum>=2),this.warn=this._loggerFactory("warn",this._levelNum>=1),this.error=this._loggerFactory("error",this._levelNum>=0)},t._matchLevel=function(e){var t=3;switch(e){case"INFO":t=3;break;case"LOG":t=2;break;case"WARN":t=1;break;case"ERROR":t=0}return t},t._loggerFactory=function(t,i){var r=console[t];if(i&&r){var s,n=this._options.name?"%c["+this._options.name+"]%c %c["+t.toUpperCase()+"]":"%c["+t.toUpperCase()+"]",a=[this._options.name?"background: green;color: #fff":null,this._options.name?"":null,j[t]].filter((function(e){return null!=e}));return(s=r).bind.apply(s,[].concat([console,n],a))}return e.noop},t.getOptions=function(){return this._options},t.getVersion=function(){return"1.0.1"},e}();function Y(e){return(e=+e)<10&&(e="0"+e),e+""}W.noop=function(){};var q=["info","log","warn","error"];function z(e){var t=new W(e);return new Proxy(t,{get:function(e,t){if(q.includes(t)){var i;if(null==(i=e._options)?void 0:i.showTime){var r=(n=(s=new Date(Date.now())).getFullYear(),a=s.getMonth()+1,o=s.getDate(),l=s.getHours(),h=s.getMinutes(),c=s.getSeconds(),d=s.getMilliseconds(),n+"/"+Y(a)+"/"+Y(o)+" "+Y(l)+":"+Y(h)+":"+Y(c)+":"+d);return e[t].bind(console,"["+r+"]")}return e[t].bind(console)}var s,n,a,o,l,h,c,d;return Reflect.get(e,t)}})}var X="object"==typeof global&&global&&global.Object===Object&&global,Q="object"==typeof self&&self&&self.Object===Object&&self,J=X||Q||Function("return this")(),Z=J.Symbol,ee=Object.prototype,te=ee.hasOwnProperty,ie=ee.toString,re=Z?Z.toStringTag:void 0;var se=Object.prototype.toString;var ne="[object Null]",ae="[object Undefined]",oe=Z?Z.toStringTag:void 0;function le(e){return null==e?void 0===e?ae:ne:oe&&oe in Object(e)?function(e){var t=te.call(e,re),i=e[re];try{e[re]=void 0;var r=!0}catch(e){}var s=ie.call(e);return r&&(t?e[re]=i:delete e[re]),s}(e):function(e){return se.call(e)}(e)}function he(e){return null!=e&&"object"==typeof e}var ce=Array.isArray;function de(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function ue(e){return e}var fe="[object AsyncFunction]",ge="[object Function]",me="[object GeneratorFunction]",pe="[object Proxy]";function ve(e){if(!de(e))return!1;var t=le(e);return t==ge||t==me||t==fe||t==pe}var ye,Te=J["__core-js_shared__"],Ee=(ye=/[^.]+$/.exec(Te&&Te.keys&&Te.keys.IE_PROTO||""))?"Symbol(src)_1."+ye:"";var Se=Function.prototype.toString;var be=/^\[object .+?Constructor\]$/,Le=Function.prototype,we=Object.prototype,Ae=Le.toString,Re=we.hasOwnProperty,ke=RegExp("^"+Ae.call(Re).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function _e(e){return!(!de(e)||(t=e,Ee&&Ee in t))&&(ve(e)?ke:be).test(function(e){if(null!=e){try{return Se.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e));var t}function De(e,t){var i=function(e,t){return null==e?void 0:e[t]}(e,t);return _e(i)?i:void 0}var xe=Object.create,Ce=function(){function e(){}return function(t){if(!de(t))return{};if(xe)return xe(t);e.prototype=t;var i=new e;return e.prototype=void 0,i}}();var Ie=Date.now;var Pe,Oe,Me,Fe=function(){try{var e=De(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),Ne=Fe?function(e,t){return Fe(e,"toString",{configurable:!0,enumerable:!1,value:(i=t,function(){return i}),writable:!0});var i}:ue,Ue=(Pe=Ne,Oe=0,Me=0,function(){var e=Ie(),t=16-(e-Me);if(Me=e,t>0){if(++Oe>=800)return arguments[0]}else Oe=0;return Pe.apply(void 0,arguments)}),Be=9007199254740991,$e=/^(?:0|[1-9]\d*)$/;function Ge(e,t){var i=typeof e;return!!(t=null==t?Be:t)&&("number"==i||"symbol"!=i&&$e.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=qe}function Xe(e){return null!=e&&ze(e.length)&&!ve(e)}var Qe=Object.prototype;function Je(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Qe)}function Ze(e){return he(e)&&"[object Arguments]"==le(e)}var et=Object.prototype,tt=et.hasOwnProperty,it=et.propertyIsEnumerable,rt=Ze(function(){return arguments}())?Ze:function(e){return he(e)&&tt.call(e,"callee")&&!it.call(e,"callee")};var st="object"==typeof exports&&exports&&!exports.nodeType&&exports,nt=st&&"object"==typeof module&&module&&!module.nodeType&&module,at=nt&&nt.exports===st?J.Buffer:void 0,ot=(at?at.isBuffer:void 0)||function(){return!1},lt={};lt["[object Float32Array]"]=lt["[object Float64Array]"]=lt["[object Int8Array]"]=lt["[object Int16Array]"]=lt["[object Int32Array]"]=lt["[object Uint8Array]"]=lt["[object Uint8ClampedArray]"]=lt["[object Uint16Array]"]=lt["[object Uint32Array]"]=!0,lt["[object Arguments]"]=lt["[object Array]"]=lt["[object ArrayBuffer]"]=lt["[object Boolean]"]=lt["[object DataView]"]=lt["[object Date]"]=lt["[object Error]"]=lt["[object Function]"]=lt["[object Map]"]=lt["[object Number]"]=lt["[object Object]"]=lt["[object RegExp]"]=lt["[object Set]"]=lt["[object String]"]=lt["[object WeakMap]"]=!1;var ht="object"==typeof exports&&exports&&!exports.nodeType&&exports,ct=ht&&"object"==typeof module&&module&&!module.nodeType&&module,dt=ct&&ct.exports===ht&&X.process,ut=function(){try{var e=ct&&ct.require&&ct.require("util").types;return e||dt&&dt.binding&&dt.binding("util")}catch(e){}}(),ft=ut&&ut.isTypedArray,gt=ft?function(e){return function(t){return e(t)}}(ft):function(e){return he(e)&&ze(e.length)&&!!lt[le(e)]};function mt(e,t){var i=ce(e),r=!i&&rt(e),s=!i&&!r&&ot(e),n=!i&&!r&&!s&>(e),a=i||r||s||n,o=a?function(e,t){for(var i=-1,r=Array(e);++i-1},At.prototype.set=function(e,t){var i=this.__data__,r=Lt(i,e);return r<0?(++this.size,i.push([e,t])):i[r][1]=t,this};var Rt=De(J,"Map");function kt(e,t){var i,r,s=e.__data__;return("string"==(r=typeof(i=t))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==i:null===i)?s["string"==typeof t?"string":"hash"]:s.map}function _t(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t1?t[r-1]:void 0,n=r>2?t[2]:void 0;for(s=qt.length>3&&"function"==typeof s?(r--,s):void 0,n&&function(e,t,i){if(!de(i))return!1;var r=typeof t;return!!("number"==r?Xe(i)&&Ge(t,i.length):"string"==r&&t in i)&&Ve(i[t],e)}(t[0],t[1],n)&&(s=r<3?void 0:s,r=1),e=Object(e);++i{if("undefined"==typeof document)return!1;const e=ti[0],t={};for(const i of ti){const r=i?.[1];if(r in document){for(const[r,s]of i.entries())t[e[r]]=s;return t}}return!1})(),ri={change:ii.fullscreenchange,error:ii.fullscreenerror};let si={request:(e=document.documentElement,t)=>new Promise(((i,r)=>{const s=()=>{si.off("change",s),i()};si.on("change",s);const n=e[ii.requestFullscreen](t);n instanceof Promise&&n.then(s).catch(r)})),exit:()=>new Promise(((e,t)=>{if(!si.isFullscreen)return void e();const i=()=>{si.off("change",i),e()};si.on("change",i);const r=document[ii.exitFullscreen]();r instanceof Promise&&r.then(i).catch(t)})),toggle:(e,t)=>si.isFullscreen?si.exit():si.request(e,t),onchange(e){si.on("change",e)},onerror(e){si.on("error",e)},on(e,t){const i=ri[e];i&&document.addEventListener(i,t,!1)},off(e,t){const i=ri[e];i&&document.removeEventListener(i,t,!1)},raw:ii};Object.defineProperties(si,{isFullscreen:{get:()=>Boolean(document[ii.fullscreenElement])},element:{enumerable:!0,get:()=>document[ii.fullscreenElement]??void 0},isEnabled:{enumerable:!0,get:()=>Boolean(document[ii.fullscreenEnabled])}}),ii||(si={isEnabled:!1});var ni=si,ai={exports:{}};!function(e,t){function i(e){return e&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}!function(r,s){var n="function",a="undefined",o="object",l="string",h="major",c="model",d="name",u="type",f="vendor",g="version",m="architecture",p="console",v="mobile",y="tablet",T="smarttv",E="wearable",S="embedded",b="Amazon",L="Apple",w="ASUS",A="BlackBerry",R="Browser",k="Chrome",_="Firefox",D="Google",x="Huawei",C="LG",I="Microsoft",P="Motorola",O="Opera",M="Samsung",F="Sharp",N="Sony",U="Xiaomi",B="Zebra",$="Facebook",G="Chromium OS",K="Mac OS",V=function(e){for(var t={},i=0;i0?2===h.length?i(h[1])==n?this[h[0]]=h[1].call(this,d):this[h[0]]=h[1]:3===h.length?i(h[1])!==n||h[1].exec&&h[1].test?this[h[0]]=d?d.replace(h[1],h[2]):s:this[h[0]]=d?h[1].call(this,d,h[2]):s:4===h.length&&(this[h[0]]=d?h[3].call(this,d.replace(h[1],h[2])):s):this[h]=d||s;u+=2}},q=function(e,t){for(var r in t)if(i(t[r])===o&&t[r].length>0){for(var n=0;n2&&(e[c]="iPad",e[u]=y),e},this.getEngine=function(){var e={};return e[d]=s,e[g]=s,Y.call(e,S,L.engine),e},this.getOS=function(){var e={};return e[d]=s,e[g]=s,Y.call(e,S,L.os),w&&!e[d]&&b&&"Unknown"!=b.platform&&(e[d]=b.platform.replace(/chrome os/i,G).replace(/macos/i,K)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return S},this.setUA=function(e){return S=(void 0===e?"undefined":i(e))===l&&e.length>500?W(e,500):e,this},this.setUA(S),this};Q.VERSION="1.0.37",Q.BROWSER=V([d,g,h]),Q.CPU=V([m]),Q.DEVICE=V([c,f,u,p,v,T,y,E,S]),Q.ENGINE=Q.OS=V([d,g]),i(t)!==a?(i(e)!==a&&e.exports&&(t=e.exports=Q),t.UAParser=Q):(void 0===r?"undefined":i(r))!==a&&(r.UAParser=Q);var J=(void 0===r?"undefined":i(r))!==a&&(r.jQuery||r.Zepto);if(J&&!J.ua){var Z=new Q;J.ua=Z.getResult(),J.ua.get=function(){return Z.getUA()},J.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)J.ua[i]=t[i]}}}("object"===("undefined"==typeof window?"undefined":i(window))?window:Qt)}(ai,ai.exports);var oi,li,hi,ci,di=Jt(ai.exports),ui=(oi="undefined"!=typeof self?self:window,li={navigator:void 0!==oi.navigator?oi.navigator:{userAgent:""},infoMap:{engine:["WebKit","Trident","Gecko","Presto"],browser:["Safari","Chrome","Edge","IE","Firefox","Firefox Focus","Chromium","Opera","Vivaldi","Yandex","Arora","Lunascape","QupZilla","Coc Coc","Kindle","Iceweasel","Konqueror","Iceape","SeaMonkey","Epiphany","360","360SE","360EE","UC","QQBrowser","QQ","Baidu","Maxthon","Sogou","LBBROWSER","2345Explorer","TheWorld","XiaoMi","Quark","Qiyu","Wechat","Taobao","Alipay","Weibo","Douban","Suning","iQiYi"],os:["Windows","Linux","Mac OS","Android","Ubuntu","FreeBSD","Debian","iOS","Windows Phone","BlackBerry","MeeGo","Symbian","Chrome OS","WebOS"],device:["Mobile","Tablet","iPad"]}},hi={getMatchMap:function(e){return{Trident:e.indexOf("Trident")>-1||e.indexOf("NET CLR")>-1,Presto:e.indexOf("Presto")>-1,WebKit:e.indexOf("AppleWebKit")>-1,Gecko:e.indexOf("Gecko/")>-1,Safari:e.indexOf("Safari")>-1,Chrome:e.indexOf("Chrome")>-1||e.indexOf("CriOS")>-1,IE:e.indexOf("MSIE")>-1||e.indexOf("Trident")>-1,Edge:e.indexOf("Edge")>-1,Firefox:e.indexOf("Firefox")>-1||e.indexOf("FxiOS")>-1,"Firefox Focus":e.indexOf("Focus")>-1,Chromium:e.indexOf("Chromium")>-1,Opera:e.indexOf("Opera")>-1||e.indexOf("OPR")>-1,Vivaldi:e.indexOf("Vivaldi")>-1,Yandex:e.indexOf("YaBrowser")>-1,Arora:e.indexOf("Arora")>-1,Lunascape:e.indexOf("Lunascape")>-1,QupZilla:e.indexOf("QupZilla")>-1,"Coc Coc":e.indexOf("coc_coc_browser")>-1,Kindle:e.indexOf("Kindle")>-1||e.indexOf("Silk/")>-1,Iceweasel:e.indexOf("Iceweasel")>-1,Konqueror:e.indexOf("Konqueror")>-1,Iceape:e.indexOf("Iceape")>-1,SeaMonkey:e.indexOf("SeaMonkey")>-1,Epiphany:e.indexOf("Epiphany")>-1,360:e.indexOf("QihooBrowser")>-1||e.indexOf("QHBrowser")>-1,"360EE":e.indexOf("360EE")>-1,"360SE":e.indexOf("360SE")>-1,UC:e.indexOf("UC")>-1||e.indexOf(" UBrowser")>-1,QQBrowser:e.indexOf("QQBrowser")>-1,QQ:e.indexOf("QQ/")>-1,Baidu:e.indexOf("Baidu")>-1||e.indexOf("BIDUBrowser")>-1,Maxthon:e.indexOf("Maxthon")>-1,Sogou:e.indexOf("MetaSr")>-1||e.indexOf("Sogou")>-1,LBBROWSER:e.indexOf("LBBROWSER")>-1,"2345Explorer":e.indexOf("2345Explorer")>-1,TheWorld:e.indexOf("TheWorld")>-1,XiaoMi:e.indexOf("MiuiBrowser")>-1,Quark:e.indexOf("Quark")>-1,Qiyu:e.indexOf("Qiyu")>-1,Wechat:e.indexOf("MicroMessenger")>-1,Taobao:e.indexOf("AliApp(TB")>-1,Alipay:e.indexOf("AliApp(AP")>-1,Weibo:e.indexOf("Weibo")>-1,Douban:e.indexOf("com.douban.frodo")>-1,Suning:e.indexOf("SNEBUY-APP")>-1,iQiYi:e.indexOf("IqiyiApp")>-1,Windows:e.indexOf("Windows")>-1,Linux:e.indexOf("Linux")>-1||e.indexOf("X11")>-1,"Mac OS":e.indexOf("Macintosh")>-1,Android:e.indexOf("Android")>-1||e.indexOf("Adr")>-1,Ubuntu:e.indexOf("Ubuntu")>-1,FreeBSD:e.indexOf("FreeBSD")>-1,Debian:e.indexOf("Debian")>-1,"Windows Phone":e.indexOf("IEMobile")>-1||e.indexOf("Windows Phone")>-1,BlackBerry:e.indexOf("BlackBerry")>-1||e.indexOf("RIM")>-1,MeeGo:e.indexOf("MeeGo")>-1,Symbian:e.indexOf("Symbian")>-1,iOS:e.indexOf("like Mac OS X")>-1,"Chrome OS":e.indexOf("CrOS")>-1,WebOS:e.indexOf("hpwOS")>-1,Mobile:e.indexOf("Mobi")>-1||e.indexOf("iPh")>-1||e.indexOf("480")>-1,Tablet:e.indexOf("Tablet")>-1||e.indexOf("Nexus 7")>-1,iPad:e.indexOf("iPad")>-1}},matchInfoMap:function(e){var t,i=(null==(t=li.navigator)?void 0:t.userAgent)||"",r=hi.getMatchMap(i);for(var s in li.infoMap)for(var n=0;n36&&oi.showModalDialog?s=!0:+n>45&&(s=i("type","application/vnd.chromium.remoting-viewer"))}if(r.Baidu&&r.Opera&&(r.Baidu=!1),r.Mobile&&(r.Mobile=!t.includes("iPad")),s&&(i("type","application/gameplugin")||li.navigator&&void 0===li.navigator.connection.saveData?r["360SE"]=!0:r["360EE"]=!0),r.IE||r.Edge)switch(window.screenTop-window.screenY){case 71:case 74:case 99:case 75:case 105:break;case 102:r["360EE"]=!0;break;case 104:r["360SE"]=!0}var a={Safari:function(){return t.replace(/^.*Version\/([\d.]+).*$/,"$1")},Chrome:function(){return t.replace(/^.*Chrome\/([\d.]+).*$/,"$1").replace(/^.*CriOS\/([\d.]+).*$/,"$1")},IE:function(){return t.replace(/^.*MSIE ([\d.]+).*$/,"$1").replace(/^.*rv:([\d.]+).*$/,"$1")},Edge:function(){return t.replace(/^.*Edge\/([\d.]+).*$/,"$1")},Firefox:function(){return t.replace(/^.*Firefox\/([\d.]+).*$/,"$1").replace(/^.*FxiOS\/([\d.]+).*$/,"$1")},"Firefox Focus":function(){return t.replace(/^.*Focus\/([\d.]+).*$/,"$1")},Chromium:function(){return t.replace(/^.*Chromium\/([\d.]+).*$/,"$1")},Opera:function(){return t.replace(/^.*Opera\/([\d.]+).*$/,"$1").replace(/^.*OPR\/([\d.]+).*$/,"$1")},Vivaldi:function(){return t.replace(/^.*Vivaldi\/([\d.]+).*$/,"$1")},Yandex:function(){return t.replace(/^.*YaBrowser\/([\d.]+).*$/,"$1")},Arora:function(){return t.replace(/^.*Arora\/([\d.]+).*$/,"$1")},Lunascape:function(){return t.replace(/^.*Lunascape[\/\s]([\d.]+).*$/,"$1")},QupZilla:function(){return t.replace(/^.*QupZilla[\/\s]([\d.]+).*$/,"$1")},"Coc Coc":function(){return t.replace(/^.*coc_coc_browser\/([\d.]+).*$/,"$1")},Kindle:function(){return t.replace(/^.*Version\/([\d.]+).*$/,"$1")},Iceweasel:function(){return t.replace(/^.*Iceweasel\/([\d.]+).*$/,"$1")},Konqueror:function(){return t.replace(/^.*Konqueror\/([\d.]+).*$/,"$1")},Iceape:function(){return t.replace(/^.*Iceape\/([\d.]+).*$/,"$1")},SeaMonkey:function(){return t.replace(/^.*SeaMonkey\/([\d.]+).*$/,"$1")},Epiphany:function(){return t.replace(/^.*Epiphany\/([\d.]+).*$/,"$1")},360:function(){return t.replace(/^.*QihooBrowser\/([\d.]+).*$/,"$1")},"360SE":function(){return{63:"10.0",55:"9.1",45:"8.1",42:"8.0",31:"7.0",21:"6.3"}[+t.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"360EE":function(){return{69:"11.0",63:"9.5",55:"9.0",50:"8.7",30:"7.5"}[+t.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},Maxthon:function(){return t.replace(/^.*Maxthon\/([\d.]+).*$/,"$1")},QQBrowser:function(){return t.replace(/^.*QQBrowser\/([\d.]+).*$/,"$1")},QQ:function(){return t.replace(/^.*QQ\/([\d.]+).*$/,"$1")},Baidu:function(){return t.replace(/^.*BIDUBrowser[\s\/]([\d.]+).*$/,"$1")},UC:function(){return t.replace(/^.*UC?Browser\/([\d.]+).*$/,"$1")},Sogou:function(){return t.replace(/^.*SE ([\d.X]+).*$/,"$1").replace(/^.*SogouMobileBrowser\/([\d.]+).*$/,"$1")},LBBROWSER:function(){return{57:"6.5",49:"6.0",46:"5.9",42:"5.3",39:"5.2",34:"5.0",29:"4.5",21:"4.0"}[+navigator.userAgent.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"2345Explorer":function(){return t.replace(/^.*2345Explorer\/([\d.]+).*$/,"$1")},TheWorld:function(){return t.replace(/^.*TheWorld ([\d.]+).*$/,"$1")},XiaoMi:function(){return t.replace(/^.*MiuiBrowser\/([\d.]+).*$/,"$1")},Quark:function(){return t.replace(/^.*Quark\/([\d.]+).*$/,"$1")},Qiyu:function(){return t.replace(/^.*Qiyu\/([\d.]+).*$/,"$1")},Wechat:function(){return t.replace(/^.*MicroMessenger\/([\d.]+).*$/,"$1")},Taobao:function(){return t.replace(/^.*AliApp\(TB\/([\d.]+).*$/,"$1")},Alipay:function(){return t.replace(/^.*AliApp\(AP\/([\d.]+).*$/,"$1")},Weibo:function(){return t.replace(/^.*weibo__([\d.]+).*$/,"$1")},Douban:function(){return t.replace(/^.*com.douban.frodo\/([\d.]+).*$/,"$1")},Suning:function(){return t.replace(/^.*SNEBUY-APP([\d.]+).*$/,"$1")},iQiYi:function(){return t.replace(/^.*IqiyiVersion\/([\d.]+).*$/,"$1")}};return e.browserVersion="",a[e.browser]&&(e.browserVersion=a[e.browser](),e.browserVersion==t&&(e.browserVersion="")),"Edge"==e.browser&&(e.engine="EdgeHTML"),"Chrome"==e.browser&&parseInt(e.browserVersion)>27&&(e.engine="Blink"),"Opera"==e.browser&&parseInt(e.browserVersion)>12&&(e.engine="Blink"),"Yandex"==e.browser&&(e.engine="Blink"),e.browser+" (version: "+e.browserVersion+"; kernel: "+e.engine+")"}},ci={DeviceInfoObj:function(e){var t,i=function(t){var i;null==(i=e.info)||i.forEach((function(e){e.toLowerCase()===t.toLowerCase()&&(s[t]=r[t])}))};e=e||{domain:""};var r={deviceType:hi.getDeviceType(),OS:hi.getOS(),OSVersion:hi.getOSVersion(),sh:oi.screen.height,sw:oi.screen.width,lang:hi.getLanguage(),netWork:hi.getNetwork(),orientation:hi.getOrientationStatu(),browserInfo:hi.getBrowserInfo(),fingerprint:hi.createFingerprint(e.domain),userAgent:null==(t=li.navigator)?void 0:t.userAgent};if(!e.info||0===e.info.length)return r;var s={};for(var n in r)i(n);return s}},{getDeviceInfo:function(e){return ci.DeviceInfoObj(e)}}),fi=function(){function e(){}return e.add=function(t,i){e.queues.push({url:t,data:i})},e.fire=function(){if(e.queues&&0!==e.queues.length){e.isStop=!1;var t=e.queues[0];t.url&&e.api.report(t.data),e.queues.splice(0,1),e.fire()}else e.isStop=!0},e}();fi.isStop=!0,fi.queues=[];var gi=function(){function e(e){this.url=e}var t=e.prototype;return t.report=function(e){this.checkUrl(this.url)&&this.sendInfo(e)},t.sendInfo=function(e){navigator.sendBeacon?this.sendBeacon(this.url,e):this.sendImage(this.url,e)},t.sendImage=function(e,t){var i=this.changeJSON2Query(t),r=new Image;r.onload=r.onerror=function(){r=null},r.src=e+"?"+i+"&random="+Math.random()},t.sendBeacon=function(e,t){try{navigator.sendBeacon(e,this.formatParamsByURLSearchParams(t))}catch(e){}},t.formatParamsByURLSearchParams=function(e){var t=new URLSearchParams;for(var i in e)"object"==typeof e[i]&&(e[i]=JSON.stringify(e[i])),t.append(i,e[i]);return t},t.changeJSON2Query=function(e){var t="";for(var i in e){""!=t&&(t+="&");var r=e[i];t+=i+"="+encodeURIComponent("object"==typeof r?JSON.stringify(r):r)}return t},t.checkUrl=function(e){return!!e&&/^[hH][tT][tT][pP]([sS]?):\/\//.test(e)},e}();function mi(){return mi=Object.assign||function(e){for(var t=1;t0&&t>0))throw new Error("width value "+e+" or height value "+t+" unqualified!");this.width=e,this.height=t},i.play=function(e){throw new Error("Method play not implemented.")},i.pause=function(){throw new Error("Method pause not implemented.")},i.fullscreen=function(){var e,t,i,r;return null==(t=this.logger)||null==(e=t.log)||e.call(t,"[fullscreen]"),null==(r=this.event)||null==(i=r.emit)||i.call(r,"fullscreen"),Ti.send(1,{name:"fullscreen"}),ni.isEnabled&&!this.isMobile?ni.request(this.$container):(this.logger.warn("Not support fullscreen"),Promise.resolve())},i.exitFullscreen=function(){var e,t,i,r;return null==(t=this.logger)||null==(e=t.log)||e.call(t,"[exitFullscreen]"),null==(r=this.event)||null==(i=r.emit)||i.call(r,"exitFullscreen"),Ti.send(1,{name:"exitFullscreen"}),ni.isEnabled&&!this.isMobile?ni.exit():(this.logger.warn("Not support exitFullscreen"),Promise.resolve())},i.setVolume=function(e){throw new Error("Method setVolume not implemented.")},i.resize=function(e,t){Ti.send(1,{name:"resize"});try{var i,r,s,n;this._checkSize(e,t),this.$container.style.width=e+"px",this.$container.style.height=t+"px",null==(r=this.logger)||null==(i=r.log)||i.call(r,"[resize] width: "+e+", height: "+t),null==(n=this.event)||null==(s=n.emit)||s.call(n,"resize",{data:{width:e,height:t}})}catch(e){}},i.destroy=function(){var e,t=this;this.browser&&(this.browser=null),ni.isEnabled&&this._screenfullChange&&(null==ni||null==(e=ni.off)||e.call(ni,"change",this._screenfullChange),this._screenfullChange=null),this.logger&&(this.logger=null),this.event&&setTimeout((function(){t.event.removeAllListeners(),t.event=null}),100)},i.setLogger=function(e){Ti.send(1,{name:"setLogger"}),this.options=zt(this.options,{loggerOptions:e}),this.logger.setOptions(this.options.loggerOptions)},i.getVersion=function(){throw new Error("Method getVersion not implemented.")},i.getOptions=function(){return Ti.send(1,{name:"getOptions"}),this.options},t.supportType=function(e){return!1},t}(ei),bi=function(){function e(e,t){if(this._$container=e,"string"==typeof e&&(this._$container=document.getElementById(e)),!this._$container)throw new Error("VideoCanvas create fail!");this._options=t,this._createDom()}return e.prototype._createDom=function(){var e,t,i,r,s,n,a=this;this.$video||(this.$video=document.createElement("video"),this._options.autoPlay&&(this.$video.muted=!(null==(e=window)?void 0:e.___HUMAN_TOUCH_SCREEN___),this.$video.autoplay=!0,"object"==((s=null==(t=window)?void 0:t.WeixinJSBridge)&&"undefined"!=typeof Symbol&&s.constructor===Symbol?"symbol":typeof s)&&"function"==typeof(null==(r=window)||null==(i=r.WeixinJSBridge)?void 0:i.invoke)&&document.addEventListener("WeixinJSBridgeReady",(function(){a.$video.play(),a.$video.pause()}),!1),this.$video.addEventListener("loadeddata",(function(){setTimeout((function(){a.$video.play()}),10)}))),this.$video.volume=+this._options.volume||0,this.$video.controls=!!this._options.controls,this.$video.preload=this._options.preload||"auto",this.$video.disablePictureInPicture=!0,this.$video.setAttribute("playsInline","true"),this.$video.setAttribute("webkit-playsinline","true"),this.$video.setAttribute("controlsList",this._options.controlsList||""),(this._options.isMobile&&navigator.userAgent.includes("MQQBrowser")||navigator.userAgent.includes("QQTheme"))&&(this.$video.setAttribute("x5-video-player-type","h5"),this.$video.setAttribute("x5-video-player-fullscreen","false"),this.$video.setAttribute("x5-video-orientation","portraint")),this._options.loop&&this.$video.setAttribute("loop","true"),this.$video.style.cssText+="width: 100%; height: 100%; object-fit: contain; position: absolute; z-index: 1; outline: none;",this._$container.innerHTML="",this._$container.appendChild(this.$video),this._options.disableContextmenu&&(null==(n=this.$video)||n.addEventListener("contextmenu",(function(e){return e.preventDefault(),!1}))))},e}(),Li="ezui-hls",wi={width:600,height:400,volume:0,retry:20,autoPlay:!0,staticPath:"",isLive:!0,loggerOptions:{name:"HLS",level:"INFO",showTime:!0}},Ai={disableContextmenu:!0},Ri=function(){function e(e){void 0===e&&(e={}),this.options=Object.assign({},Ai,e),this.logger=this.options.logger,this.event=this.options.event,this._classVideo=Li+"-video",this._$container=document.getElementById(this.options.id),this._render()}var t=e.prototype;return t._render=function(){var e,t;if("video"===this.options.nodeName)this.$video=new bi(this._$container,this.options).$video;else{var i;if(this.$video=document.createElement(this.options.nodeName),this._$container.innerHTML="",this._$container.appendChild(this.$video),this.options.disableContextmenu)null==(i=this.$video)||i.addEventListener("contextmenu",(function(e){return e.preventDefault(),!1}));this.$video.classList.add(this._classVideo),this.$video.style.cssText+="object-fit: contain; z-index:1;"}null==(t=this.event)||null==(e=t.emit)||e.call(t,"rendered")},t._isVideo=function(){return"VIDEO"===this.$video.nodeName},t.destroy=function(){if(this.$video&&this._$container&&this.$video){try{this._$container.removeChild(this.$video)}catch(e){}this.$video=null}},e}();function ki(e,t,i){return t&&function(e,t){for(var i=0;i=1&&(null==(i=e)||null==(t=i.onLoadCacheFinished)||t.call(i),window.clearInterval(e.cacheInterval),e.cacheInterval=null,e.isCaching===b&&e.play(e.playParams),e.isCaching=S)}),40))}},r._playFunc=function(){var e=!1;if(R()-this.calculateStartTime>=this.frameTime-this.preCostTime){e=!0;var t=!0;if(this.calculateStartTime=R(),this.options.audioNone)this.playFrameYUV(t);else{this.fix_poc_err_skip>0&&(this.fix_poc_err_skip--,t=!1);var i=this.videoPTS-this.audio.getAlignVPTS();if(i>0)return void(this.playParams.seekEvent&&!this.options.audioNone&&this.audio.setVolume(0));if(t){if(!(t=-1*i<=1*this.frameTimeSec)){for(var r=parseInt(i/this.frameTimeSec+""),s=0;s",e,r,i),r>=i&&(t.playFrameYUV(!0),i+=1)}),this.frameTime||5)}else(this.videoPTS>=this.playParams.seekPos&&!this.isNewSeek||0===this.playParams.seekPos||0===this.playParams.seekPos)&&(this.frameTime=1e3/this.options.fps,this.frameTimeSec=this.frameTime/1e3,this.options.audioNone||this.audio.play(),this._volume=this.options.audioNone?0:this.audio.volume,this.loop=window.setInterval((function(){var e=R();t._playFunc(),t.preCostTime=R()-e}),this.frameTime||5));return this.setVolume(this._volume),Promise.resolve()},r.stop=function(){this.destroy(),this.stream=new Uint8Array},r.destroy=function(){return void 0!==this.gl&&null!==this.gl&&(this.gl.destroyContext(),this.gl=null),this.endAudio(),this.cacheLoop&&window.clearInterval(this.cacheLoop),this.cacheLoop=null,this.loop&&window.clearInterval(this.loop),this.loop=null,this.pause(),this.decoderWorker.postMessage(P(B)),this.stream=null,this.frameList=null,this.durationMs=-1,this.videoPTS=0,this.isPlaying=!1,this.$video.remove(),!0},r.nextNalu=function(e){if(void 0===e&&(e=1),this.stream.length<=4)return!1;for(var t=-1,i=0;i=this.stream.length){if(-1===t)return!1;var r=this.stream.subarray(t);return this.stream=new Uint8Array,r}var s="0 0 1"===this.stream.slice(0,3).join(" "),n="0 0 0 1"===this.stream.slice(0,4).join(" ");if(s||n){if(-1===t)t=i;else{if(e<=1){var a=this.stream.subarray(t,i);return this.stream=this.stream.subarray(i),a}e-=1}i+=3}}return!1},r.playFrameYUV=function(e){void 0===e&&(e=!1);var t=this.cacheYuvBuf.shiftYuv();if(!t)return this.noCacheFrame+=1,e&&!this.playParams.seekEvent&&this.loadCache(),!1;this.noCacheFrame=0;var i=t.pts;return this.videoPTS=i,this.drawImage(t.width,t.height,t.imageBufferY,t.imageBufferB,t.imageBufferR),t=null,e&&!this.playParams.seekEvent&&this.isPlaying&&this.loadCache(),!0},r.drawImage=function(e,t,i,r,s){this.$video.width===e&&this.$video.height===t||(this.$video.width=e,this.$video.height=t),this.isCheckDisplay||this.checkDisplaySize(e,t);var n=e*t,a=e/2*(t/2),o=new Uint8Array(n+2*a);o.set(i,0),o.set(r,n),o.set(s,n+a),this.gl.renderFrame(i,r,s,e,t),o=null},r.checkDisplaySize=function(e,t){var i,r=e/(null==(i=this.options)?void 0:i.width)>t/this.options.height,s=+(this.options.width/e).toFixed(2),n=+(this.options.height/t).toFixed(2),a=r?s:n,o=this.options.fixed,l=o?this.options.width:parseInt(e*a+""),h=o?this.options.height:parseInt(t*a+"");return this.$video.style.maxWidth="100%",this.$video.style.maxHeight="100%",this.options.width/this.options.height>=1&&l/h>=1?this.$video.style.width="100%":this.$video.style.height="100%",this.isCheckDisplay=!0,[l,h]},r._onWorkerMessage=function(){var e=this;this.decoderWorker.onmessage=function(t){var i=t.data;if(i.cmd===N){var r=i.data,s=r.ptsSec,n=r.strideY,a=r.height;r.width;var o=r.bufY,l=r.bufU,h=r.bufV,c=new x(s,n,a,o,l,h);e.cacheYuvBuf.appendCacheByCacheYuv(c),c=null}}},r.initVideoAndAudio=function(){this.$video.width=this.options.width,this.$video.height=this.options.height,this.gl=new I(this.$video,{preserveDrawingBuffer:!1}),this.options.audioNone||(this.audio=new _({logger:this.logger,sampleRate:this.options.sampleRate,appendType:this.options.appendHevcType,volume:this.options.volume,isLive:this.options.isLive})),this.isPlayLoadingFinish=1},ki(i,[{key:"volume",get:function(){var e;return(null==(e=this.audio)?void 0:e.volume)||this._volume},set:function(e){this.setVolume(e)}}]),i}(Ri),Ci=[/#EXT-X-PROGRAM-DATE-TIME.+\n/g],Ii={lineDelimiter:/\r?\n/,extensionHeader:"#EXTM3U",tagPrefix:"#EXT",segmentPrefix:"#EXTINF",segmentParse:/^#EXTINF: *([0-9.]+)(, *(.+?)?)?$/,tagParse:/^#EXT-X-([A-Z-]+)(:(.+))?$/,version:"VERSION",allowCache:"ALLOW-CACHE",combined:"COMBINED",endList:"ENDLIST",targetDuration:"TARGETDURATION",mediaSequence:"MEDIA-SEQUENCE",discontinuity:"DISCONTINUITY",streamInf:"STREAM-INF",isComment:function(e){return e&&"#"===e[0]&&!e.startsWith(Ii.tagPrefix)},isBlank:function(e){return""===e},canStrip:function(e){return Ii.isBlank(e)||Ii.isComment(e)},defaultMinDur:99999},Pi=function(){function e(e){this._retry=10,this.logger=null==e?void 0:e.logger,this.initState=!0,this.controller=new AbortController,this._slices=[],this._type=o,this._preURI="",this.duration=-1,this.onTransportStream=null,this.onFinished=null}var t=e.prototype;return t.destroy=function(){this.initState=!1},t.fetchM3u8=function(e){var t=this,i=this;if(this.initState){var r=function(t){return new Promise((function(i,r){var s=new XMLHttpRequest;s.open("GET",t),s.onload=function(){this.status>=200&&this.status<300&&(t!==this.responseURL?(e=this.responseURL,i(this.responseURL)):i(""))},s.onreadystatechange=function(){4===s.readyState&&200===s.status&&i(s.responseText)},s.onerror=function(){r(new Error("Network error."))},s.send()}))};r(e).then((function(s){if(t._retry=10,i._uriParse(e)){var n=i._m3u8Parse(s);if("number"==typeof n&&n>=0)var a=setTimeout((function(){i.fetchM3u8(e),clearTimeout(a)}),200*n)}return r=null,s})).catch((function(s){if(t.logger.error("[M3u8Base] fetch m3u8 url Error ==> ",s),r=null,t._retry>=1)var n=setTimeout((function(){i.fetchM3u8(e),clearTimeout(n)}),500);t._retry--}))}},t._uriParse=function(e){this._preURI="";var t=e.split("://"),i=null,r=null;if(t.length<1)return this.logger.log("HLS URI ERROR : "+e),!1;t.length>1?(i=t[0],r=t[1].split("/"),this._preURI=i+"://"):r=t[0].split("/");for(var s=0;su&&(s=u);var f,g=r[o+=1],m=null;if(g.includes("http"))m=g;else{if("/"===g[0]){var p=this._preURI.split("//"),v=p[p.length-1].split("/");this._preURI=p[0]+"//"+v[0]}m=this._preURI+g}if(!this._slices.includes(m))this._slices.push(m),null==this||null==(f=this.onTransportStream)||f.call(this,m,u)}}}this._slices.length>500&&(this._slices=this._slices.slice(-500));var y={type:this._type,duration:-1};return null==this||null==(t=this.onFinished)||t.call(this,y),s},t._readTag=function(e){var t=Ii.tagParse.exec(e);return null!==t?{key:t[1],value:t[3]}:null},e}(),Oi=function(){function e(e){this.sampleRate=e.sampleRate,this.frameDurMs=Math.floor(1024e3/this.sampleRate),this.frameDurSec=this.frameDurMs/1e3}var t=e.prototype;return t.updateOptions=function(e){this.sampleRate=e.sampleRate,this.frameDurMs=1024e3/this.sampleRate,this.frameDurSec=this.frameDurMs/1e3},t._getPktLen=function(e,t,i){return((3&e)<<11)+(t<<3)+((224&i)>>5)},t.sliceAACFrames=function(e,t){for(var i=[],r=e,s=0;s>4==15){var n=this._getPktLen(t[s+3],t[s+4],t[s+5]);if(n<=0)continue;var a=t.subarray(s,s+n),o=new Uint8Array(n);o.set(a,0),i.push({ptime:r,data:o}),r+=this.frameDurSec,s+=n}else s+=1;return i},e}(),Mi="M3U8",Fi="TS",Ni="FETCH",Ui=function(){function e(){}return e.init=function(t){e.collect=new pi(t)},e.send=function(t,i){var r,s;null==(s=e.collect)||null==(r=s.send)||r.call(s,{action:t,logInfo:i})},e.updateParams=function(t){e.collect.updateExtendsInfo(t)},e}();function Bi(e,t,i){return t&&function(e,t){for(var i=0;i ",e),s=null})).catch((function(r){var s,n,a,o;t.logger.error("[MpegTsDemux] demuxerTsInit ERROR fetch ERROR ==> ",r),null==(n=t.event)||null==(s=n.emit)||s.call(n,Fi,{data:r}),null==(o=t.event)||null==(a=o.emit)||a.call(o,Ni,{data:r,type:Fi}),null==i||i.onDemuxedFailed(r,e),Ui.send(100,{url:e,msg:"fetch error"})}))},t._demuxCore=function(e,t){e.length<=0||this.decoderWorker.postMessage(P($,{buff:e,tsUrl:t}))},t.readMediaInfo=function(){return this.mediaInfo},t.readAudioNone=function(){var e;return null==(e=this.mediaInfo)?void 0:e.audioNone},t.isHEVC=function(){return this.mediaInfo.vCodec===n||this.mediaInfo.vCodec===s},t.destroy=function(){this.controller&&this.controller.abort(),this.controller=null,this.mediaInfo=null,this.aacDec=null},t._onWorkerMessage=function(){var e=this;e.logger.log("[demuxer] register _onWorkerMessage"),e.decoderWorker.addEventListener("message",(function(t){var i=t.data;switch(i.cmd){case H:var r,s;if(e.mediaInfo=i.data,e.mediaInfo)null==(s=e.event)||null==(r=s.emit)||r.call(s,"mediaInfo",e.mediaInfo);break;case G:var n;if(e.mediaInfo.vCodec)null==e.aacDec?e.aacDec=new Oi(e.mediaInfo):e.aacDec.updateOptions(e.mediaInfo),null==e||null==(n=e.onDemuxed)||n.call(e)}}))},Bi(e,[{key:"vCodec",get:function(){return this.mediaInfo.vCodec}}]),e}(),Ki=function(){function e(e,t,i,r){this.pts=e,this.dts=e,this.isKey=t,this.data=i,this.video=r}return e.prototype.setFrame=function(e,t,i,r){this.pts=e,this.isKey=t,this.data=i,this.video=r},e}(),Vi=function(){function e(e){this.logger=null==e?void 0:e.logger,this.event=null==e?void 0:e.event,this.decoderWorker=e.decoderWorker,this.m3u8Base=new Pi(e),this.mpegTsDemux=new Gi(e),this.tsList=[],this._startTime=0,this._aStartTime=0,this.lockWait={state:!1,lockMember:{dur:0}},this._timerFeed=null,this.seekPos=-1,this.vPreFramePTS=0,this.aPreFramePTS=0,this.audioNone=!1,this.isHevcParam=!1,this.vCodec="",this.aCodec=null,this.aChannel=0,this.durationMs=-1,this.fps=-1,this.sampleRate=-1,this.size={width:-1,height:-1},this.mediaInfo=null,this._onWorkerMessage(),this.onReadyOBJ=null,this.onFinished=null,this.onDemuxed=null,this.onSamples=null,this.onCacheProcess=null}var t=e.prototype;return t.getCachePTS=function(){return Math.max(this.vPreFramePTS,this.aPreFramePTS)},t.demux=function(e){var t=this,i=this;this.vPreFramePTS=0,this.aPreFramePTS=0,this.m3u8Base.onTransportStream=function(e,t){i.tsList.push({streamURI:e,streamDur:t}),i.lockWait.state=!1},this.m3u8Base.onFinished=function(e){var t;e.type===a?i.durationMs=1e3*e.duration:i.durationMs=-1,null==i||null==(t=i.onFinished)||t.call(i,i.onReadyOBJ,e)},this.mpegTsDemux.onDemuxedFailed=function(e,r){t.logger.error("[M3u8] onDemuxedFailed: ",e,r),i.lockWait.state=!1},this.mpegTsDemux.onDemuxed=function(){var e;t.logger.log("[M3u8] onDemuxed"),null==i.mediaInfo&&(i.mediaInfo=i.mpegTsDemux.readMediaInfo(),t.logger.log("[M3u8] mediaInfo: ",i.mediaInfo),i.isHevcParam=i.mpegTsDemux.isHEVC(),i.vCodec=i.mpegTsDemux.vCodec,i.aCodec=i.mediaInfo.aCodec,i.aChannel=i.mediaInfo.sampleChannel,i.fps=i.mediaInfo.fps,i.sampleRate=i.mediaInfo.sampleRate,(null===i.aCodec||""===i.aCodec||i.aChannel<=0)&&(i.audioNone=!0),i.mediaInfo.width>0&&i.mediaInfo.height>0&&(t.size.width=t.mediaInfo.width,t.size.height=t.mediaInfo.height)),null==i||null==(e=i.onDemuxed)||e.call(i,i.onReadyOBJ),i.mpegTsDemux&&t.decoderWorker.postMessage(P(K))},this.mpegTsDemux.onReady=function(){i._fetchM3u8AndIntervalTs(e)},this._timerTsWasm=window.setInterval((function(){1===Uc.__HLS_WASM_DecoderState__&&(i._fetchM3u8AndIntervalTs(e),window.clearInterval(i._timerTsWasm),i._timerTsWasm=null)}),500)},t._fetchM3u8AndIntervalTs=function(e){var t=this,i=this;this.logger.log("[M3u8] start fetch m3u8 url"),i.m3u8Base.fetchM3u8(e),i._timerFeed=window.setInterval((function(){if(i.tsList.length>0&&!i.lockWait.state)try{var e=i.tsList.shift();if(null!=e){var r=e.streamURI,s=e.streamDur;i.lockWait.state=!0,i.lockWait.lockMember.dur=+s,i.mpegTsDemux.demuxURL(r)}else t.logger.error("[M3u8] onTsReady need wait ")}catch(e){var n,a,o,l;t.logger.error("[M3u8] onTsReady ERROR:",e),null==(a=t.event)||null==(n=a.emit)||n.call(a,Mi,{data:e}),null==(l=t.event)||null==(o=l.emit)||o.call(l,Ni,{data:e,type:Mi}),i.lockWait.state=!1}}),50)},t.destroy=function(){var e;this.m3u8Base&&(null==(e=this.m3u8Base)||e.destroy(),this.m3u8Base=null);this._timerFeed&&(window.clearInterval(this._timerFeed),this._timerFeed=null),this.mpegTsDemux&&(this.mpegTsDemux.destroy(),this.mpegTsDemux=null)},t.bindReady=function(e){this.onReadyOBJ=e},t.getACodec=function(){return this.aCodec},t.getVCodec=function(){return this.vCodec},t.getDurationMs=function(){return this.durationMs},t.getFPS=function(){return this.fps},t.getSampleRate=function(){return this.sampleRate},t.getSampleChannel=function(){return this.aChannel},t.getSize=function(){return this.size},t._onWorkerMessage=function(){this.logger.log("[M3U8] register _onWorkerMessage");var e=this;e.decoderWorker.addEventListener("message",(function(t){var i=t.data;switch(i.cmd){case K:var s,n=i.data,a=n.type,o=n.pts,l=n.ptime,h=n.keyframe,c=n.data,d=n.layer;if(c=new Uint8Array(c),1===a&&e.mpegTsDemux.mediaInfo.aCodec===r&&(c=e.mpegTsDemux.aacDec.sliceAACFrames(l,c)),0===a){var u=function(e){var t=e.nalu,i=e.vlc.vlc;null==t.vps&&(t.vps=new Uint8Array);var r=new Uint8Array(t.vps.length+t.sps.length+t.pps.length+t.sei.length+i.length);return r.set(t.vps,0),r.set(t.sps,t.vps.length),r.set(t.pps,t.vps.length+t.sps.length),r.set(t.sei,t.vps.length+t.sps.length+t.pps.length),r.set(i,t.vps.length+t.sps.length+t.pps.length+t.sei.length),r}(d),f=o,g=new Ki(f,1===h,u,!0);e.vPreFramePTS=f,null==e||e.onSamples(e.onReadyOBJ,g)}else if(1===a){var m;if("aac"===(null==(m=e.mediaInfo)?void 0:m.aCodec)){for(var p=c,v=0;v`):sr}(t)}))}const lr=ar,hr=/^(\d+)x(\d+)$/,cr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class dr{constructor(e){"string"==typeof e&&(e=dr.parseAttrList(e)),Qi(this,e)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;eNumber.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return"YES"===this[e]}decimalResolution(e){const t=hr.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={};for(cr.lastIndex=0;null!==(t=cr.exec(e));){let e=t[2];0===e.indexOf('"')&&e.lastIndexOf('"')===e.length-1&&(e=e.slice(1,-1));i[t[1].trim()]=e}return i}}function ur(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}class fr{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){lr.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=Qi(new dr({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=new Date(this.attr["END-DATE"]);Ji(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Ji(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&Ji(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class gr{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var mr="audio",pr="video",vr="audiovideo";class yr{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[mr]:null,[pr]:null,[vr]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2);let r;r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Wi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class Tr extends yr{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new gr,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!Ji(this.programDateTime))return null;const e=Ji(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,r,s,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[mr]=null,e[pr]=null,e[vr]=null}}class Er extends yr{constructor(e,t,i,r,s){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new gr,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}class Sr{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&Ji(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function br(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function Lr(e){const t=e.split(":");let i=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){const t="base64"===r[0],s=r[1];t?(e.splice(-1,1),i=br(s)):i=function(e){const t=wr(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(s)}}return i}function wr(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}const Ar="undefined"!=typeof self?self:void 0;var Rr={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},kr="org.w3.clearkey",_r="com.apple.streamingkeydelivery",Dr="com.microsoft.playready",xr="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Cr(e){switch(e){case _r:return Rr.FAIRPLAY;case Dr:return Rr.PLAYREADY;case xr:return Rr.WIDEVINE;case kr:return Rr.CLEARKEY}}var Ir="edef8ba979d64acea3c827dcd51d21ed";function Pr(e){switch(e){case Rr.FAIRPLAY:return _r;case Rr.PLAYREADY:return Dr;case Rr.WIDEVINE:return xr;case Rr.CLEARKEY:return kr}}function Or(e){const{drmSystems:t,widevineLicenseUrl:i}=e,r=t?[Rr.FAIRPLAY,Rr.WIDEVINE,Rr.PLAYREADY,Rr.CLEARKEY].filter((e=>!!t[e])):[];return!r[Rr.WIDEVINE]&&i&&r.push(Rr.WIDEVINE),r}const Mr=null!=Ar&&null!=(Fr=Ar.navigator)&&Fr.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Fr;function Nr(e,t,i){return Uint8Array.prototype.slice?e.slice(t,i):new Uint8Array(Array.prototype.slice.call(e,t,i))}const Ur=(e,t)=>t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,Br=(e,t)=>t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,$r=(e,t)=>{const i=t;let r=0;for(;Ur(e,t);){r+=10;r+=Gr(e,t+6),Br(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(i,i+r)},Gr=(e,t)=>{let i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3],i},Kr=(e,t)=>Ur(e,t)&&Gr(e,t+6)+10<=e.length-t,Vr=e=>{const t=Wr(e);for(let e=0;ee&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,jr=e=>{const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=Gr(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}},Wr=e=>{let t=0;const i=[];for(;Ur(e,t);){const r=Gr(e,t+6);t+=10;const s=t+r;for(;t+8"PRIV"===e.type?qr(e):"W"===e.type[0]?Xr(e):zr(e),qr=e=>{if(e.size<2)return;const t=Jr(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}},zr=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1;const i=Jr(e.data.subarray(t),!0);t+=i.length+1;const r=Jr(e.data.subarray(t));return{key:e.type,info:i,data:r}}const t=Jr(e.data.subarray(1));return{key:e.type,data:t}},Xr=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1;const i=Jr(e.data.subarray(t),!0);t+=i.length+1;const r=Jr(e.data.subarray(t));return{key:e.type,info:i,data:r}}const t=Jr(e.data);return{key:e.type,data:t}},Qr=e=>{if(8===e.data.byteLength){const t=new Uint8Array(e.data),i=1&t[3];let r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}},Jr=(e,t=!1)=>{const i=es();if(i){const r=i.decode(e);if(t){const e=r.indexOf("\0");return-1!==e?r.substring(0,e):r}return r.replace(/\0/g,"")}const r=e.length;let s,n,a,o="",l=0;for(;l>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:n=e[l++],o+=String.fromCharCode((31&s)<<6|63&n);break;case 14:n=e[l++],a=e[l++],o+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&a)}}return o};let Zr;function es(){if(!navigator.userAgent.includes("PlayStation 4"))return Zr||void 0===self.TextDecoder||(Zr=new self.TextDecoder("utf-8")),Zr}const ts=function(e){let t="";for(let i=0;i>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function ds(e,t){const i=[];if(!t.length)return i;const r=e.byteLength;for(let s=0;s1?s+n:r;if(ns(e.subarray(s+4,s+8))===t[0])if(1===t.length)i.push(e.subarray(s+8,a));else{const r=ds(e.subarray(s+8,a),t.slice(1));r.length&&rs.apply(i,r)}s=a}return i}function us(e){const t=[],i=e[0];let r=8;const s=os(e,r);r+=4;let n=0,a=0;0===i?(n=os(e,r),a=os(e,r+4),r+=8):(n=ls(e,r),a=ls(e,r+8),r+=16),r+=2;let o=e.length+a;const l=as(e,r);r+=2;for(let i=0;i>>31)return lr.warn("SIDX has hierarchical references (not supported)"),null;const l=os(e,i);i+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,i+=4,r=i}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:t}}function fs(e){const t=[],i=ds(e,["moov","trak"]);for(let e=0;e{const i=os(e,4),r=t[i];r&&(r.default={duration:os(e,12),flags:os(e,20)})})),t}function gs(e){const t=e.subarray(8),i=t.subarray(86),r=ns(t.subarray(4,8));let s=r;const n="enca"===r||"encv"===r;if(n){const e=ds(t,[r])[0];ds(e.subarray("enca"===r?28:78),["sinf"]).forEach((e=>{const t=ds(e,["schm"])[0];if(t){const i=ns(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=ds(e,["frma"])[0];t&&(s=ns(t))}}}))}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const e=ds(i,["avcC"])[0];s+="."+ps(e[1])+ps(e[2])+ps(e[3]);break}case"mp4a":{const e=ds(t,[r])[0],i=ds(e.subarray(28),["esds"])[0];if(i&&i.length>12){let e=4;if(3!==i[e++])break;e=ms(i,e),e+=2;const t=i[e++];if(128&t&&(e+=2),64&t&&(e+=i[e++]),4!==i[e++])break;e=ms(i,e);const r=i[e++];if(64!==r)break;if(s+="."+ps(r),e+=12,5!==i[e++])break;e=ms(i,e);const n=i[e++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&i[e])>>5)),s+="."+a}break}case"hvc1":case"hev1":{const e=ds(i,["hvcC"])[0],t=e[1],r=["","A","B","C"][t>>6],n=31&t,a=os(e,2),o=(32&t)>>5?"H":"L",l=e[12],h=e.subarray(6,12);s+="."+r+n,s+="."+a.toString(16).toUpperCase(),s+="."+o+l;let c="";for(let e=h.length;e--;){const t=h[e];if(t||c){c="."+t.toString(16).toUpperCase()+c}}s+=c;break}case"dvh1":case"dvhe":{const e=ds(i,["dvcC"])[0],t=e[2]>>1&127,r=e[2]<<5&32|e[3]>>3&31;s+="."+vs(t)+"."+vs(r);break}case"vp09":{const e=ds(i,["vpcC"])[0],t=e[4],r=e[5],n=e[6]>>4&15;s+="."+vs(t)+"."+vs(r)+"."+vs(n);break}case"av01":{const e=ds(i,["av1C"])[0],t=e[1]>>>5,r=31&e[1],n=e[2]>>>7?"H":"M",a=(64&e[2])>>6,o=(32&e[2])>>5,l=2===t&&a?o?12:10:a?10:8,h=(16&e[2])>>4,c=(8&e[2])>>3,d=(4&e[2])>>2,u=3&e[2],f=1,g=1,m=1,p=0;s+="."+t+"."+vs(r)+n+"."+vs(l)+"."+h+"."+c+d+u+"."+vs(f)+"."+vs(g)+"."+vs(m)+"."+p;break}}return{codec:s,encrypted:n}}function ms(e,t){const i=t+5;for(;128&e[t++]&&t{const l=o.byteOffset-8;ds(o,["traf"]).map((o=>{const h=ds(o,["tfdt"]).map((e=>{const t=e[0];let i=os(e,4);return 1===t&&(i*=Math.pow(2,32),i+=os(e,8)),i/s}))[0];return void 0!==h&&(e=h),ds(o,["tfhd"]).map((h=>{const c=os(h,4),d=16777215&os(h,0);let u=0;const f=!!(16&d);let g=0;const m=!!(32&d);let p=8;c===n&&(!!(1&d)&&(p+=8),!!(2&d)&&(p+=4),!!(8&d)&&(u=os(h,p),p+=4),f&&(g=os(h,p),p+=4),m&&(p+=4),"video"===t.type&&(a=function(e){if(!e)return!1;const t=e.indexOf("."),i=t<0?e:e.substring(0,t);return"hvc1"===i||"hev1"===i||"dvh1"===i||"dvhe"===i}(t.codec)),ds(o,["trun"]).map((n=>{const o=n[0],h=16777215&os(n,0),c=!!(1&h);let d=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const T=!!(1024&h),E=!!(2048&h);let S=0;const b=os(n,4);let L=8;c&&(d=os(n,L),L+=4),f&&(L+=4);let w=d+l;for(let l=0;l>1&63;return 39===e||40===e}return 6===(31&t)}function Ls(e,t,i,r){const s=ws(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);const e=s.length-n;let t=n;if(oe){lr.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===s[t++]){const e=as(s,t);if(t+=2,49===e){const e=os(s,t);if(t+=4,1195456820===e){const e=s[t++];if(3===e){const n=s[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e16){const e=[];for(let i=0;i<16;i++){const r=s[t++].toString(16);e.push(1==r.length?"0"+r:r),3!==i&&5!==i&&7!==i&&9!==i||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e,...t){const i=t.length;let r=8,s=i;for(;s--;)r+=t[s].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(e,4),s=0,r=8;s>8*(15-i)&255;return t}(e);return new ks(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=Lr(this.uri);if(t)switch(this.keyFormat){case xr:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Dr:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=As(e,0,t);const i=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(i)),s=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const e=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(e){const t=br(e).subarray(0,16);!function(e){const t=function(e,t,i){const r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(t),this.keyId=t}}break}default:{let e=t.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=Rs[this.uri];if(!e){const t=Object.keys(Rs).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),Rs[this.uri]=e}this.keyId=e}return this}}const _s=/\{\$([a-zA-Z0-9-_]+)\}/g;function Ds(e){return _s.test(e)}function xs(e,t,i){if(null!==e.variableList||e.hasVariableRefs)for(let r=i.length;r--;){const s=i[r],n=t[s];n&&(t[s]=Cs(e,n))}}function Cs(e,t){if(null!==e.variableList||e.hasVariableRefs){const i=e.variableList;return t.replace(_s,(t=>{const r=t.substring(2,t.length-1),s=null==i?void 0:i[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):s}))}return t}function Is(e,t,i){let r,s,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{const e=new self.URL(i).searchParams;if(!e.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${i}"`);s=e.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,s=t.VALUE;r in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=s||""}function Ps(e,t,i){const r=t.IMPORT;if(i&&r in i){let t=e.variableList;t||(e.variableList=t={}),t[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}function Os(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const Ms={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Fs(e,t,i=!0){return!e.split(",").some((e=>!Ns(e,t,i)))}function Ns(e,t,i=!0){var r;const s=Os(i);return null!=(r=null==s?void 0:s.isTypeSupported(Us(e,t)))&&r}function Us(e,t){return`${t}/mp4;codecs="${e}"`}function Bs(e){if(e){const t=e.substring(0,4);return Ms.video[t]}return 2}function $s(e){return e.split(",").reduce(((e,t)=>{const i=Ms.video[t];return i?(2*i+e)/(e?3:2):(Ms.audio[t]+e)/(e?2:1)}),0)}const Gs={};const Ks=/flac|opus/i;function Vs(e,t=!0){return e.replace(Ks,(e=>function(e,t=!0){if(Gs[e])return Gs[e];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[e];for(let r=0;r0&&r.length({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:n.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Ws.lastIndex=0;null!==(r=Ws.exec(e));){const e=new dr(r[1]),n=e.TYPE;if(n){const r=a[n],l=s[n]||[];s[n]=l,xs(i,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h=e.LANGUAGE,c=e["ASSOC-LANGUAGE"],d=e.CHANNELS,u=e.CHARACTERISTICS,f=e["INSTREAM-ID"],g={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||h||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:h,url:e.URI?Xs.resolve(e.URI,t):""};if(c&&(g.assocLang=c),d&&(g.channels=d),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=r&&r.length){const e=Xs.findGroup(r,g.groupId)||r[0];en(g,e,"audioCodec"),en(g,e,"textCodec")}l.push(g)}}return s}static parseLevelPlaylist(e,t,i,r,s,n){const a=new Sr(t),o=a.fragments;let l,h,c,d=null,u=0,f=0,g=0,m=0,p=null,v=new Tr(r,t),y=-1,T=!1,E=null;for(qs.lastIndex=0,a.m3u8=e,a.hasVariableRefs=Ds(e);null!==(l=qs.exec(e));){T&&(T=!1,v=new Tr(r,t),v.start=g,v.sn=u,v.cc=m,v.level=i,d&&(v.initSegment=d,v.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null,E&&(v.setByteRange(E),E=null)));const e=l[1];if(e){v.duration=parseFloat(e);const t=(" "+l[2]).slice(1);v.title=t||null,v.tagList.push(t?["INF",e,t]:["INF",e])}else if(l[3]){if(Ji(v.duration)){v.start=g,c&&sn(v,c,a),v.sn=u,v.level=i,v.cc=m,o.push(v);const e=(" "+l[3]).slice(1);v.relurl=Cs(a,e),tn(v,p),p=v,g+=v.duration,u++,f=0,T=!0}}else if(l[4]){const e=(" "+l[4]).slice(1);p?v.setByteRange(e,p):v.setByteRange(e)}else if(l[5])v.rawProgramDateTime=(" "+l[5]).slice(1),v.tagList.push(["PROGRAM-DATE-TIME",v.rawProgramDateTime]),-1===y&&(y=o.length);else{if(l=l[0].match(zs),!l){lr.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h0&&e.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),a.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new dr(s);a.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=a.partList;e||(e=a.partList=[]);const i=f>0?e[e.length-1]:void 0,r=f++,n=new dr(s);xs(a,n,["BYTERANGE","URI"]);const o=new Er(n,v,t,r,i);e.push(o),v.duration+=o.duration;break}case"PRELOAD-HINT":{const e=new dr(s);xs(a,e,["URI"]),a.preloadHint=e;break}case"RENDITION-REPORT":{const e=new dr(s);xs(a,e,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(e);break}default:lr.warn(`line parsed but not handled: ${l}`)}}}p&&!p.relurl?(o.pop(),g-=p.duration,a.partList&&(a.fragmentHint=p)):a.partList&&(tn(v,p),v.cc=m,a.fragmentHint=v,c&&sn(v,c,a));const S=o.length,b=o[0],L=o[S-1];if(g+=a.skippedSegments*a.targetduration,g>0&&S&&L){a.averagetargetduration=g/S;const e=L.sn;a.endSN="initSegment"!==e?e:0,a.live||(L.endList=!0),b&&(a.startCC=b.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(g+=a.fragmentHint.duration),a.totalduration=g,a.endCC=m,y>0&&function(e,t){let i=e[t];for(let r=t;r--;){const t=e[r];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(o,y),a}}function Qs(e,t,i){var r,s;const n=new dr(e);xs(i,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,c=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&lr.error(`Invalid IV: ${n.IV}`);const d=o?Xs.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new ks(a,d,c,u,l)}function Js(e){const t=new dr(e).decimalFloatingPoint("TIME-OFFSET");return Ji(t)?t:null}function Zs(e,t){let i=(e||"").split(/[ ,]+/).filter((e=>e));["video","audio","text"].forEach((e=>{const r=i.filter((t=>function(e,t){const i=Ms[t];return!!i&&!!i[e.slice(0,4)]}(t,e)));r.length&&(t[`${e}Codec`]=r.join(","),i=i.filter((e=>-1===r.indexOf(e))))})),t.unknownCodecs=i}function en(e,t,i){const r=t[i];r&&(e[i]=r)}function tn(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Ji(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function rn(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function sn(e,t,i){e.levelkeys=t;const{encryptedFragments:r}=i;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||r.push(e)}var nn="manifest",an="level",on="audioTrack",ln="subtitleTrack",hn="main",cn="audio",dn="subtitle";function un(e){const{type:t}=e;switch(t){case on:return cn;case ln:return dn;default:return hn}}function fn(e,t){let i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}class gn{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.LEVEL_LOADING,this.onLevelLoading,this),e.on(tr.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(tr.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.LEVEL_LOADING,this.onLevelLoading,this),e.off(tr.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(tr.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:nn,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:r,pathwayId:s,url:n,deliveryDirectives:a}=t;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:an,url:n,deliveryDirectives:a})}onAudioTrackLoading(e,t){const{id:i,groupId:r,url:s,deliveryDirectives:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:on,url:s,deliveryDirectives:n})}onSubtitleTrackLoading(e,t){const{id:i,groupId:r,url:s,deliveryDirectives:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ln,url:s,deliveryDirectives:n})}load(e){var t;const i=this.hls.config;let r,s=this.getInternalLoader(e);if(s){const t=s.context;if(t&&t.url===e.url&&t.level===e.level)return void lr.trace("[playlist-loader]: playlist request ongoing");lr.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(r=e.type===nn?i.manifestLoadPolicy.default:Qi({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),Ji(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===an&&null!==e.level?t=this.hls.levels[e.level].details:e.type===on&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===ln&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,i=t.targetduration;if(e&&i){const t=1e3*Math.max(3*e,.8*i);r=Qi({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,i,r)=>{const s=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=e.data;0===n.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),Xs.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(e,t,i,r||null,s):this.handleMasterPlaylist(e,t,i,r)):this.handleManifestParsingError(e,i,new Error("no EXTM3U delimiter"),r||null,t)},onError:(e,t,i,r)=>{this.handleNetworkError(t,i,!1,e,r)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}};s.load(e,a,o)}handleMasterPlaylist(e,t,i,r){const s=this.hls,n=e.data,a=fn(e,i),o=Xs.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,i,o.playlistParsingError,r,t);const{contentSteering:l,levels:h,sessionData:c,sessionKeys:d,startTimeOffset:u,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=Xs.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((e=>!e.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(lr.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new dr({}),bitrate:0,url:""}))}s.trigger(tr.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:c,sessionKeys:d,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,r,s){const n=this.hls,{id:a,level:o,type:l}=i,h=fn(e,i),c=Ji(o)?o:Ji(a)?a:0,d=un(i),u=Xs.parseLevelPlaylist(e.data,h,c,d,0,this.variableList);if(l===nn){const e={attrs:new dr({}),bitrate:0,details:u,name:"",url:h};n.trigger(tr.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=u,this.handlePlaylistLoaded(u,e,t,i,r,s)}handleManifestParsingError(e,t,i,r,s){this.hls.trigger(tr.ERROR,{type:ir.NETWORK_ERROR,details:rr.MANIFEST_PARSING_ERROR,fatal:t.type===nn,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,i=!1,r,s){let n=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===an?n+=`: ${e.level} id: ${e.id}`:e.type!==on&&e.type!==ln||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);lr.warn(`[playlist-loader]: ${n}`);let o=rr.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case nn:o=i?rr.MANIFEST_LOAD_TIMEOUT:rr.MANIFEST_LOAD_ERROR,l=!0;break;case an:o=i?rr.LEVEL_LOAD_TIMEOUT:rr.LEVEL_LOAD_ERROR,l=!1;break;case on:o=i?rr.AUDIO_TRACK_LOAD_TIMEOUT:rr.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ln:o=i?rr.SUBTITLE_TRACK_LOAD_TIMEOUT:rr.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const c={type:ir.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:s};if(r){const i=(null==t?void 0:t.url)||e.url;c.response=qi({url:i,data:void 0},r)}this.hls.trigger(tr.ERROR,c)}handlePlaylistLoaded(e,t,i,r,s,n){const a=this.hls,{type:o,level:l,id:h,groupId:c,deliveryDirectives:d}=r,u=fn(t,r),f=un(r),g="number"==typeof r.level&&f===hn?l:void 0;if(!e.fragments.length){const e=new Error("No Segments found in Playlist");return void a.trigger(tr.ERROR,{type:ir.NETWORK_ERROR,details:rr.LEVEL_EMPTY_ERROR,fatal:!1,url:u,error:e,reason:e.message,response:t,context:r,level:g,parent:f,networkDetails:s,stats:i})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const m=e.playlistParsingError;if(m)a.trigger(tr.ERROR,{type:ir.NETWORK_ERROR,details:rr.LEVEL_PARSING_ERROR,fatal:!1,url:u,error:m,reason:m.message,response:t,context:r,level:g,parent:f,networkDetails:s,stats:i});else switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case nn:case an:a.trigger(tr.LEVEL_LOADED,{details:e,level:g||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:d});break;case on:a.trigger(tr.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:c||"",stats:i,networkDetails:s,deliveryDirectives:d});break;case ln:a.trigger(tr.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:c||"",stats:i,networkDetails:s,deliveryDirectives:d})}}}function mn(e,t){let i;try{i=new Event("addtrack")}catch(e){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function pn(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){lr.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){lr.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function vn(e){const t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(let t=e.cues.length;t--;)e.removeCue(e.cues[t]);"disabled"===t&&(e.mode=t)}function yn(e,t,i,r){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){const s=function(e,t,i){const r=[],s=function(e,t){if(te[i].endTime)return-1;let r=0,s=i;for(;r<=s;){const n=Math.floor((s+r)/2);if(te[n].startTime&&r-1)for(let n=s,a=e.length;n=t&&s.endTime<=i)r.push(s);else if(s.startTime>i)return r}return r}(e.cues,t,i);for(let t=0;t{const e=Ln();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Rn(e,t){return e.getTime()/1e3-t}class kn{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(vn(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;tAn&&(r=An);r-i<=0&&(r=i+.25);for(let e=0;ee.type===En&&o:"video"===r?e=>e.type===bn&&a:e=>e.type===En&&o||e.type===bn&&a,yn(s,t,i,e)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:r}=this,{dateRanges:s}=t,n=Object.keys(s);if(r){const e=Object.keys(i).filter((e=>!n.includes(e)));for(let t=e.length;t--;){const s=e[t];Object.keys(i[s].cues).forEach((e=>{r.removeCue(i[s].cues[e])})),delete i[s]}}const a=t.fragments[t.fragments.length-1];if(0===n.length||!Ji(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=Ln();for(let e=0;e{if(t!==r.id){const i=s[t];if(i.class===r.class&&i.startDate>r.startDate&&(!e||r.startDatethis.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(null===e)return null;const{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||t;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:n*r);const h=r;return l+Math.min(1*this.stallCount,h)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(null===e||null===t||null===i)return null;const r=i.edge,s=e-t-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}get drift(){const{levelDetails:e}=this;return null===e?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(tr.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(tr.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===rr.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(i=this.levelDetails)&&i.live&&lr.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(t,Math.max(1,i))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}const Dn=["NONE","TYPE-0","TYPE-1",null];const xn=["SDR","PQ","HLG"];var Cn="",In="YES",Pn="v2";function On(e){const{canSkipUntil:t,canSkipDateRanges:i,age:r}=e;return t&&r!!e)).map((e=>e.substring(0,4))).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Nn(this._audioGroups,e)}hasSubtitleGroup(e){return Nn(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function Nn(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Un(e,t){const i=t.startPTS;if(Ji(i)){let r,s=0;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&(r.duration=s)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration}else t.start=Math.max(e.start-t.duration,0)}function Bn(e,t,i,r,s,n){r-i<=0&&(lr.warn("Fragment should have a positive duration",t),r=i+t.duration,n=s+t.duration);let a=i,o=r;const l=t.startPTS,h=t.endPTS;if(Ji(l)){const e=Math.abs(l-i);Ji(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(i,l),i=Math.min(i,l),s=Math.min(s,t.startDTS),o=Math.min(r,h),r=Math.max(r,h),n=Math.max(n,t.endDTS)}const c=i-t.start;0!==t.start&&(t.start=i),t.duration=r-t.start,t.startPTS=i,t.maxStartPTS=a,t.startDTS=s,t.endPTS=r,t.minEndPTS=o,t.endDTS=n;const d=t.sn;if(!e||de.endSN)return 0;let u;const f=d-e.startSN,g=e.fragments;for(g[f]=t,u=f;u>0;u--)Un(g[u],g[u-1]);for(u=f;u=0;e--){const t=r[e].initSegment;if(t){i=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let s,n=0;if(function(e,t,i){const r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let e=s;e<=n;e++){const s=l[a+e];let n=o[e];r&&!n&&e{e.relurl&&(n=e.cc-r.cc),Ji(e.startPTS)&&Ji(e.endPTS)&&(r.start=r.startPTS=e.startPTS,r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.duration=e.endPTS-e.startPTS,r.duration&&(s=r),t.PTSKnown=t.alignedSliding=!0),r.elementaryStreams=e.elementaryStreams,r.loader=e.loader,r.stats=e.stats,e.initSegment&&(r.initSegment=e.initSegment,i=e.initSegment)})),i){(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach((e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)}))}if(t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some((e=>!e)),t.deltaUpdateFailed){lr.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){const r=Qi({},e);i&&i.forEach((e=>{delete r[e]}));return Object.keys(t).forEach((e=>{const i=new fr(t[e].attr,r[e]);i.isValid?r[e]=i:lr.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),r}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const a=t.fragments;if(n){lr.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?Bn(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):Gn(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const e=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=e),t.driftEndTime=o,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function Gn(e,t){const i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments;i<0||i>=r.length||Kn(t,r[i].start)}function Kn(e,t){if(t){const i=e.fragments;for(let r=e.skippedSegments;r{const{details:i}=e;null!=i&&i.fragments&&i.fragments.forEach((e=>{e.level=t}))}))}function Wn(e){switch(e.details){case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_TIMEOUT:case rr.LEVEL_LOAD_TIMEOUT:case rr.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Yn(e,t){const i=Wn(t);return e.default[(i?"timeout":"error")+"Retry"]}function qn(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function zn(e){return qi(qi({},e),{errorRetry:null,timeoutRetry:null})}function Xn(e,t,i,r){if(!e)return!1;const s=null==r?void 0:r.code,n=t499)}(s)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}const Qn=function(e,t){let i=0,r=e.length-1,s=null,n=null;for(;i<=r;){s=(i+r)/2|0,n=e[s];const a=t(n);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null};function Jn(e,t,i=0,r=0,s=.005){let n=null;if(e){n=t[e.sn-t[0].sn+1]||null;const r=e.endDTS-i;r>0&&r<15e-7&&(i+=15e-7)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===Zn(i,r,n)||function(e,t,i){if(t&&0===t.start&&t.level0){const r=t.tagList.reduce(((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e)),i);return e.start<=r}return!1}(n,e,Math.min(s,r))))return n;const a=Qn(t,Zn.bind(null,i,r));return!a||a===e&&n?n:a}function Zn(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;const r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function ea(e,t,i){const r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}var ta=0,ia=2,ra=3,sa=5,na=0,aa=1,oa=2;class la{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=lr.log.bind(lr,`${t}:`),this.warn=lr.warn.bind(lr,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const r=null==t?void 0:t.renditionReports;if(r){let s=-1;for(let i=0;i=0&&e>t.partTarget&&(a+=1)}const o=i&&On(i);return new Mn(n,a>=0?a:void 0,o)}}}loadPlaylist(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){const{details:r,stats:s}=t,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;if(r.advancedDateTime=Date.now()-a,r.live||null!=i&&i.live){if(r.reloaded(i),i&&this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),i&&r.fragments.length>0&&$n(i,r),!this.canLoad||!r.live)return;let a,o,l;if(r.canBlockReload&&r.endSN&&r.advanced){const e=this.hls.config.lowLatencyMode,s=r.lastPartSn,n=r.endSN,h=r.lastPartIndex,c=s===n;-1!==h?(o=c?n+1:s,l=c?e?0:h:h+1):o=n+1;const d=r.age,u=d+r.ageHeader;let f=Math.min(u-r.partTarget,1.5*r.targetduration);if(f>0){if(i&&f>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${f} with playlist age: ${r.age}`),f=0;else{const e=Math.floor(f/r.targetduration);if(o+=e,void 0!==l){l+=Math.round(f%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${f} skip sn ${e} to part ${l}`)}r.tuneInGoal=f}if(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l),e||!c)return void this.loadPlaylist(a)}else(r.canBlockReload||r.canSkipUntil)&&(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l));const h=this.hls.mainForwardBufferInfo,c=h?h.end-h.len:0,d=function(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){const r=e.fragments,s=4;if(r.length&&i*s>t){const e=1e3*r[r.length-1].duration;ethis.requestScheduled+d&&(this.requestScheduled=s.loading.start),void 0!==o&&r.canBlockReload?this.requestScheduled=s.loading.first+d-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+dthis.loadPlaylist(a)),u)}else this.clearTimer()}getDeliveryDirectives(e,t,i,r){let s=On(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=Cn),new Mn(i,r,s)}checkRetry(e){const t=e.details,i=Wn(e),r=e.errorAction,{action:s,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(s===sa||!r.resolved&&s===ia);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(i&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=qn(a,n);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return o}}class ha{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class ca{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ha(e),this.fast_=new ha(t),this.defaultTTFB_=r,this.ttfb_=new ha(e)}update(e,t){const{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==e&&(this.slow_=new ha(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new ha(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new ha(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){const i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const da={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},ua={};function fa(e,t,i,r,s,n){const a=e.audioCodec?e.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let c=null;if(null!=a&&a.length)try{c=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce(((e,i)=>{if(i){const r=t.groups[i];if(!r)throw new Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach((t=>{e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(s,8e6))||!!c&&Ji(h)&&Object.keys(c).some((e=>parseInt(e)>h))}function ga(e,t,i){const r=e.videoCodec,s=e.audioCodec;if(!r||!s||!i)return Promise.resolve(da);const n={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},a=e.videoRange;"SDR"!==a&&(n.transferFunction=a.toLowerCase());const o=r.split(",").map((e=>({type:"media-source",video:qi(qi({},n),{},{contentType:Us(e,"video")})})));return s&&e.audioGroups&&e.audioGroups.forEach((e=>{var i;e&&(null==(i=t.groups[e])||i.tracks.forEach((t=>{if(t.groupId===e){const e=t.channels||"",i=parseFloat(e);Ji(i)&&i>2&&o.push.apply(o,s.split(",").map((e=>({type:"media-source",audio:{contentType:Us(e,"audio"),channels:""+i}}))))}})))})),Promise.all(o.map((e=>{const t=function(e){const{audio:t,video:i}=e,r=i||t;if(r){const e=r.contentType.split('"')[1];if(i)return`r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${e}_${Math.ceil(i.bitrate/1e5)}`;if(t)return`c${t.channels}${t.spatialRendering?"s":"n"}_${e}`}return""}(e);return ua[t]||(ua[t]=i.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:o,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:o,decodingInfoResults:[],error:e})))}function ma(e,t){let i=!1,r=[];return e&&(i="SDR"!==e,r=[e]),t&&(r=t.allowedVideoRanges||xn.slice(0),i=void 0!==t.preferHDR?t.preferHDR:function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),r=i?r.filter((e=>"SDR"!==e)):["SDR"]),{preferHDR:i,allowedVideoRanges:r}}function pa(e,t){lr.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function va(e,t,i){if("attrs"in e){const i=t.indexOf(e);if(-1!==i)return i}for(let r=0;r-1===r.indexOf(e)))}(o,t.characteristics))&&(void 0===i||i(e,t))}function Ta(e,t){const{audioCodec:i,channels:r}=e;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function Ea(e,t,i){for(let r=t;r;r--)if(i(e[r]))return r;for(let r=t+1;r1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var ba="NOT_LOADED",La="APPENDING",wa="PARTIAL",Aa="OK";class Ra{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(tr.BUFFER_APPENDED,this.onBufferAppended,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.on(tr.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.BUFFER_APPENDED,this.onBufferAppended,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.off(tr.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let t=i.length;t--;){const r=i[t];if(!r)break;const s=r.end;if(r.start<=e&&null!==s&&e<=s)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,r=Object.keys(i);for(let s=r.length;s--;){const n=i[r[s]];if((null==n?void 0:n.body.type)===t&&n.buffered){const t=n.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,r){this.timeRanges&&(this.timeRanges[e]=t);const s=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((r=>{const n=this.fragments[r];if(!n)return;if(s>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===i&&this.removeFragment(n.body));const a=n.range[e];a&&a.time.some((e=>{const i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(n.body),i}))}))}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:r}=e;if(!t||"initSegment"===i.sn)return;const s=_a(i),n=this.fragments[s];if(!n||n.buffered&&i.gap)return;const a=!i.relurl;if(Object.keys(t).forEach((e=>{const s=i.elementaryStreams[e];if(!s)return;const o=t[e],l=a||!0===s.partial;n.range[e]=this.getBufferedTimes(i,r,l,o)})),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),ka(n)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(n.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter((t=>t.fragment.sn>=e)))}fragBuffered(e,t){const i=_a(e);let r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,i,r){const s={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e=t&&o<=i){s.time.push({startPTS:Math.max(n,r.start(e)),endPTS:Math.min(a,r.end(e))});break}if(nt){const t=Math.max(n,r.start(e)),i=Math.min(a,r.end(e));i>t&&(s.partial=!0,s.time.push({startPTS:t,endPTS:i}))}else if(a<=t)break}return s}getPartialFragment(e){let t,i,r,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&ka(h)&&(i=h.body.start-a,r=h.body.end+a,e>=i&&e<=r&&(t=Math.min(e-i,r-e),n<=t&&(s=h.body,n=t)))})),s}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||ka(t))}getState(e){const t=_a(e),i=this.fragments[t];return i?i.buffered?ka(i)?wa:Aa:La:ba}isTimeBuffered(e,t,i){let r,s;for(let n=0;n=r&&t<=s)return!0;if(t<=r)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:r}=t;if("initSegment"===i.sn||i.bitrateTest)return;const s=r?null:t,n=_a(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:r,timeRanges:s}=t;if("initSegment"===i.sn)return;const n=i.type;if(r){let e=this.activePartLists[n];e||(this.activePartLists[n]=e=[]),e.push(r)}this.timeRanges=s,Object.keys(s).forEach((e=>{const t=s[e];this.detectEvictedFragments(e,t,n,r)}))}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=_a(e);return!!this.fragments[t]}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,i,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||r&&!o.gap||o.starte&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(e){const t=_a(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const t=e.sn;this.activePartLists[e.type]=i.filter((e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function ka(e){var t,i,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(i=e.range.audio)?void 0:i.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function _a(e){return`${e.type}_${e.level}_${e.sn}`}const Da={length:0,start:()=>0,end:()=>0};class xa{static isBuffered(e,t){try{if(e){const i=xa.getBuffered(e);for(let e=0;e=i.start(e)&&t<=i.end(e))return!0}}catch(e){}return!1}static bufferInfo(e,t,i){try{if(e){const r=xa.getBuffered(e),s=[];let n;for(n=0;nn&&(r[s-1].end=e[t].end):r.push(e[t])}else r.push(e[t])}else r=e;let s,n=0,a=t,o=t;for(let e=0;e=l&&ti.startCC||e&&e.cc{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o($a(e));e.gap=!1}const l=this.loader=e.loader=s?new s(r):new n(r),h=Ba(e),c=zn(r.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Na};e.stats=l.stats,l.load(h,d,{onSuccess:(t,i,r,s)=>{this.resetLoader(e,l);let n=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:s})},onError:(t,r,s,n)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:qi({url:i,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:n}))},onAbort:(t,i,r)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,i,r)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:r,stats:t}))},onProgress:(i,r,s,n)=>{t&&t({frag:e,part:null,payload:s,networkDetails:n})}})}))}loadPart(e,t,i){this.abort();const r=this.config,s=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o($a(e,t));const l=this.loader=e.loader=s?new s(r):new n(r),h=Ba(e,t),c=zn(r.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Na};t.stats=l.stats,l.load(h,d,{onSuccess:(r,s,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const h={frag:e,part:t,payload:r.data,networkDetails:o};i(h),a(h)},onError:(i,r,s,n)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:qi({url:h.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:n}))},onAbort:(i,r,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:s,stats:i}))}})}))}updateStatsFromPart(e,t){const i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){const r=Math.round(e.duration/t.duration),n=Math.min(Math.round(i.loaded/s),r),a=(r-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=r.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Ba(e,t=null){const i=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(Ji(s)&&Ji(n)){var a;let t=s,i=n;if("initSegment"===e.sn&&"AES-128"===(null==(a=e.decryptdata)?void 0:a.method)){const e=n-s;e%16&&(i=n+(16-e%16)),0!==s&&(r.resetIV=!0,t=s-16)}r.rangeStart=t,r.rangeEnd=i}return r}function $a(e,t){const i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:ir.MEDIA_ERROR,details:rr.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Ga(r)}class Ga extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ka{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class Va{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class Ha{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],c=o[2],d=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[i]^16843008*i;r[f]=v<<24|v>>>8,s[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,c[i]=v<<8|v>>>24,d[i]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,r=0;for(;r{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Ka(this.subtle,new Uint8Array(i)).decrypt(e.buffer,t)})).catch((r=>(lr.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i))))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%16;return i!==e.length&&(t=Nr(e,0,i),this.remainderData=Nr(e,i)),t}logOnce(e){this.logEnabled&&(lr.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Wa=function(e){let t="";const i=e.length;for(let r=0;ra.end){const e=n>s;(n{if(this.fragContextChanged(e))return this.warn(`Fragment ${e.sn}${t.part?" p: "+t.part.index:""} of level ${e.level} was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const i=this.state;this.fragContextChanged(e)?(i===Xa||!this.fragCurrent&&i===Za)&&(this.fragmentTracker.removeFragment(e),this.state=qa):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(tr.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state!==Ya&&this.state!==io&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===La){const t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,r?r.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(s))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===wa&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:i};this.hls.trigger(tr.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((t=>{if(!t||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:i}=this,{payload:r}=t,s=e.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&"AES-128"===s.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer).catch((t=>{throw i.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((r=>{const s=self.performance.now();return i.trigger(tr.FRAG_DECRYPTED,{frag:e,payload:r,stats:{tstart:n,tdecrypt:s}}),t.payload=r,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)})).catch((t=>{this.state!==Ya&&this.state!==io&&(this.warn(t),this.resetFragmentLoading(e))}))}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state=qa,e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var i,r,s,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===hn?"level":"track"} ${e.level} (frag:[${(null!=(i=e.startPTS)?i:NaN).toFixed(3)}-${(null!=(r=e.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?Wa(xa.getBuffered(a)):"(detached)"})`),"initSegment"!==e.sn){var o;if(e.type!==dn){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return void(this.state=qa)}const t=null==(o=this.levels)?void 0:o[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=qa,a&&(!this.loadedmetadata&&e.type==hn&&a.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:r,partsLoaded:s}=e,n=!s||0===s.length||s.some((e=>!e)),a=new Ca(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var s;const n=null==t?void 0:t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${e.level}`),this.state=za,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(tr.KEY_LOADED,e),this.state===za&&(this.state=qa),e})),this.hls.trigger(tr.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){const s=n.partList;if(s&&r){i>e.end&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(s,e,i);if(o>-1){const l=s[o];let h;return this.log(`Loading part sn: ${e.sn} p: ${l.index} cc: ${e.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Xa,h=a?a.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,l,t,r))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,r).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(tr.FRAG_LOADING,{frag:e,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(s,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),Ji(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Xa;const o=this.config.progressive;let l;return l=o&&a?a.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,r))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,o?r:void 0),a]).then((([e])=>(!o&&e&&r&&r(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(tr.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(e,t,i,r){return new Promise(((s,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,r).then((r=>{o[t.index]=r;const n=r.part;this.hls.trigger(tr.FRAG_LOADED,r);const a=Vn(i,e.sn,t.index+1)||Hn(l,e.sn,t.index+1);if(!a)return s({frag:e,part:n,partsLoaded:o});h(a)})).catch(n)};h(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===rr.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(tr.ERROR,t)}else this.hls.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Za)return void(this.fragCurrent||this.state===Ya||this.state===io||(this.state=qa));const{frag:i,part:r,level:s}=t,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n),this.updateLevelTiming(i,r,s,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:r,sn:s,part:n}=e;if(null==t||!t[r])return this.warn(`Levels object was unset while buffering fragment ${s} of level ${r}. The current chunk will not be buffered.`),null;const a=t[r],o=n>-1?Vn(a,s,n):null,l=o?o.fragment:function(e,t,i){if(null==e||!e.details)return null;const r=e.details;let s=r.fragments[t-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===t?s:tn&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return Ji(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:r}}=this,s=xa.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&s.nextStart=i&&(t.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=hn){const i=this.fragmentTracker.getAppendedFrag(e,hn);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,r=i.length;if(!r)return null;const{config:s}=this,n=i[0].start;let a;if(t.live){const o=s.initialLiveManifestSize;if(rt}getNextFragmentLoopLoading(e,t,i,r,s){const n=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(null===a)return a;if(e=a,n&&e&&!e.gap&&i.nextStart){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r);if(null!==t&&i.len+t.len>=s)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let r=-1,s=!1,n=!0;for(let a=0,o=e.length;a-1&&ii.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!Ji(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;i=i||0;for(let r=0;r=e.startSN&&s<=e.endSN){const n=t[s-e.startSN];i.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=function(e,t){return Qn(e,(e=>e.cct?-1:0))}(t,i.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){const{config:r}=this;let{fragPrevious:s}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=r,h=i.partList,c=!!(r.lowLatencyMode&&null!=h&&h.length&&o);let d;if(c&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),et-l?0:l)}else d=n[n.length-1];if(d){const e=d.sn-i.startSN,t=this.fragmentTracker.getState(d);if((t===Aa||t===wa&&d.gap)&&(s=d),s&&d.sn===s.sn&&(!c||h[0].fragment.sn>d.sn)){if(s&&d.level===s.level){const t=n[e+1];d=d.sn=n-t.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s${e.startSN} prev-sn: ${s?s.sn:"na"} fragments: ${r}`),n}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;if(i ${null==(r=this.fragCurrent)?void 0:r.url}`);const s=t.details===rr.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);const n=t.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===sa&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const r=qn(l,o);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=Qa}else if(l&&n){if(this.resetFragmentErrors(e),!(o.5;r&&this.reduceMaxBufferLength(i.len);const s=!r;return s&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(e){e===cn&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Ya&&(this.state=qa)}afterBufferFlushed(e,t,i){if(!e)return;const r=xa.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===to&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=qa}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){var s;const n=i.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce(((t,s)=>{const a=e.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${o})`),t||!1;const l=r?0:Bn(n,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(tr.LEVEL_PTS_UPDATED,{details:n,level:i,drift:l,type:s,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1)&&null===(null==(s=this.transmuxer)?void 0:s.error)){const t=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===i.fragmentError&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(t.message),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=eo,this.hls.trigger(tr.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class ao{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;return e.length?(i=1===e.length?e[0]:function(e,t){const i=new Uint8Array(t);let r=0;for(let t=0;t0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:En,duration:Number.POSITIVE_INFINITY});s{if(Ji(e))return 90*e;return 9e4*t+(i?9e4*i.baseTime/i.timescale:0)};function co(e,t){return 255===e[t]&&240==(246&e[t+1])}function uo(e,t){return 1&e[t+1]?7:9}function fo(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function go(e,t){return t+1=e.length)return!1;const r=fo(e,t);if(r<=i)return!1;const s=t+r;return s===e.length||go(e,s)}return!1}function po(e,t,i,r,s){if(!e.samplerate){const n=function(e,t,i,r){let s,n,a,o;const l=navigator.userAgent.toLowerCase(),h=r,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[i+2])>>>6);const d=(60&t[i+2])>>>2;if(!(d>c.length-1))return a=(1&t[i+2])<<2,a|=(192&t[i+3])>>>6,lr.log(`manifest codec:${r}, ADTS type:${s}, samplingIndex:${d}`),/firefox/i.test(l)?d>=6?(s=5,o=new Array(4),n=d-3):(s=2,o=new Array(2),n=d):-1!==l.indexOf("android")?(s=2,o=new Array(2),n=d):(s=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&d>=6?n=d-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(d>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(s=2,o=new Array(2)),n=d)),o[0]=s<<3,o[0]|=(14&d)>>1,o[1]|=(1&d)<<7,o[1]|=a<<3,5===s&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:c[d],channelCount:a,codec:"mp4a.40."+s,manifestCodec:h};{const t=new Error(`invalid ADTS sampling index:${d}`);e.emit(tr.ERROR,tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}}(t,i,r,s);if(!n)return;e.config=n.config,e.samplerate=n.samplerate,e.channelCount=n.channelCount,e.codec=n.codec,e.manifestCodec=n.manifestCodec,lr.log(`parsed codec:${e.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function vo(e){return 9216e4/e}function yo(e,t,i,r,s){const n=r+s*vo(e.samplerate),a=function(e,t){const i=uo(e,t);if(t+i<=e.length){const r=fo(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);let o;if(a){const{frameLength:r,headerLength:s}=a,l=s+r,h=Math.max(0,i+l-t.length);h?(o=new Uint8Array(l-s),o.set(t.subarray(i+s,t.length),0)):o=t.subarray(i+s,i+l);const c={unit:o,pts:n};return h||e.samples.push(c),{sample:c,length:l,missing:h}}const l=t.length-i;o=new Uint8Array(l),o.set(t.subarray(i,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let To=null;const Eo=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],So=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],bo=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Lo=[0,1,1,4];function wo(e,t,i,r,s){if(i+24>t.length)return;const n=Ao(t,i);if(n&&i+n.frameLength<=t.length){const a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Ao(e,t){const i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Eo[14*(3===i?3-r:3===r?3:4)+s-1],h=So[3*(3===i?0:2===i?1:2)+n],c=3===o?1:2,d=bo[i][r],u=Lo[r],f=8*d*u,g=Math.floor(d*l/h+a)*u;if(null===To){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);To=e?parseInt(e[1]):0}return!!To&&To<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:c,frameLength:g,samplesPerFrame:f}}}function Ro(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function ko(e,t){return t+1{let i=0,r=5;t+=r;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=e[t];const o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<>l,i=i?i<t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;const n=t[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>t.length)return-1;const h=t[i+6]>>5;let c=0;2===h?c+=2:(1&h&&1!==h&&(c+=2),4&h&&(c+=2));const d=(t[i+6]<<8|t[i+7])>>12-c&1,u=[2,1,2,3,3,4,4,5][h]+d,f=t[i+5]>>3,g=7&t[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|d<<2|o>>4,o<<4&224]),p=r+s*(1536/a*9e4),v=t.subarray(i,i+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:v,pts:p}),l}class Po{constructor(){this.VideoSample=null}createVideoSample(e,t,i,r){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:r,length:0}}getLastNalUnit(e){var t;let i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){const e=r.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const i=t.samples,r=i.length;if(!r)return void t.dropped++;{const t=i[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}e.debug.length&&lr.log(e.pts+"/"+e.dts+":"+e.debug)}}class Oo{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&lr.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?i<>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t,i=8,r=8;for(let s=0;s{var n;switch(r.type){case 1:{let t=!1;a=!0;const s=r.data;if(l&&s.length>4){const e=new Oo(s).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var h;if(t)null!=(h=o)&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=t;break}case 5:a=!0,null!=(n=o)&&n.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,Ls(r.data,1,i.pts,t.samples);break;case 7:{var c,d;a=!0,l=!0;const t=r.data,i=new Oo(t).readSPS();if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(c=e.pixelRatio)?void 0:c[0])!==i.pixelRatio[0]||(null==(d=e.pixelRatio)?void 0:d[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t],e.duration=s;const r=t.subarray(1,4);let n="avc1.";for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t="0"+t),n+=t}e.codec=n}break}case 8:a=!0,e.pps=[r.data];break;case 9:a=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+r.type+" ")}if(o&&a){o.units.push(r)}})),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const i=t.byteLength;let r=e.naluState||0;const s=r,n=[];let a,o,l,h=0,c=-1,d=0;for(-1===r&&(c=0,d=31&t[0],r=0,h=1);h=0){const e={data:t.subarray(c,o),type:d};n.push(e)}else{const i=this.getLastNalUnit(e.samples);i&&(s&&h<=4-s&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-s)),o>0&&(i.data=Es(i.data,t.subarray(0,o)),i.state=0))}h=0&&r>=0){const e={data:t.subarray(c,i),type:d,state:r};n.push(e)}if(0===n.length){const i=this.getLastNalUnit(e.samples);i&&(i.data=Es(i.data,t))}return e.naluState=r,n}}class Fo{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ja(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){const r=e[t].unit;if(r.length<=16)return;const s=r.subarray(16,r.length-r.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then((s=>{const n=new Uint8Array(s);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}))}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t);let r=0;for(let t=32;t{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)}))}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();const s=e[t].units;for(;!(i>=s.length);i++){const n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,r,n),this.decrypter.isSync())))return}}}}const No=188;class Uo{constructor(e,t,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.videoParser=new Mo}static probe(e){const t=Uo.syncOffset(e);return t>0&&lr.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),-1!==t}static syncOffset(e){const t=e.length;let i=Math.min(940,t-No)+1,r=0;for(;r1&&(0===n&&a>2||o+No>i))return n}r++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:ss[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Uo.createTrack("video"),this._audioTrack=Uo.createTrack("audio",r),this._id3Track=Uo.createTrack("id3"),this._txtTrack=Uo.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,r=!1){let s;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,c=n.pesData,d=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=Es(this.remainderData,e)).length,this.remainderData=null),y>4>1){if(E=t+5+e[t+4],E===t+No)continue}else E=t+4;switch(y){case h:r&&(c&&(s=Ho(c))&&this.videoParser.parseAVCPES(n,l,s,!1,this._duration),c={data:[],size:0}),c&&(c.data.push(e.subarray(E,t+No)),c.size+=t+No-E);break;case d:if(r){if(f&&(s=Ho(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(E,t+No)),f.size+=t+No-E);break;case u:r&&(g&&(s=Ho(g))&&this.parseID3PES(o,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(E,t+No)),g.size+=t+No-E);break;case 0:r&&(E+=e[E]+1),v=this._pmtId=$o(e,E);break;case v:{r&&(E+=e[E]+1);const s=Go(e,E,this.typeSupported,i,this.observer);h=s.videoPid,h>0&&(n.pid=h,n.segmentCodec=s.segmentVideoCodec),d=s.audioPid,d>0&&(a.pid=d,a.segmentCodec=s.segmentAudioCodec),u=s.id3Pid,u>0&&(o.pid=u),null===m||p||(lr.warn(`MPEG-TS PMT found at ${t} after unknown PID '${m}'. Backtracking to sync byte @${T} to parse all TS packets.`),m=null,t=T-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else E++;E>0&&Ko(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`)),n.pesData=c,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:r,textTrack:s}=e,n=i.pesData,a=t.pesData,o=r.pesData;let l;if(n&&(l=Ho(n))?(this.videoParser.parseAVCPES(i,s,l,!0,this._duration),i.pesData=null):i.pesData=n,a&&(l=Ho(a))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&lr.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=Ho(o))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(e,t,i){const r=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new Fo(this.observer,this.config,t);return this.decrypt(r,s)}decrypt(e,t){return new Promise((i=>{const{audioTrack:r,videoTrack:s}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,(()=>{i(e)})):i(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(()=>{i(e)}))}))}destroy(){this._duration=0}parseAACPES(e,t){let i=0;const r=this.aacOverFlow;let s,n,a,o=t.data;if(r){this.aacOverFlow=null;const t=r.missing,s=r.sample.unit.byteLength;if(-1===t)o=Es(r.sample.unit,o);else{const n=s-t;r.sample.unit.set(o.subarray(0,t),n),e.samples.push(r.sample),i=r.missing}}for(s=i,n=o.length;s0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void lr.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=Qi({},t,{type:this._videoTrack?bn:En,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Bo(e,t){return((31&e[t+1])<<8)+e[t+2]}function $o(e,t){return(31&e[t+10])<<8|e[t+11]}function Go(e,t,i,r,s){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t0){let r=t+5,s=o;for(;s>2;){if(106===e[r])!0!==i.ac3?lr.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=a,n.segmentAudioCodec="ac3");const t=e[r+1]+2;r+=t,s-=t}}break;case 194:case 135:return Ko(s,new Error("Unsupported EC-3 in M2TS found")),n;case 36:return Ko(s,new Error("Unsupported HEVC in M2TS found")),n}t+=o+5}return n}function Ko(e,t,i){lr.warn(`parsing error: ${t.message}`),e.emit(tr.ERROR,tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function Vo(e){lr.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Ho(e){let t,i,r,s,n,a=0;const o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=Es(o[0],o[1]),o.splice(1,1);t=o[0];if(1===(t[0]<<16)+(t[1]<<8)+t[2]){if(i=(t[4]<<8)+t[5],i&&i>e.size-6)return null;const l=t[7];192&l&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?(n=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,s-n>54e5&&(lr.warn(`${Math.round((s-n)/9e4)}s delta between PTS and DTS, align them`),s=n)):n=s),r=t[8];let h=r+9;if(e.size<=h)return null;e.size-=h;const c=new Uint8Array(e.size);for(let e=0,i=o.length;ei){h-=i;continue}t=t.subarray(h),i-=h,h=0}c.set(t,a),a+=i}return i&&(i-=r+3),{data:c,pts:s,dts:n,len:i}}return null}class jo{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const Wo=Math.pow(2,32)-1;class Yo{static init(){let e;for(e in Yo.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Yo.types)Yo.types.hasOwnProperty(e)&&(Yo.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Yo.HDLR_TYPES={video:t,audio:i};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);Yo.STTS=Yo.STSC=Yo.STCO=s,Yo.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Yo.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Yo.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Yo.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Yo.FTYP=Yo.box(Yo.types.ftyp,n,o,n,a),Yo.DINF=Yo.box(Yo.types.dinf,Yo.box(Yo.types.dref,r))}static box(e,...t){let i=8,r=t.length;const s=r;for(;r--;)i+=t[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(e,4),r=0,i=8;r>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return Yo.box(Yo.types.mdia,Yo.mdhd(e.timescale,e.duration),Yo.hdlr(e.type),Yo.minf(e))}static mfhd(e){return Yo.box(Yo.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?Yo.box(Yo.types.minf,Yo.box(Yo.types.smhd,Yo.SMHD),Yo.DINF,Yo.stbl(e)):Yo.box(Yo.types.minf,Yo.box(Yo.types.vmhd,Yo.VMHD),Yo.DINF,Yo.stbl(e))}static moof(e,t,i){return Yo.box(Yo.types.moof,Yo.mfhd(e),Yo.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Yo.trak(e[t]);return Yo.box.apply(null,[Yo.types.moov,Yo.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(Yo.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Yo.trex(e[t]);return Yo.box.apply(null,[Yo.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Wo+1)),r=Math.floor(t%(Wo+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Yo.box(Yo.types.mvhd,s)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let r,s;for(r=0;r>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));for(t=0;t>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));const a=Yo.box(Yo.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,h=e.pixelRatio[0],c=e.pixelRatio[1];return Yo.box(Yo.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Yo.box(Yo.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Yo.box(Yo.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return Yo.box(Yo.types.mp4a,Yo.audioStsd(e),Yo.box(Yo.types.esds,Yo.esds(e)))}static mp3(e){return Yo.box(Yo.types[".mp3"],Yo.audioStsd(e))}static ac3(e){return Yo.box(Yo.types["ac-3"],Yo.audioStsd(e),Yo.box(Yo.types.dac3,e.config))}static stsd(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?Yo.box(Yo.types.stsd,Yo.STSD,Yo.mp3(e)):"ac3"===e.segmentCodec?Yo.box(Yo.types.stsd,Yo.STSD,Yo.ac3(e)):Yo.box(Yo.types.stsd,Yo.STSD,Yo.mp4a(e)):Yo.box(Yo.types.stsd,Yo.STSD,Yo.avc1(e))}static tkhd(e){const t=e.id,i=e.duration*e.timescale,r=e.width,s=e.height,n=Math.floor(i/(Wo+1)),a=Math.floor(i%(Wo+1));return Yo.box(Yo.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,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,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){const i=Yo.sdtp(e),r=e.id,s=Math.floor(t/(Wo+1)),n=Math.floor(t%(Wo+1));return Yo.box(Yo.types.traf,Yo.box(Yo.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),Yo.box(Yo.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n])),Yo.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Yo.box(Yo.types.trak,Yo.tkhd(e),Yo.mdia(e))}static trex(e){const t=e.id;return Yo.box(Yo.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],r=i.length,s=12+16*r,n=new Uint8Array(s);let a,o,l,h,c,d;for(t+=8+s,n.set(["video"===e.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,d>>>24&255,d>>>16&255,d>>>8&255,255&d],12+16*a);return Yo.box(Yo.types.trun,n)}static initSegment(e){Yo.types||Yo.init();const t=Yo.moov(e);return Es(Yo.FTYP,t)}}Yo.types=void 0,Yo.HDLR_TYPES=void 0,Yo.STTS=void 0,Yo.STSC=void 0,Yo.STCO=void 0,Yo.STSZ=void 0,Yo.VMHD=void 0,Yo.SMHD=void 0,Yo.STSD=void 0,Yo.FTYP=void 0,Yo.DINF=void 0;const qo=9e4;function zo(e,t,i=1,r=!1){const s=e*t*i;return r?Math.round(s):s}function Xo(e,t=!1){return zo(e,1e3,1/qo,t)}let Qo,Jo=null,Zo=null;class el{constructor(e,t,i,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===Jo){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Jo=e?parseInt(e[1]):0}if(null===Zo){const e=navigator.userAgent.match(/Safari\/(\d+)/i);Zo=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){lr.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){lr.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){lr.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e.reduce(((e,i)=>{const r=i.pts-e;return r<-4294967296?(t=!0,tl(e,i.pts)):r>0?e:i.pts}),e[0].pts);return t&&lr.debug("PTS rollover detected"),i}remux(e,t,i,r,s,n,a,o){let l,h,c,d,u,f,g=s,m=s;const p=e.pid>-1,v=t.pid>-1,y=t.samples.length,T=e.samples.length>0,E=a&&y>0||y>1;if((!p||T)&&(!v||E)||this.ISGenerated||a){if(this.ISGenerated){var S,b,L,w;const e=this.videoTrackConfig;!e||t.width===e.width&&t.height===e.height&&(null==(S=t.pixelRatio)?void 0:S[0])===(null==(b=e.pixelRatio)?void 0:b[0])&&(null==(L=t.pixelRatio)?void 0:L[1])===(null==(w=e.pixelRatio)?void 0:w[1])||this.resetInitSegment()}else c=this.generateIS(e,t,s,n);const i=this.isVideoContiguous;let r,a=-1;if(E&&(a=function(e){for(let t=0;t0){lr.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.inputTimeScale,r=m}else-1===a&&(lr.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(T&&E){const i=this.getVideoStartPts(t.samples),r=(tl(e.samples[0].pts,i)-i)/t.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(T){if(e.samplerate||(lr.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,s,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||E||o===cn?m:void 0),E){const r=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(lr.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,m,i,r)}}else E&&(l=this.remuxVideo(t,m,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(u=il(i,s,this._initPTS,this._initDTS)),r.samples.length&&(d=rl(r,s,this._initPTS))),{audio:h,video:l,initSegment:c,independent:f,text:d,id3:u}}generateIS(e,t,i,r){const s=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let h,c,d,u=!l||r,f="audio/mp4";if(u&&(h=c=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Yo.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(d=e.inputTimeScale,l&&d===l.timescale?u=!1:h=c=s[0].pts-Math.round(d*i))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Yo.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(d=t.inputTimeScale,l&&d===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=Math.round(d*i);c=Math.min(c,tl(n[0].dts,e)-t),h=Math.min(h,e-t)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:d},this._initDTS={baseTime:c,timescale:d}):h=d=void 0,{tracks:o,initPTS:h,timescale:d}}remuxVideo(e,t,i,r){const s=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS;let h,c,d=this.nextAvcDts,u=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!i||null===d){const e=t*s,r=n[0].pts-tl(n[0].dts,n[0].pts);Jo&&null!==d&&Math.abs(e-r-d)<15e3?i=!0:d=e-r}const v=l.baseTime*s/l.timescale;for(let e=0;e0?e-1:e].dts&&(p=!0)}p&&n.sort((function(e,t){const i=e.dts-t.dts,r=e.pts-t.pts;return i||r})),h=n[0].dts,c=n[n.length-1].dts;const y=c-h,T=y?Math.round(y/(o-1)):f||e.inputTimeScale/30;if(i){const e=h-d,i=e>T,r=e<-1;if((i||r)&&(i?lr.warn(`AVC: ${Xo(e,!0)} ms (${e}dts) hole between fragments detected at ${t.toFixed(3)}`):lr.warn(`AVC: ${Xo(-e,!0)} ms (${e}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||d>=n[0].pts||Jo)){h=d;const t=n[0].pts-e;if(i)n[0].dts=h,n[0].pts=t;else for(let i=0;it);i++)n[i].dts-=e,n[i].pts-=e;lr.log(`Video: Initial PTS/DTS adjusted: ${Xo(t,!0)}/${Xo(h,!0)}, delta: ${Xo(e,!0)} ms`)}}h=Math.max(0,h);let E=0,S=0,b=h;for(let e=0;e0?t.dts-n[e-1].dts:T;if(l=e>0?t.pts-n[e-1].pts:T,i.stretchShortVideoTrack&&null!==this.nextAudioPts){const e=Math.floor(i.maxBufferHole*s),n=(r?g+r*s:this.nextAudioPts)-t.pts;n>e?(f=n-a,f<0?f=a:R=!0,lr.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const c=Math.round(t.pts-t.dts);k=Math.min(k,f),D=Math.max(D,f),_=Math.min(_,l),x=Math.max(x,l),a.push(new sl(t.key,f,h,c))}if(a.length)if(Jo){if(Jo<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Zo&&x-_0&&(r&&Math.abs(p-m)<9e3||Math.abs(tl(f[0].pts-v,p)-m)<20*l),f.forEach((function(e){e.pts=tl(e.pts-v,p)})),!i||m<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;m=0===s?0:r&&!u?Math.max(0,p):f[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let i=0,r=m;i=t*l&&h<1e4&&u){let t=Math.round(o/l);r=a-t*l,r<0&&(t--,r+=l),0===i&&(this.nextAudioPts=m=r),lr.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(r/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n0))return;S+=g;try{y=new Uint8Array(S)}catch(e){return void this.observer.emit(tr.ERROR,tr.ERROR,{type:ir.MUX_ERROR,details:rr.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!c){new DataView(y.buffer).setUint32(0,S),y.set(Yo.types.mdat,4)}}y.set(s,g);const l=s.byteLength;g+=l,d.push(new sl(!0,o,l,0)),E=n}const L=d.length;if(!L)return;const w=d[d.length-1];this.nextAudioPts=m=E+a*w.duration;const A=c?new Uint8Array(0):Yo.moof(e.sequenceNumber++,T/a,Qi({},e,{samples:d}));e.samples=[];const R=T/n,k=m/n,_={data1:A,data2:y,startPTS:R,endPTS:k,startDTS:R,endDTS:k,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,_}remuxEmptyAudio(e,t,i,r){const s=e.inputTimeScale,n=s/(e.samplerate?e.samplerate:s),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:r.startDTS*s)+l,c=r.endDTS*s+l,d=1024*n,u=Math.ceil((c-h)/d),f=jo.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(lr.warn("[mp4-remuxer]: remux empty Audio"),!f)return void lr.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let e=0;e4294967296;)e+=i;return e}function il(e,t,i,r){const s=e.samples.length;if(!s)return;const n=e.inputTimeScale;for(let a=0;ae.pts-t.pts));const n=e.samples;return e.samples=[],{samples:n}}class sl{constructor(e,t,i,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}function nl(e,t){const i=null==e?void 0:e.codec;if(i&&i.length>4)return i;if(t===mr){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return Vs(i,!1)}const e="mp4a.40.5";return lr.info(`Parsed audio codec "${i}" or audio object type not handled. Using "${e}"`),e}return lr.warn(`Unhandled video codec "${i}"`),"hvc1"===i||"hev1"===i?"hvc1.1.6.L120.90":"av01"===i?"av01.0.04M.08":"avc1.42e01e"}try{Qo=self.performance.now.bind(self.performance)}catch(e){lr.debug("Unable to use Performance API on this environment"),Qo=null==Ar?void 0:Ar.Date.now}const al=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,r){const s=this.videoTrack=oo("video",1),n=this.audioTrack=oo("audio",1),a=this.txtTrack=oo("text",1);if(this.id3Track=oo("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=fs(e);if(o.video){const{id:e,timescale:t,codec:i}=o.video;s.id=e,s.timescale=a.timescale=t,s.codec=i}if(o.audio){const{id:e,timescale:t,codec:i}=o.audio;n.id=e,n.timescale=t,n.codec=i}a.id=ss.text,s.sampleDuration=0,s.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let i=0;i8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}(e)}demux(e,t){this.timeOffset=t;let i=e;const r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Es(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},i=ds(e,["moof"]);if(i.length<2)return t.remainder=e,t;const r=i[i.length-1];return t.valid=Nr(e,0,r.byteOffset-8),t.remainder=Nr(e,r.byteOffset-8),t}(i);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=i;const n=this.extractID3Track(r,t);return s.samples=Ss(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(t,this.timeOffset);return i.samples=Ss(e,t),{videoTrack:t,audioTrack:oo(),id3Track:r,textTrack:oo()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const r=ds(e.samples,["emsg"]);r&&r.forEach((e=>{const r=function(e){const t=e[0];let i="",r="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==ns(e.subarray(h,h+1));)i+=ns(e.subarray(h,h+1)),h+=1;for(i+=ns(e.subarray(h,h+1)),h+=1;"\0"!==ns(e.subarray(h,h+1));)r+=ns(e.subarray(h,h+1)),h+=1;r+=ns(e.subarray(h,h+1)),h+=1,s=os(e,12),n=os(e,16),o=os(e,20),l=os(e,24),h=28}else if(1===t){h+=4,s=os(e,h),h+=4;const t=os(e,h);h+=4;const n=os(e,h);for(h+=4,a=2**32*t+n,Zi(a)||(a=Number.MAX_SAFE_INTEGER,lr.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=os(e,h),h+=4,l=os(e,h),h+=4;"\0"!==ns(e.subarray(h,h+1));)i+=ns(e.subarray(h,h+1)),h+=1;for(i+=ns(e.subarray(h,h+1)),h+=1;"\0"!==ns(e.subarray(h,h+1));)r+=ns(e.subarray(h,h+1)),h+=1;r+=ns(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(Do.test(r.schemeIdUri)){const e=Ji(r.presentationTime)?r.presentationTime/r.timeScale:t+r.presentationTimeDelta/r.timeScale;let s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const n=r.payload;i.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:bn,duration:s})}}))}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(function(e,t){if(!e||!t)return e;const i=t.keyId;i&&t.isCommonEncryption&&ds(e,["moov","trak"]).forEach((e=>{const t=ds(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=ds(t,["enca"]);const s=r.length>0;s||(r=ds(t,["encv"])),r.forEach((e=>{ds(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=ys(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(lr.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${ts(e)} -> ${ts(i)}`),t.set(i,8))}}))}))}));return e}(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=fs(e);r.audio&&(t=nl(r.audio,mr)),r.video&&(i=nl(r.video,pr));const s={};r.audio&&r.video?s.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:r.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?s.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:lr.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,i,r,s,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const c={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};Ji(h)||(h=this.lastEndTime=s||0);const d=t.samples;if(null==d||!d.length)return c;const u={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return lr.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t){let i=0,r=0,s=0;const n=ds(e,["moof","traf"]);for(let e=0;ee+t.info.duration||0),0);i=Math.max(i,e+n.earliestPresentationTime/n.timescale),r=i-t}}if(r&&Ji(r))return r}return r||s}(d,f),m=function(e,t){return ds(t,["moof","traf"]).reduce(((t,i)=>{const r=ds(i,["tfdt"])[0],s=r[0],n=ds(i,["tfhd"]).reduce(((t,i)=>{const n=os(i,4),a=e[n];if(a){let e=os(r,4);if(1===s){if(e===is)return lr.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=is+1,e+=os(r,8)}const i=e/(a.timescale||9e4);if(Ji(i)&&(null===t||is}(l,p,s,g)||u.timescale!==l.timescale&&n)&&(u.initPTS=p-s,l&&1===l.timescale&&lr.warn("Adjusting initPTS by "+(u.initPTS-l.baseTime)),this.initPTS=l={baseTime:u.initPTS,timescale:1});const v=e?p-l.baseTime/l.timescale:h,y=v+g;!function(e,t,i){ds(t,["moof","traf"]).forEach((t=>{ds(t,["tfhd"]).forEach((r=>{const s=os(r,4),n=e[s];if(!n)return;const a=n.timescale||9e4;ds(t,["tfdt"]).forEach((e=>{const t=e[0],r=i*a;if(r){let i=os(e,4);if(0===t)i-=r,i=Math.max(i,0),cs(e,4,i);else{i*=Math.pow(2,32),i+=os(e,8),i-=r,i=Math.max(i,0);const t=Math.floor(i/(is+1)),s=Math.floor(i%(is+1));cs(e,4,t),cs(e,8,s)}}}))}))}))}(f,d,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(lr.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const T=!!f.audio,E=!!f.video;let S="";T&&(S+="audio"),E&&(S+="video");const b={data1:d,startPTS:v,startDTS:v,endPTS:y,endDTS:y,type:S,hasAudio:T,hasVideo:E,nb:1,dropped:0};return c.audio="audio"===b.type?b:void 0,c.video="audio"!==b.type?b:void 0,c.initSegment=u,c.id3=il(i,s,l,l),r.samples.length&&(c.text=rl(r,s,l)),c}}},{demux:Uo,remux:el},{demux:class extends lo{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=$r(e,0);let i=(null==t?void 0:t.length)||0;if(_o(e,i))return!1;for(let t=e.length;i0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t);return i}(n,t);if(T&&"AES-128"===T.method){const e=this.getDecrypter();if(!e.isSync())return this.decryptionPromise=e.webCryptoDecrypt(n,T.key.buffer,T.iv.buffer).then((e=>{const t=this.push(e,null,i);return this.decryptionPromise=null,t})),this.decryptionPromise;{let t=e.softwareDecrypt(n,T.key.buffer,T.iv.buffer);if(i.part>-1&&(t=e.flush()),!t)return s.executeEnd=Qo(),ll(i);n=new Uint8Array(t)}}const E=this.needsProbing(h,c);if(E){const e=this.configureTransmuxer(n);if(e)return lr.warn(`[transmuxer] ${e.message}`),this.observer.emit(tr.ERROR,tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=Qo(),ll(i)}(h||c||f||E)&&this.resetInitSegment(y,g,m,v,t),(h||f||E)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,T,u,d,i),b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,s.executeEnd=Qo(),S}flush(e){const t=e.transmuxing;t.executeStart=Qo();const{decrypter:i,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));const n=[],{timeOffset:a}=r;if(i){const t=i.flush();t&&n.push(this.push(t,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return t.executeEnd=Qo(),[ll(e)];const h=o.flush(a);return hl(h)?h.then((t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,h,e),n)}flushRemux(e,t,i){const{audioTrack:r,videoTrack:s,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;lr.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const h=this.remuxer.remux(r,s,n,a,l,o,!0,this.id);e.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=Qo()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,s){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,i,r),a.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,s){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s),n}transmuxUnencrypted(e,t,i,r){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,s){return this.demuxer.demuxSampleAes(e,t,i).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,this.id),chunkMeta:s})))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:r,vendor:s}=this;let n;for(let t=0,i=al.length;t({remuxResult:{},chunkMeta:e});function hl(e){return"then"in e&&e.then instanceof Function}class cl{constructor(e,t,i,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}}class dl{constructor(e,t,i,r,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=n}}var ul={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function n(e,t,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new s(r,n||e,a),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s{(t=t||{}).frag=this.frag,t.id=this.id,e===tr.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new fl,this.observer.on(tr.FRAG_DECRYPTED,n),this.observer.on(tr.ERROR,n);const a=Os(s.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(lr.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){const t=new self.URL(e,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}(s.workerPath)):(lr.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e);return{worker:new self.Worker(t),objectURL:t}}()),this.onwmsg=e=>this.onWorkerMessage(e);const{worker:e}=this.workerContext;e.addEventListener("message",this.onwmsg),e.onerror=e=>{const i=new Error(`${e.message} (${e.filename}:${e.lineno})`);s.enableWorker=!1,lr.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:i})},e.postMessage({cmd:"init",typeSupported:o,vendor:"",id:t,config:JSON.stringify(s)})}catch(e){lr.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new ol(this.observer,o,s,"",t)}return}}this.transmuxer=new ol(this.observer,o,s,"",t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,r,s,n,a,o,l,h){var c,d;l.transmuxing.start=self.performance.now();const{transmuxer:u}=this,f=n?n.start:s.start,g=s.decryptdata,m=this.frag,p=!(m&&s.cc===m.cc),v=!(m&&l.level===m.level),y=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,E=0===y&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!v&&(1===y||0===y&&(1===T||E&&T<=0)),b=self.performance.now();(v||y||0===s.stats.parsing.start)&&(s.stats.parsing.start=b),!n||!T&&S||(n.stats.parsing.start=b);const L=!(m&&(null==(c=s.initSegment)?void 0:c.url)===(null==(d=m.initSegment)?void 0:d.url)),w=new dl(p,S,o,v,f,L);if(!S||p||L){lr.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${p}\n trackSwitch: ${v}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${L}`);const e=new cl(i,r,t,a,h);this.configureTransmuxer(e)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:l,state:w},e instanceof ArrayBuffer?[e]:[]);else if(u){const t=u.push(e,g,l,w);hl(t)?(u.async=!0,t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}))):(u.async=!1,this.handleTransmuxComplete(t))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);hl(i)||t.async?(hl(i)||(i=Promise.resolve(i)),i.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}))):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}onWorkerMessage(e){const t=e.data;if(null==t||!t.event)return void lr.warn("worker message received with no "+(t?"event name":"data"));const i=this.hls;if(this.hls)switch(t.event){case"init":{var r;const e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":lr[t.data.logType]&&lr[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data)}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function ml(e,t){if(e.length!==t.length)return!1;for(let i=0;ie[i]!==t[i]))}function vl(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class yl{constructor(e){this.buffered=void 0;const t=(t,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}class Tl{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,i){const r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const i=new Promise((e=>{t=e})),r={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,e),i}executeNext(e){const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(t){lr.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${t}`),i.onError(t);const r=this.buffers[e];null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const El=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function Sl(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))} +/** + * + * This code was ported from the dash.js project at: + * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js + * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2 + * + * The original copyright appears below: + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and contributor + * rights, including patent rights, and no such rights are granted under this license. + * + * Copyright (c) 2015-2016, DASH Industry Forum. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * 2. Neither the name of Dash Industry Forum nor the names of its + * contributors may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +const bl={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Ll=e=>String.fromCharCode(bl[e]||e),wl=15,Al=100,Rl={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},kl={17:2,18:4,21:6,22:8,23:10,19:13,20:15},_l={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Dl={25:2,26:4,29:6,30:8,31:10,27:13,28:15},xl=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Cl{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i="function"==typeof t?t():t;lr.log(`${this.time} [${e}] ${i}`)}}}const Il=function(e){const t=[];for(let i=0;iAl&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Al)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e=144&&this.backSpace();const t=Ll(e);this.pos>=Al?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t"pacData = "+JSON.stringify(e)));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+JSON.stringify(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",r=-1;for(let i=0;i0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class Nl{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Fl(i),this.nonDisplayedMemory=new Fl(i),this.lastOutputScreen=new Fl(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;tt+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Ul{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new Cl;this.channels=[null,new Nl(e,t,r),new Nl(e+1,i,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e"["+Il([t[e],t[e+1]])+"] -> ("+Il([i,r])+")"));const a=this.cmdHistory;if(i>=16&&i<=31){if($l(i,r,a)){Bl(null,null,a),this.logger.log(3,(()=>"Repeated command ("+Il([i,r])+") is dropped"));continue}Bl(i,r,this.cmdHistory),s=this.parseCmd(i,r),s||(s=this.parseMidrow(i,r)),s||(s=this.parsePAC(i,r)),s||(s=this.parseBackgroundAttributes(i,r))}else Bl(null,null,a);if(!s&&(n=this.parseChars(i,r),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}s||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+Il([i,r])+" orig: "+Il([t[e],t[e+1]])))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;const i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if(i=17===e?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(()=>"MIDROW ("+Il([e,t])+")")),!0)}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const r=e<=23?1:2;i=t>=64&&t<=95?1===r?Rl[e]:_l[e]:1===r?kl[e]:Dl[e];const s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)}interpretPAC(e,t){let i;const r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(e,t){let i,r=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,(()=>"Special char '"+Ll(e)+"' in channel "+i)),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);return r&&this.logger.log(3,(()=>"Char codes = "+Il(r).join(","))),r}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let i;const r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=xl[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(r),!0}reset(){for(let e=0;ee)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Kl=function(){if(null!=Ar&&Ar.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){return i(t,e)}function s(e,...t){let i=1;for(;i100)throw new Error("Position must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return E},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return b},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");b=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class Vl{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Hl(e){function t(e,t,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}const i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class jl{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r=0&&i<=100)return this.set(e,i),!0}return!1}}function Wl(e,t,i,r){const s=r?e.split(r):[e];for(const e in s){if("string"!=typeof s[e])continue;const r=s[e].split(i);if(2!==r.length)continue;t(r[0],r[1])}}const Yl=new Kl(0,0,""),ql="middle"===Yl.align?"middle":"center";function zl(e,t,i){const r=e;function s(){const t=Hl(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=s(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),n(),t.endTime=s(),n(),function(e,t){const r=new jl;Wl(e,(function(e,t){let s;switch(e){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===t){r.set(e,i[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",ql,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",ql,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",ql,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===Yl.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",ql);let n=r.get("position","auto");"auto"===n&&50===Yl.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function Xl(e){return e.replace(//gi,"\n")}class Ql{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Vl,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function i(){let e=t.buffer,i=0;for(e=Xl(e);i>>0).toString()};function th(e,t,i){return eh(e.toString())+eh(t.toString())+eh(i)}function ih(e,t,i,r,s,n,a){const o=new Ql,l=Jr(new Uint8Array(e)).trim().replace(Jl,"\n").split("\n"),h=[],c=t?function(e,t=1){return zo(e,qo,1/t)}(t.baseTime,t.timescale):0;let d,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(e){const n=i[r];let a=i.ccOffset;const o=(f-c)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:function(e,t,i){let r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;e.ccOffset+=r.start-s.start,r.new=!1,r=s,s=e[r.prevCC]}e.presentationOffset=i}(i,r,o)),o){if(!t)return void(d=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=e.endTime-e.startTime,u=tl(9e4*(e.startTime+a-g),9e4*s)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=th(e.startTime,e.endTime,m)),e.endTime>0&&h.push(e)},o.onparsingerror=function(e){d=e},o.onflush=function(){d?a(d):n(h)},l.forEach((e=>{if(m){if(Zl(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((e=>{Zl(e,"LOCAL:")?u=e.slice(6):Zl(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{g=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(Ji(t)&&Ji(i)&&Ji(r)&&Ji(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*r,t+=36e5*s,t}(u)/1e3}catch(e){d=e}return}""===e&&(m=!1)}o.parse(e+"\n")})),o.flush()}const rh="stpp.ttml.im1t",sh=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,nh=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ah={left:"start",center:"center",right:"end",start:"start",end:"end"};function oh(e,t,i,r){const s=ds(new Uint8Array(e),["mdat"]);if(0===s.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=s.map((e=>Jr(e))),a=function(e,t,i=1,r=!1){return zo(e,t,1/i,r)}(t.baseTime,1,t.timescale);try{n.forEach((e=>i(function(e,t){const i=(new DOMParser).parseFromString(e,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(s).reduce(((e,t)=>(e[t]=r.getAttribute(`ttp:${t}`)||s[t],e)),{}),a="preserve"!==r.getAttribute("xml:space"),o=hh(lh(r,"styling","style")),l=hh(lh(r,"layout","region")),h=lh(r,"body","[begin]");return[].map.call(h,(e=>{const i=ch(e,a);if(!i||!e.hasAttribute("begin"))return null;const r=fh(e.getAttribute("begin"),n),s=fh(e.getAttribute("dur"),n);let h=fh(e.getAttribute("end"),n);if(null===r)throw uh(e);if(null===h){if(null===s)throw uh(e);h=r+s}const c=new Kl(r-t,h-t,i);c.id=th(c.startTime,c.endTime,c.text);const d=function(e,t,i){const r="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(s=i[a]);return n.reduce(((i,n)=>{const a=dh(t,r,n)||dh(e,r,n)||dh(s,r,n);return a&&(i[n]=a),i}),{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:u}=d;if(u){const e=ah[u];e&&(c.lineAlign=e),c.align=u}return Qi(c,d),c})).filter((e=>null!==e))}(e,a))))}catch(e){r(e)}}function lh(e,t,i){const r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function hh(e){return e.reduce(((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function ch(e,t){return[].slice.call(e.childNodes).reduce(((e,i,r)=>{var s;return"br"===i.nodeName&&r?e+"\n":null!=(s=i.childNodes)&&s.length?ch(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function dh(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function uh(e){return new Error(`Could not parse ttml timestamp ${e}`)}function fh(e,t){if(!e)return null;let i=Hl(e);return null===i&&(sh.test(e)?i=function(e,t){const i=sh.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}(e,t):nh.test(e)&&(i=function(e,t){const i=nh.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}function gh(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function mh(e,t){return!!e&&e.kind===gh(t)&&vl(t,e)}class ph{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(tr.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(tr.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&Ji(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&lr.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter(((t,i)=>this.isLevelAllowed(t)&&i<=e));return this.clientRect=null,ph.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return e}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,i){if(null==e||!e.length)return-1;let r=e.length-1;const s=Math.max(t,i);for(let t=0;t=s||i.height>=s)&&(n=i,!(a=e[t+1])||n.width!==a.width||n.height!==a.height)){r=t;break}}var n,a;return r}}const vh="[eme]";class yh{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=yh.CDMCleanupPromise?[yh.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=lr.debug.bind(lr,vh),this.log=lr.log.bind(lr,vh),this.warn=lr.warn.bind(lr,vh),this.error=lr.error.bind(lr,vh),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(tr.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(tr.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===Rr.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,r=t.map((e=>e.audioCodec)).filter(i),s=t.map((e=>e.videoCodec)).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((t,i)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,r,s).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?n(e):i(t instanceof Th?t:new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};n(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Mr&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){const r=function(e,t,i,r){let s;switch(e){case Rr.FAIRPLAY:s=["cenc","sinf"];break;case Rr.WIDEVINE:case Rr.PLAYREADY:s=["cenc"];break;case Rr.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs="${e}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:i.map((e=>({contentType:`video/mp4; codecs="${e}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}(s,t,i,r)}(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let n=null==s?void 0:s.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),n=this.requestMediaKeySystemAccess(e,r);const t=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),n.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const r=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=i.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),r.then((i=>i?this.setMediaKeysServerCertificate(t,e,i):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return n.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${ts(e.keyId||[])}`);const r=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return ts(e.keyId)}updateKeySession(e,t){var i;const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${ts((null==(i=e.decryptdata)?void 0:i.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),r.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,i)=>{const r=Or(this.config),s=e.map(Cr).filter((e=>!!e&&-1!==r.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const r=Pr(e);r?t(r):i(new Error(`Unable to find format for key-system "${e}"`))})).catch(i)}))}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[i];return s||(s=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then((({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then((()=>{this.throwIfDestroyed();const e=this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:t});return this.generateRequestWithPreferredKeySession(e,"cenc",t.pssh,"playlist-key")}))))),s.catch((e=>this.handleError(e)))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Th?this.hls.trigger(tr.ERROR,e.data):this.hls.trigger(tr.ERROR,{type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const t=Cr(e.keyFormat),i=t?[t]:Or(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Or(this.config)),0===e.length)throw new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),null===i)return;let r,s;if("sinf"===t&&this.config.drmSystems[Rr.FAIRPLAY]){const e=ns(new Uint8Array(i));try{const t=br(JSON.parse(e).sinf),i=ys(new Uint8Array(t));if(!i)return;r=i.subarray(8,24),s=Rr.FAIRPLAY}catch(e){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const e=function(e){if(!(e instanceof ArrayBuffer)||e.byteLength<32)return null;const t={version:0,systemId:"",kids:null,data:null},i=new DataView(e),r=i.getUint32(0);if(e.byteLength!==r&&r>44)return null;if(1886614376!==i.getUint32(4))return null;if(t.version=i.getUint32(8)>>>24,t.version>1)return null;t.systemId=ts(new Uint8Array(e,12,16));const s=i.getUint32(28);if(0===t.version){if(r-32this.generateRequestWithPreferredKeySession(s,t,i,"encrypted-event-key-match")));break}}l||(l=a[n]=this.getKeySystemSelectionPromise([s]).then((({keySystem:e,mediaKeys:s})=>{var a;this.throwIfDestroyed();const o=new ks("ISO-23001-7",n,null!=(a=Pr(e))?a:"");return o.pssh=new Uint8Array(i),o.keyId=r,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:e,mediaKeys:s});return this.generateRequestWithPreferredKeySession(r,t,i,"encrypted-event-no-match")}))}))),l.catch((e=>this.handleError(e)))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(i).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===i.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,i,r){var s,n;const a=null==(s=this.config.drmSystems)||null==(n=s[e.keySystem])?void 0:n.generateRequest;if(a)try{const r=a.call(this.hls,t,i,e);if(!r)throw new Error("Invalid response from configured generateRequest filter");t=r.initDataType,i=e.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${t} length: ${i?i.byteLength:null})`);const h=new fl,c=e._onmessage=t=>{const i=e.mediaKeysSession;if(!i)return void h.emit("error",new Error("invalid state"));const{messageType:r,message:s}=t;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,s).catch((e=>{this.handleError(e),h.emit("error",e)})):"license-release"===r?e.keySystem===Rr.FAIRPLAY&&(this.updateKeySession(e,wr("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${r}"`)},d=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const i=e.keyStatus;h.emit("keyStatus",i),"expired"===i&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",c),e.mediaKeysSession.addEventListener("keystatuseschange",d);const u=new Promise(((e,t)=>{h.on("error",t),h.on("keyStatus",(i=>{i.startsWith("usable")?e():"output-restricted"===i?t(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)}))}));return e.mediaKeysSession.generateRequest(t,i).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>u)).catch((t=>{throw h.removeAllListeners(),this.removeSession(e),t})).then((()=>(h.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${ts("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${ts(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise(((s,n)=>{const a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,r)=>{s(e.data)},onError:(t,i,s,o)=>{n(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:qi({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,s)=>{n(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,i)=>{n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise(((r,s)=>{e.setServerCertificate(i).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==i?void 0:i.byteLength}) on "${t}"`),r(e)})).catch((e=>{s(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let t;for(let i=0,r=s.length;i in key message");return wr(atob(l))}setupLicenseXHR(e,t,i,r){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,i,r)})).catch((n=>{if(!i.decryptdata)throw n;return e.open("POST",t,!0),s.call(this.hls,e,t,i,r)})).then((i=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:i||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise(((r,s)=>{const n=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,a,n,e)}catch(e){this.error(e)}r(t)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then((({xhr:t,licenseChallenge:i})=>{e.keySystem==Rr.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},ks.clearKeyUriToKeyIdMap();const i=t.length;yh.CDMCleanupPromise=Promise.all(t.map((e=>this.removeSession(e))).concat(null==e?void 0:e.setMediaKeys(null).catch((e=>{this.log(`Could not clear media keys: ${e}`)})))).then((()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)})).catch((e=>{this.log(`Could not close sessions and clear media keys: ${e}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch((e=>{this.log(`Could not remove session: ${e}`)})).then((()=>t.close())).catch((e=>{this.log(`Could not close session: ${e}`)}))}}}yh.CDMCleanupPromise=void 0;class Th extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var Eh,Sh,bh;!function(e){e.MANIFEST="m",e.AUDIO="a",e.VIDEO="v",e.MUXED="av",e.INIT="i",e.CAPTION="c",e.TIMED_TEXT="tt",e.KEY="k",e.OTHER="o"}(Eh||(Eh={})),function(e){e.DASH="d",e.HLS="h",e.SMOOTH="s",e.OTHER="o"}(Sh||(Sh={})),function(e){e.OBJECT="CMCD-Object",e.REQUEST="CMCD-Request",e.SESSION="CMCD-Session",e.STATUS="CMCD-Status"}(bh||(bh={}));const Lh={[bh.OBJECT]:["br","d","ot","tb"],[bh.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[bh.SESSION]:["cid","pr","sf","sid","st","v"],[bh.STATUS]:["bs","rtp"]};class wh{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map((e=>e instanceof wh?e:new wh(e)))),this.value=e,this.params=t}}class Ah{constructor(e){this.description=void 0,this.description=e}}const Rh="Dict";function kh(e,t,i,r){return new Error(`failed to ${e} "${s=t,Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":"object"==typeof s?JSON.stringify(s):String(s)}" as ${i}`,{cause:r});var s}const _h="Bare Item",Dh="Boolean",xh="Byte Sequence",Ch="Decimal",Ih="Integer";const Ph=/[\x00-\x1f\x7f]+/,Oh="Token",Mh="Key";function Fh(e,t,i){return kh("serialize",e,t,i)}function Nh(e){if(!1===ArrayBuffer.isView(e))throw Fh(e,xh);return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}function Uh(e){if(function(e){return e<-999999999999999||99999999999999912)throw Fh(e,Ch);const i=t.toString();return i.includes(".")?i:`${i}.0`}const Gh="String";function Kh(e){const t=(i=e).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Fh(t,Oh);return t}function Vh(e){switch(typeof e){case"number":if(!Ji(e))throw Fh(e,_h);return Number.isInteger(e)?Uh(e):$h(e);case"string":return function(e){if(Ph.test(e))throw Fh(e,Gh);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return Kh(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Fh(e,Dh);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${Uh(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return Nh(e);if(e instanceof Ah)return Kh(e);default:throw Fh(e,_h)}}function Hh(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Fh(e,Mh);return e}function jh(e){return null==e?"":Object.entries(e).map((([e,t])=>!0===t?`;${Hh(e)}`:`;${Hh(e)}=${Vh(t)}`)).join("")}function Wh(e){return e instanceof wh?`${Vh(e.value)}${jh(e.params)}`:Vh(e)}function Yh(e,t={whitespace:!0}){if("object"!=typeof e)throw Fh(e,Rh);const i=e instanceof Map?e.entries():Object.entries(e),r=null!=t&&t.whitespace?" ":"";return Array.from(i).map((([e,t])=>{t instanceof wh==!1&&(t=new wh(t));let i=Hh(e);var r;return!0===t.value?i+=jh(t.params):(i+="=",Array.isArray(t.value)?i+=`(${(r=t).value.map(Wh).join(" ")})${jh(r.params)}`:i+=Wh(t)),i})).join(`,${r}`)}const qh=e=>"ot"===e||"sf"===e||"st"===e,zh=e=>"number"==typeof e?Ji(e):null!=e&&""!==e&&!1!==e;const Xh=e=>Math.round(e),Qh=e=>100*Xh(e/100),Jh={br:Xh,d:Xh,bl:Qh,dl:Qh,mtp:Qh,nor:(e,t)=>(null!=t&&t.baseUrl&&(e=function(e,t){const i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;const s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}(e,t.baseUrl)),encodeURIComponent(e)),rtp:Qh,tb:Xh};function Zh(e,t={}){return e?function(e,t){return Yh(e,t)}(function(e,t){const i={};if(null==e||"object"!=typeof e)return i;const r=Object.keys(e).sort(),s=Qi({},Jh,null==t?void 0:t.formatters),n=null==t?void 0:t.filter;return r.forEach((r=>{if(null!=n&&n(r))return;let a=e[r];const o=s[r];o&&(a=o(a,t)),"v"===r&&1===a||"pr"==r&&1===a||zh(a)&&(qh(r)&&"string"==typeof a&&(a=new Ah(a)),i[r]=a)})),i}(e,t),Qi({whitespace:!1},t)):""}function ec(e,t,i){return Qi(e,function(e,t={}){if(!e)return{};const i=Object.entries(e),r=Object.entries(Lh).concat(Object.entries((null==t?void 0:t.customHeaderMap)||{})),s=i.reduce(((e,t)=>{var i;const[s,n]=t,a=(null==(i=r.find((e=>e[1].includes(s))))?void 0:i[0])||bh.REQUEST;return null!=e[a]||(e[a]={}),e[a][s]=n,e}),{});return Object.entries(s).reduce(((e,[i,r])=>(e[i]=Zh(r,t),e)),{})}(t,i))}const tc="CMCD";const ic=/CMCD=[^&#]+/;function rc(e,t,i){const r=function(e,t={}){if(!e)return"";const i=Zh(e,t);return`${tc}=${encodeURIComponent(i)}`}(t,i);if(!r)return e;if(ic.test(e))return e.replace(ic,r);const s=e.includes("?")?"&":"?";return`${e}${s}${r}`}function sc(e,t,i,r){e&&Object.keys(t).forEach((s=>{const n=e.filter((e=>e.groupId===s)).map((e=>{const n=Qi({},e);return n.details=void 0,n.attrs=new dr(n.attrs),n.url=n.attrs.URI=nc(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=t[s],n.attrs["PATHWAY-ID"]=r,n}));e.push(...n)}))}function nc(e,t,i,r){const{HOST:s,PARAMS:n,[i]:a}=r;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach((e=>{e&&l.searchParams.set(e,n[e])})),l.href}const ac=/^age:\s*[\d.]+\s*$/im;class oc{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new gr,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return s(i,t.url)})).catch((e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),s(i,t.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)})).catch((e=>{this.callbacks.onError({code:i.status,text:e.message},t,i,r)})):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&Ji(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,n="text"!==t.responseType;if(r>=200&&r<300&&(n&&t.response||null!==t.responseText)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const s=n?t.response:t.responseText,a="arraybuffer"===t.responseType?s.byteLength:s.length;if(i.loaded=i.total=a,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(i,e,s,t),!this.callbacks)return;const l={url:t.responseURL,data:s,code:r};this.callbacks.onSuccess(l,i,e,t)}else{const n=s.loadPolicy.errorRetry;Xn(n,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(n):(lr.error(`${r} while loading ${e.url}`),this.callbacks.onError({code:r,text:t.statusText},e,t,i))}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Xn(e,this.stats.retry,!0))this.retry(e);else{var t;lr.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=qn(e,i.retry),i.retry++,lr.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&ac.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const lc=/(\d+)-(\d+)\/(\d+)/;class hc{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||cc,this.controller=new self.AbortController,this.stats=new gr}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const s=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Qi({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal),n=i.onProgress,a="arraybuffer"===e.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=l&&Ji(l)?l:h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,e,this.response)}),t.timeout),self.fetch(this.request).then((s=>{this.response=this.loader=s;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,e,this.response)}),h-(o-r.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new dc(t||"fetch, bad network response",e,s)}return r.loading.first=o,r.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=lc.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Ji(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(s.headers)||r.total,n&&Ji(t.highWaterMark)?this.loadProgressively(s,r,e,t.highWaterMark,n):a?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=s[o];l&&(r.loaded=r.total=l);const h={url:a.url,data:s,code:a.status};n&&!Ji(t.highWaterMark)&&n(r,e,s,a),i.onSuccess(h,r,e,a)})).catch((t=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const s=t&&t.code||0,n=t?t.message:null;i.onError({code:s,text:n},e,t?t.details:null,r)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,s){const n=new ao,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&s(t,i,n.flush(),e),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return t.loaded+=h,h=r&&s(t,i,n.flush(),e)):s(t,i,l,e),o()})).catch((()=>Promise.reject()));return o()}}function cc(e,t){return new self.Request(e.url,t)}class dc extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const uc=/\s/,fc={newCue(e,t,i,r){const s=[];let n,a,o,l,h;const c=self.VTTCue||self.TextTrackCue;for(let u=0;u=16?l--:l++;const r=Xl(h.trim()),f=th(t,i,r);null!=e&&null!=(d=e.cues)&&d.getCueById(f)||(a=new c(t,i,r),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return e&&s.length&&(s.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),s.forEach((t=>pn(e,t)))),s}},gc=qi(qi({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:oc,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:e,partCurrent:t,hls:i}=this,{autoLevelEnabled:r,media:s}=i;if(!e||!s)return;const n=performance.now(),a=t?t.stats:e.stats,o=t?t.duration:e.duration,l=n-a.loading.start,h=i.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||e.level<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||s.paused||!s.playbackRate||!s.readyState)return;const c=i.mainForwardBufferInfo;if(null===c)return;const d=this.bwEstimator.getEstimateTTFB(),u=Math.abs(s.playbackRate);if(l<=Math.max(d,o/(2*u)*1e3))return;const f=c.len/u,g=a.loading.first?a.loading.first-a.loading.start:-1,m=a.loaded&&g>-1,p=this.getBwEstimate(),v=i.levels,y=v[e.level],T=a.total||Math.max(a.loaded,Math.round(o*y.averageBitrate/8));let E=m?l-g:l;E<1&&m&&(E=Math.min(l,8*a.loaded/p));const S=m?1e3*a.loaded/E:0,b=S?(T-a.loaded)/S:8*T/p+d/1e3;if(b<=f)return;const L=S?8*S:p;let w,A=Number.POSITIVE_INFINITY;for(w=e.level-1;w>h;w--){const e=v[w].maxBitrate;if(A=this.getTimeToLoadFrag(d/1e3,L,o*e,!v[w].details),A=b)return;if(A>10*o)return;i.nextLoadLevel=i.nextAutoLevel=w,m?this.bwEstimator.sample(l-Math.min(d,g),a.loaded):this.bwEstimator.sampleTTFB(l);const R=v[w].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>R&&this.resetEstimator(R),this.clearTimer(),lr.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${b.toFixed(3)} s\n Estimated load time for down switch fragment: ${A.toFixed(3)} s\n TTFB estimate: ${0|g} ms\n Current BW estimate: ${Ji(p)?0|p:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${w} @ ${0|R} bps`),i.trigger(tr.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:a})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(lr.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new ca(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.FRAG_LOADING,this.onFragLoading,this),e.on(tr.FRAG_LOADED,this.onFragLoaded,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.on(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.on(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(tr.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.FRAG_LOADING,this.onFragLoading,this),e.off(tr.FRAG_LOADED,this.onFragLoaded,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.off(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.off(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(tr.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(tr.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){var r;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case rr.BUFFER_ADD_CODEC_ERROR:case rr.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case rr.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:i,partCurrent:r}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){const t=performance.now(),i=r?r.stats:e.stats,s=t-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(e,n),i.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(e,t,i,r){return e+i/t+(r?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const i=this.hls.config,{loading:r}=t.stats,s=r.end-r.start;Ji(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:i}){const r=i?i.stats:t.stats;if(t.type===hn&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=i?i.duration:t.duration,s=this.hls.levels[t.level],n=(s.loaded?s.loaded.bytes:0)+r.loaded,a=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(tr.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:r}=t,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted)return;if(this.ignoreFragment(i))return;const n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==hn||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,t,e,0,r,1,1);if(s>-1)return s;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return lr.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:r,config:s,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=s.abrBandWidthFactor,c=s.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,r,l,0,h,c);if(e>=0)return e}let d=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){d=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-e,lr.info(`[abr] bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=c=1}}const u=this.findBestLevel(o,n,r,l,d,h,c);if(lr.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`),u>-1)return u;const f=i.levels[n],g=i.levels[i.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,s,n,a){var o;const l=r+s,h=this.lastLoadedFragLevel,c=-1===h?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[c],y=!(null==v||null==(o=v.details)||!o.live),T=-1===m||-1===h;let E,S="SDR",b=(null==v?void 0:v.frameRate)||0;const{audioPreference:L,videoPreference:w}=p,A=this.audioTracksByGroup||(this.audioTracksByGroup=function(e){return e.reduce(((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(g));if(T){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(e,t,i,r){return e.slice(i,r+1).reduce(((e,i)=>{if(!i.codecSet)return e;const r=i.audioGroups;let s=e[i.codecSet];s||(e[i.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,i.bitrate);const n=Math.min(i.height,i.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,i.frameRate),s.maxScore=Math.max(s.maxScore,i.score),s.fragmentError+=i.fragmentError,s.videoRanges[i.videoRange]=(s.videoRanges[i.videoRange]||0)+1,r&&r.forEach((e=>{if(!e)return;const i=t.groups[e];i&&(s.hasDefaultAudio=s.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((e=>{s.channels[e]=(s.channels[e]||0)+i.channels[e]})))})),e}),{})}(f,A,t,i)),s=function(e,t,i,r,s){const n=Object.keys(e),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=a&&2===parseInt(a);let h=!0,c=!1,d=1/0,u=1/0,f=1/0,g=0,m=[];const{preferHDR:p,allowedVideoRanges:v}=ma(t,s);for(let t=n.length;t--;){const i=e[n[t]];h=i.channels[2]>0,d=Math.min(d,i.minHeight),u=Math.min(u,i.minFramerate),f=Math.min(f,i.minBitrate);const r=v.filter((e=>i.videoRanges[e]>0));r.length>0&&(c=!0,m=r)}d=Ji(d)?d:0,u=Ji(u)?u:0;const y=Math.max(1080,d),T=Math.max(30,u);return f=Ji(f)?f:i,i=Math.max(f,i),c||(t=void 0,m=[]),{codecSet:n.reduce(((t,r)=>{const s=e[r];if(r===t)return t;if(s.minBitrate>i)return pa(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),t;if(!s.hasDefaultAudio)return pa(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return pa(r,`audio codec preference "${o}" not found`),t;if(a&&!l){if(!s.channels[a])return pa(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(s.channels)})`),t}else if((!o||l)&&h&&0===s.channels[2])return pa(r,"no renditions with stereo sound found"),t;return s.minHeight>y?(pa(r,`min resolution of ${s.minHeight} > maximum of ${y}`),t):s.minFramerate>T?(pa(r,`min framerate of ${s.minFramerate} > maximum of ${T}`),t):m.some((e=>s.videoRanges[e]>0))?s.maxScore=$s(t)||s.fragmentError>e[t].fragmentError)?t:(g=s.maxScore,r):(pa(r,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),t)}),void 0),videoRanges:m,preferHDR:p,minFramerate:u,minBitrate:f}}(r,S,e,L,w),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,preferHDR:h}=s;E=n,S=h?a[a.length-1]:a[0],b=o,e=Math.max(e,l),lr.log(`[abr] picked start tier ${JSON.stringify(s)}`)}else E=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const R=u?u.duration:d?d.duration:0,k=this.bwEstimator.getEstimateTTFB()/1e3,_=[];for(let o=i;o>=t;o--){var D;const t=f[o],d=o>c;if(!t)continue;if(p.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&fa(t,A,S,b,e,L)?(t.supportedPromise=ga(t,A,i),t.supportedPromise.then((e=>{if(!this.hls)return;t.supportedResult=e;const i=this.hls.levels,r=i.indexOf(t);e.error?lr.warn(`[abr] MediaCapabilities decodingInfo error: "${e.error}" for level ${r} ${JSON.stringify(e)}`):e.supported||(lr.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${r} ${JSON.stringify(e)}`),r>-1&&i.length>1&&(lr.log(`[abr] Removing unsupported level ${r}`),this.hls.removeLevel(r)))}))):t.supportedResult=da}if(E&&t.codecSet!==E||S&&t.videoRange!==S||d&&b>t.frameRate||!d&&b>0&&b=2*R&&0===s?f[o].averageBitrate:f[o].maxBitrate,I=this.getTimeToLoadFrag(k,x,C*w,void 0===g);if(x>=C&&(o===h||0===t.loadError&&0===t.fragmentError)&&(I<=k||!Ji(I)||y&&!this.bitrateTestDelay||I${o} adjustedbw(${Math.round(x)})-bitrate=${Math.round(x-C)} ttfb:${k.toFixed(1)} avgDuration:${w.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${I.toFixed(1)} firstSelection:${T} codecSet:${E} videoRange:${S} hls.loadLevel:${m}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls,r=Math.min(Math.max(e,i),t);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}},bufferController:class{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=e=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:e,mediaSource:t}=this;this.log("Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(tr.MEDIA_ATTACHED,{media:e,mediaSource:t})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&lr.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e;const t="[buffer-controller]";var i;this.appendSource=(i=Os(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.log=lr.log.bind(lr,t),this.warn=lr.warn.bind(lr,t),this.error=lr.error.bind(lr,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.BUFFER_RESET,this.onBufferReset,this),e.on(tr.BUFFER_APPENDING,this.onBufferAppending,this),e.on(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.on(tr.BUFFER_EOS,this.onBufferEos,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(tr.FRAG_PARSED,this.onFragParsed,this),e.on(tr.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.BUFFER_RESET,this.onBufferReset,this),e.off(tr.BUFFER_APPENDING,this.onBufferAppending,this),e.off(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.off(tr.BUFFER_EOS,this.onBufferEos,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(tr.FRAG_PARSED,this.onFragParsed,this),e.off(tr.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Tl(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media,r=Os(this.appendSource);if(i&&r){var s;const e=this.mediaSource=new r;this.log(`created media source: ${null==(s=e.constructor)?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming));const t=this._objectUrl=self.URL.createObjectURL(e);if(this.appendSource)try{i.removeAttribute("src");const r=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||r&&e instanceof r,Sl(i),function(e,t){const i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(this.log("media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(e.removeAttribute("src"),this.appendSource&&Sl(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(tr.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((e=>{this.resetBuffer(e)})),this._initSourceBuffer()}resetBuffer(e){const t=this.sourceBuffer[e];try{var i;if(t)this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}catch(t){this.warn(`onBufferReset ${e}`,t)}}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length,r=Object.keys(t);if(r.forEach((e=>{if(i){const i=this.tracks[e];if(i&&"function"==typeof i.buffer.changeType){var r;const{id:s,codec:n,levelCodec:a,container:o,metadata:l}=t[e],h=Hs(i.codec,i.levelCodec),c=null==h?void 0:h.replace(El,"$1");let d=Hs(n,a);const u=null==(r=d)?void 0:r.replace(El,"$1");if(d&&c!==u){"audio"===e.slice(0,5)&&(d=Vs(d,this.appendSource));const t=`${o};codecs=${d}`;this.appendChangeType(e,t),this.log(`switching codec ${h} to ${d}`),this.tracks[e]={buffer:i.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:s}}}}else this.pendingTracks[e]=t[e]})),i)return;const s=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==s&&(this.log(`${s} bufferCodec event(s) expected ${r.join(",")}`),this.bufferCodecEventsExpected=s),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:i}=this,r={execute:()=>{const r=this.sourceBuffer[e];r&&(this.log(`changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};i.append(r,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:i,operationQueue:r,tracks:s}=this,{data:n,type:a,frag:o,part:l,chunkMeta:h}=t,c=h.buffering[a],d=self.performance.now();c.start=d;const u=o.stats.buffering,f=l?l.stats.buffering:null;0===u.start&&(u.start=d),f&&0===f.start&&(f.start=d);const g=s.audio;let m=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const p=o.start,v={execute:()=>{if(c.executeStart=self.performance.now(),m){const e=this.sourceBuffer[a];if(e){const t=p-e.timestampOffset;Math.abs(t)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${p} (delta: ${t}) sn: ${o.sn})`),e.timestampOffset=p)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();c.executeEnd=c.end=e,0===u.first&&(u.first=e),f&&0===f.first&&(f.first=e);const{sourceBuffer:t}=this,i={};for(const e in t)i[e]=xa.getBuffered(t[e]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(tr.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:i})},onError:e=>{const t={type:ir.MEDIA_ERROR,parent:o.type,details:rr.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:h,error:e,err:e,fatal:!1};if(e.code===DOMException.QUOTA_EXCEEDED_ERR)t.details=rr.BUFFER_FULL_ERROR;else{const e=++this.appendErrors[a];t.details=rr.BUFFER_APPEND_ERROR,this.warn(`Failed ${e}/${i.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),e>=i.config.appendErrorMaxRetry&&(t.fatal=!0)}i.trigger(tr.ERROR,t)}};r.append(v,a,!!this.pendingTracks[a])}onBufferFlushing(e,t){const{operationQueue:i}=this,r=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(tr.BUFFER_FLUSHED,{type:e})},onError:t=>{this.warn(`Failed to remove from ${e} SourceBuffer`,t)}});t.type?i.append(r(t.type),t.type):this.getSourceBufferTypes().forEach((e=>{i.append(r(e),e)}))}onFragParsed(e,t){const{frag:i,part:r}=t,s=[],n=r?r.elementaryStreams:i.elementaryStreams;n[vr]?s.push("audiovideo"):(n[mr]&&s.push("audio"),n[pr]&&s.push("video"));0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{const e=self.performance.now();i.stats.buffering.end=e,r&&(r.stats.buffering.end=e);const t=r?r.stats:i.stats;this.hls.trigger(tr.FRAG_BUFFERED,{frag:i,part:r,stats:t,id:i.type})}),s)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce(((e,i)=>{const r=this.sourceBuffer[i];return!r||t.type&&t.type!==i||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${i} sourceBuffer now EOS`))),e&&!(r&&!r.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];t&&(t.ending=!1)}));const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream()):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||null===t)return;if(!this.getSourceBufferTypes().length)return;const r=e.config,s=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(Ji(a)&&a>0){const e=Math.max(a,n),t=Math.floor(s/n)*n-e;this.flushBackBuffer(s,n,t)}if(Ji(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const e=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),t=Math.max(e,n),i=Math.floor(s/n)*n+t;this.flushFrontBuffer(s,n,i)}}flushBackBuffer(e,t,i){const{details:r,sourceBuffer:s}=this;this.getSourceBufferTypes().forEach((n=>{const a=s[n];if(a){const s=xa.getBuffered(a);if(s.length>0&&i>s.start(0)){if(this.hls.trigger(tr.BACK_BUFFER_REACHED,{bufferEnd:i}),null!=r&&r.live)this.hls.trigger(tr.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(a.ended&&s.end(s.length-1)-e<2*t)return void this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);this.hls.trigger(tr.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}}))}flushFrontBuffer(e,t,i){const{sourceBuffer:r}=this;this.getSourceBufferTypes().forEach((s=>{const n=r[s];if(n){const r=xa.getBuffered(n),a=r.length;if(a<2)return;const o=r.start(a-1),l=r.end(a-1);if(i>o||e>=o&&e<=l)return;if(n.ended&&e-l<2*t)return void this.log(`Cannot flush ${s} front buffer while SourceBuffer is in ended state`);this.hls.trigger(tr.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:s})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:e,hls:t,media:i,mediaSource:r}=this,s=e.fragments[0].start+e.totalduration,n=i.duration,a=Ji(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(e)):(s>a&&s>n||!Ji(n))&&(this.log(`Updating Media Source duration to ${s.toFixed(3)}`),r.duration=s)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&null!=t&&t.setLiveSeekableRange){const r=Math.max(0,i[0].start),s=Math.max(r,r+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${r}-${s}.`),t.setLiveSeekableRange(r,s)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,r=Object.keys(i).length;if(r&&(!e||2===r||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const e=this.getSourceBufferTypes();if(e.length)this.hls.trigger(tr.BUFFER_CREATED,{tracks:this.tracks}),e.forEach((e=>{t.executeNext(e)}));else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const s in e)if(!t[s]){var r;const n=e[s];if(!n)throw Error(`source buffer exists for track ${s}, however track does not`);let a=-1===(null==(r=n.levelCodec)?void 0:r.indexOf(","))?n.levelCodec:n.codec;a&&"audio"===s.slice(0,5)&&(a=Vs(a,this.appendSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const e=t[s]=i.addSourceBuffer(o),r=s;this.addBufferListener(r,"updatestart",this._onSBUpdateStart),this.addBufferListener(r,"updateend",this._onSBUpdateEnd),this.addBufferListener(r,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(r,"bufferedchange",((e,t)=>{const i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(tr.BUFFER_FLUSHED,{type:s})})),this.tracks[s]={buffer:e,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(e){this.error(`error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:s,mimeType:o})}}}get mediaSrc(){var e;const t=(null==(e=this.media)?void 0:e.firstChild)||this.media;return null==t?void 0:t.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const{operationQueue:i}=this;i.current(e).onComplete(),i.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var i;const r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const s=this.operationQueue.current(e);s&&s.onError(r)}removeExecutor(e,t,i){const{media:r,mediaSource:s,operationQueue:n,sourceBuffer:a}=this,o=a[e];if(!r||!s||!o)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(e);const l=Ji(r.duration)?r.duration:1/0,h=Ji(s.duration)?s.duration:1/0,c=Math.max(0,t),d=Math.min(i,l,h);d>c&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${c},${d}] from the ${e} SourceBuffer`),o.remove(c,d)):n.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.sourceBuffer[t];if(i)i.ended=!1,i.appendBuffer(e);else if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);const{operationQueue:i}=this,r=t.map((e=>i.appendBlocker(e)));Promise.all(r).then((()=>{e(),t.forEach((e=>{const t=this.sourceBuffer[e];null!=t&&t.updating||i.shiftAndExecuteNext(e)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const r=this.sourceBuffer[e];if(!r)return;const s=i.bind(this,e);this.listeners[e].push({event:t,listener:s}),r.addEventListener(t,s)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach((e=>{t.removeEventListener(e.event,e.listener)}))}},capLevelController:ph,errorController:class{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=lr.log.bind(lr,"[info]:"),this.warn=lr.warn.bind(lr,"[warning]:"),this.error=lr.error.bind(lr,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(tr.ERROR,this.onError,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(tr.ERROR,this.onError,this),e.off(tr.ERROR,this.onErrorOut,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===hn?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,r;if(t.fatal)return;const s=this.hls,n=t.context;switch(t.details){case rr.FRAG_LOAD_ERROR:case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_ERROR:case rr.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case rr.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction={action:ta,flags:na});case rr.FRAG_GAP:case rr.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=ia);case rr.LEVEL_EMPTY_ERROR:case rr.LEVEL_PARSING_ERROR:{var a,o;const e=t.parent===hn?t.level:s.loadLevel;t.details===rr.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(o=a.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case rr.LEVEL_LOAD_ERROR:case rr.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case rr.AUDIO_TRACK_LOAD_ERROR:case rr.AUDIO_TRACK_LOAD_TIMEOUT:case rr.SUBTITLE_LOAD_ERROR:case rr.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const e=s.levels[s.loadLevel];if(e&&(n.type===on&&e.hasAudioGroup(n.groupId)||n.type===ln&&e.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=ia,void(t.errorAction.flags=aa)}return;case rr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.levels[s.loadLevel],i=null==e?void 0:e.attrs["HDCP-LEVEL"];i?t.errorAction={action:ia,flags:oa,hdcpLevel:i}:this.keySystemError(t)}return;case rr.BUFFER_ADD_CODEC_ERROR:case rr.REMUX_ALLOC_ERROR:case rr.BUFFER_APPEND_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(r=t.level)?r:s.loadLevel));case rr.INTERNAL_EXCEPTION:case rr.BUFFER_APPENDING_ERROR:case rr.BUFFER_FULL_ERROR:case rr.LEVEL_SWITCH_ERROR:case rr.BUFFER_STALLED_ERROR:case rr.BUFFER_SEEK_OVER_HOLE:case rr.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:ta,flags:na})}t.type===ir.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=Yn(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(Xn(i,r,Wn(e),e.response))return{action:sa,flags:na,retryConfig:i,retryCount:r};const s=this.getLevelSwitchAction(e,t);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:n}=t.config,a=Yn(e.details.startsWith("key")?n:s,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(r){e.details!==rr.FRAG_GAP&&r.fragmentError++;if(Xn(a,o,Wn(e),e.response))return{action:sa,flags:na,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const i=this.hls;null==t&&(t=i.loadLevel);const r=this.hls.levels[t];if(r){var s,n;const t=e.details;r.loadError++,t===rr.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1;const{levels:h,loadLevel:c,minAutoLevel:d,maxAutoLevel:u}=i;i.autoLevelEnabled||(i.loadLevel=-1);const f=null==(s=e.frag)?void 0:s.type,g=(f===cn&&t===rr.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===rr.BUFFER_ADD_CODEC_ERROR||t===rr.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:e})=>r.audioCodec!==e)),m="video"===e.sourceBufferName&&(t===rr.BUFFER_ADD_CODEC_ERROR||t===rr.BUFFER_APPEND_ERROR)&&h.some((({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t)),{type:p,groupId:v}=null!=(n=e.context)?n:{};for(let i=h.length;i--;){const s=(i+c)%h.length;if(s!==c&&s>=d&&s<=u&&0===h[s].loadError){var a,o;const i=h[s];if(t===rr.FRAG_GAP&&f===hn&&e.frag){const t=h[s].details;if(t){const i=Jn(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else{if(p===on&&i.hasAudioGroup(v)||p===ln&&i.hasSubtitleGroup(v))continue;if(f===cn&&null!=(a=r.audioGroups)&&a.some((e=>i.hasAudioGroup(e)))||f===dn&&null!=(o=r.subtitleGroups)&&o.some((e=>i.hasSubtitleGroup(e)))||g&&r.audioCodec===i.audioCodec||!g&&r.audioCodec!==i.audioCodec||m&&r.codecSet===i.codecSet)continue}l=s;break}}if(l>-1&&i.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:ia,flags:na,nextAutoLevel:l}}return{action:ia,flags:aa}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case ta:break;case ia:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===rr.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:r,hdcpLevel:s,nextAutoLevel:n}=i;switch(r){case na:this.switchLevel(e,n);break;case oa:s&&(t.maxHdcpLevel=Dn[Dn.indexOf(s)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(e,n)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const r=performance.now();if(t){if(this.lastTime){const e=r-this.lastTime,s=i-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*s/e,o=this.hls;if(o.trigger(tr.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:i}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;lr.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(tr.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Mr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:fc,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends no{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",dn),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.on(tr.ERROR,this.onError,this),e.on(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(tr.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(tr.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.off(tr.ERROR,this.onError,this),e.off(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(tr.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(tr.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=qa,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:r}=t;if(this.fragPrevious=i,this.state=qa,!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let n;const a=i.start;for(let e=0;e=s[e].start&&a<=s[e].end){n=s[e];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(e,t){const{startOffset:i,endOffset:r}=t;if(0===i&&r!==Number.POSITIVE_INFINITY){const e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let i=0;inew Fn(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new Fn(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,dn),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:r,levels:s}=this,{details:n,id:a}=t;if(!s)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=s[a];if(a>=s.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){const e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;const t=e.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&t&&(l=t.start,Kn(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(Fa(n,e),l=n.fragments[0].start):t&&(l=t.start,Kn(n,l))}if(o.details=n,this.levelLastLoaded=o,a===r&&(this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===qa)){Jn(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,r=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){const e=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch((e=>{throw s.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((i=>{const r=performance.now();s.trigger(tr.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:r}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=qa}))}}doTick(){if(this.media){if(this.state===qa){const{currentTrackId:e,levels:t}=this,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;const{config:r}=this,s=this.getLoadPosition(),n=xa.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,hn),h=i.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;const c=h.fragments,d=c.length,u=h.edge;let f=null;const g=this.fragPrevious;if(au-e?0:e;f=Jn(g,c,Math.max(c[0].start,a),t),!f&&g&&g.startthis.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=Tn(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.LEVEL_LOADING,this.onLevelLoading,this),e.on(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.LEVEL_LOADING,this.onLevelLoading,this),e.off(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(tr.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);Tn(this.media.textTracks).forEach((e=>{vn(e)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:r,details:s}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!s&&t){this.selectDefaultTrack=!1;const i=va(t,e);if(i>-1)s=e[i];else{const e=va(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(tr.SUBTITLE_TRACKS_UPDATED,n),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r-1){const e=this.tracksInGroup[r];return this.setSubtitleTrack(r),e}if(i)return null;{const i=va(e,t);if(i>-1)return t[i]}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const i=t.id,r=t.groupId;let s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(tr.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Tn(e.textTracks),i=this.currentTrack;let r;if(i&&(r=t.filter((e=>vl(i,e)))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach((e=>{"disabled"!==e.mode&&e!==r&&(e.mode="disabled")})),r){const e=this.subtitleDisplay?"showing":"hidden";r.mode!==e&&(r.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!Ji(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(tr.SUBTITLE_TRACK_SWITCH,{id:e});const s=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&s)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=r;this.hls.trigger(tr.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const c=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(c)}},timelineController:class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(tr.FRAG_LOADING,this.onFragLoading,this),e.on(tr.FRAG_LOADED,this.onFragLoaded,this),e.on(tr.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(tr.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(tr.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(tr.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(tr.FRAG_LOADING,this.onFragLoading,this),e.off(tr.FRAG_LOADED,this.onFragLoaded,this),e.off(tr.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(tr.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(tr.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(tr.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new Gl(this,"textTrack1"),t=new Gl(this,"textTrack2"),i=new Gl(this,"textTrack3"),r=new Gl(this,"textTrack4");this.cea608Parser1=new Ul(1,e,t),this.cea608Parser2=new Ul(3,i,r)}}addCues(e,t,i,r,s){let n=!1;for(let e=s.length;e--;){const r=s[e],c=(a=r[0],o=r[1],l=t,h=i,Math.min(o,h)-Math.max(a,l));if(c>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],i),n=!0,c/(i-t)>.5))return}var a,o,l,h;if(n||s.push([t,i]),this.config.renderTextTracksNatively){const s=this.captionsTracks[e];this.Cues.newCue(s,t,i,r)}else{const s=this.Cues.newCue(null,t,i,r);this.hls.trigger(tr.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s}){const{unparsedVttFrags:n}=this;"main"===i&&(this.initPTS[t.cc]={baseTime:r,timescale:s}),n.length&&(this.unparsedVttFrags=[],n.forEach((e=>{this.onFragLoaded(tr.FRAG_LOADED,e)})))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let r=0;r{vn(e[t]),delete e[t]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;ee.textCodec===rh));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(ml(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const e=this.media,t=e?Tn(e.textTracks):null;if(this.tracks.forEach(((e,i)=>{let r;if(t){let i=null;for(let r=0;rnull!==e)).map((e=>e.label));e.length&&lr.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(tr.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const i=`textTrack${t[1]}`,r=this.captionsProperties[i];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===hn){var i,r;const{cea608Parser1:e,cea608Parser2:s,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;e&&s&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),s.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:i,payload:r}=t;if(i.type===dn)if(r.byteLength){const e=i.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){const e=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===rh?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;oh(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),i.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{lr.log(`Failed to parse IMSC1: ${t}`),i.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:i,payload:r}=e,{initPTS:s,unparsedVttFrags:n}=this,a=s.length-1;if(!s[i.cc]&&-1===a)return void n.push(e);const o=this.hls;ih(null!=(t=i.initSegment)&&t.data?Es(i.initSegment.data,new Uint8Array(r)):r,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(e=>{this._appendCues(e,i.level),o.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(t=>{const s="Missing initPTS for VTT MPEGTS"===t.message;s?n.push(e):this._fallbackToIMSC1(i,r),lr.log(`Failed to parse VTT cue: ${t}`),s&&a>i.cc||o.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})}))}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||oh(t,this.initPTS[e.cc],(()=>{i.textCodec=rh,this._parseIMSC1(e,t)}),(()=>{i.textCodec="wvtt"}))}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach((e=>pn(i,e)))}else{const r=this.tracks[t];if(!r)return;const s=r.default?"default":"subtitles"+t;i.trigger(tr.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===dn&&this.onFragLoaded(tr.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!i||!r)return;const{frag:s,samples:n}=t;if(s.type!==hn||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;eyn(e[r],t,i)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){const{textTracks:e}=this;Object.keys(e).forEach((i=>yn(e[i],t,r)))}}}extractCea608Data(e){const t=[[],[]],i=31&e[0];let r=2;for(let s=0;s0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=qa):(this.loadedmetadata=!1,this.state=Ja),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case qa:this.doTickIdle();break;case Ja:{var e;const{levels:t,trackId:i}=this,r=null==t||null==(e=t[i])?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=ro}break}case Qa:{var t;const e=performance.now(),i=this.retryDate;if(!i||e>=i||null!=(t=this.media)&&t.seeking){const{levels:e,trackId:t}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==e?void 0:e[t])||null),this.state=qa}break}case ro:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:r,complete:s}=e;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=Xa;const e={frag:t,part:i,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const e=this.getLoadPosition(),i=xa.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);Zn(i.end,this.config.maxFragLookUpTolerance,t)<0&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${i.end} is needed`),this.clearWaitingFragment())}}else this.state=qa}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=qa)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:i,trackId:r}=this,s=e.config;if(!i&&(this.startFragRequested||!s.startFragPrefetch)||null==t||!t[r])return;const n=t[r],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=Ja);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,mr,cn));const l=this.getFwdBufferInfo(o,cn);if(null===l)return;const{bufferedTrack:h,switchingTrack:c}=this;if(!c&&this._streamEnded(l,a))return e.trigger(tr.BUFFER_EOS,{type:"audio"}),void(this.state=to);const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,hn),u=l.len,f=this.getMaxBufferLength(null==d?void 0:d.len),g=a.fragments,m=g[0].start;let p=this.flushing?this.getLoadPosition():l.end;if(c&&i){const e=this.getLoadPosition();h&&!pl(c.attrs,h.attrs)&&(p=e),a.PTSKnown&&em||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=m+.05)}if(u>=f&&!c&&pd.end+a.targetduration;if(T||(null==d||!d.len)&&l.len){const e=this.getAppendedFrag(v.start,hn);if(null===e)return;if(y||(y=!!e.gap||!!T&&0===d.len),T&&!y||y&&l.nextStart&&l.nextStartnew Fn(e)))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?this.setInterval(100):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=qa,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=Ya),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(tr.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=t);const{levels:r}=this,{details:s,id:n}=t;if(!r)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const a=r[n];let o=0;if(s.live||null!=(i=a.details)&&i.live){this.checkLiveUpdate(s);const e=this.mainDetails;if(s.deltaUpdateFailed||!e)return;var l;if(!a.details&&s.hasProgramDateTime&&e.hasProgramDateTime)Fa(s,e),o=s.fragments[0].start;else o=this.alignPlaylists(s,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=s,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(this.mainDetails||s,o),this.state!==Ja||this.waitForCdnTuneIn(s)||(this.state=qa),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:s}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new gl(this.hls,cn,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=r?r.index:-1,n=-1!==t,a=new Ca(i.level,i.sn,i.stats.chunkCount,s.byteLength,t,n);d.push(s,f,c,"",i,r,h.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new ao,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=ro}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:i,part:r}=t;if(i.type===cn)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==i.sn){this.fragPrevious=i;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(tr.AUDIO_TRACK_SWITCHED,qi({},e)))}this.fragBufferedComplete(i,r)}else if(!this.loadedmetadata&&i.type===hn){const e=this.videoBuffer||this.media;if(e){xa.getBuffered(e).length&&(this.loadedmetadata=!0)}}}onError(e,t){var i;if(t.fatal)this.state=io;else switch(t.details){case rr.FRAG_GAP:case rr.FRAG_PARSING_ERROR:case rr.FRAG_DECRYPT_ERROR:case rr.FRAG_LOAD_ERROR:case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_ERROR:case rr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(cn,t);break;case rr.AUDIO_TRACK_LOAD_ERROR:case rr.AUDIO_TRACK_LOAD_TIMEOUT:case rr.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Ja||(null==(i=t.context)?void 0:i.type)!==on||(this.state=qa);break;case rr.BUFFER_APPEND_ERROR:case rr.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;if(t.details===rr.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case rr.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==pr&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==pr){this.flushing=!1,this.bufferFlushed=!0,this.state===to&&(this.state=qa);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,cn),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:c}=h,{audio:d,text:u,id3:f,initSegment:g}=s;if(!this.fragContextChanged(o)&&c){if(this.state=Za,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;this._bufferInitSegment(h,g.tracks,e,n),r.trigger(tr.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:g.tracks})}if(d){const{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=d;l&&(l.elementaryStreams[mr]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(mr,e,t,i,r),this.bufferFragmentData(d,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=Qi({id:i,frag:o,details:c},f);r.trigger(tr.FRAG_PARSING_METADATA,e)}if(u){const e=Qi({id:i,frag:o,details:c},u);r.trigger(tr.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,i,r){if(this.state!==Za)return;t.video&&delete t.video;const s=t.audio;if(!s)return;s.id="audio";const n=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${n}/${s.codec}]`),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(tr.BUFFER_CODECS,t);const a=s.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(tr.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);var s;if(this.fragCurrent=e,this.switchingTrack||r===ba||r===wa)if("initSegment"===e.sn)this._loadInitSegment(e,t);else if(null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=ro;const i=this.mainDetails;i&&i.fragments[0].start!==t.details.fragments[0].start&&Fa(t.details,i)}else this.startFragRequested=!0,super.loadFragment(e,t,i);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:t,bufferedTrack:i}=this,r=null==i?void 0:i.attrs,s=e.attrs;t&&r&&(r.CHANNELS!==s.CHANNELS||i.name!==e.name||i.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(tr.AUDIO_TRACK_SWITCHED,qi({},e))}},audioTrackController:class extends la{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.LEVEL_LOADING,this.onLevelLoading,this),e.on(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(tr.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.LEVEL_LOADING,this.onLevelLoading,this),e.off(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(tr.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(tr.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:r,details:s}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!s&&t){const i=va(t,e,Ta);if(i>-1)s=e[i];else{const e=va(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(tr.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}else this.shouldReloadPlaylist(s)&&this.setAudioTrack(this.trackId)}onError(e,t){!t.fatal&&t.context&&(t.context.type!==on||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||(this.requestScheduled=-1,this.checkRetry(t)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const r=this.currentTrack;if(r&&ya(e,r,Ta))return r;const s=va(e,this.tracksInGroup,Ta);if(s>-1){const e=this.tracksInGroup[s];return this.setAudioTrack(s),e}if(r){let r=t.loadLevel;-1===r&&(r=t.firstAutoLevel);const s=function(e,t,i,r,s){const n=t[r],a=t.reduce(((e,t,i)=>{const r=t.uri;return(e[r]||(e[r]=[])).push(i),e}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),c=Ea(t,r,(t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;const r=t.audioGroups,n=i.filter((e=>!r||-1!==r.indexOf(e.groupId)));return va(e,n,s)>-1}));return c>-1?c:Ea(t,r,(t=>{const r=t.audioGroups,n=i.filter((e=>!r||-1!==r.indexOf(e.groupId)));return va(e,n,s)>-1}))}(e,t.levels,i,r,Ta);if(-1===s)return null;t.nextLoadLevel=s}if(e.channels||e.audioCodec){const t=va(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e],s=r.details&&!r.details.live;if(e===this.trackId&&r===i&&s)return;if(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(tr.AUDIO_TRACK_SWITCHING,qi({},r)),s)return;const n=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:Eh.MANIFEST,su:!this.initialized})}catch(e){lr.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const t=e.frag,i=this.hls.levels[t.level],r=this.getObjectType(t),s={d:1e3*t.duration,ot:r};r!==Eh.VIDEO&&r!==Eh.AUDIO&&r!=Eh.MUXED||(s.br=i.bitrate/1e3,s.tb=this.getTopBandwidth(r)/1e3,s.bl=this.getBufferLength(r)),this.apply(e,s)}catch(e){lr.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();const i="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:3&i|8).toString(16)}));return i}}}(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHED,this.onMediaDetached,this),e.on(tr.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHED,this.onMediaDetached,this),e.off(tr.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:Sh.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Qi(t,this.createData());const i=t.ot===Eh.INIT||t.ot===Eh.VIDEO||t.ot===Eh.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce(((e,i)=>(r.includes(i)&&(e[i]=t[i]),e)),{})),this.useHeaders?(e.headers||(e.headers={}),ec(e.headers,t)):e.url=rc(e.url,t)}getObjectType(e){const{type:t}=e;return"subtitle"===t?Eh.TIMED_TEXT:"initSegment"===e.sn?Eh.INIT:"audio"===t?Eh.AUDIO:"main"===t?this.hls.audioTracks.length?Eh.VIDEO:Eh.MUXED:void 0}getTopBandwidth(e){let t,i=0;const r=this.hls;if(e===Eh.AUDIO)t=r.audioTracks;else{const e=r.maxAutoLevel,i=e>-1?e+1:r.levels.length;t=r.levels.slice(0,i)}for(const e of t)e.bitrate>i&&(i=e.bitrate);return i>0?i:NaN}getBufferLength(e){const t=this.hls.media,i=e===Eh.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!t)return NaN;return 1e3*xa.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}},contentSteeringController:class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=lr.log.bind(lr,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((null==i?void 0:i.action)===ia&&i.flags===aa){const e=this.levels;let r=this.pathwayPriority,s=this.pathwayId;if(t.context){const{groupId:i,pathwayId:r,type:n}=t.context;i&&e?s=this.getPathwayForGroupId(i,n,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&e&&(r=e.reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s),i.resolved||lr.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${s} levels: ${e?e.length:e} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this.pathwayPriority=e;const i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((e=>{r-i[e]>3e5&&delete i[e]}));for(let r=0;r0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,jn(t),this.hls.trigger(tr.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===s)))return;const o=this.getLevelsForPathway(n).map((e=>{const t=new dr(e.attrs);t["PATHWAY-ID"]=s;const n=t.AUDIO&&`${t.AUDIO}_clone_${s}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${s}`;n&&(i[t.AUDIO]=n,t.AUDIO=n),o&&(r[t.SUBTITLES]=o,t.SUBTITLES=o);const l=nc(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new Fn({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t{this.log(`Loaded steering manifest: "${r}"`);const n=e.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,r).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:r.toString()};this.hls.trigger(tr.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(e,t,i,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,s);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;const i=null==(t=this.hls)?void 0:t.media;!i||i.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}}});function mc(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(mc):Object.keys(e).reduce(((t,i)=>(t[i]=mc(e[i]),t)),{}):e}function pc(e){const t=e.loader;if(t!==hc&&t!==oc)lr.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=hc,e.progressive=!0,e.enableSoftwareAES=!0,lr.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let vc;class yc extends la{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.on(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.on(tr.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.off(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.off(tr.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,r=[],s={},n={};let a=!1,o=!1,l=!1;t.levels.forEach((e=>{var t,h;const c=e.attrs;let{audioCodec:d,videoCodec:u}=e;-1!==(null==(t=d)?void 0:t.indexOf("mp4a.40.34"))&&(vc||(vc=/chrome|firefox/i.test(navigator.userAgent)),vc&&(e.audioCodec=d=void 0)),d&&(e.audioCodec=d=Vs(d,i)),0===(null==(h=u)?void 0:h.indexOf("avc1"))&&(u=e.videoCodec=function(e){const t=e.split(".");if(t.length>2){let e=t.shift()+".";return e+=parseInt(t.shift()).toString(16),e+=("000"+parseInt(t.shift()).toString(16)).slice(-4),e}return e}(u));const{width:f,height:g,unknownCodecs:m}=e;if(a||(a=!(!f||!g)),o||(o=!!u),l||(l=!!d),null!=m&&m.length||d&&!Fs(d,"audio",i)||u&&!Fs(u,"video",i))return;const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":T,RESOLUTION:E,"VIDEO-RANGE":S}=c,b=`${`${T||"."}-`}${e.bitrate}-${E}-${v}-${p}-${S}-${y}`;if(s[b])if(s[b].uri===e.url||e.attrs["PATHWAY-ID"])s[b].addGroupId("audio",c.AUDIO),s[b].addGroupId("text",c.SUBTITLES);else{const t=n[b]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const i=new Fn(e);s[b]=i,r.push(i)}else{const t=new Fn(e);s[b]=t,n[b]=1,r.push(t)}})),this.filterAndSortMediaOptions(r,t,a,o,l)}filterAndSortMediaOptions(e,t,i,r,s){let n=[],a=[],o=e;if((i||r)&&s&&(o=o.filter((({videoCodec:e,videoRange:t,width:i,height:r})=>{return(!!e||!(!i||!r))&&(!!(s=t)&&xn.indexOf(s)>-1);var s}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));if(t.audioTracks){const{preferManagedMediaSource:e}=this.hls.config;n=t.audioTracks.filter((t=>!t.audioCodec||Fs(t.audioCodec,"audio",e))),Tc(n)}t.subtitles&&(a=t.subtitles,Tc(a));const l=o.slice(0);o.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return xn.indexOf(e.videoRange)-xn.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const i=Bs(e.videoCodec),r=Bs(t.videoCodec);if(i!==r)return r-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const i=$s(e.codecSet),r=$s(t.codecSet);if(i!==r)return r-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let e=0;ei&&i===gc.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const d=s&&!r,u={levels:o,audioTracks:n,subtitleTracks:a,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:!d&&n.some((e=>!!e.url))};this.hls.trigger(tr.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&n.details&&r&&s===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${s?" with Pathway "+s:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(tr.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==r?void 0:r.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){!t.fatal&&t.context&&t.context.type===an&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===hn){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;const i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:r,details:s}=t,n=this._levels[r];var a;if(!n)return this.warn(`Invalid level index ${r}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));r===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(r,t,n.details)):null!=(i=t.deliveryDirectives)&&i.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(e)try{r=e.addDirectives(r)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}const s=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""} with${s?" Pathway "+s:""} ${r}`),this.clearTimer(),this.hls.trigger(tr.LEVEL_LOADING,{url:r,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const i=this._levels.filter(((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));jn(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(tr.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(tr.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Tc(e){const t={};e.forEach((e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}class Ec{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==(null==(t=r.context)?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=rr.KEY_LOAD_ERROR,i,r,s){return new Ga({type:ir.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:r}=e;for(let e=0;e{s.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const i=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,rr.KEY_LOAD_ERROR,i))}const n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,rr.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(i=a)&&i.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,rr.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(i);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,i)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,r=new(0,i.loader)(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise(((s,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,r)=>{const{frag:a,keyInfo:o,url:l}=i;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,rr.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(e,i,r,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,rr.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),r,qi({url:a.url,data:void 0},e)))},onTimeout:(e,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,rr.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,rr.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,h)}))}resetLoader(e){const{frag:t,keyInfo:i,url:r}=e,s=i.loader;t.keyLoader===s&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()}}function Sc(){return self.SourceBuffer||self.WebKitSourceBuffer}function bc(){if(!Os())return!1;const e=Sc();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class Lc{constructor(e,t,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:r,stalled:s}=this;if(null===r)return;const{currentTime:n,seeking:a}=r,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==e){if(this.moved=!0,a||(this.nudgeRetry=0),null!==s){if(this.stallReported){const e=self.performance.now()-s;lr.warn(`playback not stuck anymore @${n}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(r.paused&&!a||r.ended||0===r.playbackRate||!xa.getBuffered(r).length)return void(this.nudgeRetry=0);const h=xa.bufferInfo(r,n,0),c=h.nextStart||0;if(a){const e=h.len>2,i=!c||t&&t.start<=n||c-n>2&&!this.fragmentTracker.getPartialFragment(n);if(e||i)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var d;if(!(h.len>0)&&!c)return;const e=Math.max(c,h.start||0)-n,t=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,i=(null==t||null==(d=t.details)?void 0:d.live)?2*t.details.targetduration:2,s=this.fragmentTracker.getPartialFragment(n);if(e>0&&(e<=i||s))return void(r.paused||this._trySkipBufferHole(s))}const u=self.performance.now();if(null===s)return void(this.stalled=u);const f=u-s;if(!a&&f>=250&&(this._reportStall(h),!this.media))return;const g=xa.bufferInfo(r,n,i.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:r,media:s}=this;if(null===s)return;const n=s.currentTime,a=r.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-n1e3*i.highBufferWatchdogPeriod&&(lr.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);lr.warn(r.message),t.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:r}=this;if(null===r)return 0;const s=r.currentTime,n=xa.bufferInfo(r,s,0),a=s0&&n.len<1&&r.readyState<3,h=a-s;if(h>0&&(o||l)){if(h>t.maxBufferHole){const{fragmentTracker:t}=this;let i=!1;if(0===s){const e=t.getAppendedFrag(0,hn);e&&a1?(e=0,this.bitrateTest=!0):e=i.firstAutoLevel),i.nextLoadLevel=e,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&-1===e&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=qa,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=Ya}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case so:{const{levels:e,level:t}=this,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(r))break;this.state=qa;break}if(this.hls.nextLoadLevel!==this.level){this.state=qa;break}break}case Qa:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:e,level:t}=this,i=null==e?void 0:e[t];this.resetStartWhenNotLoaded(i||null),this.state=qa}}}this.state===qa&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(null===t||!r&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=e.nextLoadLevel;if(null==i||!i[s])return;const n=i[s],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return this.altAudio&&(e.type="video"),this.hls.trigger(tr.BUFFER_EOS,e),void(this.state=to)}e.loadLevel!==s&&-1===e.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const l=n.details;if(!l||this.state===so||l.live&&this.levelLastLoaded!==n)return this.level=s,void(this.state=so);const h=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(h>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&"initSegment"!==u.sn&&this.fragmentTracker.getState(u)!==Aa){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,d)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?mr:pr,t=(e===pr?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,hn)}u=this.getNextFragmentLoopLoading(u,l,a,hn,c)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,d))}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===ba||r===wa?"initSegment"===e.sn?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,hn)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let i;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else i=0;const n=this.getBufferedFrag(t.currentTime+i);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,r=Math.max(n.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case za:case Xa:case Qa:case Za:case eo:this.state=qa}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Lc(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;Ji(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(tr.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,r=!1;t.levels.forEach((e=>{const t=e.audioCodec;t&&(i=i||-1!==t.indexOf("mp4a.40.2"),r=r||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&r&&!function(){var e;const t=Sc();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==qa)return;const r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=so)}onLevelLoaded(e,t){var i;const{levels:r}=this,s=t.level,n=t.details,a=n.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${a}`);const o=r[s],l=this.fragCurrent;!l||this.state!==Xa&&this.state!==Qa||l.level!==t.level&&l.loader&&this.abortCurrentFrag();let h=0;if(n.live||null!=(i=o.details)&&i.live){var c;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(tr.LEVEL_UPDATED,{details:n,level:s}),this.state===so){if(this.waitForCdnTuneIn(n))return;this.state=qa}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:s}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,h=o.PTSKnown||!o.live,c=null==(t=i.initSegment)?void 0:t.data,d=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new gl(this.hls,hn,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new Ca(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,g),p=this.initPTS[i.cc];u.push(s,c,d,l,i,r,o.totalduration,h,m,p)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const e=this.hls;i&&(e.trigger(tr.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(tr.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,r=!!this.hls.audioTracks[i].url;if(r){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=r,this.tick()}onBufferCreated(e,t){const i=t.tracks;let r,s,n=!1;for(const e in i){const t=i[e];if("main"===t.id){if(s=e,r=t,"video"===e){const t=i[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:r}=t;if(i&&i.type!==hn)return;if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===eo&&(this.state=qa));const s=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==i.sn&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal)this.state=io;else switch(t.details){case rr.FRAG_GAP:case rr.FRAG_PARSING_ERROR:case rr.FRAG_DECRYPT_ERROR:case rr.FRAG_LOAD_ERROR:case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_ERROR:case rr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(hn,t);break;case rr.LEVEL_LOAD_ERROR:case rr.LEVEL_LOAD_TIMEOUT:case rr.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==so||(null==(i=t.context)?void 0:i.type)!==an||(this.state=qa);break;case rr.BUFFER_APPEND_ERROR:case rr.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;if(t.details===rr.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case rr.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!xa.getBuffered(e).length){const e=this.state!==qa?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=qa,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==mr||this.audioOnly&&!this.altAudio){const e=(t===pr?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,hn),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t0&&(s{const{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=qa,this.startFragRequested=!1,this.bitrateTest=!1;const s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(tr.FRAG_LOADED,i),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const i="main",{hls:r}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{video:c,text:d,id3:u,initSegment:f}=s,{details:g}=h,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Za,f){if(null!=f&&f.tracks){const e=o.initSegment||o;this._bufferInitSegment(h,f.tracks,e,n),r.trigger(tr.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;Ji(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},r.trigger(tr.INIT_PTS_FOUND,{frag:o,id:i,initPTS:e,timescale:t}))}if(c&&g&&"initSegment"!==o.sn){const e=g.fragments[o.sn-1-g.startSN],t=o.sn===g.startSN,i=!e||o.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:r,startDTS:s,endDTS:a}=c;if(l)l.elementaryStreams[c.type]={startPTS:e,endPTS:r,startDTS:s,endDTS:a};else if(c.firstKeyFrame&&c.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),c.dropped&&c.independent){const s=this.getMainFwdBufferInfo(),n=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=c.firstKeyFramePTS?c.firstKeyFramePTS:e;if(!t&&n2&&(o.gap=!0);o.setElementaryStreamInfo(c.type,e,r,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,l,n,t||i)}else{if(!t&&!i)return void this.backtrack(o);o.gap=!0}}if(m){const{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=m;l&&(l.elementaryStreams[mr]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(mr,e,t,i,r),this.bufferFragmentData(m,o,l,n)}if(g&&null!=u&&null!=(t=u.samples)&&t.length){const e={id:i,frag:o,details:g,samples:u.samples};r.trigger(tr.FRAG_PARSING_METADATA,e)}if(g&&d){const e={id:i,frag:o,details:g,samples:d.samples};r.trigger(tr.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,i,r){if(this.state!==Za)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:s,video:n,audiovideo:a}=t;if(s){let t=e.audioCodec;const i=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=s.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===i.indexOf("firefox")&&(t="mp4a.40.5")}t&&-1!==t.indexOf("mp4a.40.5")&&-1!==i.indexOf("android")&&"audio/mpeg"!==s.container&&(t="mp4a.40.2",this.log(`Android: force audio codec to ${t}`)),e.audioCodec&&e.audioCodec!==t&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${t}"`),s.levelCodec=t,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${t||""}/${e.audioCodec||""}/${s.codec}]`)}n&&(n.levelCodec=e.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),this.hls.trigger(tr.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(tr.BUFFER_APPENDING,{type:e,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,hn)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=qa}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const i=e.currentTime;if(xa.isBuffered(e,i)?t=this.getAppendedFrag(i):xa.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,i=t.level;e&&t.sn===e.sn&&e.level===i||(this.fragPlaying=t,this.hls.trigger(tr.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(tr.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&Ji(t)&&Ji(i.programDateTime)){const e=i.programDateTime+1e3*(t-i.start);return new Date(e)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Ac{static get version(){return"1.5.11"}static isMSESupported(){return bc()}static isSupported(){return function(){if(!bc())return!1;const e=Os();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(Us(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(Us(t,"audio")))))}()}static getMediaSource(){return Os()}static get Events(){return tr}static get ErrorTypes(){return ir}static get ErrorDetails(){return rr}static get DefaultConfig(){return Ac.defaultConfig?Ac.defaultConfig:gc}static set DefaultConfig(e){Ac.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new fl,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,function(e,t){if("object"==typeof console&&!0===e||"object"==typeof e){or(e,"debug","log","info","warn","error");try{ar.log(`Debug logs enabled for "${t}" in hls.js version 1.5.11`)}catch(e){ar=nr}}else ar=nr}(e.debug||!1,"Hls instance");const t=this.config=function(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=mc(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,n=void 0===t[s],a=[];r.forEach((r=>{const o=`${e}Loading${r}`,l=t[o];if(void 0!==l&&n){a.push(o);const e=i[s].default;switch(t[s]={default:e},r){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&lr.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),qi(qi({},i),t)}(Ac.DefaultConfig,e);this.userConfig=e,t.progressive&&pc(t);const{abrController:i,bufferController:r,capLevelController:s,errorController:n,fpsController:a}=t,o=new n(this),l=this.abrController=new i(this),h=this.bufferController=new r(this),c=this.capLevelController=new s(this),d=new a(this),u=new gn(this),f=new kn(this),g=t.contentSteeringController,m=g?new g(this):null,p=this.levelController=new yc(this,m),v=new Ra(this),y=new Ec(this.config),T=this.streamController=new wc(this,v,y);c.setStreamController(T),d.setStreamController(T);const E=[u,p,T];m&&E.splice(1,0,m),this.networkControllers=E;const S=[l,h,c,d,f,v];this.audioTrackController=this.createController(t.audioTrackController,E);const b=t.audioStreamController;b&&E.push(new b(this,v,y)),this.subtitleTrackController=this.createController(t.subtitleTrackController,E);const L=t.subtitleStreamController;L&&E.push(new L(this,v,y)),this.createController(t.timelineController,S),y.emeController=this.emeController=this.createController(t.emeController,S),this.cmcdController=this.createController(t.cmcdController,S),this.latencyController=this.createController(_n,S),this.coreComponents=S,E.push(o);const w=o.onErrorOut;"function"==typeof w&&this.on(tr.ERROR,w,o)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(lr.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const i=e===tr.ERROR;this.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){lr.log("destroy"),this.trigger(tr.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){lr.log("attachMedia"),this._media=e,this.trigger(tr.MEDIA_ATTACHING,{media:e})}detachMedia(){lr.log("detachMedia"),this.trigger(tr.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,r=this.url=Wi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,lr.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(tr.MANIFEST_LOADING,{url:e})}startLoad(e=-1){lr.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){lr.log("stopLoad"),this.started=!1,this.networkControllers.forEach((e=>{e.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((e=>{"fragmentLoader"in e&&e.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((e=>{"fragmentLoader"in e&&e.stopLoad()}))}swapAudioCodec(){lr.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){lr.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){lr.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){lr.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){lr.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){lr.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){lr.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(lr.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return Dn.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let r=0;r=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let r;if(r=-1===t&&null!=e&&e.length?e.length-1:t,i)for(let t=r;t--;){const r=e[t].attrs["HDCP-LEVEL"];if(r&&r<=i)return t}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return null==(t=this.audioTrackController)?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return null==(t=this.subtitleTrackController)||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}function Rc(e,t,i){return t&&function(e,t){for(var i=0;i0&&(e.$video.volume=e._options.volume)}),1e3)})),e.event.emit("parsed")}))}))}else if(this.$video.canPlayType("application/vnd.apple.mpegurl")){this.logger.log("Browser support application/vnd.apple.mpegurl : ",this.$video.canPlayType("application/vnd.apple.mpegurl")),this.$video.src=this._options.url;var i=!1;this.$video.addEventListener("canplay",(function(){!i&&e._options.autoPlay&&setTimeout((function(){e.$video.play().then((function(){e.logger.log("autoPlay video!"),setTimeout((function(){e._options.volume>0&&e.setVolume(e._options.volume)}),1e3),i=!0}))}),200)}))}else this.logger.warn("Browser not support hls")},i.isPlayingState=function(){return!this.$video.paused},i.play=function(){if(this.isPlayingState())return Promise.resolve();if(this._options.isLive&&(this.$video.buffered.length>=1&&this.$video.buffered.end(0)>1)){var e=this.$video.buffered.end(0)-1;this.$video.currentTime=e}return this.$video.play()},i.pause=function(){this.$video.pause()},i.setVolume=function(e){this.$video.muted&&(this.$video.muted=!1),this._volume=+(e||0),0===this._volume&&(this.$video.muted=!0),this.$video.volume=this._volume},i.destroy=function(){this.$video&&this.$video.pause(),this._hls&&(this._hls.destroy(),this._hls=null),e.prototype.destroy.call(this)},i._onEvent=function(){var e;(e=this).$video&&(e.$video.addEventListener("canplay",(function(){e.event.emit("canplay")})),e.$video.addEventListener("loadeddata",(function(){e.event.emit("loadeddata")})),e.$video.addEventListener("volumechange",(function(){e.event.emit("volumechange",{data:e.$video.volume})})),e.$video.addEventListener("waiting",(function(){e.event.emit("waiting")})),e.$video.addEventListener("timeupdate",(function(){var t;null==(t=e.event)||t.emit("timeupdate")})),e.$video.addEventListener("seeking",(function(){e.event.emit("seeking",{data:e.$video.currentTime})})),e.$video.addEventListener("seeked",(function(){e.event.emit("seeked")})),e.$video.addEventListener("abort",(function(){e.event.emit("abort")})),e.$video.addEventListener("error",(function(){var t;null==(t=e.event)||t.emit("error",{data:e.$video.error})})),e.$video.addEventListener("ended",(function(){e.event.emit("ended")})))},Rc(t,[{key:"volume",get:function(){return this._volume},set:function(e){this.setVolume(e)}}]),t}(Ri);var xc="wasm_loaded",Cc="wasm_failed",Ic="init";function Pc(e,t){return Pc=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Pc(e,t)}var Oc=function(e){function t(t){var i;return void 0===t&&(t={}),i=e.call(this,t)||this,t.url=function(e,t){void 0===t&&(t=["h264"]);var i=(t||["h264"]).reduce((function(e,t){return t=t.toLowerCase(),e+(Xt[t]||0)}),0),r=e.split("?")[0],s=e.split("?")[1];return s=(s||"").split("&").filter((function(e){return!/^vc=\d?/.test(e)})).join("&"),r+"?"+s+(s?"&":"")+"vc="+i}(null==t?void 0:t.url,["h264","h265"]),function(e,t){if(((null==t?void 0:t.volume)||0)>1?e._volume=1:((null==t?void 0:t.volume)||0)<=0?e._volume=0:e._volume=+((null==t?void 0:t.volume)||0),t.volume=e._volume,e.options=zt({},wi,t),"string"!=typeof e.options.id)throw new Error("id is required!");e.logger=z(e.options.loggerOptions),e.event=new ei,e.logger.log("HlsPlayer version: ",Uc.version),e.logger.log("HlsPlayer options: ",e.options),e.options.logger=e.logger}(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(i),t),i._containerClassName=Li+"-container",i._render(),i}!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&Pc(e,t)}(t,e);var i=t.prototype;return i._render=function(){this.$container.classList.add(this._containerClassName)},i.destroy=function(){this.$container&&(this.$container.classList.remove(this._containerClassName),this.$container.innerHTML="",this.$container=null)},t}(Si);function Mc(e,t,i){return t&&function(e,t){for(var i=0;i0&&(e=!0),this.playParam={durationMs:0,fps:0,sampleRate:0,size:{width:0,height:0},audioNone:e,videoCodec:T},!A())throw new Error("Browser not support WebAssembly!");this._onWorkerMessage()},i.play=function(){if(Ui.send(1,{name:"play"}),null===this.player)return Promise.resolve();if(this.playParam.videoCodec===T){var e={seekPos:0,isLive:this.options.isLive,accurateSeek:!0,seekEvent:!1,realPlay:!0};return this.player.play(e)}return this.player.play()},i.pause=function(){return Ui.send(1,{name:"pause"}),null!==this.player&&(this.player.pause(),!0)},i.destroy=function(){var t,i;return Ui.send(1,{name:"destroy"}),void 0!==this.player&&null!==this.player&&(this.playParam.videoCodec===T&&this._m3u8Obj&&(this._m3u8Obj.destroy(),this._m3u8Obj=null),this.player.destroy(),this._decoderWorker&&(this._decoderWorker.postMessage(P(B)),this._decoderWorker.terminate(),this._decoderWorker=null),this.logger.log("destroy"),null==(i=this.event)||null==(t=i.emit)||t.call(i,"destroy"),this.player=null,e.prototype.destroy.call(this),!0)},i.isPlaying=function(){return null!==this.player&&this.player.isPlayingState()},i.setVolume=function(e){var t;(e=+e)>1||e<0?this.logger.warn("volume volume value 0.0 ~ 1.0!"):((t=this).player||(t.event.emit("playerIsNull"),t.logger.warn("Player instance does not exist!"),0))&&(this.player.setVolume(e),this.event.emit("volumeChange",{data:e}))},i.getVersion=function(){return Ui.send(1,{name:"getVersion"}),"0.1.0"},i._m3u8Entry=function(){var e=this;this._m3u8Obj=new Vi({logger:this.logger,decoderWorker:this._decoderWorker,event:this.event}),this._m3u8Obj.bindReady(this),this._m3u8Obj.onFinished=function(e,t){},this._m3u8Obj.onCacheProcess=function(t){e.options.isLive||null==e.onCacheProcess||e.onCacheProcess.call(e,t)},this._m3u8Obj.onDemuxed=this._checkPlayer.bind(this),this._m3u8Obj.onSamples=this._hlsOnSamples.bind(this),this._m3u8Obj.demux(this.url)},i._checkPlayer=function(e,t){var i=this;if(null==i.player){var r,s,n;if(!(null==i||null==(r=i._m3u8Obj)?void 0:r.isHevcParam)||t)return null==i||null==(n=i._m3u8Obj)||null==(s=n.destroy)||s.call(n),i._m3u8Obj=null,this._decoderWorker.terminate(),this._decoderWorker=null,void(i.player=new Dc(Fc({},this.options,{event:this.event,logger:this.logger})));var a=i._m3u8Obj.getACodec(),o=i._m3u8Obj.getFPS(),l=i._m3u8Obj.getSampleRate(),h=i._m3u8Obj.getSize(),c=!1;c=i._m3u8Obj.getSampleChannel()<=0||""===a,i._softPlayer(0,o,l,h,c)}},i._hlsOnSamples=function(e,t){var i,r,s,n=this;if(t.video)null==(s=n.player)||null==(r=s.appendHevcFrame)||r.call(s,t);else if(!(null==(i=n._m3u8Obj)?void 0:i.audioNone)){var a,o;null==(o=n.player)||null==(a=o.appendAACFrame)||a.call(o,t)}},i._onWorkerMessage=function(){var e=this,i=this;this._decoderWorker.onmessage=function(r){var s=r.data;switch(s.cmd){case O:t.__HLS_WASM_DecoderState__=0;break;case M:t.__HLS_WASM_DecoderState__=1,e.logger.log("Wasm already init over!"),i.event.emit(xc),i._decoderWorker.postMessage(P("registerWasmPlayer")),i._m3u8Entry();break;case F:t.__HLS_WASM_DecoderState__=-1,e.logger.error("Wasm init failed!",s),i.event.emit(Cc,s),Ui.send("wasm",{name:"wasm loading failed"}),i._checkPlayer(!0)}}},i._softPlayer=function(e,t,i,r,s,n){var a,o,l=this;void 0===s&&(s=!1),void 0===n&&(n=null);var c,d=this;(this.playParam.durationMs=e,this.playParam.fps=t,this.playParam.sampleRate=i,this.playParam.size=r,this.playParam.audioNone=s,this.playParam.videoCodec=n||T,this.logger.log("this.playParam: ",this.playParam),this.logger.log("start init soft player"),this.player=new xi(Fc({},d.options,{sampleRate:i,fps:t,appendHevcType:h,fixed:!1,id:this.options.id,audioNone:s,videoCodec:n,logger:this.logger,event:this.event,decoderWorker:this._decoderWorker})),this.player.onPlayingTime=function(e){var t;null==d||null==(t=d.onPlayTime)||t.call(d,e)},this.player.onPlayingFinish=function(){var e,t;(l.pause(),null!=l.onPlayFinish)&&(null==(t=l)||null==(e=t.onPlayFinish)||e.call(t))},this.player.onLoadCache=function(){var e,t;null==(t=l)||null==(e=t.onLoadCache)||e.call(t)},this.player.onLoadCacheFinished=function(){var e,t;null==(t=l)||null==(e=t.onLoadCacheFinished)||e.call(t)},null==(a=d.player)||a.setDurationMs(e),null==(o=d.player)||o.setFrameRate(t),null!=d.onReadyShowDone)&&(null==d||null==(c=d.onReadyShowDone)||c.call(d));this.event.emit("parsed"),this.player&&this.options.autoPlay&&this.play()},t.supportType=function(e){if(Ui.send(1,{name:"supportType",options:e}),"hls"===e.type)return!0;if(e.url){var t=e.url;t.startsWith("http://")||t.startsWith("https://")||(t=/^\/\//.test(t)?"http:"+t:location.origin+location.pathname+t);try{return/\.m3u8$/i.test(new URL(t).pathname)}catch(e){}}return!1},Mc(t,[{key:"volume",get:function(){return this.player?this.player.volume:this.options.volume},set:function(e){e=+e,this.setVolume(e)}}]),t}(Oc);return Uc.__HLS_WASM_DecoderState__=0,Uc.version="0.1.0",Uc})); diff --git a/dist/types/index.d.ts b/dist/types/index.d.ts new file mode 100644 index 0000000..6011f73 --- /dev/null +++ b/dist/types/index.d.ts @@ -0,0 +1,509 @@ +import { LoggerCls } from '@ezuikit/utils-logger'; +export { LoggerOptions } from '@ezuikit/utils-logger'; +import BasePlayer, { BasePlayerOptions } from '@ezuikit/player-base'; +import Hls from 'hls.js'; +import EventEmitter from 'eventemitter3'; + +type Fn$1 = () => any; +declare class AudioCore { + options: { + sampleRate: any; + appendType: any; + playMode: any; + isLive: boolean; + }; + logger: LoggerCls; + sourceChannel: number; + audioCtx: AudioContext; + gainNode: GainNode; + sourceList: AudioBufferSourceNode[]; + startStatus: boolean; + sampleQueue: Array; + nextBuffer: { + data: any; + pts: number; + }; + playTimestamp: number; + playStartTime: number; + durationMs: number; + volume: number; + onLoadCache: Fn$1; + seekPos: any; + constructor(options: any); + resetStartParam(): void; + setOnLoadCache(callback: any): void; + setDurationMs(durationMs?: number): void; + setVolume(volume?: number): void; + getAlignVPTS(): number; + /** + * @brief Swap SourceNode To Play When before node play end + */ + swapSource(sourceIndex?: number, dstIndex?: number): null; + /** + * @param sampleObj : {data:Uint8Array, pts:xxx} + */ + addSample(sampleObj?: null): boolean; + runNextBuffer(): void; + /** + * @return + * 1 queue length == 0, no frame + * 0 OK + * -1 sourceIndex out of bounds + * -2 decode Error + */ + decodeSample(sourceIndex?: number, dstIndex?: number): 1 | -1 | -2 | 0 | -3; + /** + * @return + * 1 queue length == 0, no frame + * 0 OK + * -1 sourceIndex out of bounds + * -2 decode Error + */ + decodeWholeSamples(sourceIndex?: number): 1 | -1 | -2 | 0 | -3; + play(): void; + pause(): void; + stop(): void; + cleanQueue(): void; +} + +/** + * @description yuv 数据结构 + */ +declare class YuvStruct { + pts: number; + width: number; + height: number; + imageBufferY: Uint8Array; + imageBufferB: Uint8Array; + imageBufferR: Uint8Array; + constructor(pts: number, width: number, height: number, imageBufferY: Uint8Array, imageBufferB: Uint8Array, imageBufferR: Uint8Array); + /** + * + * @param pts + * @param width + * @param height + * @param imageBufferY + * @param imageBufferB + * @param imageBufferR + */ + setYuv(pts: number, width: number, height: number, imageBufferY: Uint8Array, imageBufferB: Uint8Array, imageBufferR: Uint8Array): void; +} + +declare class Cache { + limit: number; + logger: LoggerCls; + yuvCache: YuvStruct[]; + constructor(options: any); + appendCacheByCacheYuv(cacheYuvObj: YuvStruct): number; + getState(): number; + cleanPipeline(): void; + shiftYuv(): YuvStruct | null | undefined; +} + +declare class WebGlRender { + gl: WebGLRenderingContext; + program: WebGLProgram; + verticesBuffer: WebGLBuffer | null; + texCoordBuffer: WebGLBuffer | null; + constructor(canvas: HTMLCanvasElement, options?: any); + /** + * @description 渲染视频帧 + * @param {number} videoFrameY + * @param {number} videoFrameB + * @param {number} videoFrameR + * @param {number} width + * @param {number} height + */ + renderFrame(videoFrameY: any, videoFrameB: any, videoFrameR: any, width: any, height: any): void; + /** + * @description 释放webgl 数据 + */ + destroyContext(): void; +} + +interface IEnginePlayer { + volume: number; + play: () => Promise; + pause: () => void; + setVolume: (volume?: number) => void; +} + +declare class BufferFrame { + pts: number; + dts: number; + isKey: boolean; + data: Uint8Array; + video: boolean; + constructor(pts: number, isKey: boolean, data: Uint8Array, isVideo: boolean); + setFrame(pts: number, isKey: boolean, data: Uint8Array, isVideo: boolean): void; +} + +interface HlsOptions extends BasePlayerOptions { + /** 出错尝试连接次数 默认 20 */ + retry: number; + /** 是否是直播 默认 true */ + isLive: boolean; + decoder?: string; + [key: string]: any; +} + +interface UIOptions extends HlsOptions { + /** 视窗的宽 */ + nodeName: 'video' | 'canvas'; + disableContextmenu: boolean; +} +/** + * @class UI + * @description UI + * + * @example + * ```ts + * const ui = new UIVideo({ + * id: "id", + * width: 100, + * height: 100 + * }); + * ``` + */ +declare class UIVideo { + private readonly _classVideo; + $video: T; + logger: any; + event: any; + options: any; + private readonly _$container; + /** + * @description 构造函数 + * @param {UIOptions} options + */ + constructor(options?: Partial); + /** + * @description 渲染 UI + */ + private _render; + /** + * @description 是否是 video 标签 + * @returns {boolean} + */ + private _isVideo; + /** + * @description 销毁 + */ + destroy(): void; +} + +interface SoftPlayerOptions extends UIOptions { + width: number; + height: number; + fps: number; + fixed: any; + sampleRate: number; + appendHevcType: number; + frameDurMs: number; + id: string; + audioNone: boolean; + videoCodec: any; + logger: LoggerCls; + decoderWorker: Worker; + type: 'hls'; + volume: number; + isLive: boolean; +} +type Fn = (a?: any) => any; +declare class SoftPlayer extends UIVideo implements IEnginePlayer { + options: SoftPlayerOptions; + logger: LoggerCls; + frameList: BufferFrame[]; + cacheInterval: number; + nowPacket: null; + stream: Uint8Array; + vCodecID: number; + audio: AudioCore; + liveStartMs: number; + durationMs: number; + videoPTS: number; + loop: number; + cacheLoop: number; + playParams: { + seekPos: number; + isLive: boolean; + accurateSeek: boolean; + seekEvent: boolean; + realPlay: boolean; + }; + calculateStartTime: number; + fix_poc_err_skip: number; + frameTime: number; + frameTimeSec: number; + preCostTime: number; + _volume: number; + isPlaying: boolean; + isCaching: any; + isNewSeek: boolean; + flushDecoder: number; + isCheckDisplay: boolean; + isPlayLoadingFinish: number; + vCachePTS: number; + aCachePTS: number; + noCacheFrame: number; + onPlayingTime: Fn; + onPlayingFinish: Fn; + onLoadCache: Fn; + onLoadCacheFinished: Fn; + gl: WebGlRender; + cacheYuvBuf: Cache; + decoderWorker: Worker; + constructor(options?: Partial); + setSize(width: any, height: any): void; + setFrameRate(fps?: number): void; + setDurationMs(durationMs?: number): void; + setPlayingCall(callback: any): void; + get volume(): number; + set volume(volume: number); + setVolume(volume?: number): void; + isPlayingState(): boolean; + appendAACFrame(streamBytes: any): void; + appendHevcFrame(streamBytes: BufferFrame): void; + getCachePTS(): number; + endAudio(): void; + cleanSample(): void; + cleanVideoQueue(): void; + cleanCacheYUV(): void; + /** + * @description pause + */ + pause(): void; + checkFinished(mode: any): boolean; + clearAllCache(): void; + getNalu1Packet(alginPTS?: boolean): { + nalBuf: false | Uint8Array; + pts: number; + } | null; + /** + * @TODO + */ + cacheThread(): void; + stopCacheThread(): void; + /** + * 缓存中 + */ + loadCache(): void; + _playFunc(): boolean | undefined; + /** + * seekPos=-1, + * accurateSeek=true, + * seekEvent=false, + * realPlay=true + */ + play(playParams?: any): Promise; + stop(): void; + /** + * @description 释放 + * @returns + */ + destroy(): boolean; + /** + * + */ + nextNalu(onceGetNalCount?: number): false | Uint8Array; + /** + * @brief play yuv cache + */ + playFrameYUV(show?: boolean): boolean; + drawImage(width: any, height: any, imageBufferY: any, imageBufferB: any, imageBufferR: any): void; + checkDisplaySize(widthIn: number, heightIn: number): number[]; + _onWorkerMessage(): void; + initVideoAndAudio(): void; +} + +interface HardHlsPlayerOptions extends Omit { + logger: LoggerCls; + event: EventEmitter; + volume: number; +} +/** + * @classdesc hls 播放器 (h264) + */ +declare class HardHlsPlayer extends UIVideo implements IEnginePlayer { + hlsPlayer: Hls; + _options: HardHlsPlayerOptions; + event: EventEmitter; + _hls: Hls; + _volume: number; + logger: LoggerCls; + constructor(options: HardHlsPlayerOptions); + private _init; + isPlayingState(): boolean; + play(): Promise; + pause(): void; + /** + * @description 获取音量 + * @example + * ```ts + * player.volume // return number + * ``` + */ + get volume(): number; + /** + * @description 设置音量 [0.0 ~ 1.0] + * @example + * ```ts + * player.volume = 0.8 + * ``` + */ + set volume(volume: number); + /** + * @description 设置音量 [0.0 ~ 1.0] + * @param {number} volume + */ + setVolume(volume?: number): void; + destroy(): void; + _onEvent(): void; +} + +/** + * @class UI + * @description UI + * + * @example + * ```ts + * const ui = new UIContainer({ + * id: "id", + * width: 100, + * height: 100 + * }); + * ``` + */ +declare class UIContainer extends BasePlayer { + private readonly _containerClassName; + /** + * @description 构造函数 + * @param {UIOptions} options + */ + constructor(options?: Partial); + private _render; + /** + * @description 销毁 + */ + destroy(): void; +} + +/** + * @description hls 播放器 + */ +declare class HlsPlayer extends UIContainer { + /** WebAssembly completed loading identity */ + static __HLS_WASM_DecoderState__: number; + private _decoderWorker; + private _m3u8Obj; + url: string; + playParam: any; + player: SoftPlayer | HardHlsPlayer; + onPlayTime: any; + onParsed: any; + onSeekStart: null; + onLoadCache?: any; + onLoadCacheFinished?: any; + onPlayFinish: any; + onCacheProcess: any; + onReadyShowDone: any; + onError: null; + _volume: number; + constructor(options: Partial); + _init(): void; + /** + * + * @description 播放 + * @returns {Promise} + * @example + * + * ```ts + * player.play() + * ``` + * + */ + play(): Promise; + /** + * @description 暂停 + * @returns {void} + * + * @example + * ```ts + * player.pause() + * ``` + */ + pause(): boolean; + /** + * @description 销毁实例和dom + * @returns {void} + * @example + * ```ts + * player.destroy() + * ``` + */ + destroy(): boolean; + /** + * @description 当前的播放状态 + * @returns {boolean} + */ + isPlaying(): boolean; + /** + * @description 获取音量 + * @example + * ```ts + * player.volume // return number + * ``` + */ + get volume(): number; + /** + * @description 设置音量 [0.0 ~ 1.0] + * @example + * ```ts + * player.volume = 0.8 + * ``` + */ + set volume(volume: number); + setVolume(volume: number): void; + /** + * @description 当前版本 + * @static + * + * @example + * ```ts + * HlsPlayer.version + * ``` + */ + static version: string; + /** + * @description 获取版本号 + * @returns {string} + */ + getVersion(): string; + /** + * @description 静态方法 判断是否支持播放地址 + * @param {Partial<{ url: string }>} options + * @returns {boolean} + * @static + * + * @example + * ```ts + * HlsPlayer.supportType({url: "https://open.ys7.com/v3/openlive/E71992743_1_1.m3u8"}) + * ``` + */ + static supportType(options: Partial<{ + url?: string; + type?: string; + }>): boolean; + /** + * @brief m3u8 + */ + _m3u8Entry(): void; + _checkPlayer(empty: any, isAVC?: boolean): void; + _hlsOnSamples(readyObj: any, frame: BufferFrame): void; + _onWorkerMessage(): void; + _softPlayer(durationMs: any, fps: any, sampleRate: any, size: any, audioNone?: boolean, videoCodec?: null): void; +} + +export { type HlsOptions, HlsPlayer as default }; diff --git a/examples/base-app/README.md b/examples/base-app/README.md index 2fbb336..3700a35 100644 --- a/examples/base-app/README.md +++ b/examples/base-app/README.md @@ -1,7 +1,5 @@ ## 使用 - - ```bash # 安装 http-server diff --git a/examples/base-app/decoder.wasm b/examples/base-app/decoder.wasm new file mode 100644 index 0000000..5c0c2fa Binary files /dev/null and b/examples/base-app/decoder.wasm differ diff --git a/examples/base-app/decoder.worker.js b/examples/base-app/decoder.worker.js new file mode 100644 index 0000000..4b8dbac --- /dev/null +++ b/examples/base-app/decoder.worker.js @@ -0,0 +1,8 @@ +/* +* +* DecoderWorker.js v0.1.0 +* Copyright (c) 2024-8-1 Ezviz-OpenBiz +* . +* +*/ +!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";var e={DEFAULT_SAMPLERATE:44100,DEFAULT_CHANNEL:1,H264AUD:[0,0,0,1,9,224],H265AUD:[0,0,0,1,70,1,80],DEF_AAC:"aac",DEF_MP3:"mp3",DEF_H265:"h265",DEF_HEVC:"hevc",DEF_H264:"h264",DEF_AVC:"avc",CODEC_OFFSET_TABLE:["hevc","h265","avc","h264","aac","mp3"]};function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t={exports:{}};!function(e,r){function t(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var d,f,p=(f="undefined"!=typeof document?null==(d=document.currentScript)?void 0:d.src:void 0,function(e){var r,t=function(){var r=dr.value;r in e||Object.defineProperty(e,r,{configurable:!0,get:function(){q("Access to module property ('"+r+"') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.")}})};void 0===e&&(e={});var n,i,d=Object.assign({},e),p=new Promise((function(e,r){n=e,i=r}));["_malloc","_free","_memory","_registerWasmPlayer","_setCodecType","_exitWasmPlayer","_initDecoder","_decodeCodecContext","_destroy","_demuxTsStream","_getPacket","_getVLCLen","_getVLC","_getVPSLen","_getVPS","_getSPSLen","_getSPS","_getPPSLen","_getPPS","_getSEILen","_getSEI","___indirect_function_table","_ff_h264_cabac_tables","onRuntimeInitialized"].forEach((function(e){Object.getOwnPropertyDescriptor(p,e)||Object.defineProperty(p,e,{get:function(){return q("You are getting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")},set:function(){return q("You are setting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")}})}));var m="object"==("undefined"==typeof window?"undefined":u(window)),h="function"==typeof importScripts,g="object"==("undefined"==typeof process?"undefined":u(process))&&"object"==u(process.versions)&&"string"==typeof process.versions.node,v=!m&&!g&&!h;if(d.ENVIRONMENT)throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");var E,y,w,b=Object.assign({},d),_="./this.program",S="";if(v){if("object"==("undefined"==typeof process?"undefined":u(process))||"object"==("undefined"==typeof window?"undefined":u(window))||"function"==typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)")}else{if(!m&&!h)throw new Error("environment detection error");if(h?S=self.location.href:"undefined"!=typeof document&&document.currentScript&&(S=document.currentScript.src),f&&(S=f),S=S.startsWith("blob:")?"":S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1),"object"!=("undefined"==typeof window?"undefined":u(window))&&"function"!=typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");E=function(e){var r=new XMLHttpRequest;return r.open("GET",e,!1),r.send(null),r.responseText},h&&(w=function(e){var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),y=function(e,r,t){var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=function(){200==n.status||0==n.status&&n.response?r(n.response):t()},n.onerror=t,n.send(null)}}var O,T,k,A=d.print||console.log.bind(console),M=d.printErr||console.error.bind(console);Object.assign(d,b),b=null,O="fetchSettings",Object.getOwnPropertyDescriptor(d,O)&&q("`Module."+O+"` was supplied but `"+O+"` not included in INCOMING_MODULE_JS_API"),d.arguments&&d.arguments,ie("arguments","arguments_"),d.thisProgram&&(_=d.thisProgram),ie("thisProgram","thisProgram"),d.quit&&d.quit,ie("quit","quit_"),L(void 0===d.memoryInitializerPrefixURL,"Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.pthreadMainPrefixURL,"Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.cdInitializerPrefixURL,"Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.filePackagePrefixURL,"Module.filePackagePrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.read,"Module.read option was removed (modify read_ in JS)"),L(void 0===d.readAsync,"Module.readAsync option was removed (modify readAsync in JS)"),L(void 0===d.readBinary,"Module.readBinary option was removed (modify readBinary in JS)"),L(void 0===d.setWindowTitle,"Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"),L(void 0===d.TOTAL_MEMORY,"Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"),ie("asm","wasmExports"),ie("read","read_"),ie("readAsync","readAsync"),ie("readBinary","readBinary"),ie("setWindowTitle","setWindowTitle"),L(!g,"node environment detected but not enabled at build time. Add `node` to `-sENVIRONMENT` to enable."),L(!v,"shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable."),d.wasmBinary&&(T=d.wasmBinary),ie("wasmBinary","wasmBinary"),"object"!=("undefined"==typeof WebAssembly?"undefined":u(WebAssembly))&&M("no native wasm support detected");var P,F,C,D,x,I=!1;function L(e,r){e||q("Assertion failed"+(r?": "+r:""))}function N(){var e=k.buffer;d.HEAP8=P=new Int8Array(e),d.HEAP16=C=new Int16Array(e),d.HEAPU8=F=new Uint8Array(e),d.HEAPU16=new Uint16Array(e),d.HEAP32=D=new Int32Array(e),d.HEAPU32=x=new Uint32Array(e),d.HEAPF32=new Float32Array(e),d.HEAPF64=new Float64Array(e)}function R(){if(!I){var e=ir();0==e&&(e+=4);var r=x[e>>2],t=x[e+4>>2];34821223==r&&2310721022==t||q("Stack overflow! Stack cookie has been overwritten at "+le(e)+", expected hex dwords 0x89BACDFE and 0x2135467, but received "+le(t)+" "+le(r)),1668509029!=x[0]&&q("Runtime error: The application has corrupted its heap memory area (address zero)!")}}L(!d.STACK_SIZE,"STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"),L("undefined"!=typeof Int32Array&&"undefined"!=typeof Float64Array&&null!=Int32Array.prototype.subarray&&null!=Int32Array.prototype.set,"JS engine does not provide full typed array support"),L(!d.wasmMemory,"Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"),L(!d.INITIAL_MEMORY,"Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically"),function(){var e=new Int16Array(1),r=new Int8Array(e.buffer);if(e[0]=25459,115!==r[0]||99!==r[1])throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"}();var U=[],B=[],j=[],$=!1;L(Math.imul,"This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.fround,"This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.clz32,"This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.trunc,"This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");var W=0,H=null,z=null,V={};function G(e){for(var r=e;;){if(!V[e])return e;e=r+Math.random()}}function Y(e){var r;W++,null==(r=d.monitorRunDependencies)||r.call(d,W),e?(L(!V[e]),V[e]=1,null===H&&"undefined"!=typeof setInterval&&(H=setInterval((function(){if(I)return clearInterval(H),void(H=null);var e=!1;for(var r in V)e||(e=!0,M("still waiting on run dependencies:")),M("dependency: "+r);e&&M("(end of list)")}),1e4))):M("warning: run dependency added without ID")}function Q(e){var r;if(W--,null==(r=d.monitorRunDependencies)||r.call(d,W),e?(L(V[e]),delete V[e]):M("warning: run dependency removed without ID"),0==W&&(null!==H&&(clearInterval(H),H=null),z)){var t=z;z=null,t()}}function q(e){var r;null==(r=d.onAbort)||r.call(d,e),M(e="Aborted("+e+")"),I=!0;var t=new WebAssembly.RuntimeError(e);throw i(t),t}var K,X,J,Z=function(e){return e.startsWith("data:application/octet-stream;base64,")},ee=function(e){return e.startsWith("file://")};function re(e,r){return function(){for(var t=arguments.length,n=new Array(t),o=0;o0;)e.shift()(d)};d.noExitRuntime;var le=function(e){return L("number"==typeof e),"0x"+(e>>>=0).toString(16).padStart(8,"0")},de=function(e){var r;(r=de).shown||(r.shown={}),de.shown[e]||(de.shown[e]=1,M(e))};function fe(){L(null!=xe.varargs);var e=D[+xe.varargs>>2];return xe.varargs+=4,e}var pe=fe,me={isAbs:function(e){return"/"===e.charAt(0)},splitPath:function(e){return/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1)},normalizeArray:function(e,r){for(var t=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),t++):t&&(e.splice(n,1),t--)}if(r)for(;t;t--)e.unshift("..");return e},normalize:function(e){var r=me.isAbs(e),t="/"===e.substr(-1);return(e=me.normalizeArray(e.split("/").filter((function(e){return!!e})),!r).join("/"))||r||(e="."),e&&t&&(e+="/"),(r?"/":"")+e},dirname:function(e){var r=me.splitPath(e),t=r[0],n=r[1];return t||n?(n&&(n=n.substr(0,n.length-1)),t+n):"."},basename:function(e){if("/"===e)return"/";var r=(e=(e=me.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===r?e:e.substr(r+1)},join:function(){for(var e=arguments.length,r=new Array(e),t=0;t { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };")}())(e)},ge={resolve:function(){for(var e=arguments.length,r=new Array(e),t=0;t=-1&&!o;i--){var a=i>=0?r[i]:Ce.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");if(!a)return"";n=a+"/"+n,o=me.isAbs(a)}return(o?"/":"")+(n=me.normalizeArray(n.split("/").filter((function(e){return!!e})),!o).join("/"))||"."},relative:function(e,r){var t=function(e){for(var r=0;r=0&&""===e[t];t--);return r>t?[]:e.slice(r,t-r+1)};e=ge.resolve(e).substr(1),r=ge.resolve(r).substr(1);for(var n=t(e.split("/")),o=t(r.split("/")),i=Math.min(n.length,o.length),a=i,s=0;s=n);)++o;if(o-r>16&&e.buffer&&ve)return ve.decode(e.subarray(r,o));for(var i="";r>10,56320|1023&c)}}else i+=String.fromCharCode((31&a)<<6|s)}else i+=String.fromCharCode(a)}return i},ye=[],we=function(e){for(var r=0,t=0;t=55296&&n<=57343?(r+=4,++t):r+=3}return r},be=function(e,r,t,n){if(L("string"==typeof e,"stringToUTF8Array expects a string (got "+(void 0===e?"undefined":u(e))+")"),!(n>0))return 0;for(var o=t,i=t+n-1,a=0;a=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),s<=127){if(t>=i)break;r[t++]=s}else if(s<=2047){if(t+1>=i)break;r[t++]=192|s>>6,r[t++]=128|63&s}else if(s<=65535){if(t+2>=i)break;r[t++]=224|s>>12,r[t++]=128|s>>6&63,r[t++]=128|63&s}else{if(t+3>=i)break;s>1114111&&de("Invalid Unicode code point "+le(s)+" encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."),r[t++]=240|s>>18,r[t++]=128|s>>12&63,r[t++]=128|s>>6&63,r[t++]=128|63&s}}return r[t]=0,t-o};function _e(e,r,t){var n=we(e)+1,o=new Array(n),i=be(e,o,0,o.length);return o.length=i,o}var Se,Oe={ttys:[],init:function(){},shutdown:function(){},register:function(e,r){Oe.ttys[e]={input:[],output:[],ops:r},Ce.registerDevice(e,Oe.stream_ops)},stream_ops:{open:function(e){var r=Oe.ttys[e.node.rdev];if(!r)throw new Ce.ErrnoError(43);e.tty=r,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,r,t,n,o){if(!e.tty||!e.tty.ops.get_char)throw new Ce.ErrnoError(60);for(var i=0,a=0;a0&&(A(Ee(e.output,0)),e.output=[])},ioctl_tcgets:function(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(e,r,t){return 0},ioctl_tiocgwinsz:function(e){return[24,80]}},default_tty1_ops:{put_char:function(e,r){null===r||10===r?(M(Ee(e.output,0)),e.output=[]):0!=r&&e.output.push(r)},fsync:function(e){e.output&&e.output.length>0&&(M(Ee(e.output,0)),e.output=[])}}},Te=function(e){q("internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported")},ke={ops_table:null,mount:function(e){return ke.createNode(null,"/",16895,0)},createNode:function(e,r,t,n){var o;if(Ce.isBlkdev(t)||Ce.isFIFO(t))throw new Ce.ErrnoError(63);(o=ke).ops_table||(o.ops_table={dir:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr,lookup:ke.node_ops.lookup,mknod:ke.node_ops.mknod,rename:ke.node_ops.rename,unlink:ke.node_ops.unlink,rmdir:ke.node_ops.rmdir,readdir:ke.node_ops.readdir,symlink:ke.node_ops.symlink},stream:{llseek:ke.stream_ops.llseek}},file:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr},stream:{llseek:ke.stream_ops.llseek,read:ke.stream_ops.read,write:ke.stream_ops.write,allocate:ke.stream_ops.allocate,mmap:ke.stream_ops.mmap,msync:ke.stream_ops.msync}},link:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr,readlink:ke.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr},stream:Ce.chrdev_stream_ops}});var i=Ce.createNode(e,r,t,n);return Ce.isDir(i.mode)?(i.node_ops=ke.ops_table.dir.node,i.stream_ops=ke.ops_table.dir.stream,i.contents={}):Ce.isFile(i.mode)?(i.node_ops=ke.ops_table.file.node,i.stream_ops=ke.ops_table.file.stream,i.usedBytes=0,i.contents=null):Ce.isLink(i.mode)?(i.node_ops=ke.ops_table.link.node,i.stream_ops=ke.ops_table.link.stream):Ce.isChrdev(i.mode)&&(i.node_ops=ke.ops_table.chrdev.node,i.stream_ops=ke.ops_table.chrdev.stream),i.timestamp=Date.now(),e&&(e.contents[r]=i,e.timestamp=i.timestamp),i},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,r){var t=e.contents?e.contents.length:0;if(!(t>=r)){r=Math.max(r,t*(t<1048576?2:1.125)>>>0),0!=t&&(r=Math.max(r,256));var n=e.contents;e.contents=new Uint8Array(r),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,r){if(e.usedBytes!=r)if(0==r)e.contents=null,e.usedBytes=0;else{var t=e.contents;e.contents=new Uint8Array(r),t&&e.contents.set(t.subarray(0,Math.min(r,e.usedBytes))),e.usedBytes=r}},node_ops:{getattr:function(e){var r={};return r.dev=Ce.isChrdev(e.mode)?e.id:1,r.ino=e.id,r.mode=e.mode,r.nlink=1,r.uid=0,r.gid=0,r.rdev=e.rdev,Ce.isDir(e.mode)?r.size=4096:Ce.isFile(e.mode)?r.size=e.usedBytes:Ce.isLink(e.mode)?r.size=e.link.length:r.size=0,r.atime=new Date(e.timestamp),r.mtime=new Date(e.timestamp),r.ctime=new Date(e.timestamp),r.blksize=4096,r.blocks=Math.ceil(r.size/r.blksize),r},setattr:function(e,r){void 0!==r.mode&&(e.mode=r.mode),void 0!==r.timestamp&&(e.timestamp=r.timestamp),void 0!==r.size&&ke.resizeFileStorage(e,r.size)},lookup:function(e,r){throw Ce.genericErrors[44]},mknod:function(e,r,t,n){return ke.createNode(e,r,t,n)},rename:function(e,r,t){if(Ce.isDir(e.mode)){var n;try{n=Ce.lookupNode(r,t)}catch(e){}if(n)for(var o in n.contents)throw new Ce.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=t,r.contents[t]=e,r.timestamp=e.parent.timestamp,e.parent=r},unlink:function(e,r){delete e.contents[r],e.timestamp=Date.now()},rmdir:function(e,r){var t=Ce.lookupNode(e,r);for(var n in t.contents)throw new Ce.ErrnoError(55);delete e.contents[r],e.timestamp=Date.now()},readdir:function(e){for(var r,t=[".",".."],n=l(Object.keys(e.contents));!(r=n()).done;){var o=r.value;t.push(o)}return t},symlink:function(e,r,t){var n=ke.createNode(e,r,41471,0);return n.link=t,n},readlink:function(e){if(!Ce.isLink(e.mode))throw new Ce.ErrnoError(28);return e.link}},stream_ops:{read:function(e,r,t,n,o){var i=e.node.contents;if(o>=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,n);if(L(a>=0),a>8&&i.subarray)r.set(i.subarray(o,o+a),t);else for(var s=0;s0||t+r8)throw new Ce.ErrnoError(32);for(var t=e.split("/").filter((function(e){return!!e})),n=Ce.root,o="/",i=0;i40)throw new Ce.ErrnoError(32)}}return{path:o,node:n}},getPath:function(e){for(var r;;){if(Ce.isRoot(e)){var t=e.mount.mountpoint;return r?"/"!==t[t.length-1]?t+"/"+r:t+r:t}r=r?e.name+"/"+r:e.name,e=e.parent}},hashName:function(e,r){for(var t=0,n=0;n>>0)%Ce.nameTable.length},hashAddNode:function(e){var r=Ce.hashName(e.parent.id,e.name);e.name_next=Ce.nameTable[r],Ce.nameTable[r]=e},hashRemoveNode:function(e){var r=Ce.hashName(e.parent.id,e.name);if(Ce.nameTable[r]===e)Ce.nameTable[r]=e.name_next;else for(var t=Ce.nameTable[r];t;){if(t.name_next===e){t.name_next=e.name_next;break}t=t.name_next}},lookupNode:function(e,r){var t=Ce.mayLookup(e);if(t)throw new Ce.ErrnoError(t);for(var n=Ce.hashName(e.id,r),o=Ce.nameTable[n];o;o=o.name_next){var i=o.name;if(o.parent.id===e.id&&i===r)return o}return Ce.lookup(e,r)},createNode:function(e,r,t,n){L("object"==(void 0===e?"undefined":u(e)));var o=new Ce.FSNode(e,r,t,n);return Ce.hashAddNode(o),o},destroyNode:function(e){Ce.hashRemoveNode(e)},isRoot:function(e){return e===e.parent},isMountpoint:function(e){return!!e.mounted},isFile:function(e){return 32768==(61440&e)},isDir:function(e){return 16384==(61440&e)},isLink:function(e){return 40960==(61440&e)},isChrdev:function(e){return 8192==(61440&e)},isBlkdev:function(e){return 24576==(61440&e)},isFIFO:function(e){return 4096==(61440&e)},isSocket:function(e){return!(49152&~e)},flagsToPermissionString:function(e){var r=["r","w","rw"][3&e];return 512&e&&(r+="w"),r},nodePermissions:function(e,r){return Ce.ignorePermissions||(!r.includes("r")||292&e.mode)&&(!r.includes("w")||146&e.mode)&&(!r.includes("x")||73&e.mode)?0:2},mayLookup:function(e){if(!Ce.isDir(e.mode))return 54;var r=Ce.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate:function(e,r){try{return Ce.lookupNode(e,r),20}catch(e){}return Ce.nodePermissions(e,"wx")},mayDelete:function(e,r,t){var n;try{n=Ce.lookupNode(e,r)}catch(e){return e.errno}var o=Ce.nodePermissions(e,"wx");if(o)return o;if(t){if(!Ce.isDir(n.mode))return 54;if(Ce.isRoot(n)||Ce.getPath(n)===Ce.cwd())return 10}else if(Ce.isDir(n.mode))return 31;return 0},mayOpen:function(e,r){return e?Ce.isLink(e.mode)?32:Ce.isDir(e.mode)&&("r"!==Ce.flagsToPermissionString(r)||512&r)?31:Ce.nodePermissions(e,Ce.flagsToPermissionString(r)):44},MAX_OPEN_FDS:4096,nextfd:function(){for(var e=0;e<=Ce.MAX_OPEN_FDS;e++)if(!Ce.streams[e])return e;throw new Ce.ErrnoError(33)},getStreamChecked:function(e){var r=Ce.getStream(e);if(!r)throw new Ce.ErrnoError(8);return r},getStream:function(e){return Ce.streams[e]},createStream:function(e,r){return void 0===r&&(r=-1),e=Object.assign(new Ce.FSStream,e),-1==r&&(r=Ce.nextfd()),e.fd=r,Ce.streams[r]=e,e},closeStream:function(e){Ce.streams[e]=null},dupStream:function(e,r){var t,n;void 0===r&&(r=-1);var o=Ce.createStream(e,r);return null==(n=o.stream_ops)||null==(t=n.dup)||t.call(n,o),o},chrdev_stream_ops:{open:function(e){var r=Ce.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,null==e.stream_ops.open||e.stream_ops.open.call(e.stream_ops,e)},llseek:function(){throw new Ce.ErrnoError(70)}},major:function(e){return e>>8},minor:function(e){return 255&e},makedev:function(e,r){return e<<8|r},registerDevice:function(e,r){Ce.devices[e]={stream_ops:r}},getDevice:function(e){return Ce.devices[e]},getMounts:function(e){for(var r=[],t=[e];t.length;){var n,o=t.pop();r.push(o),(n=t).push.apply(n,[].concat(o.mounts))}return r},syncfs:function(e,r){"function"==typeof e&&(r=e,e=!1),Ce.syncFSRequests++,Ce.syncFSRequests>1&&M("warning: "+Ce.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var t=Ce.getMounts(Ce.root.mount),n=0;function o(e){return L(Ce.syncFSRequests>0),Ce.syncFSRequests--,r(e)}function i(e){if(e)return i.errored?void 0:(i.errored=!0,o(e));++n>=t.length&&o(null)}t.forEach((function(r){if(!r.type.syncfs)return i(null);r.type.syncfs(r,e,i)}))},mount:function(e,r,t){if("string"==typeof e)throw e;var n,o="/"===t,i=!t;if(o&&Ce.root)throw new Ce.ErrnoError(10);if(!o&&!i){var a=Ce.lookupPath(t,{follow_mount:!1});if(t=a.path,n=a.node,Ce.isMountpoint(n))throw new Ce.ErrnoError(10);if(!Ce.isDir(n.mode))throw new Ce.ErrnoError(54)}var s={type:e,opts:r,mountpoint:t,mounts:[]},u=e.mount(s);return u.mount=s,s.root=u,o?Ce.root=u:n&&(n.mounted=s,n.mount&&n.mount.mounts.push(s)),u},unmount:function(e){var r=Ce.lookupPath(e,{follow_mount:!1});if(!Ce.isMountpoint(r.node))throw new Ce.ErrnoError(28);var t=r.node,n=t.mounted,o=Ce.getMounts(n);Object.keys(Ce.nameTable).forEach((function(e){for(var r=Ce.nameTable[e];r;){var t=r.name_next;o.includes(r.mount)&&Ce.destroyNode(r),r=t}})),t.mounted=null;var i=t.mount.mounts.indexOf(n);L(-1!==i),t.mount.mounts.splice(i,1)},lookup:function(e,r){return e.node_ops.lookup(e,r)},mknod:function(e,r,t){var n=Ce.lookupPath(e,{parent:!0}).node,o=me.basename(e);if(!o||"."===o||".."===o)throw new Ce.ErrnoError(28);var i=Ce.mayCreate(n,o);if(i)throw new Ce.ErrnoError(i);if(!n.node_ops.mknod)throw new Ce.ErrnoError(63);return n.node_ops.mknod(n,o,r,t)},create:function(e,r){return r=void 0!==r?r:438,r&=4095,r|=32768,Ce.mknod(e,r,0)},mkdir:function(e,r){return r=void 0!==r?r:511,r&=1023,r|=16384,Ce.mknod(e,r,0)},mkdirTree:function(e,r){for(var t=e.split("/"),n="",o=0;o=0),n<0||o<0)throw new Ce.ErrnoError(28);if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(1==(2097155&e.flags))throw new Ce.ErrnoError(8);if(Ce.isDir(e.node.mode))throw new Ce.ErrnoError(31);if(!e.stream_ops.read)throw new Ce.ErrnoError(28);var i=void 0!==o;if(i){if(!e.seekable)throw new Ce.ErrnoError(70)}else o=e.position;var a=e.stream_ops.read(e,r,t,n,o);return i||(e.position+=a),a},write:function(e,r,t,n,o,i){if(L(t>=0),n<0||o<0)throw new Ce.ErrnoError(28);if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(!(2097155&e.flags))throw new Ce.ErrnoError(8);if(Ce.isDir(e.node.mode))throw new Ce.ErrnoError(31);if(!e.stream_ops.write)throw new Ce.ErrnoError(28);e.seekable&&1024&e.flags&&Ce.llseek(e,0,2);var a=void 0!==o;if(a){if(!e.seekable)throw new Ce.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,r,t,n,o,i);return a||(e.position+=s),s},allocate:function(e,r,t){if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(r<0||t<=0)throw new Ce.ErrnoError(28);if(!(2097155&e.flags))throw new Ce.ErrnoError(8);if(!Ce.isFile(e.node.mode)&&!Ce.isDir(e.node.mode))throw new Ce.ErrnoError(43);if(!e.stream_ops.allocate)throw new Ce.ErrnoError(138);e.stream_ops.allocate(e,r,t)},mmap:function(e,r,t,n,o){if(2&n&&!(2&o)&&2!=(2097155&e.flags))throw new Ce.ErrnoError(2);if(1==(2097155&e.flags))throw new Ce.ErrnoError(2);if(!e.stream_ops.mmap)throw new Ce.ErrnoError(43);return e.stream_ops.mmap(e,r,t,n,o)},msync:function(e,r,t,n,o){return L(t>=0),e.stream_ops.msync?e.stream_ops.msync(e,r,t,n,o):0},ioctl:function(e,r,t){if(!e.stream_ops.ioctl)throw new Ce.ErrnoError(59);return e.stream_ops.ioctl(e,r,t)},readFile:function(e,r){if(void 0===r&&(r={}),r.flags=r.flags||0,r.encoding=r.encoding||"binary","utf8"!==r.encoding&&"binary"!==r.encoding)throw new Error('Invalid encoding type "'+r.encoding+'"');var t,n=Ce.open(e,r.flags),o=Ce.stat(e).size,i=new Uint8Array(o);return Ce.read(n,i,0,o,0),"utf8"===r.encoding?t=Ee(i,0):"binary"===r.encoding&&(t=i),Ce.close(n),t},writeFile:function(e,r,t){void 0===t&&(t={}),t.flags=t.flags||577;var n=Ce.open(e,t.flags,t.mode);if("string"==typeof r){var o=new Uint8Array(we(r)+1),i=be(r,o,0,o.length);Ce.write(n,o,0,i,void 0,t.canOwn)}else{if(!ArrayBuffer.isView(r))throw new Error("Unsupported data type");Ce.write(n,r,0,r.byteLength,void 0,t.canOwn)}Ce.close(n)},cwd:function(){return Ce.currentPath},chdir:function(e){var r=Ce.lookupPath(e,{follow:!0});if(null===r.node)throw new Ce.ErrnoError(44);if(!Ce.isDir(r.node.mode))throw new Ce.ErrnoError(54);var t=Ce.nodePermissions(r.node,"x");if(t)throw new Ce.ErrnoError(t);Ce.currentPath=r.path},createDefaultDirectories:function(){Ce.mkdir("/tmp"),Ce.mkdir("/home"),Ce.mkdir("/home/web_user")},createDefaultDevices:function(){Ce.mkdir("/dev"),Ce.registerDevice(Ce.makedev(1,3),{read:function(){return 0},write:function(e,r,t,n,o){return n}}),Ce.mkdev("/dev/null",Ce.makedev(1,3)),Oe.register(Ce.makedev(5,0),Oe.default_tty_ops),Oe.register(Ce.makedev(6,0),Oe.default_tty1_ops),Ce.mkdev("/dev/tty",Ce.makedev(5,0)),Ce.mkdev("/dev/tty1",Ce.makedev(6,0));var e=new Uint8Array(1024),r=0,t=function(){return 0===r&&(r=he(e).byteLength),e[--r]};Ce.createDevice("/dev","random",t),Ce.createDevice("/dev","urandom",t),Ce.mkdir("/dev/shm"),Ce.mkdir("/dev/shm/tmp")},createSpecialDirectories:function(){Ce.mkdir("/proc");var e=Ce.mkdir("/proc/self");Ce.mkdir("/proc/self/fd"),Ce.mount({mount:function(){var r=Ce.createNode(e,"fd",16895,73);return r.node_ops={lookup:function(e,r){var t=+r,n=Ce.getStreamChecked(t),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:function(){return n.path}}};return o.parent=o,o}},r}},{},"/proc/self/fd")},createStandardStreams:function(){d.stdin?Ce.createDevice("/dev","stdin",d.stdin):Ce.symlink("/dev/tty","/dev/stdin"),d.stdout?Ce.createDevice("/dev","stdout",null,d.stdout):Ce.symlink("/dev/tty","/dev/stdout"),d.stderr?Ce.createDevice("/dev","stderr",null,d.stderr):Ce.symlink("/dev/tty1","/dev/stderr");var e=Ce.open("/dev/stdin",0),r=Ce.open("/dev/stdout",1),t=Ce.open("/dev/stderr",1);L(0===e.fd,"invalid handle for stdin ("+e.fd+")"),L(1===r.fd,"invalid handle for stdout ("+r.fd+")"),L(2===t.fd,"invalid handle for stderr ("+t.fd+")")},staticInit:function(){[44].forEach((function(e){Ce.genericErrors[e]=new Ce.ErrnoError(e),Ce.genericErrors[e].stack=""})),Ce.nameTable=new Array(4096),Ce.mount(ke,{},"/"),Ce.createDefaultDirectories(),Ce.createDefaultDevices(),Ce.createSpecialDirectories(),Ce.filesystems={MEMFS:ke}},init:function(e,r,t){L(!Ce.init.initialized,"FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"),Ce.init.initialized=!0,d.stdin=e||d.stdin,d.stdout=r||d.stdout,d.stderr=t||d.stderr,Ce.createStandardStreams()},quit:function(){Ce.init.initialized=!1,tr(0);for(var e=0;ethis.length-1||e<0)){var r=e%this.chunkSize,t=e/this.chunkSize|0;return this.getter(t)[r]}},r.setDataGetter=function(e){this.getter=e},r.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",t,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+t+". Status: "+e.status);var r,n=Number(e.getResponseHeader("Content-length")),o=(r=e.getResponseHeader("Accept-Ranges"))&&"bytes"===r,i=(r=e.getResponseHeader("Content-Encoding"))&&"gzip"===r,a=1048576;o||(a=n);var s=this;s.setDataGetter((function(e){var r=e*a,o=(e+1)*a-1;if(o=Math.min(o,n-1),void 0===s.chunks[e]&&(s.chunks[e]=function(e,r){if(e>r)throw new Error("invalid range ("+e+", "+r+") or no bytes requested!");if(r>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",t,!1),n!==a&&o.setRequestHeader("Range","bytes="+e+"-"+r),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+t+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):_e(o.responseText||"")}(r,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]})),!i&&n||(a=n=1,n=this.getter(0).length,a=n,A("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=a,this.lengthKnown=!0},o(e,[{key:"length",get:function(){return this.lengthKnown||this.cacheLength(),this._length}},{key:"chunkSize",get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}]),e}();if("undefined"!=typeof XMLHttpRequest){if(!h)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s={isDevice:!1,contents:new a}}else s={isDevice:!1,url:t};var u=Ce.createFile(e,r,s,n,i);s.contents?u.contents=s.contents:s.url&&(u.contents=null,u.url=s.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var c={};function l(e,r,t,n,o){var i=e.node.contents;if(o>=i.length)return 0;var a=Math.min(i.length-o,n);if(L(a>=0),i.slice)for(var s=0;s>2]=n.dev,D[t+4>>2]=n.mode,x[t+8>>2]=n.nlink,D[t+12>>2]=n.uid,D[t+16>>2]=n.gid,D[t+20>>2]=n.rdev,J=[n.size>>>0,(X=n.size,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+24>>2]=J[0],D[t+28>>2]=J[1],D[t+32>>2]=4096,D[t+36>>2]=n.blocks;var o=n.atime.getTime(),i=n.mtime.getTime(),a=n.ctime.getTime();return J=[Math.floor(o/1e3)>>>0,(X=Math.floor(o/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+40>>2]=J[0],D[t+44>>2]=J[1],x[t+48>>2]=o%1e3*1e3,J=[Math.floor(i/1e3)>>>0,(X=Math.floor(i/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+56>>2]=J[0],D[t+60>>2]=J[1],x[t+64>>2]=i%1e3*1e3,J=[Math.floor(a/1e3)>>>0,(X=Math.floor(a/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+72>>2]=J[0],D[t+76>>2]=J[1],x[t+80>>2]=a%1e3*1e3,J=[n.ino>>>0,(X=n.ino,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+88>>2]=J[0],D[t+92>>2]=J[1],0},doMsync:function(e,r,t,n,o){if(!Ce.isFile(r.node.mode))throw new Ce.ErrnoError(43);if(2&n)return 0;var i=F.slice(e,e+t);Ce.msync(r,i,o,t,n)},getStreamFromFD:function(e){return Ce.getStreamChecked(e)},varargs:void 0,getStr:function(e){return De(e)}},Ie=function(e,r){return L(e==e>>>0||e==(0|e)),L(r===(0|r)),r+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*r:NaN},Le=[0,31,60,91,121,152,182,213,244,274,305,335],Ne=[0,31,59,90,120,151,181,212,243,273,304,334],Re=function(e){var r;return((r=e.getFullYear())%4!=0||r%100==0&&r%400!=0?Ne:Le)[e.getMonth()]+e.getDate()-1},Ue=function(e,r,t){return L("number"==typeof t,"stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),be(e,F,r,t)};Se=function(){return performance.now()};var Be,je,$e=function(e){var r=k.buffer,t=(e-r.byteLength+65535)/65536;try{return k.grow(t),N(),1}catch(t){M("growMemory: Attempted to grow heap from "+r.byteLength+" bytes to "+e+" bytes, but got error: "+t)}},We={},He=function(){if(!He.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==("undefined"==typeof navigator?"undefined":u(navigator))&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:_||"./this.program"};for(var r in We)void 0===We[r]?delete e[r]:e[r]=We[r];var t=[];for(var r in e)t.push(r+"="+e[r]);He.strings=t}return He.strings},ze=function(e){return sr(e)},Ve=function(e,r,t,n,o){var i={string:function(e){var r=0;return null!=e&&0!==e&&(r=function(e){var r=we(e)+1,t=ze(r);return Ue(e,t,r),t}(e)),r},array:function(e){var r,t,n=ze(e.length);return t=n,L((r=e).length>=0,"writeArrayToMemory array must have a length (should be an array or typed array)"),P.set(r,t),n}},a=function(e){var r=d["_"+e];return L(r,"Cannot call unknown function "+e+", make sure it is exported"),r}(e),s=[],u=0;if(L("array"!==r,'Return type should not be "array".'),n)for(var c=0;c>7)},Ye=function(e,r){var t;if(L(!r.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled"),"function"==typeof WebAssembly.Function)return new WebAssembly.Function(function(e){L(!e.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled");for(var r={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},t={parameters:[],results:"v"==e[0]?[]:[r[e[0]]]},n=1;n=Qe.length&&(Qe.length=e+1),Qe[e]=r=Be.get(e)),L(Be.get(e)==r,"JavaScript-side Wasm function table mirror is out of date!"),r},Ke=function(e){return je||(je=new WeakMap,function(e,r){if(je)for(var t=e;t>1]=2,0}return-28}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_openat:function(e,r,t,n){xe.varargs=n;try{r=xe.getStr(r),r=xe.calculateAt(e,r);var o=n?fe():0;return Ce.open(r,t,o).fd}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return-e.errno}},_abort_js:function(){q("native code called abort()")},_emscripten_get_now_is_monotonic:function(){return 1},_emscripten_memcpy_js:function(e,r,t){return F.copyWithin(e,r,r+t)},_gmtime_js:function(e,r,t){var n=Ie(e,r),o=new Date(1e3*n);D[t>>2]=o.getUTCSeconds(),D[t+4>>2]=o.getUTCMinutes(),D[t+8>>2]=o.getUTCHours(),D[t+12>>2]=o.getUTCDate(),D[t+16>>2]=o.getUTCMonth(),D[t+20>>2]=o.getUTCFullYear()-1900,D[t+24>>2]=o.getUTCDay();var i=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),a=(o.getTime()-i)/864e5|0;D[t+28>>2]=a},_localtime_js:function(e,r,t){var n=Ie(e,r),o=new Date(1e3*n);D[t>>2]=o.getSeconds(),D[t+4>>2]=o.getMinutes(),D[t+8>>2]=o.getHours(),D[t+12>>2]=o.getDate(),D[t+16>>2]=o.getMonth(),D[t+20>>2]=o.getFullYear()-1900,D[t+24>>2]=o.getDay();var i=0|Re(o);D[t+28>>2]=i,D[t+36>>2]=-60*o.getTimezoneOffset();var a=new Date(o.getFullYear(),0,1),s=new Date(o.getFullYear(),6,1).getTimezoneOffset(),u=a.getTimezoneOffset(),c=0|(s!=u&&o.getTimezoneOffset()==Math.min(u,s));D[t+32>>2]=c},_mktime_js:function(e){var r,t=function(){var r=new Date(D[e+20>>2]+1900,D[e+16>>2],D[e+12>>2],D[e+8>>2],D[e+4>>2],D[e>>2],0),t=D[e+32>>2],n=r.getTimezoneOffset(),o=new Date(r.getFullYear(),0,1),i=new Date(r.getFullYear(),6,1).getTimezoneOffset(),a=o.getTimezoneOffset(),s=Math.min(a,i);if(t<0)D[e+32>>2]=Number(i!=a&&s==n);else if(t>0!=(s==n)){var u=Math.max(a,i),c=t>0?s:u;r.setTime(r.getTime()+6e4*(c-n))}D[e+24>>2]=r.getDay();var l=0|Re(r);D[e+28>>2]=l,D[e>>2]=r.getSeconds(),D[e+4>>2]=r.getMinutes(),D[e+8>>2]=r.getHours(),D[e+12>>2]=r.getDate(),D[e+16>>2]=r.getMonth(),D[e+20>>2]=r.getYear();var d=r.getTime();return isNaN(d)?-1:d/1e3}();return X=t,r=+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0,nr(r),t>>>0},_tzset_js:function(e,r,t,n){var o=(new Date).getFullYear(),i=new Date(o,0,1),a=new Date(o,6,1),s=i.getTimezoneOffset(),u=a.getTimezoneOffset(),c=Math.max(s,u);x[e>>2]=60*c,D[r>>2]=Number(s!=u);var l=function(e){return e.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1]},d=l(i),f=l(a);L(d),L(f),L(we(d)<=16,"timezone name truncated to fit in TZNAME_MAX ("+d+")"),L(we(f)<=16,"timezone name truncated to fit in TZNAME_MAX ("+f+")"),u>>=0)>r);var t=2147483648;if(e>t)return M("Cannot enlarge memory, requested "+e+" bytes, but the limit is "+t+" bytes!"),!1;for(var n,o,i=1;i<=4;i*=2){var a=r*(1+.2/i);a=Math.min(a,e+100663296);var s=Math.min(t,(n=Math.max(e,a))+((o=65536)-n%o)%o);if($e(s))return!0}return M("Failed to grow the heap from "+r+" bytes to "+s+" bytes, not enough memory!"),!1},environ_get:function(e,r){var t=0;return He().forEach((function(n,o){var i=r+t;x[e+4*o>>2]=i,function(e,r){for(var t=0;t>2]=t.length;var n=0;return t.forEach((function(e){return n+=e.length+1})),x[r>>2]=n,0},fd_close:function(e){try{var r=xe.getStreamFromFD(e);return Ce.close(r),0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_fdstat_get:function(e,r){try{var t=xe.getStreamFromFD(e),n=t.tty?2:Ce.isDir(t.mode)?3:Ce.isLink(t.mode)?7:4;return P[r]=n,C[r+2>>1]=0,J=[0,(X=0,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[r+8>>2]=J[0],D[r+12>>2]=J[1],J=[0,(X=0,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[r+16>>2]=J[0],D[r+20>>2]=J[1],0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_read:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,i=0;i>2],s=x[r+4>>2];r+=8;var u=Ce.read(e,P,a,s,n);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_seek:function(e,r,t,n,o){var i=Ie(r,t);try{if(isNaN(i))return 61;var a=xe.getStreamFromFD(e);return Ce.llseek(a,i,n),J=[a.position>>>0,(X=a.position,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[o>>2]=J[0],D[o+4>>2]=J[1],a.getdents&&0===i&&0===n&&(a.getdents=null),0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_write:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,i=0;i>2],s=x[r+4>>2];r+=8;var u=Ce.write(e,P,a,s,n);if(u<0)return-1;o+=u}return o}(xe.getStreamFromFD(e),r,t);return x[n>>2]=o,0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}}},er=function(){var e={env:Ze,wasi_snapshot_preview1:Ze};function r(e,r){var t;return er=e.exports,L(k=er.memory,"memory not found in wasm exports"),N(),L(Be=er.__indirect_function_table,"table not found in wasm exports"),t=er.__wasm_call_ctors,B.unshift(t),Q("wasm-instantiate"),er}Y("wasm-instantiate");var t,n,o,a,s=d;if(d.instantiateWasm)try{return d.instantiateWasm(e,r)}catch(e){M("Module.instantiateWasm callback failed with error: "+e),i(e)}return K||(K=te()),(t=T,n=K,o=e,a=function(e){L(d===s,"the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"),s=null,r(e.instance)},t||"function"!=typeof WebAssembly.instantiateStreaming||Z(n)||"function"!=typeof fetch?oe(n,o,a):fetch(n,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,o).then(a,(function(e){return M("wasm streaming compile failed: "+e),M("falling back to ArrayBuffer instantiation"),oe(n,o,a)}))}))).catch(i),{}}();d._malloc=re("malloc",1),d._free=re("free",1),d._registerWasmPlayer=re("registerWasmPlayer",0),d._setCodecType=re("setCodecType",4),d._exitWasmPlayer=re("exitWasmPlayer",1),d._initDecoder=re("initDecoder",1),d._decodeCodecContext=re("decodeCodecContext",5),d._destroy=re("destroy",1),d._demuxTsStream=re("demuxTsStream",3),d._getPacket=re("getPacket",0),d._getVLCLen=re("getVLCLen",0),d._getVLC=re("getVLC",0),d._getVPSLen=re("getVPSLen",0),d._getVPS=re("getVPS",0),d._getSPSLen=re("getSPSLen",0),d._getSPS=re("getSPS",0),d._getPPSLen=re("getPPSLen",0),d._getPPS=re("getPPS",0),d._getSEILen=re("getSEILen",0),d._getSEI=re("getSEI",0);var rr,tr=re("fflush",1),nr=re("_emscripten_tempret_set",1),or=function(){return(or=er.emscripten_stack_init)()},ir=function(){return(ir=er.emscripten_stack_get_end)()},ar=function(e){return(ar=er._emscripten_stack_restore)(e)},sr=function(e){return(sr=er._emscripten_stack_alloc)(e)},ur=function(){return(ur=er.emscripten_stack_get_current)()};function cr(){var e;or(),L(!(3&(e=ir()))),0==e&&(e+=4),x[e>>2]=34821223,x[e+4>>2]=2310721022,x[0]=1668509029}function lr(){function e(){rr||(rr=!0,d.calledRun=!0,I||(L(!$),$=!0,R(),d.noFSInit||Ce.init.initialized||Ce.init(),Ce.ignorePermissions=!1,ce(B),n(d),d.onRuntimeInitialized&&d.onRuntimeInitialized(),L(!d._main,'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'),function(){if(R(),d.postRun)for("function"==typeof d.postRun&&(d.postRun=[d.postRun]);d.postRun.length;)e=d.postRun.shift(),j.unshift(e);var e;ce(j)}()))}W>0||(cr(),function(){if(d.preRun)for("function"==typeof d.preRun&&(d.preRun=[d.preRun]);d.preRun.length;)e=d.preRun.shift(),U.unshift(e);var e;ce(U)}(),W>0||(d.setStatus?(d.setStatus("Running..."),setTimeout((function(){setTimeout((function(){d.setStatus("")}),1),e()}),1)):e(),R()))}if(d.dynCall_jiji=re("dynCall_jiji",5),d.dynCall_iiiiij=re("dynCall_iiiiij",7),d.dynCall_jiiij=re("dynCall_jiiij",6),d._ff_h264_cabac_tables=113148,d.run=lr,d.ccall=Ve,d.cwrap=function(e,r,t,n){return function(){for(var n=arguments.length,o=new Array(n),i=0;i0;)d.preInit.pop()();lr(),r=p;for(var dr,fr=l(Object.keys(d));!(dr=fr()).done;)t();return r});"object"===u(r)&&"object"===u(e)&&(e.exports=p)}(t,t.exports);var n,o,i,a,s=r(t.exports),u="wasmLoading",c="wasmLoaded",l="wasmFailed",d="registerWasmPlayer",f="videoCallback",p="decodeCodecContext",m="destroy",h="demuxTsStream",g="demuxCoreReceive",v="readPacket",E="readPacketEnd",y="mediaInfo",w=function(e,r){return{cmd:e,data:r}},b=(n="undefined"!=typeof self?self:window,o={navigator:void 0!==n.navigator?n.navigator:{userAgent:""},infoMap:{engine:["WebKit","Trident","Gecko","Presto"],browser:["Safari","Chrome","Edge","IE","Firefox","Firefox Focus","Chromium","Opera","Vivaldi","Yandex","Arora","Lunascape","QupZilla","Coc Coc","Kindle","Iceweasel","Konqueror","Iceape","SeaMonkey","Epiphany","360","360SE","360EE","UC","QQBrowser","QQ","Baidu","Maxthon","Sogou","LBBROWSER","2345Explorer","TheWorld","XiaoMi","Quark","Qiyu","Wechat","Taobao","Alipay","Weibo","Douban","Suning","iQiYi"],os:["Windows","Linux","Mac OS","Android","Ubuntu","FreeBSD","Debian","iOS","Windows Phone","BlackBerry","MeeGo","Symbian","Chrome OS","WebOS"],device:["Mobile","Tablet","iPad"]}},i={getMatchMap:function(e){return{Trident:e.indexOf("Trident")>-1||e.indexOf("NET CLR")>-1,Presto:e.indexOf("Presto")>-1,WebKit:e.indexOf("AppleWebKit")>-1,Gecko:e.indexOf("Gecko/")>-1,Safari:e.indexOf("Safari")>-1,Chrome:e.indexOf("Chrome")>-1||e.indexOf("CriOS")>-1,IE:e.indexOf("MSIE")>-1||e.indexOf("Trident")>-1,Edge:e.indexOf("Edge")>-1,Firefox:e.indexOf("Firefox")>-1||e.indexOf("FxiOS")>-1,"Firefox Focus":e.indexOf("Focus")>-1,Chromium:e.indexOf("Chromium")>-1,Opera:e.indexOf("Opera")>-1||e.indexOf("OPR")>-1,Vivaldi:e.indexOf("Vivaldi")>-1,Yandex:e.indexOf("YaBrowser")>-1,Arora:e.indexOf("Arora")>-1,Lunascape:e.indexOf("Lunascape")>-1,QupZilla:e.indexOf("QupZilla")>-1,"Coc Coc":e.indexOf("coc_coc_browser")>-1,Kindle:e.indexOf("Kindle")>-1||e.indexOf("Silk/")>-1,Iceweasel:e.indexOf("Iceweasel")>-1,Konqueror:e.indexOf("Konqueror")>-1,Iceape:e.indexOf("Iceape")>-1,SeaMonkey:e.indexOf("SeaMonkey")>-1,Epiphany:e.indexOf("Epiphany")>-1,360:e.indexOf("QihooBrowser")>-1||e.indexOf("QHBrowser")>-1,"360EE":e.indexOf("360EE")>-1,"360SE":e.indexOf("360SE")>-1,UC:e.indexOf("UC")>-1||e.indexOf(" UBrowser")>-1,QQBrowser:e.indexOf("QQBrowser")>-1,QQ:e.indexOf("QQ/")>-1,Baidu:e.indexOf("Baidu")>-1||e.indexOf("BIDUBrowser")>-1,Maxthon:e.indexOf("Maxthon")>-1,Sogou:e.indexOf("MetaSr")>-1||e.indexOf("Sogou")>-1,LBBROWSER:e.indexOf("LBBROWSER")>-1,"2345Explorer":e.indexOf("2345Explorer")>-1,TheWorld:e.indexOf("TheWorld")>-1,XiaoMi:e.indexOf("MiuiBrowser")>-1,Quark:e.indexOf("Quark")>-1,Qiyu:e.indexOf("Qiyu")>-1,Wechat:e.indexOf("MicroMessenger")>-1,Taobao:e.indexOf("AliApp(TB")>-1,Alipay:e.indexOf("AliApp(AP")>-1,Weibo:e.indexOf("Weibo")>-1,Douban:e.indexOf("com.douban.frodo")>-1,Suning:e.indexOf("SNEBUY-APP")>-1,iQiYi:e.indexOf("IqiyiApp")>-1,Windows:e.indexOf("Windows")>-1,Linux:e.indexOf("Linux")>-1||e.indexOf("X11")>-1,"Mac OS":e.indexOf("Macintosh")>-1,Android:e.indexOf("Android")>-1||e.indexOf("Adr")>-1,Ubuntu:e.indexOf("Ubuntu")>-1,FreeBSD:e.indexOf("FreeBSD")>-1,Debian:e.indexOf("Debian")>-1,"Windows Phone":e.indexOf("IEMobile")>-1||e.indexOf("Windows Phone")>-1,BlackBerry:e.indexOf("BlackBerry")>-1||e.indexOf("RIM")>-1,MeeGo:e.indexOf("MeeGo")>-1,Symbian:e.indexOf("Symbian")>-1,iOS:e.indexOf("like Mac OS X")>-1,"Chrome OS":e.indexOf("CrOS")>-1,WebOS:e.indexOf("hpwOS")>-1,Mobile:e.indexOf("Mobi")>-1||e.indexOf("iPh")>-1||e.indexOf("480")>-1,Tablet:e.indexOf("Tablet")>-1||e.indexOf("Nexus 7")>-1,iPad:e.indexOf("iPad")>-1}},matchInfoMap:function(e){var r,t=(null==(r=o.navigator)?void 0:r.userAgent)||"",n=i.getMatchMap(t);for(var a in o.infoMap)for(var s=0;s36&&n.showModalDialog?s=!0:+u>45&&(s=t("type","application/vnd.chromium.remoting-viewer"))}if(a.Baidu&&a.Opera&&(a.Baidu=!1),a.Mobile&&(a.Mobile=!r.includes("iPad")),s&&(t("type","application/gameplugin")||o.navigator&&void 0===o.navigator.connection.saveData?a["360SE"]=!0:a["360EE"]=!0),a.IE||a.Edge)switch(window.screenTop-window.screenY){case 71:case 74:case 99:case 75:case 105:break;case 102:a["360EE"]=!0;break;case 104:a["360SE"]=!0}var c={Safari:function(){return r.replace(/^.*Version\/([\d.]+).*$/,"$1")},Chrome:function(){return r.replace(/^.*Chrome\/([\d.]+).*$/,"$1").replace(/^.*CriOS\/([\d.]+).*$/,"$1")},IE:function(){return r.replace(/^.*MSIE ([\d.]+).*$/,"$1").replace(/^.*rv:([\d.]+).*$/,"$1")},Edge:function(){return r.replace(/^.*Edge\/([\d.]+).*$/,"$1")},Firefox:function(){return r.replace(/^.*Firefox\/([\d.]+).*$/,"$1").replace(/^.*FxiOS\/([\d.]+).*$/,"$1")},"Firefox Focus":function(){return r.replace(/^.*Focus\/([\d.]+).*$/,"$1")},Chromium:function(){return r.replace(/^.*Chromium\/([\d.]+).*$/,"$1")},Opera:function(){return r.replace(/^.*Opera\/([\d.]+).*$/,"$1").replace(/^.*OPR\/([\d.]+).*$/,"$1")},Vivaldi:function(){return r.replace(/^.*Vivaldi\/([\d.]+).*$/,"$1")},Yandex:function(){return r.replace(/^.*YaBrowser\/([\d.]+).*$/,"$1")},Arora:function(){return r.replace(/^.*Arora\/([\d.]+).*$/,"$1")},Lunascape:function(){return r.replace(/^.*Lunascape[\/\s]([\d.]+).*$/,"$1")},QupZilla:function(){return r.replace(/^.*QupZilla[\/\s]([\d.]+).*$/,"$1")},"Coc Coc":function(){return r.replace(/^.*coc_coc_browser\/([\d.]+).*$/,"$1")},Kindle:function(){return r.replace(/^.*Version\/([\d.]+).*$/,"$1")},Iceweasel:function(){return r.replace(/^.*Iceweasel\/([\d.]+).*$/,"$1")},Konqueror:function(){return r.replace(/^.*Konqueror\/([\d.]+).*$/,"$1")},Iceape:function(){return r.replace(/^.*Iceape\/([\d.]+).*$/,"$1")},SeaMonkey:function(){return r.replace(/^.*SeaMonkey\/([\d.]+).*$/,"$1")},Epiphany:function(){return r.replace(/^.*Epiphany\/([\d.]+).*$/,"$1")},360:function(){return r.replace(/^.*QihooBrowser\/([\d.]+).*$/,"$1")},"360SE":function(){return{63:"10.0",55:"9.1",45:"8.1",42:"8.0",31:"7.0",21:"6.3"}[+r.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"360EE":function(){return{69:"11.0",63:"9.5",55:"9.0",50:"8.7",30:"7.5"}[+r.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},Maxthon:function(){return r.replace(/^.*Maxthon\/([\d.]+).*$/,"$1")},QQBrowser:function(){return r.replace(/^.*QQBrowser\/([\d.]+).*$/,"$1")},QQ:function(){return r.replace(/^.*QQ\/([\d.]+).*$/,"$1")},Baidu:function(){return r.replace(/^.*BIDUBrowser[\s\/]([\d.]+).*$/,"$1")},UC:function(){return r.replace(/^.*UC?Browser\/([\d.]+).*$/,"$1")},Sogou:function(){return r.replace(/^.*SE ([\d.X]+).*$/,"$1").replace(/^.*SogouMobileBrowser\/([\d.]+).*$/,"$1")},LBBROWSER:function(){return{57:"6.5",49:"6.0",46:"5.9",42:"5.3",39:"5.2",34:"5.0",29:"4.5",21:"4.0"}[+navigator.userAgent.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"2345Explorer":function(){return r.replace(/^.*2345Explorer\/([\d.]+).*$/,"$1")},TheWorld:function(){return r.replace(/^.*TheWorld ([\d.]+).*$/,"$1")},XiaoMi:function(){return r.replace(/^.*MiuiBrowser\/([\d.]+).*$/,"$1")},Quark:function(){return r.replace(/^.*Quark\/([\d.]+).*$/,"$1")},Qiyu:function(){return r.replace(/^.*Qiyu\/([\d.]+).*$/,"$1")},Wechat:function(){return r.replace(/^.*MicroMessenger\/([\d.]+).*$/,"$1")},Taobao:function(){return r.replace(/^.*AliApp\(TB\/([\d.]+).*$/,"$1")},Alipay:function(){return r.replace(/^.*AliApp\(AP\/([\d.]+).*$/,"$1")},Weibo:function(){return r.replace(/^.*weibo__([\d.]+).*$/,"$1")},Douban:function(){return r.replace(/^.*com.douban.frodo\/([\d.]+).*$/,"$1")},Suning:function(){return r.replace(/^.*SNEBUY-APP([\d.]+).*$/,"$1")},iQiYi:function(){return r.replace(/^.*IqiyiVersion\/([\d.]+).*$/,"$1")}};return e.browserVersion="",c[e.browser]&&(e.browserVersion=c[e.browser](),e.browserVersion==r&&(e.browserVersion="")),"Edge"==e.browser&&(e.engine="EdgeHTML"),"Chrome"==e.browser&&parseInt(e.browserVersion)>27&&(e.engine="Blink"),"Opera"==e.browser&&parseInt(e.browserVersion)>12&&(e.engine="Blink"),"Yandex"==e.browser&&(e.engine="Blink"),e.browser+" (version: "+e.browserVersion+"; kernel: "+e.engine+")"}},a={DeviceInfoObj:function(e){var r,t=function(r){var t;null==(t=e.info)||t.forEach((function(e){e.toLowerCase()===r.toLowerCase()&&(s[r]=a[r])}))};e=e||{domain:""};var a={deviceType:i.getDeviceType(),OS:i.getOS(),OSVersion:i.getOSVersion(),sh:n.screen.height,sw:n.screen.width,lang:i.getLanguage(),netWork:i.getNetwork(),orientation:i.getOrientationStatu(),browserInfo:i.getBrowserInfo(),fingerprint:i.createFingerprint(e.domain),userAgent:null==(r=o.navigator)?void 0:r.userAgent};if(!e.info||0===e.info.length)return a;var s={};for(var u in a)t(u);return s}},{getDeviceInfo:function(e){return a.DeviceInfoObj(e)}}),_=function(){function e(){}return e.add=function(r,t){e.queues.push({url:r,data:t})},e.fire=function(){if(e.queues&&0!==e.queues.length){e.isStop=!1;var r=e.queues[0];r.url&&e.api.report(r.data),e.queues.splice(0,1),e.fire()}else e.isStop=!0},e}();_.isStop=!0,_.queues=[];var S=function(){function e(e){this.url=e}var r=e.prototype;return r.report=function(e){this.checkUrl(this.url)&&this.sendInfo(e)},r.sendInfo=function(e){navigator.sendBeacon?this.sendBeacon(this.url,e):this.sendImage(this.url,e)},r.sendImage=function(e,r){var t=this.changeJSON2Query(r),n=new Image;n.onload=n.onerror=function(){n=null},n.src=e+"?"+t+"&random="+Math.random()},r.sendBeacon=function(e,r){try{navigator.sendBeacon(e,this.formatParamsByURLSearchParams(r))}catch(e){}},r.formatParamsByURLSearchParams=function(e){var r=new URLSearchParams;for(var t in e)"object"==typeof e[t]&&(e[t]=JSON.stringify(e[t])),r.append(t,e[t]);return r},r.changeJSON2Query=function(e){var r="";for(var t in e){""!=r&&(r+="&");var n=e[t];r+=t+"="+encodeURIComponent("object"==typeof n?JSON.stringify(n):n)}return r},r.checkUrl=function(e){return!!e&&/^[hH][tT][tT][pP]([sS]?):\/\//.test(e)},e}();function O(){return O=Object.assign||function(e){for(var r=1;r0&&(r._free(l),l=null),{};var d=r.HEAPU8.subarray(l,l+c);s.sps=new Uint8Array(c),null==(n=s.sps)||n.set(d,0);var f=r.cwrap("getPPSLen","number",[])(),p=r.cwrap("getPPS","number",[])(),m=r.HEAPU8.subarray(p,p+f);s.pps=new Uint8Array(f),null==(o=s.pps)||o.set(m,0);var h=r.cwrap("getSEILen","number",[])(),g=r.cwrap("getSEI","number",[])(),v=r.HEAPU8.subarray(g,g+h);s.sei=new Uint8Array(h),null==(i=s.sei)||i.set(v,0);var E=r.cwrap("getVLCLen","number",[])(),y=r.cwrap("getVLC","number",[])(),w=r.HEAPU8.subarray(y,y+E);if(u.vlc=new Uint8Array(E),null==(a=u.vlc)||a.set(w,0),(null==t?void 0:t.vCodec)===e.DEF_HEVC||(null==t?void 0:t.vCodec)===e.DEF_H265){var b,_=r.cwrap("getVPSLen","number",[])(),S=r.cwrap("getVPS","number",[])(),O=r.HEAPU8.subarray(S,S+_);s.vps=new Uint8Array(_),null==(b=s.vps)||b.set(O,0),r._free(O),O=null}try{r._free(l)}catch(e){k.send("worker",{name:"readPacket",free:"spsPtr"})}l=null;try{r._free(d)}catch(e){k.send("worker",{name:"readPacket",free:"spsSubPtr"})}d=null;try{r._free(m)}catch(e){k.send("worker",{name:"readPacket",free:"ppsSubPtr"})}m=null;try{r._free(v)}catch(e){k.send("worker",{name:"readPacket",free:"seiSubPtr"})}v=null;try{r._free(w)}catch(e){k.send("worker",{name:"readPacket",free:"vlcSubPtr"})}return w=null,{nalu:s,vlc:u}};function F(){return F=Object.assign||function(e){for(var r=1;r0?r:e.DEFAULT_SAMPLERATE,sampleChannel:t>=0?t:e.DEFAULT_CHANNEL}:{sampleRate:0,sampleChannel:0,audioNone:!0})))}),"viiddddiiiii"),t._setCodecType(n,0,o,i),t.cwrap("initDecoder","number",["number"])(n);break;case p:var u=s.data,c=u.nalBuf,l=u.pts,b=u.flushDecoder,_=t._malloc(c.length);t.HEAP8.set(c,_);var S=parseInt(1e3*l+"");t._decodeCodecContext(n,_,c.length,S,b),t._free(_),_=null;break;case h:var O=s.data,T=O.buff;O.tsUrl,function(e,r,t,n){null!=M&&(e._free(M),M=null),M=e._malloc(r.length),e.HEAP8.set(r,M);try{var o=e.cwrap("demuxTsStream","number",["number","number","number"])(M,r.length,t);e._free(M),M=null,o>=0&&postMessage(w(g))}catch(e){k.send("worker",{name:"demuxTsStream",msg:e})}}(t,T,n);break;case v:!function(e,r){for(;;){var t=e.cwrap("getPacket","number",[])(),n=e.HEAPU32[t/4],o=e.HEAPU32[t/4+1],i=e.HEAPF64[t/8+1],a=e.HEAPF64[t/8+1+1],s=e.HEAPU32[t/4+1+1+2+2],u=e.HEAPU32[t/4+1+1+2+2+1],c=e.HEAPU8.subarray(u,u+o),l=null,d=[0,1].includes(n);if(d)try{l=P(e,r)}catch(e){}if(!d||o<=0)break;var f=a>0?a:i;f<0||0===t||(self.postMessage(w(v,{type:n,size:o,ptime:i,dtime:a,keyframe:s,data:Array.from(c),pts:f,layer:l})),c=null,l=null,t=null)}postMessage(w(E))}(t,a);break;case m:null!==o&&t.removeFunction(o),o=null,null!==i&&t.removeFunction(i),i=null,t.cwrap("destroy","number",["number"])(n),self.close()}}})).catch((function(e){self.postMessage(w(l,{data:e}))}))})); diff --git a/examples/base-app/index.html b/examples/base-app/index.html index 8b0e383..502bfc1 100644 --- a/examples/base-app/index.html +++ b/examples/base-app/index.html @@ -1,177 +1,156 @@ - - - + + Title - + - + - +
-
-
-
- - -
-
- - - - -
- - -
-
- - -
-
- - -
- -
+
+
+
+ + +
+
+ + + + +
+ + +
+
+
- - - - \ No newline at end of file + + diff --git a/examples/base-app/index.js b/examples/base-app/index.js deleted file mode 100644 index 902155a..0000000 --- a/examples/base-app/index.js +++ /dev/null @@ -1,42 +0,0 @@ -/* -* -* EzuikitFlv.js v1.0.2 -* Copyright (c) 2024-7-31 Ezviz-OpenBiz -* -* https://github.com/Ezviz-OpenBiz/EZUIKit-flv -* -*/ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).EzuikitFlv=t()}(this,(function(){"use strict";function e(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var n=i.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function t(t,i,n){return(i=e(i))in t?Object.defineProperty(t,i,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[i]=n,t} -/* - * - * @ezuikit/utils-tools v1.0.2 - * Copyright (c) 2024-5-22 Ezviz-OpenBiz - * Released under MIT the License. - * - */function i(e){var t,i;return!!((null==(i=window)||null==(t=i.navigator)?void 0:t.userAgent)||"").match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)}var n={h264:1,h265:2,h266:4,vp8:8,vp9:16,av1:32};function r(e,t){void 0===t&&(t=["h264"]);var i=(t||["h264"]).reduce((function(e,t){return t=t.toLowerCase(),e+(n[t]||0)}),0),r=e.split("?")[0],o=e.split("?")[1];return o=(o||"").split("&").filter((function(e){return!/^vc=\d?/.test(e)})).join("&"),r+"?"+o+(o?"&":"")+"vc="+i} -/*! - * browser-tool v1.2.2 - * Useragent analysis tool. - * https://passer-by.com/browser/ - * - * Copyright (c) 2017-present, HaoLe Zheng - * - * Released under the MIT License - * https://github.com/mumuy/browser - * - * Created on: 2024-01-16 - */function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}var a={name:"Safari",match:function(e){return e.indexOf("Safari")>-1},version:function(e){var t;return(null===(t=e.match(/Version\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},s={name:"Chrome",match:function(e){return e.indexOf("Chrome")>-1||e.indexOf("CriOS")>-1},version:function(e){var t,i;return(null===(t=e.match(/Chrome\/([\d.]+)/))||void 0===t?void 0:t[1])||(null===(i=e.match(/CriOS\/([\d.]+)/))||void 0===i?void 0:i[1])||""}},d={name:"Edge",match:function(e){return e.indexOf("Edge")>-1||e.indexOf("Edg/")>-1||e.indexOf("EdgA")>-1||e.indexOf("EdgiOS")>-1},version:function(e){var t,i,n,r;return(null===(t=e.match(/Edge\/([\d.]+)/))||void 0===t?void 0:t[1])||(null===(i=e.match(/Edg\/([\d.]+)/))||void 0===i?void 0:i[1])||(null===(n=e.match(/EdgA\/([\d.]+)/))||void 0===n?void 0:n[1])||(null===(r=e.match(/EdgiOS\/([\d.]+)/))||void 0===r?void 0:r[1])||""}},l={name:"IE",match:function(e){return e.indexOf("MSIE")>-1||e.indexOf("Trident")>-1},version:function(e){var t,i;return(null===(t=e.match(/MSIE ([\d.]+)/))||void 0===t?void 0:t[1])||(null===(i=e.match(/rv:([\d.]+)/))||void 0===i?void 0:i[1])||""}},c={name:"Firefox",match:function(e){return e.indexOf("Firefox")>-1||e.indexOf("FxiOS")>-1},version:function(e){var t,i;return(null===(t=e.match(/Firefox\/([\d.]+)/))||void 0===t?void 0:t[1])||(null===(i=e.match(/FxiOS\/([\d.]+)/))||void 0===i?void 0:i[1])||""}},h={name:"Firefox Focus",match:function(e){return e.indexOf("Focus")>-1},version:function(e){var t;return(null===(t=e.match(/Focus\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},u={name:"Chromium",match:function(e){return e.indexOf("Chromium")>-1},version:function(e){var t;return(null===(t=e.match(/Chromium\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},A={name:"Opera",match:function(e){return e.indexOf("Opera")>-1||e.indexOf("OPR")>-1},version:function(e){var t,i;return(null===(t=e.match(/Opera\/([\d.]+)/))||void 0===t?void 0:t[1])||(null===(i=e.match(/OPR\/([\d.]+)/))||void 0===i?void 0:i[1])||""}},p={name:"Vivaldi",match:function(e){return e.indexOf("Vivaldi")>-1},version:function(e){var t;return(null===(t=e.match(/Vivaldi\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},_={name:"Yandex",match:function(e){return e.indexOf("YaBrowser")>-1},version:function(e){var t;return(null===(t=e.match(/YaBrowser\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},f={};"undefined"!=typeof globalThis?f=globalThis:"undefined"!=typeof self?f=self:"undefined"!=typeof window?f=window:"undefined"!=typeof global&&(f=global);var m=f,v={name:"Brave",match:function(e){var t;return!(null==m||null===(t=m.navigator)||void 0===t||!t.brave)},version:function(e){var t;return(null===(t=e.match(/Chrome\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},g={name:"Arora",match:function(e){return e.indexOf("Arora")>-1},version:function(e){var t;return(null===(t=e.match(/Arora\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},y={name:"Lunascape",match:function(e){return e.indexOf("Lunascape")>-1},version:function(e){var t;return(null===(t=e.match(/Lunascape[\/\s]([\d.]+)/))||void 0===t?void 0:t[1])||""}},b={name:"QupZilla",match:function(e){return e.indexOf("QupZilla")>-1},version:function(e){var t;return(null===(t=e.match(/QupZilla[\/\s]([\d.]+)/))||void 0===t?void 0:t[1])||""}},E={name:"Coc Coc",match:function(e){return e.indexOf("coc_coc_browser")>-1},version:function(e){var t;return(null===(t=e.match(/coc_coc_browser\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},S={name:"Kindle",match:function(e){return e.indexOf("Kindle")>-1||e.indexOf("Silk/")>-1},version:function(e){var t;return(null===(t=e.match(/Version\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},w={name:"Iceweasel",match:function(e){return e.indexOf("Iceweasel")>-1},version:function(e){var t;return(null===(t=e.match(/Iceweasel\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},T={name:"Konqueror",match:function(e){return e.indexOf("Konqueror")>-1},version:function(e){var t;return(null===(t=e.match(/Konqueror\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},B={name:"Iceape",match:function(e){return e.indexOf("Iceape")>-1},version:function(e){var t;return(null===(t=e.match(/Iceape\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},k={name:"SeaMonkey",match:function(e){return e.indexOf("SeaMonkey")>-1},version:function(e){var t;return(null===(t=e.match(/SeaMonkey\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},C={name:"Epiphany",match:function(e){return e.indexOf("Epiphany")>-1},version:function(e){var t;return(null===(t=e.match(/Epiphany\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},R={name:"Huawei",match:function(e){return e.indexOf("HuaweiBrowser")>-1||e.indexOf("HUAWEI")>-1||e.indexOf("HONOR")>-1||e.indexOf("HBPC/")>-1},version:function(e){var t,i,n;return(null===(t=e.match(/Version\/([\d.]+)/))||void 0===t?void 0:t[1])||(null===(i=e.match(/HuaweiBrowser\/([\d.]+)/))||void 0===i?void 0:i[1])||(null===(n=e.match(/HBPC\/([\d.]+)/))||void 0===n?void 0:n[1])||""}},O={name:"OPPO",match:function(e){return e.indexOf("HeyTapBrowser")>-1||e.indexOf("OPPO")>-1},version:function(e){var t;return(null===(t=e.match(/HeyTapBrowser\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},I={name:"Vivo",match:function(e){return e.indexOf("VivoBrowser")>-1},version:function(e){var t;return(null===(t=e.match(/VivoBrowser\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},x={name:"Xiaomi",match:function(e){return e.indexOf("MiuiBrowser")>-1},version:function(e){var t;return(null===(t=e.match(/MiuiBrowser\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},D={name:"Meizu",match:function(e){return e.indexOf("MZBrowser")>-1},version:function(e){var t;return(null===(t=e.match(/MZBrowser\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},L={name:"Samsung",match:function(e){return e.indexOf("SamsungBrowser")>-1},version:function(e){var t;return(null===(t=e.match(/SamsungBrowser\/([\d.]+)/))||void 0===t?void 0:t[1])||""}};function M(e,t){var i,n=null==m||null===(i=m.navigator)||void 0===i?void 0:i.mimeTypes;for(var r in n)if(n[r][e]&&n[r][e]==t)return n[r];return null}var P={name:"360",match:function(e){var t=!1;if(null!=m&&m.chrome){var i=e.replace(/^.*Chrome\/([\d]+).*$/,"$1");M("type","application/360softmgrplugin")||M("type","application/mozilla-npqihooquicklogin")||i>36&&null!=m&&m.showModalDialog?t=!0:i>45&&!(t=M("type","application/vnd.chromium.remoting-viewer"))&&i>=69&&(t=M("type","application/hwepass2001.installepass2001")||M("type","application/asx"))}return e.indexOf("QihooBrowser")>-1||e.indexOf("QHBrowser")>-1||t},version:function(e){var t;return(null===(t=e.match(/QihooBrowser(HD)?\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},U={name:"360SE",match:function(e){var t,i=!1;return P.match(e)&&(M("type","application/gameplugin")||null!=m&&null!==(t=m.navigator)&&void 0!==t&&null!==(t=t.userAgentData)&&void 0!==t&&t.brands.filter((function(e){return"Not.A/Brand"==e.brand})).length)&&(i=!0),e.indexOf("360SE")>-1||i},version:function(e){return{114:"15.0",108:"14.0",86:"13.0",78:"12.0",69:"11.0",63:"10.0",55:"9.1",45:"8.1",42:"8.0",31:"7.0",21:"6.3"}[parseInt(s.version(e))]||""}},F={name:"360EE",match:function(e){var t=!1;if(M("type","application/cenroll.cenroll.version.1")||M("type","application/hwepass2001.installepass2001"))t=!0;else if(P.match(e)){var i;null!=m&&null!==(i=m.navigator)&&void 0!==i&&null!==(i=i.userAgentData)&&void 0!==i&&i.brands.filter((function(e){return"Not A(Brand"==e.brand})).length&&(t=!0)}return e.indexOf("360EE")>-1||t},version:function(e){return{119:"(X)22.0",108:"14.0",95:"(X)21.0",86:"13.0",78:"12.0",69:"11.0",63:"9.5",55:"9.0",50:"8.7",30:"7.5"}[parseInt(s.version(e))]||""}},V={name:"UC",match:function(e){return e.indexOf("UCBrowser")>-1||e.indexOf(" UBrowser")>-1||e.indexOf("UCWEB")>-1},version:function(e){var t;return(null===(t=e.match(/UC?Browser\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},N={name:"QQBrowser",match:function(e){return e.indexOf("QQBrowser")>-1},version:function(e){var t;return(null===(t=e.match(/QQBrowser\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},G={name:"QQ",match:function(e){return e.indexOf("QQ/")>-1},version:function(e){var t;return(null===(t=e.match(/QQ\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},W={name:"Baidu",match:function(e){return e.indexOf("Baidu")>-1||e.indexOf("BIDUBrowser")>-1||e.indexOf("baidubrowser")>-1||e.indexOf("baiduboxapp")>-1||e.indexOf("BaiduD")>-1},version:function(e){var t,i;return(null===(t=e.match(/BIDUBrowser[\s\/]([\d.]+)/))||void 0===t?void 0:t[1])||(null===(i=e.match(/baiduboxapp\/([\d.]+)/))||void 0===i?void 0:i[1])||""}},j={name:"Maxthon",match:function(e){return e.indexOf("Maxthon")>-1||(null==m?void 0:m.maxthon)},version:function(e){var t;return{109:"7.0",78:"6.0"}[parseInt(s.version(e))]||(null===(t=e.match(/Maxthon\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},Q={name:"Sogou",match:function(e){return e.indexOf("MetaSr")>-1||e.indexOf("Sogou")>-1},version:function(e){var t,i;return{94:"12.0",80:"11.0"}[(null===(t=e.match(/Chrome\/([\d]+)/))||void 0===t?void 0:t[1])||""]||(null===(i=e.match(/SogouMobileBrowser\/([\d.]+)/))||void 0===i?void 0:i[1])||""}},z={name:"Liebao",match:function(e){return e.indexOf("LBBROWSER")>-1||e.indexOf("LieBaoFast")>-1||(null==m?void 0:m.liebao)},version:function(e){var t="";e.indexOf("LieBaoFast")>-1&&(t=e.replace(/LieBaoFast\/([\d.]+)/,"$1"));var i=parseInt(s.version(e));return t||{79:"8.0",57:"6.5",49:"6.0",46:"5.9",42:"5.3",39:"5.2",34:"5.0",29:"4.5",21:"4.0"}[i]||""}},H={name:"2345Explorer",match:function(e){var t,i,n=(null==m?void 0:m.chrome)&&((null==m||null===(t=m.chrome)||void 0===t?void 0:t.adblock2345)||(null==m||null===(i=m.chrome)||void 0===i?void 0:i.common2345));return e.indexOf("2345Explorer")>-1||e.indexOf("Mb2345Browser")>-1||e.indexOf("2345chrome")>-1||n},version:function(e){var t,i;return{69:"10.0",55:"9.9"}[parseInt(s.version(e))]||(null===(t=e.match(/2345Explorer\/([\d.]+)/))||void 0===t?void 0:t[1])||(null===(i=e.match(/Mb2345Browser\/([\d.]+)/))||void 0===i?void 0:i[1])||""}},q={name:"115Browser",match:function(e){return e.indexOf("115Browser")>-1},version:function(e){var t;return(null===(t=e.match(/115Browser\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},X={name:"TheWorld",match:function(e){return e.indexOf("TheWorld")>-1},version:function(e){var t;return(null===(t=e.match(/TheWorld ([\d.]+)/))||void 0===t?void 0:t[1])||""}},$={name:"Quark",match:function(e){return e.indexOf("Quark")>-1},version:function(e){var t;return(null===(t=e.match(/Quark\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},Y={name:"Qiyu",match:function(e){return e.indexOf("Qiyu")>-1},version:function(e){var t;return(null===(t=e.match(/Qiyu\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},Z={name:"Wechat",match:function(e){return e.indexOf("MicroMessenger")>-1},version:function(e){var t;return(null===(t=e.match(/MicroMessenger\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},K={name:"WechatWork",match:function(e){return e.indexOf("wxwork/")>-1},version:function(e){var t;return(null===(t=e.match(/wxwork\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},J={name:"Taobao",match:function(e){return e.indexOf("AliApp(TB")>-1},version:function(e){var t;return(null===(t=e.match(/AliApp\(TB\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},ee={name:"Alipay",match:function(e){return e.indexOf("AliApp(AP")>-1},version:function(e){var t;return(null===(t=e.match(/AliApp\(AP\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},te={name:"Weibo",match:function(e){return e.indexOf("Weibo")>-1},version:function(e){var t;return(null===(t=e.match(/weibo__([\d.]+)/))||void 0===t?void 0:t[1])||""}},ie={name:"Douban",match:function(e){return e.indexOf("com.douban.frodo")>-1},version:function(e){var t;return(null===(t=e.match(/com.douban.frodo\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},ne={name:"Suning",match:function(e){return e.indexOf("SNEBUY-APP")>-1},version:function(e){var t;return(null===(t=e.match(/SNEBUY-APP([\d.]+)/))||void 0===t?void 0:t[1])||""}},re={name:"iQIYI",match:function(e){return e.indexOf("IqiyiApp")>-1},version:function(e){var t;return(null===(t=e.match(/IqiyiVersion\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},oe={name:"DingTalk",match:function(e){return e.indexOf("DingTalk")>-1},version:function(e){var t;return(null===(t=e.match(/DingTalk\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},ae={name:"Douyin",match:function(e){return e.indexOf("aweme")>-1},version:function(e){var t;return(null===(t=e.match(/app_version\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},se={name:"Googlebot",match:function(e){return e.indexOf("Googlebot")>-1},version:function(e){var t;return(null===(t=e.match(/Googlebot\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},de={name:"Baiduspider",match:function(e){return e.indexOf("Baiduspider")>-1},version:function(e){var t;return(null===(t=e.match(/Baiduspider(-render)?\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},le={name:"Sogouspider",match:function(e){return e.indexOf("MSIE")>-1||e.indexOf("Trident")>-1},version:function(e){var t;return(null===(t=e.match(/Sogou (\S+) Spider\/([\d.]+)/i))||void 0===t?void 0:t[1])||""}},ce={name:"Bingbot",match:function(e){return e.indexOf("bingbot")>-1},version:function(e){var t;return(null===(t=e.match(/bingbot\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},he={name:"360Spider",match:function(e){return e.indexOf("360Spider")>-1||e.indexOf("HaosouSpider")>-1},version:function(e){return""}},ue={name:"Bytespider",match:function(e){return e.indexOf("Bytespider")>-1},version:function(e){return""}},Ae={name:"YisouSpider",match:function(e){return e.indexOf("YisouSpider")>-1},version:function(e){var t;return(null===(t=e.match(/YisouSpider\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},pe={name:"YodaoBot",match:function(e){return e.indexOf("YodaoBot")>-1},version:function(e){var t;return(null===(t=e.match(/YodaoBot\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},_e={name:"YandexBot",match:function(e){return e.indexOf("YandexBot")>-1},version:function(e){var t;return(null===(t=e.match(/YandexBot\/([\d.]+)/))||void 0===t?void 0:t[1])||""}};function fe(e,t){var i,n=e.userAgent;e.browser="",e.browserVersion="",[a,s,d,l,c,h,u,A,p,_,v,g,y,b,E,S,w,T,B,k,C,R,O,I,x,D,L,P,F,U,V,N,G,W,j,Q,z,H,q,X,$,Y,Z,K,J,ee,te,ie,ne,re,oe,ae,se,de,le,ce,he,ue,Ae,pe,_e].forEach((function(i){i.match(n)&&(e.browser=i.name,e.browserVersion=i.version(n,t))})),"Chrome"==e.browser&&n.match(/\S+Browser/)&&(e.browser=n.match(/\S+Browser/)[0],e.browserVersion=(null===(i=n.replace(/^.*Browser\/([\d.]+).*$/))||void 0===i?void 0:i[1])||"")}var me={name:"Mobile",match:function(e){return e.indexOf("Mobi")>-1||e.indexOf("iPh")>-1||e.indexOf("480")>-1}},ve={name:"Tablet",match:function(e){var t=(null==m?void 0:m.navigator)||{};return e.indexOf("Tablet")>-1||e.indexOf("Pad")>-1||e.indexOf("Nexus 7")>-1||"MacIntel"===t.platform&&t.maxTouchPoints>1}};function ge(e){e.device="Desktop",[me,ve].forEach((function(t){t.match(e.userAgent)&&(e.device=t.name)}))}var ye={name:"WebKit",match:function(e){return e.indexOf("AppleWebKit")>-1}},be={name:"Trident",match:function(e){return e.indexOf("Trident")>-1||e.indexOf("NET CLR")>-1}},Ee={name:"Gecko",match:function(e){return e.indexOf("Gecko/")>-1}},Se={name:"Presto",match:function(e){return e.indexOf("Presto")>-1}},we={name:"KHTML",match:function(e){return e.indexOf("KHTML/")>-1}};function Te(e){e.engine="",[ye,be,Ee,Se,we].forEach((function(t){t.match(e.userAgent)&&(e.engine=t.name)})),"Edge"==e.browser?e.engine=parseInt(e.browserVersion)>75?"Blink":"EdgeHTML":(s.match(e.userAgent)&&"WebKit"==e.engine&&parseInt(s.version(e.userAgent))>27||"Opera"==e.browser&&parseInt(e.browserVersion)>12||"Yandex"==e.browser)&&(e.engine="Blink")}var Be={name:"Windows",match:function(e){return e.indexOf("Windows")>-1},version:function(e){var t,i=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=(null===(t=e.match(/^Mozilla\/\d.0 \(Windows NT ([\d.]+)[;)].*$/))||void 0===t?void 0:t[1])||"",r={"10.0":"10",6.4:"10 Technical Preview",6.3:"8.1",6.2:"8",6.1:"7","6.0":"Vista",5.2:"XP 64-bit",5.1:"XP",5.01:"2000 SP1","5.0":"2000","4.0":"NT","4.90":"ME"};return i?new Promise((function(e){var t;null!=m&&null!==(t=m.navigator)&&void 0!==t&&t.userAgentData?m.navigator.userAgentData.getHighEntropyValues(["platformVersion"]).then((function(t){var i="";"Windows"===navigator.userAgentData.platform&&(i=parseInt(t.platformVersion.split(".")[0])>=13?"11":"10"),e(i)})):e(r[n]||n)})):r[n]||n}},ke={name:"Linux",match:function(e){return e.indexOf("Linux")>-1||e.indexOf("X11")>-1},version:function(e){return""}},Ce={name:"macOS",match:function(e){return e.indexOf("Macintosh")>-1},version:function(e){var t;return(null===(t=e.match(/Mac OS X -?([\d_]+)/))||void 0===t?void 0:t[1].replace(/_/g,"."))||""}},Re={name:"Android",match:function(e){return e.indexOf("Android")>-1||e.indexOf("Adr")>-1},version:function(e){var t;return(null===(t=e.match(/Android ([\d.]+);/))||void 0===t?void 0:t[1])||""}},Oe={name:"HarmonyOS",match:function(e){return e.indexOf("HarmonyOS")>-1},version:function(e){var t,i=+(null===(t=e.match(/HMSCore (\d+.\d+)/))||void 0===t?void 0:t[1])||0;return i>=6.1?"4.0":i>=6?"3.0":i>=5?"2.0":i>=4?"1.0":""}},Ie={name:"Ubuntu",match:function(e){return e.indexOf("Ubuntu")>-1},version:function(e){return""}},xe={name:"FreeBSD",match:function(e){return e.indexOf("FreeBSD")>-1},version:function(e){return""}},De={name:"Debian",match:function(e){return e.indexOf("Debian")>-1},version:function(e){var t;return(null===(t=e.match(/Debian\/([\d.]+)/))||void 0===t?void 0:t[1])||""}},Le={name:"iOS",match:function(e){return e.indexOf("like Mac OS X")>-1},version:function(e){var t;return(null===(t=e.match(/OS ([\d_]+) like/))||void 0===t?void 0:t[1].replace(/_/g,"."))||""}},Me={name:"Windows Phone",match:function(e){return e.indexOf("IEMobile")>-1||e.indexOf("Windows Phone")>-1},version:function(e){var t;return(null===(t=e.match(/Windows Phone( OS)? ([\d.]+);/))||void 0===t?void 0:t[2])||""}},Pe={name:"BlackBerry",match:function(e){return e.indexOf("BlackBerry")>-1||e.indexOf("RIM")>-1},version:function(e){return""}},Ue={name:"MeeGo",match:function(e){return e.indexOf("MeeGo")>-1},version:function(e){return""}},Fe={name:"Symbian",match:function(e){return e.indexOf("Symbian")>-1},version:function(e){return""}},Ve={name:"Chrome OS",match:function(e){return e.indexOf("CrOS")>-1},version:function(e){var t,i;return(null===(t=e.match(/MSIE ([\d.]+)/))||void 0===t?void 0:t[1])||(null===(i=e.match(/rv:([\d.]+)/))||void 0===i?void 0:i[1])||""}},Ne={name:"WebOS",match:function(e){return e.indexOf("hpwOS")>-1},version:function(e){var t;return(null===(t=e.match(/hpwOS\/([\d.]+);/))||void 0===t?void 0:t[1])||""}};function Ge(e,t){var i,n=e.userAgent;e.system="",e.systemVersion="",[Be,ke,Ce,Re,Oe,Ie,xe,De,Le,Me,Pe,Ue,Fe,Ve,Ne].forEach((function(i){i.match(n)&&(e.system=i.name,e.systemVersion=i.version(n,t))})),e.platform="",n.match(/(Win64|x64|WOW64|x86_64)/i)?e.platform="Win64":n.match(/(Win32|x86|WOW32)/i)?e.platform="Win32":n.match(/aarch64|arm64/)?e.platform="ARM64":n.match(/arm32/)?e.platform="ARM32":null!=m&&null!==(i=m.navigator)&&void 0!==i&&i.platform&&(e.platform=m.navigator.platform),e.architecture="";var r,o=n+"|"+e.platform;o.match(/armv\d+/i)||o.match(/aarch64/)?e.architecture="arm":o.match(/loongarch64/)?e.architecture="loongarch":e.architecture="x86",e.bitness=n.match(/Win64|x64|WOW64|x86_64|aarch64|arm64|loongarch64/i)?64:32,t&&null!=m&&null!==(r=m.navigator)&&void 0!==r&&r.userAgentData&&(e.architecture=navigator.userAgentData.getHighEntropyValues(["architecture"]).then((function(e){return e.architecture})),e.bitness=navigator.userAgentData.getHighEntropyValues(["bitness"]).then((function(e){return+e.bitness})))}function We(e){if(e.gpu="",e.gpuModel="",null!=m&&m.document){var t,i,n=m.document.createElement("canvas").getContext("experimental-webgl"),r=n.getExtension("WEBGL_debug_renderer_info"),o=n.getParameter(r.UNMASKED_RENDERER_WEBGL);e.gpu=(null===(t=o.match(/ANGLE \((.+?),/))||void 0===t?void 0:t[1])||"",e.gpuModel=(null===(i=o.match(/, (.+?) (\(|vs_)/))||void 0===i?void 0:i[1])||""}}function je(e){e.language=function(e,t){var i=(null==m||null===(e=m.navigator)||void 0===e?void 0:e.browserLanguage)||(null==m||null===(t=m.navigator)||void 0===t?void 0:t.language);if("string"!=typeof i)return"Unknown language";var n=i.split("-");return n[1]&&(n[1]=n[1].toUpperCase()),n.join("_")}()}function Qe(e){var t,i,n;e.network=(i="unknown",(n=null==m||null===(t=m.navigator)||void 0===t?void 0:t.connection)&&("2"!=(i=n.type||n.effectiveType)&&"unknown"!=i||(i="wifi")),i)}function ze(e){e.isWebview=e.userAgent.indexOf("; wv)")>-1,e.isRobot=["Googlebot","Baiduspider","Sogouspider","Bingbot","360Spider","Bytespider","YandexBot"].includes(e.browser)}var He=function(e){var t,i=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n={};return n.userAgent=e||(null==m||null===(t=m.navigator)||void 0===t?void 0:t.userAgent)||"",[fe,ge,Te,Ge,We,je,Qe,ze].forEach((function(e){return e(n,i)})),n};function qe(e){var t=He(e);for(var i in t)"object"==o(t[i])&&(t[i]="");return t}qe.getInfo=function(e){var t=He(e,!0),i=Object.keys(t),n=Object.values(t).map((function(e){return"object"==o(e)?e:Promise.resolve(e)}));return Promise.all(n).then((function(e){var t={};return e.forEach((function(e,n){t[i[n]]=e})),t}))};const Xe=0,$e=1,Ye="flv",Ze="m7s",Ke={videoBuffer:200,videoBufferDelay:1e3,scaleMode:1,debug:!1,loadingTimeout:10,heartTimeout:5,timeout:10,loadingTimeoutReplay:!0,heartTimeoutReplay:!0,loadingTimeoutReplayTimes:3,heartTimeoutReplayTimes:3,keepScreenOn:!1,isNotMute:!1,hasAudio:!0,volume:.5,hasVideo:!0,decoder:"decoder.js",staticPath:"",url:"",rotate:0,forceNoOffscreen:!0,protocol:$e,demuxType:Ye,useMSE:!1,autoWasm:!0,wasmDecodeErrorReplay:!0,openWebglAlignment:!1,wasmDecodeAudioSyncVideo:!1,useWebFullScreen:!0,loggerOptions:{level:"INFO"}},Je="init",et="initVideo",tt="render",it="playAudio",nt="initAudio",rt="audioCode",ot="videoCode",at="wasmError",st="Invalid NAL unit size",dt=1,lt=2,ct=8,ht=9,ut="init",At="decode",pt="audioDecode",_t="close",ft="updateConfig",mt={fullscreen:"fullscreen$2",webFullscreen:"webFullscreen",decoderWorkerInit:"decoderWorkerInit",play:"play",playing:"playing",pause:"pause",mute:"mute",load:"load",loading:"loading",videoInfo:"videoInfo",timeUpdate:"timeUpdate",audioInfo:"audioInfo",log:"log",error:"error",kBps:"kBps",timeout:"timeout",delayTimeout:"delayTimeout",loadingTimeout:"loadingTimeout",stats:"stats",performance:"performance",buffer:"buffer",videoFrame:"videoFrame",start:"start",metadata:"metadata",resize:"resize",streamEnd:"streamEnd",streamSuccess:"streamSuccess",streamMessage:"streamMessage",streamError:"streamError",volumechange:"volumechange",destroy:"destroy",mseSourceOpen:"mseSourceOpen",mseSourceClose:"mseSourceClose",mseSourceBufferError:"mseSourceBufferError",mseSourceBufferBusy:"mseSourceBufferBusy",mseSourceBufferFull:"mseSourceBufferFull",videoWaiting:"videoWaiting",videoTimeUpdate:"videoTimeUpdate",videoSyncAudio:"videoSyncAudio",playToRenderTimes:"playToRenderTimes"},vt={load:mt.load,timeUpdate:mt.timeUpdate,videoInfo:mt.videoInfo,audioInfo:mt.audioInfo,error:mt.error,kBps:mt.kBps,log:mt.log,start:mt.start,timeout:mt.timeout,loadingTimeout:mt.loadingTimeout,delayTimeout:mt.delayTimeout,fullscreen:"fullscreen",webFullscreen:mt.webFullscreen,play:mt.play,pause:mt.pause,mute:mt.mute,stats:mt.stats,volumechange:mt.volumechange,performance:mt.performance,playToRenderTimes:mt.playToRenderTimes},gt={playError:"playIsNotPauseOrUrlIsNull",fetchError:"NetworkError",websocketError:"websocketError",webcodecsH265NotSupport:"webcodecsH265NotSupport",webcodecsDecodeError:"webcodecsDecodeError",webcodecsWidthOrHeightChange:"webcodecsWidthOrHeightChange",mediaSourceH265NotSupport:"mediaSourceH265NotSupport",mediaSourceFull:mt.mseSourceBufferFull,mseSourceBufferError:mt.mseSourceBufferError,mediaSourceAppendBufferError:"mediaSourceAppendBufferError",mediaSourceBufferListLarge:"mediaSourceBufferListLarge",mediaSourceAppendBufferEndTimeout:"mediaSourceAppendBufferEndTimeout",wasmDecodeError:"wasmDecodeError",webglAlignmentError:"webglAlignmentError"},yt="notConnect",bt="open",Et="close",St="error",wt={download:"download",base64:"base64",blob:"blob"},Tt={7:"H264(AVC)",12:"H265(HEVC)"},Bt={10:"AAC",7:"ALAW",8:"MULAW"},kt={full:0,auto:1,fullAuto:2},Ct="webcodecs",Rt="webgl",Ot="offscreen",It=1e3,xt="The user aborted a request",Dt="AbortError",Lt="AbortError";function Mt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Pt={exports:{}};!function(e){!function(){var t="undefined"!=typeof window&&void 0!==window.document?window.document:{},i=e.exports,n=function(){for(var e,i=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],n=0,r=i.length,o={};n{Gt(e,i,t[i])})),e.style[t]=i,e}function Wt(){return performance&&"function"==typeof performance.now?performance.now():Date.now()}function jt(e){let t=0,i=Wt();return n=>{t+=n;const r=Wt(),o=r-i;o>=1e3&&(e(t/o*1e3),i=r,t=0)}}function Qt(){return/phone|pad|pod|iphone|ipod|ios|ipad|android|mobile|blackberry|iemobile|mqqbrowser|juc|wosbrowser|webos|symbian|windows phone|opera mini|huaweibrowser/i.test(window.navigator.userAgent.toLowerCase())}function zt(){return Ut.isFullscreen}function Ht(e){return null==e}function qt(e){return!Ht(e)}function Xt(e){const t=e||window.event;return t.target||t.srcElement}(()=>{try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){const e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}})();class $t{constructor(){}on(e,t,i){const n=this.e||(this.e={});return(n[e]||(n[e]=[])).push({fn:t,ctx:i}),this}once(e,t,i){const n=this;function r(...o){n.off(e,r),t.apply(i,o)}return r._=t,this.on(e,r,i)}emit(e,...t){const i=((this.e||(this.e={}))[e]||[]).slice();for(let e=0;e{delete i[e]})),void delete this.e;const n=i[e],r=[];if(n&&t)for(let e=0,i=n.length;e=200&&t.status<=299}function ei(e){try{e.dispatchEvent(new MouseEvent("click"))}catch(t){const i=document.createEvent("MouseEvents");i.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),e.dispatchEvent(i)}}const ti=Zt.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent);var ii="object"!=typeof window||window!==Zt?function(){}:"download"in HTMLAnchorElement.prototype&&!ti?function(e,t,i){const n=Zt.URL||Zt.webkitURL,r=document.createElementNS("http://www.w3.org/1999/xhtml","a");t=t||e.name||"download",r.download=t,r.rel="noopener","string"==typeof e?(r.href=e,r.origin!==location.origin?Jt(r.href)?Kt(e,t,i):ei(r,r.target="_blank"):ei(r)):(r.href=n.createObjectURL(e),setTimeout((function(){n.revokeObjectURL(r.href)}),4e4),setTimeout((function(){ei(r)}),0))}:"msSaveOrOpenBlob"in navigator?function(e,t,i){if(t=t||e.name||"download","string"==typeof e)if(Jt(e))Kt(e,t,i);else{const t=document.createElement("a");t.href=e,t.target="_blank",setTimeout((function(){ei(t)}))}else navigator.msSaveOrOpenBlob(function(e,t){return void 0===t?t={autoBom:!1}:"object"!=typeof t&&(t={autoBom:!t}),t.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob([String.fromCharCode(65279),e],{type:e.type}):e}(e,i),t)}:function(e,t,i,n){if((n=n||open("","_blank"))&&(n.document.title=n.document.body.innerText="downloading..."),"string"==typeof e)return Kt(e,t,i);const r="application/octet-stream"===e.type,o=/constructor/i.test(Zt.HTMLElement)||Zt.safari,a=/CriOS\/[\d]+/.test(navigator.userAgent);if((a||r&&o||ti)&&"undefined"!=typeof FileReader){const t=new FileReader;t.onloadend=function(){let e=t.result;e=a?e:e.replace(/^data:[^;]*;/,"data:attachment/file;"),n?n.location.href=e:location=e,n=null},t.readAsDataURL(e)}else{const t=Zt.URL||Zt.webkitURL,i=t.createObjectURL(e);n?n.location=i:location.href=i,n=null,setTimeout((function(){t.revokeObjectURL(i)}),4e4)}};class ni extends Yt{constructor(e){super(),this.player=e;const t=document.createElement("canvas");t.style.position="absolute",t.style.top=0,t.style.left=0,this.$videoElement=t,e.$container.appendChild(this.$videoElement),this.context2D=null,this.contextGl=null,this.contextGlRender=null,this.contextGlDestroy=null,this.bitmaprenderer=null,this.renderType=null,this.videoInfo={width:"",height:"",encType:""},this._initCanvasRender(),this._contextmenuEvent=e=>{e.target===this.$videoElement&&e.preventDefault()},document.addEventListener("contextmenu",this._contextmenuEvent),this.player.debug.log("CanvasVideo","init")}destroy(){super.destroy(),this.contextGl&&(this.contextGl=null),this.context2D&&(this.context2D=null),this.contextGlRender&&(this.contextGlDestroy&&this.contextGlDestroy(),this.contextGlDestroy=null,this.contextGlRender=null),this.bitmaprenderer&&(this.bitmaprenderer=null),this._contextmenuEvent&&(document.removeEventListener("contextmenu",this._contextmenuEvent),this._contextmenuEvent=null),this.renderType=null,this.player.debug.log("CanvasVideoLoader","destroy")}_initContextGl(){this.contextGl=function(e){let t=null;const i=["webgl","experimental-webgl","moz-webgl","webkit-3d"];let n=0;for(;!t&&n{var i=["attribute vec4 vertexPos;","attribute vec4 texturePos;","varying vec2 textureCoord;","void main()","{","gl_Position = vertexPos;","textureCoord = texturePos.xy;","}"].join("\n"),n=["precision highp float;","varying highp vec2 textureCoord;","uniform sampler2D ySampler;","uniform sampler2D uSampler;","uniform sampler2D vSampler;","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",");","void main(void) {","highp float y = texture2D(ySampler, textureCoord).r;","highp float u = texture2D(uSampler, textureCoord).r;","highp float v = texture2D(vSampler, textureCoord).r;","gl_FragColor = vec4(y, u, v, 1) * YUV2RGB;","}"].join("\n");t&&e.pixelStorei(e.UNPACK_ALIGNMENT,1);var r=e.createShader(e.VERTEX_SHADER);e.shaderSource(r,i),e.compileShader(r),e.getShaderParameter(r,e.COMPILE_STATUS);var o=e.createShader(e.FRAGMENT_SHADER);e.shaderSource(o,n),e.compileShader(o),e.getShaderParameter(o,e.COMPILE_STATUS);var a=e.createProgram();e.attachShader(a,r),e.attachShader(a,o),e.linkProgram(a),e.getProgramParameter(a,e.LINK_STATUS),e.useProgram(a);var s=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,s),e.bufferData(e.ARRAY_BUFFER,new Float32Array([1,1,-1,1,1,-1,-1,-1]),e.STATIC_DRAW);var d=e.getAttribLocation(a,"vertexPos");e.enableVertexAttribArray(d),e.vertexAttribPointer(d,2,e.FLOAT,!1,0,0);var l=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,new Float32Array([1,0,0,0,1,1,0,1]),e.STATIC_DRAW);var c=e.getAttribLocation(a,"texturePos");function h(t,i){var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),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.bindTexture(e.TEXTURE_2D,null),e.uniform1i(e.getUniformLocation(a,t),i),n}e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0);var u=h("ySampler",0),A=h("uSampler",1),p=h("vSampler",2);return{render:function(t,i,n,r,o){e.viewport(0,0,t,i),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,u),e.texImage2D(e.TEXTURE_2D,0,e.LUMINANCE,t,i,0,e.LUMINANCE,e.UNSIGNED_BYTE,n),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,A),e.texImage2D(e.TEXTURE_2D,0,e.LUMINANCE,t/2,i/2,0,e.LUMINANCE,e.UNSIGNED_BYTE,r),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,p),e.texImage2D(e.TEXTURE_2D,0,e.LUMINANCE,t/2,i/2,0,e.LUMINANCE,e.UNSIGNED_BYTE,o),e.drawArrays(e.TRIANGLE_STRIP,0,4)},destroy:function(){try{e.deleteProgram(a),e.deleteBuffer(s),e.deleteBuffer(l),e.deleteTexture(u),e.deleteTexture(A),e.deleteTexture(p)}catch(e){}}}})(this.contextGl,this.player._opt.openWebglAlignment);this.contextGlRender=e.render,this.contextGlDestroy=e.destroy}_initContext2D(){this.context2D=this.$videoElement.getContext("2d")}_initCanvasRender(){this._supportOffscreen()?(this.renderType=Ot,this._bindOffscreen()):(this.renderType=Rt,this._initContextGl())}_supportOffscreen(){return"function"==typeof this.$videoElement.transferControlToOffscreen&&this.player._opt.useOffscreen}_bindOffscreen(){this.bitmaprenderer=this.$videoElement.getContext("bitmaprenderer")}initCanvasViewSize(){this.$videoElement.width=this.videoInfo.width,this.$videoElement.height=this.videoInfo.height,this.resize()}render(e){switch(this.player.videoTimestamp=e.ts,this.renderType){case Ot:this.bitmaprenderer.transferFromImageBitmap(e.buffer);break;case Rt:this.contextGlRender(this.$videoElement.width,this.$videoElement.height,e.output[0],e.output[1],e.output[2]);break;case Ct:this.context2D.drawImage(e.videoFrame,0,0,this.$videoElement.width,this.$videoElement.height),(t=e.videoFrame).close?t.close():t.destroy&&t.destroy()}var t}screenshot(e,t,i,n){e=e||Nt(),n=n||wt.download;const r={png:"image/png",jpeg:"image/jpeg",webp:"image/webp"};let o=.92;!r[t]&&wt[t]&&(n=t,t="png",i=void 0),"string"==typeof i&&(n=i,i=void 0),void 0!==i&&(o=Number(i));const a=this.$videoElement.toDataURL(r[t]||r.png,o);if(n===wt.base64)return a;{const t=Vt(a);if(n===wt.blob)return t;n===wt.download&&ii(t,e)}}clearView(){switch(this.renderType){case Ot:(function(e,t){const i=document.createElement("canvas");return i.width=e,i.height=t,window.createImageBitmap(i,0,0,e,t)})(this.$videoElement.width,this.$videoElement.height).then((e=>{this.bitmaprenderer.transferFromImageBitmap(e)}));break;case Rt:this.contextGl.clear(this.contextGl.COLOR_BUFFER_BIT);break;case Ct:this.context2D.clearRect(0,0,this.$videoElement.width,this.$videoElement.height)}}resize(){this.player.debug.log("canvasVideo","resize");const e=this.player._opt,t=this.player.width,i=this.player.height;let n=this.$videoElement.width,r=this.$videoElement.height;const o=e.rotate,a=(t-n)/2,s=(i-r)/2;270!==o&&90!==o||(n=this.$videoElement.height,r=this.$videoElement.width);const d=t/n,l=i/r;let c=d>l?l:d;e.scaleMode!==kt.auto&&d!==l&&(c=d+","+l),e.scaleMode===kt.fullAuto&&(c=d>l?d:l);let h="scale("+c+")";o&&(h+=" rotate("+o+"deg)"),this.$videoElement.style.transform=h,this.$videoElement.style.left=a+"px",this.$videoElement.style.top=s+"px"}}class ri extends $t{constructor(e){super(),this.bufferList=[],this.player=e,this.scriptNode=null,this.hasInitScriptNode=!1,this.audioContextChannel=null,this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.gainNode=this.audioContext.createGain();const t=this.audioContext.createBufferSource();t.buffer=this.audioContext.createBuffer(1,1,22050),t.connect(this.audioContext.destination),t.noteOn?t.noteOn(0):t.start(0),this.audioBufferSourceNode=t,this.mediaStreamAudioDestinationNode=this.audioContext.createMediaStreamDestination(),this.audioEnabled(!0),this.gainNode.gain.value=0,this.playing=!1,this.audioSyncVideoOption={diff:null},this.audioInfo={encType:"",channels:"",sampleRate:""},this.init=!1,this.hasAudio=!1,this.on(mt.videoSyncAudio,(e=>{this.audioSyncVideoOption=e})),this.player.debug.log("AudioContext","init")}resetInit(){this.init=!1,this.audioInfo={encType:"",channels:"",sampleRate:""}}destroy(){this.closeAudio(),this.resetInit(),this.audioContext.close(),this.audioContext=null,this.gainNode=null,this.hasAudio=!1,this.playing=!1,this.scriptNode&&(this.scriptNode.onaudioprocess=Ft,this.scriptNode=null),this.audioBufferSourceNode=null,this.mediaStreamAudioDestinationNode=null,this.hasInitScriptNode=!1,this.audioSyncVideoOption={diff:null},this.off(),this.player.debug.log("AudioContext","destroy")}updateAudioInfo(e){e.encTypeCode&&(this.audioInfo.encType=Bt[e.encTypeCode]),e.channels&&(this.audioInfo.channels=e.channels),e.sampleRate&&(this.audioInfo.sampleRate=e.sampleRate),this.audioInfo.sampleRate&&this.audioInfo.channels&&this.audioInfo.encType&&!this.init&&(this.player.emit(mt.audioInfo,this.audioInfo),this.init=!0)}get isPlaying(){return this.playing}get isMute(){return 0===this.gainNode.gain.value}get volume(){return this.gainNode.gain.value}get bufferSize(){return this.bufferList.length}initScriptNode(){if(this.playing=!0,this.hasInitScriptNode)return;const e=this.audioInfo.channels,t=this.audioContext.createScriptProcessor(1024,0,e);t.onaudioprocess=t=>{const i=t.outputBuffer;if(this.bufferList.length&&this.playing){if(!this.player._opt.useWCS&&!this.player._opt.useMSE&&this.player._opt.wasmDecodeAudioSyncVideo){if(this.audioSyncVideoOption.diff>It)return void this.player.debug.warn("AudioContext",`audioSyncVideoOption more than diff :${this.audioSyncVideoOption.diff}, waiting`);if(this.audioSyncVideoOption.diff<-1e3){this.player.debug.warn("AudioContext",`audioSyncVideoOption less than diff :${this.audioSyncVideoOption.diff}, dropping`);let e=this.bufferList.shift();for(;e.ts-this.player.videoTimestamp<-1e3&&this.bufferList.length>0;)e=this.bufferList.shift();if(0===this.bufferList.length)return}}if(0===this.bufferList.length)return;const t=this.bufferList.shift();t&&t.ts&&(this.player.audioTimestamp=t.ts);for(let n=0;n20&&(this.player.debug.warn("AudioContext",`bufferList is large: ${this.bufferList.length}`),this.bufferList.length>50&&this.bufferList.shift()))}pause(){this.audioSyncVideoOption={diff:null},this.playing=!1,this.clear()}resume(){this.playing=!0}}class oi{constructor(e){return new(oi.getLoaderFactory())(e)}static getLoaderFactory(){return ri}}class ai extends $t{constructor(e){super(),this.player=e,this.playing=!1,this.abortController=new AbortController,this.streamRate=jt((e=>{})),e.debug.log("FetchStream","init")}destroy(){this.abort(),this.off(),this.streamRate=null,this.player.debug.log("FetchStream","destroy")}fetchStream(e,t={}){const{demux:i}=this.player;this.player._times.streamStart=Nt();const n=Object.assign({signal:this.abortController.signal},{headers:t.headers||{}});fetch(e,n).then((e=>{const t=e.body.getReader();this.emit(mt.streamSuccess);const n=()=>{t.read().then((({done:e,value:t})=>{e?i.close():(this.streamRate&&this.streamRate(t.byteLength),i.dispatch(t),n())})).catch((e=>{i.close();const n=e.toString();-1===n.indexOf(xt)&&-1===n.indexOf(Dt)&&e.name!==Lt&&(this.abort(),t.cancel(),this.emit(gt.fetchError,e),this.player.emit(mt.error,gt.fetchError))}))};n()})).catch((e=>{"AbortError"!==e.name&&(i.close(),this.abort(),this.emit(gt.fetchError,e),this.player.emit(mt.error,gt.fetchError))}))}abort(){this.abortController&&(this.abortController.abort(),this.abortController=null)}}class si extends $t{constructor(e){super(),this.player=e,this.socket=null,this.socketStatus=yt,this.wsUrl=null,this.streamRate=jt((e=>{})),e.debug.log("WebsocketLoader","init")}destroy(){this.socket&&(this.socket.close(1e3,"Client disconnecting"),this.socket=null),this.socketStatus=yt,this.streamRate=null,this.wsUrl=null,this.off(),this.player.debug.log("websocketLoader","destroy")}_createWebSocket(){const e=this.player,{debug:t,events:{proxy:i},demux:n}=e;this.socket=new WebSocket(this.wsUrl),this.socket.binaryType="arraybuffer",i(this.socket,"open",(()=>{this.emit(mt.streamSuccess),t.log("websocketLoader","socket open"),this.socketStatus=bt})),i(this.socket,"message",(e=>{this.streamRate&&this.streamRate(e.data.byteLength),this._handleMessage(e.data)})),i(this.socket,"close",(()=>{t.log("websocketLoader","socket close"),this.emit(mt.streamEnd),this.socketStatus=Et})),i(this.socket,"error",(e=>{t.log("websocketLoader","socket error"),this.emit(gt.websocketError,e),this.player.emit(mt.error,gt.websocketError),this.socketStatus=St,n.close(),t.log("websocketLoader","socket error:",e)}))}_handleMessage(e){const{demux:t}=this.player;t?t.dispatch(e):this.player.debug.warn("websocketLoader","websocket handle message demux is null")}fetchStream(e,t){this.player._times.streamStart=Nt(),this.wsUrl=e,this._createWebSocket()}}class di{constructor(e){return new(di.getLoaderFactory(e._opt.protocol))(e)}static getLoaderFactory(e){return e===$e?ai:e===Xe?si:void 0}}class li{constructor(e){this.player=e,this.decoderWorker=new Worker((""===e._opt.staticPath?"":function(e,t){void 0===t&&(t="");var i=/^(https?:\/\/|^\/\/)/;return i.test(e)?e:(e=e.replace(/\/+/g,"/"),t=i.test(t||"")?t:window.location.href,new URL(e,t).href)}(e._opt.staticPath))+e._opt.decoder),this._initDecoderWorker(),e.debug.log("decoderWorker","init")}destroy(){this.decoderWorker.postMessage({cmd:_t}),this.decoderWorker.terminate(),this.decoderWorker=null,this.player.debug.log("decoderWorker","destroy")}_initDecoderWorker(){const{debug:e,events:{proxy:t}}=this.player;this.decoderWorker.onmessage=t=>{var i,n,r,o,a,s;const d=t.data;switch(d.cmd){case Je:e.log("decoderWorker","onmessage:",Je),this.player.loaded||this.player.emit(mt.load),this.player.emit(mt.decoderWorkerInit),this._initWork();break;case ot:e.log("decoderWorker","onmessage:",ot,d.code),this.player._times.decodeStart||(this.player._times.decodeStart=Nt()),this.player.video.updateVideoInfo({encTypeCode:d.code});break;case rt:e.log("decoderWorker","onmessage:",rt,d.code),null===(i=this.player)||void 0===i||null===(i=i.audio)||void 0===i||null===(n=i.updateAudioInfo)||void 0===n||n.call(i,{encTypeCode:d.code});break;case et:if(e.log("decoderWorker","onmessage:",et,`width:${d.w},height:${d.h}`),null===(r=this.player)||void 0===r||null===(r=r.video)||void 0===r||null===(o=r.updateVideoInfo)||void 0===o||o.call(r,{width:d.w,height:d.h}),!this.player._opt.openWebglAlignment&&d.w/2%4!=0)return void this.player.emit(gt.webglAlignmentError);this.player.video.initCanvasViewSize();break;case nt:e.log("decoderWorker","onmessage:",nt,`channels:${d.channels},sampleRate:${d.sampleRate}`),this.player.audio&&(this.player.audio.updateAudioInfo(d),this.player.audio.initScriptNode(d));break;case tt:this.player.handleRender(),this.player.video.render(d),this.player.emit(mt.timeUpdate,d.ts),this.player.updateStats({fps:!0,ts:d.ts,buf:d.delay}),this.player._times.videoStart||(this.player._times.videoStart=Nt(),this.player.handlePlayToRenderTimes());break;case it:this.player.playing&&this.player.audio&&this.player.audio.play(d.buffer,d.ts);break;case at:d.message&&-1!==d.message.indexOf(st)&&this.player.emitError(gt.wasmDecodeError);break;default:null===(a=(s=this.player)[d.cmd])||void 0===a||a.call(s,d)}}}_initWork(){var e;const t={debug:this.player._opt.debug,useOffscreen:this.player._opt.useOffscreen,useWCS:this.player._opt.useWCS,videoBuffer:this.player._opt.videoBuffer,videoBufferDelay:this.player._opt.videoBufferDelay,openWebglAlignment:this.player._opt.openWebglAlignment};this.decoderWorker.postMessage({cmd:ut,opt:JSON.stringify(t),sampleRate:(null===(e=this.player)||void 0===e||null===(e=e.audio)||void 0===e||null===(e=e.audioContext)||void 0===e?void 0:e.sampleRate)||0})}decodeVideo(e,t,i){const n={type:lt,ts:Math.max(t,0),isIFrame:i};this.decoderWorker.postMessage({cmd:At,buffer:e,options:n},[e.buffer])}decodeAudio(e,t){this.player._opt.useWCS||this.player._opt.useMSE?this._decodeAudioNoDelay(e,t):this._decodeAudio(e,t)}_decodeAudio(e,t){const i={type:dt,ts:Math.max(t,0)};this.decoderWorker.postMessage({cmd:At,buffer:e,options:i},[e.buffer])}_decodeAudioNoDelay(e,t){this.decoderWorker.postMessage({cmd:pt,buffer:e,ts:Math.max(t,0)},[e.buffer])}updateWorkConfig(e){this.decoderWorker.postMessage({cmd:ft,key:e.key,value:e.value})}}class ci extends $t{constructor(e){super(),this.player=e,this.stopId=null,this.firstTimestamp=null,this.startTimestamp=null,this.delay=-1,this.bufferList=[],this.dropping=!1,this.initInterval()}destroy(){this.stopId&&(clearInterval(this.stopId),this.stopId=null),this.firstTimestamp=null,this.startTimestamp=null,this.delay=-1,this.bufferList=[],this.dropping=!1,this.off(),this.player.debug.log("CommonDemux","destroy")}getDelay(e){if(!e)return-1;if(this.firstTimestamp){if(e){const t=Date.now()-this.startTimestamp,i=e-this.firstTimestamp;this.delay=t>=i?t-i:i-t}}else this.firstTimestamp=e,this.startTimestamp=Date.now(),this.delay=-1;return this.delay}resetDelay(){this.firstTimestamp=null,this.startTimestamp=null,this.delay=-1,this.dropping=!1}initInterval(){this.player.debug.log("common dumex","init Interval");const e=()=>{let e;const t=this.player._opt.videoBuffer,i=this.player._opt.videoBufferDelay;if(this.bufferList.length)if(this.dropping){for(e=this.bufferList.shift(),e.type===dt&&0===e.payload[1]&&this._doDecoderDecode(e);!e.isIFrame&&this.bufferList.length;)e=this.bufferList.shift(),e.type===dt&&0===e.payload[1]&&this._doDecoderDecode(e);e.isIFrame&&this.getDelay(e.ts)<=Math.min(t,200)&&(this.dropping=!1,this._doDecoderDecode(e))}else e=this.bufferList[0],-1===this.getDelay(e.ts)?(this.bufferList.shift(),this._doDecoderDecode(e)):this.delay>t+i?(this.resetDelay(),this.dropping=!0):(e=this.bufferList[0],this.getDelay(e.ts)>t&&(this.bufferList.shift(),this._doDecoderDecode(e)))};e(),this.stopId=setInterval(e,10)}_doDecode(e,t,i,n,r){const o=this.player,a={ts:i,cts:r,type:t,isIFrame:!1};var s,d;if(o._opt.useWCS&&!o._opt.useOffscreen)t===lt&&(a.isIFrame=n),this.pushBuffer(e,a);else if(t===lt)null==o||null===(s=o.decoderWorker)||void 0===s||null===(d=s.decodeVideo)||void 0===d||d.call(s,e,i,n);else if(t===dt){var l,c;if(o._opt.hasAudio)null==o||null===(l=o.decoderWorker)||void 0===l||null===(c=l.decodeAudio)||void 0===c||c.call(l,e,i)}}_doDecoderDecode(e){const t=this.player;var i,n;e.type===dt?t._opt.hasAudio&&(null===(i=t.decoderWorker)||void 0===i||null===(n=i.decodeAudio)||void 0===n||n.call(i,e.payload,e.ts)):e.type}pushBuffer(e,t){t.type===dt?this.bufferList.push({ts:t.ts,payload:e,type:dt}):t.type===lt&&this.bufferList.push({ts:t.ts,cts:t.cts,payload:e,type:lt,isIFrame:t.isIFrame})}close(){}}class hi extends ci{constructor(e){super(e),this.input=this._inputFlv(),this.flvDemux=this.dispatchFlvData(this.input),e.debug.log("FlvDemux","init")}destroy(){super.destroy(),this.input=null,this.flvDemux=null,this.player.debug.log("FlvDemux","destroy")}dispatch(e){this.flvDemux(e)}*_inputFlv(){yield 9;const e=new ArrayBuffer(4),t=new Uint8Array(e),i=new Uint32Array(e),n=this.player;for(;;){t[3]=0;const e=yield 15,r=e[4];t[0]=e[7],t[1]=e[6],t[2]=e[5];const o=i[0];t[0]=e[10],t[1]=e[9],t[2]=e[8];let a=i[0];16777215===a&&(t[3]=e[11],a=i[0]);const s=yield o;switch(r){case ct:n._opt.hasAudio&&(n.updateStats({abps:s.byteLength}),s.byteLength>0&&this._doDecode(s,dt,a));break;case ht:if(n._times.demuxStart||(n._times.demuxStart=Nt()),n._opt.hasVideo){n.updateStats({vbps:s.byteLength});const e=s[0]>>4==1;if(s.byteLength>0){i[0]=s[4],i[1]=s[3],i[2]=s[2],i[3]=0;const t=i[0];this._doDecode(s,lt,a,e,t)}}}}}dispatchFlvData(e){let t=e.next(),i=null;return n=>{let r=new Uint8Array(n);if(i){const e=new Uint8Array(i.length+r.length);e.set(i),e.set(r,i.length),r=e,i=null}for(;r.length>=t.value;){const i=r.slice(t.value);t=e.next(r.slice(0,t.value)),r=i}r.length>0&&(i=r)}}close(){var e,t;null===(e=this.input)||void 0===e||null===(t=e.return)||void 0===t||t.call(e,null)}}class ui extends ci{constructor(e){super(e),e.debug.log("M7sDemux","init")}destroy(){super.destroy(),this.player.debug.log("M7sDemux","destroy"),this.player=null}dispatch(e){const t=this.player,i=new DataView(e),n=i.getUint8(0),r=i.getUint32(1,!1);switch(n){case dt:if(t._opt.hasAudio){const i=new Uint8Array(e,5);t.updateStats({abps:i.byteLength}),i.byteLength>0&&this._doDecode(i,n,r)}break;case lt:if(t._opt.hasVideo)if(t._times.demuxStart||(t._times.demuxStart=Nt()),i.byteLength>5){const o=new Uint8Array(e,5),a=i.getUint8(5)>>4==1;t.updateStats({vbps:o.byteLength}),o.byteLength>0&&this._doDecode(o,n,r,a)}else this.player.debug.warn("M7sDemux","dispatch","dv byteLength is",i.byteLength)}}}class Ai{constructor(e){return new(Ai.getLoaderFactory(e._opt.demuxType))(e)}static getLoaderFactory(e){return e===Ze?ui:e===Ye?hi:void 0}}const pi=()=>"undefined"!=typeof navigator&&parseFloat((""+(/CPU.*OS ([0-9_]{3,4})[0-9_]{0,1}|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent)||[0,""])[1]).replace("undefined","3_2").replace("_",".").replace("_",""))<10&&!window.MSStream,_i=()=>"wakeLock"in navigator;class fi{constructor(e){if(this.player=e,this.enabled=!1,_i()){this._wakeLock=null;const e=()=>{null!==this._wakeLock&&"visible"===document.visibilityState&&this.enable()};document.addEventListener("visibilitychange",e),document.addEventListener("fullscreenchange",e)}else pi()?this.noSleepTimer=null:(this.noSleepVideo=document.createElement("video"),this.noSleepVideo.setAttribute("title","No Sleep"),this.noSleepVideo.setAttribute("playsinline",""),this._addSourceToVideo(this.noSleepVideo,"webm","data:video/webm;base64,GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4EEQoWBAhhTgGcBAAAAAAAVkhFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsghV17AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU1LjMzLjEwMFdBjUxhdmY1NS4zMy4xMDBzpJBlrrXf3DCDVB8KcgbMpcr+RImIQJBgAAAAAAAWVK5rAQAAAAAAD++uAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDiDgQEj44OEAmJaAOABAAAAAAAABrCBsLqBkK4BAAAAAAAPq9eBAnPFgQKcgQAitZyDdW5khohBX1ZPUkJJU4OBAuEBAAAAAAAAEZ+BArWIQOdwAAAAAABiZIEgY6JPbwIeVgF2b3JiaXMAAAAAAoC7AAAAAAAAgLUBAAAAAAC4AQN2b3JiaXMtAAAAWGlwaC5PcmcgbGliVm9yYmlzIEkgMjAxMDExMDEgKFNjaGF1ZmVudWdnZXQpAQAAABUAAABlbmNvZGVyPUxhdmM1NS41Mi4xMDIBBXZvcmJpcyVCQ1YBAEAAACRzGCpGpXMWhBAaQlAZ4xxCzmvsGUJMEYIcMkxbyyVzkCGkoEKIWyiB0JBVAABAAACHQXgUhIpBCCGEJT1YkoMnPQghhIg5eBSEaUEIIYQQQgghhBBCCCGERTlokoMnQQgdhOMwOAyD5Tj4HIRFOVgQgydB6CCED0K4moOsOQghhCQ1SFCDBjnoHITCLCiKgsQwuBaEBDUojILkMMjUgwtCiJqDSTX4GoRnQXgWhGlBCCGEJEFIkIMGQcgYhEZBWJKDBjm4FITLQagahCo5CB+EIDRkFQCQAACgoiiKoigKEBqyCgDIAAAQQFEUx3EcyZEcybEcCwgNWQUAAAEACAAAoEiKpEiO5EiSJFmSJVmSJVmS5omqLMuyLMuyLMsyEBqyCgBIAABQUQxFcRQHCA1ZBQBkAAAIoDiKpViKpWiK54iOCISGrAIAgAAABAAAEDRDUzxHlETPVFXXtm3btm3btm3btm3btm1blmUZCA1ZBQBAAAAQ0mlmqQaIMAMZBkJDVgEACAAAgBGKMMSA0JBVAABAAACAGEoOogmtOd+c46BZDppKsTkdnEi1eZKbirk555xzzsnmnDHOOeecopxZDJoJrTnnnMSgWQqaCa0555wnsXnQmiqtOeeccc7pYJwRxjnnnCateZCajbU555wFrWmOmkuxOeecSLl5UptLtTnnnHPOOeecc84555zqxekcnBPOOeecqL25lpvQxTnnnE/G6d6cEM4555xzzjnnnHPOOeecIDRkFQAABABAEIaNYdwpCNLnaCBGEWIaMulB9+gwCRqDnELq0ehopJQ6CCWVcVJKJwgNWQUAAAIAQAghhRRSSCGFFFJIIYUUYoghhhhyyimnoIJKKqmooowyyyyzzDLLLLPMOuyssw47DDHEEEMrrcRSU2011lhr7jnnmoO0VlprrbVSSimllFIKQkNWAQAgAAAEQgYZZJBRSCGFFGKIKaeccgoqqIDQkFUAACAAgAAAAABP8hzRER3RER3RER3RER3R8RzPESVREiVREi3TMjXTU0VVdWXXlnVZt31b2IVd933d933d+HVhWJZlWZZlWZZlWZZlWZZlWZYgNGQVAAACAAAghBBCSCGFFFJIKcYYc8w56CSUEAgNWQUAAAIACAAAAHAUR3EcyZEcSbIkS9IkzdIsT/M0TxM9URRF0zRV0RVdUTdtUTZl0zVdUzZdVVZtV5ZtW7Z125dl2/d93/d93/d93/d93/d9XQdCQ1YBABIAADqSIymSIimS4ziOJElAaMgqAEAGAEAAAIriKI7jOJIkSZIlaZJneZaomZrpmZ4qqkBoyCoAABAAQAAAAAAAAIqmeIqpeIqoeI7oiJJomZaoqZoryqbsuq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq4LhIasAgAkAAB0JEdyJEdSJEVSJEdygNCQVQCADACAAAAcwzEkRXIsy9I0T/M0TxM90RM901NFV3SB0JBVAAAgAIAAAAAAAAAMybAUy9EcTRIl1VItVVMt1VJF1VNVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVN0zRNEwgNWQkAkAEAkBBTLS3GmgmLJGLSaqugYwxS7KWxSCpntbfKMYUYtV4ah5RREHupJGOKQcwtpNApJq3WVEKFFKSYYyoVUg5SIDRkhQAQmgHgcBxAsixAsiwAAAAAAAAAkDQN0DwPsDQPAAAAAAAAACRNAyxPAzTPAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAA0DwP8DwR8EQRAAAAAAAAACzPAzTRAzxRBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAAsDwP8EQR0DwRAAAAAAAAACzPAzxRBDzRAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEOAAABBgIRQasiIAiBMAcEgSJAmSBM0DSJYFTYOmwTQBkmVB06BpME0AAAAAAAAAAAAAJE2DpkHTIIoASdOgadA0iCIAAAAAAAAAAAAAkqZB06BpEEWApGnQNGgaRBEAAAAAAAAAAAAAzzQhihBFmCbAM02IIkQRpgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAgwoQwUGrIiAIgTAHA4imUBAIDjOJYFAACO41gWAABYliWKAABgWZooAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAYcAAACDChDBQashIAiAIAcCiKZQHHsSzgOJYFJMmyAJYF0DyApgFEEQAIAAAocAAACLBBU2JxgEJDVgIAUQAABsWxLE0TRZKkaZoniiRJ0zxPFGma53meacLzPM80IYqiaJoQRVE0TZimaaoqME1VFQAAUOAAABBgg6bE4gCFhqwEAEICAByKYlma5nmeJ4qmqZokSdM8TxRF0TRNU1VJkqZ5niiKommapqqyLE3zPFEURdNUVVWFpnmeKIqiaaqq6sLzPE8URdE0VdV14XmeJ4qiaJqq6roQRVE0TdNUTVV1XSCKpmmaqqqqrgtETxRNU1Vd13WB54miaaqqq7ouEE3TVFVVdV1ZBpimaaqq68oyQFVV1XVdV5YBqqqqruu6sgxQVdd1XVmWZQCu67qyLMsCAAAOHAAAAoygk4wqi7DRhAsPQKEhKwKAKAAAwBimFFPKMCYhpBAaxiSEFEImJaXSUqogpFJSKRWEVEoqJaOUUmopVRBSKamUCkIqJZVSAADYgQMA2IGFUGjISgAgDwCAMEYpxhhzTiKkFGPOOScRUoox55yTSjHmnHPOSSkZc8w556SUzjnnnHNSSuacc845KaVzzjnnnJRSSuecc05KKSWEzkEnpZTSOeecEwAAVOAAABBgo8jmBCNBhYasBABSAQAMjmNZmuZ5omialiRpmud5niiapiZJmuZ5nieKqsnzPE8URdE0VZXneZ4oiqJpqirXFUXTNE1VVV2yLIqmaZqq6rowTdNUVdd1XZimaaqq67oubFtVVdV1ZRm2raqq6rqyDFzXdWXZloEsu67s2rIAAPAEBwCgAhtWRzgpGgssNGQlAJABAEAYg5BCCCFlEEIKIYSUUggJAAAYcAAACDChDBQashIASAUAAIyx1lprrbXWQGettdZaa62AzFprrbXWWmuttdZaa6211lJrrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmstpZRSSimllFJKKaWUUkoppZRSSgUA+lU4APg/2LA6wknRWGChISsBgHAAAMAYpRhzDEIppVQIMeacdFRai7FCiDHnJKTUWmzFc85BKCGV1mIsnnMOQikpxVZjUSmEUlJKLbZYi0qho5JSSq3VWIwxqaTWWoutxmKMSSm01FqLMRYjbE2ptdhqq7EYY2sqLbQYY4zFCF9kbC2m2moNxggjWywt1VprMMYY3VuLpbaaizE++NpSLDHWXAAAd4MDAESCjTOsJJ0VjgYXGrISAAgJACAQUooxxhhzzjnnpFKMOeaccw5CCKFUijHGnHMOQgghlIwx5pxzEEIIIYRSSsaccxBCCCGEkFLqnHMQQgghhBBKKZ1zDkIIIYQQQimlgxBCCCGEEEoopaQUQgghhBBCCKmklEIIIYRSQighlZRSCCGEEEIpJaSUUgohhFJCCKGElFJKKYUQQgillJJSSimlEkoJJYQSUikppRRKCCGUUkpKKaVUSgmhhBJKKSWllFJKIYQQSikFAAAcOAAABBhBJxlVFmGjCRcegEJDVgIAZAAAkKKUUiktRYIipRikGEtGFXNQWoqocgxSzalSziDmJJaIMYSUk1Qy5hRCDELqHHVMKQYtlRhCxhik2HJLoXMOAAAAQQCAgJAAAAMEBTMAwOAA4XMQdAIERxsAgCBEZohEw0JweFAJEBFTAUBigkIuAFRYXKRdXECXAS7o4q4DIQQhCEEsDqCABByccMMTb3jCDU7QKSp1IAAAAAAADADwAACQXAAREdHMYWRobHB0eHyAhIiMkAgAAAAAABcAfAAAJCVAREQ0cxgZGhscHR4fICEiIyQBAIAAAgAAAAAggAAEBAQAAAAAAAIAAAAEBB9DtnUBAAAAAAAEPueBAKOFggAAgACjzoEAA4BwBwCdASqwAJAAAEcIhYWIhYSIAgIABhwJ7kPfbJyHvtk5D32ych77ZOQ99snIe+2TkPfbJyHvtk5D32ych77ZOQ99YAD+/6tQgKOFggADgAqjhYIAD4AOo4WCACSADqOZgQArADECAAEQEAAYABhYL/QACIBDmAYAAKOFggA6gA6jhYIAT4AOo5mBAFMAMQIAARAQABgAGFgv9AAIgEOYBgAAo4WCAGSADqOFggB6gA6jmYEAewAxAgABEBAAGAAYWC/0AAiAQ5gGAACjhYIAj4AOo5mBAKMAMQIAARAQABgAGFgv9AAIgEOYBgAAo4WCAKSADqOFggC6gA6jmYEAywAxAgABEBAAGAAYWC/0AAiAQ5gGAACjhYIAz4AOo4WCAOSADqOZgQDzADECAAEQEAAYABhYL/QACIBDmAYAAKOFggD6gA6jhYIBD4AOo5iBARsAEQIAARAQFGAAYWC/0AAiAQ5gGACjhYIBJIAOo4WCATqADqOZgQFDADECAAEQEAAYABhYL/QACIBDmAYAAKOFggFPgA6jhYIBZIAOo5mBAWsAMQIAARAQABgAGFgv9AAIgEOYBgAAo4WCAXqADqOFggGPgA6jmYEBkwAxAgABEBAAGAAYWC/0AAiAQ5gGAACjhYIBpIAOo4WCAbqADqOZgQG7ADECAAEQEAAYABhYL/QACIBDmAYAAKOFggHPgA6jmYEB4wAxAgABEBAAGAAYWC/0AAiAQ5gGAACjhYIB5IAOo4WCAfqADqOZgQILADECAAEQEAAYABhYL/QACIBDmAYAAKOFggIPgA6jhYICJIAOo5mBAjMAMQIAARAQABgAGFgv9AAIgEOYBgAAo4WCAjqADqOFggJPgA6jmYECWwAxAgABEBAAGAAYWC/0AAiAQ5gGAACjhYICZIAOo4WCAnqADqOZgQKDADECAAEQEAAYABhYL/QACIBDmAYAAKOFggKPgA6jhYICpIAOo5mBAqsAMQIAARAQABgAGFgv9AAIgEOYBgAAo4WCArqADqOFggLPgA6jmIEC0wARAgABEBAUYABhYL/QACIBDmAYAKOFggLkgA6jhYIC+oAOo5mBAvsAMQIAARAQABgAGFgv9AAIgEOYBgAAo4WCAw+ADqOZgQMjADECAAEQEAAYABhYL/QACIBDmAYAAKOFggMkgA6jhYIDOoAOo5mBA0sAMQIAARAQABgAGFgv9AAIgEOYBgAAo4WCA0+ADqOFggNkgA6jmYEDcwAxAgABEBAAGAAYWC/0AAiAQ5gGAACjhYIDeoAOo4WCA4+ADqOZgQObADECAAEQEAAYABhYL/QACIBDmAYAAKOFggOkgA6jhYIDuoAOo5mBA8MAMQIAARAQABgAGFgv9AAIgEOYBgAAo4WCA8+ADqOFggPkgA6jhYID+oAOo4WCBA+ADhxTu2sBAAAAAAAAEbuPs4EDt4r3gQHxghEr8IEK"),this._addSourceToVideo(this.noSleepVideo,"mp4","data:video/mp4;base64,AAAAHGZ0eXBNNFYgAAACAGlzb21pc28yYXZjMQAAAAhmcmVlAAAGF21kYXTeBAAAbGliZmFhYyAxLjI4AABCAJMgBDIARwAAArEGBf//rdxF6b3m2Ui3lizYINkj7u94MjY0IC0gY29yZSAxNDIgcjIgOTU2YzhkOCAtIEguMjY0L01QRUctNCBBVkMgY29kZWMgLSBDb3B5bGVmdCAyMDAzLTIwMTQgLSBodHRwOi8vd3d3LnZpZGVvbGFuLm9yZy94MjY0Lmh0bWwgLSBvcHRpb25zOiBjYWJhYz0wIHJlZj0zIGRlYmxvY2s9MTowOjAgYW5hbHlzZT0weDE6MHgxMTEgbWU9aGV4IHN1Ym1lPTcgcHN5PTEgcHN5X3JkPTEuMDA6MC4wMCBtaXhlZF9yZWY9MSBtZV9yYW5nZT0xNiBjaHJvbWFfbWU9MSB0cmVsbGlzPTEgOHg4ZGN0PTAgY3FtPTAgZGVhZHpvbmU9MjEsMTEgZmFzdF9wc2tpcD0xIGNocm9tYV9xcF9vZmZzZXQ9LTIgdGhyZWFkcz02IGxvb2thaGVhZF90aHJlYWRzPTEgc2xpY2VkX3RocmVhZHM9MCBucj0wIGRlY2ltYXRlPTEgaW50ZXJsYWNlZD0wIGJsdXJheV9jb21wYXQ9MCBjb25zdHJhaW5lZF9pbnRyYT0wIGJmcmFtZXM9MCB3ZWlnaHRwPTAga2V5aW50PTI1MCBrZXlpbnRfbWluPTI1IHNjZW5lY3V0PTQwIGludHJhX3JlZnJlc2g9MCByY19sb29rYWhlYWQ9NDAgcmM9Y3JmIG1idHJlZT0xIGNyZj0yMy4wIHFjb21wPTAuNjAgcXBtaW49MCBxcG1heD02OSBxcHN0ZXA9NCB2YnZfbWF4cmF0ZT03NjggdmJ2X2J1ZnNpemU9MzAwMCBjcmZfbWF4PTAuMCBuYWxfaHJkPW5vbmUgZmlsbGVyPTAgaXBfcmF0aW89MS40MCBhcT0xOjEuMDAAgAAAAFZliIQL8mKAAKvMnJycnJycnJycnXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXiEASZACGQAjgCEASZACGQAjgAAAAAdBmjgX4GSAIQBJkAIZACOAAAAAB0GaVAX4GSAhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGagC/AySEASZACGQAjgAAAAAZBmqAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZrAL8DJIQBJkAIZACOAAAAABkGa4C/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmwAvwMkhAEmQAhkAI4AAAAAGQZsgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGbQC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm2AvwMkhAEmQAhkAI4AAAAAGQZuAL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGboC/AySEASZACGQAjgAAAAAZBm8AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZvgL8DJIQBJkAIZACOAAAAABkGaAC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmiAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZpAL8DJIQBJkAIZACOAAAAABkGaYC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBmoAvwMkhAEmQAhkAI4AAAAAGQZqgL8DJIQBJkAIZACOAIQBJkAIZACOAAAAABkGawC/AySEASZACGQAjgAAAAAZBmuAvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZsAL8DJIQBJkAIZACOAAAAABkGbIC/AySEASZACGQAjgCEASZACGQAjgAAAAAZBm0AvwMkhAEmQAhkAI4AhAEmQAhkAI4AAAAAGQZtgL8DJIQBJkAIZACOAAAAABkGbgCvAySEASZACGQAjgCEASZACGQAjgAAAAAZBm6AnwMkhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AhAEmQAhkAI4AAAAhubW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAABDcAAQAAAQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAzB0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAA+kAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAALAAAACQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAPpAAAAAAABAAAAAAKobWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAB1MAAAdU5VxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRlb0hhbmRsZXIAAAACU21pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAhNzdGJsAAAAr3N0c2QAAAAAAAAAAQAAAJ9hdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAALAAkABIAAAASAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAALWF2Y0MBQsAN/+EAFWdCwA3ZAsTsBEAAAPpAADqYA8UKkgEABWjLg8sgAAAAHHV1aWRraEDyXyRPxbo5pRvPAyPzAAAAAAAAABhzdHRzAAAAAAAAAAEAAAAeAAAD6QAAABRzdHNzAAAAAAAAAAEAAAABAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAAIxzdHN6AAAAAAAAAAAAAAAeAAADDwAAAAsAAAALAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAACgAAAAoAAAAKAAAAiHN0Y28AAAAAAAAAHgAAAEYAAANnAAADewAAA5gAAAO0AAADxwAAA+MAAAP2AAAEEgAABCUAAARBAAAEXQAABHAAAASMAAAEnwAABLsAAATOAAAE6gAABQYAAAUZAAAFNQAABUgAAAVkAAAFdwAABZMAAAWmAAAFwgAABd4AAAXxAAAGDQAABGh0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAACAAAAAAAABDcAAAAAAAAAAAAAAAEBAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAQkAAADcAABAAAAAAPgbWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAAC7gAAAykBVxAAAAAAALWhkbHIAAAAAAAAAAHNvdW4AAAAAAAAAAAAAAABTb3VuZEhhbmRsZXIAAAADi21pbmYAAAAQc21oZAAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAADT3N0YmwAAABnc3RzZAAAAAAAAAABAAAAV21wNGEAAAAAAAAAAQAAAAAAAAAAAAIAEAAAAAC7gAAAAAAAM2VzZHMAAAAAA4CAgCIAAgAEgICAFEAVBbjYAAu4AAAADcoFgICAAhGQBoCAgAECAAAAIHN0dHMAAAAAAAAAAgAAADIAAAQAAAAAAQAAAkAAAAFUc3RzYwAAAAAAAAAbAAAAAQAAAAEAAAABAAAAAgAAAAIAAAABAAAAAwAAAAEAAAABAAAABAAAAAIAAAABAAAABgAAAAEAAAABAAAABwAAAAIAAAABAAAACAAAAAEAAAABAAAACQAAAAIAAAABAAAACgAAAAEAAAABAAAACwAAAAIAAAABAAAADQAAAAEAAAABAAAADgAAAAIAAAABAAAADwAAAAEAAAABAAAAEAAAAAIAAAABAAAAEQAAAAEAAAABAAAAEgAAAAIAAAABAAAAFAAAAAEAAAABAAAAFQAAAAIAAAABAAAAFgAAAAEAAAABAAAAFwAAAAIAAAABAAAAGAAAAAEAAAABAAAAGQAAAAIAAAABAAAAGgAAAAEAAAABAAAAGwAAAAIAAAABAAAAHQAAAAEAAAABAAAAHgAAAAIAAAABAAAAHwAAAAQAAAABAAAA4HN0c3oAAAAAAAAAAAAAADMAAAAaAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAAAJAAAACQAAAAkAAACMc3RjbwAAAAAAAAAfAAAALAAAA1UAAANyAAADhgAAA6IAAAO+AAAD0QAAA+0AAAQAAAAEHAAABC8AAARLAAAEZwAABHoAAASWAAAEqQAABMUAAATYAAAE9AAABRAAAAUjAAAFPwAABVIAAAVuAAAFgQAABZ0AAAWwAAAFzAAABegAAAX7AAAGFwAAAGJ1ZHRhAAAAWm1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAALWlsc3QAAAAlqXRvbwAAAB1kYXRhAAAAAQAAAABMYXZmNTUuMzMuMTAw"),this.noSleepVideo.addEventListener("loadedmetadata",(()=>{this.noSleepVideo.duration<=1?this.noSleepVideo.setAttribute("loop",""):this.noSleepVideo.addEventListener("timeupdate",(()=>{this.noSleepVideo.currentTime>.5&&(this.noSleepVideo.currentTime=Math.random())}))})))}_addSourceToVideo(e,t,i){const n=document.createElement("source");n.src=i,n.type=`video/${t}`,e.appendChild(n)}get isEnabled(){return this.enabled}enable(){const e=this.player.debug;if(_i())return navigator.wakeLock.request("screen").then((t=>{this._wakeLock=t,this.enabled=!0,e.log("wakeLock","Wake Lock active."),this._wakeLock.addEventListener("release",(()=>{e.log("wakeLock","Wake Lock released.")}))})).catch((t=>{throw this.enabled=!1,e.error("wakeLock",`${t.name}, ${t.message}`),t}));if(pi())return this.disable(),this.noSleepTimer=window.setInterval((()=>{document.hidden||(window.location.href=window.location.href.split("#")[0],window.setTimeout(window.stop,0))}),15e3),this.enabled=!0,Promise.resolve();return this.noSleepVideo.play().then((e=>(this.enabled=!0,e))).catch((e=>{throw this.enabled=!1,e}))}disable(){const e=this.player.debug;_i()?(this._wakeLock&&this._wakeLock.release(),this._wakeLock=null):pi()?this.noSleepTimer&&(e.warn("wakeLock","NoSleep now disabled for older iOS devices."),window.clearInterval(this.noSleepTimer),this.noSleepTimer=null):this.noSleepVideo.pause(),this.enabled=!1}} -/* - * - * @ezuikit/utils-logger v1.0.1 - * Copyright (c) 2024-3-23 Ezviz-OpenBiz - * Released under MIT the License. - * - */var mi={info:"",log:"background: #4096ff; color: #FFF;",warn:"background: yellow; color: #FFF;",error:"background: red; color: #FFF;"},vi=function(){function e(e){void 0===e&&(e={}),this._options={level:"INFO",showTime:!1},this._levelNum=3,this.info=this._loggerFactory("info",this._levelNum>=3),this.log=this._loggerFactory("log",this._levelNum>=2),this.warn=this._loggerFactory("warn",this._levelNum>=1),this.error=this._loggerFactory("error",this._levelNum>=0),this.setOptions(e)}var t=e.prototype;return t.setOptions=function(e){var t;this._options=Object.assign({},this._options,e),this._levelNum=this._matchLevel(null!=(t=this._options.level)?t:"INFO"),this.info=this._loggerFactory("info",this._levelNum>=3),this.log=this._loggerFactory("log",this._levelNum>=2),this.warn=this._loggerFactory("warn",this._levelNum>=1),this.error=this._loggerFactory("error",this._levelNum>=0)},t._matchLevel=function(e){var t=3;switch(e){case"INFO":t=3;break;case"LOG":t=2;break;case"WARN":t=1;break;case"ERROR":t=0}return t},t._loggerFactory=function(t,i){var n=console[t];if(i&&n){var r,o=this._options.name?"%c["+this._options.name+"]%c %c["+t.toUpperCase()+"]":"%c["+t.toUpperCase()+"]",a=[this._options.name?"background: green;color: #fff":null,this._options.name?"":null,mi[t]].filter((function(e){return null!=e}));return(r=n).bind.apply(r,[].concat([console,o],a))}return e.noop},t.getOptions=function(){return this._options},t.getVersion=function(){return"1.0.1"},e}();function gi(e){return(e=+e)<10&&(e="0"+e),e+""}vi.noop=function(){};var yi=["info","log","warn","error"];function bi(e){var t=new vi(e);return new Proxy(t,{get:function(e,t){if(yi.includes(t)){var i;if(null==(i=e._options)?void 0:i.showTime){var n=(o=(r=new Date(Date.now())).getFullYear(),a=r.getMonth()+1,s=r.getDate(),d=r.getHours(),l=r.getMinutes(),c=r.getSeconds(),h=r.getMilliseconds(),o+"/"+gi(a)+"/"+gi(s)+" "+gi(d)+":"+gi(l)+":"+gi(c)+":"+h);return e[t].bind(console,"["+n+"]")}return e[t].bind(console)}var r,o,a,s,d,l,c,h;return Reflect.get(e,t)}})}class Ei{constructor(e){this.master=e,this.logger=new bi({name:"FLV",showTime:!0}),console.log(e._opt.loggerOptions)}info(e,...t){this._setLoger()>=4&&this.logger.log(e,...t)}log(e,...t){this._setLoger()>=3&&this.logger.log(e,...t)}warn(e,...t){this._setLoger()>=2&&this.logger.warn(e,...t)}error(e,...t){this.logger.error(e,...t)}_setLoger(e){var t,i,n,r,o;if(this.master._opt.debug&&null!==(t=this.master._opt.loggerOptions)&&void 0!==t&&t.level)return"INFO"===(null===(i=this.master._opt.loggerOptions)||void 0===i?void 0:i.level)?4:"LOG"===(null===(n=this.master._opt.loggerOptions)||void 0===n?void 0:n.level)?3:"WARN"===(null===(r=this.master._opt.loggerOptions)||void 0===r?void 0:r.level)?2:"ERROR"===(null===(o=this.master._opt.loggerOptions)||void 0===o?void 0:o.level)?1:5}}class Si{constructor(e){this.destroys=[],this.proxy=this.proxy.bind(this),this.master=e}proxy(e,t,i,n={}){if(!e)return;if(Array.isArray(t))return t.map((t=>this.proxy(e,t,i,n)));e.addEventListener(t,i,n);const r=()=>e.removeEventListener(t,i,n);return this.destroys.push(r),r}destroy(){var e;null===(e=this.master.debug)||void 0===e||e.log("Events","destroy"),this.destroys.forEach((e=>e()))}}class wi{constructor(e){this.player=e,((e,t)=>{const{events:{proxy:i}}=e,n=document.createElement("object");n.setAttribute("aria-hidden","true"),n.setAttribute("tabindex",-1),n.type="text/html",n.data="about:blank",Gt(n,{display:"block",position:"absolute",top:"0",left:"0",height:"100%",width:"100%",overflow:"hidden",pointerEvents:"none",zIndex:"-1"});let r=e.width,o=e.height;i(n,"load",(()=>{i(n.contentDocument.defaultView,"resize",(()=>{e.width===r&&e.height===o||(r=e.width,o=e.height,e.emit(mt.resize),s())}))})),e.$container.appendChild(n),e.on(mt.destroy,(()=>{e.$container.removeChild(n)}));const a=i=>{const n=!0===(r=i)||!1===r?i:e.fullscreen;var r;Gt(t.$fullscreenExit,"display",n?"flex":"none"),Gt(t.$fullscreen,"display",n?"none":"flex")},s=()=>{Qt()&&e._opt.useWebFullScreen};try{Ut.on("change",a),e.events.destroys.push((()=>{Ut.off("change",a)}))}catch(e){}e.on(mt.webFullscreen,(e=>{a(e),s()}))})(e,this)}}class Ti extends $t{constructor(e,t,i){var n;super(),this.$container=e,this._opt=t,this.debug=new Ei(this),this._loading=!1,this._playing=!1,this._hasLoaded=!1,this._checkHeartTimeout=null,this._checkLoadingTimeout=null,this._checkStatsInterval=null,this._startBpsTime=null,this._isPlayingBeforePageHidden=!1,this._stats={buf:0,fps:0,abps:0,vbps:0,ts:0},this._times={playInitStart:"",playStart:"",streamStart:"",streamResponse:"",demuxStart:"",decodeStart:"",videoStart:"",playTimestamp:"",streamTimestamp:"",streamResponseTimestamp:"",demuxTimestamp:"",decodeTimestamp:"",videoTimestamp:"",allTimestamp:""},this._videoTimestamp=0,this._audioTimestamp=0,n=this,Object.defineProperty(n,"rect",{get:()=>{const e=n.$container.getBoundingClientRect();return e.width=Math.max(e.width,n.$container.clientWidth),e.height=Math.max(e.height,n.$container.clientHeight),e}}),["bottom","height","left","right","top","width"].forEach((e=>{Object.defineProperty(n,e,{get:()=>n.rect[e]})})),this.events=new Si(this),this.video=new i(this),(e=>{try{const t=t=>{Xt(t)===e.$container&&(e.emit(vt.fullscreen,e.fullscreen),e.fullscreen?e._opt.useMSE&&e.resize():e.resize())};Ut.on("change",t),e.events.destroys.push((()=>{Ut.off("change",t)}))}catch(e){}e.on(mt.decoderWorkerInit,(()=>{e.debug.log("player","has loaded"),e.loaded=!0})),e.on(mt.play,(()=>{e.loading=!1})),e.on(mt.fullscreen,(t=>{if(t)try{Ut.request(e.$container).then((()=>{})).catch((t=>{Qt()&&e._opt.useWebFullScreen&&(e.webFullscreen=!0)}))}catch(t){Qt()&&e._opt.useWebFullScreen&&(e.webFullscreen=!0)}else try{Ut.exit().then((()=>{e.webFullscreen&&(e.webFullscreen=!1)})).catch((()=>{e.webFullscreen=!1}))}catch(t){e.webFullscreen=!1}})),Qt()&&e.on(mt.webFullscreen,(t=>{t?e.$container.classList.add("flv-fullscreen-web"):e.$container.classList.remove("flv-fullscreen-web"),e._opt.useWebFullScreen&&Gt(e.$container,t?{position:"fixed",top:"0px",left:"0px",right:"0px",bottom:"0px",height:"100%",width:"100%"}:{position:"relative",top:"",left:"",right:"",bottom:"",height:"",width:""}),e.emit(vt.fullscreen,e.fullscreen)})),e.on(mt.resize,(()=>{var t;null===(t=e.video)||void 0===t||t.resize()}));const t=[mt.timeUpdate];Object.keys(mt).forEach((i=>{e.on(mt[i],(n=>{t.includes(i)||e.debug.log("player events",mt[i],n)}))})),Object.keys(gt).forEach((t=>{e.on(gt[t],(i=>{e.debug.log("player event error",gt[t],i)}))}))})(this),(e=>{const{_opt:t,debug:i,events:{proxy:n}}=e;t.supportDblclickFullscreen&&n(e.$container,"dblclick",(t=>{const i=Xt(t).nodeName.toLowerCase();"canvas"!==i&&"video"!==i||(e.fullscreen=!e.fullscreen)})),n(document,"visibilitychange",(()=>{t.hiddenAutoPause&&(i.log("visibilitychange",document.visibilityState,e._isPlayingBeforePageHidden),"visible"===document.visibilityState?e._isPlayingBeforePageHidden&&e.play():(e._isPlayingBeforePageHidden=e.playing,e.playing&&e.pause()))})),n(window,"fullscreenchange",(()=>{null!==e.keepScreenOn&&"visible"===document.visibilityState&&e.enableWakeLock&&e.enableWakeLock()}))})(this),this.control=new wi(this)}updateOption(e){this._opt=Object.assign({},this._opt,e)}} -/* - * - * @ezuikit/utils-collect v0.1.0-beta.1 - * Copyright (c) 2024-7-11 Ezviz-OpenBiz - * Released under MIT the License. - * - */var Bi,ki,Ci,Ri,Oi=(Bi="undefined"!=typeof self?self:window,ki={navigator:void 0!==Bi.navigator?Bi.navigator:{userAgent:""},infoMap:{engine:["WebKit","Trident","Gecko","Presto"],browser:["Safari","Chrome","Edge","IE","Firefox","Firefox Focus","Chromium","Opera","Vivaldi","Yandex","Arora","Lunascape","QupZilla","Coc Coc","Kindle","Iceweasel","Konqueror","Iceape","SeaMonkey","Epiphany","360","360SE","360EE","UC","QQBrowser","QQ","Baidu","Maxthon","Sogou","LBBROWSER","2345Explorer","TheWorld","XiaoMi","Quark","Qiyu","Wechat","Taobao","Alipay","Weibo","Douban","Suning","iQiYi"],os:["Windows","Linux","Mac OS","Android","Ubuntu","FreeBSD","Debian","iOS","Windows Phone","BlackBerry","MeeGo","Symbian","Chrome OS","WebOS"],device:["Mobile","Tablet","iPad"]}},Ci={getMatchMap:function(e){return{Trident:e.indexOf("Trident")>-1||e.indexOf("NET CLR")>-1,Presto:e.indexOf("Presto")>-1,WebKit:e.indexOf("AppleWebKit")>-1,Gecko:e.indexOf("Gecko/")>-1,Safari:e.indexOf("Safari")>-1,Chrome:e.indexOf("Chrome")>-1||e.indexOf("CriOS")>-1,IE:e.indexOf("MSIE")>-1||e.indexOf("Trident")>-1,Edge:e.indexOf("Edge")>-1,Firefox:e.indexOf("Firefox")>-1||e.indexOf("FxiOS")>-1,"Firefox Focus":e.indexOf("Focus")>-1,Chromium:e.indexOf("Chromium")>-1,Opera:e.indexOf("Opera")>-1||e.indexOf("OPR")>-1,Vivaldi:e.indexOf("Vivaldi")>-1,Yandex:e.indexOf("YaBrowser")>-1,Arora:e.indexOf("Arora")>-1,Lunascape:e.indexOf("Lunascape")>-1,QupZilla:e.indexOf("QupZilla")>-1,"Coc Coc":e.indexOf("coc_coc_browser")>-1,Kindle:e.indexOf("Kindle")>-1||e.indexOf("Silk/")>-1,Iceweasel:e.indexOf("Iceweasel")>-1,Konqueror:e.indexOf("Konqueror")>-1,Iceape:e.indexOf("Iceape")>-1,SeaMonkey:e.indexOf("SeaMonkey")>-1,Epiphany:e.indexOf("Epiphany")>-1,360:e.indexOf("QihooBrowser")>-1||e.indexOf("QHBrowser")>-1,"360EE":e.indexOf("360EE")>-1,"360SE":e.indexOf("360SE")>-1,UC:e.indexOf("UC")>-1||e.indexOf(" UBrowser")>-1,QQBrowser:e.indexOf("QQBrowser")>-1,QQ:e.indexOf("QQ/")>-1,Baidu:e.indexOf("Baidu")>-1||e.indexOf("BIDUBrowser")>-1,Maxthon:e.indexOf("Maxthon")>-1,Sogou:e.indexOf("MetaSr")>-1||e.indexOf("Sogou")>-1,LBBROWSER:e.indexOf("LBBROWSER")>-1,"2345Explorer":e.indexOf("2345Explorer")>-1,TheWorld:e.indexOf("TheWorld")>-1,XiaoMi:e.indexOf("MiuiBrowser")>-1,Quark:e.indexOf("Quark")>-1,Qiyu:e.indexOf("Qiyu")>-1,Wechat:e.indexOf("MicroMessenger")>-1,Taobao:e.indexOf("AliApp(TB")>-1,Alipay:e.indexOf("AliApp(AP")>-1,Weibo:e.indexOf("Weibo")>-1,Douban:e.indexOf("com.douban.frodo")>-1,Suning:e.indexOf("SNEBUY-APP")>-1,iQiYi:e.indexOf("IqiyiApp")>-1,Windows:e.indexOf("Windows")>-1,Linux:e.indexOf("Linux")>-1||e.indexOf("X11")>-1,"Mac OS":e.indexOf("Macintosh")>-1,Android:e.indexOf("Android")>-1||e.indexOf("Adr")>-1,Ubuntu:e.indexOf("Ubuntu")>-1,FreeBSD:e.indexOf("FreeBSD")>-1,Debian:e.indexOf("Debian")>-1,"Windows Phone":e.indexOf("IEMobile")>-1||e.indexOf("Windows Phone")>-1,BlackBerry:e.indexOf("BlackBerry")>-1||e.indexOf("RIM")>-1,MeeGo:e.indexOf("MeeGo")>-1,Symbian:e.indexOf("Symbian")>-1,iOS:e.indexOf("like Mac OS X")>-1,"Chrome OS":e.indexOf("CrOS")>-1,WebOS:e.indexOf("hpwOS")>-1,Mobile:e.indexOf("Mobi")>-1||e.indexOf("iPh")>-1||e.indexOf("480")>-1,Tablet:e.indexOf("Tablet")>-1||e.indexOf("Nexus 7")>-1,iPad:e.indexOf("iPad")>-1}},matchInfoMap:function(e){var t,i=(null==(t=ki.navigator)?void 0:t.userAgent)||"",n=Ci.getMatchMap(i);for(var r in ki.infoMap)for(var o=0;o36&&Bi.showModalDialog?r=!0:+o>45&&(r=i("type","application/vnd.chromium.remoting-viewer"))}if(n.Baidu&&n.Opera&&(n.Baidu=!1),n.Mobile&&(n.Mobile=!t.includes("iPad")),r&&(i("type","application/gameplugin")||ki.navigator&&void 0===ki.navigator.connection.saveData?n["360SE"]=!0:n["360EE"]=!0),n.IE||n.Edge)switch(window.screenTop-window.screenY){case 71:case 74:case 99:case 75:case 105:break;case 102:n["360EE"]=!0;break;case 104:n["360SE"]=!0}var a={Safari:function(){return t.replace(/^.*Version\/([\d.]+).*$/,"$1")},Chrome:function(){return t.replace(/^.*Chrome\/([\d.]+).*$/,"$1").replace(/^.*CriOS\/([\d.]+).*$/,"$1")},IE:function(){return t.replace(/^.*MSIE ([\d.]+).*$/,"$1").replace(/^.*rv:([\d.]+).*$/,"$1")},Edge:function(){return t.replace(/^.*Edge\/([\d.]+).*$/,"$1")},Firefox:function(){return t.replace(/^.*Firefox\/([\d.]+).*$/,"$1").replace(/^.*FxiOS\/([\d.]+).*$/,"$1")},"Firefox Focus":function(){return t.replace(/^.*Focus\/([\d.]+).*$/,"$1")},Chromium:function(){return t.replace(/^.*Chromium\/([\d.]+).*$/,"$1")},Opera:function(){return t.replace(/^.*Opera\/([\d.]+).*$/,"$1").replace(/^.*OPR\/([\d.]+).*$/,"$1")},Vivaldi:function(){return t.replace(/^.*Vivaldi\/([\d.]+).*$/,"$1")},Yandex:function(){return t.replace(/^.*YaBrowser\/([\d.]+).*$/,"$1")},Arora:function(){return t.replace(/^.*Arora\/([\d.]+).*$/,"$1")},Lunascape:function(){return t.replace(/^.*Lunascape[\/\s]([\d.]+).*$/,"$1")},QupZilla:function(){return t.replace(/^.*QupZilla[\/\s]([\d.]+).*$/,"$1")},"Coc Coc":function(){return t.replace(/^.*coc_coc_browser\/([\d.]+).*$/,"$1")},Kindle:function(){return t.replace(/^.*Version\/([\d.]+).*$/,"$1")},Iceweasel:function(){return t.replace(/^.*Iceweasel\/([\d.]+).*$/,"$1")},Konqueror:function(){return t.replace(/^.*Konqueror\/([\d.]+).*$/,"$1")},Iceape:function(){return t.replace(/^.*Iceape\/([\d.]+).*$/,"$1")},SeaMonkey:function(){return t.replace(/^.*SeaMonkey\/([\d.]+).*$/,"$1")},Epiphany:function(){return t.replace(/^.*Epiphany\/([\d.]+).*$/,"$1")},360:function(){return t.replace(/^.*QihooBrowser\/([\d.]+).*$/,"$1")},"360SE":function(){return{63:"10.0",55:"9.1",45:"8.1",42:"8.0",31:"7.0",21:"6.3"}[+t.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"360EE":function(){return{69:"11.0",63:"9.5",55:"9.0",50:"8.7",30:"7.5"}[+t.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},Maxthon:function(){return t.replace(/^.*Maxthon\/([\d.]+).*$/,"$1")},QQBrowser:function(){return t.replace(/^.*QQBrowser\/([\d.]+).*$/,"$1")},QQ:function(){return t.replace(/^.*QQ\/([\d.]+).*$/,"$1")},Baidu:function(){return t.replace(/^.*BIDUBrowser[\s\/]([\d.]+).*$/,"$1")},UC:function(){return t.replace(/^.*UC?Browser\/([\d.]+).*$/,"$1")},Sogou:function(){return t.replace(/^.*SE ([\d.X]+).*$/,"$1").replace(/^.*SogouMobileBrowser\/([\d.]+).*$/,"$1")},LBBROWSER:function(){return{57:"6.5",49:"6.0",46:"5.9",42:"5.3",39:"5.2",34:"5.0",29:"4.5",21:"4.0"}[+navigator.userAgent.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"2345Explorer":function(){return t.replace(/^.*2345Explorer\/([\d.]+).*$/,"$1")},TheWorld:function(){return t.replace(/^.*TheWorld ([\d.]+).*$/,"$1")},XiaoMi:function(){return t.replace(/^.*MiuiBrowser\/([\d.]+).*$/,"$1")},Quark:function(){return t.replace(/^.*Quark\/([\d.]+).*$/,"$1")},Qiyu:function(){return t.replace(/^.*Qiyu\/([\d.]+).*$/,"$1")},Wechat:function(){return t.replace(/^.*MicroMessenger\/([\d.]+).*$/,"$1")},Taobao:function(){return t.replace(/^.*AliApp\(TB\/([\d.]+).*$/,"$1")},Alipay:function(){return t.replace(/^.*AliApp\(AP\/([\d.]+).*$/,"$1")},Weibo:function(){return t.replace(/^.*weibo__([\d.]+).*$/,"$1")},Douban:function(){return t.replace(/^.*com.douban.frodo\/([\d.]+).*$/,"$1")},Suning:function(){return t.replace(/^.*SNEBUY-APP([\d.]+).*$/,"$1")},iQiYi:function(){return t.replace(/^.*IqiyiVersion\/([\d.]+).*$/,"$1")}};return e.browserVersion="",a[e.browser]&&(e.browserVersion=a[e.browser](),e.browserVersion==t&&(e.browserVersion="")),"Edge"==e.browser&&(e.engine="EdgeHTML"),"Chrome"==e.browser&&parseInt(e.browserVersion)>27&&(e.engine="Blink"),"Opera"==e.browser&&parseInt(e.browserVersion)>12&&(e.engine="Blink"),"Yandex"==e.browser&&(e.engine="Blink"),e.browser+" (version: "+e.browserVersion+"; kernel: "+e.engine+")"}},Ri={DeviceInfoObj:function(e){var t,i=function(t){var i;null==(i=e.info)||i.forEach((function(e){e.toLowerCase()===t.toLowerCase()&&(r[t]=n[t])}))};e=e||{domain:""};var n={deviceType:Ci.getDeviceType(),OS:Ci.getOS(),OSVersion:Ci.getOSVersion(),sh:Bi.screen.height,sw:Bi.screen.width,lang:Ci.getLanguage(),netWork:Ci.getNetwork(),orientation:Ci.getOrientationStatu(),browserInfo:Ci.getBrowserInfo(),fingerprint:Ci.createFingerprint(e.domain),userAgent:null==(t=ki.navigator)?void 0:t.userAgent};if(!e.info||0===e.info.length)return n;var r={};for(var o in n)i(o);return r}},{getDeviceInfo:function(e){return Ri.DeviceInfoObj(e)}}),Ii=function(){function e(){}return e.add=function(t,i){e.queues.push({url:t,data:i})},e.fire=function(){if(e.queues&&0!==e.queues.length){e.isStop=!1;var t=e.queues[0];t.url&&e.api.report(t.data),e.queues.splice(0,1),e.fire()}else e.isStop=!0},e}();Ii.isStop=!0,Ii.queues=[];var xi=function(){function e(e){this.url=e}var t=e.prototype;return t.report=function(e){this.checkUrl(this.url)&&this.sendInfo(e)},t.sendInfo=function(e){navigator.sendBeacon?this.sendBeacon(this.url,e):this.sendImage(this.url,e)},t.sendImage=function(e,t){var i=this.changeJSON2Query(t),n=new Image;n.onload=n.onerror=function(){n=null},n.src=e+"?"+i+"&random="+Math.random()},t.sendBeacon=function(e,t){try{navigator.sendBeacon(e,this.formatParamsByURLSearchParams(t))}catch(e){}},t.formatParamsByURLSearchParams=function(e){var t=new URLSearchParams;for(var i in e)"object"==typeof e[i]&&(e[i]=JSON.stringify(e[i])),t.append(i,e[i]);return t},t.changeJSON2Query=function(e){var t="";for(var i in e){""!=t&&(t+="&");var n=e[i];t+=i+"="+encodeURIComponent("object"==typeof n?JSON.stringify(n):n)}return t},t.checkUrl=function(e){return!!e&&/^[hH][tT][tT][pP]([sS]?):\/\//.test(e)},e}();function Di(){return Di=Object.assign||function(e){for(var t=1;t0&&i[0]&&i[1]&&i[2]&&(n.serial=i[0],n.no=i[1],n.bitstream=i[2])}catch(e){}return n}return{}}class Pi{static initMonitor(e){Pi.collect=new Li({forbidden:e,url:"https://log.ys7.com/statistics.do/opensdk_ezuikit",jsError:!1,promiseError:!1,resourceError:!1,extendsInfo:{protocol:"flv",v:"1.0.2"}})}static report(e,t={}){Pi.collect||Pi.initMonitor();try{const i=Mi(Pi.url);Pi.collect.send({url:Pi.url,serial:i.serial,no:i.no,action:e,logInfo:t})}catch(e){}}}class Ui extends Ti{constructor(e,t){super(e,t,ni),this._opt.useMSE=!1,this._opt.hasAudio&&(this.audio=new oi(this)),this.decoderWorker=new li(this),this.stream=null,this.demux=null,this._lastVolume=null,Qt()&&(this.keepScreenOn=new fi(this)),this._opt.hasAudio&&this._opt.volume>0&&(this.volume=this._opt.volume)}destroy(){this._loading=!1,this._playing=!1,this._hasLoaded=!1,this._lastVolume=null,this._times={playInitStart:"",playStart:"",streamStart:"",streamResponse:"",demuxStart:"",decodeStart:"",videoStart:"",playTimestamp:"",streamTimestamp:"",streamResponseTimestamp:"",demuxTimestamp:"",decodeTimestamp:"",videoTimestamp:"",allTimestamp:""},this.decoderWorker&&(this.decoderWorker.destroy(),this.decoderWorker=null),this.video&&(this.video.destroy(),this.video=null),this.audio&&(this.audio.destroy(),this.audio=null),this.stream&&(this.stream.destroy(),this.stream=null),this.demux&&(this.demux.destroy(),this.demux=null),this.events&&(this.events.destroy(),this.events=null),this.clearCheckHeartTimeout(),this.clearCheckLoadingTimeout(),this.clearStatsInterval(),this.releaseWakeLock(),this.keepScreenOn=null,this.resetStats(),this._audioTimestamp=0,this._videoTimestamp=0,this.emit("destroy"),this.off(),this.debug.log("play","destroy end")}set fullscreen(e){Qt()&&this._opt.useWebFullScreen?(this.emit(mt.webFullscreen,e),setTimeout((()=>{this.updateOption({rotate:e?270:0}),this.resize()}),10)):this.emit(mt.fullscreen,e)}get fullscreen(){return zt()||this.webFullscreen}set webFullscreen(e){this.emit(mt.webFullscreen,e)}get webFullscreen(){return this.$container.classList.contains("flv-fullscreen-web")}set loaded(e){this._hasLoaded=e}get loaded(){return this._hasLoaded}set playing(e){e&&(this.loading=!1),this.playing!==e&&(this._playing=e,this.emit(mt.playing,e),this.emit(mt.volumechange,this.volume),e?this.emit(mt.play):this.emit(mt.pause))}get playing(){return this._playing}get volume(){var e;return+((null===(e=this.audio)||void 0===e?void 0:e.volume)||0).toFixed(2)||0}set volume(e){var t;e!==this.volume&&(null===(t=this.audio)||void 0===t||t.setVolume(e),this._lastVolume=e)}get lastVolume(){return this._lastVolume}set loading(e){this.loading!==e&&(this._loading=e,this.emit(mt.loading,this._loading))}get loading(){return this._loading}set audioTimestamp(e){null!==e&&(this._audioTimestamp=e)}get audioTimestamp(){return this._audioTimestamp}set videoTimestamp(e){null!==e&&(this._videoTimestamp=e,this._opt.useWCS||this._opt.useMSE||this.audioTimestamp&&this.videoTimestamp&&this.audio&&this.audio.emit(mt.videoSyncAudio,{audioTimestamp:this.audioTimestamp,videoTimestamp:this.videoTimestamp,diff:this.audioTimestamp-this.videoTimestamp}))}get videoTimestamp(){return this._videoTimestamp}get isDebug(){return!0===this._opt.debug}init(){return new Promise(((e,t)=>{this.stream||(this.stream=new di(this)),this.audio||this._opt.hasAudio&&(this.audio=new oi(this)),this.demux||(this.demux=new Ai(this)),this.decoderWorker?e():(this.decoderWorker=new li(this),this.once(mt.decoderWorkerInit,(()=>{e()})))}))}play(e){return this._opt=Object.assign({},this._opt,e||{}),this.clearCheckHeartTimeout(),new Promise(((e,t)=>{if(!this._opt.url)return t();this.loading=!0,this.playing=!1,this._times.playInitStart=Nt(),this.init().then((()=>{this._times.playStart=Nt(),this._opt.isNotMute&&this.mute(!1),this.enableWakeLock();try{this.stream.fetchStream(this._opt.url,this._opt)}catch(e){}this.checkLoadingTimeout(),this.stream.once(gt.fetchError,(e=>{t(e)})),this.stream.once(gt.websocketError,(e=>{t(e)})),this.stream.once(mt.streamEnd,(()=>{t()})),this.stream.once(mt.streamSuccess,(()=>{e(),this._times.streamResponse=Nt(),this.video.play(),this.checkStatsInterval()}))})).catch((e=>{t(e)})),this._resumeAudioAfterPause()}))}close(){return new Promise((e=>{this._close().then((()=>{this.video&&this.video.clearView(),e()}))}))}_resumeAudioAfterPause(){this.lastVolume&&(this.volume=this.lastVolume)}_close(){return new Promise((e=>{this.stream&&(this.stream.destroy(),this.stream=null),this.demux&&(this.demux.destroy(),this.demux=null),this.decoderWorker&&(this.decoderWorker.destroy(),this.decoderWorker=null),this.audio&&(this.audio.destroy(),this.audio=null),this.clearCheckHeartTimeout(),this.clearCheckLoadingTimeout(),this.clearStatsInterval(),this.playing=!1,this.loading=!1,this.video&&(this.video.resetInit(),this.video.pause(!0)),this.releaseWakeLock(),this.resetStats(),this._audioTimestamp=0,this._videoTimestamp=0,this._times={playInitStart:"",playStart:"",streamStart:"",streamResponse:"",demuxStart:"",decodeStart:"",videoStart:"",playTimestamp:"",streamTimestamp:"",streamResponseTimestamp:"",demuxTimestamp:"",decodeTimestamp:"",videoTimestamp:"",allTimestamp:""},setTimeout((()=>{e()}),0)}))}pause(e=!1){return e?this.close():this._close()}mute(e){this.volume=e?0:.5,this.audio&&this.audio.mute(e)}resize(){this.$container.style.width=(this._opt.width||this.width)+"px",this.$container.style.height=(this._opt.height||this.height)+"px",this.video.resize()}_onlyMseOrWcsVideo(){return!1===this._opt.hasAudio&&(this._opt.useMSE||this._opt.useWCS&&!this._opt.useOffscreen)}checkHeart(){this.clearCheckHeartTimeout(),this.checkHeartTimeout()}checkHeartTimeout(){this._checkHeartTimeout&&this.clearCheckHeartTimeout(),this._checkHeartTimeout=setTimeout((()=>{if(this._checkHeartTimeout&&this.clearCheckHeartTimeout(),this.playing){if(0!==this._stats.fps)return;this.pause().then((()=>{this.emit(mt.timeout,mt.delayTimeout),this.emit(mt.delayTimeout)}))}}),1e3*this._opt.heartTimeout)}checkStatsInterval(){this._checkStatsInterval=setInterval((()=>{this.updateStats()}),1e3)}clearCheckHeartTimeout(){this._checkHeartTimeout&&(clearTimeout(this._checkHeartTimeout),this._checkHeartTimeout=null)}checkLoadingTimeout(){this._checkLoadingTimeout=setTimeout((()=>{this.playing||(this.clearCheckLoadingTimeout(),this.pause().then((()=>{this.emit(mt.timeout,mt.loadingTimeout),this.emit(mt.loadingTimeout)})).catch((()=>{})))}),1e3*this._opt.loadingTimeout)}clearCheckLoadingTimeout(){this._checkLoadingTimeout&&(clearTimeout(this._checkLoadingTimeout),this._checkLoadingTimeout=null)}clearStatsInterval(){this._checkStatsInterval&&(clearInterval(this._checkStatsInterval),this._checkStatsInterval=null)}handleRender(){this.loading&&(this.emit(mt.start),this.loading=!1),this.clearCheckLoadingTimeout(),this.playing||(this.playing=!0),this.checkHeart()}updateStats(e){e=e||{},this._startBpsTime||(this._startBpsTime=Nt()),qt(e.ts)&&(this._stats.ts=e.ts),qt(e.buf)&&(this._stats.buf=e.buf),e.fps&&(this._stats.fps+=1),e.abps&&(this._stats.abps+=e.abps),e.vbps&&(this._stats.vbps+=e.vbps);const t=Nt();t-this._startBpsTime<1e3||(this.emit(mt.stats,this._stats),this._stats.fps=0,this._stats.abps=0,this._stats.vbps=0,this._startBpsTime=t)}resetStats(){this._startBpsTime=null,this._stats={buf:0,fps:0,abps:0,vbps:0,ts:0}}enableWakeLock(){this._opt.keepScreenOn&&this.keepScreenOn&&this.keepScreenOn.enable()}releaseWakeLock(){this._opt.keepScreenOn&&this.keepScreenOn&&this.keepScreenOn.disable()}handlePlayToRenderTimes(){const e=this._times;e.playTimestamp=e.playStart-e.playInitStart,e.streamTimestamp=e.streamStart-e.playStart,e.streamResponseTimestamp=e.streamResponse-e.streamStart,e.demuxTimestamp=e.demuxStart-e.streamResponse,e.decodeTimestamp=e.decodeStart-e.demuxStart,e.videoTimestamp=e.videoStart-e.decodeStart,e.allTimestamp=e.videoStart-e.playInitStart,this.emit(mt.playToRenderTimes,e)}getOption(){return this._opt}emitError(e,t=""){Pi.report(51,{event:e,value:t}),this.emit(mt.error,e,t),this.emit(e,t)}}var Fi={exports:{}};!function(e,t){!function(t,i){e.exports=i()}(globalThis,(()=>(()=>{var e={343:e=>{var t=Object.prototype.hasOwnProperty,i="~";function n(){}function r(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function o(e,t,n,o,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var s=new r(n,o||e,a),d=i?i+t:t;return e._events[d]?e._events[d].fn?e._events[d]=[e._events[d],s]:e._events[d].push(s):(e._events[d]=s,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function s(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(i=!1)),s.prototype.eventNames=function(){var e,n,r=[];if(0===this._eventsCount)return r;for(n in e=this._events)t.call(e,n)&&r.push(i?n.slice(1):n);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},s.prototype.listeners=function(e){var t=i?i+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var r=0,o=n.length,a=new Array(o);r{i.d(t,{A:()=>n});const n=function(){function e(){this.mimeType=null,this.duration=null,this.hasAudio=null,this.hasVideo=null,this.audioCodec=null,this.videoCodec=null,this.audioDataRate=null,this.videoDataRate=null,this.audioSampleRate=null,this.audioChannelCount=null,this.width=null,this.height=null,this.fps=null,this.profile=null,this.level=null,this.refFrames=null,this.chromaFormat=null,this.sarNum=null,this.sarDen=null,this.metadata=null,this.segments=null,this.segmentCount=null,this.hasKeyframesIndex=null,this.keyframesIndex=null}return e.prototype.isComplete=function(){return!this.hasAudio||this.hasAudio&&null!=this.audioCodec&&null!=this.audioSampleRate&&this.audioChannelCount,!this.hasVideo||this.hasVideo&&null!=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&&this.sarDen,null!=this.mimeType},e.prototype.isSeekable=function(){return this.hasKeyframesIndex},e.prototype.getNearestKeyframe=function(e){if(null==this.keyframesIndex)return null;var t=this.keyframesIndex,i=this._search(t.times,e);return{index:i,milliseconds:t.times[i],fileposition:t.filepositions[i]}},e.prototype._search=function(e,t){var i=0,n=e.length-1,r=0,o=0,a=n;for(t=e[r]&&t{i.d(t,{$_:()=>n,EX:()=>o,EZ:()=>r,Sc:()=>a});var n=function(e,t,i,n,r){this.dts=e,this.pts=t,this.duration=i,this.originalDts=n,this.isSyncPoint=r,this.fileposition=null},r=function(){function e(){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}return e.prototype.appendSyncPoint=function(e){e.isSyncPoint=!0,this.syncPoints.push(e)},e}(),o=function(){function e(){this._list=[]}return e.prototype.clear=function(){this._list=[]},e.prototype.appendArray=function(e){var t=this._list;0!==e.length&&(t.length>0&&e[0].originalDts=t[r].dts&&e((null===(t=i[r].lastSample)||void 0===t?void 0:t.originalDts)||0)&&e=((null===(i=null===(t=n[o])||void 0===t?void 0:t.lastSample)||void 0===i?void 0:i.originalDts)||0)&&(o===n.length-1||o0&&(a=this._searchNearestSegmentBefore(r.originalBeginDts)+1),this._lastAppendLocation=a,this._list.splice(a,0,r)},e.prototype.getLastSegmentBefore=function(e){var t=this._searchNearestSegmentBefore(e);return t>=0?this._list[t]:null},e.prototype.getLastSampleBefore=function(e){var t=this.getLastSegmentBefore(e);return null!=t?t.lastSample:null},e.prototype.getLastSyncPointBefore=function(e){for(var t=this._searchNearestSegmentBefore(e),i=this._list[t].syncPoints;0===i.length&&t>0;)t--,i=this._list[t].syncPoints;return i.length>0?i[i.length-1]:null},e}()},976:(e,t,i)=>{i.d(t,{A:()=>Me});var n=i(413),r=i(502),o=i(620),a=i(825);function s(e,t,i){var n=e;if(t+i=128){t.push(String.fromCharCode(65535&o)),n+=2;continue}}else if(i[n]<240){if(s(i,n,2)&&(o=(15&i[n])<<12|(63&i[n+1])<<6|63&i[n+2])>=2048&&55296!=(63488&o)){t.push(String.fromCharCode(65535&o)),n+=3;continue}}else if(i[n]<248){var o;if(s(i,n,3)&&(o=(7&i[n])<<18|(63&i[n+1])<<12|(63&i[n+2])<<6|63&i[n+3])>65536&&o<1114112){o-=65536,t.push(String.fromCharCode(o>>>10|55296)),t.push(String.fromCharCode(1023&o|56320)),n+=4;continue}}t.push(String.fromCharCode(65533)),++n}return t.join("")};var l,c=i(713),h=(l=new ArrayBuffer(2),new DataView(l).setInt16(0,256,!0),256===new Int16Array(l)[0]);const u=function(){function e(){}return e.parseScriptData=function(t,i,n){var o={};try{var a=e.parseValue(t,i,n),s=e.parseValue(t,i+a.size,n-a.size);o[a.data]=s.data}catch(e){r.A.e("AMF",e.toString())}return o},e.parseObject=function(t,i,n){if(n<3)throw new c.j4("Data not enough when parse ScriptDataObject");var r=e.parseString(t,i,n),o=e.parseValue(t,i+r.size,n-r.size),a=o.objectEnd;return{data:{name:r.data,value:o.data},size:r.size+o.size,objectEnd:a}},e.parseVariable=function(t,i,n){return e.parseObject(t,i,n)},e.parseString=function(e,t,i){if(i<2)throw new c.j4("Data not enough when parse String");var n=new DataView(e,t,i).getUint16(0,!h);return{data:n>0?d(new Uint8Array(e,t+2,n)):"",size:2+n}},e.parseLongString=function(e,t,i){if(i<4)throw new c.j4("Data not enough when parse LongString");var n=new DataView(e,t,i).getUint32(0,!h);return{data:n>0?d(new Uint8Array(e,t+4,n)):"",size:4+n}},e.parseDate=function(e,t,i){if(i<10)throw new c.j4("Data size invalid when parse Date");var n=new DataView(e,t,i),r=n.getFloat64(0,!h),o=n.getInt16(8,!h);return{data:new Date(r+=60*o*1e3),size:10}},e.parseValue=function(t,i,n){if(n<1)throw new c.j4("Data not enough when parse Value");var o,a=new DataView(t,i,n),s=1,d=a.getUint8(0),l=!1;try{switch(d){case 0:o=a.getFloat64(1,!h),s+=8;break;case 1:o=!!a.getUint8(1),s+=1;break;case 2:var u=e.parseString(t,i+1,n-1);o=u.data,s+=u.size;break;case 3:o={};var A=0;for(9==(16777215&a.getUint32(n-4,!h))&&(A=3);s32)throw new c.Qn("ExpGolomb: readBits() bits exceeded max 32bits!");if(e<=this._current_word_bits_left){var t=this._current_word>>>32-e;return this._current_word<<=e,this._current_word_bits_left-=e,t}var i=this._current_word_bits_left?this._current_word:0;i>>>=32-this._current_word_bits_left;var n=e-this._current_word_bits_left;this._fillCurrentWord();var r=Math.min(n,this._current_word_bits_left),o=this._current_word>>>32-r;return this._current_word<<=r,this._current_word_bits_left-=r,i<>>e)return this._current_word<<=e,this._current_word_bits_left-=e,e;return this._fillCurrentWord(),e+this._skipLeadingZero()},e.prototype.readUEG=function(){var e=this._skipLeadingZero();return this.readBits(e+1)-1},e.prototype.readSEG=function(){var e=this.readUEG();return 1&e?e+1>>>1:-1*(e>>>1)},e}(),p=function(){function e(){}return e._ebsp2rbsp=function(e){for(var t=e,i=t.byteLength,n=new Uint8Array(i),r=0,o=0;o=2&&3===t[o]&&0===t[o-1]&&0===t[o-2]||(n[r]=t[o],r++);return new Uint8Array(n.buffer,0,r)},e.parseSPS=function(t){for(var i=t.subarray(1,4),n="avc1.",r=0;r<3;r++){var o=i[r].toString(16);o.length<2&&(o="0"+o),n+=o}var a=e._ebsp2rbsp(t),s=new A(a);s.readByte();var d=s.readByte();s.readByte();var l=s.readByte();s.readUEG();var c=e.getProfileString(d),h=e.getLevelString(l),u=1,p=420,_=8,f=8;if((100===d||110===d||122===d||244===d||44===d||83===d||86===d||118===d||128===d||138===d||144===d)&&(3===(u=s.readUEG())&&s.readBits(1),u<=3&&(p=[0,420,422,444][u]),_=s.readUEG()+8,f=s.readUEG()+8,s.readBits(1),s.readBool()))for(var m=3!==u?8:12,v=0;v0&&M<16?(R=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][M-1],O=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][M-1]):255===M&&(R=s.readByte()<<8|s.readByte(),O=s.readByte()<<8|s.readByte())}if(s.readBool()&&s.readBool(),s.readBool()&&(s.readBits(4),s.readBool()&&s.readBits(24)),s.readBool()&&(s.readUEG(),s.readUEG()),s.readBool()){var P=s.readBits(32),U=s.readBits(32);x=s.readBool(),I=(D=U)/(L=2*P)}}var F=1;1===R&&1===O||(F=R/O);var V=0,N=0;0===u?(V=1,N=2-w):(V=3===u?1:2,N=(1===u?2:1)*(2-w));var G=16*(E+1),W=16*(S+1)*(2-w);G-=(T+B)*V,W-=(k+C)*N;var j=Math.ceil(G*F);return s.destroy(),s=null,{codec_mimetype:n,profile_idc:d,level_idc:l,profile_string:c,level_string:h,chroma_format_idc:u,bit_depth:_,bit_depth_luma:_,bit_depth_chroma:f,ref_frames:b,chroma_format:p,chroma_format_string:e.getChromaFormatString(p),frame_rate:{fixed:x,fps:I,fps_den:L,fps_num:D},sar_ratio:{width:R,height:O},codec_size:{width:G,height:W},present_size:{width:j,height:W}}},e._skipScalingList=function(e,t){for(var i=8,n=8,r=0;r=2&&3===t[o]&&0===t[o-1]&&0===t[o-2]||(n[r]=t[o],r++);return new Uint8Array(n.buffer,0,r)},e.parseVPS=function(t){var i=e._ebsp2rbsp(t),n=new A(i);return n.readByte(),n.readByte(),n.readBits(4),n.readBits(2),n.readBits(6),{num_temporal_layers:n.readBits(3)+1,temporal_id_nested:n.readBool()}},e.parseSPS=function(t){var i=e._ebsp2rbsp(t),n=new A(i);n.readByte(),n.readByte();for(var r=0,o=0,a=0,s=0,d=(n.readBits(4),n.readBits(3)),l=(n.readBool(),n.readBits(2)),c=n.readBool(),h=n.readBits(5),u=n.readByte(),p=n.readByte(),_=n.readByte(),f=n.readByte(),m=n.readByte(),v=n.readByte(),g=n.readByte(),y=n.readByte(),b=n.readByte(),E=n.readByte(),S=n.readByte(),w=[],T=[],B=0;B0)for(B=d;B<8;B++)n.readBits(2);for(B=0;B1&&n.readSEG(),B=0;B0&&K<=16?(q=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][K-1],X=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][K-1]):255===K&&(q=n.readBits(16),X=n.readBits(16))}if(n.readBool()&&n.readBool(),n.readBool()&&(n.readBits(3),n.readBool(),n.readBool()&&(n.readByte(),n.readByte(),n.readByte())),n.readBool()&&(n.readUEG(),n.readUEG()),n.readBool(),n.readBool(),n.readBool(),n.readBool()&&(n.readUEG(),n.readUEG(),n.readUEG(),n.readUEG()),n.readBool()&&(Y=n.readBits(32),Z=n.readBits(32),n.readBool()&&n.readUEG(),n.readBool())){var J,ee,te=!1;for(J=n.readBool(),ee=n.readBool(),(J||ee)&&((te=n.readBool())&&(n.readByte(),n.readBits(5),n.readBool(),n.readBits(5)),n.readBits(4),n.readBits(4),te&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5)),B=0;B<=d;B++){var ie=n.readBool();$=ie;var ne=!1,re=1;ie||(ne=n.readBool());var oe=!1;if(ne?n.readSEG():oe=n.readBool(),oe||(re=n.readUEG()+1),J)for(N=0;N>3,o=!!(4&t[n]),a=!!(2&t[n]);t[n],n+=1,o&&(n+=1);var s=Number.POSITIVE_INFINITY;if(a){s=0;for(var d=0;s|=(127&t[n])<<7*d,128&t[n+=1];d++);}1===r&&(i=e.parseSeuqneceHeader(t.subarray(n,n+s))),n+=s}return i},e.parseSeuqneceHeader=function(t){var i=new A(t),n=i.readBits(3),r=(i.readBool(),i.readBool()),o=!0,a=0,s=0,d=[];if(r)d.push({operating_point_idc:0,level:i.readBits(5),tier:0});else{if(i.readBool()){var l=i.readBits(32),c=i.readBits(32),h=i.readBool();if(h){for(var u=0;0===i.readBits(1);)u+=1;u>=32||i.readBits(u)}a=c,s=l,o=h,i.readBool()&&(i.readBits(5),i.readBits(32),i.readBits(5),i.readBits(5))}for(var p=i.readBool(),_=i.readBits(5),f=0;f<=_;f++){var m=i.readBits(12),v=i.readBits(5),g=v>7?i.readBits(1):0;d.push({operating_point_idc:m,level:v,tier:g}),p&&i.readBool()&&i.readBits(4)}}var y=d[0],b=y.level,E=y.tier,S=i.readBits(4),w=i.readBits(4),T=i.readBits(S+1)+1,B=i.readBits(w+1)+1,k=!1;r||(k=i.readBool()),k&&(i.readBits(4),i.readBits(4)),i.readBool(),i.readBool(),i.readBool();var C=!1;r||(i.readBool(),i.readBool(),i.readBool(),i.readBool(),(C=i.readBool())&&(i.readBool(),i.readBool()),(i.readBool()||i.readBits(1))&&(i.readBool()||i.readBits(1)),C&&i.readBits(3)),i.readBool(),i.readBool(),i.readBool();var R=i.readBool(),O=8;O=2===n&&R?i.readBool()?12:10:R?10:8;var I=!1;1!==n&&(I=i.readBool()),i.readBool()&&(i.readBits(8),i.readBits(8),i.readBits(8));var x=1,D=1;return I?(i.readBits(1),x=1,D=1):(i.readBits(1),0===n?(x=1,D=1):1===n?(x=0,D=0):12===O?i.readBits(1)&&i.readBits(1):(x=1,D=0),x&&D&&i.readBits(2),i.readBits(1)),i.readBool(),i.destroy(),i=null,{codec_mimetype:"av01.".concat(n,".").concat(e.getLevelString(b,E),".").concat(O.toString(10).padStart(2,"0")),level:b,tier:E,level_string:e.getLevelString(b,E),profile_idc:n,profile_string:"".concat(n),bit_depth:O,ref_frames:1,chroma_format:e.getChromaFormat(I,x,D),chroma_format_string:e.getChromaFormatString(I,x,D),frame_rate:{fixed:o,fps:a/s,fps_den:s,fps_num:a},sar_ratio:{width:1,height:1},codec_size:{width:T,height:B},present_size:{width:1*T,height:B}}},e.getLevelString=function(e,t){return"".concat(e.toString(10).padStart(2,"0")).concat(0===t?"M":"H")},e.getChromaFormat=function(e,t,i){return e?0:0===t&&0===i?3:1===t&&0===i?2:1===t&&1===i?1:Number.NaN},e.getChromaFormatString=function(e,t,i){return e?"4:0:0":0===t&&0===i?"4:4:4":1===t&&0===i?"4:2:2":1===t&&1===i?"4:2:0":"Unknown"},e}();var E=function(){function e(e,t){this.TAG="FLVDemuxer",this._config=t,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null,this._dataOffset=e.dataOffset,this._firstParse=!0,this._dispatch=!1,this._hasAudio=e.hasAudioTrack,this._hasVideo=e.hasVideoTrack,this._hasAudioFlagOverrided=!1,this._hasVideoFlagOverrided=!1,this._audioInitialMetadataDispatched=!1,this._videoInitialMetadataDispatched=!1,this._mediaInfo=new a.A,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(){var e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),256===new Int16Array(e)[0]}()}return e.prototype.destroy=function(){this._mediaInfo=null,this._metadata=null,this._audioMetadata=null,this._videoMetadata=null,this._videoTrack=null,this._audioTrack=null,this._onError=null,this._onMediaInfo=null,this._onMetaDataArrived=null,this._onScriptDataArrived=null,this._onTrackMetadata=null,this._onDataAvailable=null},e.probe=function(e){var t=new Uint8Array(e);if(t.byteLength<9)return{needMoreData:!0};var i={match:!1};if(70!==t[0]||76!==t[1]||86!==t[2]||1!==t[3])return i;var n,r=(4&t[4])>>>2!=0,o=!!(1&t[4]),a=(n=t)[5]<<24|n[6]<<16|n[7]<<8|n[8];return a<9?i:{match:!0,consumed:a,dataOffset:a,hasAudioTrack:r,hasVideoTrack:o}},e.prototype.bindDataSource=function(e){return e.onDataArrival=this.parseChunks.bind(this),this},Object.defineProperty(e.prototype,"onTrackMetadata",{get:function(){return this._onTrackMetadata},set:function(e){this._onTrackMetadata=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onMediaInfo",{get:function(){return this._onMediaInfo},set:function(e){this._onMediaInfo=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onMetaDataArrived",{get:function(){return this._onMetaDataArrived},set:function(e){this._onMetaDataArrived=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onScriptDataArrived",{get:function(){return this._onScriptDataArrived},set:function(e){this._onScriptDataArrived=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onError",{get:function(){return this._onError},set:function(e){this._onError=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onDataAvailable",{get:function(){return this._onDataAvailable},set:function(e){this._onDataAvailable=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"timestampBase",{get:function(){return this._timestampBase},set:function(e){this._timestampBase=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"overridedDuration",{get:function(){return this._duration},set:function(e){this._durationOverrided=!0,this._duration=e,this._mediaInfo&&(this._mediaInfo.duration=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"overridedHasAudio",{set:function(e){this._hasAudioFlagOverrided=!0,this._hasAudio=e,this._mediaInfo&&(this._mediaInfo.hasAudio=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"overridedHasVideo",{set:function(e){this._hasVideoFlagOverrided=!0,this._hasVideo=e,this._mediaInfo&&(this._mediaInfo.hasVideo=e)},enumerable:!1,configurable:!0}),e.prototype.resetMediaInfo=function(){this._mediaInfo=new a.A},e.prototype._isInitialMetadataDispatched=function(){return this._hasAudio&&this._hasVideo?this._audioInitialMetadataDispatched&&this._videoInitialMetadataDispatched:this._hasAudio&&!this._hasVideo?this._audioInitialMetadataDispatched:!(this._hasAudio||!this._hasVideo)&&this._videoInitialMetadataDispatched},e.prototype.parseChunks=function(t,i){var n,o;if(!(this._onError&&this._onMediaInfo&&this._onTrackMetadata&&this._onDataAvailable))throw new c.j4("Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");var a=0,s=this._littleEndian;if(0===i){if(!(t.byteLength>13))return 0;var d=e.probe(t);a=(null==d?void 0:d.dataOffset)||0}for(this._firstParse&&(this._firstParse=!1,i+a!==this._dataOffset&&r.A.w(this.TAG,"First time parsing but chunk byteStart invalid!"),0!==(l=new DataView(t,a)).getUint32(0,!s)&&r.A.w(this.TAG,"PrevTagSize0 !== 0 !!!"),a+=4);at.byteLength)break;var h=l.getUint8(0),u=16777215&l.getUint32(0,!s);if(a+11+u+4>t.byteLength)break;if(8===h||9===h||18===h){var A=l.getUint8(4),p=l.getUint8(5),_=l.getUint8(6)|p<<8|A<<16|l.getUint8(7)<<24;16777215&l.getUint32(7,!s)&&r.A.w(this.TAG,"Meet tag which has StreamID != 0!");var f=a+11;switch(h){case 8:this._parseAudioData(t,f,u,_);break;case 9:this._parseVideoData(t,f,u,_,i+a);break;case 18:this._parseScriptData(t,f,u)}var m=l.getUint32(11+u,!s);m!==11+u&&r.A.w(this.TAG,"Invalid PrevTagSize ".concat(m)),a+=11+u+4}else r.A.w(this.TAG,"Unsupported tag type ".concat(h,", skipped")),a+=11+u+4}return this._isInitialMetadataDispatched()&&this._dispatch&&((null===(n=this._audioTrack)||void 0===n?void 0:n.length)||(null===(o=this._videoTrack)||void 0===o?void 0:o.length))&&this._onDataAvailable(this._audioTrack,this._videoTrack),a},e.prototype._parseScriptData=function(e,t,i){var n,o,a,s=u.parseScriptData(e,t,i);if(s.hasOwnProperty("onMetaData")){if(null==s.onMetaData||"object"!=typeof s.onMetaData)return void r.A.w(this.TAG,"Invalid onMetaData structure!");this._metadata&&r.A.w(this.TAG,"Found another onMetaData tag!"),this._metadata=s;var d=null===(n=this._metadata)||void 0===n?void 0:n.onMetaData;if(this._onMetaDataArrived&&this._onMetaDataArrived(Object.assign({},d)),"boolean"==typeof(null==d?void 0:d.hasAudio)&&(this._hasAudioFlagOverrided||(this._hasAudio=d.hasAudio,this._mediaInfo&&(this._mediaInfo.hasAudio=this._hasAudio))),"boolean"==typeof(null==d?void 0:d.hasVideo)&&(this._hasVideoFlagOverrided||(this._hasVideo=d.hasVideo,this._mediaInfo&&(this._mediaInfo.hasVideo=this._hasVideo))),"number"==typeof(null==d?void 0:d.audiodatarate)&&this._mediaInfo&&(this._mediaInfo.audioDataRate=d.audiodatarate),"number"==typeof(null==d?void 0:d.videodatarate)&&this._mediaInfo&&(this._mediaInfo.videoDataRate=d.videodatarate),"number"==typeof(null==d?void 0:d.width)&&this._mediaInfo&&(this._mediaInfo.width=d.width),"number"==typeof(null==d?void 0:d.height)&&this._mediaInfo&&(this._mediaInfo.height=d.height),"number"==typeof(null==d?void 0:d.duration)){if(!this._durationOverrided){var l=Math.floor(d.duration*this._timescale);this._duration=l,this._mediaInfo&&(this._mediaInfo.duration=l)}}else this._mediaInfo&&(this._mediaInfo.duration=0);if("number"==typeof(null==d?void 0:d.framerate)){var c=Math.floor(1e3*d.framerate);if(c>0){var h=c/1e3;this._referenceFrameRate.fixed=!0,this._referenceFrameRate.fps=h,this._referenceFrameRate.fps_num=c,this._referenceFrameRate.fps_den=1e3,this._mediaInfo&&(this._mediaInfo.fps=h)}}if("object"==typeof(null==d?void 0:d.keyframes)){this._mediaInfo&&(this._mediaInfo.hasKeyframesIndex=!0);var A=d.keyframes;this._mediaInfo&&(this._mediaInfo.keyframesIndex=this._parseKeyframesIndex(A)),d.keyframes=null}else this._mediaInfo&&(this._mediaInfo.hasKeyframesIndex=!1);this._dispatch=!1,this._mediaInfo&&(this._mediaInfo.metadata=d),r.A.v(this.TAG,"Parsed onMetaData"),(null===(o=this._mediaInfo)||void 0===o?void 0:o.isComplete())&&(null===(a=this._onMediaInfo)||void 0===a||a.call(this,this._mediaInfo))}Object.keys(s).length>0&&this._onScriptDataArrived&&this._onScriptDataArrived(Object.assign({},s))},e.prototype._parseKeyframesIndex=function(e){for(var t=[],i=[],n=1;n>>4;if(2===m||10===m){var v=0,g=(12&f)>>>2;if(g>=0&&g<=4){v=this._flvSoundRateTable[g];var b=1&f,E=this._audioMetadata,S=this._audioTrack;if(E||(!1!==this._hasAudio||this._hasAudioFlagOverrided||(this._hasAudio=!0,this._mediaInfo&&(this._mediaInfo.hasAudio=!0)),(E=this._audioMetadata={}).type="audio",E.id=null==S?void 0:S.id,E.timescale=this._timescale,E.duration=this._duration,E.audioSampleRate=v,E.channelCount=0===b?1:2),10===m){var w=this._parseAACAudioData(e,t+1,i-1);if(void 0===w)return;if(0===(null==w?void 0:w.packetType)){if(null==E?void 0:E.config){if(y(w.data.config,null==E?void 0:E.config))return;r.A.w(this.TAG,"AudioSpecificConfig has been changed, re-generate initialization segment")}var T=w.data;E.audioSampleRate=null==T?void 0:T.samplingRate,E.channelCount=null==T?void 0:T.channelCount,E.codec=null==T?void 0:T.codec,E.originalCodec=null==T?void 0:T.originalCodec,E.config=null==T?void 0:T.config,E.refSampleDuration=1024/E.audioSampleRate*E.timescale,r.A.v(this.TAG,"Parsed AudioSpecificConfig"),this._isInitialMetadataDispatched()?this._dispatch&&((null===(s=this._audioTrack)||void 0===s?void 0:s.length)||(null===(d=this._videoTrack)||void 0===d?void 0:d.length))&&(null===(l=this._onDataAvailable)||void 0===l||l.call(this,this._audioTrack,this._videoTrack)):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,null===(c=this._onTrackMetadata)||void 0===c||c.call(this,"audio",E),(C=this._mediaInfo).audioCodec=E.originalCodec||"",C.audioSampleRate=E.audioSampleRate,C.audioChannelCount=E.channelCount,C.hasVideo?null!=C.videoCodec&&(C.mimeType='video/x-flv; codecs="'+C.videoCodec+","+C.audioCodec+'"'):C.mimeType='video/x-flv; codecs="'+C.audioCodec+'"',(null==C?void 0:C.isComplete())&&(null===(h=this._onMediaInfo)||void 0===h||h.call(this,C))}else if(1===w.packetType){var B=this._timestampBase+n,k={unit:w.data,length:w.data.byteLength,dts:B,pts:B};S&&(null==S||S.samples.push(k),S.length+=(null===(u=null==w?void 0:w.data)||void 0===u?void 0:u.length)||0)}else r.A.e(this.TAG,"Flv: Unsupported AAC data type ".concat(w.packetType))}else if(2===m){if(!E.codec){var C;if(void 0===(T=this._parseMP3AudioData(e,t+1,i-1,!0)))return;E.audioSampleRate=T.samplingRate,E.channelCount=T.channelCount,E.codec=T.codec,E.originalCodec=T.originalCodec,E.refSampleDuration=1152/E.audioSampleRate*E.timescale,r.A.v(this.TAG,"Parsed MPEG Audio Frame Header"),this._audioInitialMetadataDispatched=!0,null===(A=this._onTrackMetadata)||void 0===A||A.call(this,"audio",E),(C=this._mediaInfo).audioCodec=E.codec,C.audioSampleRate=E.audioSampleRate,C.audioChannelCount=E.channelCount,C.audioDataRate=T.bitRate,(null==C?void 0:C.hasVideo)?null!=C.videoCodec&&(C.mimeType='video/x-flv; codecs="'+C.videoCodec+","+C.audioCodec+'"'):C.mimeType='video/x-flv; codecs="'+C.audioCodec+'"',C.isComplete()&&(null===(p=this._onMediaInfo)||void 0===p||p.call(this,C))}var R=this._parseMP3AudioData(e,t+1,i-1,!1);if(void 0===R)return;B=this._timestampBase+n;var O={unit:R,length:R.byteLength,dts:B,pts:B};null==S||S.samples.push(O),S&&(S.length+=R.length)}}else null===(a=this._onError)||void 0===a||a.call(this,_.A.FORMAT_ERROR,"Flv: Invalid audio sample rate idx: "+g)}else null===(o=this._onError)||void 0===o||o.call(this,_.A.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec idx: "+m)}},e.prototype._parseAACAudioData=function(e,t,i){if(!(i<=1)){var n={},o=new Uint8Array(e,t,i);return n.packetType=o[0],0===o[0]?n.data=this._parseAACAudioSpecificConfig(e,t+1,i-1):n.data=o.subarray(1),n}r.A.w(this.TAG,"Flv: Invalid AAC packet, missing AACPacketType or/and Data!")},e.prototype._parseAACAudioSpecificConfig=function(e,t,i){var n,r,o,a,s=new Uint8Array(e,t,i),d=null,l=0,c=null;if(l=o=s[0]>>>3,(a=(7&s[0])<<1|s[1]>>>7)<0||a>=this._mpegSamplingRates.length)null===(n=this._onError)||void 0===n||n.call(this,_.A.FORMAT_ERROR,"Flv: AAC invalid sampling frequency index!");else{var h=this._mpegSamplingRates[a],u=(120&s[1])>>>3;if(!(u<0||u>=8)){5===l&&(c=(7&s[1])<<1|s[2]>>>7,s[2]);var A=self.navigator.userAgent.toLowerCase();return A.includes("firefox")?a>=6?(l=5,d=new Array(4),c=a-3):(l=2,d=new Array(2),c=a):A.includes("android")?(l=2,d=new Array(2),c=a):(l=5,c=a,d=new Array(4),a>=6?c=a-3:1===u&&(l=2,d=new Array(2),c=a)),d[0]=l<<3,d[0]|=(15&a)>>>1,d[1]=(15&a)<<7,d[1]|=(15&u)<<3,5===l&&(d[1]|=(15&c)>>>1,d[2]=(1&c)<<7,d[2]|=8,d[3]=0),{config:d,samplingRate:h,channelCount:u,codec:"mp4a.40."+l,originalCodec:"mp4a.40."+o}}null===(r=this._onError)||void 0===r||r.call(this,_.A.FORMAT_ERROR,"Flv: AAC invalid channel configuration")}},e.prototype._parseMP3AudioData=function(e,t,i,n){if(!(i<4)){this._littleEndian;var o,a=new Uint8Array(e,t,i);if(n){if(255!==a[0])return;var s=a[1]>>>3&3,d=(6&a[1])>>1,l=(240&a[2])>>>4,c=(12&a[2])>>>2,h=3&~(a[3]>>>6)?2:1,u=0,A=0;switch(s){case 0:u=this._mpegAudioV25SampleRateTable[c];break;case 2:u=this._mpegAudioV20SampleRateTable[c];break;case 3:u=this._mpegAudioV10SampleRateTable[c]}switch(d){case 1:l>>4;if(128&d){var c=15&d,h=String.fromCharCode.apply(String,function(e,t,i){if(2===arguments.length)for(var n,r=0,o=t.length;r0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){r={error:e}}finally{try{n&&!n.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}return a}(new Uint8Array(e,t,i).slice(1,5)),!1));"hvc1"===h?this._parseEnhancedHEVCVideoPacket(e,t+5,i-5,n,o,l,c):"av01"===h?this._parseEnhancedAV1VideoPacket(e,t+5,i-5,n,o,l,c):null===(s=this._onError)||void 0===s||s.call(this,_.A.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: ".concat(h))}else{var u=15&d;7===u?this._parseAVCVideoPacket(e,t+1,i-1,n,o,l):12===u?this._parseHEVCVideoPacket(e,t+1,i-1,n,o,l):null===(a=this._onError)||void 0===a||a.call(this,_.A.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: ".concat(u))}}},e.prototype._parseAVCVideoPacket=function(e,t,i,n,o,a){var s;if(i<4)r.A.w(this.TAG,"Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime");else{var d=this._littleEndian,l=new DataView(e,t,i),c=l.getUint8(0),h=(16777215&l.getUint32(0,!d))<<8>>8;0===c?this._parseAVCDecoderConfigurationRecord(e,t+4,i-4):1===c?this._parseAVCVideoData(e,t+4,i-4,n,o,a,h):2===c||null===(s=this._onError)||void 0===s||s.call(this,_.A.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(c))}},e.prototype._parseHEVCVideoPacket=function(e,t,i,n,o,a){var s;if(i<4)r.A.w(this.TAG,"Flv: Invalid HEVC packet, missing HEVCPacketType or/and CompositionTime");else{var d=this._littleEndian,l=new DataView(e,t,i),c=l.getUint8(0),h=(16777215&l.getUint32(0,!d))<<8>>8;0===c?this._parseHEVCDecoderConfigurationRecord(e,t+4,i-4):1===c?this._parseHEVCVideoData(e,t+4,i-4,n,o,a,h):2===c||null===(s=this._onError)||void 0===s||s.call(this,_.A.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(c))}},e.prototype._parseEnhancedHEVCVideoPacket=function(e,t,i,n,r,o,a){var s,d=this._littleEndian,l=new DataView(e,t,i);if(0===a)this._parseHEVCDecoderConfigurationRecord(e,t,i);else if(1===a){var c=(4294967040&l.getUint32(0,!d))>>8;this._parseHEVCVideoData(e,t+3,i-3,n,r,o,c)}else 3===a?this._parseHEVCVideoData(e,t,i,n,r,o,0):2===a||null===(s=this._onError)||void 0===s||s.call(this,_.A.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(a))},e.prototype._parseEnhancedAV1VideoPacket=function(e,t,i,n,r,o,a){var s,d;this._littleEndian,0===a?this._parseAV1CodecConfigurationRecord(e,t,i):1===a?this._parseAV1VideoData(e,t,i,n,r,o,0):5===a?null===(s=this._onError)||void 0===s||s.call(this,_.A.FORMAT_ERROR,"Flv: Not Suported MP2T AV1 video packet type ".concat(a)):2===a||null===(d=this._onError)||void 0===d||d.call(this,_.A.FORMAT_ERROR,"Flv: Invalid video packet type ".concat(a))},e.prototype._parseAVCDecoderConfigurationRecord=function(e,t,i){var n,o,a,s,d,l,c,h,u,A,f;if(i<7)r.A.w(this.TAG,"Flv: Invalid AVCDecoderConfigurationRecord, lack of data!");else{var m=this._videoMetadata,v=this._videoTrack,g=this._littleEndian,b=new DataView(e,t,i);if(m){if(void 0!==m.avcc){var E=new Uint8Array(e,t,i);if(y(E,m.avcc))return;r.A.w(this.TAG,"AVCDecoderConfigurationRecord has been changed, re-generate initialization segment")}}else!1!==this._hasVideo||this._hasVideoFlagOverrided||(this._hasVideo=!0,this._mediaInfo&&(this._mediaInfo.hasVideo=!0)),(m=this._videoMetadata={}).type="video",m.id=null==v?void 0:v.id,m.timescale=this._timescale,m.duration=this._duration;var S=b.getUint8(0),w=b.getUint8(1);if(b.getUint8(2),b.getUint8(3),1===S&&0!==w)if(this._naluLengthSize=1+(3&b.getUint8(4)),3===this._naluLengthSize||4===this._naluLengthSize){var T=31&b.getUint8(5);if(0!==T){T>1&&r.A.w(this.TAG,"Flv: Strange AVCDecoderConfigurationRecord: SPS Count = ".concat(T));for(var B=6,k=0;k1&&r.A.w(this.TAG,"Flv: Strange AVCDecoderConfigurationRecord: PPS Count = ".concat(F)),B++,k=0;k=i){r.A.w(this.TAG,"Malformed Nalu near timestamp ".concat(p,", offset = ").concat(u,", dataSize = ").concat(i));break}var f=l.getUint32(u,!d);if(3===A&&(f>>>=8),f>i-A)return void r.A.w(this.TAG,"Malformed Nalus near timestamp ".concat(p,", NaluSize > DataSize!"));var m=31&l.getUint8(u+A);5===m&&(_=!0);var v=new Uint8Array(e,t+u,A+f),g={type:m,data:v};c.push(g),h+=v.byteLength,u+=A+f}if(c.length){var y=this._videoTrack,b={units:c,length:h,isKeyframe:_,dts:p,cts:s,pts:p+s};_&&(b.fileposition=o),y&&(y.samples.push(b),y.length+=h)}},e.prototype._parseHEVCVideoData=function(e,t,i,n,o,a,s){for(var d=this._littleEndian,l=new DataView(e,t,i),c=[],h=0,u=0,A=this._naluLengthSize,p=this._timestampBase+n,_=1===a;u=i){r.A.w(this.TAG,"Malformed Nalu near timestamp ".concat(p,", offset = ").concat(u,", dataSize = ").concat(i));break}var f=l.getUint32(u,!d);if(3===A&&(f>>>=8),f>i-A)return void r.A.w(this.TAG,"Malformed Nalus near timestamp ".concat(p,", NaluSize > DataSize!"));var m=31&l.getUint8(u+A);19!==m&&20!==m||(_=!0);var v=new Uint8Array(e,t+u,A+f),g={type:m,data:v};c.push(g),h+=v.byteLength,u+=A+f}if(c.length){var y=this._videoTrack,b={units:c,length:h,isKeyframe:_,dts:p,cts:s,pts:p+s};_&&(b.fileposition=o),y&&(null==y||y.samples.push(b),y.length+=h)}},e.prototype._parseAV1VideoData=function(e,t,i,n,r,o,a){this._littleEndian;var s,d=[],l=this._timestampBase+n,c=1===o;if(s=i,d.push({unitType:0,data:new Uint8Array(e,t+0,i)}),d.length){var h=this._videoTrack,u={units:d,length:s,isKeyframe:c,dts:l,cts:a,pts:l+a};c&&(u.fileposition=r),h&&(null==h||h.samples.push(u),h.length+=s)}},e}();const S=E,w=function(){function e(){}return e.prototype.destroy=function(){this.onError=null,this.onMediaInfo=null,this.onMetaDataArrived=null,this.onTrackMetadata=null,this.onDataAvailable=null,this.onTimedID3Metadata=null,this.onSMPTE2038Metadata=null,this.onSCTE35Metadata=null,this.onPESPrivateData=null,this.onPESPrivateDataDescriptor=null},e}();var T,B=function(){this.program_pmt_pid={}};!function(e){e[e.kMPEG1Audio=3]="kMPEG1Audio",e[e.kMPEG2Audio=4]="kMPEG2Audio",e[e.kPESPrivateData=6]="kPESPrivateData",e[e.kADTSAAC=15]="kADTSAAC",e[e.kLOASAAC=17]="kLOASAAC",e[e.kAC3=129]="kAC3",e[e.kEAC3=135]="kEAC3",e[e.kID3=21]="kID3",e[e.kSCTE35=134]="kSCTE35",e[e.kH264=27]="kH264",e[e.kH265=36]="kH265"}(T||(T={}));var k,C=function(){this.pid_stream_type={},this.common_pids={h264:void 0,h265:void 0,adts_aac:void 0,loas_aac:void 0,opus:void 0,ac3:void 0,eac3:void 0,mp3:void 0},this.pes_private_data_pids={},this.timed_id3_pids={},this.scte_35_pids={},this.smpte2038_pids={}},R=function(){},O=function(){},I=function(){this.slices=[],this.total_length=0,this.expected_length=0,this.file_position=0,this.random_access_indicator=0};!function(e){e[e.kUnspecified=0]="kUnspecified",e[e.kSliceNonIDR=1]="kSliceNonIDR",e[e.kSliceDPA=2]="kSliceDPA",e[e.kSliceDPB=3]="kSliceDPB",e[e.kSliceDPC=4]="kSliceDPC",e[e.kSliceIDR=5]="kSliceIDR",e[e.kSliceSEI=6]="kSliceSEI",e[e.kSliceSPS=7]="kSliceSPS",e[e.kSlicePPS=8]="kSlicePPS",e[e.kSliceAUD=9]="kSliceAUD",e[e.kEndOfSequence=10]="kEndOfSequence",e[e.kEndOfStream=11]="kEndOfStream",e[e.kFiller=12]="kFiller",e[e.kSPSExt=13]="kSPSExt",e[e.kReserved0=14]="kReserved0"}(k||(k={}));var x,D,L=function(){},M=function(e){var t=e.data.byteLength;this.type=e.type,this.data=new Uint8Array(4+t),new DataView(this.data.buffer).setUint32(0,t),this.data.set(e.data,4)},P=function(){function e(e){this.TAG="H264AnnexBParser",this.current_startcode_offset_=0,this.eof_flag_=!1,this.data_=e,this.current_startcode_offset_=this.findNextStartCodeOffset(0),this.eof_flag_&&r.A.e(this.TAG,"Could not find H264 startcode until payload end!")}return e.prototype.findNextStartCodeOffset=function(e){for(var t=e,i=this.data_;;){if(t+3>=i.byteLength)return this.eof_flag_=!0,i.byteLength;var n=i[t+0]<<24|i[t+1]<<16|i[t+2]<<8|i[t+3],r=i[t+0]<<16|i[t+1]<<8|i[t+2];if(1===n||1===r)return t;t++}},e.prototype.readNextNaluPayload=function(){for(var e=this.data_,t=null;null==t&&!this.eof_flag_;){var i=this.current_startcode_offset_,n=31&e[i+=1==(e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3])?4:3],r=(128&e[i])>>>7,o=this.findNextStartCodeOffset(i);if(this.current_startcode_offset_=o,!(n>=k.kReserved0)&&0===r){var a=e.subarray(i,o);(t=new L).type=n,t.data=a}}return t},e}(),U=function(){function e(e,t,i){var n=8+e.byteLength+1+2+t.byteLength,r=!1;66!==e[3]&&77!==e[3]&&88!==e[3]&&(r=!0,n+=4);var o=this.data=new Uint8Array(n);o[0]=1,o[1]=e[1],o[2]=e[2],o[3]=e[3],o[4]=255,o[5]=225;var a=e.byteLength;o[6]=a>>>8,o[7]=255&a;var s=8;o.set(e,8),o[s+=a]=1;var d=t.byteLength;o[s+1]=d>>>8,o[s+2]=255&d,o.set(t,s+3),s+=3+d,r&&(o[s]=252|i.chroma_format_idc,o[s+1]=248|i.bit_depth_luma-8,o[s+2]=248|i.bit_depth_chroma-8,o[s+3]=0,s+=4)}return e.prototype.getData=function(){return this.data},e}();!function(e){e[e.kNull=0]="kNull",e[e.kAACMain=1]="kAACMain",e[e.kAAC_LC=2]="kAAC_LC",e[e.kAAC_SSR=3]="kAAC_SSR",e[e.kAAC_LTP=4]="kAAC_LTP",e[e.kAAC_SBR=5]="kAAC_SBR",e[e.kAAC_Scalable=6]="kAAC_Scalable",e[e.kLayer1=32]="kLayer1",e[e.kLayer2=33]="kLayer2",e[e.kLayer3=34]="kLayer3"}(x||(x={})),function(e){e[e.k96000Hz=0]="k96000Hz",e[e.k88200Hz=1]="k88200Hz",e[e.k64000Hz=2]="k64000Hz",e[e.k48000Hz=3]="k48000Hz",e[e.k44100Hz=4]="k44100Hz",e[e.k32000Hz=5]="k32000Hz",e[e.k24000Hz=6]="k24000Hz",e[e.k22050Hz=7]="k22050Hz",e[e.k16000Hz=8]="k16000Hz",e[e.k12000Hz=9]="k12000Hz",e[e.k11025Hz=10]="k11025Hz",e[e.k8000Hz=11]="k8000Hz",e[e.k7350Hz=12]="k7350Hz"}(D||(D={}));var F,V,N=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],G=(F=function(e,t){return F=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},F(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}F(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),W=function(){},j=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return G(t,e),t}(W),Q=function(){function e(e){this.TAG="AACADTSParser",this.data_=e,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&r.A.e(this.TAG,"Could not found ADTS syncword until payload end")}return e.prototype.findNextSyncwordOffset=function(e){for(var t=e,i=this.data_;;){if(t+7>=i.byteLength)return this.eof_flag_=!0,i.byteLength;if(4095==(i[t+0]<<8|i[t+1])>>>4)return t;t++}},e.prototype.readNextAACFrame=function(){for(var e=this.data_,t=null;null==t&&!this.eof_flag_;){var i=this.current_syncword_offset_,n=(8&e[i+1])>>>3,r=(6&e[i+1])>>>1,o=1&e[i+1],a=(192&e[i+2])>>>6,s=(60&e[i+2])>>>2,d=(1&e[i+2])<<2|(192&e[i+3])>>>6,l=(3&e[i+3])<<11|e[i+4]<<3|(224&e[i+5])>>>5;if(e[i+6],i+l>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var c=1===o?7:9,h=l-c;i+=c;var u=this.findNextSyncwordOffset(i+h);if(this.current_syncword_offset_=u,(0===n||1===n)&&0===r){var A=e.subarray(i,i+h);(t=new W).audio_object_type=a+1,t.sampling_freq_index=s,t.sampling_frequency=N[s],t.channel_config=d,t.data=A}}return t},e.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},e.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},e}(),z=function(){function e(e){this.TAG="AACLOASParser",this.data_=e,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&r.A.e(this.TAG,"Could not found LOAS syncword until payload end")}return e.prototype.findNextSyncwordOffset=function(e){for(var t=e,i=this.data_;;){if(t+1>=i.byteLength)return this.eof_flag_=!0,i.byteLength;if(695==(i[t+0]<<3|i[t+1]>>>5))return t;t++}},e.prototype.getLATMValue=function(e){for(var t=e.readBits(2),i=0,n=0;n<=t;n++)i<<=8,i|=e.readByte();return i},e.prototype.readNextAACFrame=function(e){for(var t=this.data_,i=null;null==i&&!this.eof_flag_;){var n=this.current_syncword_offset_,o=(31&t[n+1])<<8|t[n+2];if(n+3+o>=this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var a=new A(t.subarray(n+3,n+3+o)),s=null;if(a.readBool()){if(null==e){r.A.w(this.TAG,"StreamMuxConfig Missing"),this.current_syncword_offset_=this.findNextSyncwordOffset(n+3+o),a.destroy();continue}s=e}else{var d=a.readBool();if(d&&a.readBool()){r.A.e(this.TAG,"audioMuxVersionA is Not Supported"),a.destroy();break}if(d&&this.getLATMValue(a),!a.readBool()){r.A.e(this.TAG,"allStreamsSameTimeFraming zero is Not Supported"),a.destroy();break}if(0!==a.readBits(6)){r.A.e(this.TAG,"more than 2 numSubFrames Not Supported"),a.destroy();break}if(0!==a.readBits(4)){r.A.e(this.TAG,"more than 2 numProgram Not Supported"),a.destroy();break}if(0!==a.readBits(3)){r.A.e(this.TAG,"more than 2 numLayer Not Supported"),a.destroy();break}var l=d?this.getLATMValue(a):0,c=a.readBits(5);l-=5;var h=a.readBits(4);l-=4;var u=a.readBits(4);l-=4,a.readBits(3),(l-=3)>0&&a.readBits(l);var p=a.readBits(3);if(0!==p){r.A.e(this.TAG,"frameLengthType = ".concat(p,". Only frameLengthType = 0 Supported")),a.destroy();break}a.readByte();var _=a.readBool();if(_)if(d)this.getLATMValue(a);else for(;;){8;var f=a.readBool();if(a.readByte(),!f)break}a.readBool()&&a.readByte(),(s=new j).audio_object_type=c,s.sampling_freq_index=h,s.sampling_frequency=N[s.sampling_freq_index],s.channel_config=u,s.other_data_present=_}for(var m=0;;){var v=a.readByte();if(m+=v,255!==v)break}for(var g=new Uint8Array(m),y=0;y=6?(n=5,t=new Array(4),a=r-3):(n=2,t=new Array(2),a=r):s.includes("android")?(n=2,t=new Array(2),a=r):(n=5,a=r,t=new Array(4),r>=6?a=r-3:1===o&&(n=2,t=new Array(2),a=r)),t[0]=n<<3,t[0]|=(15&r)>>>1,t[1]=(15&r)<<7,t[1]|=(15&o)<<3,5===n&&(t[1]|=(15&a)>>>1,t[2]=(1&a)<<7,t[2]|=8,t[3]=0),this.config=t,this.sampling_rate=N[r],this.channel_count=o,this.codec_mimetype="mp4a.40."+n.toString(),this.original_codec_mimetype="mp4a.40."+i.toString()},q=function(){},X=function(){};!function(e){e[e.kSpliceNull=0]="kSpliceNull",e[e.kSpliceSchedule=4]="kSpliceSchedule",e[e.kSpliceInsert=5]="kSpliceInsert",e[e.kTimeSignal=6]="kTimeSignal",e[e.kBandwidthReservation=7]="kBandwidthReservation",e[e.kPrivateCommand=255]="kPrivateCommand"}(V||(V={}));var $,Y=function(e){var t=e.readBool();return t?(e.readBits(6),{time_specified_flag:t,pts_time:4*e.readBits(31)+e.readBits(2)}):(e.readBits(7),{time_specified_flag:t})},Z=function(e){var t=e.readBool();return e.readBits(6),{auto_return:t,duration:4*e.readBits(31)+e.readBits(2)}},K=function(e,t){var i=t.readBits(8);return e?{component_tag:i}:{component_tag:i,splice_time:Y(t)}},J=function(e){return{component_tag:e.readBits(8),utc_splice_time:e.readBits(32)}},ee=function(e){var t=e.readBits(32),i=e.readBool();e.readBits(7);var n={splice_event_id:t,splice_event_cancel_indicator:i};if(i)return n;if(n.out_of_network_indicator=e.readBool(),n.program_splice_flag=e.readBool(),n.duration_flag=e.readBool(),e.readBits(5),n.program_splice_flag)n.utc_splice_time=e.readBits(32);else{n.component_count=e.readBits(8),n.components=[];for(var r=0;r=i.byteLength)return this.eof_flag_=!0,i.byteLength;var n=i[t+0]<<24|i[t+1]<<16|i[t+2]<<8|i[t+3],r=i[t+0]<<16|i[t+1]<<8|i[t+2];if(1===n||1===r)return t;t++}},e.prototype.readNextNaluPayload=function(){for(var e=this.data_,t=null;null==t&&!this.eof_flag_;){var i=this.current_startcode_offset_,n=e[i+=1==(e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3])?4:3]>>1&63,r=(128&e[i])>>>7,o=this.findNextStartCodeOffset(i);if(this.current_startcode_offset_=o,0===r){var a=e.subarray(i,o);(t=new de).type=n,t.data=a}}return t},e}(),he=function(){function e(e,t,i,n){var r=23+(5+e.byteLength)+(5+t.byteLength)+(5+i.byteLength),o=this.data=new Uint8Array(r);o[0]=1,o[1]=(3&n.general_profile_space)<<6|(n.general_tier_flag?1:0)<<5|31&n.general_profile_idc,o[2]=n.general_profile_compatibility_flags_1,o[3]=n.general_profile_compatibility_flags_2,o[4]=n.general_profile_compatibility_flags_3,o[5]=n.general_profile_compatibility_flags_4,o[6]=n.general_constraint_indicator_flags_1,o[7]=n.general_constraint_indicator_flags_2,o[8]=n.general_constraint_indicator_flags_3,o[9]=n.general_constraint_indicator_flags_4,o[10]=n.general_constraint_indicator_flags_5,o[11]=n.general_constraint_indicator_flags_6,o[12]=n.general_level_idc,o[13]=240|(3840&n.min_spatial_segmentation_idc)>>8,o[14]=255&n.min_spatial_segmentation_idc,o[15]=252|3&n.parallelismType,o[16]=252|3&n.chroma_format_idc,o[17]=248|7&n.bit_depth_luma_minus8,o[18]=248|7&n.bit_depth_chroma_minus8,o[19]=0,o[20]=0,o[21]=(3&n.constant_frame_rate)<<6|(7&n.num_temporal_layers)<<3|(n.temporal_id_nested?1:0)<<2|3,o[22]=3,o[23]=128|$.kSliceVPS,o[24]=0,o[25]=1,o[26]=(65280&e.byteLength)>>8,o[27]=255&e.byteLength,o.set(e,28),o[23+(5+e.byteLength)+0]=128|$.kSliceSPS,o[23+(5+e.byteLength)+1]=0,o[23+(5+e.byteLength)+2]=1,o[23+(5+e.byteLength)+3]=(65280&t.byteLength)>>8,o[23+(5+e.byteLength)+4]=255&t.byteLength,o.set(t,23+(5+e.byteLength)+5),o[23+(5+e.byteLength+5+t.byteLength)+0]=128|$.kSlicePPS,o[23+(5+e.byteLength+5+t.byteLength)+1]=0,o[23+(5+e.byteLength+5+t.byteLength)+2]=1,o[23+(5+e.byteLength+5+t.byteLength)+3]=(65280&i.byteLength)>>8,o[23+(5+e.byteLength+5+t.byteLength)+4]=255&i.byteLength,o.set(i,23+(5+e.byteLength+5+t.byteLength)+5)}return e.prototype.getData=function(){return this.data},e}(),ue=function(){},Ae=function(){},pe=function(){},_e=[[64,64,80,80,96,96,112,112,128,128,160,160,192,192,224,224,256,256,320,320,384,384,448,448,512,512,640,640,768,768,896,896,1024,1024,1152,1152,1280,1280],[69,70,87,88,104,105,121,122,139,140,174,175,208,209,243,244,278,279,348,349,417,418,487,488,557,558,696,697,835,836,975,976,1114,1115,1253,1254,1393,1394],[96,96,120,120,144,144,168,168,192,192,240,240,288,288,336,336,384,384,480,480,576,576,672,672,768,768,960,960,1152,1152,1344,1344,1536,1536,1728,1728,1920,1920]],fe=function(){function e(e){this.TAG="AC3Parser",this.data_=e,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&r.A.e(this.TAG,"Could not found AC3 syncword until payload end")}return e.prototype.findNextSyncwordOffset=function(e){for(var t=e,i=this.data_;;){if(t+7>=i.byteLength)return this.eof_flag_=!0,i.byteLength;if(2935==(i[t+0]<<8|i[t+1]))return t;t++}},e.prototype.readNextAC3Frame=function(){for(var e=this.data_,t=null;null==t&&!this.eof_flag_;){var i=this.current_syncword_offset_,n=e[i+4]>>6,r=[48e3,44200,33e3][n],o=63&e[i+4],a=2*_e[n][o];if(i+a>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var s=this.findNextSyncwordOffset(i+a);this.current_syncword_offset_=s;var d=e[i+5]>>3,l=7&e[i+5],c=e[i+6]>>5,h=0;1&c&&1!==c&&(h+=2),4&c&&(h+=2),2===c&&(h+=2);var u=(e[i+6]<<8|e[i+7])>>12-h&1,A=[2,1,2,3,3,4,4,5][c]+u;(t=new pe).sampling_frequency=r,t.channel_count=A,t.channel_mode=c,t.bit_stream_identification=d,t.low_frequency_effects_channel_on=u,t.bit_stream_mode=l,t.frame_size_code=o,t.data=e.subarray(i,i+a)}return t},e.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},e.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},e}(),me=function(e){var t;t=[e.sampling_rate_code<<6|e.bit_stream_identification<<1|e.bit_stream_mode>>2,(3&e.bit_stream_mode)<<6|e.channel_mode<<3|e.low_frequency_effects_channel_on<<2|e.frame_size_code>>4,e.frame_size_code<<4&224],this.config=t,this.sampling_rate=e.sampling_frequency,this.bit_stream_identification=e.bit_stream_identification,this.bit_stream_mode=e.bit_stream_mode,this.low_frequency_effects_channel_on=e.low_frequency_effects_channel_on,this.channel_count=e.channel_count,this.channel_mode=e.channel_mode,this.codec_mimetype="ac-3",this.original_codec_mimetype="ac-3"},ve=function(){},ge=function(){function e(e){this.TAG="EAC3Parser",this.data_=e,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&r.A.e(this.TAG,"Could not found AC3 syncword until payload end")}return e.prototype.findNextSyncwordOffset=function(e){for(var t=e,i=this.data_;;){if(t+7>=i.byteLength)return this.eof_flag_=!0,i.byteLength;if(2935==(i[t+0]<<8|i[t+1]))return t;t++}},e.prototype.readNextEAC3Frame=function(){for(var e=this.data_,t=null;null==t&&!this.eof_flag_;){var i=this.current_syncword_offset_,n=new A(e.subarray(i+2)),r=(n.readBits(2),n.readBits(3),n.readBits(11)+1<<1),o=n.readBits(2),a=null,s=null;3===o?(a=[24e3,22060,16e3][o=n.readBits(2)],s=3):(a=[48e3,44100,32e3][o],s=n.readBits(2));var d=n.readBits(3),l=n.readBits(1),c=n.readBits(5);if(i+r>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var h=this.findNextSyncwordOffset(i+r);this.current_syncword_offset_=h;var u=[2,1,2,3,3,4,4,5][d]+l;n.destroy(),(t=new ve).sampling_frequency=a,t.channel_count=u,t.channel_mode=d,t.bit_stream_identification=c,t.low_frequency_effects_channel_on=l,t.frame_size=r,t.num_blks=[1,2,3,6][s],t.data=e.subarray(i,i+r)}return t},e.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},e.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},e}(),ye=function(e){var t,i=Math.floor(e.frame_size*e.sampling_frequency/(16*e.num_blks));t=[255&i,248&i,e.sampling_rate_code<<6|e.bit_stream_identification<<1,e.channel_mode<<1|e.low_frequency_effects_channel_on,0],this.config=t,this.sampling_rate=e.sampling_frequency,this.bit_stream_identification=e.bit_stream_identification,this.num_blks=e.num_blks,this.low_frequency_effects_channel_on=e.low_frequency_effects_channel_on,this.channel_count=e.channel_count,this.channel_mode=e.channel_mode,this.codec_mimetype="ec-3",this.original_codec_mimetype="ec-3"},be=function(){var e=function(t,i){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},e(t,i)};return function(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function n(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(n.prototype=i.prototype,new n)}}(),Ee=function(){return Ee=Object.assign||function(e){for(var t,i=1,n=arguments.length;i0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){r={error:e}}finally{try{n&&!n.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}return a},we=function(e,t,i){if(2===arguments.length)for(var n,r=0,o=t.length;r=4?(r.A.v("TSDemuxer","ts_packet_size = 192, m2ts mode"),i-=4):204===n&&r.A.v("TSDemuxer","ts_packet_size = 204, RS encoded MPEG2-TS stream"),{match:!0,consumed:0,ts_packet_size:n,sync_offset:i})},t.prototype.bindDataSource=function(e){return e.onDataArrival=this.parseChunks.bind(this),this},t.prototype.resetMediaInfo=function(){this.media_info_=new a.A},t.prototype.parseChunks=function(e,t){var i;if(!(this.onError&&this.onMediaInfo&&this.onTrackMetadata&&this.onDataAvailable))throw new c.j4("onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");var n=0;for(this.first_parse_&&(this.first_parse_=!1,n=this.sync_offset_);n+this.ts_packet_size_<=e.byteLength;){var o=t+n;192===this.ts_packet_size_&&(n+=4);var a=new Uint8Array(e,n,188),s=a[0];if(71!==s){r.A.e(this.TAG,"sync_byte = ".concat(s,", not 0x47"));break}var d=(64&a[1])>>>6,l=(a[1],(31&a[1])<<8|a[2]),h=(48&a[3])>>>4,u=15&a[3],A={},p=4;if(2===h||3===h){var _=a[4];if(5+_===188){n+=188,204===this.ts_packet_size_&&(n+=16);continue}_>0&&(A=this.parseAdaptationField(e,n+4,1+_)),p=5+_}if(1===h||3===h)if(0===l||l===this.current_pmt_pid_||void 0!==this.pmt_&&this.pmt_.pid_stream_type[l]===T.kSCTE35){var f=188-p;this.handleSectionSlice(e,n+p,f,{pid:l,file_position:o,payload_unit_start_indicator:d,continuity_conunter:u,random_access_indicator:A.random_access_indicator})}else if(void 0!==(null===(i=this.pmt_)||void 0===i?void 0:i.pid_stream_type[l])){f=188-p;var m=this.pmt_.pid_stream_type[l];(l===this.pmt_.common_pids.h264||l===this.pmt_.common_pids.h265||l===this.pmt_.common_pids.adts_aac||l===this.pmt_.common_pids.loas_aac||l===this.pmt_.common_pids.ac3||l===this.pmt_.common_pids.eac3||l===this.pmt_.common_pids.opus||l===this.pmt_.common_pids.mp3||this.pmt_.pes_private_data_pids[l]||this.pmt_.timed_id3_pids[l])&&this.handlePESSlice(e,n+p,f,{pid:l,stream_type:m,file_position:o,payload_unit_start_indicator:d,continuity_conunter:u,random_access_indicator:A.random_access_indicator})}n+=188,204===this.ts_packet_size_&&(n+=16)}return this.dispatchAudioVideoMediaSegment(),n},t.prototype.parseAdaptationField=function(e,t,i){var n=new Uint8Array(e,t,i),o=n[0];return o>0?o>183?(r.A.w(this.TAG,"Illegal adaptation_field_length: ".concat(o)),{}):{discontinuity_indicator:(128&n[1])>>>7,random_access_indicator:(64&n[1])>>>6,elementary_stream_priority_indicator:(32&n[1])>>>5}:{}},t.prototype.handleSectionSlice=function(e,t,i,n){var r=new Uint8Array(e,t,i),o=this.section_slice_queues_?this.section_slice_queues_[n.pid]:{};if(n.payload_unit_start_indicator){var a=r[0];if(void 0!==o&&0!==(null==o?void 0:o.total_length)){var s=new Uint8Array(e,t+1,Math.min(i,a));o.slices.push(s),o.total_length+=s.byteLength,o.total_length===o.expected_length?this.emitSectionSlices(o,n):this.clearSlices(o,n)}for(var d=1+a;d=o.expected_length&&this.clearSlices(o,n),d+=s.byteLength}}else void 0!==o&&0!==o.total_length&&(s=new Uint8Array(e,t,Math.min(i,o.expected_length-o.total_length)),o.slices.push(s),o.total_length+=s.byteLength,o.total_length===o.expected_length?this.emitSectionSlices(o,n):o.total_length>=o.expected_length&&this.clearSlices(o,n))},t.prototype.handlePESSlice=function(e,t,i,n){var o=new Uint8Array(e,t,i),a=o[0]<<16|o[1]<<8|o[2],s=(o[3],o[4]<<8|o[5]);if(n.payload_unit_start_indicator){if(1!==a)return void r.A.e(this.TAG,"handlePESSlice: packet_start_code_prefix should be 1 but with value ".concat(a));var d=this.pes_slice_queues_[n.pid];d&&(0===d.expected_length||d.expected_length===d.total_length?this.emitPESSlices(d,n):this.clearSlices(d,n)),this.pes_slice_queues_&&(this.pes_slice_queues_[n.pid]=new I,this.pes_slice_queues_[n.pid].file_position=n.file_position,this.pes_slice_queues_[n.pid].random_access_indicator=n.random_access_indicator)}if(void 0!==this.pes_slice_queues_[n.pid]){var l=this.pes_slice_queues_[n.pid];l.slices.push(o),n.payload_unit_start_indicator&&(l.expected_length=0===s?0:s+6),l.total_length+=o.byteLength,l.expected_length>0&&l.expected_length===l.total_length?this.emitPESSlices(l,n):l.expected_length>0&&l.expected_length>>6,s=t[8],d=void 0,l=void 0;2!==a&&3!==a||(d=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,l=3===a?536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2:d);var c=9+s,h=void 0;if(0!==o){if(o<3+s)return void r.A.v(this.TAG,"Malformed PES: PES_packet_length < 3 + PES_header_data_length");h=o-3-s}else h=t.byteLength-c;var u=t.subarray(c,c+h);switch(e.stream_type){case T.kMPEG1Audio:case T.kMPEG2Audio:this.parseMP3Payload(u,d);break;case T.kPESPrivateData:this.pmt_.common_pids.opus===e.pid?this.parseOpusPayload(u,d):this.pmt_.common_pids.ac3===e.pid?this.parseAC3Payload(u,d):this.pmt_.common_pids.eac3===e.pid?this.parseEAC3Payload(u,d):this.pmt_.smpte2038_pids[e.pid]?this.parseSMPTE2038MetadataPayload(u,d,l,e.pid,n):this.parsePESPrivateDataPayload(u,d,l,e.pid,n);break;case T.kADTSAAC:this.parseADTSAACPayload(u,d);break;case T.kLOASAAC:this.parseLOASAACPayload(u,d);break;case T.kAC3:this.parseAC3Payload(u,d);break;case T.kEAC3:this.parseEAC3Payload(u,d);break;case T.kID3:this.parseTimedID3MetadataPayload(u,d,l,e.pid,n);break;case T.kH264:this.parseH264Payload(u,d,l,e.file_position,e.random_access_indicator);break;case T.kH265:this.parseH265Payload(u,d,l,e.file_position,e.random_access_indicator)}}else 188!==n&&191!==n&&240!==n&&241!==n&&255!==n&&242!==n&&248!==n||e.stream_type!==T.kPESPrivateData||(c=6,h=void 0,h=0!==o?o:t.byteLength-c,u=t.subarray(c,c+h),this.parsePESPrivateDataPayload(u,void 0,void 0,e.pid,n));else r.A.e(this.TAG,"parsePES: packet_start_code_prefix should be 1 but with value ".concat(i))},t.prototype.parsePAT=function(e){var t=e[0];if(0===t){var i=(15&e[1])<<8|e[2],n=(e[3],e[4],(62&e[5])>>>1),o=1&e[5],a=e[6],s=(e[7],null);if(1===o&&0===a)(s=new B).version_number=n;else if(null==(s=this.pat_))return;for(var d=i-5-4,l=-1,c=-1,h=8;h<8+d;h+=4){var u=e[h]<<8|e[h+1],A=(31&e[h+2])<<8|e[h+3];0===u?s.network_pid=A:(s.program_pmt_pid[u]=A,-1===l&&(l=u),-1===c&&(c=A))}1===o&&0===a&&(void 0===this.pat_&&r.A.v(this.TAG,"Parsed first PAT: ".concat(JSON.stringify(s))),this.pat_=s,this.current_program_=l,this.current_pmt_pid_=c)}else r.A.e(this.TAG,"parsePAT: table_id ".concat(t," is not corresponded to PAT!"))},t.prototype.parsePMT=function(e){var t=e[0];if(2===t){var i=(15&e[1])<<8|e[2],n=e[3]<<8|e[4],o=(62&e[5])>>>1,a=1&e[5],s=e[6],d=(e[7],null);if(1===a&&0===s)(d=new C).program_number=n,d.version_number=o,this.program_pmt_map_[n]=d;else if(null==(d=this.program_pmt_map_[n]))return;e[8],e[9];for(var l=(15&e[10])<<8|e[11],c=12+l,h=i-9-l-4,u=c;u0){for(var v=u+5;v1&&(r.A.w(this.TAG,"AAC: Detected pts overlapped, "+"expected: ".concat(l,"ms, PES pts: ").concat(d,"ms")),d=l)}}for(var c=new Q(e),h=null,u=d,A=0;null!=(h=c.readNextAACFrame());){s=1024/h.sampling_frequency*1e3;var p={codec:"aac",data:h};this.audio_init_segment_dispatched_?this.detectAudioMetadataChange(p)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(p)):(this.audio_metadata_={codec:"aac",audio_object_type:h.audio_object_type,sampling_freq_index:h.sampling_freq_index,sampling_frequency:h.sampling_frequency,channel_config:h.channel_config},this.dispatchAudioInitSegment(p)),A=u;var _=Math.floor(u),f={unit:h.data,length:h.data.byteLength,pts:_,dts:_};this.audio_track_&&(null===(o=this.audio_track_)||void 0===o||o.samples.push(f),this.audio_track_.length+=h.data.byteLength),u+=s}c.hasIncompleteData()&&(this.aac_last_incomplete_data_=c.getIncompleteData()),A&&(this.aac_last_sample_pts_=A)}},t.prototype.parseLOASAACPayload=function(e,t){var i,n,o;if(!this.has_video_||this.video_init_segment_dispatched_){if(this.aac_last_incomplete_data_){var a=new Uint8Array(e.byteLength+this.aac_last_incomplete_data_.byteLength);a.set(this.aac_last_incomplete_data_,0),a.set(e,this.aac_last_incomplete_data_.byteLength),e=a}var s,d=0;if(void 0!==t&&(d=t/this.timescale_),"aac"===(null===(i=this.audio_metadata_)||void 0===i?void 0:i.codec)){if(void 0===t&&void 0!==this.aac_last_sample_pts_)s=1024/this.audio_metadata_.sampling_frequency*1e3,d=this.aac_last_sample_pts_+s;else if(void 0===t)return void r.A.w(this.TAG,"AAC: Unknown pts");if(this.aac_last_incomplete_data_&&this.aac_last_sample_pts_){s=1024/this.audio_metadata_.sampling_frequency*1e3;var l=this.aac_last_sample_pts_+s;Math.abs(l-d)>1&&(r.A.w(this.TAG,"AAC: Detected pts overlapped, "+"expected: ".concat(l,"ms, PES pts: ").concat(d,"ms")),d=l)}}for(var c=new z(e),h=null,u=d,A=0;null!=(h=c.readNextAACFrame(null!==(n=this.loas_previous_frame)&&void 0!==n?n:void 0));){this.loas_previous_frame=h,s=1024/h.sampling_frequency*1e3;var p={codec:"aac",data:h};this.audio_init_segment_dispatched_?this.detectAudioMetadataChange(p)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(p)):(this.audio_metadata_={codec:"aac",audio_object_type:h.audio_object_type,sampling_freq_index:h.sampling_freq_index,sampling_frequency:h.sampling_frequency,channel_config:h.channel_config},this.dispatchAudioInitSegment(p)),A=u;var _=Math.floor(u),f={unit:h.data,length:h.data.byteLength,pts:_,dts:_};this.audio_track_&&(null===(o=this.audio_track_)||void 0===o||o.samples.push(f),this.audio_track_.length+=h.data.byteLength),u+=s}c.hasIncompleteData()&&(this.aac_last_incomplete_data_=c.getIncompleteData()),A&&(this.aac_last_sample_pts_=A)}},t.prototype.parseAC3Payload=function(e,t){var i,n;if(!this.has_video_||this.video_init_segment_dispatched_){var o,a=0;if(void 0!==t&&(a=t/this.timescale_),"ac-3"===(null===(i=this.audio_metadata_)||void 0===i?void 0:i.codec))if(void 0===t&&void 0!==this.aac_last_sample_pts_)o=1536/this.audio_metadata_.sampling_frequency*1e3,a=this.aac_last_sample_pts_+o;else if(void 0===t)return void r.A.w(this.TAG,"AC3: Unknown pts");for(var s=new fe(e),d=null,l=a,c=0;null!=(d=s.readNextAC3Frame());){o=1536/d.sampling_frequency*1e3;var h={codec:"ac-3",data:d};this.audio_init_segment_dispatched_?this.detectAudioMetadataChange(h)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(h)):(this.audio_metadata_={codec:"ac-3",sampling_frequency:d.sampling_frequency,bit_stream_identification:d.bit_stream_identification,bit_stream_mode:d.bit_stream_mode,low_frequency_effects_channel_on:d.low_frequency_effects_channel_on,channel_mode:d.channel_mode},this.dispatchAudioInitSegment(h)),c=l;var u=Math.floor(l),A={unit:d.data,length:d.data.byteLength,pts:u,dts:u};this.audio_track_&&(null===(n=this.audio_track_)||void 0===n||n.samples.push(A),this.audio_track_.length+=d.data.byteLength),l+=o}c&&(this.aac_last_sample_pts_=c)}},t.prototype.parseEAC3Payload=function(e,t){var i,n;if(!this.has_video_||this.video_init_segment_dispatched_){var o,a=0;if(void 0!==t&&(a=t/this.timescale_),"ec-3"===(null===(i=this.audio_metadata_)||void 0===i?void 0:i.codec))if(void 0===t&&void 0!==this.aac_last_sample_pts_)o=256*(this.audio_metadata_.num_blks||0)/(this.audio_metadata_.sampling_frequency||0)*1e3,a=this.aac_last_sample_pts_+o;else if(void 0===t)return void r.A.w(this.TAG,"EAC3: Unknown pts");for(var s=new ge(e),d=null,l=a,c=0;null!=(d=s.readNextEAC3Frame());){o=1536/d.sampling_frequency*1e3;var h={codec:"ec-3",data:d};this.audio_init_segment_dispatched_?this.detectAudioMetadataChange(h)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(h)):(this.audio_metadata_={codec:"ec-3",sampling_frequency:d.sampling_frequency,bit_stream_identification:d.bit_stream_identification,low_frequency_effects_channel_on:d.low_frequency_effects_channel_on,num_blks:d.num_blks,channel_mode:d.channel_mode},this.dispatchAudioInitSegment(h)),c=l;var u=Math.floor(l),A={unit:d.data,length:d.data.byteLength,pts:u,dts:u};this.audio_track_&&(null===(n=this.audio_track_)||void 0===n||n.samples.push(A),this.audio_track_.length+=d.data.byteLength),l+=o}c&&(this.aac_last_sample_pts_=c)}},t.prototype.parseOpusPayload=function(e,t){var i,n;if(!this.has_video_||this.video_init_segment_dispatched_){var o,a=0;if(void 0!==t&&(a=t/this.timescale_),"opus"===(null===(i=this.audio_metadata_)||void 0===i?void 0:i.codec))if(void 0===t&&void 0!==this.aac_last_sample_pts_)o=20,a=this.aac_last_sample_pts_+o;else if(void 0===t)return void r.A.w(this.TAG,"Opus: Unknown pts");for(var s=a,d=0,l=0;l>>3&3,r=(6&e[1])>>1,o=(e[2],(12&e[2])>>>2),a=3&~(e[3]>>>6)?2:1,s=0,d=34;switch(n){case 0:s=[11025,12e3,8e3,0][o];break;case 2:s=[22050,24e3,16e3,0][o];break;case 3:s=[44100,48e3,32e3,0][o]}switch(r){case 1:d=34;break;case 2:d=33;break;case 3:d=32}var l=new Ae;l.object_type=d,l.sample_rate=s,l.channel_count=a,l.data=e;var c={codec:"mp3",data:l};this.audio_init_segment_dispatched_?this.detectAudioMetadataChange(c)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(c)):(this.audio_metadata_={codec:"mp3",object_type:d,sample_rate:s,channel_count:a},this.dispatchAudioInitSegment(c));var h={unit:e,length:e.byteLength,pts:t/this.timescale_,dts:t/this.timescale_};this.audio_track_&&(null===(i=this.audio_track_)||void 0===i||i.samples.push(h),this.audio_track_.length+=e.byteLength)}},t.prototype.detectAudioMetadataChange=function(e){var t,i,n,o;if(e.codec!==(null===(t=this.audio_metadata_)||void 0===t?void 0:t.codec))return r.A.v(this.TAG,"Audio: Audio Codecs changed from "+"".concat(null===(i=this.audio_metadata_)||void 0===i?void 0:i.codec," to ").concat(e.codec)),!0;if("aac"===e.codec&&"aac"===this.audio_metadata_.codec){if((a=e.data).audio_object_type!==this.audio_metadata_.audio_object_type)return r.A.v(this.TAG,"AAC: AudioObjectType changed from "+"".concat(this.audio_metadata_.audio_object_type," to ").concat(a.audio_object_type)),!0;if(a.sampling_freq_index!==this.audio_metadata_.sampling_freq_index)return r.A.v(this.TAG,"AAC: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sampling_freq_index," to ").concat(a.sampling_freq_index)),!0;if(a.channel_config!==this.audio_metadata_.channel_config)return r.A.v(this.TAG,"AAC: Channel configuration changed from "+"".concat(null===(n=this.audio_metadata_)||void 0===n?void 0:n.channel_config," to ").concat(a.channel_config)),!0}else if("ac-3"===e.codec&&"ac-3"===this.audio_metadata_.codec){var a;if((a=e.data).sampling_frequency!==this.audio_metadata_.sampling_frequency)return r.A.v(this.TAG,"AC3: Sampling Frequency changed from "+"".concat(null===(o=this.audio_metadata_)||void 0===o?void 0:o.sampling_frequency," to ").concat(a.sampling_frequency)),!0;if(a.bit_stream_identification!==this.audio_metadata_.bit_stream_identification)return r.A.v(this.TAG,"AC3: Bit Stream Identification changed from "+"".concat(this.audio_metadata_.bit_stream_identification," to ").concat(a.bit_stream_identification)),!0;if(a.bit_stream_mode!==this.audio_metadata_.bit_stream_mode)return r.A.v(this.TAG,"AC3: BitStream Mode changed from "+"".concat(this.audio_metadata_.bit_stream_mode," to ").concat(a.bit_stream_mode)),!0;if(a.channel_mode!==this.audio_metadata_.channel_mode)return r.A.v(this.TAG,"AC3: Channel Mode changed from "+"".concat(this.audio_metadata_.channel_mode," to ").concat(a.channel_mode)),!0;if(a.low_frequency_effects_channel_on!==this.audio_metadata_.low_frequency_effects_channel_on)return r.A.v(this.TAG,"AC3: Low Frequency Effects Channel On changed from "+"".concat(this.audio_metadata_.low_frequency_effects_channel_on," to ").concat(a.low_frequency_effects_channel_on)),!0}else if("opus"===e.codec&&"opus"===this.audio_metadata_.codec){if((s=e.meta).sample_rate!==this.audio_metadata_.sample_rate)return r.A.v(this.TAG,"Opus: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sample_rate," to ").concat(s.sample_rate)),!0;if(s.channel_count!==this.audio_metadata_.channel_count)return r.A.v(this.TAG,"Opus: Channel count changed from "+"".concat(this.audio_metadata_.channel_count," to ").concat(s.channel_count)),!0}else if("mp3"===e.codec&&"mp3"===this.audio_metadata_.codec){var s;if((s=e.data).object_type!==this.audio_metadata_.object_type)return r.A.v(this.TAG,"MP3: AudioObjectType changed from "+"".concat(this.audio_metadata_.object_type," to ").concat(s.object_type)),!0;if(s.sample_rate!==this.audio_metadata_.sample_rate)return r.A.v(this.TAG,"MP3: SamplingFrequencyIndex changed from "+"".concat(this.audio_metadata_.sample_rate," to ").concat(s.sample_rate)),!0;if(s.channel_count!==this.audio_metadata_.channel_count)return r.A.v(this.TAG,"MP3: Channel count changed from "+"".concat(this.audio_metadata_.channel_count," to ").concat(s.channel_count)),!0}return!1},t.prototype.dispatchAudioInitSegment=function(e){var t,i,n,o,a,s,d={type:"audio"};if(d.id=null===(t=this.audio_track_)||void 0===t?void 0:t.id,d.timescale=1e3,d.duration=this.duration_,"aac"===(null===(i=this.audio_metadata_)||void 0===i?void 0:i.codec)){var l="aac"===e.codec?e.data:null,c=new H(l);d.audioSampleRate=c.sampling_rate,d.channelCount=c.channel_count,d.codec=c.codec_mimetype,d.originalCodec=c.original_codec_mimetype,d.config=c.config,d.refSampleDuration=1024/d.audioSampleRate*d.timescale}else if("ac-3"===(null===(n=this.audio_metadata_)||void 0===n?void 0:n.codec)){var h="ac-3"===e.codec?e.data:null,u=new me(h);d.audioSampleRate=u.sampling_rate,d.channelCount=u.channel_count,d.codec=u.codec_mimetype,d.originalCodec=u.original_codec_mimetype,d.config=u.config,d.refSampleDuration=1536/d.audioSampleRate*d.timescale}else if("ec-3"===(null===(o=this.audio_metadata_)||void 0===o?void 0:o.codec)){var A="ec-3"===e.codec?e.data:null,p=new ye(A);d.audioSampleRate=p.sampling_rate,d.channelCount=p.channel_count,d.codec=p.codec_mimetype,d.originalCodec=p.original_codec_mimetype,d.config=p.config,d.refSampleDuration=256*p.num_blks/d.audioSampleRate*d.timescale}else"opus"===(null===(a=this.audio_metadata_)||void 0===a?void 0:a.codec)?(d.audioSampleRate=this.audio_metadata_.sample_rate,d.channelCount=this.audio_metadata_.channel_count,d.channelConfigCode=this.audio_metadata_.channel_config_code,d.codec="opus",d.originalCodec="opus",d.config=void 0,d.refSampleDuration=20):"mp3"===(null===(s=this.audio_metadata_)||void 0===s?void 0:s.codec)&&(d.audioSampleRate=this.audio_metadata_.sample_rate,d.channelCount=this.audio_metadata_.channel_count,d.codec="mp3",d.originalCodec="mp3",d.config=void 0);this.audio_init_segment_dispatched_||r.A.v(this.TAG,"Generated first AudioSpecificConfig for mimeType: ".concat(d.codec)),this.onTrackMetadata&&this.onTrackMetadata("audio",d),this.audio_init_segment_dispatched_=!0,this.video_metadata_changed_=!1;var _=this.media_info_;_.hasAudio=!0,_.audioCodec=d.originalCodec,_.audioSampleRate=d.audioSampleRate,_.audioChannelCount=d.channelCount,_.hasVideo&&_.videoCodec?_.mimeType='video/mp2t; codecs="'.concat(_.videoCodec,",").concat(_.audioCodec,'"'):_.mimeType='video/mp2t; codecs="'.concat(_.audioCodec,'"'),_.isComplete()&&this.onMediaInfo&&this.onMediaInfo(_)},t.prototype.dispatchPESPrivateDataDescriptor=function(e,t,i){var n=new X;n.pid=e,n.stream_type=t,n.descriptor=i,this.onPESPrivateDataDescriptor&&this.onPESPrivateDataDescriptor(n)},t.prototype.parsePESPrivateDataPayload=function(e,t,i,n,r){var o=new q;if(o.pid=n,o.stream_id=r,o.len=e.byteLength,o.data=e,void 0!==t){var a=Math.floor(t/this.timescale_);o.pts=a}else o.nearest_pts=this.aac_last_sample_pts_;if(void 0!==i){var s=Math.floor(i/this.timescale_);o.dts=s}this.onPESPrivateData&&this.onPESPrivateData(o)},t.prototype.parseTimedID3MetadataPayload=function(e,t,i,n,r){var o=new q;if(o.pid=n,o.stream_id=r,o.len=e.byteLength,o.data=e,void 0!==t){var a=Math.floor(t/this.timescale_);o.pts=a}if(void 0!==i){var s=Math.floor(i/this.timescale_);o.dts=s}this.onTimedID3Metadata&&this.onTimedID3Metadata(o)},t.prototype.parseSMPTE2038MetadataPayload=function(e,t,i,n,r){var o=new ue;if(o.pid=n,o.stream_id=r,o.len=e.byteLength,o.data=e,void 0!==t){var a=Math.floor(t/this.timescale_);o.pts=a}if(o.nearest_pts=this.aac_last_sample_pts_,void 0!==i){var s=Math.floor(i/this.timescale_);o.dts=s}o.ancillaries=function(e){for(var t=new A(e),i=0,n=[];i+=6,0===t.readBits(6);){var r=t.readBool();i+=1;var o=t.readBits(11);i+=11;var a=t.readBits(12);i+=12;var s=255&t.readBits(10);i+=10;var d=255&t.readBits(10);i+=10;var l=255&t.readBits(10);i+=10;for(var c=new Uint8Array(l),h=0;h>>24&255,r[1]=n>>>16&255,r[2]=n>>>8&255,r[3]=255&n,r.set(e,4);var d=8;for(s=0;s>>24&255,t>>>16&255,t>>>8&255,255&t,i>>>24&255,i>>>16&255,i>>>8&255,255&i,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]))},e.trak=function(t){return e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.tkhd=function(t){var i=t.id,n=t.duration,r=t.presentWidth,o=t.presentHeight;return e.box(e.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i,0,0,0,0,n>>>24&255,n>>>16&255,n>>>8&255,255&n,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,r>>>8&255,255&r,0,0,o>>>8&255,255&o,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t),e.hdlr(t),e.minf(t))},e.mdhd=function(t){var i=t.timescale,n=t.duration;return e.box(e.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i,n>>>24&255,n>>>16&255,n>>>8&255,255&n,85,196,0,0]))},e.hdlr=function(t){var i;return i="audio"===t.type?e.constants.HDLR_AUDIO:e.constants.HDLR_VIDEO,e.box(e.types.hdlr,i)},e.minf=function(t){var i;return i="audio"===t.type?e.box(e.types.smhd,e.constants.SMHD):e.box(e.types.vmhd,e.constants.VMHD),e.box(e.types.minf,i,e.dinf(),e.stbl(t))},e.dinf=function(){return e.box(e.types.dinf,e.box(e.types.dref,e.constants.DREF))},e.stbl=function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.constants.STTS),e.box(e.types.stsc,e.constants.STSC),e.box(e.types.stsz,e.constants.STSZ),e.box(e.types.stco,e.constants.STCO))},e.stsd=function(t){return"audio"===t.type?"mp3"===t.codec?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.mp3(t)):"ac-3"===t.codec?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.ac3(t)):"ec-3"===t.codec?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.ec3(t)):"opus"===t.codec?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.Opus(t)):e.box(e.types.stsd,e.constants.STSD_PREFIX,e.mp4a(t)):"video"===t.type&&t.codec.startsWith("hvc1")?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.hvc1(t)):"video"===t.type&&t.codec.startsWith("av01")?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.av01(t)):e.box(e.types.stsd,e.constants.STSD_PREFIX,e.avc1(t))},e.mp3=function(t){var i=t.channelCount,n=t.audioSampleRate,r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,i,0,16,0,0,0,0,n>>>8&255,255&n,0,0]);return e.box(e.types[".mp3"],r)},e.mp4a=function(t){var i=t.channelCount,n=t.audioSampleRate,r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,i,0,16,0,0,0,0,n>>>8&255,255&n,0,0]);return e.box(e.types.mp4a,r,e.esds(t))},e.ac3=function(t){var i,n=t.channelCount,r=t.audioSampleRate,o=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,255&r,0,0]);return e.box(e.types["ac-3"],o,e.box(e.types.dac3,new Uint8Array(null!==(i=t.config)&&void 0!==i?i:[])))},e.ec3=function(t){var i,n=t.channelCount,r=t.audioSampleRate,o=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,255&r,0,0]);return e.box(e.types["ec-3"],o,e.box(e.types.dec3,new Uint8Array(null!==(i=t.config)&&void 0!==i?i:[])))},e.esds=function(t){var i,n=null!==(i=t.config)&&void 0!==i?i:[],r=n.length,o=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 e.box(e.types.esds,o)},e.Opus=function(t){var i=t.channelCount,n=t.audioSampleRate,r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,i,0,16,0,0,0,0,n>>>8&255,255&n,0,0]);return e.box(e.types.Opus,r,e.dOps(t))},e.dOps=function(t){var i=t.channelCount,n=t.channelConfigCode,r=t.audioSampleRate,o=[];switch(n){case 1:case 2:o=[0];break;case 0:o=[255,1,1,0,1];break;case 128:o=[255,2,0,0,1];break;case 3:o=[1,2,1,0,2,1];break;case 4:o=[1,2,2,0,1,2,3];break;case 5:o=[1,3,2,0,4,1,2,3];break;case 6:o=[1,4,2,0,4,1,2,3,5];break;case 7:o=[1,4,2,0,4,1,2,3,5,6];break;case 8:o=[1,5,3,0,6,1,2,3,4,5,7];break;case 130:o=[1,1,2,0,1];break;case 131:o=[1,1,3,0,1,2];break;case 132:o=[1,1,4,0,1,2,3];break;case 133:o=[1,1,5,0,1,2,3,4];break;case 134:o=[1,1,6,0,1,2,3,4,5];break;case 135:o=[1,1,7,0,1,2,3,4,5,6];break;case 136:o=[1,1,8,0,1,2,3,4,5,6,7]}var a=new Uint8Array(function(e,t,i){if(2===arguments.length)for(var n,r=0,o=t.length;r>>24&255,r>>>17&255,r>>>8&255,r>>>0&255,0,0],function(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,r,o=i.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){r={error:e}}finally{try{n&&!n.done&&(i=o.return)&&i.call(o)}finally{if(r)throw r.error}}return a}(o),!1));return e.box(e.types.dOps,a)},e.avc1=function(t){var i=t.avcc,n=t.codecWidth,r=t.codecHeight,o=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,n>>>8&255,255&n,r>>>8&255,255&r,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 e.box(e.types.avc1,o,e.box(e.types.avcC,i))},e.hvc1=function(t){var i=t.hvcc,n=t.codecWidth,r=t.codecHeight,o=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,n>>>8&255,255&n,r>>>8&255,255&r,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 e.box(e.types.hvc1,o,e.box(e.types.hvcC,i))},e.av01=function(t){var i,n,r=t.av1c,o=null!==(i=t.codecWidth)&&void 0!==i?i:192,a=null!==(n=t.codecHeight)&&void 0!==n?n:108,s=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,o>>>8&255,255&o,a>>>8&255,255&a,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return e.box(e.types.av01,s,e.box(e.types.av1C,r))},e.mvex=function(t){return e.box(e.types.mvex,e.trex(t))},e.trex=function(t){var i=t.id,n=new Uint8Array([0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return e.box(e.types.trex,n)},e.moof=function(t,i){return e.box(e.types.moof,e.mfhd(t.sequenceNumber),e.traf(t,i))},e.mfhd=function(t){var i=new Uint8Array([0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t]);return e.box(e.types.mfhd,i)},e.traf=function(t,i){var n=t.id,r=e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>>24&255,n>>>16&255,n>>>8&255,255&n])),o=e.box(e.types.tfdt,new Uint8Array([0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i])),a=e.sdtp(t),s=e.trun(t,a.byteLength+16+16+8+16+8+8);return e.box(e.types.traf,r,o,s,a)},e.sdtp=function(t){for(var i=t.samples||[],n=i.length,r=new Uint8Array(4+n),o=0;o>>24&255,r>>>16&255,r>>>8&255,255&r,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0);for(var s=0;s>>24&255,d>>>16&255,d>>>8&255,255&d,l>>>24&255,l>>>16&255,l>>>8&255,255&l,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.isNonSync,0,0,h>>>24&255,h>>>16&255,h>>>8&255,255&h],12+16*s)}return e.box(e.types.trun,a)},e.mdat=function(t){return e.box(e.types.mdat,t)},e.constants={FTYP:new Uint8Array([105,115,111,109,0,0,0,1,105,115,111,109,97,118,99,49]),STSD_PREFIX:new Uint8Array([0,0,0,0,0,0,0,1]),STTS:ke,STSC:ke,STCO:ke,STSZ:new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),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]),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]),DREF:new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),SMHD:new Uint8Array([0,0,0,0,0,0,0,0]),VMHD:new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0])},e}();Ce.init();const Re=Ce,Oe=function(){function e(){}return e.getSilentFrame=function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}return null},e}();var Ie=i(453);const xe=function(){function e(e){var t;this.TAG="MP4Remuxer",this._fillSilentAfterSeek=!1,this._config=e,this._isLive=!!e.isLive,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 Ie.Sc("audio"),this._videoSegmentInfoList=new Ie.Sc("video"),this._onInitSegment=null,this._onMediaSegment=null,this._forceFirstIDR=!(!o.A.chrome||!(o.A.version&&o.A.version.major<50||o.A.version&&50===o.A.version.major&&((null===(t=o.A.version)||void 0===t?void 0:t.build)||0)<2661)),this._fillSilentAfterSeek=!(!o.A.msedge&&!o.A.msie),this._mp3UseMpegAudio=!o.A.firefox,this._fillAudioTimestampGap=this._config.fixAudioTimestampGap}return e.prototype.destroy=function(){this._dtsBase=-1,this._dtsBaseInited=!1,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList.clear(),this._audioSegmentInfoList=null,this._videoSegmentInfoList.clear(),this._videoSegmentInfoList=null,this._onInitSegment=null,this._onMediaSegment=null},e.prototype.bindDataSource=function(e){var t;return e.onDataAvailable=null===(t=this.remux)||void 0===t?void 0:t.bind(this),e.onTrackMetadata=this._onTrackMetadataReceived.bind(this),this},Object.defineProperty(e.prototype,"onInitSegment",{get:function(){return this._onInitSegment},set:function(e){this._onInitSegment=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onMediaSegment",{get:function(){return this._onMediaSegment},set:function(e){this._onMediaSegment=e},enumerable:!1,configurable:!0}),e.prototype.insertDiscontinuity=function(){this._audioNextDts=this._videoNextDts=void 0},e.prototype.seek=function(e){this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._videoSegmentInfoList.clear(),this._audioSegmentInfoList.clear()},e.prototype.remux=function(e,t){if(!this._onMediaSegment)throw new c.j4("MP4Remuxer: onMediaSegment callback must be specificed!");this._dtsBaseInited||this._calculateDtsBase(e,t),t&&this._remuxVideo(t),e&&this._remuxAudio(e)},e.prototype._onTrackMetadataReceived=function(e,t){var i=null,n="mp4",r=t.codec;if("audio"===e)this._audioMeta=t,"mp3"===t.codec&&this._mp3UseMpegAudio?(n="mpeg",r="",i=new Uint8Array):i=Re.generateInitSegment(t);else{if("video"!==e)return;this._videoMeta=t,i=Re.generateInitSegment(t)}if(!this._onInitSegment)throw new c.j4("MP4Remuxer: onInitSegment callback must be specified!");this._onInitSegment(e,{type:e,data:i.buffer,codec:r,container:"".concat(e,"/").concat(n),mediaDuration:t.duration})},e.prototype._calculateDtsBase=function(e,t){var i,n;this._dtsBaseInited||((null===(i=null==e?void 0:e.samples)||void 0===i?void 0:i.length)&&(this._audioDtsBase=e.samples[0].dts),(null===(n=null==t?void 0:t.samples)||void 0===n?void 0:n.length)&&(this._videoDtsBase=t.samples[0].dts),this._dtsBase=Math.min(this._audioDtsBase,this._videoDtsBase),this._dtsBaseInited=!0)},e.prototype.getTimestampBase=function(){if(this._dtsBaseInited)return this._dtsBase},e.prototype.flushStashedSamples=function(){var e=this._videoStashedLastSample,t=this._audioStashedLastSample,i={type:"video",id:1,sequenceNumber:0,samples:[],length:0};null!=e&&(i.samples.push(e),i.length=null==e?void 0:e.length);var n={type:"audio",id:2,sequenceNumber:0,samples:[],length:0};null!=t&&(n.samples.push(t),n.length=null==t?void 0:t.length),this._videoStashedLastSample=null,this._audioStashedLastSample=null,this._remuxVideo(i,!0),this._remuxAudio(n,!0)},e.prototype._remuxAudio=function(e,t){var i,n,a,s,d,l,c;if(null!=this._audioMeta){var h,u,A=e,p=A.samples,_=-1,f=this._audioMeta.refSampleDuration,m="mp3"===this._audioMeta.codec&&this._mp3UseMpegAudio,v=this._dtsBaseInited&&void 0===this._audioNextDts,g=!1;if(p&&0!==p.length&&(1!==p.length||t)){var y=0,b=null,E=0;m?(y=0,E=A.length):(y=8,E=8+A.length);var S=null;if(p.length>1&&(E-=(S=p.pop()).length),null!=this._audioStashedLastSample){var w=this._audioStashedLastSample;this._audioStashedLastSample=null,p.unshift(w),E+=w.length}null!=S&&(this._audioStashedLastSample=S);var T=p[0].dts-this._dtsBase;if(this._audioNextDts)h=T-this._audioNextDts;else if(this._audioSegmentInfoList.isEmpty())h=0,this._fillSilentAfterSeek&&!this._videoSegmentInfoList.isEmpty()&&"mp3"!==this._audioMeta.originalCodec&&(g=!0);else{var B=this._audioSegmentInfoList.getLastSampleBefore(T);if(null!=B){var k=T-(B.originalDts+B.duration);k<=3&&(k=0),h=T-(B.dts+B.duration+k)}else h=0}if(g){var C=T-h,R=this._videoSegmentInfoList.getLastSegmentBefore(T);if(null!=R&&R.beginDts=3*(f||0)&&this._fillAudioTimestampGap&&!o.A.safari){P=!0;var N,G=Math.floor(h/(f||0));r.A.w(this.TAG,"Large audio timestamp gap detected, may cause AV sync to drift. Silent frames will be generated to avoid unsync.\n"+"originalDts: ".concat(M," ms, curRefDts: ").concat(V," ms, ")+"dtsCorrection: ".concat(Math.round(h)," ms, generate: ").concat(G," frames")),O=Math.floor(V),F=Math.floor(V+(f||0))-O,null==(N=Oe.getSilentFrame(null===(a=this._audioMeta)||void 0===a?void 0:a.originalCodec,this._audioMeta.channelCount))&&(r.A.w(this.TAG,"Unable to generate silent frame for "+"".concat(null===(s=this._audioMeta)||void 0===s?void 0:s.originalCodec," with ").concat(this._audioMeta.channelCount," channels, repeat last frame")),N=L),U=[];for(var W=0;W=1?null===(d=x[x.length-1])||void 0===d?void 0:d.duration:Math.floor(f||0),this._audioNextDts=O+F;-1===_&&(_=O),x.push({dts:O,pts:O,cts:0,unit:w.unit,size:null===(l=w.unit)||void 0===l?void 0:l.byteLength,duration:F,originalDts:M,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}}),P&&x.push.apply(x,U)}}if(0===x.length)return A.samples=[],void(A.length=0);for(m?b=new Uint8Array(E):((b=new Uint8Array(E))[0]=E>>>24&255,b[1]=E>>>16&255,b[2]=E>>>8&255,b[3]=255&E,b.set(Re.types.mdat,4)),D=0;D1&&(A-=(p=d.pop()).length),null!=this._videoStashedLastSample){var _=this._videoStashedLastSample;this._videoStashedLastSample=null,d.unshift(_),A+=(null==_?void 0:_.length)||0}null!=p&&(this._videoStashedLastSample=p);var f=d[0].dts-this._dtsBase;if(this._videoNextDts)r=f-this._videoNextDts;else if(this._videoSegmentInfoList.isEmpty())r=0;else{var m=this._videoSegmentInfoList.getLastSampleBefore(f);if(null!=m){var v=f-(m.originalDts+m.duration);v<=3&&(v=0),r=f-(m.dts+m.duration+v)}else r=0}for(var g=new Ie.EZ,y=[],b=0;b=1?y[y.length-1].duration:Math.floor((null===(i=this._videoMeta)||void 0===i?void 0:i.refSampleDuration)||0),S){var C=new Ie.$_(w,B,k,_.dts,!0);C.fileposition=_.fileposition,g.appendSyncPoint(C)}y.push({dts:w,pts:B,cts:T,units:_.units,size:_.length,isKeyframe:S,duration:k,originalDts:E,flags:{isLeading:0,dependsOn:S?2:1,isDependedOn:S?1:0,hasRedundancy:0,isNonSync:S?0:1}})}for((u=new Uint8Array(A))[0]=A>>>24&255,u[1]=A>>>16&255,u[2]=A>>>8&255,u[3]=255&A,u.set(Re.types.mdat,4),b=0;b0)null===(i=this._demuxer)||void 0===i||i.bindDataSource(this._ioctl),this._demuxer.timestampBase=this._mediaDataSource.segments?null===(n=this._mediaDataSource.segments[this._currentSegmentIndex])||void 0===n?void 0:n.timestampBase:0,l=(null===(o=this._demuxer)||void 0===o?void 0:o.parseChunks(e,t))||0;else{var c=null;(c=S.probe(e)).match&&(this._setupFLVDemuxerRemuxer(c),l=(null===(a=this._demuxer)||void 0===a?void 0:a.parseChunks(e,t))||0),c.match||(null==c?void 0:c.needMoreData)||(c=Be.probe(e)).match&&(this._setupTSDemuxerRemuxer(c),l=(null===(s=this._demuxer)||void 0===s?void 0:s.parseChunks(e,t))||0),c.match||(null==c?void 0:c.needMoreData)||(c=null,r.A.e(this.TAG,"Non MPEG-TS/FLV, Unsupported media type!"),Promise.resolve().then((function(){d._internalAbort()})),this._emitter.emit(Le.A.DEMUX_ERROR,_.A.FORMAT_UNSUPPORTED,"Non MPEG-TS/FLV, Unsupported media type!"))}return l},e.prototype._setupFLVDemuxerRemuxer=function(e){var t;this._demuxer=new S(e,this._config),this._remuxer||(this._remuxer=new xe(this._config));var i=this._mediaDataSource;void 0===i.duration||isNaN(i.duration)||(this._demuxer.overridedDuration=i.duration),"boolean"==typeof i.hasAudio&&(this._demuxer.overridedHasAudio=i.hasAudio),"boolean"==typeof i.hasVideo&&(this._demuxer.overridedHasVideo=i.hasVideo),i.segments&&this._demuxer&&this._remuxer&&(this._demuxer.timestampBase=null===(t=null==i?void 0:i.segments[this._currentSegmentIndex])||void 0===t?void 0:t.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))},e.prototype._setupTSDemuxerRemuxer=function(e){var t=this._demuxer=new Be(e,this._config);this._remuxer||(this._remuxer=new xe(this._config)),t.onError=this._onDemuxException.bind(this),t.onMediaInfo=this._onMediaInfo.bind(this),t.onMetaDataArrived=this._onMetaDataArrived.bind(this),t.onTimedID3Metadata=this._onTimedID3Metadata.bind(this),t.onSMPTE2038Metadata=this._onSMPTE2038Metadata.bind(this),t.onSCTE35Metadata=this._onSCTE35Metadata.bind(this),t.onPESPrivateDataDescriptor=this._onPESPrivateDataDescriptor.bind(this),t.onPESPrivateData=this._onPESPrivateData.bind(this),this._remuxer.bindDataSource(this._demuxer),this._demuxer.bindDataSource(this._ioctl),this._remuxer.onInitSegment=this._onRemuxerInitSegmentArrival.bind(this),this._remuxer.onMediaSegment=this._onRemuxerMediaSegmentArrival.bind(this)},e.prototype._onMediaInfo=function(e){var t,i,n=this;null==this._mediaInfo&&(this._mediaInfo=Object.assign({},e),this._mediaInfo.keyframesIndex=null,this._mediaInfo.segments=[],this._mediaInfo.segmentCount=(null===(i=null===(t=this._mediaDataSource)||void 0===t?void 0:t.segments)||void 0===i?void 0:i.length)||0,Object.setPrototypeOf(this._mediaInfo,a.A.prototype));var r=Object.assign({},e);Object.setPrototypeOf(r,a.A.prototype),this._mediaInfo.segments&&(this._mediaInfo.segments[this._currentSegmentIndex]=r),this._reportSegmentMediaInfo(this._currentSegmentIndex),null!=this._pendingSeekTime&&Promise.resolve().then((function(){var e=n._pendingSeekTime;n._pendingSeekTime=null,n.seek(e)}))},e.prototype._onMetaDataArrived=function(e){this._emitter.emit(Le.A.METADATA_ARRIVED,e)},e.prototype._onScriptDataArrived=function(e){this._emitter.emit(Le.A.SCRIPTDATA_ARRIVED,e)},e.prototype._onTimedID3Metadata=function(e){var t,i=null===(t=this._remuxer)||void 0===t?void 0:t.getTimestampBase();void 0!==i&&(void 0!==e.pts&&(e.pts-=i),void 0!==e.dts&&(e.dts-=i),this._emitter.emit(Le.A.TIMED_ID3_METADATA_ARRIVED,e))},e.prototype._onSMPTE2038Metadata=function(e){var t,i=null===(t=this._remuxer)||void 0===t?void 0:t.getTimestampBase();void 0!==i&&(void 0!==e.pts&&(e.pts-=i),void 0!==e.dts&&(e.dts-=i),void 0!==e.nearest_pts&&(e.nearest_pts-=i),this._emitter.emit(Le.A.SMPTE2038_METADATA_ARRIVED,e))},e.prototype._onSCTE35Metadata=function(e){var t,i=null===(t=this._remuxer)||void 0===t?void 0:t.getTimestampBase();void 0!==i&&(void 0!==e.pts&&(e.pts-=i),void 0!==e.nearest_pts&&(e.nearest_pts-=i),this._emitter.emit(Le.A.SCTE35_METADATA_ARRIVED,e))},e.prototype._onPESPrivateDataDescriptor=function(e){this._emitter.emit(Le.A.PES_PRIVATE_DATA_DESCRIPTOR,e)},e.prototype._onPESPrivateData=function(e){var t,i=null===(t=this._remuxer)||void 0===t?void 0:t.getTimestampBase();void 0!==i&&(void 0!==e.pts&&(e.pts-=i),void 0!==e.nearest_pts&&(e.nearest_pts-=i),void 0!==e.dts&&(e.dts-=i),this._emitter.emit(Le.A.PES_PRIVATE_DATA_ARRIVED,e))},e.prototype._onIOSeeked=function(){var e;null===(e=this._remuxer)||void 0===e||e.insertDiscontinuity()},e.prototype._onIOComplete=function(e){var t,i,n=e+1;n<((null===(i=null===(t=this._mediaDataSource)||void 0===t?void 0:t.segments)||void 0===i?void 0:i.length)||0)?(this._internalAbort(),this._remuxer&&this._remuxer.flushStashedSamples(),this._loadSegment(n)):(this._remuxer&&this._remuxer.flushStashedSamples(),this._emitter.emit(Le.A.LOADING_COMPLETE),this._disableStatisticsReporter())},e.prototype._onIORedirect=function(e){var t,i=null===(t=this._ioctl)||void 0===t?void 0:t.extraData;this._mediaDataSource.segments&&(this._mediaDataSource.segments[i].redirectedURL=e)},e.prototype._onIORecoveredEarlyEof=function(){this._emitter.emit(Le.A.RECOVERED_EARLY_EOF)},e.prototype._onIOException=function(e,t){r.A.e(this.TAG,"IOException: type = ".concat(e,", code = ").concat(t.code,", msg = ").concat(t.msg)),this._emitter.emit(Le.A.IO_ERROR,e,t),this._disableStatisticsReporter()},e.prototype._onDemuxException=function(e,t){r.A.e(this.TAG,"DemuxException: type = ".concat(e,", info = ").concat(t)),this._emitter.emit(Le.A.DEMUX_ERROR,e,t)},e.prototype._onRemuxerInitSegmentArrival=function(e,t){this._emitter.emit(Le.A.INIT_SEGMENT,e,t)},e.prototype._onRemuxerMediaSegmentArrival=function(e,t){if(null==this._pendingSeekTime&&(this._emitter.emit(Le.A.MEDIA_SEGMENT,e,t),null!=this._pendingResolveSeekPoint&&"video"===e)){var i=t.info.syncPoints,n=this._pendingResolveSeekPoint;this._pendingResolveSeekPoint=null,o.A.safari&&i.length>0&&i[0].originalDts===n&&(n=i[0].pts),this._emitter.emit(Le.A.RECOMMEND_SEEKPOINT,n)}},e.prototype._enableStatisticsReporter=function(){null==this._statisticsReporter&&this._reportStatisticsInfo&&(this._statisticsReporter=self.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval))},e.prototype._disableStatisticsReporter=function(){this._statisticsReporter&&(self.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},e.prototype._reportSegmentMediaInfo=function(e){var t,i,n,r,o=(null===(t=this._mediaInfo)||void 0===t?void 0:t.segments)?null===(i=this._mediaInfo)||void 0===i?void 0:i.segments[e]:{},a=Object.assign({},o);a.duration=null===(n=this._mediaInfo)||void 0===n?void 0:n.duration,a.segmentCount=null===(r=this._mediaInfo)||void 0===r?void 0:r.segmentCount,delete a.segments,delete a.keyframesIndex,this._emitter.emit(Le.A.MEDIA_INFO,a)},e.prototype._reportStatisticsInfo=function(){var e,t,i,n,r,o,a={};a.url=null===(e=this._ioctl)||void 0===e?void 0:e.currentURL,a.hasRedirect=null===(t=this._ioctl)||void 0===t?void 0:t.hasRedirect,a.hasRedirect&&(a.redirectedURL=null===(i=this._ioctl)||void 0===i?void 0:i.currentRedirectedURL),a.speed=null===(n=this._ioctl)||void 0===n?void 0:n.currentSpeed,a.loaderType=null===(r=this._ioctl)||void 0===r?void 0:r.loaderType,a.currentSegmentIndex=this._currentSegmentIndex,a.totalSegmentCount=null===(o=this._mediaDataSource.segments)||void 0===o?void 0:o.length,this._emitter.emit(Le.A.STATISTICS_INFO,a)},e}()},716:(e,t,i)=>{i.d(t,{A:()=>n});const n={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",TIMED_ID3_METADATA_ARRIVED:"timed_id3_metadata_arrived",SMPTE2038_METADATA_ARRIVED:"smpte2038_metadata_arrived",SCTE35_METADATA_ARRIVED:"scte35_metadata_arrived",PES_PRIVATE_DATA_DESCRIPTOR:"pes_private_data_descriptor",PES_PRIVATE_DATA_ARRIVED:"pes_private_data_arrived",STATISTICS_INFO:"statistics_info",RECOMMEND_SEEKPOINT:"recommend_seekpoint"}},291:(e,t,i)=>{var n=i(641),r=i(976),o=i(716),a=null,s=function(e,t){self.postMessage({msg:"logcat_callback",data:{type:e,logcat:t}})};function d(e,t){var i={msg:o.A.INIT_SEGMENT,data:{type:e,data:t}};self.postMessage(i,[t.data])}function l(e,t){var i={msg:o.A.MEDIA_SEGMENT,data:{type:e,data:t}};self.postMessage(i,[t.data])}function c(){var e={msg:o.A.LOADING_COMPLETE};self.postMessage(e)}function h(){var e={msg:o.A.RECOVERED_EARLY_EOF};self.postMessage(e)}function u(e){var t={msg:o.A.MEDIA_INFO,data:e};self.postMessage(t)}function A(e){var t={msg:o.A.METADATA_ARRIVED,data:e};self.postMessage(t)}function p(e){var t={msg:o.A.SCRIPTDATA_ARRIVED,data:e};self.postMessage(t)}function _(e){var t={msg:o.A.TIMED_ID3_METADATA_ARRIVED,data:e};self.postMessage(t)}function f(e){var t={msg:o.A.SMPTE2038_METADATA_ARRIVED,data:e};self.postMessage(t)}function m(e){var t={msg:o.A.SCTE35_METADATA_ARRIVED,data:e};self.postMessage(t)}function v(e){var t={msg:o.A.PES_PRIVATE_DATA_DESCRIPTOR,data:e};self.postMessage(t)}function g(e){var t={msg:o.A.PES_PRIVATE_DATA_ARRIVED,data:e};self.postMessage(t)}function y(e){var t={msg:o.A.STATISTICS_INFO,data:e};self.postMessage(t)}function b(e,t){self.postMessage({msg:o.A.IO_ERROR,data:{type:e,info:t}})}function E(e,t){self.postMessage({msg:o.A.DEMUX_ERROR,data:{type:e,info:t}})}function S(e){self.postMessage({msg:o.A.RECOMMEND_SEEKPOINT,data:e})}self.addEventListener("message",(function(e){switch(e.data.cmd){case"init":(a=new r.A(e.data.param[0],e.data.param[1])).on(o.A.IO_ERROR,b),a.on(o.A.DEMUX_ERROR,E),a.on(o.A.INIT_SEGMENT,d),a.on(o.A.MEDIA_SEGMENT,l),a.on(o.A.LOADING_COMPLETE,c),a.on(o.A.RECOVERED_EARLY_EOF,h),a.on(o.A.MEDIA_INFO,u),a.on(o.A.METADATA_ARRIVED,A),a.on(o.A.SCRIPTDATA_ARRIVED,p),a.on(o.A.TIMED_ID3_METADATA_ARRIVED,_),a.on(o.A.SMPTE2038_METADATA_ARRIVED,f),a.on(o.A.SCTE35_METADATA_ARRIVED,m),a.on(o.A.PES_PRIVATE_DATA_DESCRIPTOR,v),a.on(o.A.PES_PRIVATE_DATA_ARRIVED,g),a.on(o.A.STATISTICS_INFO,y),a.on(o.A.RECOMMEND_SEEKPOINT,S);break;case"destroy":a&&(a.destroy(),a=null),self.postMessage({msg:"destroyed"});break;case"start":null==a||a.start();break;case"stop":null==a||a.stop();break;case"seek":null==a||a.seek(e.data.param);break;case"pause":null==a||a.pause();break;case"resume":null==a||a.resume();break;case"logging_config":var t=e.data.param;n.A.applyConfig(t),!0===t.enableCallback?n.A.addLogListener(s):n.A.removeLogListener(s)}}))},465:(e,t,i)=>{i.d(t,{A:()=>n});const n={OK:"OK",FORMAT_ERROR:"FormatError",FORMAT_UNSUPPORTED:"FormatUnsupported",CODEC_UNSUPPORTED:"CodecUnsupported"}},133:(e,t,i)=>{i.d(t,{default:()=>Q});var n={h264:1,h265:2,h266:4,vp8:8,vp9:16,av1:32},r=i(302),o={enableWorker:!1,enableStashBuffer:!0,stashInitialSize:void 0,isLive:!1,liveBufferLatencyChasing:!1,liveBufferLatencyMaxLatency:1.5,liveBufferLatencyMinRemain:.5,lazyLoad:!0,lazyLoadMaxDuration:180,lazyLoadRecoverDuration:30,deferLoadAfterSourceOpen:!0,autoCleanupMaxBackwardDuration:180,autoCleanupMinBackwardDuration:120,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,url:void 0,redirectedURL:void 0,cors:!1};function a(){return Object.assign({},o)}var s=function(){function e(){}return e.supportMSEH264Playback=function(){var e;return null===(e=window.MediaSource)||void 0===e?void 0:e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"')},e.supportMSEH265Playback=function(){var e;return null===(e=window.MediaSource)||void 0===e?void 0:e.isTypeSupported('video/mp4; codecs="hvc1.1.6.L93.B0"')},e.supportNetworkStreamIO=function(){var e=new r.A({},a()),t=e.loaderType;return e.destroy(),"fetch-stream-loader"===t||"xhr-moz-chunked-loader"===t},e.getNetworkLoaderTypeName=function(){var e=new r.A({},a()),t=e.loaderType;return e.destroy(),t},e.supportNativeMediaPlayback=function(t){void 0===e.videoElement&&(e.videoElement=window.document.createElement("video"));var i=e.videoElement.canPlayType(t);return"probably"===i||"maybe"===i},e.getFeatureList=function(){var t={msePlayback:!1,mseLivePlayback:!1,mseH265Playback:!1,networkStreamIO:!1,networkLoaderName:"",nativeMP4H264Playback:!1,nativeMP4H265Playback:!1,nativeWebmVP8Playback:!1,nativeWebmVP9Playback:!1};return t.msePlayback=e.supportMSEH264Playback(),t.networkStreamIO=e.supportNetworkStreamIO(),t.networkLoaderName=e.getNetworkLoaderTypeName()||"",t.mseLivePlayback=t.msePlayback&&t.networkStreamIO,t.mseH265Playback=e.supportMSEH265Playback(),t.nativeMP4H264Playback=e.supportNativeMediaPlayback('video/mp4; codecs="avc1.42001E, mp4a.40.2"'),t.nativeMP4H265Playback=e.supportNativeMediaPlayback('video/mp4; codecs="hvc1.1.6.L93.B0"'),t.nativeWebmVP8Playback=e.supportNativeMediaPlayback('video/webm; codecs="vp8.0, vorbis"'),t.nativeWebmVP9Playback=e.supportNativeMediaPlayback('video/webm; codecs="vp9"'),t},e}();const d=s;var l=i(288),c=i(413),h=i(502),u=i(620);const A={ERROR:"error",LOADING_COMPLETE:"loading_complete",RECOVERED_EARLY_EOF:"recovered_early_eof",MEDIA_INFO:"media_info",METADATA_ARRIVED:"metadata_arrived",SCRIPTDATA_ARRIVED:"scriptdata_arrived",TIMED_ID3_METADATA_ARRIVED:"timed_id3_metadata_arrived",SMPTE2038_METADATA_ARRIVED:"smpte2038_metadata_arrived",SCTE35_METADATA_ARRIVED:"scte35_metadata_arrived",PES_PRIVATE_DATA_DESCRIPTOR:"pes_private_data_descriptor",PES_PRIVATE_DATA_ARRIVED:"pes_private_data_arrived",STATISTICS_INFO:"statistics_info",DESTROYING:"destroying"},p=function(){const e=ENTRY_MODULE,t={};function i(n){if(t[n])return t[n].exports;const r=t[n]={exports:{}};return e[n](r,r.exports,i),r.exports}i.m=e,i.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(const n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.g=function(){if("[object Object]"===Object.prototype.toString.call(globalThis))return globalThis;try{return this||new Function("return this")()}catch(e){if("[object Object]"===Object.prototype.toString.call(window))return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};const n=i(ENTRY_MODULE);return n.default||n};p.toString();const _="[\\.|\\-|\\+|\\w|/|@]+",f="\\(\\s*(/\\*.*?\\*/)?\\s*.*?("+_+").*?\\)";function m(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function v(e){return!isNaN(1*e)}function g(e,t,n){const r={};r[n]=[];const o=t.toString(),a=o.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)||o.match(/^\(\w+,\s*\w+,\s*(\w+)\)\s?\=\s?\>/);if(!a)return r;const s=a[1];let d,l=new RegExp("(\\\\n|\\W)"+m(s)+f,"g");for(;d=l.exec(o);)"dll-reference"!==d[3]&&r[n].push(d[3]);for(l=new RegExp("\\("+m(s)+'\\("(dll-reference\\s('+_+'))"\\)\\)'+f,"g");d=l.exec(o);)e[d[2]]||(r[n].push(d[1]),e[d[2]]=i(d[1]).m),r[d[2]]=r[d[2]]||[],r[d[2]].push(d[4]);const c=Object.keys(r);for(let e=0;et||e[i].length>0),!1)}function b(e,t,i,n){const r=e[n].map((e=>`"${e}": ${t[n][e].toString()}`)).join(","),o=p.toString().split("ENTRY_MODULE");return`${o[0]}{${r}}${o[1]}"${i}"${o[2]}`}function E(e,t){t=t||{};const n={main:i.m},r=t.all?{main:Object.keys(n.main)}:function(e,t){const i={main:[t]},n={main:[]},r={main:{}};for(;y(i);){const t=Object.keys(i);for(let o=0;o"main"!==e)).forEach((e=>{let t=0;for(;r[e][t];)t++;r[e].push(t),n[e][t]="(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })",o+=`var ${e} = (${b(r,n,t,modules)})();\n`})),o+=`(${b(r,n,e,"main")})();`;const a=new window.Blob([o],{type:"text/javascript"});if(t.bare)return a;const s=(window.URL||window.webkitURL||window.mozURL||window.msURL).createObjectURL(a),d=new window.Worker(s);return d.objectURL=s,d}var S=i(641),w=i(976),T=i(716),B=i(825),k=function(){function e(e,t){if(this.TAG="Transmuxer",this._workerDestroying=!1,this._controller=null,this._emitter=new c.A,t.enableWorker&&"undefined"!=typeof Worker)try{this._worker=this._worker=E(291),this._workerDestroying=!1,this._worker.addEventListener("message",this._onWorkerMessage.bind(this)),this._worker.postMessage({cmd:"init",param:[e,t]}),this.e={onLoggingConfigChanged:this._onLoggingConfigChanged.bind(this)},S.A.registerListener(this.e.onLoggingConfigChanged),this._worker.postMessage({cmd:"logging_config",param:S.A.getConfig()})}catch(i){h.A.e(this.TAG,"Error while initialize transmuxing worker, fallback to inline transmuxing"),this._worker=null,this._controller=new w.A(e,t)}else this._controller=new w.A(e,t);if(this._controller){var i=this._controller;null==i||i.on(T.A.IO_ERROR,this._onIOError.bind(this)),null==i||i.on(T.A.DEMUX_ERROR,this._onDemuxError.bind(this)),null==i||i.on(T.A.INIT_SEGMENT,this._onInitSegment.bind(this)),null==i||i.on(T.A.MEDIA_SEGMENT,this._onMediaSegment.bind(this)),null==i||i.on(T.A.LOADING_COMPLETE,this._onLoadingComplete.bind(this)),null==i||i.on(T.A.RECOVERED_EARLY_EOF,this._onRecoveredEarlyEof.bind(this)),null==i||i.on(T.A.MEDIA_INFO,this._onMediaInfo.bind(this)),null==i||i.on(T.A.METADATA_ARRIVED,this._onMetaDataArrived.bind(this)),null==i||i.on(T.A.SCRIPTDATA_ARRIVED,this._onScriptDataArrived.bind(this)),null==i||i.on(T.A.TIMED_ID3_METADATA_ARRIVED,this._onTimedID3MetadataArrived.bind(this)),null==i||i.on(T.A.SMPTE2038_METADATA_ARRIVED,this._onSMPTE2038MetadataArrived.bind(this)),null==i||i.on(T.A.SCTE35_METADATA_ARRIVED,this._onSCTE35MetadataArrived.bind(this)),null==i||i.on(T.A.PES_PRIVATE_DATA_DESCRIPTOR,this._onPESPrivateDataDescriptor.bind(this)),null==i||i.on(T.A.PES_PRIVATE_DATA_ARRIVED,this._onPESPrivateDataArrived.bind(this)),null==i||i.on(T.A.STATISTICS_INFO,this._onStatisticsInfo.bind(this)),null==i||i.on(T.A.RECOMMEND_SEEKPOINT,this._onRecommendSeekpoint.bind(this))}}return e.prototype.destroy=function(){var e;this._worker?this._workerDestroying||(this._workerDestroying=!0,this._worker.postMessage({cmd:"destroy"}),S.A.removeListener(this.e.onLoggingConfigChanged),this.e=null):(null===(e=this._controller)||void 0===e||e.destroy(),this._controller=null),this._emitter.removeAllListeners(),this._emitter=null},e.prototype.on=function(e,t){this._emitter.addListener(e,t)},e.prototype.off=function(e,t){this._emitter.removeListener(e,t)},e.prototype.hasWorker=function(){return null!=this._worker},e.prototype.open=function(){var e;this._worker?this._worker.postMessage({cmd:"start"}):null===(e=this._controller)||void 0===e||e.start()},e.prototype.close=function(){var e;this._worker?this._worker.postMessage({cmd:"stop"}):null===(e=this._controller)||void 0===e||e.stop()},e.prototype.seek=function(e){var t;this._worker?this._worker.postMessage({cmd:"seek",param:e}):null===(t=this._controller)||void 0===t||t.seek(e)},e.prototype.pause=function(){var e;this._worker?this._worker.postMessage({cmd:"pause"}):null===(e=this._controller)||void 0===e||e.pause()},e.prototype.resume=function(){var e;this._worker?this._worker.postMessage({cmd:"resume"}):null===(e=this._controller)||void 0===e||e.resume()},e.prototype._onInitSegment=function(e,t){var i=this;Promise.resolve().then((function(){i._emitter.emit(T.A.INIT_SEGMENT,e,t)}))},e.prototype._onMediaSegment=function(e,t){var i=this;Promise.resolve().then((function(){i._emitter.emit(T.A.MEDIA_SEGMENT,e,t)}))},e.prototype._onLoadingComplete=function(){var e=this;Promise.resolve().then((function(){e._emitter.emit(T.A.LOADING_COMPLETE)}))},e.prototype._onRecoveredEarlyEof=function(){var e=this;Promise.resolve().then((function(){e._emitter.emit(T.A.RECOVERED_EARLY_EOF)}))},e.prototype._onMediaInfo=function(e){var t=this;Promise.resolve().then((function(){t._emitter.emit(T.A.MEDIA_INFO,e)}))},e.prototype._onMetaDataArrived=function(e){var t=this;Promise.resolve().then((function(){t._emitter.emit(T.A.METADATA_ARRIVED,e)}))},e.prototype._onScriptDataArrived=function(e){var t=this;Promise.resolve().then((function(){t._emitter.emit(T.A.SCRIPTDATA_ARRIVED,e)}))},e.prototype._onTimedID3MetadataArrived=function(e){var t=this;Promise.resolve().then((function(){t._emitter.emit(T.A.TIMED_ID3_METADATA_ARRIVED,e)}))},e.prototype._onSMPTE2038MetadataArrived=function(e){var t=this;Promise.resolve().then((function(){t._emitter.emit(T.A.SMPTE2038_METADATA_ARRIVED,e)}))},e.prototype._onSCTE35MetadataArrived=function(e){var t=this;Promise.resolve().then((function(){t._emitter.emit(T.A.SCTE35_METADATA_ARRIVED,e)}))},e.prototype._onPESPrivateDataDescriptor=function(e){var t=this;Promise.resolve().then((function(){t._emitter.emit(T.A.PES_PRIVATE_DATA_DESCRIPTOR,e)}))},e.prototype._onPESPrivateDataArrived=function(e){var t=this;Promise.resolve().then((function(){t._emitter.emit(T.A.PES_PRIVATE_DATA_ARRIVED,e)}))},e.prototype._onStatisticsInfo=function(e){var t=this;Promise.resolve().then((function(){t._emitter.emit(T.A.STATISTICS_INFO,e)}))},e.prototype._onIOError=function(e,t){var i=this;Promise.resolve().then((function(){i._emitter.emit(T.A.IO_ERROR,e,t)}))},e.prototype._onDemuxError=function(e,t){var i=this;Promise.resolve().then((function(){i._emitter.emit(T.A.DEMUX_ERROR,e,t)}))},e.prototype._onRecommendSeekpoint=function(e){var t=this;Promise.resolve().then((function(){t._emitter.emit(T.A.RECOMMEND_SEEKPOINT,e)}))},e.prototype._onLoggingConfigChanged=function(e){this._worker&&this._worker.postMessage({cmd:"logging_config",param:e})},e.prototype._onWorkerMessage=function(e){var t=e.data,i=null==t?void 0:t.data;if("destroyed"===t.msg||this._workerDestroying)return this._workerDestroying=!1,this._worker.terminate(),void(this._worker=null);switch(t.msg){case T.A.INIT_SEGMENT:case T.A.MEDIA_SEGMENT:this._emitter.emit(t.msg,i.type,i.data);break;case T.A.LOADING_COMPLETE:case T.A.RECOVERED_EARLY_EOF:this._emitter.emit(t.msg);break;case T.A.MEDIA_INFO:Object.setPrototypeOf(i,B.A.prototype),this._emitter.emit(t.msg,i);break;case T.A.METADATA_ARRIVED:case T.A.SCRIPTDATA_ARRIVED:case T.A.TIMED_ID3_METADATA_ARRIVED:case T.A.SMPTE2038_METADATA_ARRIVED:case T.A.SCTE35_METADATA_ARRIVED:case T.A.PES_PRIVATE_DATA_DESCRIPTOR:case T.A.PES_PRIVATE_DATA_ARRIVED:case T.A.STATISTICS_INFO:this._emitter.emit(t.msg,i);break;case T.A.IO_ERROR:case T.A.DEMUX_ERROR:this._emitter.emit(t.msg,i.type,i.info);break;case T.A.RECOMMEND_SEEKPOINT:this._emitter.emit(t.msg,i);break;case"logcat_callback":h.A.emitter.emit("log",i.type,i.logcat)}},e}();const C=k,R="error",O="source_open",I="update_end",x="buffer_full";var D=i(453),L=i(713),M=function(){function e(e){this.TAG="MSEController",this._config=e,this._emitter=new c.A,this._config.isLive&&void 0===this._config.autoCleanupSourceBuffer&&(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 D.EX}return e.prototype.destroy=function(){(this._mediaElement||this._mediaSource)&&this.detachMediaElement(),this.e=null,this._emitter.removeAllListeners(),this._emitter=null},e.prototype.on=function(e,t){this._emitter.addListener(e,t)},e.prototype.off=function(e,t){this._emitter.removeListener(e,t)},e.prototype.attachMediaElement=function(e){if(this._mediaSource)throw new L.j4("MediaSource has been attached to an HTMLMediaElement!");var t=this._mediaSource=new window.MediaSource;t.addEventListener("sourceopen",this.e.onSourceOpen),t.addEventListener("sourceended",this.e.onSourceEnded),t.addEventListener("sourceclose",this.e.onSourceClose),this._mediaElement=e,this._mediaSourceObjectURL=window.URL.createObjectURL(this._mediaSource),e.src=this._mediaSourceObjectURL},e.prototype.detachMediaElement=function(){if(this._mediaSource){var e=this._mediaSource;for(var t in this._sourceBuffers){var i=this._pendingSegments[t];i.splice(0,i.length),this._pendingSegments[t]=null,this._pendingRemoveRanges[t]=null,this._lastInitSegments[t]=null;var n=this._sourceBuffers[t];if(n){if("closed"!==e.readyState){try{e.removeSourceBuffer(n)}catch(e){h.A.e(this.TAG,e.message)}null==n||n.removeEventListener("error",this.e.onSourceBufferError),null==n||n.removeEventListener("updateend",this.e.onSourceBufferUpdateEnd)}this._mimeTypes[t]=null,this._sourceBuffers[t]=null}}if("open"===e.readyState)try{e.endOfStream()}catch(e){h.A.e(this.TAG,e.message)}e.removeEventListener("sourceopen",this.e.onSourceOpen),e.removeEventListener("sourceended",this.e.onSourceEnded),e.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)},e.prototype.appendInitSegment=function(e,t){var i;if(!this._mediaSource||"open"!==this._mediaSource.readyState)return this._pendingSourceBufferInit.push(e),void this._pendingSegments[e.type].push(e);var n=e,r="".concat(n.container);n.codec&&n.codec.length>0&&(r+=";codecs=".concat(n.codec));var o=!1;if(h.A.v(this.TAG,"Received Initialization Segment, mimeType: "+r),this._lastInitSegments[n.type]=n,r!==this._mimeTypes[n.type]){if(this._mimeTypes[n.type])h.A.v(this.TAG,"Notice: ".concat(n.type," mimeType changed, origin: ").concat(this._mimeTypes[n.type]||"",", target: ").concat(r));else{o=!0;try{var a=this._sourceBuffers[n.type]=this._mediaSource.addSourceBuffer(r);a.addEventListener("error",this.e.onSourceBufferError),a.addEventListener("updateend",this.e.onSourceBufferUpdateEnd)}catch(e){return h.A.e(this.TAG,e.message),void this._emitter.emit(R,{code:e.code,msg:e.message})}}this._mimeTypes[n.type]=r}t||this._pendingSegments[n.type].push(n),o||this._sourceBuffers[n.type]&&!(null===(i=this._sourceBuffers[n.type])||void 0===i?void 0:i.updating)&&this._doAppendSegments(),u.A.safari&&"audio/mpeg"===n.container&&n.mediaDuration>0&&(this._requireSetMediaDuration=!0,this._pendingMediaDuration=n.mediaDuration/1e3,this._updateMediaSourceDuration())},e.prototype.appendMediaSegment=function(e){var t=e;this._pendingSegments[t.type].push(t),this._config.autoCleanupSourceBuffer&&this._needCleanupSourceBuffer()&&this._doCleanupSourceBuffer();var i=this._sourceBuffers[t.type];!i||i.updating||this._hasPendingRemoveRanges()||this._doAppendSegments()},e.prototype.seek=function(e){var t,i;for(var n in this._sourceBuffers)if(this._sourceBuffers[n]){var r=this._sourceBuffers[n];if("open"===(null===(t=this._mediaSource)||void 0===t?void 0:t.readyState))try{null==r||r.abort()}catch(e){h.A.e(this.TAG,e.message)}this._idrList.clear();var o=this._pendingSegments[n];if(o.splice(0,o.length),"closed"!==(null===(i=this._mediaSource)||void 0===i?void 0:i.readyState)){if(r){for(var a=0;a=1&&i-o.start(0)>=((null===(t=this._config)||void 0===t?void 0:t.autoCleanupMaxBackwardDuration)||0))return!0}}return!1},e.prototype._doCleanupSourceBuffer=function(){var e,t,i,n=null===(e=this._mediaElement)||void 0===e?void 0:e.currentTime;for(var r in this._sourceBuffers){var o=this._sourceBuffers[r];if(o){for(var a=o.buffered,s=!1,d=0;d=((null===(t=this._config)||void 0===t?void 0:t.autoCleanupMaxBackwardDuration)||0)){s=!0;var h=n-((null===(i=this._config)||void 0===i?void 0:i.autoCleanupMinBackwardDuration)||0);this._pendingRemoveRanges[r].push({start:l,end:h})}}else c0&&(isNaN(o)||a>o)&&(h.A.v(this.TAG,"Update MediaSource duration from ".concat(o," to ").concat(a)),this._mediaSource.duration=a),this._requireSetMediaDuration=!1,this._pendingMediaDuration=0}},e.prototype._doRemoveRanges=function(){var e;for(var t in this._pendingRemoveRanges)if(this._sourceBuffers[t]&&!(null===(e=this._sourceBuffers[t])||void 0===e?void 0:e.updating))for(var i=this._sourceBuffers[t],n=this._pendingRemoveRanges[t];n.length&&!(null==i?void 0:i.updating);){var r=n.shift();null==i||i.remove(r.start,r.end)}},e.prototype._doAppendSegments=function(){var e,t,i,n=this._pendingSegments;for(var r in n)if(this._sourceBuffers[r]&&!(null===(e=this._sourceBuffers[r])||void 0===e?void 0:e.updating)&&n[r].length>0){var o=n[r].shift();if(null==o?void 0:o.timestampOffset){var a=(null===(t=this._sourceBuffers[r])||void 0===t?void 0:t.timestampOffset)||0,s=o.timestampOffset/1e3;Math.abs(a-s)>.1&&(h.A.v(this.TAG,"Update MPEG audio timestampOffset from ".concat(a," to ").concat(s)),this._sourceBuffers[r]&&(this._sourceBuffers[r].timestampOffset=s)),delete o.timestampOffset}if(!o.data||0===o.data.byteLength)continue;try{null===(i=this._sourceBuffers[r])||void 0===i||i.appendBuffer(o.data),this._isBufferFull=!1,"video"===r&&o.hasOwnProperty("info")&&this._idrList.appendArray(o.info.syncPoints)}catch(e){this._pendingSegments[r].unshift(o),22===e.code?(this._isBufferFull||this._emitter.emit(x),this._isBufferFull=!0):(h.A.e(this.TAG,e.message),this._emitter.emit(R,{code:e.code,msg:e.message}))}}},e.prototype._onSourceOpen=function(){var e;if(h.A.v(this.TAG,"MediaSource onSourceOpen"),null===(e=this._mediaSource)||void 0===e||e.removeEventListener("sourceopen",this.e.onSourceOpen),this._pendingSourceBufferInit.length>0)for(var t=this._pendingSourceBufferInit;t.length;){var i=t.shift();this.appendInitSegment(i,!0)}this._hasPendingSegments()&&this._doAppendSegments(),this._emitter.emit(O)},e.prototype._onSourceEnded=function(){h.A.v(this.TAG,"MediaSource onSourceEnded")},e.prototype._onSourceClose=function(){h.A.v(this.TAG,"MediaSource onSourceClose"),this._mediaSource&&null!=this.e&&(this._mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this._mediaSource.removeEventListener("sourceended",this.e.onSourceEnded),this._mediaSource.removeEventListener("sourceclose",this.e.onSourceClose))},e.prototype._hasPendingSegments=function(){var e=this._pendingSegments;return e.video.length>0||e.audio.length>0},e.prototype._hasPendingRemoveRanges=function(){var e=this._pendingRemoveRanges;return e.video.length>0||e.audio.length>0},e.prototype._onSourceBufferUpdateEnd=function(){this._requireSetMediaDuration?this._updateMediaSourceDuration():this._hasPendingRemoveRanges()?this._doRemoveRanges():this._hasPendingSegments()?this._doAppendSegments():this._hasPendingEos&&this.endOfStream(),this._emitter.emit(I)},e.prototype._onSourceBufferError=function(e){h.A.e(this.TAG,"SourceBuffer Error: ".concat(e))},e}();const P=M;var U=i(465),F={NETWORK_ERROR:"NetworkError",MEDIA_ERROR:"MediaError",OTHER_ERROR:"OtherError"},V={NETWORK_EXCEPTION:l.Xv.EXCEPTION,NETWORK_STATUS_CODE_INVALID:l.Xv.HTTP_STATUS_CODE_INVALID,NETWORK_TIMEOUT:l.Xv.CONNECTING_TIMEOUT,NETWORK_UNRECOVERABLE_EARLY_EOF:l.Xv.UNRECOVERABLE_EARLY_EOF,MEDIA_MSE_ERROR:"MediaMSEError",MEDIA_FORMAT_ERROR:U.A.FORMAT_ERROR,MEDIA_FORMAT_UNSUPPORTED:U.A.FORMAT_UNSUPPORTED,MEDIA_CODEC_UNSUPPORTED:U.A.CODEC_UNSUPPORTED},N=function(){function e(e,t){var i,n,r;this.TAG="MSEPlayer",this._type="MSEPlayer",this._emitter=new c.A,this._config=a(),"object"==typeof t&&Object.assign(this._config,t);var o=e.type.toLowerCase();if("mse"!==o&&"mpegts"!==o&&"m2ts"!==o&&"flv"!==o)throw new L.Qn("MSEPlayer requires an mpegts/m2ts/flv MediaDataSource input!");e.isLive&&(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=e,this._mediaElement=null,this._msectl=null,this._transmuxer=null,this._mseSourceOpened=!1,this._hasPendingLoad=!1,this._receivedCanPlay=!1,this._mediaInfo=null,this._statisticsInfo=null;var s=u.A.chrome&&(u.A.version&&(null===(i=u.A.version)||void 0===i?void 0:i.major)<50||u.A.version&&50===(null===(n=null===u.A||void 0===u.A?void 0:u.A.version)||void 0===n?void 0:n.major)&&((null===(r=null===u.A||void 0===u.A?void 0:u.A.version)||void 0===r?void 0:r.build)||-1)<2661);this._alwaysSeekKeyframe=!!(s||u.A.msedge||u.A.msie),this._alwaysSeekKeyframe&&(this._config.accurateSeek=!1)}return e.prototype.destroy=function(){this._emitter.emit(A.DESTROYING),null!=this._progressChecker&&(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},e.prototype.on=function(e,t){var i=this;e===A.MEDIA_INFO?null!=this._mediaInfo&&Promise.resolve().then((function(){i._emitter.emit(A.MEDIA_INFO,i.mediaInfo)})):e===A.STATISTICS_INFO&&null!=this._statisticsInfo&&Promise.resolve().then((function(){i._emitter.emit(A.STATISTICS_INFO,i.statisticsInfo)})),this._emitter.addListener(e,t)},e.prototype.off=function(e,t){this._emitter.removeListener(e,t)},e.prototype.attachMediaElement=function(e){var t,i,n,r,o,a=this;if(this._mediaElement=e,e.addEventListener("loadedmetadata",this.e.onvLoadedMetadata),e.addEventListener("seeking",this.e.onvSeeking),e.addEventListener("canplay",this.e.onvCanPlay),e.addEventListener("stalled",this.e.onvStalled),e.addEventListener("progress",this.e.onvProgress),this._msectl=new P(this._config),null===(t=this._msectl)||void 0===t||t.on(I,this._onmseUpdateEnd.bind(this)),null===(i=this._msectl)||void 0===i||i.on(x,this._onmseBufferFull.bind(this)),null===(n=this._msectl)||void 0===n||n.on(O,(function(){a._mseSourceOpened=!0,a._hasPendingLoad&&(a._hasPendingLoad=!1,a.load())})),null===(r=this._msectl)||void 0===r||r.on(R,(function(e){a._emitter.emit(A.ERROR,F.MEDIA_ERROR,V.MEDIA_MSE_ERROR,e)})),null===(o=this._msectl)||void 0===o||o.attachMediaElement(e),null!=this._pendingSeekTime)try{e.currentTime=this._pendingSeekTime,this._pendingSeekTime=null}catch(e){}},e.prototype.detachMediaElement=function(){var e;this._mediaElement&&(null===(e=this._msectl)||void 0===e||e.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)},e.prototype.load=function(){var e=this;if(!this._mediaElement)throw new L.j4("HTMLMediaElement must be attached before load()!");if(this._transmuxer)throw new L.j4("MSEPlayer.load() has been called, please call unload() first!");this._hasPendingLoad||(!this._config.deferLoadAfterSourceOpen||this._mseSourceOpened?(this._mediaElement.readyState>0&&(this._requestSetTime=!0,this._mediaElement.currentTime=0),this._transmuxer=new C(this._mediaDataSource,this._config),this._transmuxer.on(T.A.INIT_SEGMENT,(function(t,i){var n;null===(n=e._msectl)||void 0===n||n.appendInitSegment(i)})),this._transmuxer.on(T.A.MEDIA_SEGMENT,(function(t,i){var n,r,o;if(null===(n=e._msectl)||void 0===n||n.appendMediaSegment(i),e._config.lazyLoad&&!e._config.isLive){var a=null===(r=e._mediaElement)||void 0===r?void 0:r.currentTime;i.info.endDts>=1e3*(a+((null===(o=e._config)||void 0===o?void 0:o.lazyLoadMaxDuration)||0))&&null==e._progressChecker&&(h.A.v(e.TAG,"Maximum buffering duration exceeded, suspend transmuxing task"),e._suspendTransmuxer())}})),this._transmuxer.on(T.A.LOADING_COMPLETE,(function(){var t;null===(t=e._msectl)||void 0===t||t.endOfStream(),e._emitter.emit(A.LOADING_COMPLETE)})),this._transmuxer.on(T.A.RECOVERED_EARLY_EOF,(function(){e._emitter.emit(A.RECOVERED_EARLY_EOF)})),this._transmuxer.on(T.A.IO_ERROR,(function(t,i){e._emitter.emit(A.ERROR,F.NETWORK_ERROR,t,i)})),this._transmuxer.on(T.A.DEMUX_ERROR,(function(t,i){e._emitter.emit(A.ERROR,F.MEDIA_ERROR,t,{code:-1,msg:i})})),this._transmuxer.on(T.A.MEDIA_INFO,(function(t){e._mediaInfo=t,e._emitter.emit(A.MEDIA_INFO,Object.assign({},t))})),this._transmuxer.on(T.A.METADATA_ARRIVED,(function(t){e._emitter.emit(A.METADATA_ARRIVED,t)})),this._transmuxer.on(T.A.SCRIPTDATA_ARRIVED,(function(t){e._emitter.emit(A.SCRIPTDATA_ARRIVED,t)})),this._transmuxer.on(T.A.TIMED_ID3_METADATA_ARRIVED,(function(t){e._emitter.emit(A.TIMED_ID3_METADATA_ARRIVED,t)})),this._transmuxer.on(T.A.SMPTE2038_METADATA_ARRIVED,(function(t){e._emitter.emit(A.SMPTE2038_METADATA_ARRIVED,t)})),this._transmuxer.on(T.A.SCTE35_METADATA_ARRIVED,(function(t){e._emitter.emit(A.SCTE35_METADATA_ARRIVED,t)})),this._transmuxer.on(T.A.PES_PRIVATE_DATA_DESCRIPTOR,(function(t){e._emitter.emit(A.PES_PRIVATE_DATA_DESCRIPTOR,t)})),this._transmuxer.on(T.A.PES_PRIVATE_DATA_ARRIVED,(function(t){e._emitter.emit(A.PES_PRIVATE_DATA_ARRIVED,t)})),this._transmuxer.on(T.A.STATISTICS_INFO,(function(t){e._statisticsInfo=e._fillStatisticsInfo(t),e._emitter.emit(A.STATISTICS_INFO,Object.assign({},e._statisticsInfo))})),this._transmuxer.on(T.A.RECOMMEND_SEEKPOINT,(function(t){e._mediaElement&&!e._config.accurateSeek&&(e._requestSetTime=!0,e._mediaElement.currentTime=t/1e3)})),this._transmuxer.open()):this._hasPendingLoad=!0)},e.prototype.unload=function(){this._mediaElement&&this._mediaElement.pause(),this._msectl&&this._msectl.seek(0),this._transmuxer&&(this._transmuxer.close(),this._transmuxer.destroy(),this._transmuxer=null)},e.prototype.play=function(){var e;return function(e,t,i,n){return new(i||(i=Promise))((function(t,r){function o(e){try{s(n.next(e))}catch(e){r(e)}}function a(e){try{s(n.throw(e))}catch(e){r(e)}}function s(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i((function(e){e(n)}))).then(o,a)}s((n=n.apply(e,[])).next())}))}(this,0,void 0,(function(){return function(e,t){var i,n,r,o,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(d){return function(s){if(i)throw new TypeError("Generator is already executing.");for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&s[0]?n.return:s[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,s[1])).done)return r;switch(n=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,n=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]0&&!(null===(i=this._mediaElement)||void 0===i?void 0:i.paused)){var a=r.end(r.length-1);if(a>((null===(n=this._config)||void 0===n?void 0:n.liveBufferLatencyMaxLatency)||0)&&a-o>(this._config.liveBufferLatencyMaxLatency||0)){var s=a-(this._config.liveBufferLatencyMinRemain||0);this.currentTime=s}}if(this._config.lazyLoad&&!this._config.isLive){for(var d=0,l=0;l=o+(this._config.lazyLoadMaxDuration||0)&&null==this._progressChecker&&(h.A.v(this.TAG,"Maximum buffering duration exceeded, suspend transmuxing task"),this._suspendTransmuxer())}},e.prototype._onmseBufferFull=function(){h.A.v(this.TAG,"MSE SourceBuffer is full, suspend transmuxing task"),null==this._progressChecker&&this._suspendTransmuxer()},e.prototype._suspendTransmuxer=function(){this._transmuxer&&(this._transmuxer.pause(),null==this._progressChecker&&(this._progressChecker=window.setInterval(this._checkProgressAndResume.bind(this),1e3)))},e.prototype._checkProgressAndResume=function(){for(var e,t,i,n=(null===(e=this._mediaElement)||void 0===e?void 0:e.currentTime)||0,r=null===(t=this._mediaElement)||void 0===t?void 0:t.buffered,o=!1,a=0;a=s&&n=d-(this._config.lazyLoadRecoverDuration||0)&&(o=!0);break}}o&&(window.clearInterval(this._progressChecker),this._progressChecker=null,o&&(h.A.v(this.TAG,"Continue loading from paused position"),null===(i=this._transmuxer)||void 0===i||i.resume()))},e.prototype._isTimepointBuffered=function(e){for(var t,i=null===(t=this._mediaElement)||void 0===t?void 0:t.buffered,n=0;n=r&&e0){var l=(null===(i=this._mediaElement)||void 0===i?void 0:i.buffered).start(0);(l<1&&e0&&t.currentTime0){var a=o.start(0);if(a<1&&r0&&(this._mediaElement.currentTime=0),this._mediaElement.preload="auto",this._mediaElement.load(),this._statisticsReporter=window.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval)},e.prototype.unload=function(){this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src")),null!=this._statisticsReporter&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},e.prototype.play=function(){var e;return function(e,t,i,n){return new(i||(i=Promise))((function(t,r){function o(e){try{s(n.next(e))}catch(e){r(e)}}function a(e){try{s(n.throw(e))}catch(e){r(e)}}function s(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i((function(e){e(n)}))).then(o,a)}s((n=n.apply(e,[])).next())}))}(this,0,void 0,(function(){return function(e,t){var i,n,r,o,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(d){return function(s){if(i)throw new TypeError("Generator is already executing.");for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(i=1,n&&(r=2&s[0]?n.return:s[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,s[1])).done)return r;switch(n=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,n=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]{e.exports=i(133).default},302:(e,t,i)=>{i.d(t,{A:()=>g});var n=i(502);const r=function(){function e(){var e;this._firstCheckpoint=0,this._lastCheckpoint=0,this._intervalBytes=0,this._totalBytes=0,this._lastSecondBytes=0,(null===(e=self.performance)||void 0===e?void 0:e.now)?this._now=self.performance.now.bind(self.performance):this._now=Date.now}return e.prototype.reset=function(){this._firstCheckpoint=this._lastCheckpoint=0,this._totalBytes=this._intervalBytes=0,this._lastSecondBytes=0},e.prototype.addBytes=function(e){0===this._firstCheckpoint?(this._firstCheckpoint=this._now(),this._lastCheckpoint=this._firstCheckpoint,this._intervalBytes+=e,this._totalBytes+=e):this._now()-this._lastCheckpoint<1e3?(this._intervalBytes+=e,this._totalBytes+=e):(this._lastSecondBytes=this._intervalBytes,this._intervalBytes=e,this._totalBytes+=e,this._lastCheckpoint=this._now())},Object.defineProperty(e.prototype,"currentKBps",{get:function(){this.addBytes(0);var e=(this._now()-this._lastCheckpoint)/1e3;return 0===e&&(e=1),this._intervalBytes/e/1024},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"lastSecondKBps",{get:function(){return this.addBytes(0),0!==this._lastSecondBytes?this._lastSecondBytes/1024:this._now()-this._lastCheckpoint>=500?this.currentKBps:0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"averageKBps",{get:function(){var e=(this._now()-this._firstCheckpoint)/1e3;return this._totalBytes/e/1024},enumerable:!1,configurable:!0}),e}();var o,a=i(288),s=i(620),d=i(713),l=(o=function(e,t){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},o(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)});const c=function(e){function t(t,i){var n=e.call(this,"fetch-stream-loader")||this;return n.TAG="FetchStreamLoader",n._seekHandler=t,n._config=i,n._needStash=!0,n._requestAbort=!1,n._abortController=null,n._contentLength=null,n._receivedLength=0,n}return l(t,e),t.isSupported=function(){var e;try{var t=s.A.msedge&&((null===(e=null===s.A||void 0===s.A?void 0:s.A.version)||void 0===e?void 0:e.minor)||0)>=15048&&!s.A.webkit,i=!s.A.msedge||t;return self.fetch&&self.ReadableStream&&i}catch(e){return!1}},t.prototype.destroy=function(){this.isWorking()&&this.abort(),e.prototype.destroy.call(this)},t.prototype.open=function(e,t){var i=this;this._dataSource=e,this._range=t;var n=e.url;this._config.reuseRedirectedURL&&void 0!==e.redirectedURL&&(n=e.redirectedURL);var r=this._seekHandler.getConfig(n,t),o=new self.Headers;if("object"==typeof r.headers){var s=r.headers;for(var l in s)s.hasOwnProperty(l)&&o.append(l,s[l])}var c={method:"GET",headers:o,mode:"cors",cache:"default",referrerPolicy:"no-referrer-when-downgrade"};if("object"==typeof this._config.headers)for(var l in this._config.headers)o.append(l,this._config.headers[l]);e.cors||(c.mode="same-origin"),e.withCredentials&&(c.credentials="include"),(null==e?void 0:e.referrerPolicy)&&(c.referrerPolicy=e.referrerPolicy),self.AbortController&&(this._abortController=new self.AbortController,this._abortController&&(c.signal=this._abortController.signal)),this._status=a.eO.kConnecting,self.fetch(r.url,c).then((function(e){var t,n;if(i._requestAbort)return i._status=a.eO.kIdle,void(null===(t=e.body)||void 0===t||t.cancel());if(e.ok&&e.status>=200&&e.status<=299){if(e.url!==r.url&&i._onURLRedirect){var o=i._seekHandler.removeURLParameters(e.url);i._onURLRedirect(o)}var s=e.headers.get("Content-Length");return null!=s&&(i._contentLength=parseInt(s),0!==i._contentLength&&i._onContentLengthKnown&&i._onContentLengthKnown(i._contentLength)),i._pump.call(i,null===(n=e.body)||void 0===n?void 0:n.getReader())}if(i._status=a.eO.kError,!i._onError)throw new d.Al("FetchStreamLoader: Http code invalid, "+e.status+" "+e.statusText);i._onError(a.Xv.HTTP_STATUS_CODE_INVALID,{code:e.status,msg:e.statusText})})).catch((function(e){var t;if(!(null===(t=i._abortController)||void 0===t?void 0:t.signal.aborted)){if(i._status=a.eO.kError,!i._onError)throw e;i._onError(a.Xv.EXCEPTION,{code:-1,msg:e.message})}}))},t.prototype.abort=function(){var e;if(this._requestAbort=!0,(this._status!==a.eO.kBuffering||!s.A.chrome)&&this._abortController)try{null===(e=this._abortController)||void 0===e||e.abort()}catch(e){}},t.prototype._pump=function(e){var t=this;return e.read().then((function(i){var n,r,o,s;if(i.done)if(null!==t._contentLength&&t._receivedLength299)){if(this._status=a.eO.kError,!this._onError)throw new d.Al("MozChunkedLoader: Http code invalid, "+t.status+" "+t.statusText);this._onError(a.Xv.HTTP_STATUS_CODE_INVALID,{code:t.status,msg:t.statusText})}else this._status=a.eO.kBuffering}},t.prototype._onProgress=function(e){var t;if(this._status!==a.eO.kError){null===this._contentLength&&null!==e.total&&0!==e.total&&(this._contentLength=e.total,this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength));var i=e.target.response,n=((null===(t=this._range)||void 0===t?void 0:t.from)||0)+this._receivedLength;this._receivedLength+=i.byteLength,this._onDataArrival&&this._onDataArrival(i,n,this._receivedLength)}},t.prototype._onLoadEnd=function(e){this._requestAbort?this._requestAbort=!1:this._status!==a.eO.kError&&(this._status=a.eO.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1))},t.prototype._onXhrError=function(e){this._status=a.eO.kError;var t=0,i=null;if(this._contentLength&&e.loaded=this._contentLength&&(r=((null===(t=this._range)||void 0===t?void 0:t.from)||0)+this._contentLength-1),this._currentRequestRange={from:n,to:r},this._internalOpen(this._dataSource,this._currentRequestRange)},t.prototype._internalOpen=function(e,t){this._lastTimeLoaded=0;var i=e.url;this._config.reuseRedirectedURL&&(null!=this._currentRedirectedURL?i=this._currentRedirectedURL:null!=e.redirectedURL&&(i=e.redirectedURL));var n=this._seekHandler.getConfig(i,t);this._currentRequestURL=n.url;var r=this._xhr=new XMLHttpRequest;if(r.open("GET",n.url,!0),r.responseType="arraybuffer",r.onreadystatechange=this._onReadyStateChange.bind(this),r.onprogress=this._onProgress.bind(this),r.onload=this._onLoad.bind(this),r.onerror=this._onXhrError.bind(this),e.withCredentials&&(r.withCredentials=!0),"object"==typeof n.headers){var o=n.headers;for(var a in o)o.hasOwnProperty(a)&&r.setRequestHeader(a,o[a])}if("object"==typeof this._config.headers)for(var a in o=this._config.headers)o.hasOwnProperty(a)&&r.setRequestHeader(a,o[a]);r.send()},t.prototype.abort=function(){this._requestAbort=!0,this._internalAbort(),this._status=a.eO.kComplete},t.prototype._internalAbort=function(){this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onload=null,this._xhr.onerror=null,this._xhr.abort(),this._xhr=null)},t.prototype._onReadyStateChange=function(e){var t=e.target;if(2===t.readyState){if(null!=t.responseURL){var i=this._seekHandler.removeURLParameters(t.responseURL);t.responseURL!==this._currentRequestURL&&i!==this._currentRedirectedURL&&(this._currentRedirectedURL=i,this._onURLRedirect&&this._onURLRedirect(i))}if(t.status>=200&&t.status<=299){if(this._waitForTotalLength)return;this._status=a.eO.kBuffering}else{if(this._status=a.eO.kError,!this._onError)throw new d.Al("RangeLoader: Http code invalid, "+t.status+" "+t.statusText);this._onError(a.Xv.HTTP_STATUS_CODE_INVALID,{code:t.status,msg:t.statusText})}}},t.prototype._onProgress=function(e){if(this._status!==a.eO.kError){if(null===this._contentLength){var t=!1;if(this._waitForTotalLength){this._waitForTotalLength=!1,this._totalLengthReceived=!0,t=!0;var i=e.total;this._internalAbort(),null!=i&&0!==i&&(this._totalLength=i)}if(-1===this._range.to?this._contentLength=(this._totalLength||0)-this._range.from:this._contentLength=this._range.to-this._range.from+1,t)return void this._openSubRange();this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength)}var n=e.loaded-this._lastTimeLoaded;this._lastTimeLoaded=e.loaded,this._speedSampler.addBytes(n)}},t.prototype._normalizeSpeed=function(e){var t=this._chunkSizeKBList,i=t.length-1,n=0,r=0,o=i;if(e=t[n]&&e=3&&(t=this._speedSampler.currentKBps)),0!==t){var i=this._normalizeSpeed(t);this._currentSpeedNormalized!==i&&(this._currentSpeedNormalized=i,this._currentChunkSizeKB=i)}var n=e.target.response,r=this._range.from+this._receivedLength;this._receivedLength+=n.byteLength;var o=!1;null!=this._contentLength&&this._receivedLength0&&this._receivedLength0)for(var o=t.split("&"),a=0;a0;s[0]!==this._startName&&s[0]!==this._endName&&(d&&(r+="&"),r+=o[a])}return 0===r.length?i:i+"?"+r},e}(),g=function(){function e(e,t,i){this.TAG="IOController",this._config=t,this._extraData=i,this._stashInitialSize=65536,void 0!==t.stashInitialSize&&t.stashInitialSize>0&&(this._stashInitialSize=t.stashInitialSize),this._stashUsed=0,this._stashSize=this._stashInitialSize,this._bufferSize=3145728,this._stashBuffer=new ArrayBuffer(this._bufferSize),this._stashByteStart=0,this._enableStash=!0,t.enableStashBuffer||(this._enableStash=!1),this._loader=null,this._loaderClass=null,this._seekHandler=null,this._dataSource=e,this._isWebSocketURL=/wss?:\/\/(.+?)/.test(e.url||""),this._refTotalLength=e.filesize?e.filesize:null,this._totalLength=this._refTotalLength,this._fullRequestFlag=!1,this._currentRange=null,this._redirectedURL=null,this._speedNormalized=0,this._speedSampler=new r,this._speedNormalizeList=[32,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096],this._isEarlyEofReconnecting=!1,this._paused=!1,this._resumeFrom=0,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._selectSeekHandler(),this._selectLoader(),this._createLoader()}return e.prototype.destroy=function(){var e,t,i;(null===(e=this._loader)||void 0===e?void 0:e.isWorking())&&(null===(t=this._loader)||void 0===t||t.abort()),null===(i=this._loader)||void 0===i||i.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},e.prototype.isWorking=function(){var e;return(null===(e=this._loader)||void 0===e?void 0:e.isWorking())&&!this._paused},e.prototype.isPaused=function(){return this._paused},Object.defineProperty(e.prototype,"status",{get:function(){var e;return null===(e=this._loader)||void 0===e?void 0:e.status},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"extraData",{get:function(){return this._extraData},set:function(e){this._extraData=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onDataArrival",{get:function(){return this._onDataArrival},set:function(e){this._onDataArrival=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onSeeked",{get:function(){return this._onSeeked},set:function(e){this._onSeeked=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onError",{get:function(){return this._onError},set:function(e){this._onError=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onComplete",{get:function(){return this._onComplete},set:function(e){this._onComplete=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onRedirect",{get:function(){return this._onRedirect},set:function(e){this._onRedirect=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onRecoveredEarlyEof",{get:function(){return this._onRecoveredEarlyEof},set:function(e){this._onRecoveredEarlyEof=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentURL",{get:function(){var e;return null===(e=this._dataSource)||void 0===e?void 0:e.url},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasRedirect",{get:function(){var e;return null!=this._redirectedURL||void 0!==(null===(e=this._dataSource)||void 0===e?void 0:e.redirectedURL)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentRedirectedURL",{get:function(){var e;return this._redirectedURL||(null===(e=this._dataSource)||void 0===e?void 0:e.redirectedURL)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentSpeed",{get:function(){var e,t;return this._loaderClass===p?null===(e=this._loader)||void 0===e?void 0:e.currentSpeed:null===(t=this._speedSampler)||void 0===t?void 0:t.lastSecondKBps},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"loaderType",{get:function(){var e;return null===(e=this._loader)||void 0===e?void 0:e.type},enumerable:!1,configurable:!0}),e.prototype._selectSeekHandler=function(){var e=this._config;if("range"===e.seekType)this._seekHandler=new m(!!this._config.rangeLoadZeroStart);else if("param"===e.seekType){var t=e.seekParamStart||"bstart",i=e.seekParamEnd||"bend";this._seekHandler=new v(t,i)}else{if("custom"!==e.seekType)throw new d.Qn("Invalid seekType in config: ".concat((null==e?void 0:e.seekType)||""));if("function"!=typeof e.customSeekHandler)throw new d.Qn("Custom seekType specified in config but invalid customSeekHandler!");this._seekHandler=new e.customSeekHandler}},e.prototype._selectLoader=function(){var e;if(null!=this._config.customLoader)this._loaderClass=(null===(e=this._config)||void 0===e?void 0:e.customLoader)||null;else if(this._isWebSocketURL)this._loaderClass=f;else if(c.isSupported())this._loaderClass=c;else if(u.isSupported())this._loaderClass=u;else{if(!p.isSupported())throw new d.Al("Your browser doesn't support xhr with arraybuffer responseType!");this._loaderClass=p}},e.prototype._createLoader=function(){var e;this._loaderClass&&(this._loader=new this._loaderClass(this._seekHandler,this._config),(null===(e=this._loader)||void 0===e?void 0:e.needStashBuffer)||(this._enableStash=!1),this._loader&&(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)))},e.prototype.open=function(e){var t,i;this._currentRange={from:0,to:-1},e&&(this._currentRange.from=e),null===(t=this._speedSampler)||void 0===t||t.reset(),e||(this._fullRequestFlag=!0),null===(i=this._loader)||void 0===i||i.open(this._dataSource,Object.assign({},this._currentRange))},e.prototype.abort=function(){var e;null===(e=this._loader)||void 0===e||e.abort(),this._paused&&(this._paused=!1,this._resumeFrom=0)},e.prototype.pause=function(){var e,t;this.isWorking()&&(null===(e=this._loader)||void 0===e||e.abort(),0!==this._stashUsed?(this._resumeFrom=this._stashByteStart,this._currentRange&&(this._currentRange.to=this._stashByteStart-1)):this._resumeFrom=((null===(t=this._currentRange)||void 0===t?void 0:t.to)||0)+1,this._stashUsed=0,this._stashByteStart=0,this._paused=!0)},e.prototype.resume=function(){if(this._paused){this._paused=!1;var e=this._resumeFrom;this._resumeFrom=0,this._internalSeek(e,!0)}},e.prototype.seek=function(e){this._paused=!1,this._stashUsed=0,this._stashByteStart=0,this._internalSeek(e,!0)},e.prototype._internalSeek=function(e,t){var i,n,r,o;(null===(i=this._loader)||void 0===i?void 0:i.isWorking())&&(null===(n=this._loader)||void 0===n||n.abort()),this._flushStashBuffer(t),null===(r=this._loader)||void 0===r||r.destroy(),this._loader=null;var a={from:e,to:-1};this._currentRange={from:a.from,to:-1},null===(o=this._speedSampler)||void 0===o||o.reset(),this._stashSize=this._stashInitialSize,this._createLoader(),this._loader.open(this._dataSource,a),this._onSeeked&&this._onSeeked()},e.prototype.updateUrl=function(e){if(!e||"string"!=typeof e||0===e.length)throw new d.Qn("Url must be a non-empty string!");this._dataSource.url=e},e.prototype._expandBuffer=function(e){for(var t=this._stashSize;t+10485760){var n=new Uint8Array(this._stashBuffer,0,this._stashUsed);new Uint8Array(i,0,t).set(n,0)}this._stashBuffer=i,this._bufferSize=t}},e.prototype._normalizeSpeed=function(e){var t=this._speedNormalizeList,i=t.length-1,n=0,r=0,o=i;if(e=t[n]&&e=512&&e<=1024?Math.floor(1.5*e):2*e)>8192&&(t=8192);var i=1024*t+1048576;this._bufferSize0){var s=this._stashBuffer.slice(0,this._stashUsed);(h=this._dispatchChunks(s,this._stashByteStart))0&&(u=new Uint8Array(s,h),c.set(u,0),this._stashUsed=u.byteLength,this._stashByteStart+=h):(this._stashUsed=0,this._stashByteStart+=h),this._stashUsed+e.byteLength>this._bufferSize&&(this._expandBuffer(this._stashUsed+e.byteLength),c=new Uint8Array(this._stashBuffer,0,this._bufferSize)),c.set(new Uint8Array(e),this._stashUsed),this._stashUsed+=e.byteLength}else(h=this._dispatchChunks(e,t))this._bufferSize&&(this._expandBuffer(l),c=new Uint8Array(this._stashBuffer,0,this._bufferSize)),c.set(new Uint8Array(e,h),0),this._stashUsed+=l,this._stashByteStart=t+h);else if(0===this._stashUsed){var l;(h=this._dispatchChunks(e,t))this._bufferSize&&this._expandBuffer(l),(c=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(e,h),0),this._stashUsed+=l,this._stashByteStart=t+h)}else{var c,h;if(this._stashUsed+e.byteLength>this._bufferSize&&this._expandBuffer(this._stashUsed+e.byteLength),(c=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(e),this._stashUsed),this._stashUsed+=e.byteLength,(h=this._dispatchChunks(this._stashBuffer.slice(0,this._stashUsed),this._stashByteStart))0){var u=new Uint8Array(this._stashBuffer,h);c.set(u,0)}this._stashUsed-=h,this._stashByteStart+=h}}},e.prototype._flushStashBuffer=function(e){if(this._stashUsed>0){var t=this._stashBuffer.slice(0,this._stashUsed),i=this._dispatchChunks(t,this._stashByteStart),r=t.byteLength-i;if(i0){var o=new Uint8Array(this._stashBuffer,0,this._bufferSize),a=new Uint8Array(t,i);o.set(a,0),this._stashUsed=a.byteLength,this._stashByteStart+=i}return 0}n.A.w(this.TAG,"".concat(r," bytes unconsumed data remain when flush buffer, dropped"))}return this._stashUsed=0,this._stashByteStart=0,r}return 0},e.prototype._onLoaderComplete=function(e,t){this._flushStashBuffer(!0),this._onComplete&&this._onComplete(this._extraData)},e.prototype._onLoaderError=function(e,t){var i;switch(n.A.e(this.TAG,"Loader error, code = ".concat(t.code,", msg = ").concat(t.msg)),this._flushStashBuffer(!1),this._isEarlyEofReconnecting&&(this._isEarlyEofReconnecting=!1,e=a.Xv.UNRECOVERABLE_EARLY_EOF),e){case a.Xv.EARLY_EOF:if(!this._config.isLive&&this._totalLength){var r=((null===(i=this._currentRange)||void 0===i?void 0:i.to)||0)+1;return void(r{i.d(t,{HC:()=>a,Xv:()=>o,eO:()=>r});var n=i(713),r={kIdle:0,kConnecting:1,kBuffering:2,kError:3,kComplete:4},o={OK:"OK",EXCEPTION:"Exception",HTTP_STATUS_CODE_INVALID:"HttpStatusCodeInvalid",CONNECTING_TIMEOUT:"ConnectingTimeout",EARLY_EOF:"EarlyEof",UNRECOVERABLE_EARLY_EOF:"UnrecoverableEarlyEof"},a=function(){function e(e){this._type=e||"undefined",this._status=r.kIdle,this._needStash=!1,this._onContentLengthKnown=null,this._onURLRedirect=null,this._onDataArrival=null,this._onError=null,this._onComplete=null}return e.prototype.destroy=function(){this._status=r.kIdle,this._onContentLengthKnown=null,this._onURLRedirect=null,this._onDataArrival=null,this._onError=null,this._onComplete=null},e.prototype.isWorking=function(){return this._status===r.kConnecting||this._status===r.kBuffering},Object.defineProperty(e.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"status",{get:function(){return this._status},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"needStashBuffer",{get:function(){return this._needStash},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onContentLengthKnown",{get:function(){return this._onContentLengthKnown},set:function(e){this._onContentLengthKnown=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onURLRedirect",{get:function(){return this._onURLRedirect},set:function(e){this._onURLRedirect=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onDataArrival",{get:function(){return this._onDataArrival},set:function(e){this._onDataArrival=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onError",{get:function(){return this._onError},set:function(e){this._onError=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onComplete",{get:function(){return this._onComplete},set:function(e){this._onComplete=e},enumerable:!1,configurable:!0}),e.prototype.open=function(e,t){throw new n.Xu("Unimplemented abstract function!")},e.prototype.abort=function(){throw new n.Xu("Unimplemented abstract function!")},e}()},620:(e,t,i)=>{i.d(t,{A:()=>r});var n={};!function(){var e=self.navigator.userAgent.toLowerCase(),t=/(edge)\/([\w.]+)/.exec(e)||/(opr)[\/]([\w.]+)/.exec(e)||/(chrome)[ \/]([\w.]+)/.exec(e)||/(iemobile)[\/]([\w.]+)/.exec(e)||/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.includes("trident")&&/(rv)(?::| )([\w.]+)/.exec(e)||!e.includes("compatible")&&/(firefox)[ \/]([\w.]+)/.exec(e)||[],i=/(ipad)/.exec(e)||/(ipod)/.exec(e)||/(windows phone)/.exec(e)||/(iphone)/.exec(e)||/(kindle)/.exec(e)||/(android)/.exec(e)||/(windows)/.exec(e)||/(mac)/.exec(e)||/(linux)/.exec(e)||/(cros)/.exec(e)||[],r={browser:t[5]||t[3]||t[1]||"",version:t[2]||t[4]||"0",majorVersion:t[4]||t[2]||"0",platform:i[0]||""},o={};if(r.browser){o[r.browser]=!0;var a=r.majorVersion.split(".");o.version={major:parseInt(r.majorVersion,10),string:r.version},a.length>1&&(o.version.minor=parseInt(a[1],10)),a.length>2&&(o.version.build=parseInt(a[2],10))}if(r.platform&&(o[r.platform]=!0),(o.chrome||o.opr||o.safari)&&(o.webkit=!0),o.rv||o.iemobile){o.rv&&delete o.rv;var s="msie";r.browser=s,o[s]=!0}if(o.edge){delete o.edge;var d="msedge";r.browser=d,o[d]=!0}if(o.opr){var l="opera";r.browser=l,o[l]=!0}if(o.safari&&o.android){var c="android";r.browser=c,o[c]=!0}for(var h in o.name=r.browser,o.platform=r.platform,n)Object.prototype.hasOwnProperty.call(n,h)&&delete n[h];Object.assign(n,o)}();const r=n},713:(e,t,i)=>{i.d(t,{Al:()=>o,Qn:()=>s,Xu:()=>d,j4:()=>a});var n,r=(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),o=function(){function e(e){this.name="RuntimeException",this._message=e}return Object.defineProperty(e.prototype,"message",{get:function(){return this._message},enumerable:!1,configurable:!0}),e.prototype.toString=function(){return this.name+": "+this.message},e}(),a=function(e){function t(t){var i=e.call(this,t)||this;return i.name="IllegalStateException",i}return r(t,e),t}(o),s=function(e){function t(t){var i=e.call(this,t)||this;return i.name="InvalidArgumentException",i}return r(t,e),t}(o),d=function(e){function t(t){var i=e.call(this,t)||this;return i.name="NotImplementedException",i}return r(t,e),t}(o)},502:(e,t,i)=>{i.d(t,{A:()=>r});var n=i(413);const r=function(){function e(){}return e.e=function(t,i){var n;t&&!e.FORCE_GLOBAL_TAG||(t=e.GLOBAL_TAG);var r="[".concat(t,"] > ").concat(i);e.ENABLE_CALLBACK&&(null===(n=e.emitter)||void 0===n||n.emit("log","error",r)),e.ENABLE_ERROR&&(console.error||console.warn)},e.i=function(t,i){t&&!e.FORCE_GLOBAL_TAG||(t=e.GLOBAL_TAG);var n="[".concat(t,"] > ").concat(i);e.ENABLE_CALLBACK&&e.emitter.emit("log","info",n),e.ENABLE_INFO&&console.info},e.w=function(t,i){t&&!e.FORCE_GLOBAL_TAG||(t=e.GLOBAL_TAG);var n="[".concat(t,"] > ").concat(i);e.ENABLE_CALLBACK&&e.emitter.emit("log","warn",n),e.ENABLE_WARN&&console.warn},e.d=function(t,i){var n;t&&!e.FORCE_GLOBAL_TAG||(t=e.GLOBAL_TAG);var r="[".concat(t,"] > ").concat(i);e.ENABLE_CALLBACK&&(null===(n=e.emitter)||void 0===n||n.emit("log","debug",r)),e.ENABLE_DEBUG&&console.debug},e.v=function(t,i){var n;t&&!e.FORCE_GLOBAL_TAG||(t=e.GLOBAL_TAG);var r="[".concat(t,"] > ").concat(i);e.ENABLE_CALLBACK&&(null===(n=e.emitter)||void 0===n||n.emit("log","verbose",r)),e.ENABLE_VERBOSE},e.FORCE_GLOBAL_TAG=!1,e.GLOBAL_TAG="ezuikit-flv",e.ENABLE_CALLBACK=!1,e.emitter=new n.A,e.ENABLE_ERROR=!0,e.ENABLE_INFO=!0,e.ENABLE_WARN=!0,e.ENABLE_DEBUG=!0,e.ENABLE_VERBOSE=!0,e}()},641:(e,t,i)=>{i.d(t,{A:()=>o});var n=i(413),r=i(502);const o=function(){function e(){}return Object.defineProperty(e,"forceGlobalTag",{get:function(){return r.A.FORCE_GLOBAL_TAG},set:function(t){r.A.FORCE_GLOBAL_TAG=t,e._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(e,"globalTag",{get:function(){return r.A.GLOBAL_TAG},set:function(t){r.A.GLOBAL_TAG=t,e._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(e,"enableAll",{get:function(){return r.A.ENABLE_VERBOSE&&r.A.ENABLE_DEBUG&&r.A.ENABLE_INFO&&r.A.ENABLE_WARN&&r.A.ENABLE_ERROR},set:function(t){r.A.ENABLE_VERBOSE=t,r.A.ENABLE_DEBUG=t,r.A.ENABLE_INFO=t,r.A.ENABLE_WARN=t,r.A.ENABLE_ERROR=t,e._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(e,"enableDebug",{get:function(){return r.A.ENABLE_DEBUG},set:function(t){r.A.ENABLE_DEBUG=t,e._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(e,"enableVerbose",{get:function(){return r.A.ENABLE_VERBOSE},set:function(t){r.A.ENABLE_VERBOSE=t,e._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(e,"enableInfo",{get:function(){return r.A.ENABLE_INFO},set:function(t){r.A.ENABLE_INFO=t,e._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(e,"enableWarn",{get:function(){return r.A.ENABLE_WARN},set:function(t){r.A.ENABLE_WARN=t,e._notifyChange()},enumerable:!1,configurable:!0}),Object.defineProperty(e,"enableError",{get:function(){return r.A.ENABLE_ERROR},set:function(t){r.A.ENABLE_ERROR=t,e._notifyChange()},enumerable:!1,configurable:!0}),e.getConfig=function(){return{globalTag:r.A.GLOBAL_TAG,forceGlobalTag:r.A.FORCE_GLOBAL_TAG,enableVerbose:r.A.ENABLE_VERBOSE,enableDebug:r.A.ENABLE_DEBUG,enableInfo:r.A.ENABLE_INFO,enableWarn:r.A.ENABLE_WARN,enableError:r.A.ENABLE_ERROR,enableCallback:r.A.ENABLE_CALLBACK}},e.applyConfig=function(e){r.A.GLOBAL_TAG=e.globalTag,r.A.FORCE_GLOBAL_TAG=e.forceGlobalTag,r.A.ENABLE_VERBOSE=e.enableVerbose,r.A.ENABLE_DEBUG=e.enableDebug,r.A.ENABLE_INFO=e.enableInfo,r.A.ENABLE_WARN=e.enableWarn,r.A.ENABLE_ERROR=e.enableError,r.A.ENABLE_CALLBACK=!!e.enableCallback},e._notifyChange=function(){var t=e.emitter;if(t.listenerCount("change")>0){var i=e.getConfig();t.emit("change",i)}},e.registerListener=function(t){e.emitter.addListener("change",t)},e.removeListener=function(t){e.emitter.removeListener("change",t)},e.addLogListener=function(t){r.A.emitter.addListener("log",t),r.A.emitter.listenerCount("log")>0&&(r.A.ENABLE_CALLBACK=!0,e._notifyChange())},e.removeLogListener=function(t){r.A.emitter.removeListener("log",t),0===r.A.emitter.listenerCount("log")&&(r.A.ENABLE_CALLBACK=!1,e._notifyChange())},e.emitter=new n.A,e}()},413:(e,t,i)=>{i.d(t,{A:()=>n});const n=i(343)}},t={};function i(n){var r=t[n];if(void 0!==r)return r.exports;var o=t[n]={exports:{}};return e[n](o,o.exports,i),o.exports}return i.m=e,i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i(446)})()))}(Fi);var Vi=Fi.exports;class Ni extends Yt{constructor(e){super(),this.player=e;const t=document.createElement("video"),i=document.createElement("canvas");this.$posterElement=document.createElement("img"),t.volume=0,t.oncontextmenu=e=>{e.preventDefault()},this.player._opt.hasAudio||(t.muted=!0),t.style.position="absolute",t.style.top="0px",t.style.left="0px",this._delayPlay=!1,e.$container.appendChild(t),this.videoInfo={width:"",height:"",encType:""},this.$videoElement=t,this.$canvasElement=i,this.canvasContext=i.getContext("2d"),this.fixChromeVideoFlashBug(),this.resize();const{proxy:n}=this.player.events;n(this.$videoElement,"canplay",(()=>{this.player.debug.log("Video",`canplay and _delayPlay is ${this._delayPlay}`),this._delayPlay&&this._play(),this.player.$container.contains(this.$posterElement)&&this.$posterElement&&this.player.$container.removeChild(this.$posterElement)})),n(this.$videoElement,"waiting",(()=>{this.player.emit(mt.videoWaiting)})),n(this.$videoElement,"timeupdate",(e=>{const t=parseInt(e.timeStamp,10);this.player.emit(mt.timeUpdate,t),!this.isPlaying()&&this.init&&(this.player.debug.log("Video","timeupdate and this.isPlaying is false and retry play"),this.$videoElement.play())})),this.player.debug.log("Video","init")}destroy(){super.destroy(),this.$canvasElement=null,this.canvasContext=null,this.$videoElement&&(this.$videoElement.pause(),this.$videoElement.currentTime=0,this.$videoElement.src="",this.$videoElement.removeAttribute("src"),this.$videoElement=null),this.trackGenerator&&(this.trackGenerator.stop(),this.trackGenerator=null),this.vwriter&&(this.vwriter.close(),this.vwriter=null),this.player.$container.contains(this.$posterElement)&&this.$posterElement&&this.player.$container.removeChild(this.$posterElement),this.player.debug.log("Video","destroy")}fixChromeVideoFlashBug(){const e=function(){const e=navigator.userAgent.toLowerCase(),t={},i={IE:window.ActiveXObject||"ActiveXObject"in window,Chrome:e.indexOf("chrome")>-1&&e.indexOf("safari")>-1,Firefox:e.indexOf("firefox")>-1,Opera:e.indexOf("opera")>-1,Safari:e.indexOf("safari")>-1&&-1===e.indexOf("chrome"),Edge:e.indexOf("edge")>-1,QQBrowser:/qqbrowser/.test(e),WeixinBrowser:/MicroMessenger/i.test(e)};for(let n in i)if(i[n]){let i="";if("IE"===n)i=e.match(/(msie\s|trident.*rv:)([\w.]+)/)[2];else if("Chrome"===n){for(const e in navigator.mimeTypes)"application/360softmgrplugin"===navigator.mimeTypes[e].type&&(n="360");i=e.match(/chrome\/([\d.]+)/)[1]}else"Firefox"===n?i=e.match(/firefox\/([\d.]+)/)[1]:"Opera"===n?i=e.match(/opera\/([\d.]+)/)[1]:"Safari"===n?i=e.match(/version\/([\d.]+)/)[1]:"Edge"===n?i=e.match(/edge\/([\d.]+)/)[1]:"QQBrowser"===n&&(i=e.match(/qqbrowser\/([\d.]+)/)[1]);t.type=n,t.version=parseInt(i)}return t}(),t=e.type.toLowerCase();if("chrome"===t||"edge"===t){this.player.$container.style.backdropFilter="blur(0px)"}}play(){if(this.$videoElement){const e=this._getVideoReadyState();if(this.player.debug.log("Video",`play and readyState: ${e}`),0===e)return this.player.debug.warn("Video","readyState is 0 and set _delayPlay to true"),void(this._delayPlay=!0);this._play()}}_getVideoReadyState(){let e=0;return this.$videoElement&&(e=this.$videoElement.readyState),e}_play(){this.$videoElement&&this.$videoElement.play().then((()=>{this._delayPlay=!1,this.player.debug.log("Video","_play success"),setTimeout((()=>{this.isPlaying()||(this.player.debug.warn("Video","play failed and retry play"),this._play())}),100)})).catch((e=>{this.player.debug.error("Video","_play error",e)}))}pause(e){this._poster(),e?this.$videoElement&&this.$videoElement.pause():setTimeout((()=>{this.$videoElement&&this.$videoElement.pause()}),100)}clearView(){}screenshot(e,t,i,n){var r;e=e||Nt()+"",n=n||wt.download,t=t||"png";const o={png:"image/png",jpeg:"image/jpeg",webp:"image/webp"};"number"!=typeof i&&(i=Number(i||.92));const a=this.$videoElement,s=this.$canvasElement;s.width=a.videoWidth,s.height=a.videoHeight,null===(r=this.canvasContext)||void 0===r||r.drawImage(a,0,0,s.width,s.height);const d=s.toDataURL(o[t]||o.png,i);if(setTimeout((()=>{var e;null===(e=this.canvasContext)||void 0===e||e.clearRect(0,0,s.width,s.height),s.width=0,s.height=0}),10),n===wt.base64)return d;{const t=Vt(d);return n===wt.blob?t:(n===wt.download&&ii(t,e),"")}}initCanvasViewSize(){this.resize()}_poster(){const e=this.screenshot("poster","png",.75,wt.base64);e.length<10||(this.$posterElement.src=e,this.$posterElement.style.position="absolute",this.$posterElement.style.top="0px",this.$posterElement.style.left="0px",this.$posterElement.style.zIndex="1",this.$posterElement.style.objectFit="contain",this.$posterElement.style.pointerEvents="none",this.player.$container.appendChild(this.$posterElement),this.resize())}render(e){this.vwriter&&this.vwriter.write(e.videoFrame)}resize(){this._resizeElement(this.$videoElement),this._resizeElement(this.$posterElement)}_resizeElement(e){const t=this.player._opt,i=this.player.width,n=this.player.height,r=t.rotate;e.width=i,e.height=n,270!==r&&90!==r||(e.width=n,e.height=i);const o=(i-e.width)/2,a=(n-e.height)/2;let s="contain";t.scaleMode===kt.full&&(s="fill"),t.scaleMode===kt.fullAuto&&(s="cover"),e.style.objectFit=s,e.style.transform="rotate("+r+"deg)",e.style.left=o+"px",e.style.top=a+"px"}isPlaying(){return this.$videoElement&&!this.$videoElement.paused}}class Gi extends Ti{constructor(e,t){super(e,t,Ni),this._checkHeartTimeout=null,this._opt.useMSE=!0,this._createPlayer(t)}close(){throw new Error("Method not implemented.")}_createPlayer(e){var t;this._opt=Object.assign({},this._opt,e),this.events||(this.events=new Si(this)),this.video||(this.video=new Ni(this)),null===(t=Vi.LoggingControl)||void 0===t||t.applyConfig({globalTag:"EzuikitFlv",enableVerbose:!!this._opt.debug,enableDebug:!!this._opt.debug,enableInfo:!!this._opt.debug,enableWarn:!!this._opt.debug,enableError:!0}),this.player=Vi.createPlayer({type:"flv",url:e.url,isLive:!0},{stashInitialSize:128,enableWorker:!0,liveBufferLatencyChasing:!0}),this.player.attachMediaElement(this.video.$videoElement),this.loaded=!0,this._flvEvents()}_flvEvents(){this.player&&(this.player.on(Vi.Events.ERROR,((e,t,i)=>{"MediaError"===e&&"MediaMSEError"===t&&9===i.code&&this.emit(gt.mediaSourceH265NotSupport,i),e.indexOf("NetworkError")>-1&&this.player&&this.pause().then((()=>{this.emit(mt.timeout,mt.delayTimeout),this.emit(mt.delayTimeout)})),Pi.report(51,{event:e,value:i}),this.debug.error(`${Vi.Events.ERROR}`,e,t,i)})),this.player.on(Vi.Events.LOADING_COMPLETE,(e=>{this.debug.log(`${Vi.Events.LOADING_COMPLETE}`,e)})),this.player.on(Vi.Events.RECOVERED_EARLY_EOF,(e=>{this.debug.log(`${Vi.Events.RECOVERED_EARLY_EOF}`,e)})),this.player.on(Vi.Events.MEDIA_INFO,(e=>{this.video.updateVideoInfo({encTypeCode:(null==e?void 0:e.videoCodec.indexOf("avc"))>=0?7:12,width:e.width,height:e.height})})),this.player.on(Vi.Events.STATISTICS_INFO,(e=>{e.decodedFrames===this._decodedFrames&&null===this._checkHeartTimeout?this.checkHeartTimeout():e.decodedFrames!==this._decodedFrames&&(this.clearCheckHeartTimeout(),this._decodedFrames=e.decodedFrames)})),this.player.on(Vi.Events.DESTROYING,(e=>{this.debug.log(`${Vi.Events.DESTROYING}`,e)})),this.off(mt.videoWaiting),this.off(mt.timeUpdate),this.on(mt.videoWaiting,(()=>{this.clearCheckHeartTimeout(),null===this._checkHeartTimeout&&this.handleRender()})),this.on(mt.timeUpdate,(()=>{this.clearCheckHeartTimeout()})))}getOption(){return this._opt}emitError(e,t=""){this.emit(mt.error,e,t),this.emit(e,t)}destroy(){this.player&&this.playing&&this.player.pause(),this.player&&(this.player.unload(),this.player.detachMediaElement(),this.player.destroy(),this.player=null),this._loading=!1,this._playing=!1,this._hasLoaded=!1,this._lastVolume=null,this._times={playInitStart:"",playStart:"",streamStart:"",streamResponse:"",demuxStart:"",decodeStart:"",videoStart:"",playTimestamp:"",streamTimestamp:"",streamResponseTimestamp:"",demuxTimestamp:"",decodeTimestamp:"",videoTimestamp:"",allTimestamp:""},this.video&&(this.video.destroy(),this.video=null),this.events&&(this.events.destroy(),this.events=null),this.resetStats(),this._audioTimestamp=0,this._videoTimestamp=0,this.emit("destroy"),this.off(),this.debug.log("play","destroy end")}resetStats(){}set fullscreen(e){Qt()&&this._opt.useWebFullScreen?(this.emit(mt.webFullscreen,e),setTimeout((()=>{this.updateOption({rotate:e?270:0}),this.resize()}),10)):this.emit(mt.fullscreen,e)}get fullscreen(){return zt()||this.webFullscreen}set webFullscreen(e){this.emit(mt.webFullscreen,e)}get webFullscreen(){return this.$container.classList.contains("flv-fullscreen-web")}set loaded(e){this._hasLoaded=e}get loaded(){return this._hasLoaded}set playing(e){e&&(this.loading=!1),this.playing!==e&&(this._playing=e,this.emit(mt.playing,e),this.emit(mt.volumechange,this.volume),e?this.emit(mt.play):this.emit(mt.pause))}get playing(){return this._playing}get volume(){var e;return(null===(e=this.video)||void 0===e?void 0:e.$videoElement.volume)||0}set volume(e){e!==this.volume&&this.video&&(this.video.$videoElement.muted=!1,this.video.$videoElement.volume=e,this._lastVolume=e),0===e?this.emit(mt.mute,!0):this.emit(mt.mute,!1)}get lastVolume(){return this._lastVolume}set loading(e){this.loading!==e&&(this._loading=e,this.emit(mt.loading,this._loading))}get loading(){return this._loading}set audioTimestamp(e){null!==e&&(this._audioTimestamp=e)}get audioTimestamp(){return this._audioTimestamp}set videoTimestamp(e){null!==e&&(this._videoTimestamp=e)}get videoTimestamp(){return this._videoTimestamp}get isDebug(){return!!this._opt.debug}checkHeart(){this.clearCheckHeartTimeout(),this.checkHeartTimeout()}clearCheckHeartTimeout(){this._checkHeartTimeout&&(clearTimeout(this._checkHeartTimeout),this._checkHeartTimeout=null)}checkHeartTimeout(){this._checkHeartTimeout=setTimeout((()=>{this.playing&&this.pause().then((()=>{this.emit(mt.timeout,mt.delayTimeout),this.emit(mt.delayTimeout)}))}),1e3*this._opt.heartTimeout)}checkLoadingTimeout(){this._checkLoadingTimeout=setTimeout((()=>{this.playing||this.pause().then((()=>{this.emit(mt.timeout,mt.loadingTimeout),this.emit(mt.loadingTimeout)}))}),1e3*this._opt.loadingTimeout)}handleRender(){this.loading&&(this.emit(mt.start),this.loading=!1,this.clearCheckLoadingTimeout()),this.playing||(this.playing=!0),this.checkHeart()}clearCheckLoadingTimeout(){this._checkLoadingTimeout&&(clearTimeout(this._checkLoadingTimeout),this._checkLoadingTimeout=null)}updateOption(e){var t;super.updateOption(e),null===(t=Vi.LoggingControl)||void 0===t||t.applyConfig({globalTag:"EzuikitFlv",enableVerbose:!!e.debug,enableDebug:!!e.debug,enableInfo:!!e.debug,enableWarn:!!e.debug,enableError:!0})}play(){var e;return(null===(e=this.player)||void 0===e?void 0:e.playing)?this.pause().then((()=>this._play())):this._play()}_play(){return this._pause&&this._createPlayer(this._opt),this.loading=!0,this.playing=!1,this._times.playInitStart=Nt(),this.player?(this.player.load(),this.clearCheckHeartTimeout(),new Promise(((e,t)=>{this.player.play().then((()=>{this.loading=!1,this.playing=!0,this._opt.isNotMute&&this.mute(!1),e()})).catch((e=>{t(e)}))}))):Promise.reject()}_close(){return new Promise((e=>{this._loading=!1,this._playing=!1,this._hasLoaded=!1,this._lastVolume=null,this._times={playInitStart:"",playStart:"",streamStart:"",streamResponse:"",demuxStart:"",decodeStart:"",videoStart:"",playTimestamp:"",streamTimestamp:"",streamResponseTimestamp:"",demuxTimestamp:"",decodeTimestamp:"",videoTimestamp:"",allTimestamp:""},this.video&&(this.video.resetInit(),this.video.pause(!0)),this.player&&(this.player.pause(),this.player.unload(),this._pause=!0,this.loaded=!0),this.resetStats(),this._audioTimestamp=0,this._videoTimestamp=0,setTimeout((()=>{e()}),10)}))}pause(){return this._close()}resumeAudioAfterPause(){}mute(e){this.volume=e?0:.5}resize(){this.video.resize()}}class Wi{constructor(e,t){this._opt=Object.assign({},Ke,t),(Qt()||"360EE"===qe().browser)&&(this._opt.useMSE=!1);return new(Wi.getLoaderFactory(this._opt.useMSE))(e,this._opt)}static getLoaderFactory(e){return e?Gi:Ui}}var ji={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function n(){}function r(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function o(e,t,n,o,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var s=new r(n,o||e,a),d=i?i+t:t;return e._events[d]?e._events[d].fn?e._events[d]=[e._events[d],s]:e._events[d].push(s):(e._events[d]=s,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function s(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(i=!1)),s.prototype.eventNames=function(){var e,n,r=[];if(0===this._eventsCount)return r;for(n in e=this._events)t.call(e,n)&&r.push(i?n.slice(1):n);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},s.prototype.listeners=function(e){var t=i?i+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var r=0,o=n.length,a=new Array(o);r=i.heartTimeout)throw new Error(`Flv videoBuffer ${i.videoBuffer}s must be less than heartTimeout ${i.heartTimeout}s`);n.classList.add("ezui-player-container","ezui-flv-container"),n.style.position="relative",delete i.container,i.forceNoOffscreen=!0,qt(i.videoBuffer)&&(i.videoBuffer=1e3*Number(i.videoBuffer)),qt(i.timeout)&&(Ht(i.loadingTimeout)&&(i.loadingTimeout=i.timeout),Ht(i.heartTimeout)&&(i.heartTimeout=i.timeout)),this._opt=i,this.$container=n,this._loadingTimeoutReplayTimes=0,this._heartTimeoutReplayTimes=0,this.events=new Si(this),this._initPlayer(n,i)}static _setOptions(e){return"string"==typeof e.id?e:"string"==typeof e.container?(e.id=e.container.replace(/^#/,""),e):e}destroy(){this.events&&(this.events.destroy(),this.events=null),this.player&&(this.player.destroy(),this.player=null),this.$container&&(this.$container.classList.remove("ezui-flv-container"),this.$container=null),this.$container=null,this._opt={},this._loadingTimeoutReplayTimes=0,this._heartTimeoutReplayTimes=0,this.removeAllListeners(),Pi.report(50,{name:"destroy"})}_initPlayer(e,t){t.url&&(t.url=r(t.url,zi)),this.player=new Wi(e,t),this._bindEvents(),t.autoPlay&&this.play()}_resetPlayer(e={}){this.player.destroy(),this.player=null,this._opt=Object.assign(this._opt,e),this._initPlayer(this.$container,this._opt)}_bindEvents(){Object.keys(vt).forEach((e=>{this.player.on(vt[e],(t=>{this.emit(e,t),this.event.emit(e,t)}))}))}setDebug(e){this.player.updateOption({debug:e}),Pi.report(50,{name:"setDebug"})}setLogger(e={}){this.player.updateOption({loggerOptions:{...this.player._opt.loggerOptions||{},...e}})}closeSound(){var e,t;null===(e=this.player)||void 0===e||null===(t=e.mute)||void 0===t||t.call(e,!0),Pi.report(50,{name:"closeSound"})}openSound(){var e,t;null===(e=this.player)||void 0===e||null===(t=e.mute)||void 0===t||t.call(e,!1),Pi.report(50,{name:"openSound"})}setVolume(e){this.openSound(),this.player.volume=e,Pi.report(50,{name:"setVolume",value:e})}get volume(){return this.player.volume}set volume(e){this.setVolume(e)}getVolume(){return Pi.report(50,{name:"getVolume"}),this.player.volume}audioResume(){var e,t;null===(e=this.player)||void 0===e||null===(e=e.audio)||void 0===e||null===(t=e.audioEnabled)||void 0===t||t.call(e,!0),Pi.report(50,{name:"audioResume"})}setTimeout(e){e=Number(e),this.player.updateOption({timeout:e,loadingTimeout:e,heartTimeout:e})}setScaleMode(e){return new Promise(((t,i)=>{try{e=Number(e)}catch(e){return void i(e)}[kt.full,kt.auto,kt.fullAuto].includes(e)?(this.player.updateOption({scaleMode:e}),this.resize(),t(),Pi.report(50,{name:"setScaleMode"})):i("scale mode 0 | 1 | 2")}))}pause(){var e,t;return Pi.report(50,{name:"pause"}),null===(e=this.player)||void 0===e||null===(t=e.pause)||void 0===t?void 0:t.call(e)}close(){return this._opt.url="",this._opt.playOptions={},this._opt.urlQuery={},Pi.report(50,{name:"close"}),this.player.close()}clearView(){this.player.video.clearView(),Pi.report(50,{name:"clearView"})}play(e={}){var t;e.url&&(Pi.url=e.url),"string"==typeof e&&(e={url:e});const i=r(e.url||this._opt.url,zi);return i===this._opt.url&&null!==(t=this.player)&&void 0!==t&&t.playing?Promise.resolve():(this._opt=Object.assign({},this._opt,e||{},{url:i}),this._opt.urlQuery=Mi(e.url),Pi.report(50,{name:"play"}),new Promise(((e,t)=>{var i;if(!this._opt.url)return this.emit(mt.error,gt.playError),void t("play url is empty");null!==(i=this.player)&&void 0!==i&&i.playing?(this.clearView(),this.player.play(this._opt).then((()=>{e()})).catch((e=>{this.player.debug.warn("Flv","pause -> play and play error",e),this.player.pause().then((()=>{t(e)}))}))):this._play(this._opt).then((()=>{e()})).catch((e=>{t(e)}))})))}_play(e={}){return new Promise(((t,i)=>{const n=0===e.url.indexOf("http"),r=n?$e:Xe,o=n||-1!==e.url.indexOf(".flv")||this._opt.isFlv?Ye:Ze;this.player.updateOption({protocol:r,demuxType:o}),this.player.once(gt.webglAlignmentError,(()=>{this.pause().then((()=>{this.player.debug.log("Flv","webglAlignmentError"),this._resetPlayer({openWebglAlignment:!0}),this.play(e).then((()=>{this.player.debug.log("Flv","webglAlignmentError and play success")})).catch((()=>{this.player.debug.log("Flv","webglAlignmentError and play error")}))}))})),this.player.once(gt.mediaSourceH265NotSupport,(()=>{this.pause().then((()=>{this.player._opt.autoWasm&&(this.player.debug.log("Flv","auto wasm [mse-> wasm] reset player and play"),this._resetPlayer({useMSE:!1}),this.play(e).then((()=>{this.player.debug.log("Flv","auto wasm [mse-> wasm] reset player and play success")})).catch((()=>{this.player.debug.log("Flv","auto wasm [mse-> wasm] reset player and play error")})))}))})),this.player.once(gt.mediaSourceFull,(()=>{this.pause().then((()=>{this.player.debug.log("Flv","media source full"),this._resetPlayer(),this.play(e).then((()=>{this.player.debug.log("Flv","media source full and reset player and play success")})).catch((()=>{this.player.debug.warn("Flv","media source full and reset player and play error")}))}))})),this.player.once(gt.mediaSourceAppendBufferError,(()=>{this.pause().then((()=>{this.player.debug.log("Flv","media source append buffer error"),this._resetPlayer(),this.play(e).then((()=>{this.player.debug.log("Flv","media source append buffer error and reset player and play success")})).catch((()=>{this.player.debug.warn("Flv","media source append buffer error and reset player and play error")}))}))})),this.player.once(gt.mediaSourceBufferListLarge,(()=>{this.pause().then((()=>{this.player.debug.log("Flv","media source buffer list large"),this._resetPlayer(),this.play(e).then((()=>{this.player.debug.log("Flv","media source buffer list large and reset player and play success")})).catch((()=>{this.player.debug.warn("Flv","media source buffer list large and reset player and play error")}))}))})),this.player.once(gt.mediaSourceAppendBufferEndTimeout,(()=>{this.pause().then((()=>{this.player.debug.log("Flv","media source append buffer end timeout"),this._resetPlayer(),this.play(e).then((()=>{this.player.debug.log("Flv","media source append buffer end timeout and reset player and play success")})).catch((()=>{this.player.debug.warn("Flv","media source append buffer end timeout and reset player and play error")}))}))})),this.player.once(gt.mseSourceBufferError,(()=>{this.pause().then((()=>{this.player.debug.log("Flv","mseSourceBufferError close success")}))})),this.player.once(gt.webcodecsH265NotSupport,(()=>{this.pause().then((()=>{this.player._opt.autoWasm&&(this.player.debug.log("Flv","auto wasm [wcs-> wasm] reset player and play"),this._resetPlayer({useWCS:!1}),this.play(e).then((()=>{this.player.debug.log("Flv","auto wasm [wcs-> wasm] reset player and play success")})).catch((()=>{this.player.debug.warn("Flv","auto wasm [wcs-> wasm] reset player and play error")})))}))})),this.player.once(gt.webcodecsWidthOrHeightChange,(()=>{this.pause().then((()=>{this.player.debug.log("Flv","webcodecs Width Or Height Change reset player and play"),this._resetPlayer({useWCS:!0}),this.play(e).then((()=>{this.player.debug.log("Flv","webcodecs Width Or Height Change reset player and play success")})).catch((()=>{this.player.debug.warn("Flv","webcodecs Width Or Height Change reset player and play error")}))}))})),this.player.once(gt.webcodecsDecodeError,(()=>{this.pause().then((()=>{this.player._opt.autoWasm&&(this.player.debug.log("Flv","webcodecs decode error reset player and play"),this._resetPlayer({useWCS:!1}),this.play(e).then((()=>{this.player.debug.log("Flv","webcodecs decode error reset player and play success")})).catch((()=>{this.player.debug.warn("Flv","webcodecs decode error reset player and play error")})))}))})),this.player.once(gt.wasmDecodeError,(()=>{this.player._opt.wasmDecodeErrorReplay&&this.pause().then((()=>{this.player.debug.log("Flv","wasm decode error and reset player and play"),this._resetPlayer({useWCS:!1}),this.play(e).then((()=>{this.player.debug.log("Flv","wasm decode error and reset player and play success")})).catch((()=>{this.player.debug.warn("Flv","wasm decode error and reset player and play error")}))}))})),this.player.once(mt.delayTimeout,(()=>{this.player._opt.heartTimeoutReplay&&(this._heartTimeoutReplayTimes{this._heartTimeoutReplayTimes=0})).catch((e=>{this._heartTimeoutReplayTimes=0})))})),this.player.once(mt.loadingTimeout,(()=>{this.player._opt.loadingTimeoutReplay&&(this._loadingTimeoutReplayTimes{this._loadingTimeoutReplayTimes=0})).catch((()=>{})))})),this.hasLoaded()?this.player.play(e).then((()=>{t()})).catch((e=>{this.player&&(this.player.debug.warn("Flv","hasLoaded and play error",e),this.player.pause().then((()=>{i(e)})))})):this.player.once(mt.decoderWorkerInit,(()=>{this.player.play(e).then((()=>{t()})).catch((e=>{this.player&&(this.player.debug.warn("Flv","decoderWorkerInit and play error",e),this.player.pause().then((()=>{i(e)})))}))}))}))}resize(e,t){e>0&&t>0&&this.player.updateOption({width:e,height:t}),this.player.resize(),Pi.report(50,{name:"resize"})}setBufferTime(e){var t,i;e=Number(e),this.player.updateOption({videoBuffer:1e3*e}),null===(t=this.player)||void 0===t||null===(t=t.decoderWorker)||void 0===t||null===(i=t.updateWorkConfig)||void 0===i||i.call(t,{key:"videoBuffer",value:1e3*e})}setRotate(e){Pi.report(50,{name:"setRotate",value:e});try{e=parseInt(e,10)}catch(e){return Promise.reject("rotate 0 | 90 | 180 | 270")}const t=[0,90,180,270];return new Promise(((i,n)=>{t.includes(e)?(this.player.updateOption({rotate:e}),this.resize(),i()):n("rotate 0 | 90 | 180 | 270")}))}hasLoaded(){return this.player.loaded}setKeepScreenOn(){this.player.updateOption({keepScreenOn:!0}),Pi.report(50,{name:"setKeepScreenOn"})}_setFullscreen(e){const t=!!e;this.player.fullscreen!==t&&(this.player.fullscreen=t)}fullScreen(){return i()||this._setFullscreen(!0),Pi.report(50,{name:"fullScreen"}),Promise.resolve()}fullscreen(){return i()||this._setFullscreen(!0),Pi.report(50,{name:"fullScreen"}),Promise.resolve()}cancelFullScreen(){return Pi.report(50,{name:"cancelFullScreen"}),this._exitFullscreen()}exitFullscreen(){return this.cancelFullScreen()}_exitFullscreen(){return this._setFullscreen(!1),Pi.report(50,{name:"exitFullscreen"}),Promise.resolve()}getState(){return{playing:!!this.player&&this.player.playing,mute:!(this.player&&this.player.volume>0),fullscreen:!!this.player&&this.player.fullscreen,webFullscreen:!!this.player&&this.player.webFullscreen,loaded:!!this.player&&this.player.loaded,volume:this.player?parseFloat(this.player.volume).toFixed(2):0,isDebug:!!this.player&&this.player.isDebug}}getOptions(){return this.player?this.player._opt:{}}getVersion(){return Pi.report(50,{name:"getVersion"}),"1.0.2"}static supportType(e){if("flv"===e.type)return!0;if(e.url){let t=e.url;t.startsWith("http://")||t.startsWith("https://")||(t=/^\/\//.test(t)?"http:"+t:location.origin+location.pathname+t);try{return/\.flv$/i.test(new URL(t).pathname)}catch(e){}}return!1}}return t(Hi,"ERROR",gt),t(Hi,"TIMEOUT",{loadingTimeout:mt.loadingTimeout,delayTimeout:mt.delayTimeout}),t(Hi,"version","1.0.2"),Hi})); diff --git a/examples/base-app/index.umd.js b/examples/base-app/index.umd.js new file mode 100644 index 0000000..b67e92b --- /dev/null +++ b/examples/base-app/index.umd.js @@ -0,0 +1,60 @@ +/* +* +* HlsPlayer.js v0.1.0 +* Copyright (c) 2024-8-1 Ezviz-OpenBiz +* . +* +*/ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).HlsPlayer=t()}(this,(function(){"use strict";var e=1,t=2,i=3,r="aac",s="h265",n="hevc",a="m3u8",o="hls",l=0,h=1,c=600,d=400,u=30,f=40,g=!1,m=44100,p=20,v="ONCE",y="SWAP",T=0,E=265,S=1001,b=1002,L=1003;var w,A=function(){return window.WebAssembly&&"object"==("undefined"==typeof WebAssembly?"undefined":(e=WebAssembly)&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e);var e};function R(){return(new Date).getTime()}var k=window.AudioContext||(null==(w=window)?void 0:w.webkitAudioContext),_=function(){function e(e){var t=this;this.options={sampleRate:e.sampleRate||m,appendType:e.appendType||l,playMode:e.playMode||y,isLive:e.isLive},this.logger=null==e?void 0:e.logger,this.sourceChannel=-1,this.audioCtx=new k({latencyHint:"interactive",sampleRate:e.sampleRate}),this.gainNode=null,this.sourceList=[],this.startStatus=!1,this.sampleQueue=[],this.nextBuffer=null,this.playTimestamp=0,this.playStartTime=0,this.durationMs=-1,this.volume=e.volume||0,this.onLoadCache=null,this.sourceList.push(this.audioCtx.createBufferSource()),this.sourceList.push(this.audioCtx.createBufferSource()),this.sourceList[0].onended=function(){t.swapSource(0,1)},this.sourceList[1].onended=function(){t.swapSource(1,0)},this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.audioCtx.destination),this.runNextBuffer()}var t=e.prototype;return t.resetStartParam=function(){this.playTimestamp=0,this.playStartTime=0},t.setOnLoadCache=function(e){this.onLoadCache=e},t.setDurationMs=function(e){void 0===e&&(e=-1),this.durationMs=e},t.setVolume=function(e){void 0===e&&(e=0),this.volume=e,this.gainNode.gain.value=e},t.getAlignVPTS=function(){return this.playTimestamp+(R()-this.playStartTime)/1e3},t.swapSource=function(e,t){if(void 0===e&&(e=-1),void 0===t&&(t=-1),!this.startStatus)return null;if(e<0||e>=this.sourceList.length)return null;if(t<0||t>=this.sourceList.length)return null;try{this.sourceChannel===e&&null!==this.sourceList[e]&&(this.sourceList[e].disconnect(this.gainNode),this.sourceList[e]=null)}catch(t){this.logger.error("[DEFINE ERROR] this audioCore disconnect source Index:"+e+" error happened!",t)}(this.sourceChannel=t,-2===this.decodeSample(t,e)&&this.options.isLive)&&(this.getAlignVPTS()>=this.durationMs/1e3-.04?this.pause():null==this||this.onLoadCache());return null},t.addSample=function(e){return void 0===e&&(e=null),!(null==e||!e||void 0===e)&&(0===this.sampleQueue.length&&(this.seekPos=null==e?void 0:e.pts),this.sampleQueue.push(e),!0)},t.runNextBuffer=function(){var e=this;window.setInterval((function(){if(!(null!=e.nextBuffer||e.sampleQueue.length=this.sourceList.length)return-1;if(null!=this.sourceList[e]&&void 0!==this.sourceList[e]&&this.sourceList[e]||(this.sourceList[e]=this.audioCtx.createBufferSource(),this.sourceList[e].onended=function(){s.swapSource(e,t)}),0===this.sampleQueue.length)return this.options.isLive?(this.sourceList[e].connect(this.gainNode),this.sourceList[e].startState||null==(r=this.sourceList[e])||null==(i=r.start)||i.call(r),this.sourceList[e].onended=function(){s.swapSource(e,t)},this.sourceList[e].stop(),0):-2;if(this.sourceList[e].buffer)return this.swapSource(e,t),0;if(null==this.nextBuffer||this.nextBuffer.data.length<1){var n,a,o=this.sourceList[e];return o.connect(this.gainNode),(null==o?void 0:o.startState)||null==(a=this.sourceList[e])||null==(n=a.start)||n.call(a),o.startState=!0,o.stop(),1}var l=this.nextBuffer.data.buffer;this.playTimestamp=this.nextBuffer.pts,this.playStartTime=R();try{this.audioCtx.decodeAudioData(l,(function(t){var i,r;null!==s.sourceList[e]&&(s.sourceList[e].buffer=t,s.sourceList[e].connect(s.gainNode),s.sourceList[e].startState||null==(r=s.sourceList[e])||null==(i=r.start)||i.call(r),s.sourceList[e].startState=!0)}),(function(e){s.logger.error("Error audioCore with decoding audio data",e)}))}catch(e){return this.nextBuffer=null,this.logger.log("decodeAudioData error",e),-3}return this.nextBuffer=null,0},t.decodeWholeSamples=function(e){var t=this;if(void 0===e&&(e=-1),this.sourceChannel=e,e<0||e>=this.sourceList.length)return-1;if(null!=this.sourceList[e]&&void 0!==this.sourceList[e]&&this.sourceList[e]||(this.sourceList[e]=this.audioCtx.createBufferSource(),this.sourceList[e].onended=function(){}),0===this.sampleQueue.length)return-2;for(var i=null,r=null,s=0;s",e)}},e}(),D=function(){function r(e){this.limit=e.limit||200,this.logger=null==e?void 0:e.logger,this.yuvCache=[]}var s=r.prototype;return s.appendCacheByCacheYuv=function(i){return this.yuvCache.push(i),this.yuvCache.length>=this.limit?(this.shiftYuv(),t):e},s.getState=function(){return this.yuvCache.length<=0?i:this.yuvCache.length>=this.limit?t:e},s.cleanPipeline=function(){this.yuvCache=[],this.yuvCache.length=0},s.shiftYuv=function(){return this.yuvCache.length<=0?null:this.yuvCache.shift()},r}(),x=function(){function e(e,t,i,r,s,n){this.pts=e,this.width=t,this.height=i,this.imageBufferY=r,this.imageBufferB=s,this.imageBufferR=n}return e.prototype.setYuv=function(e,t,i,r,s,n){this.pts=e,this.width=t,this.height=i,this.imageBufferY=r,this.imageBufferB=s,this.imageBufferR=n},e}(),C=function(){function e(e){this.gl=e,this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),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)}var t=e.prototype;return t.bind=function(e,t,i){var r=this.gl;r.activeTexture([r.TEXTURE0,r.TEXTURE1,r.TEXTURE2][e]),r.bindTexture(r.TEXTURE_2D,this.texture),r.uniform1i(r.getUniformLocation(t,i),e)},t.fill=function(e,t,i){var r=this.gl;r.bindTexture(r.TEXTURE_2D,this.texture),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,i)},e}(),I=function(){function e(e,t){this.gl=null,this.gl=e.getContext("webgl")||e.getContext("experimental-webgl"),this.program=this.gl.createProgram();var i=["attribute highp vec4 aVertexPosition;","attribute vec2 aTextureCoord;","varying highp vec2 vTextureCoord;","void main(void) {"," gl_Position = aVertexPosition;"," vTextureCoord = aTextureCoord;","}"].join("\n"),r=this.gl.createShader(this.gl.VERTEX_SHADER);this.gl.shaderSource(r,i),this.gl.compileShader(r);var s=["precision highp float;","varying lowp vec2 vTextureCoord;","uniform sampler2D YTexture;","uniform sampler2D UTexture;","uniform sampler2D VTexture;","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",");","void main(void) {"," gl_FragColor = vec4( texture2D(YTexture, vTextureCoord).x, texture2D(UTexture, vTextureCoord).x, texture2D(VTexture, vTextureCoord).x, 1) * YUV2RGB;","}"].join("\n"),n=this.gl.createShader(this.gl.FRAGMENT_SHADER);this.gl.shaderSource(n,s),this.gl.compileShader(n),this.gl.attachShader(this.program,r),this.gl.attachShader(this.program,n),this.gl.linkProgram(this.program),this.gl.useProgram(this.program),this.gl.getProgramParameter(this.program,this.gl.LINK_STATUS);var a=this.gl.getAttribLocation(this.program,"aVertexPosition");this.gl.enableVertexAttribArray(a);var o=this.gl.getAttribLocation(this.program,"aTextureCoord");this.gl.enableVertexAttribArray(o),this.verticesBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.verticesBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(a,3,this.gl.FLOAT,!1,0,0),this.texCoordBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.texCoordBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([1,0,0,0,1,1,0,1]),this.gl.STATIC_DRAW),this.gl.vertexAttribPointer(o,2,this.gl.FLOAT,!1,0,0),this.gl.y=new C(this.gl),this.gl.u=new C(this.gl),this.gl.v=new C(this.gl),this.gl.y.bind(0,this.program,"YTexture"),this.gl.u.bind(1,this.program,"UTexture"),this.gl.v.bind(2,this.program,"VTexture")}var t=e.prototype;return t.renderFrame=function(e,t,i,r,s){this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height),this.gl.clearColor(0,0,0,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.y.fill(r,s,e),this.gl.u.fill(r>>1,s>>1,t),this.gl.v.fill(r>>1,s>>1,i),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)},t.destroyContext=function(){try{this.gl.deleteProgram(this.program),this.gl.deleteBuffer(this.verticesBuffer),this.gl.deleteBuffer(this.texCoordBuffer),this.gl.deleteTexture(this.gl.y.texture),this.gl.deleteTexture(this.gl.u.texture),this.gl.deleteTexture(this.gl.v.texture),this.gl=null,this.program=null,this.verticesBuffer=null,this.texCoordBuffer=null}catch(e){}},e}(),P=function(e,t){return{cmd:e,data:t}},O="wasmLoading",M="wasmLoaded",F="wasmFailed",N="videoCallback",U="decodeCodecContext",B="destroy",$="demuxTsStream",G="demuxCoreReceive",K="readPacket",V="readPacketEnd",H="mediaInfo",j={info:"",log:"background: #4096ff; color: #FFF;",warn:"background: yellow; color: #FFF;",error:"background: red; color: #FFF;"},W=function(){function e(e){void 0===e&&(e={}),this._options={level:"INFO",showTime:!1},this._levelNum=3,this.info=this._loggerFactory("info",this._levelNum>=3),this.log=this._loggerFactory("log",this._levelNum>=2),this.warn=this._loggerFactory("warn",this._levelNum>=1),this.error=this._loggerFactory("error",this._levelNum>=0),this.setOptions(e)}var t=e.prototype;return t.setOptions=function(e){var t;this._options=Object.assign({},this._options,e),this._levelNum=this._matchLevel(null!=(t=this._options.level)?t:"INFO"),this.info=this._loggerFactory("info",this._levelNum>=3),this.log=this._loggerFactory("log",this._levelNum>=2),this.warn=this._loggerFactory("warn",this._levelNum>=1),this.error=this._loggerFactory("error",this._levelNum>=0)},t._matchLevel=function(e){var t=3;switch(e){case"INFO":t=3;break;case"LOG":t=2;break;case"WARN":t=1;break;case"ERROR":t=0}return t},t._loggerFactory=function(t,i){var r=console[t];if(i&&r){var s,n=this._options.name?"%c["+this._options.name+"]%c %c["+t.toUpperCase()+"]":"%c["+t.toUpperCase()+"]",a=[this._options.name?"background: green;color: #fff":null,this._options.name?"":null,j[t]].filter((function(e){return null!=e}));return(s=r).bind.apply(s,[].concat([console,n],a))}return e.noop},t.getOptions=function(){return this._options},t.getVersion=function(){return"1.0.1"},e}();function Y(e){return(e=+e)<10&&(e="0"+e),e+""}W.noop=function(){};var q=["info","log","warn","error"];function z(e){var t=new W(e);return new Proxy(t,{get:function(e,t){if(q.includes(t)){var i;if(null==(i=e._options)?void 0:i.showTime){var r=(n=(s=new Date(Date.now())).getFullYear(),a=s.getMonth()+1,o=s.getDate(),l=s.getHours(),h=s.getMinutes(),c=s.getSeconds(),d=s.getMilliseconds(),n+"/"+Y(a)+"/"+Y(o)+" "+Y(l)+":"+Y(h)+":"+Y(c)+":"+d);return e[t].bind(console,"["+r+"]")}return e[t].bind(console)}var s,n,a,o,l,h,c,d;return Reflect.get(e,t)}})}var X="object"==typeof global&&global&&global.Object===Object&&global,Q="object"==typeof self&&self&&self.Object===Object&&self,J=X||Q||Function("return this")(),Z=J.Symbol,ee=Object.prototype,te=ee.hasOwnProperty,ie=ee.toString,re=Z?Z.toStringTag:void 0;var se=Object.prototype.toString;var ne="[object Null]",ae="[object Undefined]",oe=Z?Z.toStringTag:void 0;function le(e){return null==e?void 0===e?ae:ne:oe&&oe in Object(e)?function(e){var t=te.call(e,re),i=e[re];try{e[re]=void 0;var r=!0}catch(e){}var s=ie.call(e);return r&&(t?e[re]=i:delete e[re]),s}(e):function(e){return se.call(e)}(e)}function he(e){return null!=e&&"object"==typeof e}var ce=Array.isArray;function de(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function ue(e){return e}var fe="[object AsyncFunction]",ge="[object Function]",me="[object GeneratorFunction]",pe="[object Proxy]";function ve(e){if(!de(e))return!1;var t=le(e);return t==ge||t==me||t==fe||t==pe}var ye,Te=J["__core-js_shared__"],Ee=(ye=/[^.]+$/.exec(Te&&Te.keys&&Te.keys.IE_PROTO||""))?"Symbol(src)_1."+ye:"";var Se=Function.prototype.toString;var be=/^\[object .+?Constructor\]$/,Le=Function.prototype,we=Object.prototype,Ae=Le.toString,Re=we.hasOwnProperty,ke=RegExp("^"+Ae.call(Re).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function _e(e){return!(!de(e)||(t=e,Ee&&Ee in t))&&(ve(e)?ke:be).test(function(e){if(null!=e){try{return Se.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e));var t}function De(e,t){var i=function(e,t){return null==e?void 0:e[t]}(e,t);return _e(i)?i:void 0}var xe=Object.create,Ce=function(){function e(){}return function(t){if(!de(t))return{};if(xe)return xe(t);e.prototype=t;var i=new e;return e.prototype=void 0,i}}();var Ie=Date.now;var Pe,Oe,Me,Fe=function(){try{var e=De(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),Ne=Fe?function(e,t){return Fe(e,"toString",{configurable:!0,enumerable:!1,value:(i=t,function(){return i}),writable:!0});var i}:ue,Ue=(Pe=Ne,Oe=0,Me=0,function(){var e=Ie(),t=16-(e-Me);if(Me=e,t>0){if(++Oe>=800)return arguments[0]}else Oe=0;return Pe.apply(void 0,arguments)}),Be=9007199254740991,$e=/^(?:0|[1-9]\d*)$/;function Ge(e,t){var i=typeof e;return!!(t=null==t?Be:t)&&("number"==i||"symbol"!=i&&$e.test(e))&&e>-1&&e%1==0&&e-1&&e%1==0&&e<=qe}function Xe(e){return null!=e&&ze(e.length)&&!ve(e)}var Qe=Object.prototype;function Je(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Qe)}function Ze(e){return he(e)&&"[object Arguments]"==le(e)}var et=Object.prototype,tt=et.hasOwnProperty,it=et.propertyIsEnumerable,rt=Ze(function(){return arguments}())?Ze:function(e){return he(e)&&tt.call(e,"callee")&&!it.call(e,"callee")};var st="object"==typeof exports&&exports&&!exports.nodeType&&exports,nt=st&&"object"==typeof module&&module&&!module.nodeType&&module,at=nt&&nt.exports===st?J.Buffer:void 0,ot=(at?at.isBuffer:void 0)||function(){return!1},lt={};lt["[object Float32Array]"]=lt["[object Float64Array]"]=lt["[object Int8Array]"]=lt["[object Int16Array]"]=lt["[object Int32Array]"]=lt["[object Uint8Array]"]=lt["[object Uint8ClampedArray]"]=lt["[object Uint16Array]"]=lt["[object Uint32Array]"]=!0,lt["[object Arguments]"]=lt["[object Array]"]=lt["[object ArrayBuffer]"]=lt["[object Boolean]"]=lt["[object DataView]"]=lt["[object Date]"]=lt["[object Error]"]=lt["[object Function]"]=lt["[object Map]"]=lt["[object Number]"]=lt["[object Object]"]=lt["[object RegExp]"]=lt["[object Set]"]=lt["[object String]"]=lt["[object WeakMap]"]=!1;var ht="object"==typeof exports&&exports&&!exports.nodeType&&exports,ct=ht&&"object"==typeof module&&module&&!module.nodeType&&module,dt=ct&&ct.exports===ht&&X.process,ut=function(){try{var e=ct&&ct.require&&ct.require("util").types;return e||dt&&dt.binding&&dt.binding("util")}catch(e){}}(),ft=ut&&ut.isTypedArray,gt=ft?function(e){return function(t){return e(t)}}(ft):function(e){return he(e)&&ze(e.length)&&!!lt[le(e)]};function mt(e,t){var i=ce(e),r=!i&&rt(e),s=!i&&!r&&ot(e),n=!i&&!r&&!s&>(e),a=i||r||s||n,o=a?function(e,t){for(var i=-1,r=Array(e);++i-1},At.prototype.set=function(e,t){var i=this.__data__,r=Lt(i,e);return r<0?(++this.size,i.push([e,t])):i[r][1]=t,this};var Rt=De(J,"Map");function kt(e,t){var i,r,s=e.__data__;return("string"==(r=typeof(i=t))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==i:null===i)?s["string"==typeof t?"string":"hash"]:s.map}function _t(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t1?t[r-1]:void 0,n=r>2?t[2]:void 0;for(s=qt.length>3&&"function"==typeof s?(r--,s):void 0,n&&function(e,t,i){if(!de(i))return!1;var r=typeof t;return!!("number"==r?Xe(i)&&Ge(t,i.length):"string"==r&&t in i)&&Ve(i[t],e)}(t[0],t[1],n)&&(s=r<3?void 0:s,r=1),e=Object(e);++i{if("undefined"==typeof document)return!1;const e=ti[0],t={};for(const i of ti){const r=i?.[1];if(r in document){for(const[r,s]of i.entries())t[e[r]]=s;return t}}return!1})(),ri={change:ii.fullscreenchange,error:ii.fullscreenerror};let si={request:(e=document.documentElement,t)=>new Promise(((i,r)=>{const s=()=>{si.off("change",s),i()};si.on("change",s);const n=e[ii.requestFullscreen](t);n instanceof Promise&&n.then(s).catch(r)})),exit:()=>new Promise(((e,t)=>{if(!si.isFullscreen)return void e();const i=()=>{si.off("change",i),e()};si.on("change",i);const r=document[ii.exitFullscreen]();r instanceof Promise&&r.then(i).catch(t)})),toggle:(e,t)=>si.isFullscreen?si.exit():si.request(e,t),onchange(e){si.on("change",e)},onerror(e){si.on("error",e)},on(e,t){const i=ri[e];i&&document.addEventListener(i,t,!1)},off(e,t){const i=ri[e];i&&document.removeEventListener(i,t,!1)},raw:ii};Object.defineProperties(si,{isFullscreen:{get:()=>Boolean(document[ii.fullscreenElement])},element:{enumerable:!0,get:()=>document[ii.fullscreenElement]??void 0},isEnabled:{enumerable:!0,get:()=>Boolean(document[ii.fullscreenEnabled])}}),ii||(si={isEnabled:!1});var ni=si,ai={exports:{}};!function(e,t){function i(e){return e&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}!function(r,s){var n="function",a="undefined",o="object",l="string",h="major",c="model",d="name",u="type",f="vendor",g="version",m="architecture",p="console",v="mobile",y="tablet",T="smarttv",E="wearable",S="embedded",b="Amazon",L="Apple",w="ASUS",A="BlackBerry",R="Browser",k="Chrome",_="Firefox",D="Google",x="Huawei",C="LG",I="Microsoft",P="Motorola",O="Opera",M="Samsung",F="Sharp",N="Sony",U="Xiaomi",B="Zebra",$="Facebook",G="Chromium OS",K="Mac OS",V=function(e){for(var t={},i=0;i0?2===h.length?i(h[1])==n?this[h[0]]=h[1].call(this,d):this[h[0]]=h[1]:3===h.length?i(h[1])!==n||h[1].exec&&h[1].test?this[h[0]]=d?d.replace(h[1],h[2]):s:this[h[0]]=d?h[1].call(this,d,h[2]):s:4===h.length&&(this[h[0]]=d?h[3].call(this,d.replace(h[1],h[2])):s):this[h]=d||s;u+=2}},q=function(e,t){for(var r in t)if(i(t[r])===o&&t[r].length>0){for(var n=0;n2&&(e[c]="iPad",e[u]=y),e},this.getEngine=function(){var e={};return e[d]=s,e[g]=s,Y.call(e,S,L.engine),e},this.getOS=function(){var e={};return e[d]=s,e[g]=s,Y.call(e,S,L.os),w&&!e[d]&&b&&"Unknown"!=b.platform&&(e[d]=b.platform.replace(/chrome os/i,G).replace(/macos/i,K)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return S},this.setUA=function(e){return S=(void 0===e?"undefined":i(e))===l&&e.length>500?W(e,500):e,this},this.setUA(S),this};Q.VERSION="1.0.37",Q.BROWSER=V([d,g,h]),Q.CPU=V([m]),Q.DEVICE=V([c,f,u,p,v,T,y,E,S]),Q.ENGINE=Q.OS=V([d,g]),i(t)!==a?(i(e)!==a&&e.exports&&(t=e.exports=Q),t.UAParser=Q):(void 0===r?"undefined":i(r))!==a&&(r.UAParser=Q);var J=(void 0===r?"undefined":i(r))!==a&&(r.jQuery||r.Zepto);if(J&&!J.ua){var Z=new Q;J.ua=Z.getResult(),J.ua.get=function(){return Z.getUA()},J.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var i in t)J.ua[i]=t[i]}}}("object"===("undefined"==typeof window?"undefined":i(window))?window:Qt)}(ai,ai.exports);var oi,li,hi,ci,di=Jt(ai.exports),ui=(oi="undefined"!=typeof self?self:window,li={navigator:void 0!==oi.navigator?oi.navigator:{userAgent:""},infoMap:{engine:["WebKit","Trident","Gecko","Presto"],browser:["Safari","Chrome","Edge","IE","Firefox","Firefox Focus","Chromium","Opera","Vivaldi","Yandex","Arora","Lunascape","QupZilla","Coc Coc","Kindle","Iceweasel","Konqueror","Iceape","SeaMonkey","Epiphany","360","360SE","360EE","UC","QQBrowser","QQ","Baidu","Maxthon","Sogou","LBBROWSER","2345Explorer","TheWorld","XiaoMi","Quark","Qiyu","Wechat","Taobao","Alipay","Weibo","Douban","Suning","iQiYi"],os:["Windows","Linux","Mac OS","Android","Ubuntu","FreeBSD","Debian","iOS","Windows Phone","BlackBerry","MeeGo","Symbian","Chrome OS","WebOS"],device:["Mobile","Tablet","iPad"]}},hi={getMatchMap:function(e){return{Trident:e.indexOf("Trident")>-1||e.indexOf("NET CLR")>-1,Presto:e.indexOf("Presto")>-1,WebKit:e.indexOf("AppleWebKit")>-1,Gecko:e.indexOf("Gecko/")>-1,Safari:e.indexOf("Safari")>-1,Chrome:e.indexOf("Chrome")>-1||e.indexOf("CriOS")>-1,IE:e.indexOf("MSIE")>-1||e.indexOf("Trident")>-1,Edge:e.indexOf("Edge")>-1,Firefox:e.indexOf("Firefox")>-1||e.indexOf("FxiOS")>-1,"Firefox Focus":e.indexOf("Focus")>-1,Chromium:e.indexOf("Chromium")>-1,Opera:e.indexOf("Opera")>-1||e.indexOf("OPR")>-1,Vivaldi:e.indexOf("Vivaldi")>-1,Yandex:e.indexOf("YaBrowser")>-1,Arora:e.indexOf("Arora")>-1,Lunascape:e.indexOf("Lunascape")>-1,QupZilla:e.indexOf("QupZilla")>-1,"Coc Coc":e.indexOf("coc_coc_browser")>-1,Kindle:e.indexOf("Kindle")>-1||e.indexOf("Silk/")>-1,Iceweasel:e.indexOf("Iceweasel")>-1,Konqueror:e.indexOf("Konqueror")>-1,Iceape:e.indexOf("Iceape")>-1,SeaMonkey:e.indexOf("SeaMonkey")>-1,Epiphany:e.indexOf("Epiphany")>-1,360:e.indexOf("QihooBrowser")>-1||e.indexOf("QHBrowser")>-1,"360EE":e.indexOf("360EE")>-1,"360SE":e.indexOf("360SE")>-1,UC:e.indexOf("UC")>-1||e.indexOf(" UBrowser")>-1,QQBrowser:e.indexOf("QQBrowser")>-1,QQ:e.indexOf("QQ/")>-1,Baidu:e.indexOf("Baidu")>-1||e.indexOf("BIDUBrowser")>-1,Maxthon:e.indexOf("Maxthon")>-1,Sogou:e.indexOf("MetaSr")>-1||e.indexOf("Sogou")>-1,LBBROWSER:e.indexOf("LBBROWSER")>-1,"2345Explorer":e.indexOf("2345Explorer")>-1,TheWorld:e.indexOf("TheWorld")>-1,XiaoMi:e.indexOf("MiuiBrowser")>-1,Quark:e.indexOf("Quark")>-1,Qiyu:e.indexOf("Qiyu")>-1,Wechat:e.indexOf("MicroMessenger")>-1,Taobao:e.indexOf("AliApp(TB")>-1,Alipay:e.indexOf("AliApp(AP")>-1,Weibo:e.indexOf("Weibo")>-1,Douban:e.indexOf("com.douban.frodo")>-1,Suning:e.indexOf("SNEBUY-APP")>-1,iQiYi:e.indexOf("IqiyiApp")>-1,Windows:e.indexOf("Windows")>-1,Linux:e.indexOf("Linux")>-1||e.indexOf("X11")>-1,"Mac OS":e.indexOf("Macintosh")>-1,Android:e.indexOf("Android")>-1||e.indexOf("Adr")>-1,Ubuntu:e.indexOf("Ubuntu")>-1,FreeBSD:e.indexOf("FreeBSD")>-1,Debian:e.indexOf("Debian")>-1,"Windows Phone":e.indexOf("IEMobile")>-1||e.indexOf("Windows Phone")>-1,BlackBerry:e.indexOf("BlackBerry")>-1||e.indexOf("RIM")>-1,MeeGo:e.indexOf("MeeGo")>-1,Symbian:e.indexOf("Symbian")>-1,iOS:e.indexOf("like Mac OS X")>-1,"Chrome OS":e.indexOf("CrOS")>-1,WebOS:e.indexOf("hpwOS")>-1,Mobile:e.indexOf("Mobi")>-1||e.indexOf("iPh")>-1||e.indexOf("480")>-1,Tablet:e.indexOf("Tablet")>-1||e.indexOf("Nexus 7")>-1,iPad:e.indexOf("iPad")>-1}},matchInfoMap:function(e){var t,i=(null==(t=li.navigator)?void 0:t.userAgent)||"",r=hi.getMatchMap(i);for(var s in li.infoMap)for(var n=0;n36&&oi.showModalDialog?s=!0:+n>45&&(s=i("type","application/vnd.chromium.remoting-viewer"))}if(r.Baidu&&r.Opera&&(r.Baidu=!1),r.Mobile&&(r.Mobile=!t.includes("iPad")),s&&(i("type","application/gameplugin")||li.navigator&&void 0===li.navigator.connection.saveData?r["360SE"]=!0:r["360EE"]=!0),r.IE||r.Edge)switch(window.screenTop-window.screenY){case 71:case 74:case 99:case 75:case 105:break;case 102:r["360EE"]=!0;break;case 104:r["360SE"]=!0}var a={Safari:function(){return t.replace(/^.*Version\/([\d.]+).*$/,"$1")},Chrome:function(){return t.replace(/^.*Chrome\/([\d.]+).*$/,"$1").replace(/^.*CriOS\/([\d.]+).*$/,"$1")},IE:function(){return t.replace(/^.*MSIE ([\d.]+).*$/,"$1").replace(/^.*rv:([\d.]+).*$/,"$1")},Edge:function(){return t.replace(/^.*Edge\/([\d.]+).*$/,"$1")},Firefox:function(){return t.replace(/^.*Firefox\/([\d.]+).*$/,"$1").replace(/^.*FxiOS\/([\d.]+).*$/,"$1")},"Firefox Focus":function(){return t.replace(/^.*Focus\/([\d.]+).*$/,"$1")},Chromium:function(){return t.replace(/^.*Chromium\/([\d.]+).*$/,"$1")},Opera:function(){return t.replace(/^.*Opera\/([\d.]+).*$/,"$1").replace(/^.*OPR\/([\d.]+).*$/,"$1")},Vivaldi:function(){return t.replace(/^.*Vivaldi\/([\d.]+).*$/,"$1")},Yandex:function(){return t.replace(/^.*YaBrowser\/([\d.]+).*$/,"$1")},Arora:function(){return t.replace(/^.*Arora\/([\d.]+).*$/,"$1")},Lunascape:function(){return t.replace(/^.*Lunascape[\/\s]([\d.]+).*$/,"$1")},QupZilla:function(){return t.replace(/^.*QupZilla[\/\s]([\d.]+).*$/,"$1")},"Coc Coc":function(){return t.replace(/^.*coc_coc_browser\/([\d.]+).*$/,"$1")},Kindle:function(){return t.replace(/^.*Version\/([\d.]+).*$/,"$1")},Iceweasel:function(){return t.replace(/^.*Iceweasel\/([\d.]+).*$/,"$1")},Konqueror:function(){return t.replace(/^.*Konqueror\/([\d.]+).*$/,"$1")},Iceape:function(){return t.replace(/^.*Iceape\/([\d.]+).*$/,"$1")},SeaMonkey:function(){return t.replace(/^.*SeaMonkey\/([\d.]+).*$/,"$1")},Epiphany:function(){return t.replace(/^.*Epiphany\/([\d.]+).*$/,"$1")},360:function(){return t.replace(/^.*QihooBrowser\/([\d.]+).*$/,"$1")},"360SE":function(){return{63:"10.0",55:"9.1",45:"8.1",42:"8.0",31:"7.0",21:"6.3"}[+t.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"360EE":function(){return{69:"11.0",63:"9.5",55:"9.0",50:"8.7",30:"7.5"}[+t.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},Maxthon:function(){return t.replace(/^.*Maxthon\/([\d.]+).*$/,"$1")},QQBrowser:function(){return t.replace(/^.*QQBrowser\/([\d.]+).*$/,"$1")},QQ:function(){return t.replace(/^.*QQ\/([\d.]+).*$/,"$1")},Baidu:function(){return t.replace(/^.*BIDUBrowser[\s\/]([\d.]+).*$/,"$1")},UC:function(){return t.replace(/^.*UC?Browser\/([\d.]+).*$/,"$1")},Sogou:function(){return t.replace(/^.*SE ([\d.X]+).*$/,"$1").replace(/^.*SogouMobileBrowser\/([\d.]+).*$/,"$1")},LBBROWSER:function(){return{57:"6.5",49:"6.0",46:"5.9",42:"5.3",39:"5.2",34:"5.0",29:"4.5",21:"4.0"}[+navigator.userAgent.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"2345Explorer":function(){return t.replace(/^.*2345Explorer\/([\d.]+).*$/,"$1")},TheWorld:function(){return t.replace(/^.*TheWorld ([\d.]+).*$/,"$1")},XiaoMi:function(){return t.replace(/^.*MiuiBrowser\/([\d.]+).*$/,"$1")},Quark:function(){return t.replace(/^.*Quark\/([\d.]+).*$/,"$1")},Qiyu:function(){return t.replace(/^.*Qiyu\/([\d.]+).*$/,"$1")},Wechat:function(){return t.replace(/^.*MicroMessenger\/([\d.]+).*$/,"$1")},Taobao:function(){return t.replace(/^.*AliApp\(TB\/([\d.]+).*$/,"$1")},Alipay:function(){return t.replace(/^.*AliApp\(AP\/([\d.]+).*$/,"$1")},Weibo:function(){return t.replace(/^.*weibo__([\d.]+).*$/,"$1")},Douban:function(){return t.replace(/^.*com.douban.frodo\/([\d.]+).*$/,"$1")},Suning:function(){return t.replace(/^.*SNEBUY-APP([\d.]+).*$/,"$1")},iQiYi:function(){return t.replace(/^.*IqiyiVersion\/([\d.]+).*$/,"$1")}};return e.browserVersion="",a[e.browser]&&(e.browserVersion=a[e.browser](),e.browserVersion==t&&(e.browserVersion="")),"Edge"==e.browser&&(e.engine="EdgeHTML"),"Chrome"==e.browser&&parseInt(e.browserVersion)>27&&(e.engine="Blink"),"Opera"==e.browser&&parseInt(e.browserVersion)>12&&(e.engine="Blink"),"Yandex"==e.browser&&(e.engine="Blink"),e.browser+" (version: "+e.browserVersion+"; kernel: "+e.engine+")"}},ci={DeviceInfoObj:function(e){var t,i=function(t){var i;null==(i=e.info)||i.forEach((function(e){e.toLowerCase()===t.toLowerCase()&&(s[t]=r[t])}))};e=e||{domain:""};var r={deviceType:hi.getDeviceType(),OS:hi.getOS(),OSVersion:hi.getOSVersion(),sh:oi.screen.height,sw:oi.screen.width,lang:hi.getLanguage(),netWork:hi.getNetwork(),orientation:hi.getOrientationStatu(),browserInfo:hi.getBrowserInfo(),fingerprint:hi.createFingerprint(e.domain),userAgent:null==(t=li.navigator)?void 0:t.userAgent};if(!e.info||0===e.info.length)return r;var s={};for(var n in r)i(n);return s}},{getDeviceInfo:function(e){return ci.DeviceInfoObj(e)}}),fi=function(){function e(){}return e.add=function(t,i){e.queues.push({url:t,data:i})},e.fire=function(){if(e.queues&&0!==e.queues.length){e.isStop=!1;var t=e.queues[0];t.url&&e.api.report(t.data),e.queues.splice(0,1),e.fire()}else e.isStop=!0},e}();fi.isStop=!0,fi.queues=[];var gi=function(){function e(e){this.url=e}var t=e.prototype;return t.report=function(e){this.checkUrl(this.url)&&this.sendInfo(e)},t.sendInfo=function(e){navigator.sendBeacon?this.sendBeacon(this.url,e):this.sendImage(this.url,e)},t.sendImage=function(e,t){var i=this.changeJSON2Query(t),r=new Image;r.onload=r.onerror=function(){r=null},r.src=e+"?"+i+"&random="+Math.random()},t.sendBeacon=function(e,t){try{navigator.sendBeacon(e,this.formatParamsByURLSearchParams(t))}catch(e){}},t.formatParamsByURLSearchParams=function(e){var t=new URLSearchParams;for(var i in e)"object"==typeof e[i]&&(e[i]=JSON.stringify(e[i])),t.append(i,e[i]);return t},t.changeJSON2Query=function(e){var t="";for(var i in e){""!=t&&(t+="&");var r=e[i];t+=i+"="+encodeURIComponent("object"==typeof r?JSON.stringify(r):r)}return t},t.checkUrl=function(e){return!!e&&/^[hH][tT][tT][pP]([sS]?):\/\//.test(e)},e}();function mi(){return mi=Object.assign||function(e){for(var t=1;t0&&t>0))throw new Error("width value "+e+" or height value "+t+" unqualified!");this.width=e,this.height=t},i.play=function(e){throw new Error("Method play not implemented.")},i.pause=function(){throw new Error("Method pause not implemented.")},i.fullscreen=function(){var e,t,i,r;return null==(t=this.logger)||null==(e=t.log)||e.call(t,"[fullscreen]"),null==(r=this.event)||null==(i=r.emit)||i.call(r,"fullscreen"),Ti.send(1,{name:"fullscreen"}),ni.isEnabled&&!this.isMobile?ni.request(this.$container):(this.logger.warn("Not support fullscreen"),Promise.resolve())},i.exitFullscreen=function(){var e,t,i,r;return null==(t=this.logger)||null==(e=t.log)||e.call(t,"[exitFullscreen]"),null==(r=this.event)||null==(i=r.emit)||i.call(r,"exitFullscreen"),Ti.send(1,{name:"exitFullscreen"}),ni.isEnabled&&!this.isMobile?ni.exit():(this.logger.warn("Not support exitFullscreen"),Promise.resolve())},i.setVolume=function(e){throw new Error("Method setVolume not implemented.")},i.resize=function(e,t){Ti.send(1,{name:"resize"});try{var i,r,s,n;this._checkSize(e,t),this.$container.style.width=e+"px",this.$container.style.height=t+"px",null==(r=this.logger)||null==(i=r.log)||i.call(r,"[resize] width: "+e+", height: "+t),null==(n=this.event)||null==(s=n.emit)||s.call(n,"resize",{data:{width:e,height:t}})}catch(e){}},i.destroy=function(){var e,t=this;this.browser&&(this.browser=null),ni.isEnabled&&this._screenfullChange&&(null==ni||null==(e=ni.off)||e.call(ni,"change",this._screenfullChange),this._screenfullChange=null),this.logger&&(this.logger=null),this.event&&setTimeout((function(){t.event.removeAllListeners(),t.event=null}),100)},i.setLogger=function(e){Ti.send(1,{name:"setLogger"}),this.options=zt(this.options,{loggerOptions:e}),this.logger.setOptions(this.options.loggerOptions)},i.getVersion=function(){throw new Error("Method getVersion not implemented.")},i.getOptions=function(){return Ti.send(1,{name:"getOptions"}),this.options},t.supportType=function(e){return!1},t}(ei),bi=function(){function e(e,t){if(this._$container=e,"string"==typeof e&&(this._$container=document.getElementById(e)),!this._$container)throw new Error("VideoCanvas create fail!");this._options=t,this._createDom()}return e.prototype._createDom=function(){var e,t,i,r,s,n,a=this;this.$video||(this.$video=document.createElement("video"),this._options.autoPlay&&(this.$video.muted=!(null==(e=window)?void 0:e.___HUMAN_TOUCH_SCREEN___),this.$video.autoplay=!0,"object"==((s=null==(t=window)?void 0:t.WeixinJSBridge)&&"undefined"!=typeof Symbol&&s.constructor===Symbol?"symbol":typeof s)&&"function"==typeof(null==(r=window)||null==(i=r.WeixinJSBridge)?void 0:i.invoke)&&document.addEventListener("WeixinJSBridgeReady",(function(){a.$video.play(),a.$video.pause()}),!1),this.$video.addEventListener("loadeddata",(function(){setTimeout((function(){a.$video.play()}),10)}))),this.$video.volume=+this._options.volume||0,this.$video.controls=!!this._options.controls,this.$video.preload=this._options.preload||"auto",this.$video.disablePictureInPicture=!0,this.$video.setAttribute("playsInline","true"),this.$video.setAttribute("webkit-playsinline","true"),this.$video.setAttribute("controlsList",this._options.controlsList||""),(this._options.isMobile&&navigator.userAgent.includes("MQQBrowser")||navigator.userAgent.includes("QQTheme"))&&(this.$video.setAttribute("x5-video-player-type","h5"),this.$video.setAttribute("x5-video-player-fullscreen","false"),this.$video.setAttribute("x5-video-orientation","portraint")),this._options.loop&&this.$video.setAttribute("loop","true"),this.$video.style.cssText+="width: 100%; height: 100%; object-fit: contain; position: absolute; z-index: 1; outline: none;",this._$container.innerHTML="",this._$container.appendChild(this.$video),this._options.disableContextmenu&&(null==(n=this.$video)||n.addEventListener("contextmenu",(function(e){return e.preventDefault(),!1}))))},e}(),Li="ezui-hls",wi={width:600,height:400,volume:0,retry:20,autoPlay:!0,staticPath:"",isLive:!0,loggerOptions:{name:"HLS",level:"INFO",showTime:!0}},Ai={disableContextmenu:!0},Ri=function(){function e(e){void 0===e&&(e={}),this.options=Object.assign({},Ai,e),this.logger=this.options.logger,this.event=this.options.event,this._classVideo=Li+"-video",this._$container=document.getElementById(this.options.id),this._render()}var t=e.prototype;return t._render=function(){var e,t;if("video"===this.options.nodeName)this.$video=new bi(this._$container,this.options).$video;else{var i;if(this.$video=document.createElement(this.options.nodeName),this._$container.innerHTML="",this._$container.appendChild(this.$video),this.options.disableContextmenu)null==(i=this.$video)||i.addEventListener("contextmenu",(function(e){return e.preventDefault(),!1}));this.$video.classList.add(this._classVideo),this.$video.style.cssText+="object-fit: contain; z-index:1;"}null==(t=this.event)||null==(e=t.emit)||e.call(t,"rendered")},t._isVideo=function(){return"VIDEO"===this.$video.nodeName},t.destroy=function(){if(this.$video&&this._$container&&this.$video){try{this._$container.removeChild(this.$video)}catch(e){}this.$video=null}},e}();function ki(e,t,i){return t&&function(e,t){for(var i=0;i=1&&(null==(i=e)||null==(t=i.onLoadCacheFinished)||t.call(i),window.clearInterval(e.cacheInterval),e.cacheInterval=null,e.isCaching===b&&e.play(e.playParams),e.isCaching=S)}),40))}},r._playFunc=function(){var e=!1;if(R()-this.calculateStartTime>=this.frameTime-this.preCostTime){e=!0;var t=!0;if(this.calculateStartTime=R(),this.options.audioNone)this.playFrameYUV(t);else{this.fix_poc_err_skip>0&&(this.fix_poc_err_skip--,t=!1);var i=this.videoPTS-this.audio.getAlignVPTS();if(i>0)return void(this.playParams.seekEvent&&!this.options.audioNone&&this.audio.setVolume(0));if(t){if(!(t=-1*i<=1*this.frameTimeSec)){for(var r=parseInt(i/this.frameTimeSec+""),s=0;s",e,r,i),r>=i&&(t.playFrameYUV(!0),i+=1)}),this.frameTime||5)}else(this.videoPTS>=this.playParams.seekPos&&!this.isNewSeek||0===this.playParams.seekPos||0===this.playParams.seekPos)&&(this.frameTime=1e3/this.options.fps,this.frameTimeSec=this.frameTime/1e3,this.options.audioNone||this.audio.play(),this._volume=this.options.audioNone?0:this.audio.volume,this.loop=window.setInterval((function(){var e=R();t._playFunc(),t.preCostTime=R()-e}),this.frameTime||5));return this.setVolume(this._volume),Promise.resolve()},r.stop=function(){this.destroy(),this.stream=new Uint8Array},r.destroy=function(){return void 0!==this.gl&&null!==this.gl&&(this.gl.destroyContext(),this.gl=null),this.endAudio(),this.cacheLoop&&window.clearInterval(this.cacheLoop),this.cacheLoop=null,this.loop&&window.clearInterval(this.loop),this.loop=null,this.pause(),this.decoderWorker.postMessage(P(B)),this.stream=null,this.frameList=null,this.durationMs=-1,this.videoPTS=0,this.isPlaying=!1,this.$video.remove(),!0},r.nextNalu=function(e){if(void 0===e&&(e=1),this.stream.length<=4)return!1;for(var t=-1,i=0;i=this.stream.length){if(-1===t)return!1;var r=this.stream.subarray(t);return this.stream=new Uint8Array,r}var s="0 0 1"===this.stream.slice(0,3).join(" "),n="0 0 0 1"===this.stream.slice(0,4).join(" ");if(s||n){if(-1===t)t=i;else{if(e<=1){var a=this.stream.subarray(t,i);return this.stream=this.stream.subarray(i),a}e-=1}i+=3}}return!1},r.playFrameYUV=function(e){void 0===e&&(e=!1);var t=this.cacheYuvBuf.shiftYuv();if(!t)return this.noCacheFrame+=1,e&&!this.playParams.seekEvent&&this.loadCache(),!1;this.noCacheFrame=0;var i=t.pts;return this.videoPTS=i,this.drawImage(t.width,t.height,t.imageBufferY,t.imageBufferB,t.imageBufferR),t=null,e&&!this.playParams.seekEvent&&this.isPlaying&&this.loadCache(),!0},r.drawImage=function(e,t,i,r,s){this.$video.width===e&&this.$video.height===t||(this.$video.width=e,this.$video.height=t),this.isCheckDisplay||this.checkDisplaySize(e,t);var n=e*t,a=e/2*(t/2),o=new Uint8Array(n+2*a);o.set(i,0),o.set(r,n),o.set(s,n+a),this.gl.renderFrame(i,r,s,e,t),o=null},r.checkDisplaySize=function(e,t){var i,r=e/(null==(i=this.options)?void 0:i.width)>t/this.options.height,s=+(this.options.width/e).toFixed(2),n=+(this.options.height/t).toFixed(2),a=r?s:n,o=this.options.fixed,l=o?this.options.width:parseInt(e*a+""),h=o?this.options.height:parseInt(t*a+"");return this.$video.style.maxWidth="100%",this.$video.style.maxHeight="100%",this.options.width/this.options.height>=1&&l/h>=1?this.$video.style.width="100%":this.$video.style.height="100%",this.isCheckDisplay=!0,[l,h]},r._onWorkerMessage=function(){var e=this;this.decoderWorker.onmessage=function(t){var i=t.data;if(i.cmd===N){var r=i.data,s=r.ptsSec,n=r.strideY,a=r.height;r.width;var o=r.bufY,l=r.bufU,h=r.bufV,c=new x(s,n,a,o,l,h);e.cacheYuvBuf.appendCacheByCacheYuv(c),c=null}}},r.initVideoAndAudio=function(){this.$video.width=this.options.width,this.$video.height=this.options.height,this.gl=new I(this.$video,{preserveDrawingBuffer:!1}),this.options.audioNone||(this.audio=new _({logger:this.logger,sampleRate:this.options.sampleRate,appendType:this.options.appendHevcType,volume:this.options.volume,isLive:this.options.isLive})),this.isPlayLoadingFinish=1},ki(i,[{key:"volume",get:function(){var e;return(null==(e=this.audio)?void 0:e.volume)||this._volume},set:function(e){this.setVolume(e)}}]),i}(Ri),Ci=[/#EXT-X-PROGRAM-DATE-TIME.+\n/g],Ii={lineDelimiter:/\r?\n/,extensionHeader:"#EXTM3U",tagPrefix:"#EXT",segmentPrefix:"#EXTINF",segmentParse:/^#EXTINF: *([0-9.]+)(, *(.+?)?)?$/,tagParse:/^#EXT-X-([A-Z-]+)(:(.+))?$/,version:"VERSION",allowCache:"ALLOW-CACHE",combined:"COMBINED",endList:"ENDLIST",targetDuration:"TARGETDURATION",mediaSequence:"MEDIA-SEQUENCE",discontinuity:"DISCONTINUITY",streamInf:"STREAM-INF",isComment:function(e){return e&&"#"===e[0]&&!e.startsWith(Ii.tagPrefix)},isBlank:function(e){return""===e},canStrip:function(e){return Ii.isBlank(e)||Ii.isComment(e)},defaultMinDur:99999},Pi=function(){function e(e){this._retry=10,this.logger=null==e?void 0:e.logger,this.initState=!0,this.controller=new AbortController,this._slices=[],this._type=o,this._preURI="",this.duration=-1,this.onTransportStream=null,this.onFinished=null}var t=e.prototype;return t.destroy=function(){this.initState=!1},t.fetchM3u8=function(e){var t=this,i=this;if(this.initState){var r=function(t){return new Promise((function(i,r){var s=new XMLHttpRequest;s.open("GET",t),s.onload=function(){this.status>=200&&this.status<300&&(t!==this.responseURL?(e=this.responseURL,i(this.responseURL)):i(""))},s.onreadystatechange=function(){4===s.readyState&&200===s.status&&i(s.responseText)},s.onerror=function(){r(new Error("Network error."))},s.send()}))};r(e).then((function(s){if(t._retry=10,i._uriParse(e)){var n=i._m3u8Parse(s);if("number"==typeof n&&n>=0)var a=setTimeout((function(){i.fetchM3u8(e),clearTimeout(a)}),200*n)}return r=null,s})).catch((function(s){if(t.logger.error("[M3u8Base] fetch m3u8 url Error ==> ",s),r=null,t._retry>=1)var n=setTimeout((function(){i.fetchM3u8(e),clearTimeout(n)}),500);t._retry--}))}},t._uriParse=function(e){this._preURI="";var t=e.split("://"),i=null,r=null;if(t.length<1)return this.logger.log("HLS URI ERROR : "+e),!1;t.length>1?(i=t[0],r=t[1].split("/"),this._preURI=i+"://"):r=t[0].split("/");for(var s=0;su&&(s=u);var f,g=r[o+=1],m=null;if(g.includes("http"))m=g;else{if("/"===g[0]){var p=this._preURI.split("//"),v=p[p.length-1].split("/");this._preURI=p[0]+"//"+v[0]}m=this._preURI+g}if(!this._slices.includes(m))this._slices.push(m),null==this||null==(f=this.onTransportStream)||f.call(this,m,u)}}}this._slices.length>500&&(this._slices=this._slices.slice(-500));var y={type:this._type,duration:-1};return null==this||null==(t=this.onFinished)||t.call(this,y),s},t._readTag=function(e){var t=Ii.tagParse.exec(e);return null!==t?{key:t[1],value:t[3]}:null},e}(),Oi=function(){function e(e){this.sampleRate=e.sampleRate,this.frameDurMs=Math.floor(1024e3/this.sampleRate),this.frameDurSec=this.frameDurMs/1e3}var t=e.prototype;return t.updateOptions=function(e){this.sampleRate=e.sampleRate,this.frameDurMs=1024e3/this.sampleRate,this.frameDurSec=this.frameDurMs/1e3},t._getPktLen=function(e,t,i){return((3&e)<<11)+(t<<3)+((224&i)>>5)},t.sliceAACFrames=function(e,t){for(var i=[],r=e,s=0;s>4==15){var n=this._getPktLen(t[s+3],t[s+4],t[s+5]);if(n<=0)continue;var a=t.subarray(s,s+n),o=new Uint8Array(n);o.set(a,0),i.push({ptime:r,data:o}),r+=this.frameDurSec,s+=n}else s+=1;return i},e}(),Mi="M3U8",Fi="TS",Ni="FETCH",Ui=function(){function e(){}return e.init=function(t){e.collect=new pi(t)},e.send=function(t,i){var r,s;null==(s=e.collect)||null==(r=s.send)||r.call(s,{action:t,logInfo:i})},e.updateParams=function(t){e.collect.updateExtendsInfo(t)},e}();function Bi(e,t,i){return t&&function(e,t){for(var i=0;i ",e),s=null})).catch((function(r){var s,n,a,o;t.logger.error("[MpegTsDemux] demuxerTsInit ERROR fetch ERROR ==> ",r),null==(n=t.event)||null==(s=n.emit)||s.call(n,Fi,{data:r}),null==(o=t.event)||null==(a=o.emit)||a.call(o,Ni,{data:r,type:Fi}),null==i||i.onDemuxedFailed(r,e),Ui.send(100,{url:e,msg:"fetch error"})}))},t._demuxCore=function(e,t){e.length<=0||this.decoderWorker.postMessage(P($,{buff:e,tsUrl:t}))},t.readMediaInfo=function(){return this.mediaInfo},t.readAudioNone=function(){var e;return null==(e=this.mediaInfo)?void 0:e.audioNone},t.isHEVC=function(){return this.mediaInfo.vCodec===n||this.mediaInfo.vCodec===s},t.destroy=function(){this.controller&&this.controller.abort(),this.controller=null,this.mediaInfo=null,this.aacDec=null},t._onWorkerMessage=function(){var e=this;e.logger.log("[demuxer] register _onWorkerMessage"),e.decoderWorker.addEventListener("message",(function(t){var i=t.data;switch(i.cmd){case H:var r,s;if(e.mediaInfo=i.data,e.mediaInfo)null==(s=e.event)||null==(r=s.emit)||r.call(s,"mediaInfo",e.mediaInfo);break;case G:var n;if(e.mediaInfo.vCodec)null==e.aacDec?e.aacDec=new Oi(e.mediaInfo):e.aacDec.updateOptions(e.mediaInfo),null==e||null==(n=e.onDemuxed)||n.call(e)}}))},Bi(e,[{key:"vCodec",get:function(){return this.mediaInfo.vCodec}}]),e}(),Ki=function(){function e(e,t,i,r){this.pts=e,this.dts=e,this.isKey=t,this.data=i,this.video=r}return e.prototype.setFrame=function(e,t,i,r){this.pts=e,this.isKey=t,this.data=i,this.video=r},e}(),Vi=function(){function e(e){this.logger=null==e?void 0:e.logger,this.event=null==e?void 0:e.event,this.decoderWorker=e.decoderWorker,this.m3u8Base=new Pi(e),this.mpegTsDemux=new Gi(e),this.tsList=[],this._startTime=0,this._aStartTime=0,this.lockWait={state:!1,lockMember:{dur:0}},this._timerFeed=null,this.seekPos=-1,this.vPreFramePTS=0,this.aPreFramePTS=0,this.audioNone=!1,this.isHevcParam=!1,this.vCodec="",this.aCodec=null,this.aChannel=0,this.durationMs=-1,this.fps=-1,this.sampleRate=-1,this.size={width:-1,height:-1},this.mediaInfo=null,this._onWorkerMessage(),this.onReadyOBJ=null,this.onFinished=null,this.onDemuxed=null,this.onSamples=null,this.onCacheProcess=null}var t=e.prototype;return t.getCachePTS=function(){return Math.max(this.vPreFramePTS,this.aPreFramePTS)},t.demux=function(e){var t=this,i=this;this.vPreFramePTS=0,this.aPreFramePTS=0,this.m3u8Base.onTransportStream=function(e,t){i.tsList.push({streamURI:e,streamDur:t}),i.lockWait.state=!1},this.m3u8Base.onFinished=function(e){var t;e.type===a?i.durationMs=1e3*e.duration:i.durationMs=-1,null==i||null==(t=i.onFinished)||t.call(i,i.onReadyOBJ,e)},this.mpegTsDemux.onDemuxedFailed=function(e,r){t.logger.error("[M3u8] onDemuxedFailed: ",e,r),i.lockWait.state=!1},this.mpegTsDemux.onDemuxed=function(){var e;t.logger.log("[M3u8] onDemuxed"),null==i.mediaInfo&&(i.mediaInfo=i.mpegTsDemux.readMediaInfo(),t.logger.log("[M3u8] mediaInfo: ",i.mediaInfo),i.isHevcParam=i.mpegTsDemux.isHEVC(),i.vCodec=i.mpegTsDemux.vCodec,i.aCodec=i.mediaInfo.aCodec,i.aChannel=i.mediaInfo.sampleChannel,i.fps=i.mediaInfo.fps,i.sampleRate=i.mediaInfo.sampleRate,(null===i.aCodec||""===i.aCodec||i.aChannel<=0)&&(i.audioNone=!0),i.mediaInfo.width>0&&i.mediaInfo.height>0&&(t.size.width=t.mediaInfo.width,t.size.height=t.mediaInfo.height)),null==i||null==(e=i.onDemuxed)||e.call(i,i.onReadyOBJ),i.mpegTsDemux&&t.decoderWorker.postMessage(P(K))},this.mpegTsDemux.onReady=function(){i._fetchM3u8AndIntervalTs(e)},this._timerTsWasm=window.setInterval((function(){1===Uc.__HLS_WASM_DecoderState__&&(i._fetchM3u8AndIntervalTs(e),window.clearInterval(i._timerTsWasm),i._timerTsWasm=null)}),500)},t._fetchM3u8AndIntervalTs=function(e){var t=this,i=this;this.logger.log("[M3u8] start fetch m3u8 url"),i.m3u8Base.fetchM3u8(e),i._timerFeed=window.setInterval((function(){if(i.tsList.length>0&&!i.lockWait.state)try{var e=i.tsList.shift();if(null!=e){var r=e.streamURI,s=e.streamDur;i.lockWait.state=!0,i.lockWait.lockMember.dur=+s,i.mpegTsDemux.demuxURL(r)}else t.logger.error("[M3u8] onTsReady need wait ")}catch(e){var n,a,o,l;t.logger.error("[M3u8] onTsReady ERROR:",e),null==(a=t.event)||null==(n=a.emit)||n.call(a,Mi,{data:e}),null==(l=t.event)||null==(o=l.emit)||o.call(l,Ni,{data:e,type:Mi}),i.lockWait.state=!1}}),50)},t.destroy=function(){var e;this.m3u8Base&&(null==(e=this.m3u8Base)||e.destroy(),this.m3u8Base=null);this._timerFeed&&(window.clearInterval(this._timerFeed),this._timerFeed=null),this.mpegTsDemux&&(this.mpegTsDemux.destroy(),this.mpegTsDemux=null)},t.bindReady=function(e){this.onReadyOBJ=e},t.getACodec=function(){return this.aCodec},t.getVCodec=function(){return this.vCodec},t.getDurationMs=function(){return this.durationMs},t.getFPS=function(){return this.fps},t.getSampleRate=function(){return this.sampleRate},t.getSampleChannel=function(){return this.aChannel},t.getSize=function(){return this.size},t._onWorkerMessage=function(){this.logger.log("[M3U8] register _onWorkerMessage");var e=this;e.decoderWorker.addEventListener("message",(function(t){var i=t.data;switch(i.cmd){case K:var s,n=i.data,a=n.type,o=n.pts,l=n.ptime,h=n.keyframe,c=n.data,d=n.layer;if(c=new Uint8Array(c),1===a&&e.mpegTsDemux.mediaInfo.aCodec===r&&(c=e.mpegTsDemux.aacDec.sliceAACFrames(l,c)),0===a){var u=function(e){var t=e.nalu,i=e.vlc.vlc;null==t.vps&&(t.vps=new Uint8Array);var r=new Uint8Array(t.vps.length+t.sps.length+t.pps.length+t.sei.length+i.length);return r.set(t.vps,0),r.set(t.sps,t.vps.length),r.set(t.pps,t.vps.length+t.sps.length),r.set(t.sei,t.vps.length+t.sps.length+t.pps.length),r.set(i,t.vps.length+t.sps.length+t.pps.length+t.sei.length),r}(d),f=o,g=new Ki(f,1===h,u,!0);e.vPreFramePTS=f,null==e||e.onSamples(e.onReadyOBJ,g)}else if(1===a){var m;if("aac"===(null==(m=e.mediaInfo)?void 0:m.aCodec)){for(var p=c,v=0;v`):sr}(t)}))}const lr=ar,hr=/^(\d+)x(\d+)$/,cr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class dr{constructor(e){"string"==typeof e&&(e=dr.parseAttrList(e)),Qi(this,e)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const i=new Uint8Array(t.length/2);for(let e=0;eNumber.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return"YES"===this[e]}decimalResolution(e){const t=hr.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={};for(cr.lastIndex=0;null!==(t=cr.exec(e));){let e=t[2];0===e.indexOf('"')&&e.lastIndexOf('"')===e.length-1&&(e=e.slice(1,-1));i[t[1].trim()]=e}return i}}function ur(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}class fr{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){lr.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=Qi(new dr({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=new Date(this.attr["END-DATE"]);Ji(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Ji(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&Ji(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class gr{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var mr="audio",pr="video",vr="audiovideo";class yr{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[mr]:null,[pr]:null,[vr]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2);let r;r=1===i.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Wi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class Tr extends yr{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new gr,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!Ji(this.programDateTime))return null;const e=Ji(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,r,s,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[mr]=null,e[pr]=null,e[vr]=null}}class Er extends yr{constructor(e,t,i,r,s){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new gr,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}class Sr{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&Ji(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function br(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function Lr(e){const t=e.split(":");let i=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){const t="base64"===r[0],s=r[1];t?(e.splice(-1,1),i=br(s)):i=function(e){const t=wr(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(s)}}return i}function wr(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}const Ar="undefined"!=typeof self?self:void 0;var Rr={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},kr="org.w3.clearkey",_r="com.apple.streamingkeydelivery",Dr="com.microsoft.playready",xr="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Cr(e){switch(e){case _r:return Rr.FAIRPLAY;case Dr:return Rr.PLAYREADY;case xr:return Rr.WIDEVINE;case kr:return Rr.CLEARKEY}}var Ir="edef8ba979d64acea3c827dcd51d21ed";function Pr(e){switch(e){case Rr.FAIRPLAY:return _r;case Rr.PLAYREADY:return Dr;case Rr.WIDEVINE:return xr;case Rr.CLEARKEY:return kr}}function Or(e){const{drmSystems:t,widevineLicenseUrl:i}=e,r=t?[Rr.FAIRPLAY,Rr.WIDEVINE,Rr.PLAYREADY,Rr.CLEARKEY].filter((e=>!!t[e])):[];return!r[Rr.WIDEVINE]&&i&&r.push(Rr.WIDEVINE),r}const Mr=null!=Ar&&null!=(Fr=Ar.navigator)&&Fr.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Fr;function Nr(e,t,i){return Uint8Array.prototype.slice?e.slice(t,i):new Uint8Array(Array.prototype.slice.call(e,t,i))}const Ur=(e,t)=>t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,Br=(e,t)=>t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,$r=(e,t)=>{const i=t;let r=0;for(;Ur(e,t);){r+=10;r+=Gr(e,t+6),Br(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(i,i+r)},Gr=(e,t)=>{let i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3],i},Kr=(e,t)=>Ur(e,t)&&Gr(e,t+6)+10<=e.length-t,Vr=e=>{const t=Wr(e);for(let e=0;ee&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,jr=e=>{const t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=Gr(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}},Wr=e=>{let t=0;const i=[];for(;Ur(e,t);){const r=Gr(e,t+6);t+=10;const s=t+r;for(;t+8"PRIV"===e.type?qr(e):"W"===e.type[0]?Xr(e):zr(e),qr=e=>{if(e.size<2)return;const t=Jr(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}},zr=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1;const i=Jr(e.data.subarray(t),!0);t+=i.length+1;const r=Jr(e.data.subarray(t));return{key:e.type,info:i,data:r}}const t=Jr(e.data.subarray(1));return{key:e.type,data:t}},Xr=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1;const i=Jr(e.data.subarray(t),!0);t+=i.length+1;const r=Jr(e.data.subarray(t));return{key:e.type,info:i,data:r}}const t=Jr(e.data);return{key:e.type,data:t}},Qr=e=>{if(8===e.data.byteLength){const t=new Uint8Array(e.data),i=1&t[3];let r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}},Jr=(e,t=!1)=>{const i=es();if(i){const r=i.decode(e);if(t){const e=r.indexOf("\0");return-1!==e?r.substring(0,e):r}return r.replace(/\0/g,"")}const r=e.length;let s,n,a,o="",l=0;for(;l>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:n=e[l++],o+=String.fromCharCode((31&s)<<6|63&n);break;case 14:n=e[l++],a=e[l++],o+=String.fromCharCode((15&s)<<12|(63&n)<<6|63&a)}}return o};let Zr;function es(){if(!navigator.userAgent.includes("PlayStation 4"))return Zr||void 0===self.TextDecoder||(Zr=new self.TextDecoder("utf-8")),Zr}const ts=function(e){let t="";for(let i=0;i>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function ds(e,t){const i=[];if(!t.length)return i;const r=e.byteLength;for(let s=0;s1?s+n:r;if(ns(e.subarray(s+4,s+8))===t[0])if(1===t.length)i.push(e.subarray(s+8,a));else{const r=ds(e.subarray(s+8,a),t.slice(1));r.length&&rs.apply(i,r)}s=a}return i}function us(e){const t=[],i=e[0];let r=8;const s=os(e,r);r+=4;let n=0,a=0;0===i?(n=os(e,r),a=os(e,r+4),r+=8):(n=ls(e,r),a=ls(e,r+8),r+=16),r+=2;let o=e.length+a;const l=as(e,r);r+=2;for(let i=0;i>>31)return lr.warn("SIDX has hierarchical references (not supported)"),null;const l=os(e,i);i+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,i+=4,r=i}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:t}}function fs(e){const t=[],i=ds(e,["moov","trak"]);for(let e=0;e{const i=os(e,4),r=t[i];r&&(r.default={duration:os(e,12),flags:os(e,20)})})),t}function gs(e){const t=e.subarray(8),i=t.subarray(86),r=ns(t.subarray(4,8));let s=r;const n="enca"===r||"encv"===r;if(n){const e=ds(t,[r])[0];ds(e.subarray("enca"===r?28:78),["sinf"]).forEach((e=>{const t=ds(e,["schm"])[0];if(t){const i=ns(t.subarray(4,8));if("cbcs"===i||"cenc"===i){const t=ds(e,["frma"])[0];t&&(s=ns(t))}}}))}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const e=ds(i,["avcC"])[0];s+="."+ps(e[1])+ps(e[2])+ps(e[3]);break}case"mp4a":{const e=ds(t,[r])[0],i=ds(e.subarray(28),["esds"])[0];if(i&&i.length>12){let e=4;if(3!==i[e++])break;e=ms(i,e),e+=2;const t=i[e++];if(128&t&&(e+=2),64&t&&(e+=i[e++]),4!==i[e++])break;e=ms(i,e);const r=i[e++];if(64!==r)break;if(s+="."+ps(r),e+=12,5!==i[e++])break;e=ms(i,e);const n=i[e++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&i[e])>>5)),s+="."+a}break}case"hvc1":case"hev1":{const e=ds(i,["hvcC"])[0],t=e[1],r=["","A","B","C"][t>>6],n=31&t,a=os(e,2),o=(32&t)>>5?"H":"L",l=e[12],h=e.subarray(6,12);s+="."+r+n,s+="."+a.toString(16).toUpperCase(),s+="."+o+l;let c="";for(let e=h.length;e--;){const t=h[e];if(t||c){c="."+t.toString(16).toUpperCase()+c}}s+=c;break}case"dvh1":case"dvhe":{const e=ds(i,["dvcC"])[0],t=e[2]>>1&127,r=e[2]<<5&32|e[3]>>3&31;s+="."+vs(t)+"."+vs(r);break}case"vp09":{const e=ds(i,["vpcC"])[0],t=e[4],r=e[5],n=e[6]>>4&15;s+="."+vs(t)+"."+vs(r)+"."+vs(n);break}case"av01":{const e=ds(i,["av1C"])[0],t=e[1]>>>5,r=31&e[1],n=e[2]>>>7?"H":"M",a=(64&e[2])>>6,o=(32&e[2])>>5,l=2===t&&a?o?12:10:a?10:8,h=(16&e[2])>>4,c=(8&e[2])>>3,d=(4&e[2])>>2,u=3&e[2],f=1,g=1,m=1,p=0;s+="."+t+"."+vs(r)+n+"."+vs(l)+"."+h+"."+c+d+u+"."+vs(f)+"."+vs(g)+"."+vs(m)+"."+p;break}}return{codec:s,encrypted:n}}function ms(e,t){const i=t+5;for(;128&e[t++]&&t{const l=o.byteOffset-8;ds(o,["traf"]).map((o=>{const h=ds(o,["tfdt"]).map((e=>{const t=e[0];let i=os(e,4);return 1===t&&(i*=Math.pow(2,32),i+=os(e,8)),i/s}))[0];return void 0!==h&&(e=h),ds(o,["tfhd"]).map((h=>{const c=os(h,4),d=16777215&os(h,0);let u=0;const f=!!(16&d);let g=0;const m=!!(32&d);let p=8;c===n&&(!!(1&d)&&(p+=8),!!(2&d)&&(p+=4),!!(8&d)&&(u=os(h,p),p+=4),f&&(g=os(h,p),p+=4),m&&(p+=4),"video"===t.type&&(a=function(e){if(!e)return!1;const t=e.indexOf("."),i=t<0?e:e.substring(0,t);return"hvc1"===i||"hev1"===i||"dvh1"===i||"dvhe"===i}(t.codec)),ds(o,["trun"]).map((n=>{const o=n[0],h=16777215&os(n,0),c=!!(1&h);let d=0;const f=!!(4&h),m=!!(256&h);let p=0;const v=!!(512&h);let y=0;const T=!!(1024&h),E=!!(2048&h);let S=0;const b=os(n,4);let L=8;c&&(d=os(n,L),L+=4),f&&(L+=4);let w=d+l;for(let l=0;l>1&63;return 39===e||40===e}return 6===(31&t)}function Ls(e,t,i,r){const s=ws(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);const e=s.length-n;let t=n;if(oe){lr.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===s[t++]){const e=as(s,t);if(t+=2,49===e){const e=os(s,t);if(t+=4,1195456820===e){const e=s[t++];if(3===e){const n=s[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e16){const e=[];for(let i=0;i<16;i++){const r=s[t++].toString(16);e.push(1==r.length?"0"+r:r),3!==i&&5!==i&&7!==i&&9!==i||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e,...t){const i=t.length;let r=8,s=i;for(;s--;)r+=t[s].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(e,4),s=0,r=8;s>8*(15-i)&255;return t}(e);return new ks(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=Lr(this.uri);if(t)switch(this.keyFormat){case xr:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case Dr:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=As(e,0,t);const i=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(i)),s=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const e=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(e){const t=br(e).subarray(0,16);!function(e){const t=function(e,t,i){const r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(t),this.keyId=t}}break}default:{let e=t.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=Rs[this.uri];if(!e){const t=Object.keys(Rs).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),Rs[this.uri]=e}this.keyId=e}return this}}const _s=/\{\$([a-zA-Z0-9-_]+)\}/g;function Ds(e){return _s.test(e)}function xs(e,t,i){if(null!==e.variableList||e.hasVariableRefs)for(let r=i.length;r--;){const s=i[r],n=t[s];n&&(t[s]=Cs(e,n))}}function Cs(e,t){if(null!==e.variableList||e.hasVariableRefs){const i=e.variableList;return t.replace(_s,(t=>{const r=t.substring(2,t.length-1),s=null==i?void 0:i[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):s}))}return t}function Is(e,t,i){let r,s,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{const e=new self.URL(i).searchParams;if(!e.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${i}"`);s=e.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,s=t.VALUE;r in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=s||""}function Ps(e,t,i){const r=t.IMPORT;if(i&&r in i){let t=e.variableList;t||(e.variableList=t={}),t[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}function Os(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const Ms={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Fs(e,t,i=!0){return!e.split(",").some((e=>!Ns(e,t,i)))}function Ns(e,t,i=!0){var r;const s=Os(i);return null!=(r=null==s?void 0:s.isTypeSupported(Us(e,t)))&&r}function Us(e,t){return`${t}/mp4;codecs="${e}"`}function Bs(e){if(e){const t=e.substring(0,4);return Ms.video[t]}return 2}function $s(e){return e.split(",").reduce(((e,t)=>{const i=Ms.video[t];return i?(2*i+e)/(e?3:2):(Ms.audio[t]+e)/(e?2:1)}),0)}const Gs={};const Ks=/flac|opus/i;function Vs(e,t=!0){return e.replace(Ks,(e=>function(e,t=!0){if(Gs[e])return Gs[e];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[e];for(let r=0;r0&&r.length({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:n.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Ws.lastIndex=0;null!==(r=Ws.exec(e));){const e=new dr(r[1]),n=e.TYPE;if(n){const r=a[n],l=s[n]||[];s[n]=l,xs(i,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h=e.LANGUAGE,c=e["ASSOC-LANGUAGE"],d=e.CHANNELS,u=e.CHARACTERISTICS,f=e["INSTREAM-ID"],g={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||h||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:h,url:e.URI?Xs.resolve(e.URI,t):""};if(c&&(g.assocLang=c),d&&(g.channels=d),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=r&&r.length){const e=Xs.findGroup(r,g.groupId)||r[0];en(g,e,"audioCodec"),en(g,e,"textCodec")}l.push(g)}}return s}static parseLevelPlaylist(e,t,i,r,s,n){const a=new Sr(t),o=a.fragments;let l,h,c,d=null,u=0,f=0,g=0,m=0,p=null,v=new Tr(r,t),y=-1,T=!1,E=null;for(qs.lastIndex=0,a.m3u8=e,a.hasVariableRefs=Ds(e);null!==(l=qs.exec(e));){T&&(T=!1,v=new Tr(r,t),v.start=g,v.sn=u,v.cc=m,v.level=i,d&&(v.initSegment=d,v.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null,E&&(v.setByteRange(E),E=null)));const e=l[1];if(e){v.duration=parseFloat(e);const t=(" "+l[2]).slice(1);v.title=t||null,v.tagList.push(t?["INF",e,t]:["INF",e])}else if(l[3]){if(Ji(v.duration)){v.start=g,c&&sn(v,c,a),v.sn=u,v.level=i,v.cc=m,o.push(v);const e=(" "+l[3]).slice(1);v.relurl=Cs(a,e),tn(v,p),p=v,g+=v.duration,u++,f=0,T=!0}}else if(l[4]){const e=(" "+l[4]).slice(1);p?v.setByteRange(e,p):v.setByteRange(e)}else if(l[5])v.rawProgramDateTime=(" "+l[5]).slice(1),v.tagList.push(["PROGRAM-DATE-TIME",v.rawProgramDateTime]),-1===y&&(y=o.length);else{if(l=l[0].match(zs),!l){lr.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h0&&e.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),a.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new dr(s);a.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=a.partList;e||(e=a.partList=[]);const i=f>0?e[e.length-1]:void 0,r=f++,n=new dr(s);xs(a,n,["BYTERANGE","URI"]);const o=new Er(n,v,t,r,i);e.push(o),v.duration+=o.duration;break}case"PRELOAD-HINT":{const e=new dr(s);xs(a,e,["URI"]),a.preloadHint=e;break}case"RENDITION-REPORT":{const e=new dr(s);xs(a,e,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(e);break}default:lr.warn(`line parsed but not handled: ${l}`)}}}p&&!p.relurl?(o.pop(),g-=p.duration,a.partList&&(a.fragmentHint=p)):a.partList&&(tn(v,p),v.cc=m,a.fragmentHint=v,c&&sn(v,c,a));const S=o.length,b=o[0],L=o[S-1];if(g+=a.skippedSegments*a.targetduration,g>0&&S&&L){a.averagetargetduration=g/S;const e=L.sn;a.endSN="initSegment"!==e?e:0,a.live||(L.endList=!0),b&&(a.startCC=b.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(g+=a.fragmentHint.duration),a.totalduration=g,a.endCC=m,y>0&&function(e,t){let i=e[t];for(let r=t;r--;){const t=e[r];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(o,y),a}}function Qs(e,t,i){var r,s;const n=new dr(e);xs(i,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,c=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&lr.error(`Invalid IV: ${n.IV}`);const d=o?Xs.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new ks(a,d,c,u,l)}function Js(e){const t=new dr(e).decimalFloatingPoint("TIME-OFFSET");return Ji(t)?t:null}function Zs(e,t){let i=(e||"").split(/[ ,]+/).filter((e=>e));["video","audio","text"].forEach((e=>{const r=i.filter((t=>function(e,t){const i=Ms[t];return!!i&&!!i[e.slice(0,4)]}(t,e)));r.length&&(t[`${e}Codec`]=r.join(","),i=i.filter((e=>-1===r.indexOf(e))))})),t.unknownCodecs=i}function en(e,t,i){const r=t[i];r&&(e[i]=r)}function tn(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Ji(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function rn(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function sn(e,t,i){e.levelkeys=t;const{encryptedFragments:r}=i;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||r.push(e)}var nn="manifest",an="level",on="audioTrack",ln="subtitleTrack",hn="main",cn="audio",dn="subtitle";function un(e){const{type:t}=e;switch(t){case on:return cn;case ln:return dn;default:return hn}}function fn(e,t){let i=e.url;return void 0!==i&&0!==i.indexOf("data:")||(i=t.url),i}class gn{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.LEVEL_LOADING,this.onLevelLoading,this),e.on(tr.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(tr.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.LEVEL_LOADING,this.onLevelLoading,this),e.off(tr.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(tr.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:nn,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:r,pathwayId:s,url:n,deliveryDirectives:a}=t;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:an,url:n,deliveryDirectives:a})}onAudioTrackLoading(e,t){const{id:i,groupId:r,url:s,deliveryDirectives:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:on,url:s,deliveryDirectives:n})}onSubtitleTrackLoading(e,t){const{id:i,groupId:r,url:s,deliveryDirectives:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ln,url:s,deliveryDirectives:n})}load(e){var t;const i=this.hls.config;let r,s=this.getInternalLoader(e);if(s){const t=s.context;if(t&&t.url===e.url&&t.level===e.level)return void lr.trace("[playlist-loader]: playlist request ongoing");lr.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(r=e.type===nn?i.manifestLoadPolicy.default:Qi({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),Ji(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===an&&null!==e.level?t=this.hls.levels[e.level].details:e.type===on&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===ln&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,i=t.targetduration;if(e&&i){const t=1e3*Math.max(3*e,.8*i);r=Qi({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,i,r)=>{const s=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=e.data;0===n.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),Xs.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(e,t,i,r||null,s):this.handleMasterPlaylist(e,t,i,r)):this.handleManifestParsingError(e,i,new Error("no EXTM3U delimiter"),r||null,t)},onError:(e,t,i,r)=>{this.handleNetworkError(t,i,!1,e,r)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}};s.load(e,a,o)}handleMasterPlaylist(e,t,i,r){const s=this.hls,n=e.data,a=fn(e,i),o=Xs.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,i,o.playlistParsingError,r,t);const{contentSteering:l,levels:h,sessionData:c,sessionKeys:d,startTimeOffset:u,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=Xs.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((e=>!e.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(lr.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new dr({}),bitrate:0,url:""}))}s.trigger(tr.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:c,sessionKeys:d,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,r,s){const n=this.hls,{id:a,level:o,type:l}=i,h=fn(e,i),c=Ji(o)?o:Ji(a)?a:0,d=un(i),u=Xs.parseLevelPlaylist(e.data,h,c,d,0,this.variableList);if(l===nn){const e={attrs:new dr({}),bitrate:0,details:u,name:"",url:h};n.trigger(tr.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=u,this.handlePlaylistLoaded(u,e,t,i,r,s)}handleManifestParsingError(e,t,i,r,s){this.hls.trigger(tr.ERROR,{type:ir.NETWORK_ERROR,details:rr.MANIFEST_PARSING_ERROR,fatal:t.type===nn,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,i=!1,r,s){let n=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===an?n+=`: ${e.level} id: ${e.id}`:e.type!==on&&e.type!==ln||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);lr.warn(`[playlist-loader]: ${n}`);let o=rr.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case nn:o=i?rr.MANIFEST_LOAD_TIMEOUT:rr.MANIFEST_LOAD_ERROR,l=!0;break;case an:o=i?rr.LEVEL_LOAD_TIMEOUT:rr.LEVEL_LOAD_ERROR,l=!1;break;case on:o=i?rr.AUDIO_TRACK_LOAD_TIMEOUT:rr.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ln:o=i?rr.SUBTITLE_TRACK_LOAD_TIMEOUT:rr.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const c={type:ir.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:s};if(r){const i=(null==t?void 0:t.url)||e.url;c.response=qi({url:i,data:void 0},r)}this.hls.trigger(tr.ERROR,c)}handlePlaylistLoaded(e,t,i,r,s,n){const a=this.hls,{type:o,level:l,id:h,groupId:c,deliveryDirectives:d}=r,u=fn(t,r),f=un(r),g="number"==typeof r.level&&f===hn?l:void 0;if(!e.fragments.length){const e=new Error("No Segments found in Playlist");return void a.trigger(tr.ERROR,{type:ir.NETWORK_ERROR,details:rr.LEVEL_EMPTY_ERROR,fatal:!1,url:u,error:e,reason:e.message,response:t,context:r,level:g,parent:f,networkDetails:s,stats:i})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const m=e.playlistParsingError;if(m)a.trigger(tr.ERROR,{type:ir.NETWORK_ERROR,details:rr.LEVEL_PARSING_ERROR,fatal:!1,url:u,error:m,reason:m.message,response:t,context:r,level:g,parent:f,networkDetails:s,stats:i});else switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case nn:case an:a.trigger(tr.LEVEL_LOADED,{details:e,level:g||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:d});break;case on:a.trigger(tr.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:c||"",stats:i,networkDetails:s,deliveryDirectives:d});break;case ln:a.trigger(tr.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:c||"",stats:i,networkDetails:s,deliveryDirectives:d})}}}function mn(e,t){let i;try{i=new Event("addtrack")}catch(e){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function pn(e,t){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){lr.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){lr.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function vn(e){const t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(let t=e.cues.length;t--;)e.removeCue(e.cues[t]);"disabled"===t&&(e.mode=t)}function yn(e,t,i,r){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){const s=function(e,t,i){const r=[],s=function(e,t){if(te[i].endTime)return-1;let r=0,s=i;for(;r<=s;){const n=Math.floor((s+r)/2);if(te[n].startTime&&r-1)for(let n=s,a=e.length;n=t&&s.endTime<=i)r.push(s);else if(s.startTime>i)return r}return r}(e.cues,t,i);for(let t=0;t{const e=Ln();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Rn(e,t){return e.getTime()/1e3-t}class kn{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(vn(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;tAn&&(r=An);r-i<=0&&(r=i+.25);for(let e=0;ee.type===En&&o:"video"===r?e=>e.type===bn&&a:e=>e.type===En&&o||e.type===bn&&a,yn(s,t,i,e)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:r}=this,{dateRanges:s}=t,n=Object.keys(s);if(r){const e=Object.keys(i).filter((e=>!n.includes(e)));for(let t=e.length;t--;){const s=e[t];Object.keys(i[s].cues).forEach((e=>{r.removeCue(i[s].cues[e])})),delete i[s]}}const a=t.fragments[t.fragments.length-1];if(0===n.length||!Ji(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=Ln();for(let e=0;e{if(t!==r.id){const i=s[t];if(i.class===r.class&&i.startDate>r.startDate&&(!e||r.startDatethis.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(null===e)return null;const{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||t;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:n*r);const h=r;return l+Math.min(1*this.stallCount,h)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(null===e||null===t||null===i)return null;const r=i.edge,s=e-t-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}get drift(){const{levelDetails:e}=this;return null===e?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(tr.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(tr.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===rr.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(i=this.levelDetails)&&i.live&&lr.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,s)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(t,Math.max(1,i))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}const Dn=["NONE","TYPE-0","TYPE-1",null];const xn=["SDR","PQ","HLG"];var Cn="",In="YES",Pn="v2";function On(e){const{canSkipUntil:t,canSkipDateRanges:i,age:r}=e;return t&&r!!e)).map((e=>e.substring(0,4))).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Nn(this._audioGroups,e)}hasSubtitleGroup(e){return Nn(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function Nn(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Un(e,t){const i=t.startPTS;if(Ji(i)){let r,s=0;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&(r.duration=s)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration}else t.start=Math.max(e.start-t.duration,0)}function Bn(e,t,i,r,s,n){r-i<=0&&(lr.warn("Fragment should have a positive duration",t),r=i+t.duration,n=s+t.duration);let a=i,o=r;const l=t.startPTS,h=t.endPTS;if(Ji(l)){const e=Math.abs(l-i);Ji(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(i,l),i=Math.min(i,l),s=Math.min(s,t.startDTS),o=Math.min(r,h),r=Math.max(r,h),n=Math.max(n,t.endDTS)}const c=i-t.start;0!==t.start&&(t.start=i),t.duration=r-t.start,t.startPTS=i,t.maxStartPTS=a,t.startDTS=s,t.endPTS=r,t.minEndPTS=o,t.endDTS=n;const d=t.sn;if(!e||de.endSN)return 0;let u;const f=d-e.startSN,g=e.fragments;for(g[f]=t,u=f;u>0;u--)Un(g[u],g[u-1]);for(u=f;u=0;e--){const t=r[e].initSegment;if(t){i=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let s,n=0;if(function(e,t,i){const r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let e=s;e<=n;e++){const s=l[a+e];let n=o[e];r&&!n&&e{e.relurl&&(n=e.cc-r.cc),Ji(e.startPTS)&&Ji(e.endPTS)&&(r.start=r.startPTS=e.startPTS,r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.duration=e.endPTS-e.startPTS,r.duration&&(s=r),t.PTSKnown=t.alignedSliding=!0),r.elementaryStreams=e.elementaryStreams,r.loader=e.loader,r.stats=e.stats,e.initSegment&&(r.initSegment=e.initSegment,i=e.initSegment)})),i){(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach((e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=i)?void 0:t.relurl)||(e.initSegment=i)}))}if(t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some((e=>!e)),t.deltaUpdateFailed){lr.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){const r=Qi({},e);i&&i.forEach((e=>{delete r[e]}));return Object.keys(t).forEach((e=>{const i=new fr(t[e].attr,r[e]);i.isValid?r[e]=i:lr.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),r}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const a=t.fragments;if(n){lr.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?Bn(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):Gn(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const e=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=e),t.driftEndTime=o,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function Gn(e,t){const i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments;i<0||i>=r.length||Kn(t,r[i].start)}function Kn(e,t){if(t){const i=e.fragments;for(let r=e.skippedSegments;r{const{details:i}=e;null!=i&&i.fragments&&i.fragments.forEach((e=>{e.level=t}))}))}function Wn(e){switch(e.details){case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_TIMEOUT:case rr.LEVEL_LOAD_TIMEOUT:case rr.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Yn(e,t){const i=Wn(t);return e.default[(i?"timeout":"error")+"Retry"]}function qn(e,t){const i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function zn(e){return qi(qi({},e),{errorRetry:null,timeoutRetry:null})}function Xn(e,t,i,r){if(!e)return!1;const s=null==r?void 0:r.code,n=t499)}(s)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}const Qn=function(e,t){let i=0,r=e.length-1,s=null,n=null;for(;i<=r;){s=(i+r)/2|0,n=e[s];const a=t(n);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null};function Jn(e,t,i=0,r=0,s=.005){let n=null;if(e){n=t[e.sn-t[0].sn+1]||null;const r=e.endDTS-i;r>0&&r<15e-7&&(i+=15e-7)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===Zn(i,r,n)||function(e,t,i){if(t&&0===t.start&&t.level0){const r=t.tagList.reduce(((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e)),i);return e.start<=r}return!1}(n,e,Math.min(s,r))))return n;const a=Qn(t,Zn.bind(null,i,r));return!a||a===e&&n?n:a}function Zn(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;const r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function ea(e,t,i){const r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}var ta=0,ia=2,ra=3,sa=5,na=0,aa=1,oa=2;class la{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=lr.log.bind(lr,`${t}:`),this.warn=lr.warn.bind(lr,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){const r=null==t?void 0:t.renditionReports;if(r){let s=-1;for(let i=0;i=0&&e>t.partTarget&&(a+=1)}const o=i&&On(i);return new Mn(n,a>=0?a:void 0,o)}}}loadPlaylist(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){const{details:r,stats:s}=t,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;if(r.advancedDateTime=Date.now()-a,r.live||null!=i&&i.live){if(r.reloaded(i),i&&this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),i&&r.fragments.length>0&&$n(i,r),!this.canLoad||!r.live)return;let a,o,l;if(r.canBlockReload&&r.endSN&&r.advanced){const e=this.hls.config.lowLatencyMode,s=r.lastPartSn,n=r.endSN,h=r.lastPartIndex,c=s===n;-1!==h?(o=c?n+1:s,l=c?e?0:h:h+1):o=n+1;const d=r.age,u=d+r.ageHeader;let f=Math.min(u-r.partTarget,1.5*r.targetduration);if(f>0){if(i&&f>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${f} with playlist age: ${r.age}`),f=0;else{const e=Math.floor(f/r.targetduration);if(o+=e,void 0!==l){l+=Math.round(f%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${f} skip sn ${e} to part ${l}`)}r.tuneInGoal=f}if(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l),e||!c)return void this.loadPlaylist(a)}else(r.canBlockReload||r.canSkipUntil)&&(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l));const h=this.hls.mainForwardBufferInfo,c=h?h.end-h.len:0,d=function(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){const r=e.fragments,s=4;if(r.length&&i*s>t){const e=1e3*r[r.length-1].duration;ethis.requestScheduled+d&&(this.requestScheduled=s.loading.start),void 0!==o&&r.canBlockReload?this.requestScheduled=s.loading.first+d-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+dthis.loadPlaylist(a)),u)}else this.clearTimer()}getDeliveryDirectives(e,t,i,r){let s=On(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=Cn),new Mn(i,r,s)}checkRetry(e){const t=e.details,i=Wn(e),r=e.errorAction,{action:s,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(s===sa||!r.resolved&&s===ia);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(i&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=qn(a,n);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return o}}class ha{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class ca{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ha(e),this.fast_=new ha(t),this.defaultTTFB_=r,this.ttfb_=new ha(e)}update(e,t){const{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==e&&(this.slow_=new ha(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new ha(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new ha(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){const i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const da={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},ua={};function fa(e,t,i,r,s,n){const a=e.audioCodec?e.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let c=null;if(null!=a&&a.length)try{c=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce(((e,i)=>{if(i){const r=t.groups[i];if(!r)throw new Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach((t=>{e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(s,8e6))||!!c&&Ji(h)&&Object.keys(c).some((e=>parseInt(e)>h))}function ga(e,t,i){const r=e.videoCodec,s=e.audioCodec;if(!r||!s||!i)return Promise.resolve(da);const n={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},a=e.videoRange;"SDR"!==a&&(n.transferFunction=a.toLowerCase());const o=r.split(",").map((e=>({type:"media-source",video:qi(qi({},n),{},{contentType:Us(e,"video")})})));return s&&e.audioGroups&&e.audioGroups.forEach((e=>{var i;e&&(null==(i=t.groups[e])||i.tracks.forEach((t=>{if(t.groupId===e){const e=t.channels||"",i=parseFloat(e);Ji(i)&&i>2&&o.push.apply(o,s.split(",").map((e=>({type:"media-source",audio:{contentType:Us(e,"audio"),channels:""+i}}))))}})))})),Promise.all(o.map((e=>{const t=function(e){const{audio:t,video:i}=e,r=i||t;if(r){const e=r.contentType.split('"')[1];if(i)return`r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${e}_${Math.ceil(i.bitrate/1e5)}`;if(t)return`c${t.channels}${t.spatialRendering?"s":"n"}_${e}`}return""}(e);return ua[t]||(ua[t]=i.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:o,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:o,decodingInfoResults:[],error:e})))}function ma(e,t){let i=!1,r=[];return e&&(i="SDR"!==e,r=[e]),t&&(r=t.allowedVideoRanges||xn.slice(0),i=void 0!==t.preferHDR?t.preferHDR:function(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),r=i?r.filter((e=>"SDR"!==e)):["SDR"]),{preferHDR:i,allowedVideoRanges:r}}function pa(e,t){lr.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function va(e,t,i){if("attrs"in e){const i=t.indexOf(e);if(-1!==i)return i}for(let r=0;r-1===r.indexOf(e)))}(o,t.characteristics))&&(void 0===i||i(e,t))}function Ta(e,t){const{audioCodec:i,channels:r}=e;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function Ea(e,t,i){for(let r=t;r;r--)if(i(e[r]))return r;for(let r=t+1;r1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var ba="NOT_LOADED",La="APPENDING",wa="PARTIAL",Aa="OK";class Ra{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(tr.BUFFER_APPENDED,this.onBufferAppended,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.on(tr.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.BUFFER_APPENDED,this.onBufferAppended,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.off(tr.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let t=i.length;t--;){const r=i[t];if(!r)break;const s=r.end;if(r.start<=e&&null!==s&&e<=s)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,r=Object.keys(i);for(let s=r.length;s--;){const n=i[r[s]];if((null==n?void 0:n.body.type)===t&&n.buffered){const t=n.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,r){this.timeRanges&&(this.timeRanges[e]=t);const s=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((r=>{const n=this.fragments[r];if(!n)return;if(s>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===i&&this.removeFragment(n.body));const a=n.range[e];a&&a.time.some((e=>{const i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(n.body),i}))}))}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:r}=e;if(!t||"initSegment"===i.sn)return;const s=_a(i),n=this.fragments[s];if(!n||n.buffered&&i.gap)return;const a=!i.relurl;if(Object.keys(t).forEach((e=>{const s=i.elementaryStreams[e];if(!s)return;const o=t[e],l=a||!0===s.partial;n.range[e]=this.getBufferedTimes(i,r,l,o)})),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),ka(n)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(n.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter((t=>t.fragment.sn>=e)))}fragBuffered(e,t){const i=_a(e);let r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,i,r){const s={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e=t&&o<=i){s.time.push({startPTS:Math.max(n,r.start(e)),endPTS:Math.min(a,r.end(e))});break}if(nt){const t=Math.max(n,r.start(e)),i=Math.min(a,r.end(e));i>t&&(s.partial=!0,s.time.push({startPTS:t,endPTS:i}))}else if(a<=t)break}return s}getPartialFragment(e){let t,i,r,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&ka(h)&&(i=h.body.start-a,r=h.body.end+a,e>=i&&e<=r&&(t=Math.min(e-i,r-e),n<=t&&(s=h.body,n=t)))})),s}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||ka(t))}getState(e){const t=_a(e),i=this.fragments[t];return i?i.buffered?ka(i)?wa:Aa:La:ba}isTimeBuffered(e,t,i){let r,s;for(let n=0;n=r&&t<=s)return!0;if(t<=r)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:r}=t;if("initSegment"===i.sn||i.bitrateTest)return;const s=r?null:t,n=_a(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:r,timeRanges:s}=t;if("initSegment"===i.sn)return;const n=i.type;if(r){let e=this.activePartLists[n];e||(this.activePartLists[n]=e=[]),e.push(r)}this.timeRanges=s,Object.keys(s).forEach((e=>{const t=s[e];this.detectEvictedFragments(e,t,n,r)}))}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=_a(e);return!!this.fragments[t]}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,i,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||r&&!o.gap||o.starte&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(e){const t=_a(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const t=e.sn;this.activePartLists[e.type]=i.filter((e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function ka(e){var t,i,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(i=e.range.audio)?void 0:i.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function _a(e){return`${e.type}_${e.level}_${e.sn}`}const Da={length:0,start:()=>0,end:()=>0};class xa{static isBuffered(e,t){try{if(e){const i=xa.getBuffered(e);for(let e=0;e=i.start(e)&&t<=i.end(e))return!0}}catch(e){}return!1}static bufferInfo(e,t,i){try{if(e){const r=xa.getBuffered(e),s=[];let n;for(n=0;nn&&(r[s-1].end=e[t].end):r.push(e[t])}else r.push(e[t])}else r=e;let s,n=0,a=t,o=t;for(let e=0;e=l&&ti.startCC||e&&e.cc{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o($a(e));e.gap=!1}const l=this.loader=e.loader=s?new s(r):new n(r),h=Ba(e),c=zn(r.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Na};e.stats=l.stats,l.load(h,d,{onSuccess:(t,i,r,s)=>{this.resetLoader(e,l);let n=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:s})},onError:(t,r,s,n)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:qi({url:i,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:n}))},onAbort:(t,i,r)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,i,r)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:r,stats:t}))},onProgress:(i,r,s,n)=>{t&&t({frag:e,part:null,payload:s,networkDetails:n})}})}))}loadPart(e,t,i){this.abort();const r=this.config,s=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o($a(e,t));const l=this.loader=e.loader=s?new s(r):new n(r),h=Ba(e,t),c=zn(r.fragLoadPolicy.default),d={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Na};t.stats=l.stats,l.load(h,d,{onSuccess:(r,s,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const h={frag:e,part:t,payload:r.data,networkDetails:o};i(h),a(h)},onError:(i,r,s,n)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:qi({url:h.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:n}))},onAbort:(i,r,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(e,l),o(new Ga({type:ir.NETWORK_ERROR,details:rr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:s,stats:i}))}})}))}updateStatsFromPart(e,t){const i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){const r=Math.round(e.duration/t.duration),n=Math.min(Math.round(i.loaded/s),r),a=(r-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=r.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Ba(e,t=null){const i=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(Ji(s)&&Ji(n)){var a;let t=s,i=n;if("initSegment"===e.sn&&"AES-128"===(null==(a=e.decryptdata)?void 0:a.method)){const e=n-s;e%16&&(i=n+(16-e%16)),0!==s&&(r.resetIV=!0,t=s-16)}r.rangeStart=t,r.rangeEnd=i}return r}function $a(e,t){const i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:ir.MEDIA_ERROR,details:rr.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Ga(r)}class Ga extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Ka{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class Va{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class Ha{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],c=o[2],d=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[i]^16843008*i;r[f]=v<<24|v>>>8,s[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,c[i]=v<<8|v>>>24,d[i]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,r=0;for(;r{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Ka(this.subtle,new Uint8Array(i)).decrypt(e.buffer,t)})).catch((r=>(lr.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i))))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%16;return i!==e.length&&(t=Nr(e,0,i),this.remainderData=Nr(e,i)),t}logOnce(e){this.logEnabled&&(lr.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Wa=function(e){let t="";const i=e.length;for(let r=0;ra.end){const e=n>s;(n{if(this.fragContextChanged(e))return this.warn(`Fragment ${e.sn}${t.part?" p: "+t.part.index:""} of level ${e.level} was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const i=this.state;this.fragContextChanged(e)?(i===Xa||!this.fragCurrent&&i===Za)&&(this.fragmentTracker.removeFragment(e),this.state=qa):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(tr.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state!==Ya&&this.state!==io&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===La){const t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,r?r.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(s))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===wa&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,i=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:i};this.hls.trigger(tr.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((t=>{if(!t||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:i}=this,{payload:r}=t,s=e.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&"AES-128"===s.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer).catch((t=>{throw i.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((r=>{const s=self.performance.now();return i.trigger(tr.FRAG_DECRYPTED,{frag:e,payload:r,stats:{tstart:n,tdecrypt:s}}),t.payload=r,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)})).catch((t=>{this.state!==Ya&&this.state!==io&&(this.warn(t),this.resetFragmentLoading(e))}))}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state=qa,e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var i,r,s,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===hn?"level":"track"} ${e.level} (frag:[${(null!=(i=e.startPTS)?i:NaN).toFixed(3)}-${(null!=(r=e.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?Wa(xa.getBuffered(a)):"(detached)"})`),"initSegment"!==e.sn){var o;if(e.type!==dn){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return void(this.state=qa)}const t=null==(o=this.levels)?void 0:o[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=qa,a&&(!this.loadedmetadata&&e.type==hn&&a.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:r,partsLoaded:s}=e,n=!s||0===s.length||s.some((e=>!e)),a=new Ca(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var s;const n=null==t?void 0:t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${e.level}`),this.state=za,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(tr.KEY_LOADED,e),this.state===za&&(this.state=qa),e})),this.hls.trigger(tr.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){const s=n.partList;if(s&&r){i>e.end&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(s,e,i);if(o>-1){const l=s[o];let h;return this.log(`Loading part sn: ${e.sn} p: ${l.index} cc: ${e.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Xa,h=a?a.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,l,t,r))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,r).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(tr.FRAG_LOADING,{frag:e,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!e.url||this.loadedEndOfParts(s,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),Ji(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Xa;const o=this.config.progressive;let l;return l=o&&a?a.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,r))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,o?r:void 0),a]).then((([e])=>(!o&&e&&r&&r(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(tr.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(e,t,i,r){return new Promise(((s,n)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,r).then((r=>{o[t.index]=r;const n=r.part;this.hls.trigger(tr.FRAG_LOADED,r);const a=Vn(i,e.sn,t.index+1)||Hn(l,e.sn,t.index+1);if(!a)return s({frag:e,part:n,partsLoaded:o});h(a)})).catch(n)};h(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===rr.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(tr.ERROR,t)}else this.hls.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Za)return void(this.fragCurrent||this.state===Ya||this.state===io||(this.state=qa));const{frag:i,part:r,level:s}=t,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n),this.updateLevelTiming(i,r,s,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:r,sn:s,part:n}=e;if(null==t||!t[r])return this.warn(`Levels object was unset while buffering fragment ${s} of level ${r}. The current chunk will not be buffered.`),null;const a=t[r],o=n>-1?Vn(a,s,n):null,l=o?o.fragment:function(e,t,i){if(null==e||!e.details)return null;const r=e.details;let s=r.fragments[t-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===t?s:tn&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return Ji(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:r}}=this,s=xa.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&s.nextStart=i&&(t.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t=hn){const i=this.fragmentTracker.getAppendedFrag(e,hn);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,r=i.length;if(!r)return null;const{config:s}=this,n=i[0].start;let a;if(t.live){const o=s.initialLiveManifestSize;if(rt}getNextFragmentLoopLoading(e,t,i,r,s){const n=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(null===a)return a;if(e=a,n&&e&&!e.gap&&i.nextStart){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r);if(null!==t&&i.len+t.len>=s)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let r=-1,s=!1,n=!0;for(let a=0,o=e.length;a-1&&ii.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!Ji(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;i=i||0;for(let r=0;r=e.startSN&&s<=e.endSN){const n=t[s-e.startSN];i.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=function(e,t){return Qn(e,(e=>e.cct?-1:0))}(t,i.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){const{config:r}=this;let{fragPrevious:s}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=r,h=i.partList,c=!!(r.lowLatencyMode&&null!=h&&h.length&&o);let d;if(c&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),et-l?0:l)}else d=n[n.length-1];if(d){const e=d.sn-i.startSN,t=this.fragmentTracker.getState(d);if((t===Aa||t===wa&&d.gap)&&(s=d),s&&d.sn===s.sn&&(!c||h[0].fragment.sn>d.sn)){if(s&&d.level===s.level){const t=n[e+1];d=d.sn=n-t.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s${e.startSN} prev-sn: ${s?s.sn:"na"} fragments: ${r}`),n}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;if(i ${null==(r=this.fragCurrent)?void 0:r.url}`);const s=t.details===rr.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);const n=t.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===sa&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const r=qn(l,o);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=Qa}else if(l&&n){if(this.resetFragmentErrors(e),!(o.5;r&&this.reduceMaxBufferLength(i.len);const s=!r;return s&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(e){e===cn&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Ya&&(this.state=qa)}afterBufferFlushed(e,t,i){if(!e)return;const r=xa.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===to&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=qa}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){var s;const n=i.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce(((t,s)=>{const a=e.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${o})`),t||!1;const l=r?0:Bn(n,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(tr.LEVEL_PTS_UPDATED,{details:n,level:i,drift:l,type:s,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1)&&null===(null==(s=this.transmuxer)?void 0:s.error)){const t=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===i.fragmentError&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(t.message),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=eo,this.hls.trigger(tr.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class ao{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;return e.length?(i=1===e.length?e[0]:function(e,t){const i=new Uint8Array(t);let r=0;for(let t=0;t0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:En,duration:Number.POSITIVE_INFINITY});s{if(Ji(e))return 90*e;return 9e4*t+(i?9e4*i.baseTime/i.timescale:0)};function co(e,t){return 255===e[t]&&240==(246&e[t+1])}function uo(e,t){return 1&e[t+1]?7:9}function fo(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function go(e,t){return t+1=e.length)return!1;const r=fo(e,t);if(r<=i)return!1;const s=t+r;return s===e.length||go(e,s)}return!1}function po(e,t,i,r,s){if(!e.samplerate){const n=function(e,t,i,r){let s,n,a,o;const l=navigator.userAgent.toLowerCase(),h=r,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[i+2])>>>6);const d=(60&t[i+2])>>>2;if(!(d>c.length-1))return a=(1&t[i+2])<<2,a|=(192&t[i+3])>>>6,lr.log(`manifest codec:${r}, ADTS type:${s}, samplingIndex:${d}`),/firefox/i.test(l)?d>=6?(s=5,o=new Array(4),n=d-3):(s=2,o=new Array(2),n=d):-1!==l.indexOf("android")?(s=2,o=new Array(2),n=d):(s=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&d>=6?n=d-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(d>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(s=2,o=new Array(2)),n=d)),o[0]=s<<3,o[0]|=(14&d)>>1,o[1]|=(1&d)<<7,o[1]|=a<<3,5===s&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:c[d],channelCount:a,codec:"mp4a.40."+s,manifestCodec:h};{const t=new Error(`invalid ADTS sampling index:${d}`);e.emit(tr.ERROR,tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}}(t,i,r,s);if(!n)return;e.config=n.config,e.samplerate=n.samplerate,e.channelCount=n.channelCount,e.codec=n.codec,e.manifestCodec=n.manifestCodec,lr.log(`parsed codec:${e.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function vo(e){return 9216e4/e}function yo(e,t,i,r,s){const n=r+s*vo(e.samplerate),a=function(e,t){const i=uo(e,t);if(t+i<=e.length){const r=fo(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);let o;if(a){const{frameLength:r,headerLength:s}=a,l=s+r,h=Math.max(0,i+l-t.length);h?(o=new Uint8Array(l-s),o.set(t.subarray(i+s,t.length),0)):o=t.subarray(i+s,i+l);const c={unit:o,pts:n};return h||e.samples.push(c),{sample:c,length:l,missing:h}}const l=t.length-i;o=new Uint8Array(l),o.set(t.subarray(i,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let To=null;const Eo=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],So=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],bo=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Lo=[0,1,1,4];function wo(e,t,i,r,s){if(i+24>t.length)return;const n=Ao(t,i);if(n&&i+n.frameLength<=t.length){const a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Ao(e,t){const i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Eo[14*(3===i?3-r:3===r?3:4)+s-1],h=So[3*(3===i?0:2===i?1:2)+n],c=3===o?1:2,d=bo[i][r],u=Lo[r],f=8*d*u,g=Math.floor(d*l/h+a)*u;if(null===To){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);To=e?parseInt(e[1]):0}return!!To&&To<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:c,frameLength:g,samplesPerFrame:f}}}function Ro(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function ko(e,t){return t+1{let i=0,r=5;t+=r;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=e[t];const o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<>l,i=i?i<t.length)return-1;if(11!==t[i]||119!==t[i+1])return-1;const n=t[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>t.length)return-1;const h=t[i+6]>>5;let c=0;2===h?c+=2:(1&h&&1!==h&&(c+=2),4&h&&(c+=2));const d=(t[i+6]<<8|t[i+7])>>12-c&1,u=[2,1,2,3,3,4,4,5][h]+d,f=t[i+5]>>3,g=7&t[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|d<<2|o>>4,o<<4&224]),p=r+s*(1536/a*9e4),v=t.subarray(i,i+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:v,pts:p}),l}class Po{constructor(){this.VideoSample=null}createVideoSample(e,t,i,r){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:r,length:0}}getLastNalUnit(e){var t;let i,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){const e=r.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const i=t.samples,r=i.length;if(!r)return void t.dropped++;{const t=i[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}e.debug.length&&lr.log(e.pts+"/"+e.dts+":"+e.debug)}}class Oo{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&lr.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?i<>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t,i=8,r=8;for(let s=0;s{var n;switch(r.type){case 1:{let t=!1;a=!0;const s=r.data;if(l&&s.length>4){const e=new Oo(s).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var h;if(t)null!=(h=o)&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=t;break}case 5:a=!0,null!=(n=o)&&n.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,Ls(r.data,1,i.pts,t.samples);break;case 7:{var c,d;a=!0,l=!0;const t=r.data,i=new Oo(t).readSPS();if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(c=e.pixelRatio)?void 0:c[0])!==i.pixelRatio[0]||(null==(d=e.pixelRatio)?void 0:d[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t],e.duration=s;const r=t.subarray(1,4);let n="avc1.";for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t="0"+t),n+=t}e.codec=n}break}case 8:a=!0,e.pps=[r.data];break;case 9:a=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+r.type+" ")}if(o&&a){o.units.push(r)}})),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const i=t.byteLength;let r=e.naluState||0;const s=r,n=[];let a,o,l,h=0,c=-1,d=0;for(-1===r&&(c=0,d=31&t[0],r=0,h=1);h=0){const e={data:t.subarray(c,o),type:d};n.push(e)}else{const i=this.getLastNalUnit(e.samples);i&&(s&&h<=4-s&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-s)),o>0&&(i.data=Es(i.data,t.subarray(0,o)),i.state=0))}h=0&&r>=0){const e={data:t.subarray(c,i),type:d,state:r};n.push(e)}if(0===n.length){const i=this.getLastNalUnit(e.samples);i&&(i.data=Es(i.data,t))}return e.naluState=r,n}}class Fo{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ja(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){const r=e[t].unit;if(r.length<=16)return;const s=r.subarray(16,r.length-r.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then((s=>{const n=new Uint8Array(s);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}))}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t);let r=0;for(let t=32;t{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)}))}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();const s=e[t].units;for(;!(i>=s.length);i++){const n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,r,n),this.decrypter.isSync())))return}}}}const No=188;class Uo{constructor(e,t,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.videoParser=new Mo}static probe(e){const t=Uo.syncOffset(e);return t>0&&lr.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),-1!==t}static syncOffset(e){const t=e.length;let i=Math.min(940,t-No)+1,r=0;for(;r1&&(0===n&&a>2||o+No>i))return n}r++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:ss[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Uo.createTrack("video"),this._audioTrack=Uo.createTrack("audio",r),this._id3Track=Uo.createTrack("id3"),this._txtTrack=Uo.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,r=!1){let s;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,c=n.pesData,d=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=Es(this.remainderData,e)).length,this.remainderData=null),y>4>1){if(E=t+5+e[t+4],E===t+No)continue}else E=t+4;switch(y){case h:r&&(c&&(s=Ho(c))&&this.videoParser.parseAVCPES(n,l,s,!1,this._duration),c={data:[],size:0}),c&&(c.data.push(e.subarray(E,t+No)),c.size+=t+No-E);break;case d:if(r){if(f&&(s=Ho(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(E,t+No)),f.size+=t+No-E);break;case u:r&&(g&&(s=Ho(g))&&this.parseID3PES(o,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(E,t+No)),g.size+=t+No-E);break;case 0:r&&(E+=e[E]+1),v=this._pmtId=$o(e,E);break;case v:{r&&(E+=e[E]+1);const s=Go(e,E,this.typeSupported,i,this.observer);h=s.videoPid,h>0&&(n.pid=h,n.segmentCodec=s.segmentVideoCodec),d=s.audioPid,d>0&&(a.pid=d,a.segmentCodec=s.segmentAudioCodec),u=s.id3Pid,u>0&&(o.pid=u),null===m||p||(lr.warn(`MPEG-TS PMT found at ${t} after unknown PID '${m}'. Backtracking to sync byte @${T} to parse all TS packets.`),m=null,t=T-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else E++;E>0&&Ko(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`)),n.pesData=c,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:r,textTrack:s}=e,n=i.pesData,a=t.pesData,o=r.pesData;let l;if(n&&(l=Ho(n))?(this.videoParser.parseAVCPES(i,s,l,!0,this._duration),i.pesData=null):i.pesData=n,a&&(l=Ho(a))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&lr.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=Ho(o))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(e,t,i){const r=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new Fo(this.observer,this.config,t);return this.decrypt(r,s)}decrypt(e,t){return new Promise((i=>{const{audioTrack:r,videoTrack:s}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,(()=>{i(e)})):i(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(()=>{i(e)}))}))}destroy(){this._duration=0}parseAACPES(e,t){let i=0;const r=this.aacOverFlow;let s,n,a,o=t.data;if(r){this.aacOverFlow=null;const t=r.missing,s=r.sample.unit.byteLength;if(-1===t)o=Es(r.sample.unit,o);else{const n=s-t;r.sample.unit.set(o.subarray(0,t),n),e.samples.push(r.sample),i=r.missing}}for(s=i,n=o.length;s0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void lr.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=Qi({},t,{type:this._videoTrack?bn:En,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function Bo(e,t){return((31&e[t+1])<<8)+e[t+2]}function $o(e,t){return(31&e[t+10])<<8|e[t+11]}function Go(e,t,i,r,s){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t0){let r=t+5,s=o;for(;s>2;){if(106===e[r])!0!==i.ac3?lr.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=a,n.segmentAudioCodec="ac3");const t=e[r+1]+2;r+=t,s-=t}}break;case 194:case 135:return Ko(s,new Error("Unsupported EC-3 in M2TS found")),n;case 36:return Ko(s,new Error("Unsupported HEVC in M2TS found")),n}t+=o+5}return n}function Ko(e,t,i){lr.warn(`parsing error: ${t.message}`),e.emit(tr.ERROR,tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function Vo(e){lr.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Ho(e){let t,i,r,s,n,a=0;const o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=Es(o[0],o[1]),o.splice(1,1);t=o[0];if(1===(t[0]<<16)+(t[1]<<8)+t[2]){if(i=(t[4]<<8)+t[5],i&&i>e.size-6)return null;const l=t[7];192&l&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?(n=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,s-n>54e5&&(lr.warn(`${Math.round((s-n)/9e4)}s delta between PTS and DTS, align them`),s=n)):n=s),r=t[8];let h=r+9;if(e.size<=h)return null;e.size-=h;const c=new Uint8Array(e.size);for(let e=0,i=o.length;ei){h-=i;continue}t=t.subarray(h),i-=h,h=0}c.set(t,a),a+=i}return i&&(i-=r+3),{data:c,pts:s,dts:n,len:i}}return null}class jo{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const Wo=Math.pow(2,32)-1;class Yo{static init(){let e;for(e in Yo.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Yo.types)Yo.types.hasOwnProperty(e)&&(Yo.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Yo.HDLR_TYPES={video:t,audio:i};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);Yo.STTS=Yo.STSC=Yo.STCO=s,Yo.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Yo.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Yo.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Yo.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Yo.FTYP=Yo.box(Yo.types.ftyp,n,o,n,a),Yo.DINF=Yo.box(Yo.types.dinf,Yo.box(Yo.types.dref,r))}static box(e,...t){let i=8,r=t.length;const s=r;for(;r--;)i+=t[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(e,4),r=0,i=8;r>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return Yo.box(Yo.types.mdia,Yo.mdhd(e.timescale,e.duration),Yo.hdlr(e.type),Yo.minf(e))}static mfhd(e){return Yo.box(Yo.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?Yo.box(Yo.types.minf,Yo.box(Yo.types.smhd,Yo.SMHD),Yo.DINF,Yo.stbl(e)):Yo.box(Yo.types.minf,Yo.box(Yo.types.vmhd,Yo.VMHD),Yo.DINF,Yo.stbl(e))}static moof(e,t,i){return Yo.box(Yo.types.moof,Yo.mfhd(e),Yo.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=Yo.trak(e[t]);return Yo.box.apply(null,[Yo.types.moov,Yo.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(Yo.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=Yo.trex(e[t]);return Yo.box.apply(null,[Yo.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Wo+1)),r=Math.floor(t%(Wo+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Yo.box(Yo.types.mvhd,s)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let r,s;for(r=0;r>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));for(t=0;t>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));const a=Yo.box(Yo.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,h=e.pixelRatio[0],c=e.pixelRatio[1];return Yo.box(Yo.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Yo.box(Yo.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Yo.box(Yo.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return Yo.box(Yo.types.mp4a,Yo.audioStsd(e),Yo.box(Yo.types.esds,Yo.esds(e)))}static mp3(e){return Yo.box(Yo.types[".mp3"],Yo.audioStsd(e))}static ac3(e){return Yo.box(Yo.types["ac-3"],Yo.audioStsd(e),Yo.box(Yo.types.dac3,e.config))}static stsd(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?Yo.box(Yo.types.stsd,Yo.STSD,Yo.mp3(e)):"ac3"===e.segmentCodec?Yo.box(Yo.types.stsd,Yo.STSD,Yo.ac3(e)):Yo.box(Yo.types.stsd,Yo.STSD,Yo.mp4a(e)):Yo.box(Yo.types.stsd,Yo.STSD,Yo.avc1(e))}static tkhd(e){const t=e.id,i=e.duration*e.timescale,r=e.width,s=e.height,n=Math.floor(i/(Wo+1)),a=Math.floor(i%(Wo+1));return Yo.box(Yo.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,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,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){const i=Yo.sdtp(e),r=e.id,s=Math.floor(t/(Wo+1)),n=Math.floor(t%(Wo+1));return Yo.box(Yo.types.traf,Yo.box(Yo.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),Yo.box(Yo.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n])),Yo.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,Yo.box(Yo.types.trak,Yo.tkhd(e),Yo.mdia(e))}static trex(e){const t=e.id;return Yo.box(Yo.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],r=i.length,s=12+16*r,n=new Uint8Array(s);let a,o,l,h,c,d;for(t+=8+s,n.set(["video"===e.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,d>>>24&255,d>>>16&255,d>>>8&255,255&d],12+16*a);return Yo.box(Yo.types.trun,n)}static initSegment(e){Yo.types||Yo.init();const t=Yo.moov(e);return Es(Yo.FTYP,t)}}Yo.types=void 0,Yo.HDLR_TYPES=void 0,Yo.STTS=void 0,Yo.STSC=void 0,Yo.STCO=void 0,Yo.STSZ=void 0,Yo.VMHD=void 0,Yo.SMHD=void 0,Yo.STSD=void 0,Yo.FTYP=void 0,Yo.DINF=void 0;const qo=9e4;function zo(e,t,i=1,r=!1){const s=e*t*i;return r?Math.round(s):s}function Xo(e,t=!1){return zo(e,1e3,1/qo,t)}let Qo,Jo=null,Zo=null;class el{constructor(e,t,i,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===Jo){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Jo=e?parseInt(e[1]):0}if(null===Zo){const e=navigator.userAgent.match(/Safari\/(\d+)/i);Zo=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){lr.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){lr.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){lr.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e.reduce(((e,i)=>{const r=i.pts-e;return r<-4294967296?(t=!0,tl(e,i.pts)):r>0?e:i.pts}),e[0].pts);return t&&lr.debug("PTS rollover detected"),i}remux(e,t,i,r,s,n,a,o){let l,h,c,d,u,f,g=s,m=s;const p=e.pid>-1,v=t.pid>-1,y=t.samples.length,T=e.samples.length>0,E=a&&y>0||y>1;if((!p||T)&&(!v||E)||this.ISGenerated||a){if(this.ISGenerated){var S,b,L,w;const e=this.videoTrackConfig;!e||t.width===e.width&&t.height===e.height&&(null==(S=t.pixelRatio)?void 0:S[0])===(null==(b=e.pixelRatio)?void 0:b[0])&&(null==(L=t.pixelRatio)?void 0:L[1])===(null==(w=e.pixelRatio)?void 0:w[1])||this.resetInitSegment()}else c=this.generateIS(e,t,s,n);const i=this.isVideoContiguous;let r,a=-1;if(E&&(a=function(e){for(let t=0;t0){lr.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.inputTimeScale,r=m}else-1===a&&(lr.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(T&&E){const i=this.getVideoStartPts(t.samples),r=(tl(e.samples[0].pts,i)-i)/t.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(T){if(e.samplerate||(lr.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,s,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,v||E||o===cn?m:void 0),E){const r=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(lr.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,m,i,r)}}else E&&(l=this.remuxVideo(t,m,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(u=il(i,s,this._initPTS,this._initDTS)),r.samples.length&&(d=rl(r,s,this._initPTS))),{audio:h,video:l,initSegment:c,independent:f,text:d,id3:u}}generateIS(e,t,i,r){const s=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let h,c,d,u=!l||r,f="audio/mp4";if(u&&(h=c=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):Yo.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(d=e.inputTimeScale,l&&d===l.timescale?u=!1:h=c=s[0].pts-Math.round(d*i))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Yo.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(d=t.inputTimeScale,l&&d===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=Math.round(d*i);c=Math.min(c,tl(n[0].dts,e)-t),h=Math.min(h,e-t)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:d},this._initDTS={baseTime:c,timescale:d}):h=d=void 0,{tracks:o,initPTS:h,timescale:d}}remuxVideo(e,t,i,r){const s=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS;let h,c,d=this.nextAvcDts,u=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!i||null===d){const e=t*s,r=n[0].pts-tl(n[0].dts,n[0].pts);Jo&&null!==d&&Math.abs(e-r-d)<15e3?i=!0:d=e-r}const v=l.baseTime*s/l.timescale;for(let e=0;e0?e-1:e].dts&&(p=!0)}p&&n.sort((function(e,t){const i=e.dts-t.dts,r=e.pts-t.pts;return i||r})),h=n[0].dts,c=n[n.length-1].dts;const y=c-h,T=y?Math.round(y/(o-1)):f||e.inputTimeScale/30;if(i){const e=h-d,i=e>T,r=e<-1;if((i||r)&&(i?lr.warn(`AVC: ${Xo(e,!0)} ms (${e}dts) hole between fragments detected at ${t.toFixed(3)}`):lr.warn(`AVC: ${Xo(-e,!0)} ms (${e}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||d>=n[0].pts||Jo)){h=d;const t=n[0].pts-e;if(i)n[0].dts=h,n[0].pts=t;else for(let i=0;it);i++)n[i].dts-=e,n[i].pts-=e;lr.log(`Video: Initial PTS/DTS adjusted: ${Xo(t,!0)}/${Xo(h,!0)}, delta: ${Xo(e,!0)} ms`)}}h=Math.max(0,h);let E=0,S=0,b=h;for(let e=0;e0?t.dts-n[e-1].dts:T;if(l=e>0?t.pts-n[e-1].pts:T,i.stretchShortVideoTrack&&null!==this.nextAudioPts){const e=Math.floor(i.maxBufferHole*s),n=(r?g+r*s:this.nextAudioPts)-t.pts;n>e?(f=n-a,f<0?f=a:R=!0,lr.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const c=Math.round(t.pts-t.dts);k=Math.min(k,f),D=Math.max(D,f),_=Math.min(_,l),x=Math.max(x,l),a.push(new sl(t.key,f,h,c))}if(a.length)if(Jo){if(Jo<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Zo&&x-_0&&(r&&Math.abs(p-m)<9e3||Math.abs(tl(f[0].pts-v,p)-m)<20*l),f.forEach((function(e){e.pts=tl(e.pts-v,p)})),!i||m<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;m=0===s?0:r&&!u?Math.max(0,p):f[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let i=0,r=m;i=t*l&&h<1e4&&u){let t=Math.round(o/l);r=a-t*l,r<0&&(t--,r+=l),0===i&&(this.nextAudioPts=m=r),lr.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(r/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n0))return;S+=g;try{y=new Uint8Array(S)}catch(e){return void this.observer.emit(tr.ERROR,tr.ERROR,{type:ir.MUX_ERROR,details:rr.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!c){new DataView(y.buffer).setUint32(0,S),y.set(Yo.types.mdat,4)}}y.set(s,g);const l=s.byteLength;g+=l,d.push(new sl(!0,o,l,0)),E=n}const L=d.length;if(!L)return;const w=d[d.length-1];this.nextAudioPts=m=E+a*w.duration;const A=c?new Uint8Array(0):Yo.moof(e.sequenceNumber++,T/a,Qi({},e,{samples:d}));e.samples=[];const R=T/n,k=m/n,_={data1:A,data2:y,startPTS:R,endPTS:k,startDTS:R,endDTS:k,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,_}remuxEmptyAudio(e,t,i,r){const s=e.inputTimeScale,n=s/(e.samplerate?e.samplerate:s),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:r.startDTS*s)+l,c=r.endDTS*s+l,d=1024*n,u=Math.ceil((c-h)/d),f=jo.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(lr.warn("[mp4-remuxer]: remux empty Audio"),!f)return void lr.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let e=0;e4294967296;)e+=i;return e}function il(e,t,i,r){const s=e.samples.length;if(!s)return;const n=e.inputTimeScale;for(let a=0;ae.pts-t.pts));const n=e.samples;return e.samples=[],{samples:n}}class sl{constructor(e,t,i,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}function nl(e,t){const i=null==e?void 0:e.codec;if(i&&i.length>4)return i;if(t===mr){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return Vs(i,!1)}const e="mp4a.40.5";return lr.info(`Parsed audio codec "${i}" or audio object type not handled. Using "${e}"`),e}return lr.warn(`Unhandled video codec "${i}"`),"hvc1"===i||"hev1"===i?"hvc1.1.6.L120.90":"av01"===i?"av01.0.04M.08":"avc1.42e01e"}try{Qo=self.performance.now.bind(self.performance)}catch(e){lr.debug("Unable to use Performance API on this environment"),Qo=null==Ar?void 0:Ar.Date.now}const al=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,r){const s=this.videoTrack=oo("video",1),n=this.audioTrack=oo("audio",1),a=this.txtTrack=oo("text",1);if(this.id3Track=oo("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=fs(e);if(o.video){const{id:e,timescale:t,codec:i}=o.video;s.id=e,s.timescale=a.timescale=t,s.codec=i}if(o.audio){const{id:e,timescale:t,codec:i}=o.audio;n.id=e,n.timescale=t,n.codec=i}a.id=ss.text,s.sampleDuration=0,s.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return function(e){const t=e.byteLength;for(let i=0;i8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}(e)}demux(e,t){this.timeOffset=t;let i=e;const r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Es(this.remainderData,e));const t=function(e){const t={valid:null,remainder:null},i=ds(e,["moof"]);if(i.length<2)return t.remainder=e,t;const r=i[i.length-1];return t.valid=Nr(e,0,r.byteOffset-8),t.remainder=Nr(e,r.byteOffset-8),t}(i);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=i;const n=this.extractID3Track(r,t);return s.samples=Ss(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(t,this.timeOffset);return i.samples=Ss(e,t),{videoTrack:t,audioTrack:oo(),id3Track:r,textTrack:oo()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const r=ds(e.samples,["emsg"]);r&&r.forEach((e=>{const r=function(e){const t=e[0];let i="",r="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==ns(e.subarray(h,h+1));)i+=ns(e.subarray(h,h+1)),h+=1;for(i+=ns(e.subarray(h,h+1)),h+=1;"\0"!==ns(e.subarray(h,h+1));)r+=ns(e.subarray(h,h+1)),h+=1;r+=ns(e.subarray(h,h+1)),h+=1,s=os(e,12),n=os(e,16),o=os(e,20),l=os(e,24),h=28}else if(1===t){h+=4,s=os(e,h),h+=4;const t=os(e,h);h+=4;const n=os(e,h);for(h+=4,a=2**32*t+n,Zi(a)||(a=Number.MAX_SAFE_INTEGER,lr.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=os(e,h),h+=4,l=os(e,h),h+=4;"\0"!==ns(e.subarray(h,h+1));)i+=ns(e.subarray(h,h+1)),h+=1;for(i+=ns(e.subarray(h,h+1)),h+=1;"\0"!==ns(e.subarray(h,h+1));)r+=ns(e.subarray(h,h+1)),h+=1;r+=ns(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(Do.test(r.schemeIdUri)){const e=Ji(r.presentationTime)?r.presentationTime/r.timeScale:t+r.presentationTimeDelta/r.timeScale;let s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const n=r.payload;i.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:bn,duration:s})}}))}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(function(e,t){if(!e||!t)return e;const i=t.keyId;i&&t.isCommonEncryption&&ds(e,["moov","trak"]).forEach((e=>{const t=ds(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=ds(t,["enca"]);const s=r.length>0;s||(r=ds(t,["encv"])),r.forEach((e=>{ds(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=ys(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(lr.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${ts(e)} -> ${ts(i)}`),t.set(i,8))}}))}))}));return e}(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=fs(e);r.audio&&(t=nl(r.audio,mr)),r.video&&(i=nl(r.video,pr));const s={};r.audio&&r.video?s.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:r.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?s.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:lr.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,i,r,s,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const c={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};Ji(h)||(h=this.lastEndTime=s||0);const d=t.samples;if(null==d||!d.length)return c;const u={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return lr.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(e,t){let i=0,r=0,s=0;const n=ds(e,["moof","traf"]);for(let e=0;ee+t.info.duration||0),0);i=Math.max(i,e+n.earliestPresentationTime/n.timescale),r=i-t}}if(r&&Ji(r))return r}return r||s}(d,f),m=function(e,t){return ds(t,["moof","traf"]).reduce(((t,i)=>{const r=ds(i,["tfdt"])[0],s=r[0],n=ds(i,["tfhd"]).reduce(((t,i)=>{const n=os(i,4),a=e[n];if(a){let e=os(r,4);if(1===s){if(e===is)return lr.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=is+1,e+=os(r,8)}const i=e/(a.timescale||9e4);if(Ji(i)&&(null===t||is}(l,p,s,g)||u.timescale!==l.timescale&&n)&&(u.initPTS=p-s,l&&1===l.timescale&&lr.warn("Adjusting initPTS by "+(u.initPTS-l.baseTime)),this.initPTS=l={baseTime:u.initPTS,timescale:1});const v=e?p-l.baseTime/l.timescale:h,y=v+g;!function(e,t,i){ds(t,["moof","traf"]).forEach((t=>{ds(t,["tfhd"]).forEach((r=>{const s=os(r,4),n=e[s];if(!n)return;const a=n.timescale||9e4;ds(t,["tfdt"]).forEach((e=>{const t=e[0],r=i*a;if(r){let i=os(e,4);if(0===t)i-=r,i=Math.max(i,0),cs(e,4,i);else{i*=Math.pow(2,32),i+=os(e,8),i-=r,i=Math.max(i,0);const t=Math.floor(i/(is+1)),s=Math.floor(i%(is+1));cs(e,4,t),cs(e,8,s)}}}))}))}))}(f,d,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(lr.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const T=!!f.audio,E=!!f.video;let S="";T&&(S+="audio"),E&&(S+="video");const b={data1:d,startPTS:v,startDTS:v,endPTS:y,endDTS:y,type:S,hasAudio:T,hasVideo:E,nb:1,dropped:0};return c.audio="audio"===b.type?b:void 0,c.video="audio"!==b.type?b:void 0,c.initSegment=u,c.id3=il(i,s,l,l),r.samples.length&&(c.text=rl(r,s,l)),c}}},{demux:Uo,remux:el},{demux:class extends lo{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=$r(e,0);let i=(null==t?void 0:t.length)||0;if(_o(e,i))return!1;for(let t=e.length;i0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(i=t);return i}(n,t);if(T&&"AES-128"===T.method){const e=this.getDecrypter();if(!e.isSync())return this.decryptionPromise=e.webCryptoDecrypt(n,T.key.buffer,T.iv.buffer).then((e=>{const t=this.push(e,null,i);return this.decryptionPromise=null,t})),this.decryptionPromise;{let t=e.softwareDecrypt(n,T.key.buffer,T.iv.buffer);if(i.part>-1&&(t=e.flush()),!t)return s.executeEnd=Qo(),ll(i);n=new Uint8Array(t)}}const E=this.needsProbing(h,c);if(E){const e=this.configureTransmuxer(n);if(e)return lr.warn(`[transmuxer] ${e.message}`),this.observer.emit(tr.ERROR,tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=Qo(),ll(i)}(h||c||f||E)&&this.resetInitSegment(y,g,m,v,t),(h||f||E)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,T,u,d,i),b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,s.executeEnd=Qo(),S}flush(e){const t=e.transmuxing;t.executeStart=Qo();const{decrypter:i,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));const n=[],{timeOffset:a}=r;if(i){const t=i.flush();t&&n.push(this.push(t,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return t.executeEnd=Qo(),[ll(e)];const h=o.flush(a);return hl(h)?h.then((t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,h,e),n)}flushRemux(e,t,i){const{audioTrack:r,videoTrack:s,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;lr.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const h=this.remuxer.remux(r,s,n,a,l,o,!0,this.id);e.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=Qo()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,s){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,i,r),a.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,s){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s),n}transmuxUnencrypted(e,t,i,r){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,s){return this.demuxer.demuxSampleAes(e,t,i).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,this.id),chunkMeta:s})))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:r,vendor:s}=this;let n;for(let t=0,i=al.length;t({remuxResult:{},chunkMeta:e});function hl(e){return"then"in e&&e.then instanceof Function}class cl{constructor(e,t,i,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}}class dl{constructor(e,t,i,r,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=n}}var ul={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function n(e,t,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new s(r,n||e,a),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s{(t=t||{}).frag=this.frag,t.id=this.id,e===tr.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new fl,this.observer.on(tr.FRAG_DECRYPTED,n),this.observer.on(tr.ERROR,n);const a=Os(s.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&"undefined"!=typeof Worker){if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(lr.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){const t=new self.URL(e,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}(s.workerPath)):(lr.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e);return{worker:new self.Worker(t),objectURL:t}}()),this.onwmsg=e=>this.onWorkerMessage(e);const{worker:e}=this.workerContext;e.addEventListener("message",this.onwmsg),e.onerror=e=>{const i=new Error(`${e.message} (${e.filename}:${e.lineno})`);s.enableWorker=!1,lr.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:i})},e.postMessage({cmd:"init",typeSupported:o,vendor:"",id:t,config:JSON.stringify(s)})}catch(e){lr.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new ol(this.observer,o,s,"",t)}return}}this.transmuxer=new ol(this.observer,o,s,"",t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,r,s,n,a,o,l,h){var c,d;l.transmuxing.start=self.performance.now();const{transmuxer:u}=this,f=n?n.start:s.start,g=s.decryptdata,m=this.frag,p=!(m&&s.cc===m.cc),v=!(m&&l.level===m.level),y=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,E=0===y&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!v&&(1===y||0===y&&(1===T||E&&T<=0)),b=self.performance.now();(v||y||0===s.stats.parsing.start)&&(s.stats.parsing.start=b),!n||!T&&S||(n.stats.parsing.start=b);const L=!(m&&(null==(c=s.initSegment)?void 0:c.url)===(null==(d=m.initSegment)?void 0:d.url)),w=new dl(p,S,o,v,f,L);if(!S||p||L){lr.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${p}\n trackSwitch: ${v}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${L}`);const e=new cl(i,r,t,a,h);this.configureTransmuxer(e)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:l,state:w},e instanceof ArrayBuffer?[e]:[]);else if(u){const t=u.push(e,g,l,w);hl(t)?(u.async=!0,t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}))):(u.async=!1,this.handleTransmuxComplete(t))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);hl(i)||t.async?(hl(i)||(i=Promise.resolve(i)),i.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}))):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}onWorkerMessage(e){const t=e.data;if(null==t||!t.event)return void lr.warn("worker message received with no "+(t?"event name":"data"));const i=this.hls;if(this.hls)switch(t.event){case"init":{var r;const e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":lr[t.data.logType]&&lr[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data)}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function ml(e,t){if(e.length!==t.length)return!1;for(let i=0;ie[i]!==t[i]))}function vl(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class yl{constructor(e){this.buffered=void 0;const t=(t,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}class Tl{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,i){const r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const i=new Promise((e=>{t=e})),r={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,e),i}executeNext(e){const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(t){lr.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${t}`),i.onError(t);const r=this.buffers[e];null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const El=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function Sl(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))} +/** + * + * This code was ported from the dash.js project at: + * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js + * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2 + * + * The original copyright appears below: + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and contributor + * rights, including patent rights, and no such rights are granted under this license. + * + * Copyright (c) 2015-2016, DASH Industry Forum. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * 2. Neither the name of Dash Industry Forum nor the names of its + * contributors may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +const bl={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Ll=e=>String.fromCharCode(bl[e]||e),wl=15,Al=100,Rl={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},kl={17:2,18:4,21:6,22:8,23:10,19:13,20:15},_l={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Dl={25:2,26:4,29:6,30:8,31:10,27:13,28:15},xl=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Cl{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i="function"==typeof t?t():t;lr.log(`${this.time} [${e}] ${i}`)}}}const Il=function(e){const t=[];for(let i=0;iAl&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Al)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e=144&&this.backSpace();const t=Ll(e);this.pos>=Al?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t"pacData = "+JSON.stringify(e)));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+JSON.stringify(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",r=-1;for(let i=0;i0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class Nl{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Fl(i),this.nonDisplayedMemory=new Fl(i),this.lastOutputScreen=new Fl(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;tt+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Ul{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new Cl;this.channels=[null,new Nl(e,t,r),new Nl(e+1,i,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e"["+Il([t[e],t[e+1]])+"] -> ("+Il([i,r])+")"));const a=this.cmdHistory;if(i>=16&&i<=31){if($l(i,r,a)){Bl(null,null,a),this.logger.log(3,(()=>"Repeated command ("+Il([i,r])+") is dropped"));continue}Bl(i,r,this.cmdHistory),s=this.parseCmd(i,r),s||(s=this.parseMidrow(i,r)),s||(s=this.parsePAC(i,r)),s||(s=this.parseBackgroundAttributes(i,r))}else Bl(null,null,a);if(!s&&(n=this.parseChars(i,r),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}s||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+Il([i,r])+" orig: "+Il([t[e],t[e+1]])))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;const i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if(i=17===e?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(()=>"MIDROW ("+Il([e,t])+")")),!0)}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const r=e<=23?1:2;i=t>=64&&t<=95?1===r?Rl[e]:_l[e]:1===r?kl[e]:Dl[e];const s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)}interpretPAC(e,t){let i;const r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(e,t){let i,r=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,(()=>"Special char '"+Ll(e)+"' in channel "+i)),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);return r&&this.logger.log(3,(()=>"Char codes = "+Il(r).join(","))),r}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let i;const r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=xl[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(r),!0}reset(){for(let e=0;ee)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Kl=function(){if(null!=Ar&&Ar.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){return i(t,e)}function s(e,...t){let i=1;for(;i100)throw new Error("Position must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return E},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return b},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");b=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class Vl{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Hl(e){function t(e,t,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}const i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class jl{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r=0&&i<=100)return this.set(e,i),!0}return!1}}function Wl(e,t,i,r){const s=r?e.split(r):[e];for(const e in s){if("string"!=typeof s[e])continue;const r=s[e].split(i);if(2!==r.length)continue;t(r[0],r[1])}}const Yl=new Kl(0,0,""),ql="middle"===Yl.align?"middle":"center";function zl(e,t,i){const r=e;function s(){const t=Hl(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=s(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),n(),t.endTime=s(),n(),function(e,t){const r=new jl;Wl(e,(function(e,t){let s;switch(e){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===t){r.set(e,i[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",ql,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",ql,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",ql,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===Yl.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",ql);let n=r.get("position","auto");"auto"===n&&50===Yl.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function Xl(e){return e.replace(//gi,"\n")}class Ql{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Vl,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function i(){let e=t.buffer,i=0;for(e=Xl(e);i>>0).toString()};function th(e,t,i){return eh(e.toString())+eh(t.toString())+eh(i)}function ih(e,t,i,r,s,n,a){const o=new Ql,l=Jr(new Uint8Array(e)).trim().replace(Jl,"\n").split("\n"),h=[],c=t?function(e,t=1){return zo(e,qo,1/t)}(t.baseTime,t.timescale):0;let d,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(e){const n=i[r];let a=i.ccOffset;const o=(f-c)/9e4;if(null!=n&&n.new&&(void 0!==g?a=i.ccOffset=n.start:function(e,t,i){let r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;e.ccOffset+=r.start-s.start,r.new=!1,r=s,s=e[r.prevCC]}e.presentationOffset=i}(i,r,o)),o){if(!t)return void(d=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=e.endTime-e.startTime,u=tl(9e4*(e.startTime+a-g),9e4*s)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=th(e.startTime,e.endTime,m)),e.endTime>0&&h.push(e)},o.onparsingerror=function(e){d=e},o.onflush=function(){d?a(d):n(h)},l.forEach((e=>{if(m){if(Zl(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((e=>{Zl(e,"LOCAL:")?u=e.slice(6):Zl(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{g=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(Ji(t)&&Ji(i)&&Ji(r)&&Ji(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*r,t+=36e5*s,t}(u)/1e3}catch(e){d=e}return}""===e&&(m=!1)}o.parse(e+"\n")})),o.flush()}const rh="stpp.ttml.im1t",sh=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,nh=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ah={left:"start",center:"center",right:"end",start:"start",end:"end"};function oh(e,t,i,r){const s=ds(new Uint8Array(e),["mdat"]);if(0===s.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=s.map((e=>Jr(e))),a=function(e,t,i=1,r=!1){return zo(e,t,1/i,r)}(t.baseTime,1,t.timescale);try{n.forEach((e=>i(function(e,t){const i=(new DOMParser).parseFromString(e,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(s).reduce(((e,t)=>(e[t]=r.getAttribute(`ttp:${t}`)||s[t],e)),{}),a="preserve"!==r.getAttribute("xml:space"),o=hh(lh(r,"styling","style")),l=hh(lh(r,"layout","region")),h=lh(r,"body","[begin]");return[].map.call(h,(e=>{const i=ch(e,a);if(!i||!e.hasAttribute("begin"))return null;const r=fh(e.getAttribute("begin"),n),s=fh(e.getAttribute("dur"),n);let h=fh(e.getAttribute("end"),n);if(null===r)throw uh(e);if(null===h){if(null===s)throw uh(e);h=r+s}const c=new Kl(r-t,h-t,i);c.id=th(c.startTime,c.endTime,c.text);const d=function(e,t,i){const r="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(s=i[a]);return n.reduce(((i,n)=>{const a=dh(t,r,n)||dh(e,r,n)||dh(s,r,n);return a&&(i[n]=a),i}),{})}(l[e.getAttribute("region")],o[e.getAttribute("style")],o),{textAlign:u}=d;if(u){const e=ah[u];e&&(c.lineAlign=e),c.align=u}return Qi(c,d),c})).filter((e=>null!==e))}(e,a))))}catch(e){r(e)}}function lh(e,t,i){const r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function hh(e){return e.reduce(((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function ch(e,t){return[].slice.call(e.childNodes).reduce(((e,i,r)=>{var s;return"br"===i.nodeName&&r?e+"\n":null!=(s=i.childNodes)&&s.length?ch(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function dh(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function uh(e){return new Error(`Could not parse ttml timestamp ${e}`)}function fh(e,t){if(!e)return null;let i=Hl(e);return null===i&&(sh.test(e)?i=function(e,t){const i=sh.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}(e,t):nh.test(e)&&(i=function(e,t){const i=nh.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}function gh(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function mh(e,t){return!!e&&e.kind===gh(t)&&vl(t,e)}class ph{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(tr.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(tr.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&Ji(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&lr.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter(((t,i)=>this.isLevelAllowed(t)&&i<=e));return this.clientRect=null,ph.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return e}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,i){if(null==e||!e.length)return-1;let r=e.length-1;const s=Math.max(t,i);for(let t=0;t=s||i.height>=s)&&(n=i,!(a=e[t+1])||n.width!==a.width||n.height!==a.height)){r=t;break}}var n,a;return r}}const vh="[eme]";class yh{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=yh.CDMCleanupPromise?[yh.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=lr.debug.bind(lr,vh),this.log=lr.log.bind(lr,vh),this.warn=lr.warn.bind(lr,vh),this.error=lr.error.bind(lr,vh),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(tr.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(tr.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===Rr.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,r=t.map((e=>e.audioCodec)).filter(i),s=t.map((e=>e.videoCodec)).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((t,i)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,r,s).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?n(e):i(t instanceof Th?t:new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};n(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Mr&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){const r=function(e,t,i,r){let s;switch(e){case Rr.FAIRPLAY:s=["cenc","sinf"];break;case Rr.WIDEVINE:case Rr.PLAYREADY:s=["cenc"];break;case Rr.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs="${e}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:i.map((e=>({contentType:`video/mp4; codecs="${e}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}(s,t,i,r)}(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let n=null==s?void 0:s.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),n=this.requestMediaKeySystemAccess(e,r);const t=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),n.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const r=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=i.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),r.then((i=>i?this.setMediaKeysServerCertificate(t,e,i):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return n.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${ts(e.keyId||[])}`);const r=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return ts(e.keyId)}updateKeySession(e,t){var i;const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${ts((null==(i=e.decryptdata)?void 0:i.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),r.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,i)=>{const r=Or(this.config),s=e.map(Cr).filter((e=>!!e&&-1!==r.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{const r=Pr(e);r?t(r):i(new Error(`Unable to find format for key-system "${e}"`))})).catch(i)}))}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[i];return s||(s=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then((({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then((()=>{this.throwIfDestroyed();const e=this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:t});return this.generateRequestWithPreferredKeySession(e,"cenc",t.pssh,"playlist-key")}))))),s.catch((e=>this.handleError(e)))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Th?this.hls.trigger(tr.ERROR,e.data):this.hls.trigger(tr.ERROR,{type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const t=Cr(e.keyFormat),i=t?[t]:Or(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Or(this.config)),0===e.length)throw new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),null===i)return;let r,s;if("sinf"===t&&this.config.drmSystems[Rr.FAIRPLAY]){const e=ns(new Uint8Array(i));try{const t=br(JSON.parse(e).sinf),i=ys(new Uint8Array(t));if(!i)return;r=i.subarray(8,24),s=Rr.FAIRPLAY}catch(e){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const e=function(e){if(!(e instanceof ArrayBuffer)||e.byteLength<32)return null;const t={version:0,systemId:"",kids:null,data:null},i=new DataView(e),r=i.getUint32(0);if(e.byteLength!==r&&r>44)return null;if(1886614376!==i.getUint32(4))return null;if(t.version=i.getUint32(8)>>>24,t.version>1)return null;t.systemId=ts(new Uint8Array(e,12,16));const s=i.getUint32(28);if(0===t.version){if(r-32this.generateRequestWithPreferredKeySession(s,t,i,"encrypted-event-key-match")));break}}l||(l=a[n]=this.getKeySystemSelectionPromise([s]).then((({keySystem:e,mediaKeys:s})=>{var a;this.throwIfDestroyed();const o=new ks("ISO-23001-7",n,null!=(a=Pr(e))?a:"");return o.pssh=new Uint8Array(i),o.keyId=r,this.attemptSetMediaKeys(e,s).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:e,mediaKeys:s});return this.generateRequestWithPreferredKeySession(r,t,i,"encrypted-event-no-match")}))}))),l.catch((e=>this.handleError(e)))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(i).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===i.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,i,r){var s,n;const a=null==(s=this.config.drmSystems)||null==(n=s[e.keySystem])?void 0:n.generateRequest;if(a)try{const r=a.call(this.hls,t,i,e);if(!r)throw new Error("Invalid response from configured generateRequest filter");t=r.initDataType,i=e.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${t} length: ${i?i.byteLength:null})`);const h=new fl,c=e._onmessage=t=>{const i=e.mediaKeysSession;if(!i)return void h.emit("error",new Error("invalid state"));const{messageType:r,message:s}=t;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,s).catch((e=>{this.handleError(e),h.emit("error",e)})):"license-release"===r?e.keySystem===Rr.FAIRPLAY&&(this.updateKeySession(e,wr("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${r}"`)},d=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const i=e.keyStatus;h.emit("keyStatus",i),"expired"===i&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",c),e.mediaKeysSession.addEventListener("keystatuseschange",d);const u=new Promise(((e,t)=>{h.on("error",t),h.on("keyStatus",(i=>{i.startsWith("usable")?e():"output-restricted"===i?t(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)}))}));return e.mediaKeysSession.generateRequest(t,i).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>u)).catch((t=>{throw h.removeAllListeners(),this.removeSession(e),t})).then((()=>(h.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${ts("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${ts(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise(((s,n)=>{const a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,r)=>{s(e.data)},onError:(t,i,s,o)=>{n(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:qi({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,s)=>{n(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,i)=>{n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise(((r,s)=>{e.setServerCertificate(i).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==i?void 0:i.byteLength}) on "${t}"`),r(e)})).catch((e=>{s(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let t;for(let i=0,r=s.length;i in key message");return wr(atob(l))}setupLicenseXHR(e,t,i,r){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,i,r)})).catch((n=>{if(!i.decryptdata)throw n;return e.open("POST",t,!0),s.call(this.hls,e,t,i,r)})).then((i=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:i||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise(((r,s)=>{const n=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,a,n,e)}catch(e){this.error(e)}r(t)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new Th({type:ir.KEY_SYSTEM_ERROR,details:rr.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then((({xhr:t,licenseChallenge:i})=>{e.keySystem==Rr.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},ks.clearKeyUriToKeyIdMap();const i=t.length;yh.CDMCleanupPromise=Promise.all(t.map((e=>this.removeSession(e))).concat(null==e?void 0:e.setMediaKeys(null).catch((e=>{this.log(`Could not clear media keys: ${e}`)})))).then((()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)})).catch((e=>{this.log(`Could not close sessions and clear media keys: ${e}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch((e=>{this.log(`Could not remove session: ${e}`)})).then((()=>t.close())).catch((e=>{this.log(`Could not close session: ${e}`)}))}}}yh.CDMCleanupPromise=void 0;class Th extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var Eh,Sh,bh;!function(e){e.MANIFEST="m",e.AUDIO="a",e.VIDEO="v",e.MUXED="av",e.INIT="i",e.CAPTION="c",e.TIMED_TEXT="tt",e.KEY="k",e.OTHER="o"}(Eh||(Eh={})),function(e){e.DASH="d",e.HLS="h",e.SMOOTH="s",e.OTHER="o"}(Sh||(Sh={})),function(e){e.OBJECT="CMCD-Object",e.REQUEST="CMCD-Request",e.SESSION="CMCD-Session",e.STATUS="CMCD-Status"}(bh||(bh={}));const Lh={[bh.OBJECT]:["br","d","ot","tb"],[bh.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[bh.SESSION]:["cid","pr","sf","sid","st","v"],[bh.STATUS]:["bs","rtp"]};class wh{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map((e=>e instanceof wh?e:new wh(e)))),this.value=e,this.params=t}}class Ah{constructor(e){this.description=void 0,this.description=e}}const Rh="Dict";function kh(e,t,i,r){return new Error(`failed to ${e} "${s=t,Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":"object"==typeof s?JSON.stringify(s):String(s)}" as ${i}`,{cause:r});var s}const _h="Bare Item",Dh="Boolean",xh="Byte Sequence",Ch="Decimal",Ih="Integer";const Ph=/[\x00-\x1f\x7f]+/,Oh="Token",Mh="Key";function Fh(e,t,i){return kh("serialize",e,t,i)}function Nh(e){if(!1===ArrayBuffer.isView(e))throw Fh(e,xh);return`:${t=e,btoa(String.fromCharCode(...t))}:`;var t}function Uh(e){if(function(e){return e<-999999999999999||99999999999999912)throw Fh(e,Ch);const i=t.toString();return i.includes(".")?i:`${i}.0`}const Gh="String";function Kh(e){const t=(i=e).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Fh(t,Oh);return t}function Vh(e){switch(typeof e){case"number":if(!Ji(e))throw Fh(e,_h);return Number.isInteger(e)?Uh(e):$h(e);case"string":return function(e){if(Ph.test(e))throw Fh(e,Gh);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return Kh(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Fh(e,Dh);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${Uh(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return Nh(e);if(e instanceof Ah)return Kh(e);default:throw Fh(e,_h)}}function Hh(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Fh(e,Mh);return e}function jh(e){return null==e?"":Object.entries(e).map((([e,t])=>!0===t?`;${Hh(e)}`:`;${Hh(e)}=${Vh(t)}`)).join("")}function Wh(e){return e instanceof wh?`${Vh(e.value)}${jh(e.params)}`:Vh(e)}function Yh(e,t={whitespace:!0}){if("object"!=typeof e)throw Fh(e,Rh);const i=e instanceof Map?e.entries():Object.entries(e),r=null!=t&&t.whitespace?" ":"";return Array.from(i).map((([e,t])=>{t instanceof wh==!1&&(t=new wh(t));let i=Hh(e);var r;return!0===t.value?i+=jh(t.params):(i+="=",Array.isArray(t.value)?i+=`(${(r=t).value.map(Wh).join(" ")})${jh(r.params)}`:i+=Wh(t)),i})).join(`,${r}`)}const qh=e=>"ot"===e||"sf"===e||"st"===e,zh=e=>"number"==typeof e?Ji(e):null!=e&&""!==e&&!1!==e;const Xh=e=>Math.round(e),Qh=e=>100*Xh(e/100),Jh={br:Xh,d:Xh,bl:Qh,dl:Qh,mtp:Qh,nor:(e,t)=>(null!=t&&t.baseUrl&&(e=function(e,t){const i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;const s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}(e,t.baseUrl)),encodeURIComponent(e)),rtp:Qh,tb:Xh};function Zh(e,t={}){return e?function(e,t){return Yh(e,t)}(function(e,t){const i={};if(null==e||"object"!=typeof e)return i;const r=Object.keys(e).sort(),s=Qi({},Jh,null==t?void 0:t.formatters),n=null==t?void 0:t.filter;return r.forEach((r=>{if(null!=n&&n(r))return;let a=e[r];const o=s[r];o&&(a=o(a,t)),"v"===r&&1===a||"pr"==r&&1===a||zh(a)&&(qh(r)&&"string"==typeof a&&(a=new Ah(a)),i[r]=a)})),i}(e,t),Qi({whitespace:!1},t)):""}function ec(e,t,i){return Qi(e,function(e,t={}){if(!e)return{};const i=Object.entries(e),r=Object.entries(Lh).concat(Object.entries((null==t?void 0:t.customHeaderMap)||{})),s=i.reduce(((e,t)=>{var i;const[s,n]=t,a=(null==(i=r.find((e=>e[1].includes(s))))?void 0:i[0])||bh.REQUEST;return null!=e[a]||(e[a]={}),e[a][s]=n,e}),{});return Object.entries(s).reduce(((e,[i,r])=>(e[i]=Zh(r,t),e)),{})}(t,i))}const tc="CMCD";const ic=/CMCD=[^&#]+/;function rc(e,t,i){const r=function(e,t={}){if(!e)return"";const i=Zh(e,t);return`${tc}=${encodeURIComponent(i)}`}(t,i);if(!r)return e;if(ic.test(e))return e.replace(ic,r);const s=e.includes("?")?"&":"?";return`${e}${s}${r}`}function sc(e,t,i,r){e&&Object.keys(t).forEach((s=>{const n=e.filter((e=>e.groupId===s)).map((e=>{const n=Qi({},e);return n.details=void 0,n.attrs=new dr(n.attrs),n.url=n.attrs.URI=nc(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=t[s],n.attrs["PATHWAY-ID"]=r,n}));e.push(...n)}))}function nc(e,t,i,r){const{HOST:s,PARAMS:n,[i]:a}=r;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach((e=>{e&&l.searchParams.set(e,n[e])})),l.href}const ac=/^age:\s*[\d.]+\s*$/im;class oc{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new gr,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return s(i,t.url)})).catch((e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),s(i,t.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)})).catch((e=>{this.callbacks.onError({code:i.status,text:e.message},t,i,r)})):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&Ji(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,n="text"!==t.responseType;if(r>=200&&r<300&&(n&&t.response||null!==t.responseText)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const s=n?t.response:t.responseText,a="arraybuffer"===t.responseType?s.byteLength:s.length;if(i.loaded=i.total=a,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(i,e,s,t),!this.callbacks)return;const l={url:t.responseURL,data:s,code:r};this.callbacks.onSuccess(l,i,e,t)}else{const n=s.loadPolicy.errorRetry;Xn(n,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(n):(lr.error(`${r} while loading ${e.url}`),this.callbacks.onError({code:r,text:t.statusText},e,t,i))}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Xn(e,this.stats.retry,!0))this.retry(e);else{var t;lr.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=qn(e,i.retry),i.retry++,lr.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&ac.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const lc=/(\d+)-(\d+)\/(\d+)/;class hc{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||cc,this.controller=new self.AbortController,this.stats=new gr}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const s=function(e,t){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Qi({},e.headers))};e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1));return i}(e,this.controller.signal),n=i.onProgress,a="arraybuffer"===e.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=l&&Ji(l)?l:h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,e,this.response)}),t.timeout),self.fetch(this.request).then((s=>{this.response=this.loader=s;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,e,this.response)}),h-(o-r.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new dc(t||"fetch, bad network response",e,s)}return r.loading.first=o,r.total=function(e){const t=e.get("Content-Range");if(t){const e=function(e){const t=lc.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Ji(e))return e}const i=e.get("Content-Length");if(i)return parseInt(i)}(s.headers)||r.total,n&&Ji(t.highWaterMark)?this.loadProgressively(s,r,e,t.highWaterMark,n):a?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=s[o];l&&(r.loaded=r.total=l);const h={url:a.url,data:s,code:a.status};n&&!Ji(t.highWaterMark)&&n(r,e,s,a),i.onSuccess(h,r,e,a)})).catch((t=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const s=t&&t.code||0,n=t?t.message:null;i.onError({code:s,text:n},e,t?t.details:null,r)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,s){const n=new ao,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&s(t,i,n.flush(),e),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return t.loaded+=h,h=r&&s(t,i,n.flush(),e)):s(t,i,l,e),o()})).catch((()=>Promise.reject()));return o()}}function cc(e,t){return new self.Request(e.url,t)}class dc extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const uc=/\s/,fc={newCue(e,t,i,r){const s=[];let n,a,o,l,h;const c=self.VTTCue||self.TextTrackCue;for(let u=0;u=16?l--:l++;const r=Xl(h.trim()),f=th(t,i,r);null!=e&&null!=(d=e.cues)&&d.getCueById(f)||(a=new c(t,i,r),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return e&&s.length&&(s.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),s.forEach((t=>pn(e,t)))),s}},gc=qi(qi({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:oc,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:e,partCurrent:t,hls:i}=this,{autoLevelEnabled:r,media:s}=i;if(!e||!s)return;const n=performance.now(),a=t?t.stats:e.stats,o=t?t.duration:e.duration,l=n-a.loading.start,h=i.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||e.level<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||s.paused||!s.playbackRate||!s.readyState)return;const c=i.mainForwardBufferInfo;if(null===c)return;const d=this.bwEstimator.getEstimateTTFB(),u=Math.abs(s.playbackRate);if(l<=Math.max(d,o/(2*u)*1e3))return;const f=c.len/u,g=a.loading.first?a.loading.first-a.loading.start:-1,m=a.loaded&&g>-1,p=this.getBwEstimate(),v=i.levels,y=v[e.level],T=a.total||Math.max(a.loaded,Math.round(o*y.averageBitrate/8));let E=m?l-g:l;E<1&&m&&(E=Math.min(l,8*a.loaded/p));const S=m?1e3*a.loaded/E:0,b=S?(T-a.loaded)/S:8*T/p+d/1e3;if(b<=f)return;const L=S?8*S:p;let w,A=Number.POSITIVE_INFINITY;for(w=e.level-1;w>h;w--){const e=v[w].maxBitrate;if(A=this.getTimeToLoadFrag(d/1e3,L,o*e,!v[w].details),A=b)return;if(A>10*o)return;i.nextLoadLevel=i.nextAutoLevel=w,m?this.bwEstimator.sample(l-Math.min(d,g),a.loaded):this.bwEstimator.sampleTTFB(l);const R=v[w].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>R&&this.resetEstimator(R),this.clearTimer(),lr.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${b.toFixed(3)} s\n Estimated load time for down switch fragment: ${A.toFixed(3)} s\n TTFB estimate: ${0|g} ms\n Current BW estimate: ${Ji(p)?0|p:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${w} @ ${0|R} bps`),i.trigger(tr.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:a})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(lr.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new ca(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.FRAG_LOADING,this.onFragLoading,this),e.on(tr.FRAG_LOADED,this.onFragLoaded,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.on(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.on(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(tr.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.FRAG_LOADING,this.onFragLoading,this),e.off(tr.FRAG_LOADED,this.onFragLoaded,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.off(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.off(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(tr.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(tr.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const i=t.frag;if(!this.ignoreFragment(i)){var r;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case rr.BUFFER_ADD_CODEC_ERROR:case rr.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case rr.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:i,partCurrent:r}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){const t=performance.now(),i=r?r.stats:e.stats,s=t-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(e,n),i.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(e,t,i,r){return e+i/t+(r?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const i=this.hls.config,{loading:r}=t.stats,s=r.end-r.start;Ji(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:i}){const r=i?i.stats:t.stats;if(t.type===hn&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=i?i.duration:t.duration,s=this.hls.levels[t.level],n=(s.loaded?s.loaded.bytes:0)+r.loaded,a=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(tr.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:r}=t,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted)return;if(this.ignoreFragment(i))return;const n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==hn||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,t,e,0,r,1,1);if(s>-1)return s;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return lr.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:r,config:s,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=s.abrBandWidthFactor,c=s.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,r,l,0,h,c);if(e>=0)return e}let d=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){d=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-e,lr.info(`[abr] bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=c=1}}const u=this.findBestLevel(o,n,r,l,d,h,c);if(lr.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`),u>-1)return u;const f=i.levels[n],g=i.levels[i.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,s,n,a){var o;const l=r+s,h=this.lastLoadedFragLevel,c=-1===h?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const v=f[c],y=!(null==v||null==(o=v.details)||!o.live),T=-1===m||-1===h;let E,S="SDR",b=(null==v?void 0:v.frameRate)||0;const{audioPreference:L,videoPreference:w}=p,A=this.audioTracksByGroup||(this.audioTracksByGroup=function(e){return e.reduce(((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(g));if(T){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(e,t,i,r){return e.slice(i,r+1).reduce(((e,i)=>{if(!i.codecSet)return e;const r=i.audioGroups;let s=e[i.codecSet];s||(e[i.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,i.bitrate);const n=Math.min(i.height,i.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,i.frameRate),s.maxScore=Math.max(s.maxScore,i.score),s.fragmentError+=i.fragmentError,s.videoRanges[i.videoRange]=(s.videoRanges[i.videoRange]||0)+1,r&&r.forEach((e=>{if(!e)return;const i=t.groups[e];i&&(s.hasDefaultAudio=s.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((e=>{s.channels[e]=(s.channels[e]||0)+i.channels[e]})))})),e}),{})}(f,A,t,i)),s=function(e,t,i,r,s){const n=Object.keys(e),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=a&&2===parseInt(a);let h=!0,c=!1,d=1/0,u=1/0,f=1/0,g=0,m=[];const{preferHDR:p,allowedVideoRanges:v}=ma(t,s);for(let t=n.length;t--;){const i=e[n[t]];h=i.channels[2]>0,d=Math.min(d,i.minHeight),u=Math.min(u,i.minFramerate),f=Math.min(f,i.minBitrate);const r=v.filter((e=>i.videoRanges[e]>0));r.length>0&&(c=!0,m=r)}d=Ji(d)?d:0,u=Ji(u)?u:0;const y=Math.max(1080,d),T=Math.max(30,u);return f=Ji(f)?f:i,i=Math.max(f,i),c||(t=void 0,m=[]),{codecSet:n.reduce(((t,r)=>{const s=e[r];if(r===t)return t;if(s.minBitrate>i)return pa(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),t;if(!s.hasDefaultAudio)return pa(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return pa(r,`audio codec preference "${o}" not found`),t;if(a&&!l){if(!s.channels[a])return pa(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(s.channels)})`),t}else if((!o||l)&&h&&0===s.channels[2])return pa(r,"no renditions with stereo sound found"),t;return s.minHeight>y?(pa(r,`min resolution of ${s.minHeight} > maximum of ${y}`),t):s.minFramerate>T?(pa(r,`min framerate of ${s.minFramerate} > maximum of ${T}`),t):m.some((e=>s.videoRanges[e]>0))?s.maxScore=$s(t)||s.fragmentError>e[t].fragmentError)?t:(g=s.maxScore,r):(pa(r,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),t)}),void 0),videoRanges:m,preferHDR:p,minFramerate:u,minBitrate:f}}(r,S,e,L,w),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,preferHDR:h}=s;E=n,S=h?a[a.length-1]:a[0],b=o,e=Math.max(e,l),lr.log(`[abr] picked start tier ${JSON.stringify(s)}`)}else E=null==v?void 0:v.codecSet,S=null==v?void 0:v.videoRange;const R=u?u.duration:d?d.duration:0,k=this.bwEstimator.getEstimateTTFB()/1e3,_=[];for(let o=i;o>=t;o--){var D;const t=f[o],d=o>c;if(!t)continue;if(p.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&fa(t,A,S,b,e,L)?(t.supportedPromise=ga(t,A,i),t.supportedPromise.then((e=>{if(!this.hls)return;t.supportedResult=e;const i=this.hls.levels,r=i.indexOf(t);e.error?lr.warn(`[abr] MediaCapabilities decodingInfo error: "${e.error}" for level ${r} ${JSON.stringify(e)}`):e.supported||(lr.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${r} ${JSON.stringify(e)}`),r>-1&&i.length>1&&(lr.log(`[abr] Removing unsupported level ${r}`),this.hls.removeLevel(r)))}))):t.supportedResult=da}if(E&&t.codecSet!==E||S&&t.videoRange!==S||d&&b>t.frameRate||!d&&b>0&&b=2*R&&0===s?f[o].averageBitrate:f[o].maxBitrate,I=this.getTimeToLoadFrag(k,x,C*w,void 0===g);if(x>=C&&(o===h||0===t.loadError&&0===t.fragmentError)&&(I<=k||!Ji(I)||y&&!this.bitrateTestDelay||I${o} adjustedbw(${Math.round(x)})-bitrate=${Math.round(x-C)} ttfb:${k.toFixed(1)} avgDuration:${w.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${I.toFixed(1)} firstSelection:${T} codecSet:${E} videoRange:${S} hls.loadLevel:${m}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls,r=Math.min(Math.max(e,i),t);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}},bufferController:class{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=e=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:e,mediaSource:t}=this;this.log("Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(tr.MEDIA_ATTACHED,{media:e,mediaSource:t})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&lr.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e;const t="[buffer-controller]";var i;this.appendSource=(i=Os(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.log=lr.log.bind(lr,t),this.warn=lr.warn.bind(lr,t),this.error=lr.error.bind(lr,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.BUFFER_RESET,this.onBufferReset,this),e.on(tr.BUFFER_APPENDING,this.onBufferAppending,this),e.on(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.on(tr.BUFFER_EOS,this.onBufferEos,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(tr.FRAG_PARSED,this.onFragParsed,this),e.on(tr.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.BUFFER_RESET,this.onBufferReset,this),e.off(tr.BUFFER_APPENDING,this.onBufferAppending,this),e.off(tr.BUFFER_CODECS,this.onBufferCodecs,this),e.off(tr.BUFFER_EOS,this.onBufferEos,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(tr.FRAG_PARSED,this.onFragParsed,this),e.off(tr.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Tl(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media,r=Os(this.appendSource);if(i&&r){var s;const e=this.mediaSource=new r;this.log(`created media source: ${null==(s=e.constructor)?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming));const t=this._objectUrl=self.URL.createObjectURL(e);if(this.appendSource)try{i.removeAttribute("src");const r=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||r&&e instanceof r,Sl(i),function(e,t){const i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(this.log("media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(e.removeAttribute("src"),this.appendSource&&Sl(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(tr.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((e=>{this.resetBuffer(e)})),this._initSourceBuffer()}resetBuffer(e){const t=this.sourceBuffer[e];try{var i;if(t)this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}catch(t){this.warn(`onBufferReset ${e}`,t)}}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length,r=Object.keys(t);if(r.forEach((e=>{if(i){const i=this.tracks[e];if(i&&"function"==typeof i.buffer.changeType){var r;const{id:s,codec:n,levelCodec:a,container:o,metadata:l}=t[e],h=Hs(i.codec,i.levelCodec),c=null==h?void 0:h.replace(El,"$1");let d=Hs(n,a);const u=null==(r=d)?void 0:r.replace(El,"$1");if(d&&c!==u){"audio"===e.slice(0,5)&&(d=Vs(d,this.appendSource));const t=`${o};codecs=${d}`;this.appendChangeType(e,t),this.log(`switching codec ${h} to ${d}`),this.tracks[e]={buffer:i.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:s}}}}else this.pendingTracks[e]=t[e]})),i)return;const s=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==s&&(this.log(`${s} bufferCodec event(s) expected ${r.join(",")}`),this.bufferCodecEventsExpected=s),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:i}=this,r={execute:()=>{const r=this.sourceBuffer[e];r&&(this.log(`changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};i.append(r,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:i,operationQueue:r,tracks:s}=this,{data:n,type:a,frag:o,part:l,chunkMeta:h}=t,c=h.buffering[a],d=self.performance.now();c.start=d;const u=o.stats.buffering,f=l?l.stats.buffering:null;0===u.start&&(u.start=d),f&&0===f.start&&(f.start=d);const g=s.audio;let m=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const p=o.start,v={execute:()=>{if(c.executeStart=self.performance.now(),m){const e=this.sourceBuffer[a];if(e){const t=p-e.timestampOffset;Math.abs(t)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${p} (delta: ${t}) sn: ${o.sn})`),e.timestampOffset=p)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();c.executeEnd=c.end=e,0===u.first&&(u.first=e),f&&0===f.first&&(f.first=e);const{sourceBuffer:t}=this,i={};for(const e in t)i[e]=xa.getBuffered(t[e]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(tr.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:i})},onError:e=>{const t={type:ir.MEDIA_ERROR,parent:o.type,details:rr.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:h,error:e,err:e,fatal:!1};if(e.code===DOMException.QUOTA_EXCEEDED_ERR)t.details=rr.BUFFER_FULL_ERROR;else{const e=++this.appendErrors[a];t.details=rr.BUFFER_APPEND_ERROR,this.warn(`Failed ${e}/${i.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),e>=i.config.appendErrorMaxRetry&&(t.fatal=!0)}i.trigger(tr.ERROR,t)}};r.append(v,a,!!this.pendingTracks[a])}onBufferFlushing(e,t){const{operationQueue:i}=this,r=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(tr.BUFFER_FLUSHED,{type:e})},onError:t=>{this.warn(`Failed to remove from ${e} SourceBuffer`,t)}});t.type?i.append(r(t.type),t.type):this.getSourceBufferTypes().forEach((e=>{i.append(r(e),e)}))}onFragParsed(e,t){const{frag:i,part:r}=t,s=[],n=r?r.elementaryStreams:i.elementaryStreams;n[vr]?s.push("audiovideo"):(n[mr]&&s.push("audio"),n[pr]&&s.push("video"));0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{const e=self.performance.now();i.stats.buffering.end=e,r&&(r.stats.buffering.end=e);const t=r?r.stats:i.stats;this.hls.trigger(tr.FRAG_BUFFERED,{frag:i,part:r,stats:t,id:i.type})}),s)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce(((e,i)=>{const r=this.sourceBuffer[i];return!r||t.type&&t.type!==i||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${i} sourceBuffer now EOS`))),e&&!(r&&!r.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((e=>{const t=this.sourceBuffer[e];t&&(t.ending=!1)}));const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream()):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:i}=this;if(!i||null===t)return;if(!this.getSourceBufferTypes().length)return;const r=e.config,s=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(Ji(a)&&a>0){const e=Math.max(a,n),t=Math.floor(s/n)*n-e;this.flushBackBuffer(s,n,t)}if(Ji(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const e=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),t=Math.max(e,n),i=Math.floor(s/n)*n+t;this.flushFrontBuffer(s,n,i)}}flushBackBuffer(e,t,i){const{details:r,sourceBuffer:s}=this;this.getSourceBufferTypes().forEach((n=>{const a=s[n];if(a){const s=xa.getBuffered(a);if(s.length>0&&i>s.start(0)){if(this.hls.trigger(tr.BACK_BUFFER_REACHED,{bufferEnd:i}),null!=r&&r.live)this.hls.trigger(tr.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(a.ended&&s.end(s.length-1)-e<2*t)return void this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);this.hls.trigger(tr.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}}))}flushFrontBuffer(e,t,i){const{sourceBuffer:r}=this;this.getSourceBufferTypes().forEach((s=>{const n=r[s];if(n){const r=xa.getBuffered(n),a=r.length;if(a<2)return;const o=r.start(a-1),l=r.end(a-1);if(i>o||e>=o&&e<=l)return;if(n.ended&&e-l<2*t)return void this.log(`Cannot flush ${s} front buffer while SourceBuffer is in ended state`);this.hls.trigger(tr.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:s})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:e,hls:t,media:i,mediaSource:r}=this,s=e.fragments[0].start+e.totalduration,n=i.duration,a=Ji(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(e)):(s>a&&s>n||!Ji(n))&&(this.log(`Updating Media Source duration to ${s.toFixed(3)}`),r.duration=s)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&null!=t&&t.setLiveSeekableRange){const r=Math.max(0,i[0].start),s=Math.max(r,r+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${r}-${s}.`),t.setLiveSeekableRange(r,s)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,r=Object.keys(i).length;if(r&&(!e||2===r||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const e=this.getSourceBufferTypes();if(e.length)this.hls.trigger(tr.BUFFER_CREATED,{tracks:this.tracks}),e.forEach((e=>{t.executeNext(e)}));else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const s in e)if(!t[s]){var r;const n=e[s];if(!n)throw Error(`source buffer exists for track ${s}, however track does not`);let a=-1===(null==(r=n.levelCodec)?void 0:r.indexOf(","))?n.levelCodec:n.codec;a&&"audio"===s.slice(0,5)&&(a=Vs(a,this.appendSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const e=t[s]=i.addSourceBuffer(o),r=s;this.addBufferListener(r,"updatestart",this._onSBUpdateStart),this.addBufferListener(r,"updateend",this._onSBUpdateEnd),this.addBufferListener(r,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(r,"bufferedchange",((e,t)=>{const i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(tr.BUFFER_FLUSHED,{type:s})})),this.tracks[s]={buffer:e,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(e){this.error(`error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:s,mimeType:o})}}}get mediaSrc(){var e;const t=(null==(e=this.media)?void 0:e.firstChild)||this.media;return null==t?void 0:t.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const{operationQueue:i}=this;i.current(e).onComplete(),i.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var i;const r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const s=this.operationQueue.current(e);s&&s.onError(r)}removeExecutor(e,t,i){const{media:r,mediaSource:s,operationQueue:n,sourceBuffer:a}=this,o=a[e];if(!r||!s||!o)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(e);const l=Ji(r.duration)?r.duration:1/0,h=Ji(s.duration)?s.duration:1/0,c=Math.max(0,t),d=Math.min(i,l,h);d>c&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${c},${d}] from the ${e} SourceBuffer`),o.remove(c,d)):n.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.sourceBuffer[t];if(i)i.ended=!1,i.appendBuffer(e);else if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);const{operationQueue:i}=this,r=t.map((e=>i.appendBlocker(e)));Promise.all(r).then((()=>{e(),t.forEach((e=>{const t=this.sourceBuffer[e];null!=t&&t.updating||i.shiftAndExecuteNext(e)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const r=this.sourceBuffer[e];if(!r)return;const s=i.bind(this,e);this.listeners[e].push({event:t,listener:s}),r.addEventListener(t,s)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach((e=>{t.removeEventListener(e.event,e.listener)}))}},capLevelController:ph,errorController:class{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=lr.log.bind(lr,"[info]:"),this.warn=lr.warn.bind(lr,"[warning]:"),this.error=lr.error.bind(lr,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(tr.ERROR,this.onError,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(tr.ERROR,this.onError,this),e.off(tr.ERROR,this.onErrorOut,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===hn?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,r;if(t.fatal)return;const s=this.hls,n=t.context;switch(t.details){case rr.FRAG_LOAD_ERROR:case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_ERROR:case rr.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case rr.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction={action:ta,flags:na});case rr.FRAG_GAP:case rr.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=ia);case rr.LEVEL_EMPTY_ERROR:case rr.LEVEL_PARSING_ERROR:{var a,o;const e=t.parent===hn?t.level:s.loadLevel;t.details===rr.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(o=a.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case rr.LEVEL_LOAD_ERROR:case rr.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case rr.AUDIO_TRACK_LOAD_ERROR:case rr.AUDIO_TRACK_LOAD_TIMEOUT:case rr.SUBTITLE_LOAD_ERROR:case rr.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const e=s.levels[s.loadLevel];if(e&&(n.type===on&&e.hasAudioGroup(n.groupId)||n.type===ln&&e.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=ia,void(t.errorAction.flags=aa)}return;case rr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=s.levels[s.loadLevel],i=null==e?void 0:e.attrs["HDCP-LEVEL"];i?t.errorAction={action:ia,flags:oa,hdcpLevel:i}:this.keySystemError(t)}return;case rr.BUFFER_ADD_CODEC_ERROR:case rr.REMUX_ALLOC_ERROR:case rr.BUFFER_APPEND_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(r=t.level)?r:s.loadLevel));case rr.INTERNAL_EXCEPTION:case rr.BUFFER_APPENDING_ERROR:case rr.BUFFER_FULL_ERROR:case rr.LEVEL_SWITCH_ERROR:case rr.BUFFER_STALLED_ERROR:case rr.BUFFER_SEEK_OVER_HOLE:case rr.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:ta,flags:na})}t.type===ir.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=Yn(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(Xn(i,r,Wn(e),e.response))return{action:sa,flags:na,retryConfig:i,retryCount:r};const s=this.getLevelSwitchAction(e,t);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:n}=t.config,a=Yn(e.details.startsWith("key")?n:s,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(r){e.details!==rr.FRAG_GAP&&r.fragmentError++;if(Xn(a,o,Wn(e),e.response))return{action:sa,flags:na,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const i=this.hls;null==t&&(t=i.loadLevel);const r=this.hls.levels[t];if(r){var s,n;const t=e.details;r.loadError++,t===rr.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1;const{levels:h,loadLevel:c,minAutoLevel:d,maxAutoLevel:u}=i;i.autoLevelEnabled||(i.loadLevel=-1);const f=null==(s=e.frag)?void 0:s.type,g=(f===cn&&t===rr.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===rr.BUFFER_ADD_CODEC_ERROR||t===rr.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:e})=>r.audioCodec!==e)),m="video"===e.sourceBufferName&&(t===rr.BUFFER_ADD_CODEC_ERROR||t===rr.BUFFER_APPEND_ERROR)&&h.some((({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t)),{type:p,groupId:v}=null!=(n=e.context)?n:{};for(let i=h.length;i--;){const s=(i+c)%h.length;if(s!==c&&s>=d&&s<=u&&0===h[s].loadError){var a,o;const i=h[s];if(t===rr.FRAG_GAP&&f===hn&&e.frag){const t=h[s].details;if(t){const i=Jn(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else{if(p===on&&i.hasAudioGroup(v)||p===ln&&i.hasSubtitleGroup(v))continue;if(f===cn&&null!=(a=r.audioGroups)&&a.some((e=>i.hasAudioGroup(e)))||f===dn&&null!=(o=r.subtitleGroups)&&o.some((e=>i.hasSubtitleGroup(e)))||g&&r.audioCodec===i.audioCodec||!g&&r.audioCodec!==i.audioCodec||m&&r.codecSet===i.codecSet)continue}l=s;break}}if(l>-1&&i.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:ia,flags:na,nextAutoLevel:l}}return{action:ia,flags:aa}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case ta:break;case ia:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===rr.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:r,hdcpLevel:s,nextAutoLevel:n}=i;switch(r){case na:this.switchLevel(e,n);break;case oa:s&&(t.maxHdcpLevel=Dn[Dn.indexOf(s)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(e,n)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const r=performance.now();if(t){if(this.lastTime){const e=r-this.lastTime,s=i-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*s/e,o=this.hls;if(o.trigger(tr.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:i}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;lr.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(tr.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Mr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:fc,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends no{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",dn),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.on(tr.ERROR,this.onError,this),e.on(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(tr.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(tr.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.off(tr.ERROR,this.onError,this),e.off(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(tr.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(tr.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=qa,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:r}=t;if(this.fragPrevious=i,this.state=qa,!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let n;const a=i.start;for(let e=0;e=s[e].start&&a<=s[e].end){n=s[e];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(e,t){const{startOffset:i,endOffset:r}=t;if(0===i&&r!==Number.POSITIVE_INFINITY){const e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let i=0;inew Fn(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new Fn(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,dn),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i;const{currentTrackId:r,levels:s}=this,{details:n,id:a}=t;if(!s)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=s[a];if(a>=s.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){const e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;const t=e.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&t&&(l=t.start,Kn(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(Fa(n,e),l=n.fragments[0].start):t&&(l=t.start,Kn(n,l))}if(o.details=n,this.levelLastLoaded=o,a===r&&(this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===qa)){Jn(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,r=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){const e=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch((e=>{throw s.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((i=>{const r=performance.now();s.trigger(tr.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:r}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=qa}))}}doTick(){if(this.media){if(this.state===qa){const{currentTrackId:e,levels:t}=this,i=null==t?void 0:t[e];if(!i||!t.length||!i.details)return;const{config:r}=this,s=this.getLoadPosition(),n=xa.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,hn),h=i.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;const c=h.fragments,d=c.length,u=h.edge;let f=null;const g=this.fragPrevious;if(au-e?0:e;f=Jn(g,c,Math.max(c[0].start,a),t),!f&&g&&g.startthis.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=Tn(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.LEVEL_LOADING,this.onLevelLoading,this),e.on(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.LEVEL_LOADING,this.onLevelLoading,this),e.off(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(tr.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(tr.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);Tn(this.media.textTracks).forEach((e=>{vn(e)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,groupId:r,details:s}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.subtitleGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!s&&t){this.selectDefaultTrack=!1;const i=va(t,e);if(i>-1)s=e[i];else{const e=va(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(tr.SUBTITLE_TRACKS_UPDATED,n),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r-1){const e=this.tracksInGroup[r];return this.setSubtitleTrack(r),e}if(i)return null;{const i=va(e,t);if(i>-1)return t[i]}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const i=t.id,r=t.groupId;let s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(tr.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Tn(e.textTracks),i=this.currentTrack;let r;if(i&&(r=t.filter((e=>vl(i,e)))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach((e=>{"disabled"!==e.mode&&e!==r&&(e.mode="disabled")})),r){const e=this.subtitleDisplay?"showing":"hidden";r.mode!==e&&(r.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!Ji(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(tr.SUBTITLE_TRACK_SWITCH,{id:e});const s=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&s)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=r;this.hls.trigger(tr.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const c=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(c)}},timelineController:class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(tr.FRAG_LOADING,this.onFragLoading,this),e.on(tr.FRAG_LOADED,this.onFragLoaded,this),e.on(tr.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(tr.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(tr.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(tr.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(tr.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(tr.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(tr.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(tr.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(tr.FRAG_LOADING,this.onFragLoading,this),e.off(tr.FRAG_LOADED,this.onFragLoaded,this),e.off(tr.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(tr.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(tr.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(tr.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(tr.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new Gl(this,"textTrack1"),t=new Gl(this,"textTrack2"),i=new Gl(this,"textTrack3"),r=new Gl(this,"textTrack4");this.cea608Parser1=new Ul(1,e,t),this.cea608Parser2=new Ul(3,i,r)}}addCues(e,t,i,r,s){let n=!1;for(let e=s.length;e--;){const r=s[e],c=(a=r[0],o=r[1],l=t,h=i,Math.min(o,h)-Math.max(a,l));if(c>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],i),n=!0,c/(i-t)>.5))return}var a,o,l,h;if(n||s.push([t,i]),this.config.renderTextTracksNatively){const s=this.captionsTracks[e];this.Cues.newCue(s,t,i,r)}else{const s=this.Cues.newCue(null,t,i,r);this.hls.trigger(tr.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s}){const{unparsedVttFrags:n}=this;"main"===i&&(this.initPTS[t.cc]={baseTime:r,timescale:s}),n.length&&(this.unparsedVttFrags=[],n.forEach((e=>{this.onFragLoaded(tr.FRAG_LOADED,e)})))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let r=0;r{vn(e[t]),delete e[t]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;ee.textCodec===rh));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(ml(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const e=this.media,t=e?Tn(e.textTracks):null;if(this.tracks.forEach(((e,i)=>{let r;if(t){let i=null;for(let r=0;rnull!==e)).map((e=>e.label));e.length&&lr.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(tr.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const i=`textTrack${t[1]}`,r=this.captionsProperties[i];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===hn){var i,r;const{cea608Parser1:e,cea608Parser2:s,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;e&&s&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),s.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:i,payload:r}=t;if(i.type===dn)if(r.byteLength){const e=i.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){const e=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===rh?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;oh(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),i.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{lr.log(`Failed to parse IMSC1: ${t}`),i.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:i,payload:r}=e,{initPTS:s,unparsedVttFrags:n}=this,a=s.length-1;if(!s[i.cc]&&-1===a)return void n.push(e);const o=this.hls;ih(null!=(t=i.initSegment)&&t.data?Es(i.initSegment.data,new Uint8Array(r)):r,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(e=>{this._appendCues(e,i.level),o.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(t=>{const s="Missing initPTS for VTT MPEGTS"===t.message;s?n.push(e):this._fallbackToIMSC1(i,r),lr.log(`Failed to parse VTT cue: ${t}`),s&&a>i.cc||o.trigger(tr.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})}))}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||oh(t,this.initPTS[e.cc],(()=>{i.textCodec=rh,this._parseIMSC1(e,t)}),(()=>{i.textCodec="wvtt"}))}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach((e=>pn(i,e)))}else{const r=this.tracks[t];if(!r)return;const s=r.default?"default":"subtitles"+t;i.trigger(tr.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===dn&&this.onFragLoaded(tr.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!i||!r)return;const{frag:s,samples:n}=t;if(s.type!==hn||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;eyn(e[r],t,i)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){const{textTracks:e}=this;Object.keys(e).forEach((i=>yn(e[i],t,r)))}}}extractCea608Data(e){const t=[[],[]],i=31&e[0];let r=2;for(let s=0;s0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=qa):(this.loadedmetadata=!1,this.state=Ja),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case qa:this.doTickIdle();break;case Ja:{var e;const{levels:t,trackId:i}=this,r=null==t||null==(e=t[i])?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=ro}break}case Qa:{var t;const e=performance.now(),i=this.retryDate;if(!i||e>=i||null!=(t=this.media)&&t.seeking){const{levels:e,trackId:t}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==e?void 0:e[t])||null),this.state=qa}break}case ro:{const e=this.waitingData;if(e){const{frag:t,part:i,cache:r,complete:s}=e;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=Xa;const e={frag:t,part:i,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const e=this.getLoadPosition(),i=xa.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);Zn(i.end,this.config.maxFragLookUpTolerance,t)<0&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${i.end} is needed`),this.clearWaitingFragment())}}else this.state=qa}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=qa)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:i,trackId:r}=this,s=e.config;if(!i&&(this.startFragRequested||!s.startFragPrefetch)||null==t||!t[r])return;const n=t[r],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=Ja);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,mr,cn));const l=this.getFwdBufferInfo(o,cn);if(null===l)return;const{bufferedTrack:h,switchingTrack:c}=this;if(!c&&this._streamEnded(l,a))return e.trigger(tr.BUFFER_EOS,{type:"audio"}),void(this.state=to);const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,hn),u=l.len,f=this.getMaxBufferLength(null==d?void 0:d.len),g=a.fragments,m=g[0].start;let p=this.flushing?this.getLoadPosition():l.end;if(c&&i){const e=this.getLoadPosition();h&&!pl(c.attrs,h.attrs)&&(p=e),a.PTSKnown&&em||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=m+.05)}if(u>=f&&!c&&pd.end+a.targetduration;if(T||(null==d||!d.len)&&l.len){const e=this.getAppendedFrag(v.start,hn);if(null===e)return;if(y||(y=!!e.gap||!!T&&0===d.len),T&&!y||y&&l.nextStart&&l.nextStartnew Fn(e)))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?this.setInterval(100):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=qa,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=Ya),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(tr.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=t);const{levels:r}=this,{details:s,id:n}=t;if(!r)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const a=r[n];let o=0;if(s.live||null!=(i=a.details)&&i.live){this.checkLiveUpdate(s);const e=this.mainDetails;if(s.deltaUpdateFailed||!e)return;var l;if(!a.details&&s.hasProgramDateTime&&e.hasProgramDateTime)Fa(s,e),o=s.fragments[0].start;else o=this.alignPlaylists(s,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=s,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(this.mainDetails||s,o),this.state!==Ja||this.waitForCdnTuneIn(s)||(this.state=qa),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:s}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new gl(this.hls,cn,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=r?r.index:-1,n=-1!==t,a=new Ca(i.level,i.sn,i.stats.chunkCount,s.byteLength,t,n);d.push(s,f,c,"",i,r,h.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new ao,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=ro}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:i,part:r}=t;if(i.type===cn)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==i.sn){this.fragPrevious=i;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(tr.AUDIO_TRACK_SWITCHED,qi({},e)))}this.fragBufferedComplete(i,r)}else if(!this.loadedmetadata&&i.type===hn){const e=this.videoBuffer||this.media;if(e){xa.getBuffered(e).length&&(this.loadedmetadata=!0)}}}onError(e,t){var i;if(t.fatal)this.state=io;else switch(t.details){case rr.FRAG_GAP:case rr.FRAG_PARSING_ERROR:case rr.FRAG_DECRYPT_ERROR:case rr.FRAG_LOAD_ERROR:case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_ERROR:case rr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(cn,t);break;case rr.AUDIO_TRACK_LOAD_ERROR:case rr.AUDIO_TRACK_LOAD_TIMEOUT:case rr.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==Ja||(null==(i=t.context)?void 0:i.type)!==on||(this.state=qa);break;case rr.BUFFER_APPEND_ERROR:case rr.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;if(t.details===rr.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case rr.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==pr&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==pr){this.flushing=!1,this.bufferFlushed=!0,this.state===to&&(this.state=qa);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,cn),this.tick())}}_handleTransmuxComplete(e){var t;const i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:c}=h,{audio:d,text:u,id3:f,initSegment:g}=s;if(!this.fragContextChanged(o)&&c){if(this.state=Za,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;this._bufferInitSegment(h,g.tracks,e,n),r.trigger(tr.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:g.tracks})}if(d){const{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=d;l&&(l.elementaryStreams[mr]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(mr,e,t,i,r),this.bufferFragmentData(d,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=Qi({id:i,frag:o,details:c},f);r.trigger(tr.FRAG_PARSING_METADATA,e)}if(u){const e=Qi({id:i,frag:o,details:c},u);r.trigger(tr.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,i,r){if(this.state!==Za)return;t.video&&delete t.video;const s=t.audio;if(!s)return;s.id="audio";const n=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${n}/${s.codec}]`),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(tr.BUFFER_CODECS,t);const a=s.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(tr.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);var s;if(this.fragCurrent=e,this.switchingTrack||r===ba||r===wa)if("initSegment"===e.sn)this._loadInitSegment(e,t);else if(null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=ro;const i=this.mainDetails;i&&i.fragments[0].start!==t.details.fragments[0].start&&Fa(t.details,i)}else this.startFragRequested=!0,super.loadFragment(e,t,i);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:t,bufferedTrack:i}=this,r=null==i?void 0:i.attrs,s=e.attrs;t&&r&&(r.CHANNELS!==s.CHANNELS||i.name!==e.name||i.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(tr.AUDIO_TRACK_SWITCHED,qi({},e))}},audioTrackController:class extends la{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.LEVEL_LOADING,this.onLevelLoading,this),e.on(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(tr.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.LEVEL_LOADING,this.onLevelLoading,this),e.off(tr.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(tr.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(tr.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:r,details:s}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const i=t.audioGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!s&&t){const i=va(t,e,Ta);if(i>-1)s=e[i];else{const e=va(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(tr.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}else this.shouldReloadPlaylist(s)&&this.setAudioTrack(this.trackId)}onError(e,t){!t.fatal&&t.context&&(t.context.type!==on||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||(this.requestScheduled=-1,this.checkRetry(t)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const r=this.currentTrack;if(r&&ya(e,r,Ta))return r;const s=va(e,this.tracksInGroup,Ta);if(s>-1){const e=this.tracksInGroup[s];return this.setAudioTrack(s),e}if(r){let r=t.loadLevel;-1===r&&(r=t.firstAutoLevel);const s=function(e,t,i,r,s){const n=t[r],a=t.reduce(((e,t,i)=>{const r=t.uri;return(e[r]||(e[r]=[])).push(i),e}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),c=Ea(t,r,(t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;const r=t.audioGroups,n=i.filter((e=>!r||-1!==r.indexOf(e.groupId)));return va(e,n,s)>-1}));return c>-1?c:Ea(t,r,(t=>{const r=t.audioGroups,n=i.filter((e=>!r||-1!==r.indexOf(e.groupId)));return va(e,n,s)>-1}))}(e,t.levels,i,r,Ta);if(-1===s)return null;t.nextLoadLevel=s}if(e.channels||e.audioCodec){const t=va(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=t[e],s=r.details&&!r.details.live;if(e===this.trackId&&r===i&&s)return;if(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(tr.AUDIO_TRACK_SWITCHING,qi({},r)),s)return;const n=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;i{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:Eh.MANIFEST,su:!this.initialized})}catch(e){lr.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const t=e.frag,i=this.hls.levels[t.level],r=this.getObjectType(t),s={d:1e3*t.duration,ot:r};r!==Eh.VIDEO&&r!==Eh.AUDIO&&r!=Eh.MUXED||(s.br=i.bitrate/1e3,s.tb=this.getTopBandwidth(r)/1e3,s.bl=this.getBufferLength(r)),this.apply(e,s)}catch(e){lr.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||function(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();const i="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const i=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?i:3&i|8).toString(16)}));return i}}}(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(tr.MEDIA_DETACHED,this.onMediaDetached,this),e.on(tr.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(tr.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(tr.MEDIA_DETACHED,this.onMediaDetached,this),e.off(tr.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:Sh.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Qi(t,this.createData());const i=t.ot===Eh.INIT||t.ot===Eh.VIDEO||t.ot===Eh.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce(((e,i)=>(r.includes(i)&&(e[i]=t[i]),e)),{})),this.useHeaders?(e.headers||(e.headers={}),ec(e.headers,t)):e.url=rc(e.url,t)}getObjectType(e){const{type:t}=e;return"subtitle"===t?Eh.TIMED_TEXT:"initSegment"===e.sn?Eh.INIT:"audio"===t?Eh.AUDIO:"main"===t?this.hls.audioTracks.length?Eh.VIDEO:Eh.MUXED:void 0}getTopBandwidth(e){let t,i=0;const r=this.hls;if(e===Eh.AUDIO)t=r.audioTracks;else{const e=r.maxAutoLevel,i=e>-1?e+1:r.levels.length;t=r.levels.slice(0,i)}for(const e of t)e.bitrate>i&&(i=e.bitrate);return i>0?i:NaN}getBufferLength(e){const t=this.hls.media,i=e===Eh.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!t)return NaN;return 1e3*xa.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}},contentSteeringController:class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=lr.log.bind(lr,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.on(tr.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(tr.MANIFEST_PARSED,this.onManifestParsed,this),e.off(tr.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((null==i?void 0:i.action)===ia&&i.flags===aa){const e=this.levels;let r=this.pathwayPriority,s=this.pathwayId;if(t.context){const{groupId:i,pathwayId:r,type:n}=t.context;i&&e?s=this.getPathwayForGroupId(i,n,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&e&&(r=e.reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s),i.resolved||lr.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${s} levels: ${e?e.length:e} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this.pathwayPriority=e;const i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((e=>{r-i[e]>3e5&&delete i[e]}));for(let r=0;r0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,jn(t),this.hls.trigger(tr.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===s)))return;const o=this.getLevelsForPathway(n).map((e=>{const t=new dr(e.attrs);t["PATHWAY-ID"]=s;const n=t.AUDIO&&`${t.AUDIO}_clone_${s}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${s}`;n&&(i[t.AUDIO]=n,t.AUDIO=n),o&&(r[t.SUBTITLES]=o,t.SUBTITLES=o);const l=nc(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new Fn({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t{this.log(`Loaded steering manifest: "${r}"`);const n=e.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,r).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:r.toString()};this.hls.trigger(tr.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(e,t,i,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,s);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;const i=null==(t=this.hls)?void 0:t.media;!i||i.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}}});function mc(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(mc):Object.keys(e).reduce(((t,i)=>(t[i]=mc(e[i]),t)),{}):e}function pc(e){const t=e.loader;if(t!==hc&&t!==oc)lr.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1})()&&(e.loader=hc,e.progressive=!0,e.enableSoftwareAES=!0,lr.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let vc;class yc extends la{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.on(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.on(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.on(tr.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(tr.MANIFEST_LOADING,this.onManifestLoading,this),e.off(tr.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(tr.LEVEL_LOADED,this.onLevelLoaded,this),e.off(tr.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(tr.FRAG_BUFFERED,this.onFragBuffered,this),e.off(tr.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=this.hls.config.preferManagedMediaSource,r=[],s={},n={};let a=!1,o=!1,l=!1;t.levels.forEach((e=>{var t,h;const c=e.attrs;let{audioCodec:d,videoCodec:u}=e;-1!==(null==(t=d)?void 0:t.indexOf("mp4a.40.34"))&&(vc||(vc=/chrome|firefox/i.test(navigator.userAgent)),vc&&(e.audioCodec=d=void 0)),d&&(e.audioCodec=d=Vs(d,i)),0===(null==(h=u)?void 0:h.indexOf("avc1"))&&(u=e.videoCodec=function(e){const t=e.split(".");if(t.length>2){let e=t.shift()+".";return e+=parseInt(t.shift()).toString(16),e+=("000"+parseInt(t.shift()).toString(16)).slice(-4),e}return e}(u));const{width:f,height:g,unknownCodecs:m}=e;if(a||(a=!(!f||!g)),o||(o=!!u),l||(l=!!d),null!=m&&m.length||d&&!Fs(d,"audio",i)||u&&!Fs(u,"video",i))return;const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":T,RESOLUTION:E,"VIDEO-RANGE":S}=c,b=`${`${T||"."}-`}${e.bitrate}-${E}-${v}-${p}-${S}-${y}`;if(s[b])if(s[b].uri===e.url||e.attrs["PATHWAY-ID"])s[b].addGroupId("audio",c.AUDIO),s[b].addGroupId("text",c.SUBTITLES);else{const t=n[b]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const i=new Fn(e);s[b]=i,r.push(i)}else{const t=new Fn(e);s[b]=t,n[b]=1,r.push(t)}})),this.filterAndSortMediaOptions(r,t,a,o,l)}filterAndSortMediaOptions(e,t,i,r,s){let n=[],a=[],o=e;if((i||r)&&s&&(o=o.filter((({videoCodec:e,videoRange:t,width:i,height:r})=>{return(!!e||!(!i||!r))&&(!!(s=t)&&xn.indexOf(s)>-1);var s}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));if(t.audioTracks){const{preferManagedMediaSource:e}=this.hls.config;n=t.audioTracks.filter((t=>!t.audioCodec||Fs(t.audioCodec,"audio",e))),Tc(n)}t.subtitles&&(a=t.subtitles,Tc(a));const l=o.slice(0);o.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return xn.indexOf(e.videoRange)-xn.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const i=Bs(e.videoCodec),r=Bs(t.videoCodec);if(i!==r)return r-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const i=$s(e.codecSet),r=$s(t.codecSet);if(i!==r)return r-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let e=0;ei&&i===gc.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const d=s&&!r,u={levels:o,audioTracks:n,subtitleTracks:a,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:!d&&n.some((e=>!!e.url))};this.hls.trigger(tr.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&n.details&&r&&s===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${s?" with Pathway "+s:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(tr.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==r?void 0:r.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){!t.fatal&&t.context&&t.context.type===an&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===hn){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;const i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:r,details:s}=t,n=this._levels[r];var a;if(!n)return this.warn(`Invalid level index ${r}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));r===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(r,t,n.details)):null!=(i=t.deliveryDirectives)&&i.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(e)try{r=e.addDirectives(r)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}const s=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""} with${s?" Pathway "+s:""} ${r}`),this.clearTimer(),this.hls.trigger(tr.LEVEL_LOADING,{url:r,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const i=this._levels.filter(((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));jn(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(tr.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(tr.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Tc(e){const t={};e.forEach((e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}class Ec{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==(null==(t=r.context)?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=rr.KEY_LOAD_ERROR,i,r,s){return new Ga({type:ir.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:r}=e;for(let e=0;e{s.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const i=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,rr.KEY_LOAD_ERROR,i))}const n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,rr.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(i=a)&&i.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,rr.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(i);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,i)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,r=new(0,i.loader)(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise(((s,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,r)=>{const{frag:a,keyInfo:o,url:l}=i;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,rr.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(e,i,r,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,rr.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),r,qi({url:a.url,data:void 0},e)))},onTimeout:(e,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,rr.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,rr.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,h)}))}resetLoader(e){const{frag:t,keyInfo:i,url:r}=e,s=i.loader;t.keyLoader===s&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()}}function Sc(){return self.SourceBuffer||self.WebKitSourceBuffer}function bc(){if(!Os())return!1;const e=Sc();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class Lc{constructor(e,t,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:r,stalled:s}=this;if(null===r)return;const{currentTime:n,seeking:a}=r,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==e){if(this.moved=!0,a||(this.nudgeRetry=0),null!==s){if(this.stallReported){const e=self.performance.now()-s;lr.warn(`playback not stuck anymore @${n}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(r.paused&&!a||r.ended||0===r.playbackRate||!xa.getBuffered(r).length)return void(this.nudgeRetry=0);const h=xa.bufferInfo(r,n,0),c=h.nextStart||0;if(a){const e=h.len>2,i=!c||t&&t.start<=n||c-n>2&&!this.fragmentTracker.getPartialFragment(n);if(e||i)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var d;if(!(h.len>0)&&!c)return;const e=Math.max(c,h.start||0)-n,t=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,i=(null==t||null==(d=t.details)?void 0:d.live)?2*t.details.targetduration:2,s=this.fragmentTracker.getPartialFragment(n);if(e>0&&(e<=i||s))return void(r.paused||this._trySkipBufferHole(s))}const u=self.performance.now();if(null===s)return void(this.stalled=u);const f=u-s;if(!a&&f>=250&&(this._reportStall(h),!this.media))return;const g=xa.bufferInfo(r,n,i.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:r,media:s}=this;if(null===s)return;const n=s.currentTime,a=r.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-n1e3*i.highBufferWatchdogPeriod&&(lr.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);lr.warn(r.message),t.trigger(tr.ERROR,{type:ir.MEDIA_ERROR,details:rr.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:r}=this;if(null===r)return 0;const s=r.currentTime,n=xa.bufferInfo(r,s,0),a=s0&&n.len<1&&r.readyState<3,h=a-s;if(h>0&&(o||l)){if(h>t.maxBufferHole){const{fragmentTracker:t}=this;let i=!1;if(0===s){const e=t.getAppendedFrag(0,hn);e&&a1?(e=0,this.bitrateTest=!0):e=i.firstAutoLevel),i.nextLoadLevel=e,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&-1===e&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=qa,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=Ya}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case so:{const{levels:e,level:t}=this,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(r))break;this.state=qa;break}if(this.hls.nextLoadLevel!==this.level){this.state=qa;break}break}case Qa:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:e,level:t}=this,i=null==e?void 0:e[t];this.resetStartWhenNotLoaded(i||null),this.state=qa}}}this.state===qa&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(null===t||!r&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=e.nextLoadLevel;if(null==i||!i[s])return;const n=i[s],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return this.altAudio&&(e.type="video"),this.hls.trigger(tr.BUFFER_EOS,e),void(this.state=to)}e.loadLevel!==s&&-1===e.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const l=n.details;if(!l||this.state===so||l.live&&this.levelLastLoaded!==n)return this.level=s,void(this.state=so);const h=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(h>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&"initSegment"!==u.sn&&this.fragmentTracker.getState(u)!==Aa){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,d)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?mr:pr,t=(e===pr?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,hn)}u=this.getNextFragmentLoopLoading(u,l,a,hn,c)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,d))}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===ba||r===wa?"initSegment"===e.sn?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,hn)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let i;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else i=0;const n=this.getBufferedFrag(t.currentTime+i);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,r=Math.max(n.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case za:case Xa:case Qa:case Za:case eo:this.state=qa}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Lc(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;Ji(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(tr.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,r=!1;t.levels.forEach((e=>{const t=e.audioCodec;t&&(i=i||-1!==t.indexOf("mp4a.40.2"),r=r||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&r&&!function(){var e;const t=Sc();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==qa)return;const r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=so)}onLevelLoaded(e,t){var i;const{levels:r}=this,s=t.level,n=t.details,a=n.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${a}`);const o=r[s],l=this.fragCurrent;!l||this.state!==Xa&&this.state!==Qa||l.level!==t.level&&l.loader&&this.abortCurrentFrag();let h=0;if(n.live||null!=(i=o.details)&&i.live){var c;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(tr.LEVEL_UPDATED,{details:n,level:s}),this.state===so){if(this.waitForCdnTuneIn(n))return;this.state=qa}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:s}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,h=o.PTSKnown||!o.live,c=null==(t=i.initSegment)?void 0:t.data,d=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new gl(this.hls,hn,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new Ca(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,g),p=this.initPTS[i.cc];u.push(s,c,d,l,i,r,o.totalduration,h,m,p)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const e=this.hls;i&&(e.trigger(tr.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(tr.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,r=!!this.hls.audioTracks[i].url;if(r){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=r,this.tick()}onBufferCreated(e,t){const i=t.tracks;let r,s,n=!1;for(const e in i){const t=i[e];if("main"===t.id){if(s=e,r=t,"video"===e){const t=i[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:r}=t;if(i&&i.type!==hn)return;if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===eo&&(this.state=qa));const s=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==i.sn&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal)this.state=io;else switch(t.details){case rr.FRAG_GAP:case rr.FRAG_PARSING_ERROR:case rr.FRAG_DECRYPT_ERROR:case rr.FRAG_LOAD_ERROR:case rr.FRAG_LOAD_TIMEOUT:case rr.KEY_LOAD_ERROR:case rr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(hn,t);break;case rr.LEVEL_LOAD_ERROR:case rr.LEVEL_LOAD_TIMEOUT:case rr.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==so||(null==(i=t.context)?void 0:i.type)!==an||(this.state=qa);break;case rr.BUFFER_APPEND_ERROR:case rr.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;if(t.details===rr.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case rr.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!xa.getBuffered(e).length){const e=this.state!==qa?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=qa,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==mr||this.audioOnly&&!this.altAudio){const e=(t===pr?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,hn),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t0&&(s{const{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=qa,this.startFragRequested=!1,this.bitrateTest=!1;const s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(tr.FRAG_LOADED,i),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const i="main",{hls:r}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{video:c,text:d,id3:u,initSegment:f}=s,{details:g}=h,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Za,f){if(null!=f&&f.tracks){const e=o.initSegment||o;this._bufferInitSegment(h,f.tracks,e,n),r.trigger(tr.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;Ji(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},r.trigger(tr.INIT_PTS_FOUND,{frag:o,id:i,initPTS:e,timescale:t}))}if(c&&g&&"initSegment"!==o.sn){const e=g.fragments[o.sn-1-g.startSN],t=o.sn===g.startSN,i=!e||o.cc>e.cc;if(!1!==s.independent){const{startPTS:e,endPTS:r,startDTS:s,endDTS:a}=c;if(l)l.elementaryStreams[c.type]={startPTS:e,endPTS:r,startDTS:s,endDTS:a};else if(c.firstKeyFrame&&c.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),c.dropped&&c.independent){const s=this.getMainFwdBufferInfo(),n=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=c.firstKeyFramePTS?c.firstKeyFramePTS:e;if(!t&&n2&&(o.gap=!0);o.setElementaryStreamInfo(c.type,e,r,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,l,n,t||i)}else{if(!t&&!i)return void this.backtrack(o);o.gap=!0}}if(m){const{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=m;l&&(l.elementaryStreams[mr]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(mr,e,t,i,r),this.bufferFragmentData(m,o,l,n)}if(g&&null!=u&&null!=(t=u.samples)&&t.length){const e={id:i,frag:o,details:g,samples:u.samples};r.trigger(tr.FRAG_PARSING_METADATA,e)}if(g&&d){const e={id:i,frag:o,details:g,samples:d.samples};r.trigger(tr.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,i,r){if(this.state!==Za)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:s,video:n,audiovideo:a}=t;if(s){let t=e.audioCodec;const i=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=s.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===i.indexOf("firefox")&&(t="mp4a.40.5")}t&&-1!==t.indexOf("mp4a.40.5")&&-1!==i.indexOf("android")&&"audio/mpeg"!==s.container&&(t="mp4a.40.2",this.log(`Android: force audio codec to ${t}`)),e.audioCodec&&e.audioCodec!==t&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${t}"`),s.levelCodec=t,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${t||""}/${e.audioCodec||""}/${s.codec}]`)}n&&(n.levelCodec=e.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),this.hls.trigger(tr.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{const s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(tr.BUFFER_APPENDING,{type:e,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,hn)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=qa}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const i=e.currentTime;if(xa.isBuffered(e,i)?t=this.getAppendedFrag(i):xa.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,i=t.level;e&&t.sn===e.sn&&e.level===i||(this.fragPlaying=t,this.hls.trigger(tr.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(tr.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&Ji(t)&&Ji(i.programDateTime)){const e=i.programDateTime+1e3*(t-i.start);return new Date(e)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Ac{static get version(){return"1.5.11"}static isMSESupported(){return bc()}static isSupported(){return function(){if(!bc())return!1;const e=Os();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(Us(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(Us(t,"audio")))))}()}static getMediaSource(){return Os()}static get Events(){return tr}static get ErrorTypes(){return ir}static get ErrorDetails(){return rr}static get DefaultConfig(){return Ac.defaultConfig?Ac.defaultConfig:gc}static set DefaultConfig(e){Ac.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new fl,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,function(e,t){if("object"==typeof console&&!0===e||"object"==typeof e){or(e,"debug","log","info","warn","error");try{ar.log(`Debug logs enabled for "${t}" in hls.js version 1.5.11`)}catch(e){ar=nr}}else ar=nr}(e.debug||!1,"Hls instance");const t=this.config=function(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=mc(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const s=`${"level"===e?"playlist":e}LoadPolicy`,n=void 0===t[s],a=[];r.forEach((r=>{const o=`${e}Loading${r}`,l=t[o];if(void 0!==l&&n){a.push(o);const e=i[s].default;switch(t[s]={default:e},r){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&lr.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),qi(qi({},i),t)}(Ac.DefaultConfig,e);this.userConfig=e,t.progressive&&pc(t);const{abrController:i,bufferController:r,capLevelController:s,errorController:n,fpsController:a}=t,o=new n(this),l=this.abrController=new i(this),h=this.bufferController=new r(this),c=this.capLevelController=new s(this),d=new a(this),u=new gn(this),f=new kn(this),g=t.contentSteeringController,m=g?new g(this):null,p=this.levelController=new yc(this,m),v=new Ra(this),y=new Ec(this.config),T=this.streamController=new wc(this,v,y);c.setStreamController(T),d.setStreamController(T);const E=[u,p,T];m&&E.splice(1,0,m),this.networkControllers=E;const S=[l,h,c,d,f,v];this.audioTrackController=this.createController(t.audioTrackController,E);const b=t.audioStreamController;b&&E.push(new b(this,v,y)),this.subtitleTrackController=this.createController(t.subtitleTrackController,E);const L=t.subtitleStreamController;L&&E.push(new L(this,v,y)),this.createController(t.timelineController,S),y.emeController=this.emeController=this.createController(t.emeController,S),this.cmcdController=this.createController(t.cmcdController,S),this.latencyController=this.createController(_n,S),this.coreComponents=S,E.push(o);const w=o.onErrorOut;"function"==typeof w&&this.on(tr.ERROR,w,o)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(lr.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const i=e===tr.ERROR;this.trigger(tr.ERROR,{type:ir.OTHER_ERROR,details:rr.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){lr.log("destroy"),this.trigger(tr.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){lr.log("attachMedia"),this._media=e,this.trigger(tr.MEDIA_ATTACHING,{media:e})}detachMedia(){lr.log("detachMedia"),this.trigger(tr.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,r=this.url=Wi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,lr.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(tr.MANIFEST_LOADING,{url:e})}startLoad(e=-1){lr.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){lr.log("stopLoad"),this.started=!1,this.networkControllers.forEach((e=>{e.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((e=>{"fragmentLoader"in e&&e.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((e=>{"fragmentLoader"in e&&e.stopLoad()}))}swapAudioCodec(){lr.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){lr.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){lr.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){lr.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){lr.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){lr.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){lr.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(lr.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return Dn.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let r=0;r=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let r;if(r=-1===t&&null!=e&&e.length?e.length-1:t,i)for(let t=r;t--;){const r=e[t].attrs["HDCP-LEVEL"];if(r&&r<=i)return t}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return null==(t=this.audioTrackController)?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return null==(t=this.subtitleTrackController)||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}function Rc(e,t,i){return t&&function(e,t){for(var i=0;i0&&(e.$video.volume=e._options.volume)}),1e3)})),e.event.emit("parsed")}))}))}else if(this.$video.canPlayType("application/vnd.apple.mpegurl")){this.logger.log("Browser support application/vnd.apple.mpegurl : ",this.$video.canPlayType("application/vnd.apple.mpegurl")),this.$video.src=this._options.url;var i=!1;this.$video.addEventListener("canplay",(function(){!i&&e._options.autoPlay&&setTimeout((function(){e.$video.play().then((function(){e.logger.log("autoPlay video!"),setTimeout((function(){e._options.volume>0&&e.setVolume(e._options.volume)}),1e3),i=!0}))}),200)}))}else this.logger.warn("Browser not support hls")},i.isPlayingState=function(){return!this.$video.paused},i.play=function(){if(this.isPlayingState())return Promise.resolve();if(this._options.isLive&&(this.$video.buffered.length>=1&&this.$video.buffered.end(0)>1)){var e=this.$video.buffered.end(0)-1;this.$video.currentTime=e}return this.$video.play()},i.pause=function(){this.$video.pause()},i.setVolume=function(e){this.$video.muted&&(this.$video.muted=!1),this._volume=+(e||0),0===this._volume&&(this.$video.muted=!0),this.$video.volume=this._volume},i.destroy=function(){this.$video&&this.$video.pause(),this._hls&&(this._hls.destroy(),this._hls=null),e.prototype.destroy.call(this)},i._onEvent=function(){var e;(e=this).$video&&(e.$video.addEventListener("canplay",(function(){e.event.emit("canplay")})),e.$video.addEventListener("loadeddata",(function(){e.event.emit("loadeddata")})),e.$video.addEventListener("volumechange",(function(){e.event.emit("volumechange",{data:e.$video.volume})})),e.$video.addEventListener("waiting",(function(){e.event.emit("waiting")})),e.$video.addEventListener("timeupdate",(function(){var t;null==(t=e.event)||t.emit("timeupdate")})),e.$video.addEventListener("seeking",(function(){e.event.emit("seeking",{data:e.$video.currentTime})})),e.$video.addEventListener("seeked",(function(){e.event.emit("seeked")})),e.$video.addEventListener("abort",(function(){e.event.emit("abort")})),e.$video.addEventListener("error",(function(){var t;null==(t=e.event)||t.emit("error",{data:e.$video.error})})),e.$video.addEventListener("ended",(function(){e.event.emit("ended")})))},Rc(t,[{key:"volume",get:function(){return this._volume},set:function(e){this.setVolume(e)}}]),t}(Ri);var xc="wasm_loaded",Cc="wasm_failed",Ic="init";function Pc(e,t){return Pc=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Pc(e,t)}var Oc=function(e){function t(t){var i;return void 0===t&&(t={}),i=e.call(this,t)||this,t.url=function(e,t){void 0===t&&(t=["h264"]);var i=(t||["h264"]).reduce((function(e,t){return t=t.toLowerCase(),e+(Xt[t]||0)}),0),r=e.split("?")[0],s=e.split("?")[1];return s=(s||"").split("&").filter((function(e){return!/^vc=\d?/.test(e)})).join("&"),r+"?"+s+(s?"&":"")+"vc="+i}(null==t?void 0:t.url,["h264","h265"]),function(e,t){if(((null==t?void 0:t.volume)||0)>1?e._volume=1:((null==t?void 0:t.volume)||0)<=0?e._volume=0:e._volume=+((null==t?void 0:t.volume)||0),t.volume=e._volume,e.options=zt({},wi,t),"string"!=typeof e.options.id)throw new Error("id is required!");e.logger=z(e.options.loggerOptions),e.event=new ei,e.logger.log("HlsPlayer version: ",Uc.version),e.logger.log("HlsPlayer options: ",e.options),e.options.logger=e.logger}(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(i),t),i._containerClassName=Li+"-container",i._render(),i}!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&Pc(e,t)}(t,e);var i=t.prototype;return i._render=function(){this.$container.classList.add(this._containerClassName)},i.destroy=function(){this.$container&&(this.$container.classList.remove(this._containerClassName),this.$container.innerHTML="",this.$container=null)},t}(Si);function Mc(e,t,i){return t&&function(e,t){for(var i=0;i0&&(e=!0),this.playParam={durationMs:0,fps:0,sampleRate:0,size:{width:0,height:0},audioNone:e,videoCodec:T},!A())throw new Error("Browser not support WebAssembly!");this._onWorkerMessage()},i.play=function(){if(Ui.send(1,{name:"play"}),null===this.player)return Promise.resolve();if(this.playParam.videoCodec===T){var e={seekPos:0,isLive:this.options.isLive,accurateSeek:!0,seekEvent:!1,realPlay:!0};return this.player.play(e)}return this.player.play()},i.pause=function(){return Ui.send(1,{name:"pause"}),null!==this.player&&(this.player.pause(),!0)},i.destroy=function(){var t,i;return Ui.send(1,{name:"destroy"}),void 0!==this.player&&null!==this.player&&(this.playParam.videoCodec===T&&this._m3u8Obj&&(this._m3u8Obj.destroy(),this._m3u8Obj=null),this.player.destroy(),this._decoderWorker&&(this._decoderWorker.postMessage(P(B)),this._decoderWorker.terminate(),this._decoderWorker=null),this.logger.log("destroy"),null==(i=this.event)||null==(t=i.emit)||t.call(i,"destroy"),this.player=null,e.prototype.destroy.call(this),!0)},i.isPlaying=function(){return null!==this.player&&this.player.isPlayingState()},i.setVolume=function(e){var t;(e=+e)>1||e<0?this.logger.warn("volume volume value 0.0 ~ 1.0!"):((t=this).player||(t.event.emit("playerIsNull"),t.logger.warn("Player instance does not exist!"),0))&&(this.player.setVolume(e),this.event.emit("volumeChange",{data:e}))},i.getVersion=function(){return Ui.send(1,{name:"getVersion"}),"0.1.0"},i._m3u8Entry=function(){var e=this;this._m3u8Obj=new Vi({logger:this.logger,decoderWorker:this._decoderWorker,event:this.event}),this._m3u8Obj.bindReady(this),this._m3u8Obj.onFinished=function(e,t){},this._m3u8Obj.onCacheProcess=function(t){e.options.isLive||null==e.onCacheProcess||e.onCacheProcess.call(e,t)},this._m3u8Obj.onDemuxed=this._checkPlayer.bind(this),this._m3u8Obj.onSamples=this._hlsOnSamples.bind(this),this._m3u8Obj.demux(this.url)},i._checkPlayer=function(e,t){var i=this;if(null==i.player){var r,s,n;if(!(null==i||null==(r=i._m3u8Obj)?void 0:r.isHevcParam)||t)return null==i||null==(n=i._m3u8Obj)||null==(s=n.destroy)||s.call(n),i._m3u8Obj=null,this._decoderWorker.terminate(),this._decoderWorker=null,void(i.player=new Dc(Fc({},this.options,{event:this.event,logger:this.logger})));var a=i._m3u8Obj.getACodec(),o=i._m3u8Obj.getFPS(),l=i._m3u8Obj.getSampleRate(),h=i._m3u8Obj.getSize(),c=!1;c=i._m3u8Obj.getSampleChannel()<=0||""===a,i._softPlayer(0,o,l,h,c)}},i._hlsOnSamples=function(e,t){var i,r,s,n=this;if(t.video)null==(s=n.player)||null==(r=s.appendHevcFrame)||r.call(s,t);else if(!(null==(i=n._m3u8Obj)?void 0:i.audioNone)){var a,o;null==(o=n.player)||null==(a=o.appendAACFrame)||a.call(o,t)}},i._onWorkerMessage=function(){var e=this,i=this;this._decoderWorker.onmessage=function(r){var s=r.data;switch(s.cmd){case O:t.__HLS_WASM_DecoderState__=0;break;case M:t.__HLS_WASM_DecoderState__=1,e.logger.log("Wasm already init over!"),i.event.emit(xc),i._decoderWorker.postMessage(P("registerWasmPlayer")),i._m3u8Entry();break;case F:t.__HLS_WASM_DecoderState__=-1,e.logger.error("Wasm init failed!",s),i.event.emit(Cc,s),Ui.send("wasm",{name:"wasm loading failed"}),i._checkPlayer(!0)}}},i._softPlayer=function(e,t,i,r,s,n){var a,o,l=this;void 0===s&&(s=!1),void 0===n&&(n=null);var c,d=this;(this.playParam.durationMs=e,this.playParam.fps=t,this.playParam.sampleRate=i,this.playParam.size=r,this.playParam.audioNone=s,this.playParam.videoCodec=n||T,this.logger.log("this.playParam: ",this.playParam),this.logger.log("start init soft player"),this.player=new xi(Fc({},d.options,{sampleRate:i,fps:t,appendHevcType:h,fixed:!1,id:this.options.id,audioNone:s,videoCodec:n,logger:this.logger,event:this.event,decoderWorker:this._decoderWorker})),this.player.onPlayingTime=function(e){var t;null==d||null==(t=d.onPlayTime)||t.call(d,e)},this.player.onPlayingFinish=function(){var e,t;(l.pause(),null!=l.onPlayFinish)&&(null==(t=l)||null==(e=t.onPlayFinish)||e.call(t))},this.player.onLoadCache=function(){var e,t;null==(t=l)||null==(e=t.onLoadCache)||e.call(t)},this.player.onLoadCacheFinished=function(){var e,t;null==(t=l)||null==(e=t.onLoadCacheFinished)||e.call(t)},null==(a=d.player)||a.setDurationMs(e),null==(o=d.player)||o.setFrameRate(t),null!=d.onReadyShowDone)&&(null==d||null==(c=d.onReadyShowDone)||c.call(d));this.event.emit("parsed"),this.player&&this.options.autoPlay&&this.play()},t.supportType=function(e){if(Ui.send(1,{name:"supportType",options:e}),"hls"===e.type)return!0;if(e.url){var t=e.url;t.startsWith("http://")||t.startsWith("https://")||(t=/^\/\//.test(t)?"http:"+t:location.origin+location.pathname+t);try{return/\.m3u8$/i.test(new URL(t).pathname)}catch(e){}}return!1},Mc(t,[{key:"volume",get:function(){return this.player?this.player.volume:this.options.volume},set:function(e){e=+e,this.setVolume(e)}}]),t}(Oc);return Uc.__HLS_WASM_DecoderState__=0,Uc.version="0.1.0",Uc})); diff --git a/examples/base-app/package.json b/examples/base-app/package.json index 38abc96..a6be6f2 100644 --- a/examples/base-app/package.json +++ b/examples/base-app/package.json @@ -9,6 +9,6 @@ "http-server": "^14.1.1" }, "dependencies": { - "@ezuikit/player-hls": "^0.1.0-alpha.1" + "@ezuikit/player-hls": "^0.1.0" } } diff --git a/examples/base-app/pnpm-lock.yaml b/examples/base-app/pnpm-lock.yaml index 9d15e49..852b579 100644 --- a/examples/base-app/pnpm-lock.yaml +++ b/examples/base-app/pnpm-lock.yaml @@ -6,8 +6,8 @@ settings: dependencies: '@ezuikit/player-hls': - specifier: ^0.1.0-alpha.1 - version: 0.1.0-alpha.1 + specifier: ^0.1.0 + version: 0.1.0 devDependencies: http-server: @@ -16,9 +16,10 @@ devDependencies: packages: - /@ezuikit/player-base@0.1.0-alpha.1: - resolution: {integrity: sha512-68O3PtB5g7hm+HSpCqE/ef/Ud0xUPsFv3ckrj6VKm7wyed+9aqTazxv8mDPOXuNStZZULpfn+7Uf0KW7cHAyxg==} + /@ezuikit/player-base@0.1.0: + resolution: {integrity: sha512-IcJqnZr9FmjBCnIrmqY7oHdyDuYxRWhDZB+K+gi+4oenFjFV4aLCCG7RFPxkidHzi3TTF2f1Bm5yObZzNDqkfw==} dependencies: + '@ezuikit/utils-collect': 0.1.0 '@ezuikit/utils-logger': 1.0.1 '@ezuikit/utils-tools': 1.0.3 eventemitter3: 5.0.1 @@ -27,10 +28,10 @@ packages: ua-parser-js: 1.0.37 dev: false - /@ezuikit/player-hls@0.1.0-alpha.1: - resolution: {integrity: sha512-DcR5B3JBwY9pT+wRapk5B8ntqYdHkXjj+S0GfS2Ler41+g/l6YaSC/LsWh525bVRbfMGDxhUD9WBK01CoHn1Bw==} + /@ezuikit/player-hls@0.1.0: + resolution: {integrity: sha512-T5PCj65mw3mP1MpfJOrx/MXpNZFMrW37fjjYnil1rCuy6ACGBNWXFVvOlzuh5k7G4DFV+HjbbMJnG21icNdZnw==} dependencies: - '@ezuikit/player-base': 0.1.0-alpha.1 + '@ezuikit/player-base': 0.1.0 '@ezuikit/utils-collect': 0.1.0 '@ezuikit/utils-i18n': 1.0.1 '@ezuikit/utils-logger': 1.0.1 diff --git a/examples/react-app/package.json b/examples/react-app/package.json index 4e19c4c..6553cef 100644 --- a/examples/react-app/package.json +++ b/examples/react-app/package.json @@ -6,7 +6,7 @@ "@testing-library/jest-dom": "^5.17.0", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", - "@ezuikit/player-hls": "^0.1.0-alpha.1", + "@ezuikit/player-hls": "^0.1.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "5.0.1", diff --git a/examples/react-app/pnpm-lock.yaml b/examples/react-app/pnpm-lock.yaml index f216f14..67ab204 100644 --- a/examples/react-app/pnpm-lock.yaml +++ b/examples/react-app/pnpm-lock.yaml @@ -6,8 +6,8 @@ settings: dependencies: '@ezuikit/player-hls': - specifier: ^0.1.0-alpha.1 - version: 0.1.0-alpha.1 + specifier: ^0.1.0 + version: 0.1.0 '@testing-library/jest-dom': specifier: ^5.17.0 version: 5.17.0 @@ -1782,9 +1782,10 @@ packages: engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} dev: false - /@ezuikit/player-base@0.1.0-alpha.1: - resolution: {integrity: sha512-68O3PtB5g7hm+HSpCqE/ef/Ud0xUPsFv3ckrj6VKm7wyed+9aqTazxv8mDPOXuNStZZULpfn+7Uf0KW7cHAyxg==} + /@ezuikit/player-base@0.1.0: + resolution: {integrity: sha512-IcJqnZr9FmjBCnIrmqY7oHdyDuYxRWhDZB+K+gi+4oenFjFV4aLCCG7RFPxkidHzi3TTF2f1Bm5yObZzNDqkfw==} dependencies: + '@ezuikit/utils-collect': 0.1.0 '@ezuikit/utils-logger': 1.0.1 '@ezuikit/utils-tools': 1.0.3 eventemitter3: 5.0.1 @@ -1793,11 +1794,11 @@ packages: ua-parser-js: 1.0.37 dev: false - /@ezuikit/player-hls@0.1.0-alpha.1: - resolution: {integrity: sha512-DcR5B3JBwY9pT+wRapk5B8ntqYdHkXjj+S0GfS2Ler41+g/l6YaSC/LsWh525bVRbfMGDxhUD9WBK01CoHn1Bw==} + /@ezuikit/player-hls@0.1.0: + resolution: {integrity: sha512-T5PCj65mw3mP1MpfJOrx/MXpNZFMrW37fjjYnil1rCuy6ACGBNWXFVvOlzuh5k7G4DFV+HjbbMJnG21icNdZnw==} dependencies: - '@ezuikit/player-base': 0.1.0-alpha.1 - '@ezuikit/utils-collect': 0.1.0-beta.1 + '@ezuikit/player-base': 0.1.0 + '@ezuikit/utils-collect': 0.1.0 '@ezuikit/utils-i18n': 1.0.1 '@ezuikit/utils-logger': 1.0.1 '@ezuikit/utils-tools': 1.0.3 @@ -1809,8 +1810,8 @@ packages: ua-parser-js: 1.0.37 dev: false - /@ezuikit/utils-collect@0.1.0-beta.1: - resolution: {integrity: sha512-+kkEkOVM9bQkWp90ppFpEwuaG8sRCH/F3CamLLgS0CG18gk1Fb5lcvS21hklgxMjS5tLotjwlfs0j+pQydzRYA==} + /@ezuikit/utils-collect@0.1.0: + resolution: {integrity: sha512-85lWlB/VCaooPPkCK3nEB4F3UKgO+HbmoPEq4U1tH/ObVP7IJ7eURrFUmQT1CKsqjH5xz5g4DgZzHWgYrwGcCQ==} dev: false /@ezuikit/utils-i18n@1.0.1: diff --git a/examples/react-app/public/decoder.wasm b/examples/react-app/public/decoder.wasm new file mode 100644 index 0000000..5c0c2fa Binary files /dev/null and b/examples/react-app/public/decoder.wasm differ diff --git a/examples/react-app/public/decoder.worker.js b/examples/react-app/public/decoder.worker.js new file mode 100644 index 0000000..e229e81 --- /dev/null +++ b/examples/react-app/public/decoder.worker.js @@ -0,0 +1,8 @@ +/* +* +* DecoderWorker.js v0.1.0-beta.1 +* Copyright (c) 2024-8-1 Ezviz-OpenBiz +* . +* +*/ +!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";var e={DEFAULT_SAMPLERATE:44100,DEFAULT_CHANNEL:1,H264AUD:[0,0,0,1,9,224],H265AUD:[0,0,0,1,70,1,80],DEF_AAC:"aac",DEF_MP3:"mp3",DEF_H265:"h265",DEF_HEVC:"hevc",DEF_H264:"h264",DEF_AVC:"avc",CODEC_OFFSET_TABLE:["hevc","h265","avc","h264","aac","mp3"]};function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t={exports:{}};!function(e,r){function t(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var d,f,p=(f="undefined"!=typeof document?null==(d=document.currentScript)?void 0:d.src:void 0,function(e){var r,t=function(){var r=dr.value;r in e||Object.defineProperty(e,r,{configurable:!0,get:function(){q("Access to module property ('"+r+"') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.")}})};void 0===e&&(e={});var n,i,d=Object.assign({},e),p=new Promise((function(e,r){n=e,i=r}));["_malloc","_free","_memory","_registerWasmPlayer","_setCodecType","_exitWasmPlayer","_initDecoder","_decodeCodecContext","_destroy","_demuxTsStream","_getPacket","_getVLCLen","_getVLC","_getVPSLen","_getVPS","_getSPSLen","_getSPS","_getPPSLen","_getPPS","_getSEILen","_getSEI","___indirect_function_table","_ff_h264_cabac_tables","onRuntimeInitialized"].forEach((function(e){Object.getOwnPropertyDescriptor(p,e)||Object.defineProperty(p,e,{get:function(){return q("You are getting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")},set:function(){return q("You are setting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")}})}));var m="object"==("undefined"==typeof window?"undefined":u(window)),h="function"==typeof importScripts,g="object"==("undefined"==typeof process?"undefined":u(process))&&"object"==u(process.versions)&&"string"==typeof process.versions.node,v=!m&&!g&&!h;if(d.ENVIRONMENT)throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");var E,y,w,b=Object.assign({},d),_="./this.program",S="";if(v){if("object"==("undefined"==typeof process?"undefined":u(process))||"object"==("undefined"==typeof window?"undefined":u(window))||"function"==typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)")}else{if(!m&&!h)throw new Error("environment detection error");if(h?S=self.location.href:"undefined"!=typeof document&&document.currentScript&&(S=document.currentScript.src),f&&(S=f),S=S.startsWith("blob:")?"":S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1),"object"!=("undefined"==typeof window?"undefined":u(window))&&"function"!=typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");E=function(e){var r=new XMLHttpRequest;return r.open("GET",e,!1),r.send(null),r.responseText},h&&(w=function(e){var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),y=function(e,r,t){var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=function(){200==n.status||0==n.status&&n.response?r(n.response):t()},n.onerror=t,n.send(null)}}var O,T,k,A=d.print||console.log.bind(console),M=d.printErr||console.error.bind(console);Object.assign(d,b),b=null,O="fetchSettings",Object.getOwnPropertyDescriptor(d,O)&&q("`Module."+O+"` was supplied but `"+O+"` not included in INCOMING_MODULE_JS_API"),d.arguments&&d.arguments,ie("arguments","arguments_"),d.thisProgram&&(_=d.thisProgram),ie("thisProgram","thisProgram"),d.quit&&d.quit,ie("quit","quit_"),L(void 0===d.memoryInitializerPrefixURL,"Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.pthreadMainPrefixURL,"Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.cdInitializerPrefixURL,"Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.filePackagePrefixURL,"Module.filePackagePrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.read,"Module.read option was removed (modify read_ in JS)"),L(void 0===d.readAsync,"Module.readAsync option was removed (modify readAsync in JS)"),L(void 0===d.readBinary,"Module.readBinary option was removed (modify readBinary in JS)"),L(void 0===d.setWindowTitle,"Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"),L(void 0===d.TOTAL_MEMORY,"Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"),ie("asm","wasmExports"),ie("read","read_"),ie("readAsync","readAsync"),ie("readBinary","readBinary"),ie("setWindowTitle","setWindowTitle"),L(!g,"node environment detected but not enabled at build time. Add `node` to `-sENVIRONMENT` to enable."),L(!v,"shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable."),d.wasmBinary&&(T=d.wasmBinary),ie("wasmBinary","wasmBinary"),"object"!=("undefined"==typeof WebAssembly?"undefined":u(WebAssembly))&&M("no native wasm support detected");var P,F,C,D,x,I=!1;function L(e,r){e||q("Assertion failed"+(r?": "+r:""))}function N(){var e=k.buffer;d.HEAP8=P=new Int8Array(e),d.HEAP16=C=new Int16Array(e),d.HEAPU8=F=new Uint8Array(e),d.HEAPU16=new Uint16Array(e),d.HEAP32=D=new Int32Array(e),d.HEAPU32=x=new Uint32Array(e),d.HEAPF32=new Float32Array(e),d.HEAPF64=new Float64Array(e)}function R(){if(!I){var e=ir();0==e&&(e+=4);var r=x[e>>2],t=x[e+4>>2];34821223==r&&2310721022==t||q("Stack overflow! Stack cookie has been overwritten at "+le(e)+", expected hex dwords 0x89BACDFE and 0x2135467, but received "+le(t)+" "+le(r)),1668509029!=x[0]&&q("Runtime error: The application has corrupted its heap memory area (address zero)!")}}L(!d.STACK_SIZE,"STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"),L("undefined"!=typeof Int32Array&&"undefined"!=typeof Float64Array&&null!=Int32Array.prototype.subarray&&null!=Int32Array.prototype.set,"JS engine does not provide full typed array support"),L(!d.wasmMemory,"Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"),L(!d.INITIAL_MEMORY,"Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically"),function(){var e=new Int16Array(1),r=new Int8Array(e.buffer);if(e[0]=25459,115!==r[0]||99!==r[1])throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"}();var U=[],B=[],j=[],$=!1;L(Math.imul,"This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.fround,"This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.clz32,"This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.trunc,"This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");var W=0,H=null,z=null,V={};function G(e){for(var r=e;;){if(!V[e])return e;e=r+Math.random()}}function Y(e){var r;W++,null==(r=d.monitorRunDependencies)||r.call(d,W),e?(L(!V[e]),V[e]=1,null===H&&"undefined"!=typeof setInterval&&(H=setInterval((function(){if(I)return clearInterval(H),void(H=null);var e=!1;for(var r in V)e||(e=!0,M("still waiting on run dependencies:")),M("dependency: "+r);e&&M("(end of list)")}),1e4))):M("warning: run dependency added without ID")}function Q(e){var r;if(W--,null==(r=d.monitorRunDependencies)||r.call(d,W),e?(L(V[e]),delete V[e]):M("warning: run dependency removed without ID"),0==W&&(null!==H&&(clearInterval(H),H=null),z)){var t=z;z=null,t()}}function q(e){var r;null==(r=d.onAbort)||r.call(d,e),M(e="Aborted("+e+")"),I=!0;var t=new WebAssembly.RuntimeError(e);throw i(t),t}var K,X,J,Z=function(e){return e.startsWith("data:application/octet-stream;base64,")},ee=function(e){return e.startsWith("file://")};function re(e,r){return function(){for(var t=arguments.length,n=new Array(t),o=0;o0;)e.shift()(d)};d.noExitRuntime;var le=function(e){return L("number"==typeof e),"0x"+(e>>>=0).toString(16).padStart(8,"0")},de=function(e){var r;(r=de).shown||(r.shown={}),de.shown[e]||(de.shown[e]=1,M(e))};function fe(){L(null!=xe.varargs);var e=D[+xe.varargs>>2];return xe.varargs+=4,e}var pe=fe,me={isAbs:function(e){return"/"===e.charAt(0)},splitPath:function(e){return/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1)},normalizeArray:function(e,r){for(var t=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),t++):t&&(e.splice(n,1),t--)}if(r)for(;t;t--)e.unshift("..");return e},normalize:function(e){var r=me.isAbs(e),t="/"===e.substr(-1);return(e=me.normalizeArray(e.split("/").filter((function(e){return!!e})),!r).join("/"))||r||(e="."),e&&t&&(e+="/"),(r?"/":"")+e},dirname:function(e){var r=me.splitPath(e),t=r[0],n=r[1];return t||n?(n&&(n=n.substr(0,n.length-1)),t+n):"."},basename:function(e){if("/"===e)return"/";var r=(e=(e=me.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===r?e:e.substr(r+1)},join:function(){for(var e=arguments.length,r=new Array(e),t=0;t { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };")}())(e)},ge={resolve:function(){for(var e=arguments.length,r=new Array(e),t=0;t=-1&&!o;i--){var a=i>=0?r[i]:Ce.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");if(!a)return"";n=a+"/"+n,o=me.isAbs(a)}return(o?"/":"")+(n=me.normalizeArray(n.split("/").filter((function(e){return!!e})),!o).join("/"))||"."},relative:function(e,r){var t=function(e){for(var r=0;r=0&&""===e[t];t--);return r>t?[]:e.slice(r,t-r+1)};e=ge.resolve(e).substr(1),r=ge.resolve(r).substr(1);for(var n=t(e.split("/")),o=t(r.split("/")),i=Math.min(n.length,o.length),a=i,s=0;s=n);)++o;if(o-r>16&&e.buffer&&ve)return ve.decode(e.subarray(r,o));for(var i="";r>10,56320|1023&c)}}else i+=String.fromCharCode((31&a)<<6|s)}else i+=String.fromCharCode(a)}return i},ye=[],we=function(e){for(var r=0,t=0;t=55296&&n<=57343?(r+=4,++t):r+=3}return r},be=function(e,r,t,n){if(L("string"==typeof e,"stringToUTF8Array expects a string (got "+(void 0===e?"undefined":u(e))+")"),!(n>0))return 0;for(var o=t,i=t+n-1,a=0;a=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),s<=127){if(t>=i)break;r[t++]=s}else if(s<=2047){if(t+1>=i)break;r[t++]=192|s>>6,r[t++]=128|63&s}else if(s<=65535){if(t+2>=i)break;r[t++]=224|s>>12,r[t++]=128|s>>6&63,r[t++]=128|63&s}else{if(t+3>=i)break;s>1114111&&de("Invalid Unicode code point "+le(s)+" encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."),r[t++]=240|s>>18,r[t++]=128|s>>12&63,r[t++]=128|s>>6&63,r[t++]=128|63&s}}return r[t]=0,t-o};function _e(e,r,t){var n=we(e)+1,o=new Array(n),i=be(e,o,0,o.length);return o.length=i,o}var Se,Oe={ttys:[],init:function(){},shutdown:function(){},register:function(e,r){Oe.ttys[e]={input:[],output:[],ops:r},Ce.registerDevice(e,Oe.stream_ops)},stream_ops:{open:function(e){var r=Oe.ttys[e.node.rdev];if(!r)throw new Ce.ErrnoError(43);e.tty=r,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,r,t,n,o){if(!e.tty||!e.tty.ops.get_char)throw new Ce.ErrnoError(60);for(var i=0,a=0;a0&&(A(Ee(e.output,0)),e.output=[])},ioctl_tcgets:function(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(e,r,t){return 0},ioctl_tiocgwinsz:function(e){return[24,80]}},default_tty1_ops:{put_char:function(e,r){null===r||10===r?(M(Ee(e.output,0)),e.output=[]):0!=r&&e.output.push(r)},fsync:function(e){e.output&&e.output.length>0&&(M(Ee(e.output,0)),e.output=[])}}},Te=function(e){q("internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported")},ke={ops_table:null,mount:function(e){return ke.createNode(null,"/",16895,0)},createNode:function(e,r,t,n){var o;if(Ce.isBlkdev(t)||Ce.isFIFO(t))throw new Ce.ErrnoError(63);(o=ke).ops_table||(o.ops_table={dir:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr,lookup:ke.node_ops.lookup,mknod:ke.node_ops.mknod,rename:ke.node_ops.rename,unlink:ke.node_ops.unlink,rmdir:ke.node_ops.rmdir,readdir:ke.node_ops.readdir,symlink:ke.node_ops.symlink},stream:{llseek:ke.stream_ops.llseek}},file:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr},stream:{llseek:ke.stream_ops.llseek,read:ke.stream_ops.read,write:ke.stream_ops.write,allocate:ke.stream_ops.allocate,mmap:ke.stream_ops.mmap,msync:ke.stream_ops.msync}},link:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr,readlink:ke.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr},stream:Ce.chrdev_stream_ops}});var i=Ce.createNode(e,r,t,n);return Ce.isDir(i.mode)?(i.node_ops=ke.ops_table.dir.node,i.stream_ops=ke.ops_table.dir.stream,i.contents={}):Ce.isFile(i.mode)?(i.node_ops=ke.ops_table.file.node,i.stream_ops=ke.ops_table.file.stream,i.usedBytes=0,i.contents=null):Ce.isLink(i.mode)?(i.node_ops=ke.ops_table.link.node,i.stream_ops=ke.ops_table.link.stream):Ce.isChrdev(i.mode)&&(i.node_ops=ke.ops_table.chrdev.node,i.stream_ops=ke.ops_table.chrdev.stream),i.timestamp=Date.now(),e&&(e.contents[r]=i,e.timestamp=i.timestamp),i},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,r){var t=e.contents?e.contents.length:0;if(!(t>=r)){r=Math.max(r,t*(t<1048576?2:1.125)>>>0),0!=t&&(r=Math.max(r,256));var n=e.contents;e.contents=new Uint8Array(r),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,r){if(e.usedBytes!=r)if(0==r)e.contents=null,e.usedBytes=0;else{var t=e.contents;e.contents=new Uint8Array(r),t&&e.contents.set(t.subarray(0,Math.min(r,e.usedBytes))),e.usedBytes=r}},node_ops:{getattr:function(e){var r={};return r.dev=Ce.isChrdev(e.mode)?e.id:1,r.ino=e.id,r.mode=e.mode,r.nlink=1,r.uid=0,r.gid=0,r.rdev=e.rdev,Ce.isDir(e.mode)?r.size=4096:Ce.isFile(e.mode)?r.size=e.usedBytes:Ce.isLink(e.mode)?r.size=e.link.length:r.size=0,r.atime=new Date(e.timestamp),r.mtime=new Date(e.timestamp),r.ctime=new Date(e.timestamp),r.blksize=4096,r.blocks=Math.ceil(r.size/r.blksize),r},setattr:function(e,r){void 0!==r.mode&&(e.mode=r.mode),void 0!==r.timestamp&&(e.timestamp=r.timestamp),void 0!==r.size&&ke.resizeFileStorage(e,r.size)},lookup:function(e,r){throw Ce.genericErrors[44]},mknod:function(e,r,t,n){return ke.createNode(e,r,t,n)},rename:function(e,r,t){if(Ce.isDir(e.mode)){var n;try{n=Ce.lookupNode(r,t)}catch(e){}if(n)for(var o in n.contents)throw new Ce.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=t,r.contents[t]=e,r.timestamp=e.parent.timestamp,e.parent=r},unlink:function(e,r){delete e.contents[r],e.timestamp=Date.now()},rmdir:function(e,r){var t=Ce.lookupNode(e,r);for(var n in t.contents)throw new Ce.ErrnoError(55);delete e.contents[r],e.timestamp=Date.now()},readdir:function(e){for(var r,t=[".",".."],n=l(Object.keys(e.contents));!(r=n()).done;){var o=r.value;t.push(o)}return t},symlink:function(e,r,t){var n=ke.createNode(e,r,41471,0);return n.link=t,n},readlink:function(e){if(!Ce.isLink(e.mode))throw new Ce.ErrnoError(28);return e.link}},stream_ops:{read:function(e,r,t,n,o){var i=e.node.contents;if(o>=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,n);if(L(a>=0),a>8&&i.subarray)r.set(i.subarray(o,o+a),t);else for(var s=0;s0||t+r8)throw new Ce.ErrnoError(32);for(var t=e.split("/").filter((function(e){return!!e})),n=Ce.root,o="/",i=0;i40)throw new Ce.ErrnoError(32)}}return{path:o,node:n}},getPath:function(e){for(var r;;){if(Ce.isRoot(e)){var t=e.mount.mountpoint;return r?"/"!==t[t.length-1]?t+"/"+r:t+r:t}r=r?e.name+"/"+r:e.name,e=e.parent}},hashName:function(e,r){for(var t=0,n=0;n>>0)%Ce.nameTable.length},hashAddNode:function(e){var r=Ce.hashName(e.parent.id,e.name);e.name_next=Ce.nameTable[r],Ce.nameTable[r]=e},hashRemoveNode:function(e){var r=Ce.hashName(e.parent.id,e.name);if(Ce.nameTable[r]===e)Ce.nameTable[r]=e.name_next;else for(var t=Ce.nameTable[r];t;){if(t.name_next===e){t.name_next=e.name_next;break}t=t.name_next}},lookupNode:function(e,r){var t=Ce.mayLookup(e);if(t)throw new Ce.ErrnoError(t);for(var n=Ce.hashName(e.id,r),o=Ce.nameTable[n];o;o=o.name_next){var i=o.name;if(o.parent.id===e.id&&i===r)return o}return Ce.lookup(e,r)},createNode:function(e,r,t,n){L("object"==(void 0===e?"undefined":u(e)));var o=new Ce.FSNode(e,r,t,n);return Ce.hashAddNode(o),o},destroyNode:function(e){Ce.hashRemoveNode(e)},isRoot:function(e){return e===e.parent},isMountpoint:function(e){return!!e.mounted},isFile:function(e){return 32768==(61440&e)},isDir:function(e){return 16384==(61440&e)},isLink:function(e){return 40960==(61440&e)},isChrdev:function(e){return 8192==(61440&e)},isBlkdev:function(e){return 24576==(61440&e)},isFIFO:function(e){return 4096==(61440&e)},isSocket:function(e){return!(49152&~e)},flagsToPermissionString:function(e){var r=["r","w","rw"][3&e];return 512&e&&(r+="w"),r},nodePermissions:function(e,r){return Ce.ignorePermissions||(!r.includes("r")||292&e.mode)&&(!r.includes("w")||146&e.mode)&&(!r.includes("x")||73&e.mode)?0:2},mayLookup:function(e){if(!Ce.isDir(e.mode))return 54;var r=Ce.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate:function(e,r){try{return Ce.lookupNode(e,r),20}catch(e){}return Ce.nodePermissions(e,"wx")},mayDelete:function(e,r,t){var n;try{n=Ce.lookupNode(e,r)}catch(e){return e.errno}var o=Ce.nodePermissions(e,"wx");if(o)return o;if(t){if(!Ce.isDir(n.mode))return 54;if(Ce.isRoot(n)||Ce.getPath(n)===Ce.cwd())return 10}else if(Ce.isDir(n.mode))return 31;return 0},mayOpen:function(e,r){return e?Ce.isLink(e.mode)?32:Ce.isDir(e.mode)&&("r"!==Ce.flagsToPermissionString(r)||512&r)?31:Ce.nodePermissions(e,Ce.flagsToPermissionString(r)):44},MAX_OPEN_FDS:4096,nextfd:function(){for(var e=0;e<=Ce.MAX_OPEN_FDS;e++)if(!Ce.streams[e])return e;throw new Ce.ErrnoError(33)},getStreamChecked:function(e){var r=Ce.getStream(e);if(!r)throw new Ce.ErrnoError(8);return r},getStream:function(e){return Ce.streams[e]},createStream:function(e,r){return void 0===r&&(r=-1),e=Object.assign(new Ce.FSStream,e),-1==r&&(r=Ce.nextfd()),e.fd=r,Ce.streams[r]=e,e},closeStream:function(e){Ce.streams[e]=null},dupStream:function(e,r){var t,n;void 0===r&&(r=-1);var o=Ce.createStream(e,r);return null==(n=o.stream_ops)||null==(t=n.dup)||t.call(n,o),o},chrdev_stream_ops:{open:function(e){var r=Ce.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,null==e.stream_ops.open||e.stream_ops.open.call(e.stream_ops,e)},llseek:function(){throw new Ce.ErrnoError(70)}},major:function(e){return e>>8},minor:function(e){return 255&e},makedev:function(e,r){return e<<8|r},registerDevice:function(e,r){Ce.devices[e]={stream_ops:r}},getDevice:function(e){return Ce.devices[e]},getMounts:function(e){for(var r=[],t=[e];t.length;){var n,o=t.pop();r.push(o),(n=t).push.apply(n,[].concat(o.mounts))}return r},syncfs:function(e,r){"function"==typeof e&&(r=e,e=!1),Ce.syncFSRequests++,Ce.syncFSRequests>1&&M("warning: "+Ce.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var t=Ce.getMounts(Ce.root.mount),n=0;function o(e){return L(Ce.syncFSRequests>0),Ce.syncFSRequests--,r(e)}function i(e){if(e)return i.errored?void 0:(i.errored=!0,o(e));++n>=t.length&&o(null)}t.forEach((function(r){if(!r.type.syncfs)return i(null);r.type.syncfs(r,e,i)}))},mount:function(e,r,t){if("string"==typeof e)throw e;var n,o="/"===t,i=!t;if(o&&Ce.root)throw new Ce.ErrnoError(10);if(!o&&!i){var a=Ce.lookupPath(t,{follow_mount:!1});if(t=a.path,n=a.node,Ce.isMountpoint(n))throw new Ce.ErrnoError(10);if(!Ce.isDir(n.mode))throw new Ce.ErrnoError(54)}var s={type:e,opts:r,mountpoint:t,mounts:[]},u=e.mount(s);return u.mount=s,s.root=u,o?Ce.root=u:n&&(n.mounted=s,n.mount&&n.mount.mounts.push(s)),u},unmount:function(e){var r=Ce.lookupPath(e,{follow_mount:!1});if(!Ce.isMountpoint(r.node))throw new Ce.ErrnoError(28);var t=r.node,n=t.mounted,o=Ce.getMounts(n);Object.keys(Ce.nameTable).forEach((function(e){for(var r=Ce.nameTable[e];r;){var t=r.name_next;o.includes(r.mount)&&Ce.destroyNode(r),r=t}})),t.mounted=null;var i=t.mount.mounts.indexOf(n);L(-1!==i),t.mount.mounts.splice(i,1)},lookup:function(e,r){return e.node_ops.lookup(e,r)},mknod:function(e,r,t){var n=Ce.lookupPath(e,{parent:!0}).node,o=me.basename(e);if(!o||"."===o||".."===o)throw new Ce.ErrnoError(28);var i=Ce.mayCreate(n,o);if(i)throw new Ce.ErrnoError(i);if(!n.node_ops.mknod)throw new Ce.ErrnoError(63);return n.node_ops.mknod(n,o,r,t)},create:function(e,r){return r=void 0!==r?r:438,r&=4095,r|=32768,Ce.mknod(e,r,0)},mkdir:function(e,r){return r=void 0!==r?r:511,r&=1023,r|=16384,Ce.mknod(e,r,0)},mkdirTree:function(e,r){for(var t=e.split("/"),n="",o=0;o=0),n<0||o<0)throw new Ce.ErrnoError(28);if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(1==(2097155&e.flags))throw new Ce.ErrnoError(8);if(Ce.isDir(e.node.mode))throw new Ce.ErrnoError(31);if(!e.stream_ops.read)throw new Ce.ErrnoError(28);var i=void 0!==o;if(i){if(!e.seekable)throw new Ce.ErrnoError(70)}else o=e.position;var a=e.stream_ops.read(e,r,t,n,o);return i||(e.position+=a),a},write:function(e,r,t,n,o,i){if(L(t>=0),n<0||o<0)throw new Ce.ErrnoError(28);if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(!(2097155&e.flags))throw new Ce.ErrnoError(8);if(Ce.isDir(e.node.mode))throw new Ce.ErrnoError(31);if(!e.stream_ops.write)throw new Ce.ErrnoError(28);e.seekable&&1024&e.flags&&Ce.llseek(e,0,2);var a=void 0!==o;if(a){if(!e.seekable)throw new Ce.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,r,t,n,o,i);return a||(e.position+=s),s},allocate:function(e,r,t){if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(r<0||t<=0)throw new Ce.ErrnoError(28);if(!(2097155&e.flags))throw new Ce.ErrnoError(8);if(!Ce.isFile(e.node.mode)&&!Ce.isDir(e.node.mode))throw new Ce.ErrnoError(43);if(!e.stream_ops.allocate)throw new Ce.ErrnoError(138);e.stream_ops.allocate(e,r,t)},mmap:function(e,r,t,n,o){if(2&n&&!(2&o)&&2!=(2097155&e.flags))throw new Ce.ErrnoError(2);if(1==(2097155&e.flags))throw new Ce.ErrnoError(2);if(!e.stream_ops.mmap)throw new Ce.ErrnoError(43);return e.stream_ops.mmap(e,r,t,n,o)},msync:function(e,r,t,n,o){return L(t>=0),e.stream_ops.msync?e.stream_ops.msync(e,r,t,n,o):0},ioctl:function(e,r,t){if(!e.stream_ops.ioctl)throw new Ce.ErrnoError(59);return e.stream_ops.ioctl(e,r,t)},readFile:function(e,r){if(void 0===r&&(r={}),r.flags=r.flags||0,r.encoding=r.encoding||"binary","utf8"!==r.encoding&&"binary"!==r.encoding)throw new Error('Invalid encoding type "'+r.encoding+'"');var t,n=Ce.open(e,r.flags),o=Ce.stat(e).size,i=new Uint8Array(o);return Ce.read(n,i,0,o,0),"utf8"===r.encoding?t=Ee(i,0):"binary"===r.encoding&&(t=i),Ce.close(n),t},writeFile:function(e,r,t){void 0===t&&(t={}),t.flags=t.flags||577;var n=Ce.open(e,t.flags,t.mode);if("string"==typeof r){var o=new Uint8Array(we(r)+1),i=be(r,o,0,o.length);Ce.write(n,o,0,i,void 0,t.canOwn)}else{if(!ArrayBuffer.isView(r))throw new Error("Unsupported data type");Ce.write(n,r,0,r.byteLength,void 0,t.canOwn)}Ce.close(n)},cwd:function(){return Ce.currentPath},chdir:function(e){var r=Ce.lookupPath(e,{follow:!0});if(null===r.node)throw new Ce.ErrnoError(44);if(!Ce.isDir(r.node.mode))throw new Ce.ErrnoError(54);var t=Ce.nodePermissions(r.node,"x");if(t)throw new Ce.ErrnoError(t);Ce.currentPath=r.path},createDefaultDirectories:function(){Ce.mkdir("/tmp"),Ce.mkdir("/home"),Ce.mkdir("/home/web_user")},createDefaultDevices:function(){Ce.mkdir("/dev"),Ce.registerDevice(Ce.makedev(1,3),{read:function(){return 0},write:function(e,r,t,n,o){return n}}),Ce.mkdev("/dev/null",Ce.makedev(1,3)),Oe.register(Ce.makedev(5,0),Oe.default_tty_ops),Oe.register(Ce.makedev(6,0),Oe.default_tty1_ops),Ce.mkdev("/dev/tty",Ce.makedev(5,0)),Ce.mkdev("/dev/tty1",Ce.makedev(6,0));var e=new Uint8Array(1024),r=0,t=function(){return 0===r&&(r=he(e).byteLength),e[--r]};Ce.createDevice("/dev","random",t),Ce.createDevice("/dev","urandom",t),Ce.mkdir("/dev/shm"),Ce.mkdir("/dev/shm/tmp")},createSpecialDirectories:function(){Ce.mkdir("/proc");var e=Ce.mkdir("/proc/self");Ce.mkdir("/proc/self/fd"),Ce.mount({mount:function(){var r=Ce.createNode(e,"fd",16895,73);return r.node_ops={lookup:function(e,r){var t=+r,n=Ce.getStreamChecked(t),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:function(){return n.path}}};return o.parent=o,o}},r}},{},"/proc/self/fd")},createStandardStreams:function(){d.stdin?Ce.createDevice("/dev","stdin",d.stdin):Ce.symlink("/dev/tty","/dev/stdin"),d.stdout?Ce.createDevice("/dev","stdout",null,d.stdout):Ce.symlink("/dev/tty","/dev/stdout"),d.stderr?Ce.createDevice("/dev","stderr",null,d.stderr):Ce.symlink("/dev/tty1","/dev/stderr");var e=Ce.open("/dev/stdin",0),r=Ce.open("/dev/stdout",1),t=Ce.open("/dev/stderr",1);L(0===e.fd,"invalid handle for stdin ("+e.fd+")"),L(1===r.fd,"invalid handle for stdout ("+r.fd+")"),L(2===t.fd,"invalid handle for stderr ("+t.fd+")")},staticInit:function(){[44].forEach((function(e){Ce.genericErrors[e]=new Ce.ErrnoError(e),Ce.genericErrors[e].stack=""})),Ce.nameTable=new Array(4096),Ce.mount(ke,{},"/"),Ce.createDefaultDirectories(),Ce.createDefaultDevices(),Ce.createSpecialDirectories(),Ce.filesystems={MEMFS:ke}},init:function(e,r,t){L(!Ce.init.initialized,"FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"),Ce.init.initialized=!0,d.stdin=e||d.stdin,d.stdout=r||d.stdout,d.stderr=t||d.stderr,Ce.createStandardStreams()},quit:function(){Ce.init.initialized=!1,tr(0);for(var e=0;ethis.length-1||e<0)){var r=e%this.chunkSize,t=e/this.chunkSize|0;return this.getter(t)[r]}},r.setDataGetter=function(e){this.getter=e},r.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",t,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+t+". Status: "+e.status);var r,n=Number(e.getResponseHeader("Content-length")),o=(r=e.getResponseHeader("Accept-Ranges"))&&"bytes"===r,i=(r=e.getResponseHeader("Content-Encoding"))&&"gzip"===r,a=1048576;o||(a=n);var s=this;s.setDataGetter((function(e){var r=e*a,o=(e+1)*a-1;if(o=Math.min(o,n-1),void 0===s.chunks[e]&&(s.chunks[e]=function(e,r){if(e>r)throw new Error("invalid range ("+e+", "+r+") or no bytes requested!");if(r>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",t,!1),n!==a&&o.setRequestHeader("Range","bytes="+e+"-"+r),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+t+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):_e(o.responseText||"")}(r,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]})),!i&&n||(a=n=1,n=this.getter(0).length,a=n,A("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=a,this.lengthKnown=!0},o(e,[{key:"length",get:function(){return this.lengthKnown||this.cacheLength(),this._length}},{key:"chunkSize",get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}]),e}();if("undefined"!=typeof XMLHttpRequest){if(!h)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s={isDevice:!1,contents:new a}}else s={isDevice:!1,url:t};var u=Ce.createFile(e,r,s,n,i);s.contents?u.contents=s.contents:s.url&&(u.contents=null,u.url=s.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var c={};function l(e,r,t,n,o){var i=e.node.contents;if(o>=i.length)return 0;var a=Math.min(i.length-o,n);if(L(a>=0),i.slice)for(var s=0;s>2]=n.dev,D[t+4>>2]=n.mode,x[t+8>>2]=n.nlink,D[t+12>>2]=n.uid,D[t+16>>2]=n.gid,D[t+20>>2]=n.rdev,J=[n.size>>>0,(X=n.size,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+24>>2]=J[0],D[t+28>>2]=J[1],D[t+32>>2]=4096,D[t+36>>2]=n.blocks;var o=n.atime.getTime(),i=n.mtime.getTime(),a=n.ctime.getTime();return J=[Math.floor(o/1e3)>>>0,(X=Math.floor(o/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+40>>2]=J[0],D[t+44>>2]=J[1],x[t+48>>2]=o%1e3*1e3,J=[Math.floor(i/1e3)>>>0,(X=Math.floor(i/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+56>>2]=J[0],D[t+60>>2]=J[1],x[t+64>>2]=i%1e3*1e3,J=[Math.floor(a/1e3)>>>0,(X=Math.floor(a/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+72>>2]=J[0],D[t+76>>2]=J[1],x[t+80>>2]=a%1e3*1e3,J=[n.ino>>>0,(X=n.ino,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+88>>2]=J[0],D[t+92>>2]=J[1],0},doMsync:function(e,r,t,n,o){if(!Ce.isFile(r.node.mode))throw new Ce.ErrnoError(43);if(2&n)return 0;var i=F.slice(e,e+t);Ce.msync(r,i,o,t,n)},getStreamFromFD:function(e){return Ce.getStreamChecked(e)},varargs:void 0,getStr:function(e){return De(e)}},Ie=function(e,r){return L(e==e>>>0||e==(0|e)),L(r===(0|r)),r+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*r:NaN},Le=[0,31,60,91,121,152,182,213,244,274,305,335],Ne=[0,31,59,90,120,151,181,212,243,273,304,334],Re=function(e){var r;return((r=e.getFullYear())%4!=0||r%100==0&&r%400!=0?Ne:Le)[e.getMonth()]+e.getDate()-1},Ue=function(e,r,t){return L("number"==typeof t,"stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),be(e,F,r,t)};Se=function(){return performance.now()};var Be,je,$e=function(e){var r=k.buffer,t=(e-r.byteLength+65535)/65536;try{return k.grow(t),N(),1}catch(t){M("growMemory: Attempted to grow heap from "+r.byteLength+" bytes to "+e+" bytes, but got error: "+t)}},We={},He=function(){if(!He.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==("undefined"==typeof navigator?"undefined":u(navigator))&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:_||"./this.program"};for(var r in We)void 0===We[r]?delete e[r]:e[r]=We[r];var t=[];for(var r in e)t.push(r+"="+e[r]);He.strings=t}return He.strings},ze=function(e){return sr(e)},Ve=function(e,r,t,n,o){var i={string:function(e){var r=0;return null!=e&&0!==e&&(r=function(e){var r=we(e)+1,t=ze(r);return Ue(e,t,r),t}(e)),r},array:function(e){var r,t,n=ze(e.length);return t=n,L((r=e).length>=0,"writeArrayToMemory array must have a length (should be an array or typed array)"),P.set(r,t),n}},a=function(e){var r=d["_"+e];return L(r,"Cannot call unknown function "+e+", make sure it is exported"),r}(e),s=[],u=0;if(L("array"!==r,'Return type should not be "array".'),n)for(var c=0;c>7)},Ye=function(e,r){var t;if(L(!r.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled"),"function"==typeof WebAssembly.Function)return new WebAssembly.Function(function(e){L(!e.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled");for(var r={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},t={parameters:[],results:"v"==e[0]?[]:[r[e[0]]]},n=1;n=Qe.length&&(Qe.length=e+1),Qe[e]=r=Be.get(e)),L(Be.get(e)==r,"JavaScript-side Wasm function table mirror is out of date!"),r},Ke=function(e){return je||(je=new WeakMap,function(e,r){if(je)for(var t=e;t>1]=2,0}return-28}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_openat:function(e,r,t,n){xe.varargs=n;try{r=xe.getStr(r),r=xe.calculateAt(e,r);var o=n?fe():0;return Ce.open(r,t,o).fd}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return-e.errno}},_abort_js:function(){q("native code called abort()")},_emscripten_get_now_is_monotonic:function(){return 1},_emscripten_memcpy_js:function(e,r,t){return F.copyWithin(e,r,r+t)},_gmtime_js:function(e,r,t){var n=Ie(e,r),o=new Date(1e3*n);D[t>>2]=o.getUTCSeconds(),D[t+4>>2]=o.getUTCMinutes(),D[t+8>>2]=o.getUTCHours(),D[t+12>>2]=o.getUTCDate(),D[t+16>>2]=o.getUTCMonth(),D[t+20>>2]=o.getUTCFullYear()-1900,D[t+24>>2]=o.getUTCDay();var i=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),a=(o.getTime()-i)/864e5|0;D[t+28>>2]=a},_localtime_js:function(e,r,t){var n=Ie(e,r),o=new Date(1e3*n);D[t>>2]=o.getSeconds(),D[t+4>>2]=o.getMinutes(),D[t+8>>2]=o.getHours(),D[t+12>>2]=o.getDate(),D[t+16>>2]=o.getMonth(),D[t+20>>2]=o.getFullYear()-1900,D[t+24>>2]=o.getDay();var i=0|Re(o);D[t+28>>2]=i,D[t+36>>2]=-60*o.getTimezoneOffset();var a=new Date(o.getFullYear(),0,1),s=new Date(o.getFullYear(),6,1).getTimezoneOffset(),u=a.getTimezoneOffset(),c=0|(s!=u&&o.getTimezoneOffset()==Math.min(u,s));D[t+32>>2]=c},_mktime_js:function(e){var r,t=function(){var r=new Date(D[e+20>>2]+1900,D[e+16>>2],D[e+12>>2],D[e+8>>2],D[e+4>>2],D[e>>2],0),t=D[e+32>>2],n=r.getTimezoneOffset(),o=new Date(r.getFullYear(),0,1),i=new Date(r.getFullYear(),6,1).getTimezoneOffset(),a=o.getTimezoneOffset(),s=Math.min(a,i);if(t<0)D[e+32>>2]=Number(i!=a&&s==n);else if(t>0!=(s==n)){var u=Math.max(a,i),c=t>0?s:u;r.setTime(r.getTime()+6e4*(c-n))}D[e+24>>2]=r.getDay();var l=0|Re(r);D[e+28>>2]=l,D[e>>2]=r.getSeconds(),D[e+4>>2]=r.getMinutes(),D[e+8>>2]=r.getHours(),D[e+12>>2]=r.getDate(),D[e+16>>2]=r.getMonth(),D[e+20>>2]=r.getYear();var d=r.getTime();return isNaN(d)?-1:d/1e3}();return X=t,r=+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0,nr(r),t>>>0},_tzset_js:function(e,r,t,n){var o=(new Date).getFullYear(),i=new Date(o,0,1),a=new Date(o,6,1),s=i.getTimezoneOffset(),u=a.getTimezoneOffset(),c=Math.max(s,u);x[e>>2]=60*c,D[r>>2]=Number(s!=u);var l=function(e){return e.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1]},d=l(i),f=l(a);L(d),L(f),L(we(d)<=16,"timezone name truncated to fit in TZNAME_MAX ("+d+")"),L(we(f)<=16,"timezone name truncated to fit in TZNAME_MAX ("+f+")"),u>>=0)>r);var t=2147483648;if(e>t)return M("Cannot enlarge memory, requested "+e+" bytes, but the limit is "+t+" bytes!"),!1;for(var n,o,i=1;i<=4;i*=2){var a=r*(1+.2/i);a=Math.min(a,e+100663296);var s=Math.min(t,(n=Math.max(e,a))+((o=65536)-n%o)%o);if($e(s))return!0}return M("Failed to grow the heap from "+r+" bytes to "+s+" bytes, not enough memory!"),!1},environ_get:function(e,r){var t=0;return He().forEach((function(n,o){var i=r+t;x[e+4*o>>2]=i,function(e,r){for(var t=0;t>2]=t.length;var n=0;return t.forEach((function(e){return n+=e.length+1})),x[r>>2]=n,0},fd_close:function(e){try{var r=xe.getStreamFromFD(e);return Ce.close(r),0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_fdstat_get:function(e,r){try{var t=xe.getStreamFromFD(e),n=t.tty?2:Ce.isDir(t.mode)?3:Ce.isLink(t.mode)?7:4;return P[r]=n,C[r+2>>1]=0,J=[0,(X=0,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[r+8>>2]=J[0],D[r+12>>2]=J[1],J=[0,(X=0,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[r+16>>2]=J[0],D[r+20>>2]=J[1],0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_read:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,i=0;i>2],s=x[r+4>>2];r+=8;var u=Ce.read(e,P,a,s,n);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_seek:function(e,r,t,n,o){var i=Ie(r,t);try{if(isNaN(i))return 61;var a=xe.getStreamFromFD(e);return Ce.llseek(a,i,n),J=[a.position>>>0,(X=a.position,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[o>>2]=J[0],D[o+4>>2]=J[1],a.getdents&&0===i&&0===n&&(a.getdents=null),0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_write:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,i=0;i>2],s=x[r+4>>2];r+=8;var u=Ce.write(e,P,a,s,n);if(u<0)return-1;o+=u}return o}(xe.getStreamFromFD(e),r,t);return x[n>>2]=o,0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}}},er=function(){var e={env:Ze,wasi_snapshot_preview1:Ze};function r(e,r){var t;return er=e.exports,L(k=er.memory,"memory not found in wasm exports"),N(),L(Be=er.__indirect_function_table,"table not found in wasm exports"),t=er.__wasm_call_ctors,B.unshift(t),Q("wasm-instantiate"),er}Y("wasm-instantiate");var t,n,o,a,s=d;if(d.instantiateWasm)try{return d.instantiateWasm(e,r)}catch(e){M("Module.instantiateWasm callback failed with error: "+e),i(e)}return K||(K=te()),(t=T,n=K,o=e,a=function(e){L(d===s,"the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"),s=null,r(e.instance)},t||"function"!=typeof WebAssembly.instantiateStreaming||Z(n)||"function"!=typeof fetch?oe(n,o,a):fetch(n,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,o).then(a,(function(e){return M("wasm streaming compile failed: "+e),M("falling back to ArrayBuffer instantiation"),oe(n,o,a)}))}))).catch(i),{}}();d._malloc=re("malloc",1),d._free=re("free",1),d._registerWasmPlayer=re("registerWasmPlayer",0),d._setCodecType=re("setCodecType",4),d._exitWasmPlayer=re("exitWasmPlayer",1),d._initDecoder=re("initDecoder",1),d._decodeCodecContext=re("decodeCodecContext",5),d._destroy=re("destroy",1),d._demuxTsStream=re("demuxTsStream",3),d._getPacket=re("getPacket",0),d._getVLCLen=re("getVLCLen",0),d._getVLC=re("getVLC",0),d._getVPSLen=re("getVPSLen",0),d._getVPS=re("getVPS",0),d._getSPSLen=re("getSPSLen",0),d._getSPS=re("getSPS",0),d._getPPSLen=re("getPPSLen",0),d._getPPS=re("getPPS",0),d._getSEILen=re("getSEILen",0),d._getSEI=re("getSEI",0);var rr,tr=re("fflush",1),nr=re("_emscripten_tempret_set",1),or=function(){return(or=er.emscripten_stack_init)()},ir=function(){return(ir=er.emscripten_stack_get_end)()},ar=function(e){return(ar=er._emscripten_stack_restore)(e)},sr=function(e){return(sr=er._emscripten_stack_alloc)(e)},ur=function(){return(ur=er.emscripten_stack_get_current)()};function cr(){var e;or(),L(!(3&(e=ir()))),0==e&&(e+=4),x[e>>2]=34821223,x[e+4>>2]=2310721022,x[0]=1668509029}function lr(){function e(){rr||(rr=!0,d.calledRun=!0,I||(L(!$),$=!0,R(),d.noFSInit||Ce.init.initialized||Ce.init(),Ce.ignorePermissions=!1,ce(B),n(d),d.onRuntimeInitialized&&d.onRuntimeInitialized(),L(!d._main,'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'),function(){if(R(),d.postRun)for("function"==typeof d.postRun&&(d.postRun=[d.postRun]);d.postRun.length;)e=d.postRun.shift(),j.unshift(e);var e;ce(j)}()))}W>0||(cr(),function(){if(d.preRun)for("function"==typeof d.preRun&&(d.preRun=[d.preRun]);d.preRun.length;)e=d.preRun.shift(),U.unshift(e);var e;ce(U)}(),W>0||(d.setStatus?(d.setStatus("Running..."),setTimeout((function(){setTimeout((function(){d.setStatus("")}),1),e()}),1)):e(),R()))}if(d.dynCall_jiji=re("dynCall_jiji",5),d.dynCall_iiiiij=re("dynCall_iiiiij",7),d.dynCall_jiiij=re("dynCall_jiiij",6),d._ff_h264_cabac_tables=113148,d.run=lr,d.ccall=Ve,d.cwrap=function(e,r,t,n){return function(){for(var n=arguments.length,o=new Array(n),i=0;i0;)d.preInit.pop()();lr(),r=p;for(var dr,fr=l(Object.keys(d));!(dr=fr()).done;)t();return r});"object"===u(r)&&"object"===u(e)&&(e.exports=p)}(t,t.exports);var n,o,i,a,s=r(t.exports),u="wasmLoading",c="wasmLoaded",l="wasmFailed",d="registerWasmPlayer",f="videoCallback",p="decodeCodecContext",m="destroy",h="demuxTsStream",g="demuxCoreReceive",v="readPacket",E="readPacketEnd",y="mediaInfo",w=function(e,r){return{cmd:e,data:r}},b=(n="undefined"!=typeof self?self:window,o={navigator:void 0!==n.navigator?n.navigator:{userAgent:""},infoMap:{engine:["WebKit","Trident","Gecko","Presto"],browser:["Safari","Chrome","Edge","IE","Firefox","Firefox Focus","Chromium","Opera","Vivaldi","Yandex","Arora","Lunascape","QupZilla","Coc Coc","Kindle","Iceweasel","Konqueror","Iceape","SeaMonkey","Epiphany","360","360SE","360EE","UC","QQBrowser","QQ","Baidu","Maxthon","Sogou","LBBROWSER","2345Explorer","TheWorld","XiaoMi","Quark","Qiyu","Wechat","Taobao","Alipay","Weibo","Douban","Suning","iQiYi"],os:["Windows","Linux","Mac OS","Android","Ubuntu","FreeBSD","Debian","iOS","Windows Phone","BlackBerry","MeeGo","Symbian","Chrome OS","WebOS"],device:["Mobile","Tablet","iPad"]}},i={getMatchMap:function(e){return{Trident:e.indexOf("Trident")>-1||e.indexOf("NET CLR")>-1,Presto:e.indexOf("Presto")>-1,WebKit:e.indexOf("AppleWebKit")>-1,Gecko:e.indexOf("Gecko/")>-1,Safari:e.indexOf("Safari")>-1,Chrome:e.indexOf("Chrome")>-1||e.indexOf("CriOS")>-1,IE:e.indexOf("MSIE")>-1||e.indexOf("Trident")>-1,Edge:e.indexOf("Edge")>-1,Firefox:e.indexOf("Firefox")>-1||e.indexOf("FxiOS")>-1,"Firefox Focus":e.indexOf("Focus")>-1,Chromium:e.indexOf("Chromium")>-1,Opera:e.indexOf("Opera")>-1||e.indexOf("OPR")>-1,Vivaldi:e.indexOf("Vivaldi")>-1,Yandex:e.indexOf("YaBrowser")>-1,Arora:e.indexOf("Arora")>-1,Lunascape:e.indexOf("Lunascape")>-1,QupZilla:e.indexOf("QupZilla")>-1,"Coc Coc":e.indexOf("coc_coc_browser")>-1,Kindle:e.indexOf("Kindle")>-1||e.indexOf("Silk/")>-1,Iceweasel:e.indexOf("Iceweasel")>-1,Konqueror:e.indexOf("Konqueror")>-1,Iceape:e.indexOf("Iceape")>-1,SeaMonkey:e.indexOf("SeaMonkey")>-1,Epiphany:e.indexOf("Epiphany")>-1,360:e.indexOf("QihooBrowser")>-1||e.indexOf("QHBrowser")>-1,"360EE":e.indexOf("360EE")>-1,"360SE":e.indexOf("360SE")>-1,UC:e.indexOf("UC")>-1||e.indexOf(" UBrowser")>-1,QQBrowser:e.indexOf("QQBrowser")>-1,QQ:e.indexOf("QQ/")>-1,Baidu:e.indexOf("Baidu")>-1||e.indexOf("BIDUBrowser")>-1,Maxthon:e.indexOf("Maxthon")>-1,Sogou:e.indexOf("MetaSr")>-1||e.indexOf("Sogou")>-1,LBBROWSER:e.indexOf("LBBROWSER")>-1,"2345Explorer":e.indexOf("2345Explorer")>-1,TheWorld:e.indexOf("TheWorld")>-1,XiaoMi:e.indexOf("MiuiBrowser")>-1,Quark:e.indexOf("Quark")>-1,Qiyu:e.indexOf("Qiyu")>-1,Wechat:e.indexOf("MicroMessenger")>-1,Taobao:e.indexOf("AliApp(TB")>-1,Alipay:e.indexOf("AliApp(AP")>-1,Weibo:e.indexOf("Weibo")>-1,Douban:e.indexOf("com.douban.frodo")>-1,Suning:e.indexOf("SNEBUY-APP")>-1,iQiYi:e.indexOf("IqiyiApp")>-1,Windows:e.indexOf("Windows")>-1,Linux:e.indexOf("Linux")>-1||e.indexOf("X11")>-1,"Mac OS":e.indexOf("Macintosh")>-1,Android:e.indexOf("Android")>-1||e.indexOf("Adr")>-1,Ubuntu:e.indexOf("Ubuntu")>-1,FreeBSD:e.indexOf("FreeBSD")>-1,Debian:e.indexOf("Debian")>-1,"Windows Phone":e.indexOf("IEMobile")>-1||e.indexOf("Windows Phone")>-1,BlackBerry:e.indexOf("BlackBerry")>-1||e.indexOf("RIM")>-1,MeeGo:e.indexOf("MeeGo")>-1,Symbian:e.indexOf("Symbian")>-1,iOS:e.indexOf("like Mac OS X")>-1,"Chrome OS":e.indexOf("CrOS")>-1,WebOS:e.indexOf("hpwOS")>-1,Mobile:e.indexOf("Mobi")>-1||e.indexOf("iPh")>-1||e.indexOf("480")>-1,Tablet:e.indexOf("Tablet")>-1||e.indexOf("Nexus 7")>-1,iPad:e.indexOf("iPad")>-1}},matchInfoMap:function(e){var r,t=(null==(r=o.navigator)?void 0:r.userAgent)||"",n=i.getMatchMap(t);for(var a in o.infoMap)for(var s=0;s36&&n.showModalDialog?s=!0:+u>45&&(s=t("type","application/vnd.chromium.remoting-viewer"))}if(a.Baidu&&a.Opera&&(a.Baidu=!1),a.Mobile&&(a.Mobile=!r.includes("iPad")),s&&(t("type","application/gameplugin")||o.navigator&&void 0===o.navigator.connection.saveData?a["360SE"]=!0:a["360EE"]=!0),a.IE||a.Edge)switch(window.screenTop-window.screenY){case 71:case 74:case 99:case 75:case 105:break;case 102:a["360EE"]=!0;break;case 104:a["360SE"]=!0}var c={Safari:function(){return r.replace(/^.*Version\/([\d.]+).*$/,"$1")},Chrome:function(){return r.replace(/^.*Chrome\/([\d.]+).*$/,"$1").replace(/^.*CriOS\/([\d.]+).*$/,"$1")},IE:function(){return r.replace(/^.*MSIE ([\d.]+).*$/,"$1").replace(/^.*rv:([\d.]+).*$/,"$1")},Edge:function(){return r.replace(/^.*Edge\/([\d.]+).*$/,"$1")},Firefox:function(){return r.replace(/^.*Firefox\/([\d.]+).*$/,"$1").replace(/^.*FxiOS\/([\d.]+).*$/,"$1")},"Firefox Focus":function(){return r.replace(/^.*Focus\/([\d.]+).*$/,"$1")},Chromium:function(){return r.replace(/^.*Chromium\/([\d.]+).*$/,"$1")},Opera:function(){return r.replace(/^.*Opera\/([\d.]+).*$/,"$1").replace(/^.*OPR\/([\d.]+).*$/,"$1")},Vivaldi:function(){return r.replace(/^.*Vivaldi\/([\d.]+).*$/,"$1")},Yandex:function(){return r.replace(/^.*YaBrowser\/([\d.]+).*$/,"$1")},Arora:function(){return r.replace(/^.*Arora\/([\d.]+).*$/,"$1")},Lunascape:function(){return r.replace(/^.*Lunascape[\/\s]([\d.]+).*$/,"$1")},QupZilla:function(){return r.replace(/^.*QupZilla[\/\s]([\d.]+).*$/,"$1")},"Coc Coc":function(){return r.replace(/^.*coc_coc_browser\/([\d.]+).*$/,"$1")},Kindle:function(){return r.replace(/^.*Version\/([\d.]+).*$/,"$1")},Iceweasel:function(){return r.replace(/^.*Iceweasel\/([\d.]+).*$/,"$1")},Konqueror:function(){return r.replace(/^.*Konqueror\/([\d.]+).*$/,"$1")},Iceape:function(){return r.replace(/^.*Iceape\/([\d.]+).*$/,"$1")},SeaMonkey:function(){return r.replace(/^.*SeaMonkey\/([\d.]+).*$/,"$1")},Epiphany:function(){return r.replace(/^.*Epiphany\/([\d.]+).*$/,"$1")},360:function(){return r.replace(/^.*QihooBrowser\/([\d.]+).*$/,"$1")},"360SE":function(){return{63:"10.0",55:"9.1",45:"8.1",42:"8.0",31:"7.0",21:"6.3"}[+r.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"360EE":function(){return{69:"11.0",63:"9.5",55:"9.0",50:"8.7",30:"7.5"}[+r.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},Maxthon:function(){return r.replace(/^.*Maxthon\/([\d.]+).*$/,"$1")},QQBrowser:function(){return r.replace(/^.*QQBrowser\/([\d.]+).*$/,"$1")},QQ:function(){return r.replace(/^.*QQ\/([\d.]+).*$/,"$1")},Baidu:function(){return r.replace(/^.*BIDUBrowser[\s\/]([\d.]+).*$/,"$1")},UC:function(){return r.replace(/^.*UC?Browser\/([\d.]+).*$/,"$1")},Sogou:function(){return r.replace(/^.*SE ([\d.X]+).*$/,"$1").replace(/^.*SogouMobileBrowser\/([\d.]+).*$/,"$1")},LBBROWSER:function(){return{57:"6.5",49:"6.0",46:"5.9",42:"5.3",39:"5.2",34:"5.0",29:"4.5",21:"4.0"}[+navigator.userAgent.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"2345Explorer":function(){return r.replace(/^.*2345Explorer\/([\d.]+).*$/,"$1")},TheWorld:function(){return r.replace(/^.*TheWorld ([\d.]+).*$/,"$1")},XiaoMi:function(){return r.replace(/^.*MiuiBrowser\/([\d.]+).*$/,"$1")},Quark:function(){return r.replace(/^.*Quark\/([\d.]+).*$/,"$1")},Qiyu:function(){return r.replace(/^.*Qiyu\/([\d.]+).*$/,"$1")},Wechat:function(){return r.replace(/^.*MicroMessenger\/([\d.]+).*$/,"$1")},Taobao:function(){return r.replace(/^.*AliApp\(TB\/([\d.]+).*$/,"$1")},Alipay:function(){return r.replace(/^.*AliApp\(AP\/([\d.]+).*$/,"$1")},Weibo:function(){return r.replace(/^.*weibo__([\d.]+).*$/,"$1")},Douban:function(){return r.replace(/^.*com.douban.frodo\/([\d.]+).*$/,"$1")},Suning:function(){return r.replace(/^.*SNEBUY-APP([\d.]+).*$/,"$1")},iQiYi:function(){return r.replace(/^.*IqiyiVersion\/([\d.]+).*$/,"$1")}};return e.browserVersion="",c[e.browser]&&(e.browserVersion=c[e.browser](),e.browserVersion==r&&(e.browserVersion="")),"Edge"==e.browser&&(e.engine="EdgeHTML"),"Chrome"==e.browser&&parseInt(e.browserVersion)>27&&(e.engine="Blink"),"Opera"==e.browser&&parseInt(e.browserVersion)>12&&(e.engine="Blink"),"Yandex"==e.browser&&(e.engine="Blink"),e.browser+" (version: "+e.browserVersion+"; kernel: "+e.engine+")"}},a={DeviceInfoObj:function(e){var r,t=function(r){var t;null==(t=e.info)||t.forEach((function(e){e.toLowerCase()===r.toLowerCase()&&(s[r]=a[r])}))};e=e||{domain:""};var a={deviceType:i.getDeviceType(),OS:i.getOS(),OSVersion:i.getOSVersion(),sh:n.screen.height,sw:n.screen.width,lang:i.getLanguage(),netWork:i.getNetwork(),orientation:i.getOrientationStatu(),browserInfo:i.getBrowserInfo(),fingerprint:i.createFingerprint(e.domain),userAgent:null==(r=o.navigator)?void 0:r.userAgent};if(!e.info||0===e.info.length)return a;var s={};for(var u in a)t(u);return s}},{getDeviceInfo:function(e){return a.DeviceInfoObj(e)}}),_=function(){function e(){}return e.add=function(r,t){e.queues.push({url:r,data:t})},e.fire=function(){if(e.queues&&0!==e.queues.length){e.isStop=!1;var r=e.queues[0];r.url&&e.api.report(r.data),e.queues.splice(0,1),e.fire()}else e.isStop=!0},e}();_.isStop=!0,_.queues=[];var S=function(){function e(e){this.url=e}var r=e.prototype;return r.report=function(e){this.checkUrl(this.url)&&this.sendInfo(e)},r.sendInfo=function(e){navigator.sendBeacon?this.sendBeacon(this.url,e):this.sendImage(this.url,e)},r.sendImage=function(e,r){var t=this.changeJSON2Query(r),n=new Image;n.onload=n.onerror=function(){n=null},n.src=e+"?"+t+"&random="+Math.random()},r.sendBeacon=function(e,r){try{navigator.sendBeacon(e,this.formatParamsByURLSearchParams(r))}catch(e){}},r.formatParamsByURLSearchParams=function(e){var r=new URLSearchParams;for(var t in e)"object"==typeof e[t]&&(e[t]=JSON.stringify(e[t])),r.append(t,e[t]);return r},r.changeJSON2Query=function(e){var r="";for(var t in e){""!=r&&(r+="&");var n=e[t];r+=t+"="+encodeURIComponent("object"==typeof n?JSON.stringify(n):n)}return r},r.checkUrl=function(e){return!!e&&/^[hH][tT][tT][pP]([sS]?):\/\//.test(e)},e}();function O(){return O=Object.assign||function(e){for(var r=1;r0&&(r._free(l),l=null),{};var d=r.HEAPU8.subarray(l,l+c);s.sps=new Uint8Array(c),null==(n=s.sps)||n.set(d,0);var f=r.cwrap("getPPSLen","number",[])(),p=r.cwrap("getPPS","number",[])(),m=r.HEAPU8.subarray(p,p+f);s.pps=new Uint8Array(f),null==(o=s.pps)||o.set(m,0);var h=r.cwrap("getSEILen","number",[])(),g=r.cwrap("getSEI","number",[])(),v=r.HEAPU8.subarray(g,g+h);s.sei=new Uint8Array(h),null==(i=s.sei)||i.set(v,0);var E=r.cwrap("getVLCLen","number",[])(),y=r.cwrap("getVLC","number",[])(),w=r.HEAPU8.subarray(y,y+E);if(u.vlc=new Uint8Array(E),null==(a=u.vlc)||a.set(w,0),(null==t?void 0:t.vCodec)===e.DEF_HEVC||(null==t?void 0:t.vCodec)===e.DEF_H265){var b,_=r.cwrap("getVPSLen","number",[])(),S=r.cwrap("getVPS","number",[])(),O=r.HEAPU8.subarray(S,S+_);s.vps=new Uint8Array(_),null==(b=s.vps)||b.set(O,0),r._free(O),O=null}try{r._free(l)}catch(e){k.send("worker",{name:"readPacket",free:"spsPtr"})}l=null;try{r._free(d)}catch(e){k.send("worker",{name:"readPacket",free:"spsSubPtr"})}d=null;try{r._free(m)}catch(e){k.send("worker",{name:"readPacket",free:"ppsSubPtr"})}m=null;try{r._free(v)}catch(e){k.send("worker",{name:"readPacket",free:"seiSubPtr"})}v=null;try{r._free(w)}catch(e){k.send("worker",{name:"readPacket",free:"vlcSubPtr"})}return w=null,{nalu:s,vlc:u}};function F(){return F=Object.assign||function(e){for(var r=1;r0?r:e.DEFAULT_SAMPLERATE,sampleChannel:t>=0?t:e.DEFAULT_CHANNEL}:{sampleRate:0,sampleChannel:0,audioNone:!0})))}),"viiddddiiiii"),t._setCodecType(n,0,o,i),t.cwrap("initDecoder","number",["number"])(n);break;case p:var u=s.data,c=u.nalBuf,l=u.pts,b=u.flushDecoder,_=t._malloc(c.length);t.HEAP8.set(c,_);var S=parseInt(1e3*l+"");t._decodeCodecContext(n,_,c.length,S,b),t._free(_),_=null;break;case h:var O=s.data,T=O.buff;O.tsUrl,function(e,r,t,n){null!=M&&(e._free(M),M=null),M=e._malloc(r.length),e.HEAP8.set(r,M);try{var o=e.cwrap("demuxTsStream","number",["number","number","number"])(M,r.length,t);e._free(M),M=null,o>=0&&postMessage(w(g))}catch(e){k.send("worker",{name:"demuxTsStream",msg:e})}}(t,T,n);break;case v:!function(e,r){for(;;){var t=e.cwrap("getPacket","number",[])(),n=e.HEAPU32[t/4],o=e.HEAPU32[t/4+1],i=e.HEAPF64[t/8+1],a=e.HEAPF64[t/8+1+1],s=e.HEAPU32[t/4+1+1+2+2],u=e.HEAPU32[t/4+1+1+2+2+1],c=e.HEAPU8.subarray(u,u+o),l=null,d=[0,1].includes(n);if(d)try{l=P(e,r)}catch(e){}if(!d||o<=0)break;var f=a>0?a:i;f<0||0===t||(self.postMessage(w(v,{type:n,size:o,ptime:i,dtime:a,keyframe:s,data:Array.from(c),pts:f,layer:l})),c=null,l=null,t=null)}postMessage(w(E))}(t,a);break;case m:null!==o&&t.removeFunction(o),o=null,null!==i&&t.removeFunction(i),i=null,t.cwrap("destroy","number",["number"])(n),self.close()}}})).catch((function(e){self.postMessage(w(l,{data:e}))}))})); diff --git a/examples/react-app/src/Player.jsx b/examples/react-app/src/Player.jsx index 5f582cc..d54c4a8 100644 --- a/examples/react-app/src/Player.jsx +++ b/examples/react-app/src/Player.jsx @@ -1,15 +1,15 @@ import "./Player.css"; import { useCallback, useEffect, useRef } from "react"; -import HLSPlayer from "@ezuikit/player-hls"; +import HlsPlayer from "@ezuikit/player-hls"; function Player() { + /** @type { React.MutableRefObject} */ const playerRef = useRef(); const urlRef = useRef(); const containerRef = useRef(); const volumeRef = useRef(); useEffect(() => { - // createPlayer(); volumeRef.current.addEventListener("blur", (e) => { if (playerRef.current) { let value = (e.target.value || "").trim(); @@ -34,10 +34,9 @@ function Player() { const createPlayer = () => { const url = urlRef.current.value; if (!playerRef.current) { - playerRef.current = new HLSPlayer({ - id: containerRef.current, + playerRef.current = new HlsPlayer({ + id: "player-container", url, - decoder: "decoder.js" // 软解解码资源 (wasm 要和js 在同一个文件夹中) }); playerRef.current.play(); } @@ -70,27 +69,15 @@ function Player() { } }, []); - const handleOpenSound = useCallback(() => { + const handleFullscreen = useCallback(() => { if (playerRef.current) { - playerRef.current.openSound(); + playerRef.current.fullscreen(); } }, []); - const handleCloseSound = useCallback(() => { + const handleExitFullscreen = useCallback(() => { if (playerRef.current) { - playerRef.current.closeSound(); - } - }, []); - - const handleFullScreen = useCallback(() => { - if (playerRef.current) { - playerRef.current.fullScreen(); - } - }, []); - - const handleCancelFullScreen = useCallback(() => { - if (playerRef.current) { - playerRef.current.cancelFullScreen(); + playerRef.current.exitFullscreen(); } }, []); @@ -116,10 +103,8 @@ function Player() { - - - - + +
diff --git a/examples/vue-app/package.json b/examples/vue-app/package.json index d2de11a..1d75c59 100644 --- a/examples/vue-app/package.json +++ b/examples/vue-app/package.json @@ -10,7 +10,7 @@ "format": "prettier --write src/" }, "dependencies": { - "@ezuikit/player-hls": "^0.1.0-alpha.1", + "@ezuikit/player-hls": "^0.1.0", "vue": "^3.3.4" }, "devDependencies": { diff --git a/examples/vue-app/pnpm-lock.yaml b/examples/vue-app/pnpm-lock.yaml index 7f5ea37..41e451c 100644 --- a/examples/vue-app/pnpm-lock.yaml +++ b/examples/vue-app/pnpm-lock.yaml @@ -6,8 +6,8 @@ settings: dependencies: '@ezuikit/player-hls': - specifier: ^0.1.0-alpha.1 - version: 0.1.0-alpha.1 + specifier: ^0.1.0 + version: 0.1.0 vue: specifier: ^3.3.4 version: 3.4.35 @@ -295,9 +295,10 @@ packages: engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} dev: true - /@ezuikit/player-base@0.1.0-alpha.1: - resolution: {integrity: sha512-68O3PtB5g7hm+HSpCqE/ef/Ud0xUPsFv3ckrj6VKm7wyed+9aqTazxv8mDPOXuNStZZULpfn+7Uf0KW7cHAyxg==} + /@ezuikit/player-base@0.1.0: + resolution: {integrity: sha512-IcJqnZr9FmjBCnIrmqY7oHdyDuYxRWhDZB+K+gi+4oenFjFV4aLCCG7RFPxkidHzi3TTF2f1Bm5yObZzNDqkfw==} dependencies: + '@ezuikit/utils-collect': 0.1.0 '@ezuikit/utils-logger': 1.0.1 '@ezuikit/utils-tools': 1.0.3 eventemitter3: 5.0.1 @@ -306,11 +307,11 @@ packages: ua-parser-js: 1.0.37 dev: false - /@ezuikit/player-hls@0.1.0-alpha.1: - resolution: {integrity: sha512-DcR5B3JBwY9pT+wRapk5B8ntqYdHkXjj+S0GfS2Ler41+g/l6YaSC/LsWh525bVRbfMGDxhUD9WBK01CoHn1Bw==} + /@ezuikit/player-hls@0.1.0: + resolution: {integrity: sha512-T5PCj65mw3mP1MpfJOrx/MXpNZFMrW37fjjYnil1rCuy6ACGBNWXFVvOlzuh5k7G4DFV+HjbbMJnG21icNdZnw==} dependencies: - '@ezuikit/player-base': 0.1.0-alpha.1 - '@ezuikit/utils-collect': 0.1.0-beta.1 + '@ezuikit/player-base': 0.1.0 + '@ezuikit/utils-collect': 0.1.0 '@ezuikit/utils-i18n': 1.0.1 '@ezuikit/utils-logger': 1.0.1 '@ezuikit/utils-tools': 1.0.3 @@ -322,8 +323,8 @@ packages: ua-parser-js: 1.0.37 dev: false - /@ezuikit/utils-collect@0.1.0-beta.1: - resolution: {integrity: sha512-+kkEkOVM9bQkWp90ppFpEwuaG8sRCH/F3CamLLgS0CG18gk1Fb5lcvS21hklgxMjS5tLotjwlfs0j+pQydzRYA==} + /@ezuikit/utils-collect@0.1.0: + resolution: {integrity: sha512-85lWlB/VCaooPPkCK3nEB4F3UKgO+HbmoPEq4U1tH/ObVP7IJ7eURrFUmQT1CKsqjH5xz5g4DgZzHWgYrwGcCQ==} dev: false /@ezuikit/utils-i18n@1.0.1: diff --git a/examples/vue-app/public/decoder.wasm b/examples/vue-app/public/decoder.wasm new file mode 100644 index 0000000..5c0c2fa Binary files /dev/null and b/examples/vue-app/public/decoder.wasm differ diff --git a/examples/vue-app/public/decoder.worker.js b/examples/vue-app/public/decoder.worker.js new file mode 100644 index 0000000..e544318 --- /dev/null +++ b/examples/vue-app/public/decoder.worker.js @@ -0,0 +1,8 @@ +/* +* +* DecoderWorker.js v0.1.0-beta.2 +* Copyright (c) 2024-8-1 Ezviz-OpenBiz +* . +* +*/ +!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";var e={DEFAULT_SAMPLERATE:44100,DEFAULT_CHANNEL:1,H264AUD:[0,0,0,1,9,224],H265AUD:[0,0,0,1,70,1,80],DEF_AAC:"aac",DEF_MP3:"mp3",DEF_H265:"h265",DEF_HEVC:"hevc",DEF_H264:"h264",DEF_AVC:"avc",CODEC_OFFSET_TABLE:["hevc","h265","avc","h264","aac","mp3"]};function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t={exports:{}};!function(e,r){function t(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var d,f,p=(f="undefined"!=typeof document?null==(d=document.currentScript)?void 0:d.src:void 0,function(e){var r,t=function(){var r=dr.value;r in e||Object.defineProperty(e,r,{configurable:!0,get:function(){q("Access to module property ('"+r+"') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.")}})};void 0===e&&(e={});var n,i,d=Object.assign({},e),p=new Promise((function(e,r){n=e,i=r}));["_malloc","_free","_memory","_registerWasmPlayer","_setCodecType","_exitWasmPlayer","_initDecoder","_decodeCodecContext","_destroy","_demuxTsStream","_getPacket","_getVLCLen","_getVLC","_getVPSLen","_getVPS","_getSPSLen","_getSPS","_getPPSLen","_getPPS","_getSEILen","_getSEI","___indirect_function_table","_ff_h264_cabac_tables","onRuntimeInitialized"].forEach((function(e){Object.getOwnPropertyDescriptor(p,e)||Object.defineProperty(p,e,{get:function(){return q("You are getting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")},set:function(){return q("You are setting "+e+" on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js")}})}));var m="object"==("undefined"==typeof window?"undefined":u(window)),h="function"==typeof importScripts,g="object"==("undefined"==typeof process?"undefined":u(process))&&"object"==u(process.versions)&&"string"==typeof process.versions.node,v=!m&&!g&&!h;if(d.ENVIRONMENT)throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");var E,y,w,b=Object.assign({},d),_="./this.program",S="";if(v){if("object"==("undefined"==typeof process?"undefined":u(process))||"object"==("undefined"==typeof window?"undefined":u(window))||"function"==typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)")}else{if(!m&&!h)throw new Error("environment detection error");if(h?S=self.location.href:"undefined"!=typeof document&&document.currentScript&&(S=document.currentScript.src),f&&(S=f),S=S.startsWith("blob:")?"":S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1),"object"!=("undefined"==typeof window?"undefined":u(window))&&"function"!=typeof importScripts)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");E=function(e){var r=new XMLHttpRequest;return r.open("GET",e,!1),r.send(null),r.responseText},h&&(w=function(e){var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),y=function(e,r,t){var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=function(){200==n.status||0==n.status&&n.response?r(n.response):t()},n.onerror=t,n.send(null)}}var O,T,k,A=d.print||console.log.bind(console),M=d.printErr||console.error.bind(console);Object.assign(d,b),b=null,O="fetchSettings",Object.getOwnPropertyDescriptor(d,O)&&q("`Module."+O+"` was supplied but `"+O+"` not included in INCOMING_MODULE_JS_API"),d.arguments&&d.arguments,ie("arguments","arguments_"),d.thisProgram&&(_=d.thisProgram),ie("thisProgram","thisProgram"),d.quit&&d.quit,ie("quit","quit_"),L(void 0===d.memoryInitializerPrefixURL,"Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.pthreadMainPrefixURL,"Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.cdInitializerPrefixURL,"Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.filePackagePrefixURL,"Module.filePackagePrefixURL option was removed, use Module.locateFile instead"),L(void 0===d.read,"Module.read option was removed (modify read_ in JS)"),L(void 0===d.readAsync,"Module.readAsync option was removed (modify readAsync in JS)"),L(void 0===d.readBinary,"Module.readBinary option was removed (modify readBinary in JS)"),L(void 0===d.setWindowTitle,"Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"),L(void 0===d.TOTAL_MEMORY,"Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"),ie("asm","wasmExports"),ie("read","read_"),ie("readAsync","readAsync"),ie("readBinary","readBinary"),ie("setWindowTitle","setWindowTitle"),L(!g,"node environment detected but not enabled at build time. Add `node` to `-sENVIRONMENT` to enable."),L(!v,"shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable."),d.wasmBinary&&(T=d.wasmBinary),ie("wasmBinary","wasmBinary"),"object"!=("undefined"==typeof WebAssembly?"undefined":u(WebAssembly))&&M("no native wasm support detected");var P,F,C,D,x,I=!1;function L(e,r){e||q("Assertion failed"+(r?": "+r:""))}function N(){var e=k.buffer;d.HEAP8=P=new Int8Array(e),d.HEAP16=C=new Int16Array(e),d.HEAPU8=F=new Uint8Array(e),d.HEAPU16=new Uint16Array(e),d.HEAP32=D=new Int32Array(e),d.HEAPU32=x=new Uint32Array(e),d.HEAPF32=new Float32Array(e),d.HEAPF64=new Float64Array(e)}function R(){if(!I){var e=ir();0==e&&(e+=4);var r=x[e>>2],t=x[e+4>>2];34821223==r&&2310721022==t||q("Stack overflow! Stack cookie has been overwritten at "+le(e)+", expected hex dwords 0x89BACDFE and 0x2135467, but received "+le(t)+" "+le(r)),1668509029!=x[0]&&q("Runtime error: The application has corrupted its heap memory area (address zero)!")}}L(!d.STACK_SIZE,"STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"),L("undefined"!=typeof Int32Array&&"undefined"!=typeof Float64Array&&null!=Int32Array.prototype.subarray&&null!=Int32Array.prototype.set,"JS engine does not provide full typed array support"),L(!d.wasmMemory,"Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"),L(!d.INITIAL_MEMORY,"Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically"),function(){var e=new Int16Array(1),r=new Int8Array(e.buffer);if(e[0]=25459,115!==r[0]||99!==r[1])throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"}();var U=[],B=[],j=[],$=!1;L(Math.imul,"This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.fround,"This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.clz32,"This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"),L(Math.trunc,"This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill");var W=0,H=null,z=null,V={};function G(e){for(var r=e;;){if(!V[e])return e;e=r+Math.random()}}function Y(e){var r;W++,null==(r=d.monitorRunDependencies)||r.call(d,W),e?(L(!V[e]),V[e]=1,null===H&&"undefined"!=typeof setInterval&&(H=setInterval((function(){if(I)return clearInterval(H),void(H=null);var e=!1;for(var r in V)e||(e=!0,M("still waiting on run dependencies:")),M("dependency: "+r);e&&M("(end of list)")}),1e4))):M("warning: run dependency added without ID")}function Q(e){var r;if(W--,null==(r=d.monitorRunDependencies)||r.call(d,W),e?(L(V[e]),delete V[e]):M("warning: run dependency removed without ID"),0==W&&(null!==H&&(clearInterval(H),H=null),z)){var t=z;z=null,t()}}function q(e){var r;null==(r=d.onAbort)||r.call(d,e),M(e="Aborted("+e+")"),I=!0;var t=new WebAssembly.RuntimeError(e);throw i(t),t}var K,X,J,Z=function(e){return e.startsWith("data:application/octet-stream;base64,")},ee=function(e){return e.startsWith("file://")};function re(e,r){return function(){for(var t=arguments.length,n=new Array(t),o=0;o0;)e.shift()(d)};d.noExitRuntime;var le=function(e){return L("number"==typeof e),"0x"+(e>>>=0).toString(16).padStart(8,"0")},de=function(e){var r;(r=de).shown||(r.shown={}),de.shown[e]||(de.shown[e]=1,M(e))};function fe(){L(null!=xe.varargs);var e=D[+xe.varargs>>2];return xe.varargs+=4,e}var pe=fe,me={isAbs:function(e){return"/"===e.charAt(0)},splitPath:function(e){return/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1)},normalizeArray:function(e,r){for(var t=0,n=e.length-1;n>=0;n--){var o=e[n];"."===o?e.splice(n,1):".."===o?(e.splice(n,1),t++):t&&(e.splice(n,1),t--)}if(r)for(;t;t--)e.unshift("..");return e},normalize:function(e){var r=me.isAbs(e),t="/"===e.substr(-1);return(e=me.normalizeArray(e.split("/").filter((function(e){return!!e})),!r).join("/"))||r||(e="."),e&&t&&(e+="/"),(r?"/":"")+e},dirname:function(e){var r=me.splitPath(e),t=r[0],n=r[1];return t||n?(n&&(n=n.substr(0,n.length-1)),t+n):"."},basename:function(e){if("/"===e)return"/";var r=(e=(e=me.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===r?e:e.substr(r+1)},join:function(){for(var e=arguments.length,r=new Array(e),t=0;t { for (var i = 0; i < array.length; i++) array[i] = (Math.random()*256)|0 } };")}())(e)},ge={resolve:function(){for(var e=arguments.length,r=new Array(e),t=0;t=-1&&!o;i--){var a=i>=0?r[i]:Ce.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");if(!a)return"";n=a+"/"+n,o=me.isAbs(a)}return(o?"/":"")+(n=me.normalizeArray(n.split("/").filter((function(e){return!!e})),!o).join("/"))||"."},relative:function(e,r){var t=function(e){for(var r=0;r=0&&""===e[t];t--);return r>t?[]:e.slice(r,t-r+1)};e=ge.resolve(e).substr(1),r=ge.resolve(r).substr(1);for(var n=t(e.split("/")),o=t(r.split("/")),i=Math.min(n.length,o.length),a=i,s=0;s=n);)++o;if(o-r>16&&e.buffer&&ve)return ve.decode(e.subarray(r,o));for(var i="";r>10,56320|1023&c)}}else i+=String.fromCharCode((31&a)<<6|s)}else i+=String.fromCharCode(a)}return i},ye=[],we=function(e){for(var r=0,t=0;t=55296&&n<=57343?(r+=4,++t):r+=3}return r},be=function(e,r,t,n){if(L("string"==typeof e,"stringToUTF8Array expects a string (got "+(void 0===e?"undefined":u(e))+")"),!(n>0))return 0;for(var o=t,i=t+n-1,a=0;a=55296&&s<=57343&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),s<=127){if(t>=i)break;r[t++]=s}else if(s<=2047){if(t+1>=i)break;r[t++]=192|s>>6,r[t++]=128|63&s}else if(s<=65535){if(t+2>=i)break;r[t++]=224|s>>12,r[t++]=128|s>>6&63,r[t++]=128|63&s}else{if(t+3>=i)break;s>1114111&&de("Invalid Unicode code point "+le(s)+" encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."),r[t++]=240|s>>18,r[t++]=128|s>>12&63,r[t++]=128|s>>6&63,r[t++]=128|63&s}}return r[t]=0,t-o};function _e(e,r,t){var n=we(e)+1,o=new Array(n),i=be(e,o,0,o.length);return o.length=i,o}var Se,Oe={ttys:[],init:function(){},shutdown:function(){},register:function(e,r){Oe.ttys[e]={input:[],output:[],ops:r},Ce.registerDevice(e,Oe.stream_ops)},stream_ops:{open:function(e){var r=Oe.ttys[e.node.rdev];if(!r)throw new Ce.ErrnoError(43);e.tty=r,e.seekable=!1},close:function(e){e.tty.ops.fsync(e.tty)},fsync:function(e){e.tty.ops.fsync(e.tty)},read:function(e,r,t,n,o){if(!e.tty||!e.tty.ops.get_char)throw new Ce.ErrnoError(60);for(var i=0,a=0;a0&&(A(Ee(e.output,0)),e.output=[])},ioctl_tcgets:function(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(e,r,t){return 0},ioctl_tiocgwinsz:function(e){return[24,80]}},default_tty1_ops:{put_char:function(e,r){null===r||10===r?(M(Ee(e.output,0)),e.output=[]):0!=r&&e.output.push(r)},fsync:function(e){e.output&&e.output.length>0&&(M(Ee(e.output,0)),e.output=[])}}},Te=function(e){q("internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported")},ke={ops_table:null,mount:function(e){return ke.createNode(null,"/",16895,0)},createNode:function(e,r,t,n){var o;if(Ce.isBlkdev(t)||Ce.isFIFO(t))throw new Ce.ErrnoError(63);(o=ke).ops_table||(o.ops_table={dir:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr,lookup:ke.node_ops.lookup,mknod:ke.node_ops.mknod,rename:ke.node_ops.rename,unlink:ke.node_ops.unlink,rmdir:ke.node_ops.rmdir,readdir:ke.node_ops.readdir,symlink:ke.node_ops.symlink},stream:{llseek:ke.stream_ops.llseek}},file:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr},stream:{llseek:ke.stream_ops.llseek,read:ke.stream_ops.read,write:ke.stream_ops.write,allocate:ke.stream_ops.allocate,mmap:ke.stream_ops.mmap,msync:ke.stream_ops.msync}},link:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr,readlink:ke.node_ops.readlink},stream:{}},chrdev:{node:{getattr:ke.node_ops.getattr,setattr:ke.node_ops.setattr},stream:Ce.chrdev_stream_ops}});var i=Ce.createNode(e,r,t,n);return Ce.isDir(i.mode)?(i.node_ops=ke.ops_table.dir.node,i.stream_ops=ke.ops_table.dir.stream,i.contents={}):Ce.isFile(i.mode)?(i.node_ops=ke.ops_table.file.node,i.stream_ops=ke.ops_table.file.stream,i.usedBytes=0,i.contents=null):Ce.isLink(i.mode)?(i.node_ops=ke.ops_table.link.node,i.stream_ops=ke.ops_table.link.stream):Ce.isChrdev(i.mode)&&(i.node_ops=ke.ops_table.chrdev.node,i.stream_ops=ke.ops_table.chrdev.stream),i.timestamp=Date.now(),e&&(e.contents[r]=i,e.timestamp=i.timestamp),i},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,r){var t=e.contents?e.contents.length:0;if(!(t>=r)){r=Math.max(r,t*(t<1048576?2:1.125)>>>0),0!=t&&(r=Math.max(r,256));var n=e.contents;e.contents=new Uint8Array(r),e.usedBytes>0&&e.contents.set(n.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,r){if(e.usedBytes!=r)if(0==r)e.contents=null,e.usedBytes=0;else{var t=e.contents;e.contents=new Uint8Array(r),t&&e.contents.set(t.subarray(0,Math.min(r,e.usedBytes))),e.usedBytes=r}},node_ops:{getattr:function(e){var r={};return r.dev=Ce.isChrdev(e.mode)?e.id:1,r.ino=e.id,r.mode=e.mode,r.nlink=1,r.uid=0,r.gid=0,r.rdev=e.rdev,Ce.isDir(e.mode)?r.size=4096:Ce.isFile(e.mode)?r.size=e.usedBytes:Ce.isLink(e.mode)?r.size=e.link.length:r.size=0,r.atime=new Date(e.timestamp),r.mtime=new Date(e.timestamp),r.ctime=new Date(e.timestamp),r.blksize=4096,r.blocks=Math.ceil(r.size/r.blksize),r},setattr:function(e,r){void 0!==r.mode&&(e.mode=r.mode),void 0!==r.timestamp&&(e.timestamp=r.timestamp),void 0!==r.size&&ke.resizeFileStorage(e,r.size)},lookup:function(e,r){throw Ce.genericErrors[44]},mknod:function(e,r,t,n){return ke.createNode(e,r,t,n)},rename:function(e,r,t){if(Ce.isDir(e.mode)){var n;try{n=Ce.lookupNode(r,t)}catch(e){}if(n)for(var o in n.contents)throw new Ce.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=t,r.contents[t]=e,r.timestamp=e.parent.timestamp,e.parent=r},unlink:function(e,r){delete e.contents[r],e.timestamp=Date.now()},rmdir:function(e,r){var t=Ce.lookupNode(e,r);for(var n in t.contents)throw new Ce.ErrnoError(55);delete e.contents[r],e.timestamp=Date.now()},readdir:function(e){for(var r,t=[".",".."],n=l(Object.keys(e.contents));!(r=n()).done;){var o=r.value;t.push(o)}return t},symlink:function(e,r,t){var n=ke.createNode(e,r,41471,0);return n.link=t,n},readlink:function(e){if(!Ce.isLink(e.mode))throw new Ce.ErrnoError(28);return e.link}},stream_ops:{read:function(e,r,t,n,o){var i=e.node.contents;if(o>=e.node.usedBytes)return 0;var a=Math.min(e.node.usedBytes-o,n);if(L(a>=0),a>8&&i.subarray)r.set(i.subarray(o,o+a),t);else for(var s=0;s0||t+r8)throw new Ce.ErrnoError(32);for(var t=e.split("/").filter((function(e){return!!e})),n=Ce.root,o="/",i=0;i40)throw new Ce.ErrnoError(32)}}return{path:o,node:n}},getPath:function(e){for(var r;;){if(Ce.isRoot(e)){var t=e.mount.mountpoint;return r?"/"!==t[t.length-1]?t+"/"+r:t+r:t}r=r?e.name+"/"+r:e.name,e=e.parent}},hashName:function(e,r){for(var t=0,n=0;n>>0)%Ce.nameTable.length},hashAddNode:function(e){var r=Ce.hashName(e.parent.id,e.name);e.name_next=Ce.nameTable[r],Ce.nameTable[r]=e},hashRemoveNode:function(e){var r=Ce.hashName(e.parent.id,e.name);if(Ce.nameTable[r]===e)Ce.nameTable[r]=e.name_next;else for(var t=Ce.nameTable[r];t;){if(t.name_next===e){t.name_next=e.name_next;break}t=t.name_next}},lookupNode:function(e,r){var t=Ce.mayLookup(e);if(t)throw new Ce.ErrnoError(t);for(var n=Ce.hashName(e.id,r),o=Ce.nameTable[n];o;o=o.name_next){var i=o.name;if(o.parent.id===e.id&&i===r)return o}return Ce.lookup(e,r)},createNode:function(e,r,t,n){L("object"==(void 0===e?"undefined":u(e)));var o=new Ce.FSNode(e,r,t,n);return Ce.hashAddNode(o),o},destroyNode:function(e){Ce.hashRemoveNode(e)},isRoot:function(e){return e===e.parent},isMountpoint:function(e){return!!e.mounted},isFile:function(e){return 32768==(61440&e)},isDir:function(e){return 16384==(61440&e)},isLink:function(e){return 40960==(61440&e)},isChrdev:function(e){return 8192==(61440&e)},isBlkdev:function(e){return 24576==(61440&e)},isFIFO:function(e){return 4096==(61440&e)},isSocket:function(e){return!(49152&~e)},flagsToPermissionString:function(e){var r=["r","w","rw"][3&e];return 512&e&&(r+="w"),r},nodePermissions:function(e,r){return Ce.ignorePermissions||(!r.includes("r")||292&e.mode)&&(!r.includes("w")||146&e.mode)&&(!r.includes("x")||73&e.mode)?0:2},mayLookup:function(e){if(!Ce.isDir(e.mode))return 54;var r=Ce.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate:function(e,r){try{return Ce.lookupNode(e,r),20}catch(e){}return Ce.nodePermissions(e,"wx")},mayDelete:function(e,r,t){var n;try{n=Ce.lookupNode(e,r)}catch(e){return e.errno}var o=Ce.nodePermissions(e,"wx");if(o)return o;if(t){if(!Ce.isDir(n.mode))return 54;if(Ce.isRoot(n)||Ce.getPath(n)===Ce.cwd())return 10}else if(Ce.isDir(n.mode))return 31;return 0},mayOpen:function(e,r){return e?Ce.isLink(e.mode)?32:Ce.isDir(e.mode)&&("r"!==Ce.flagsToPermissionString(r)||512&r)?31:Ce.nodePermissions(e,Ce.flagsToPermissionString(r)):44},MAX_OPEN_FDS:4096,nextfd:function(){for(var e=0;e<=Ce.MAX_OPEN_FDS;e++)if(!Ce.streams[e])return e;throw new Ce.ErrnoError(33)},getStreamChecked:function(e){var r=Ce.getStream(e);if(!r)throw new Ce.ErrnoError(8);return r},getStream:function(e){return Ce.streams[e]},createStream:function(e,r){return void 0===r&&(r=-1),e=Object.assign(new Ce.FSStream,e),-1==r&&(r=Ce.nextfd()),e.fd=r,Ce.streams[r]=e,e},closeStream:function(e){Ce.streams[e]=null},dupStream:function(e,r){var t,n;void 0===r&&(r=-1);var o=Ce.createStream(e,r);return null==(n=o.stream_ops)||null==(t=n.dup)||t.call(n,o),o},chrdev_stream_ops:{open:function(e){var r=Ce.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,null==e.stream_ops.open||e.stream_ops.open.call(e.stream_ops,e)},llseek:function(){throw new Ce.ErrnoError(70)}},major:function(e){return e>>8},minor:function(e){return 255&e},makedev:function(e,r){return e<<8|r},registerDevice:function(e,r){Ce.devices[e]={stream_ops:r}},getDevice:function(e){return Ce.devices[e]},getMounts:function(e){for(var r=[],t=[e];t.length;){var n,o=t.pop();r.push(o),(n=t).push.apply(n,[].concat(o.mounts))}return r},syncfs:function(e,r){"function"==typeof e&&(r=e,e=!1),Ce.syncFSRequests++,Ce.syncFSRequests>1&&M("warning: "+Ce.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var t=Ce.getMounts(Ce.root.mount),n=0;function o(e){return L(Ce.syncFSRequests>0),Ce.syncFSRequests--,r(e)}function i(e){if(e)return i.errored?void 0:(i.errored=!0,o(e));++n>=t.length&&o(null)}t.forEach((function(r){if(!r.type.syncfs)return i(null);r.type.syncfs(r,e,i)}))},mount:function(e,r,t){if("string"==typeof e)throw e;var n,o="/"===t,i=!t;if(o&&Ce.root)throw new Ce.ErrnoError(10);if(!o&&!i){var a=Ce.lookupPath(t,{follow_mount:!1});if(t=a.path,n=a.node,Ce.isMountpoint(n))throw new Ce.ErrnoError(10);if(!Ce.isDir(n.mode))throw new Ce.ErrnoError(54)}var s={type:e,opts:r,mountpoint:t,mounts:[]},u=e.mount(s);return u.mount=s,s.root=u,o?Ce.root=u:n&&(n.mounted=s,n.mount&&n.mount.mounts.push(s)),u},unmount:function(e){var r=Ce.lookupPath(e,{follow_mount:!1});if(!Ce.isMountpoint(r.node))throw new Ce.ErrnoError(28);var t=r.node,n=t.mounted,o=Ce.getMounts(n);Object.keys(Ce.nameTable).forEach((function(e){for(var r=Ce.nameTable[e];r;){var t=r.name_next;o.includes(r.mount)&&Ce.destroyNode(r),r=t}})),t.mounted=null;var i=t.mount.mounts.indexOf(n);L(-1!==i),t.mount.mounts.splice(i,1)},lookup:function(e,r){return e.node_ops.lookup(e,r)},mknod:function(e,r,t){var n=Ce.lookupPath(e,{parent:!0}).node,o=me.basename(e);if(!o||"."===o||".."===o)throw new Ce.ErrnoError(28);var i=Ce.mayCreate(n,o);if(i)throw new Ce.ErrnoError(i);if(!n.node_ops.mknod)throw new Ce.ErrnoError(63);return n.node_ops.mknod(n,o,r,t)},create:function(e,r){return r=void 0!==r?r:438,r&=4095,r|=32768,Ce.mknod(e,r,0)},mkdir:function(e,r){return r=void 0!==r?r:511,r&=1023,r|=16384,Ce.mknod(e,r,0)},mkdirTree:function(e,r){for(var t=e.split("/"),n="",o=0;o=0),n<0||o<0)throw new Ce.ErrnoError(28);if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(1==(2097155&e.flags))throw new Ce.ErrnoError(8);if(Ce.isDir(e.node.mode))throw new Ce.ErrnoError(31);if(!e.stream_ops.read)throw new Ce.ErrnoError(28);var i=void 0!==o;if(i){if(!e.seekable)throw new Ce.ErrnoError(70)}else o=e.position;var a=e.stream_ops.read(e,r,t,n,o);return i||(e.position+=a),a},write:function(e,r,t,n,o,i){if(L(t>=0),n<0||o<0)throw new Ce.ErrnoError(28);if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(!(2097155&e.flags))throw new Ce.ErrnoError(8);if(Ce.isDir(e.node.mode))throw new Ce.ErrnoError(31);if(!e.stream_ops.write)throw new Ce.ErrnoError(28);e.seekable&&1024&e.flags&&Ce.llseek(e,0,2);var a=void 0!==o;if(a){if(!e.seekable)throw new Ce.ErrnoError(70)}else o=e.position;var s=e.stream_ops.write(e,r,t,n,o,i);return a||(e.position+=s),s},allocate:function(e,r,t){if(Ce.isClosed(e))throw new Ce.ErrnoError(8);if(r<0||t<=0)throw new Ce.ErrnoError(28);if(!(2097155&e.flags))throw new Ce.ErrnoError(8);if(!Ce.isFile(e.node.mode)&&!Ce.isDir(e.node.mode))throw new Ce.ErrnoError(43);if(!e.stream_ops.allocate)throw new Ce.ErrnoError(138);e.stream_ops.allocate(e,r,t)},mmap:function(e,r,t,n,o){if(2&n&&!(2&o)&&2!=(2097155&e.flags))throw new Ce.ErrnoError(2);if(1==(2097155&e.flags))throw new Ce.ErrnoError(2);if(!e.stream_ops.mmap)throw new Ce.ErrnoError(43);return e.stream_ops.mmap(e,r,t,n,o)},msync:function(e,r,t,n,o){return L(t>=0),e.stream_ops.msync?e.stream_ops.msync(e,r,t,n,o):0},ioctl:function(e,r,t){if(!e.stream_ops.ioctl)throw new Ce.ErrnoError(59);return e.stream_ops.ioctl(e,r,t)},readFile:function(e,r){if(void 0===r&&(r={}),r.flags=r.flags||0,r.encoding=r.encoding||"binary","utf8"!==r.encoding&&"binary"!==r.encoding)throw new Error('Invalid encoding type "'+r.encoding+'"');var t,n=Ce.open(e,r.flags),o=Ce.stat(e).size,i=new Uint8Array(o);return Ce.read(n,i,0,o,0),"utf8"===r.encoding?t=Ee(i,0):"binary"===r.encoding&&(t=i),Ce.close(n),t},writeFile:function(e,r,t){void 0===t&&(t={}),t.flags=t.flags||577;var n=Ce.open(e,t.flags,t.mode);if("string"==typeof r){var o=new Uint8Array(we(r)+1),i=be(r,o,0,o.length);Ce.write(n,o,0,i,void 0,t.canOwn)}else{if(!ArrayBuffer.isView(r))throw new Error("Unsupported data type");Ce.write(n,r,0,r.byteLength,void 0,t.canOwn)}Ce.close(n)},cwd:function(){return Ce.currentPath},chdir:function(e){var r=Ce.lookupPath(e,{follow:!0});if(null===r.node)throw new Ce.ErrnoError(44);if(!Ce.isDir(r.node.mode))throw new Ce.ErrnoError(54);var t=Ce.nodePermissions(r.node,"x");if(t)throw new Ce.ErrnoError(t);Ce.currentPath=r.path},createDefaultDirectories:function(){Ce.mkdir("/tmp"),Ce.mkdir("/home"),Ce.mkdir("/home/web_user")},createDefaultDevices:function(){Ce.mkdir("/dev"),Ce.registerDevice(Ce.makedev(1,3),{read:function(){return 0},write:function(e,r,t,n,o){return n}}),Ce.mkdev("/dev/null",Ce.makedev(1,3)),Oe.register(Ce.makedev(5,0),Oe.default_tty_ops),Oe.register(Ce.makedev(6,0),Oe.default_tty1_ops),Ce.mkdev("/dev/tty",Ce.makedev(5,0)),Ce.mkdev("/dev/tty1",Ce.makedev(6,0));var e=new Uint8Array(1024),r=0,t=function(){return 0===r&&(r=he(e).byteLength),e[--r]};Ce.createDevice("/dev","random",t),Ce.createDevice("/dev","urandom",t),Ce.mkdir("/dev/shm"),Ce.mkdir("/dev/shm/tmp")},createSpecialDirectories:function(){Ce.mkdir("/proc");var e=Ce.mkdir("/proc/self");Ce.mkdir("/proc/self/fd"),Ce.mount({mount:function(){var r=Ce.createNode(e,"fd",16895,73);return r.node_ops={lookup:function(e,r){var t=+r,n=Ce.getStreamChecked(t),o={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:function(){return n.path}}};return o.parent=o,o}},r}},{},"/proc/self/fd")},createStandardStreams:function(){d.stdin?Ce.createDevice("/dev","stdin",d.stdin):Ce.symlink("/dev/tty","/dev/stdin"),d.stdout?Ce.createDevice("/dev","stdout",null,d.stdout):Ce.symlink("/dev/tty","/dev/stdout"),d.stderr?Ce.createDevice("/dev","stderr",null,d.stderr):Ce.symlink("/dev/tty1","/dev/stderr");var e=Ce.open("/dev/stdin",0),r=Ce.open("/dev/stdout",1),t=Ce.open("/dev/stderr",1);L(0===e.fd,"invalid handle for stdin ("+e.fd+")"),L(1===r.fd,"invalid handle for stdout ("+r.fd+")"),L(2===t.fd,"invalid handle for stderr ("+t.fd+")")},staticInit:function(){[44].forEach((function(e){Ce.genericErrors[e]=new Ce.ErrnoError(e),Ce.genericErrors[e].stack=""})),Ce.nameTable=new Array(4096),Ce.mount(ke,{},"/"),Ce.createDefaultDirectories(),Ce.createDefaultDevices(),Ce.createSpecialDirectories(),Ce.filesystems={MEMFS:ke}},init:function(e,r,t){L(!Ce.init.initialized,"FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"),Ce.init.initialized=!0,d.stdin=e||d.stdin,d.stdout=r||d.stdout,d.stderr=t||d.stderr,Ce.createStandardStreams()},quit:function(){Ce.init.initialized=!1,tr(0);for(var e=0;ethis.length-1||e<0)){var r=e%this.chunkSize,t=e/this.chunkSize|0;return this.getter(t)[r]}},r.setDataGetter=function(e){this.getter=e},r.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",t,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+t+". Status: "+e.status);var r,n=Number(e.getResponseHeader("Content-length")),o=(r=e.getResponseHeader("Accept-Ranges"))&&"bytes"===r,i=(r=e.getResponseHeader("Content-Encoding"))&&"gzip"===r,a=1048576;o||(a=n);var s=this;s.setDataGetter((function(e){var r=e*a,o=(e+1)*a-1;if(o=Math.min(o,n-1),void 0===s.chunks[e]&&(s.chunks[e]=function(e,r){if(e>r)throw new Error("invalid range ("+e+", "+r+") or no bytes requested!");if(r>n-1)throw new Error("only "+n+" bytes available! programmer error!");var o=new XMLHttpRequest;if(o.open("GET",t,!1),n!==a&&o.setRequestHeader("Range","bytes="+e+"-"+r),o.responseType="arraybuffer",o.overrideMimeType&&o.overrideMimeType("text/plain; charset=x-user-defined"),o.send(null),!(o.status>=200&&o.status<300||304===o.status))throw new Error("Couldn't load "+t+". Status: "+o.status);return void 0!==o.response?new Uint8Array(o.response||[]):_e(o.responseText||"")}(r,o)),void 0===s.chunks[e])throw new Error("doXHR failed!");return s.chunks[e]})),!i&&n||(a=n=1,n=this.getter(0).length,a=n,A("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=n,this._chunkSize=a,this.lengthKnown=!0},o(e,[{key:"length",get:function(){return this.lengthKnown||this.cacheLength(),this._length}},{key:"chunkSize",get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}]),e}();if("undefined"!=typeof XMLHttpRequest){if(!h)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s={isDevice:!1,contents:new a}}else s={isDevice:!1,url:t};var u=Ce.createFile(e,r,s,n,i);s.contents?u.contents=s.contents:s.url&&(u.contents=null,u.url=s.url),Object.defineProperties(u,{usedBytes:{get:function(){return this.contents.length}}});var c={};function l(e,r,t,n,o){var i=e.node.contents;if(o>=i.length)return 0;var a=Math.min(i.length-o,n);if(L(a>=0),i.slice)for(var s=0;s>2]=n.dev,D[t+4>>2]=n.mode,x[t+8>>2]=n.nlink,D[t+12>>2]=n.uid,D[t+16>>2]=n.gid,D[t+20>>2]=n.rdev,J=[n.size>>>0,(X=n.size,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+24>>2]=J[0],D[t+28>>2]=J[1],D[t+32>>2]=4096,D[t+36>>2]=n.blocks;var o=n.atime.getTime(),i=n.mtime.getTime(),a=n.ctime.getTime();return J=[Math.floor(o/1e3)>>>0,(X=Math.floor(o/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+40>>2]=J[0],D[t+44>>2]=J[1],x[t+48>>2]=o%1e3*1e3,J=[Math.floor(i/1e3)>>>0,(X=Math.floor(i/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+56>>2]=J[0],D[t+60>>2]=J[1],x[t+64>>2]=i%1e3*1e3,J=[Math.floor(a/1e3)>>>0,(X=Math.floor(a/1e3),+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+72>>2]=J[0],D[t+76>>2]=J[1],x[t+80>>2]=a%1e3*1e3,J=[n.ino>>>0,(X=n.ino,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[t+88>>2]=J[0],D[t+92>>2]=J[1],0},doMsync:function(e,r,t,n,o){if(!Ce.isFile(r.node.mode))throw new Ce.ErrnoError(43);if(2&n)return 0;var i=F.slice(e,e+t);Ce.msync(r,i,o,t,n)},getStreamFromFD:function(e){return Ce.getStreamChecked(e)},varargs:void 0,getStr:function(e){return De(e)}},Ie=function(e,r){return L(e==e>>>0||e==(0|e)),L(r===(0|r)),r+2097152>>>0<4194305-!!e?(e>>>0)+4294967296*r:NaN},Le=[0,31,60,91,121,152,182,213,244,274,305,335],Ne=[0,31,59,90,120,151,181,212,243,273,304,334],Re=function(e){var r;return((r=e.getFullYear())%4!=0||r%100==0&&r%400!=0?Ne:Le)[e.getMonth()]+e.getDate()-1},Ue=function(e,r,t){return L("number"==typeof t,"stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!"),be(e,F,r,t)};Se=function(){return performance.now()};var Be,je,$e=function(e){var r=k.buffer,t=(e-r.byteLength+65535)/65536;try{return k.grow(t),N(),1}catch(t){M("growMemory: Attempted to grow heap from "+r.byteLength+" bytes to "+e+" bytes, but got error: "+t)}},We={},He=function(){if(!He.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==("undefined"==typeof navigator?"undefined":u(navigator))&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:_||"./this.program"};for(var r in We)void 0===We[r]?delete e[r]:e[r]=We[r];var t=[];for(var r in e)t.push(r+"="+e[r]);He.strings=t}return He.strings},ze=function(e){return sr(e)},Ve=function(e,r,t,n,o){var i={string:function(e){var r=0;return null!=e&&0!==e&&(r=function(e){var r=we(e)+1,t=ze(r);return Ue(e,t,r),t}(e)),r},array:function(e){var r,t,n=ze(e.length);return t=n,L((r=e).length>=0,"writeArrayToMemory array must have a length (should be an array or typed array)"),P.set(r,t),n}},a=function(e){var r=d["_"+e];return L(r,"Cannot call unknown function "+e+", make sure it is exported"),r}(e),s=[],u=0;if(L("array"!==r,'Return type should not be "array".'),n)for(var c=0;c>7)},Ye=function(e,r){var t;if(L(!r.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled"),"function"==typeof WebAssembly.Function)return new WebAssembly.Function(function(e){L(!e.includes("j"),"i64 not permitted in function signatures when WASM_BIGINT is disabled");for(var r={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},t={parameters:[],results:"v"==e[0]?[]:[r[e[0]]]},n=1;n=Qe.length&&(Qe.length=e+1),Qe[e]=r=Be.get(e)),L(Be.get(e)==r,"JavaScript-side Wasm function table mirror is out of date!"),r},Ke=function(e){return je||(je=new WeakMap,function(e,r){if(je)for(var t=e;t>1]=2,0}return-28}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return-e.errno}},__syscall_openat:function(e,r,t,n){xe.varargs=n;try{r=xe.getStr(r),r=xe.calculateAt(e,r);var o=n?fe():0;return Ce.open(r,t,o).fd}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return-e.errno}},_abort_js:function(){q("native code called abort()")},_emscripten_get_now_is_monotonic:function(){return 1},_emscripten_memcpy_js:function(e,r,t){return F.copyWithin(e,r,r+t)},_gmtime_js:function(e,r,t){var n=Ie(e,r),o=new Date(1e3*n);D[t>>2]=o.getUTCSeconds(),D[t+4>>2]=o.getUTCMinutes(),D[t+8>>2]=o.getUTCHours(),D[t+12>>2]=o.getUTCDate(),D[t+16>>2]=o.getUTCMonth(),D[t+20>>2]=o.getUTCFullYear()-1900,D[t+24>>2]=o.getUTCDay();var i=Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0),a=(o.getTime()-i)/864e5|0;D[t+28>>2]=a},_localtime_js:function(e,r,t){var n=Ie(e,r),o=new Date(1e3*n);D[t>>2]=o.getSeconds(),D[t+4>>2]=o.getMinutes(),D[t+8>>2]=o.getHours(),D[t+12>>2]=o.getDate(),D[t+16>>2]=o.getMonth(),D[t+20>>2]=o.getFullYear()-1900,D[t+24>>2]=o.getDay();var i=0|Re(o);D[t+28>>2]=i,D[t+36>>2]=-60*o.getTimezoneOffset();var a=new Date(o.getFullYear(),0,1),s=new Date(o.getFullYear(),6,1).getTimezoneOffset(),u=a.getTimezoneOffset(),c=0|(s!=u&&o.getTimezoneOffset()==Math.min(u,s));D[t+32>>2]=c},_mktime_js:function(e){var r,t=function(){var r=new Date(D[e+20>>2]+1900,D[e+16>>2],D[e+12>>2],D[e+8>>2],D[e+4>>2],D[e>>2],0),t=D[e+32>>2],n=r.getTimezoneOffset(),o=new Date(r.getFullYear(),0,1),i=new Date(r.getFullYear(),6,1).getTimezoneOffset(),a=o.getTimezoneOffset(),s=Math.min(a,i);if(t<0)D[e+32>>2]=Number(i!=a&&s==n);else if(t>0!=(s==n)){var u=Math.max(a,i),c=t>0?s:u;r.setTime(r.getTime()+6e4*(c-n))}D[e+24>>2]=r.getDay();var l=0|Re(r);D[e+28>>2]=l,D[e>>2]=r.getSeconds(),D[e+4>>2]=r.getMinutes(),D[e+8>>2]=r.getHours(),D[e+12>>2]=r.getDate(),D[e+16>>2]=r.getMonth(),D[e+20>>2]=r.getYear();var d=r.getTime();return isNaN(d)?-1:d/1e3}();return X=t,r=+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0,nr(r),t>>>0},_tzset_js:function(e,r,t,n){var o=(new Date).getFullYear(),i=new Date(o,0,1),a=new Date(o,6,1),s=i.getTimezoneOffset(),u=a.getTimezoneOffset(),c=Math.max(s,u);x[e>>2]=60*c,D[r>>2]=Number(s!=u);var l=function(e){return e.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1]},d=l(i),f=l(a);L(d),L(f),L(we(d)<=16,"timezone name truncated to fit in TZNAME_MAX ("+d+")"),L(we(f)<=16,"timezone name truncated to fit in TZNAME_MAX ("+f+")"),u>>=0)>r);var t=2147483648;if(e>t)return M("Cannot enlarge memory, requested "+e+" bytes, but the limit is "+t+" bytes!"),!1;for(var n,o,i=1;i<=4;i*=2){var a=r*(1+.2/i);a=Math.min(a,e+100663296);var s=Math.min(t,(n=Math.max(e,a))+((o=65536)-n%o)%o);if($e(s))return!0}return M("Failed to grow the heap from "+r+" bytes to "+s+" bytes, not enough memory!"),!1},environ_get:function(e,r){var t=0;return He().forEach((function(n,o){var i=r+t;x[e+4*o>>2]=i,function(e,r){for(var t=0;t>2]=t.length;var n=0;return t.forEach((function(e){return n+=e.length+1})),x[r>>2]=n,0},fd_close:function(e){try{var r=xe.getStreamFromFD(e);return Ce.close(r),0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_fdstat_get:function(e,r){try{var t=xe.getStreamFromFD(e),n=t.tty?2:Ce.isDir(t.mode)?3:Ce.isLink(t.mode)?7:4;return P[r]=n,C[r+2>>1]=0,J=[0,(X=0,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[r+8>>2]=J[0],D[r+12>>2]=J[1],J=[0,(X=0,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[r+16>>2]=J[0],D[r+20>>2]=J[1],0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_read:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,i=0;i>2],s=x[r+4>>2];r+=8;var u=Ce.read(e,P,a,s,n);if(u<0)return-1;if(o+=u,u>2]=o,0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_seek:function(e,r,t,n,o){var i=Ie(r,t);try{if(isNaN(i))return 61;var a=xe.getStreamFromFD(e);return Ce.llseek(a,i,n),J=[a.position>>>0,(X=a.position,+Math.abs(X)>=1?X>0?+Math.floor(X/4294967296)>>>0:~~+Math.ceil((X-+(~~X>>>0))/4294967296)>>>0:0)],D[o>>2]=J[0],D[o+4>>2]=J[1],a.getdents&&0===i&&0===n&&(a.getdents=null),0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}},fd_write:function(e,r,t,n){try{var o=function(e,r,t,n){for(var o=0,i=0;i>2],s=x[r+4>>2];r+=8;var u=Ce.write(e,P,a,s,n);if(u<0)return-1;o+=u}return o}(xe.getStreamFromFD(e),r,t);return x[n>>2]=o,0}catch(e){if(void 0===Ce||"ErrnoError"!==e.name)throw e;return e.errno}}},er=function(){var e={env:Ze,wasi_snapshot_preview1:Ze};function r(e,r){var t;return er=e.exports,L(k=er.memory,"memory not found in wasm exports"),N(),L(Be=er.__indirect_function_table,"table not found in wasm exports"),t=er.__wasm_call_ctors,B.unshift(t),Q("wasm-instantiate"),er}Y("wasm-instantiate");var t,n,o,a,s=d;if(d.instantiateWasm)try{return d.instantiateWasm(e,r)}catch(e){M("Module.instantiateWasm callback failed with error: "+e),i(e)}return K||(K=te()),(t=T,n=K,o=e,a=function(e){L(d===s,"the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"),s=null,r(e.instance)},t||"function"!=typeof WebAssembly.instantiateStreaming||Z(n)||"function"!=typeof fetch?oe(n,o,a):fetch(n,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,o).then(a,(function(e){return M("wasm streaming compile failed: "+e),M("falling back to ArrayBuffer instantiation"),oe(n,o,a)}))}))).catch(i),{}}();d._malloc=re("malloc",1),d._free=re("free",1),d._registerWasmPlayer=re("registerWasmPlayer",0),d._setCodecType=re("setCodecType",4),d._exitWasmPlayer=re("exitWasmPlayer",1),d._initDecoder=re("initDecoder",1),d._decodeCodecContext=re("decodeCodecContext",5),d._destroy=re("destroy",1),d._demuxTsStream=re("demuxTsStream",3),d._getPacket=re("getPacket",0),d._getVLCLen=re("getVLCLen",0),d._getVLC=re("getVLC",0),d._getVPSLen=re("getVPSLen",0),d._getVPS=re("getVPS",0),d._getSPSLen=re("getSPSLen",0),d._getSPS=re("getSPS",0),d._getPPSLen=re("getPPSLen",0),d._getPPS=re("getPPS",0),d._getSEILen=re("getSEILen",0),d._getSEI=re("getSEI",0);var rr,tr=re("fflush",1),nr=re("_emscripten_tempret_set",1),or=function(){return(or=er.emscripten_stack_init)()},ir=function(){return(ir=er.emscripten_stack_get_end)()},ar=function(e){return(ar=er._emscripten_stack_restore)(e)},sr=function(e){return(sr=er._emscripten_stack_alloc)(e)},ur=function(){return(ur=er.emscripten_stack_get_current)()};function cr(){var e;or(),L(!(3&(e=ir()))),0==e&&(e+=4),x[e>>2]=34821223,x[e+4>>2]=2310721022,x[0]=1668509029}function lr(){function e(){rr||(rr=!0,d.calledRun=!0,I||(L(!$),$=!0,R(),d.noFSInit||Ce.init.initialized||Ce.init(),Ce.ignorePermissions=!1,ce(B),n(d),d.onRuntimeInitialized&&d.onRuntimeInitialized(),L(!d._main,'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'),function(){if(R(),d.postRun)for("function"==typeof d.postRun&&(d.postRun=[d.postRun]);d.postRun.length;)e=d.postRun.shift(),j.unshift(e);var e;ce(j)}()))}W>0||(cr(),function(){if(d.preRun)for("function"==typeof d.preRun&&(d.preRun=[d.preRun]);d.preRun.length;)e=d.preRun.shift(),U.unshift(e);var e;ce(U)}(),W>0||(d.setStatus?(d.setStatus("Running..."),setTimeout((function(){setTimeout((function(){d.setStatus("")}),1),e()}),1)):e(),R()))}if(d.dynCall_jiji=re("dynCall_jiji",5),d.dynCall_iiiiij=re("dynCall_iiiiij",7),d.dynCall_jiiij=re("dynCall_jiiij",6),d._ff_h264_cabac_tables=113148,d.run=lr,d.ccall=Ve,d.cwrap=function(e,r,t,n){return function(){for(var n=arguments.length,o=new Array(n),i=0;i0;)d.preInit.pop()();lr(),r=p;for(var dr,fr=l(Object.keys(d));!(dr=fr()).done;)t();return r});"object"===u(r)&&"object"===u(e)&&(e.exports=p)}(t,t.exports);var n,o,i,a,s=r(t.exports),u="wasmLoading",c="wasmLoaded",l="wasmFailed",d="registerWasmPlayer",f="videoCallback",p="decodeCodecContext",m="destroy",h="demuxTsStream",g="demuxCoreReceive",v="readPacket",E="readPacketEnd",y="mediaInfo",w=function(e,r){return{cmd:e,data:r}},b=(n="undefined"!=typeof self?self:window,o={navigator:void 0!==n.navigator?n.navigator:{userAgent:""},infoMap:{engine:["WebKit","Trident","Gecko","Presto"],browser:["Safari","Chrome","Edge","IE","Firefox","Firefox Focus","Chromium","Opera","Vivaldi","Yandex","Arora","Lunascape","QupZilla","Coc Coc","Kindle","Iceweasel","Konqueror","Iceape","SeaMonkey","Epiphany","360","360SE","360EE","UC","QQBrowser","QQ","Baidu","Maxthon","Sogou","LBBROWSER","2345Explorer","TheWorld","XiaoMi","Quark","Qiyu","Wechat","Taobao","Alipay","Weibo","Douban","Suning","iQiYi"],os:["Windows","Linux","Mac OS","Android","Ubuntu","FreeBSD","Debian","iOS","Windows Phone","BlackBerry","MeeGo","Symbian","Chrome OS","WebOS"],device:["Mobile","Tablet","iPad"]}},i={getMatchMap:function(e){return{Trident:e.indexOf("Trident")>-1||e.indexOf("NET CLR")>-1,Presto:e.indexOf("Presto")>-1,WebKit:e.indexOf("AppleWebKit")>-1,Gecko:e.indexOf("Gecko/")>-1,Safari:e.indexOf("Safari")>-1,Chrome:e.indexOf("Chrome")>-1||e.indexOf("CriOS")>-1,IE:e.indexOf("MSIE")>-1||e.indexOf("Trident")>-1,Edge:e.indexOf("Edge")>-1,Firefox:e.indexOf("Firefox")>-1||e.indexOf("FxiOS")>-1,"Firefox Focus":e.indexOf("Focus")>-1,Chromium:e.indexOf("Chromium")>-1,Opera:e.indexOf("Opera")>-1||e.indexOf("OPR")>-1,Vivaldi:e.indexOf("Vivaldi")>-1,Yandex:e.indexOf("YaBrowser")>-1,Arora:e.indexOf("Arora")>-1,Lunascape:e.indexOf("Lunascape")>-1,QupZilla:e.indexOf("QupZilla")>-1,"Coc Coc":e.indexOf("coc_coc_browser")>-1,Kindle:e.indexOf("Kindle")>-1||e.indexOf("Silk/")>-1,Iceweasel:e.indexOf("Iceweasel")>-1,Konqueror:e.indexOf("Konqueror")>-1,Iceape:e.indexOf("Iceape")>-1,SeaMonkey:e.indexOf("SeaMonkey")>-1,Epiphany:e.indexOf("Epiphany")>-1,360:e.indexOf("QihooBrowser")>-1||e.indexOf("QHBrowser")>-1,"360EE":e.indexOf("360EE")>-1,"360SE":e.indexOf("360SE")>-1,UC:e.indexOf("UC")>-1||e.indexOf(" UBrowser")>-1,QQBrowser:e.indexOf("QQBrowser")>-1,QQ:e.indexOf("QQ/")>-1,Baidu:e.indexOf("Baidu")>-1||e.indexOf("BIDUBrowser")>-1,Maxthon:e.indexOf("Maxthon")>-1,Sogou:e.indexOf("MetaSr")>-1||e.indexOf("Sogou")>-1,LBBROWSER:e.indexOf("LBBROWSER")>-1,"2345Explorer":e.indexOf("2345Explorer")>-1,TheWorld:e.indexOf("TheWorld")>-1,XiaoMi:e.indexOf("MiuiBrowser")>-1,Quark:e.indexOf("Quark")>-1,Qiyu:e.indexOf("Qiyu")>-1,Wechat:e.indexOf("MicroMessenger")>-1,Taobao:e.indexOf("AliApp(TB")>-1,Alipay:e.indexOf("AliApp(AP")>-1,Weibo:e.indexOf("Weibo")>-1,Douban:e.indexOf("com.douban.frodo")>-1,Suning:e.indexOf("SNEBUY-APP")>-1,iQiYi:e.indexOf("IqiyiApp")>-1,Windows:e.indexOf("Windows")>-1,Linux:e.indexOf("Linux")>-1||e.indexOf("X11")>-1,"Mac OS":e.indexOf("Macintosh")>-1,Android:e.indexOf("Android")>-1||e.indexOf("Adr")>-1,Ubuntu:e.indexOf("Ubuntu")>-1,FreeBSD:e.indexOf("FreeBSD")>-1,Debian:e.indexOf("Debian")>-1,"Windows Phone":e.indexOf("IEMobile")>-1||e.indexOf("Windows Phone")>-1,BlackBerry:e.indexOf("BlackBerry")>-1||e.indexOf("RIM")>-1,MeeGo:e.indexOf("MeeGo")>-1,Symbian:e.indexOf("Symbian")>-1,iOS:e.indexOf("like Mac OS X")>-1,"Chrome OS":e.indexOf("CrOS")>-1,WebOS:e.indexOf("hpwOS")>-1,Mobile:e.indexOf("Mobi")>-1||e.indexOf("iPh")>-1||e.indexOf("480")>-1,Tablet:e.indexOf("Tablet")>-1||e.indexOf("Nexus 7")>-1,iPad:e.indexOf("iPad")>-1}},matchInfoMap:function(e){var r,t=(null==(r=o.navigator)?void 0:r.userAgent)||"",n=i.getMatchMap(t);for(var a in o.infoMap)for(var s=0;s36&&n.showModalDialog?s=!0:+u>45&&(s=t("type","application/vnd.chromium.remoting-viewer"))}if(a.Baidu&&a.Opera&&(a.Baidu=!1),a.Mobile&&(a.Mobile=!r.includes("iPad")),s&&(t("type","application/gameplugin")||o.navigator&&void 0===o.navigator.connection.saveData?a["360SE"]=!0:a["360EE"]=!0),a.IE||a.Edge)switch(window.screenTop-window.screenY){case 71:case 74:case 99:case 75:case 105:break;case 102:a["360EE"]=!0;break;case 104:a["360SE"]=!0}var c={Safari:function(){return r.replace(/^.*Version\/([\d.]+).*$/,"$1")},Chrome:function(){return r.replace(/^.*Chrome\/([\d.]+).*$/,"$1").replace(/^.*CriOS\/([\d.]+).*$/,"$1")},IE:function(){return r.replace(/^.*MSIE ([\d.]+).*$/,"$1").replace(/^.*rv:([\d.]+).*$/,"$1")},Edge:function(){return r.replace(/^.*Edge\/([\d.]+).*$/,"$1")},Firefox:function(){return r.replace(/^.*Firefox\/([\d.]+).*$/,"$1").replace(/^.*FxiOS\/([\d.]+).*$/,"$1")},"Firefox Focus":function(){return r.replace(/^.*Focus\/([\d.]+).*$/,"$1")},Chromium:function(){return r.replace(/^.*Chromium\/([\d.]+).*$/,"$1")},Opera:function(){return r.replace(/^.*Opera\/([\d.]+).*$/,"$1").replace(/^.*OPR\/([\d.]+).*$/,"$1")},Vivaldi:function(){return r.replace(/^.*Vivaldi\/([\d.]+).*$/,"$1")},Yandex:function(){return r.replace(/^.*YaBrowser\/([\d.]+).*$/,"$1")},Arora:function(){return r.replace(/^.*Arora\/([\d.]+).*$/,"$1")},Lunascape:function(){return r.replace(/^.*Lunascape[\/\s]([\d.]+).*$/,"$1")},QupZilla:function(){return r.replace(/^.*QupZilla[\/\s]([\d.]+).*$/,"$1")},"Coc Coc":function(){return r.replace(/^.*coc_coc_browser\/([\d.]+).*$/,"$1")},Kindle:function(){return r.replace(/^.*Version\/([\d.]+).*$/,"$1")},Iceweasel:function(){return r.replace(/^.*Iceweasel\/([\d.]+).*$/,"$1")},Konqueror:function(){return r.replace(/^.*Konqueror\/([\d.]+).*$/,"$1")},Iceape:function(){return r.replace(/^.*Iceape\/([\d.]+).*$/,"$1")},SeaMonkey:function(){return r.replace(/^.*SeaMonkey\/([\d.]+).*$/,"$1")},Epiphany:function(){return r.replace(/^.*Epiphany\/([\d.]+).*$/,"$1")},360:function(){return r.replace(/^.*QihooBrowser\/([\d.]+).*$/,"$1")},"360SE":function(){return{63:"10.0",55:"9.1",45:"8.1",42:"8.0",31:"7.0",21:"6.3"}[+r.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"360EE":function(){return{69:"11.0",63:"9.5",55:"9.0",50:"8.7",30:"7.5"}[+r.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},Maxthon:function(){return r.replace(/^.*Maxthon\/([\d.]+).*$/,"$1")},QQBrowser:function(){return r.replace(/^.*QQBrowser\/([\d.]+).*$/,"$1")},QQ:function(){return r.replace(/^.*QQ\/([\d.]+).*$/,"$1")},Baidu:function(){return r.replace(/^.*BIDUBrowser[\s\/]([\d.]+).*$/,"$1")},UC:function(){return r.replace(/^.*UC?Browser\/([\d.]+).*$/,"$1")},Sogou:function(){return r.replace(/^.*SE ([\d.X]+).*$/,"$1").replace(/^.*SogouMobileBrowser\/([\d.]+).*$/,"$1")},LBBROWSER:function(){return{57:"6.5",49:"6.0",46:"5.9",42:"5.3",39:"5.2",34:"5.0",29:"4.5",21:"4.0"}[+navigator.userAgent.replace(/^.*Chrome\/([\d]+).*$/,"$1")]||""},"2345Explorer":function(){return r.replace(/^.*2345Explorer\/([\d.]+).*$/,"$1")},TheWorld:function(){return r.replace(/^.*TheWorld ([\d.]+).*$/,"$1")},XiaoMi:function(){return r.replace(/^.*MiuiBrowser\/([\d.]+).*$/,"$1")},Quark:function(){return r.replace(/^.*Quark\/([\d.]+).*$/,"$1")},Qiyu:function(){return r.replace(/^.*Qiyu\/([\d.]+).*$/,"$1")},Wechat:function(){return r.replace(/^.*MicroMessenger\/([\d.]+).*$/,"$1")},Taobao:function(){return r.replace(/^.*AliApp\(TB\/([\d.]+).*$/,"$1")},Alipay:function(){return r.replace(/^.*AliApp\(AP\/([\d.]+).*$/,"$1")},Weibo:function(){return r.replace(/^.*weibo__([\d.]+).*$/,"$1")},Douban:function(){return r.replace(/^.*com.douban.frodo\/([\d.]+).*$/,"$1")},Suning:function(){return r.replace(/^.*SNEBUY-APP([\d.]+).*$/,"$1")},iQiYi:function(){return r.replace(/^.*IqiyiVersion\/([\d.]+).*$/,"$1")}};return e.browserVersion="",c[e.browser]&&(e.browserVersion=c[e.browser](),e.browserVersion==r&&(e.browserVersion="")),"Edge"==e.browser&&(e.engine="EdgeHTML"),"Chrome"==e.browser&&parseInt(e.browserVersion)>27&&(e.engine="Blink"),"Opera"==e.browser&&parseInt(e.browserVersion)>12&&(e.engine="Blink"),"Yandex"==e.browser&&(e.engine="Blink"),e.browser+" (version: "+e.browserVersion+"; kernel: "+e.engine+")"}},a={DeviceInfoObj:function(e){var r,t=function(r){var t;null==(t=e.info)||t.forEach((function(e){e.toLowerCase()===r.toLowerCase()&&(s[r]=a[r])}))};e=e||{domain:""};var a={deviceType:i.getDeviceType(),OS:i.getOS(),OSVersion:i.getOSVersion(),sh:n.screen.height,sw:n.screen.width,lang:i.getLanguage(),netWork:i.getNetwork(),orientation:i.getOrientationStatu(),browserInfo:i.getBrowserInfo(),fingerprint:i.createFingerprint(e.domain),userAgent:null==(r=o.navigator)?void 0:r.userAgent};if(!e.info||0===e.info.length)return a;var s={};for(var u in a)t(u);return s}},{getDeviceInfo:function(e){return a.DeviceInfoObj(e)}}),_=function(){function e(){}return e.add=function(r,t){e.queues.push({url:r,data:t})},e.fire=function(){if(e.queues&&0!==e.queues.length){e.isStop=!1;var r=e.queues[0];r.url&&e.api.report(r.data),e.queues.splice(0,1),e.fire()}else e.isStop=!0},e}();_.isStop=!0,_.queues=[];var S=function(){function e(e){this.url=e}var r=e.prototype;return r.report=function(e){this.checkUrl(this.url)&&this.sendInfo(e)},r.sendInfo=function(e){navigator.sendBeacon?this.sendBeacon(this.url,e):this.sendImage(this.url,e)},r.sendImage=function(e,r){var t=this.changeJSON2Query(r),n=new Image;n.onload=n.onerror=function(){n=null},n.src=e+"?"+t+"&random="+Math.random()},r.sendBeacon=function(e,r){try{navigator.sendBeacon(e,this.formatParamsByURLSearchParams(r))}catch(e){}},r.formatParamsByURLSearchParams=function(e){var r=new URLSearchParams;for(var t in e)"object"==typeof e[t]&&(e[t]=JSON.stringify(e[t])),r.append(t,e[t]);return r},r.changeJSON2Query=function(e){var r="";for(var t in e){""!=r&&(r+="&");var n=e[t];r+=t+"="+encodeURIComponent("object"==typeof n?JSON.stringify(n):n)}return r},r.checkUrl=function(e){return!!e&&/^[hH][tT][tT][pP]([sS]?):\/\//.test(e)},e}();function O(){return O=Object.assign||function(e){for(var r=1;r0&&(r._free(l),l=null),{};var d=r.HEAPU8.subarray(l,l+c);s.sps=new Uint8Array(c),null==(n=s.sps)||n.set(d,0);var f=r.cwrap("getPPSLen","number",[])(),p=r.cwrap("getPPS","number",[])(),m=r.HEAPU8.subarray(p,p+f);s.pps=new Uint8Array(f),null==(o=s.pps)||o.set(m,0);var h=r.cwrap("getSEILen","number",[])(),g=r.cwrap("getSEI","number",[])(),v=r.HEAPU8.subarray(g,g+h);s.sei=new Uint8Array(h),null==(i=s.sei)||i.set(v,0);var E=r.cwrap("getVLCLen","number",[])(),y=r.cwrap("getVLC","number",[])(),w=r.HEAPU8.subarray(y,y+E);if(u.vlc=new Uint8Array(E),null==(a=u.vlc)||a.set(w,0),(null==t?void 0:t.vCodec)===e.DEF_HEVC||(null==t?void 0:t.vCodec)===e.DEF_H265){var b,_=r.cwrap("getVPSLen","number",[])(),S=r.cwrap("getVPS","number",[])(),O=r.HEAPU8.subarray(S,S+_);s.vps=new Uint8Array(_),null==(b=s.vps)||b.set(O,0),r._free(O),O=null}try{r._free(l)}catch(e){k.send("worker",{name:"readPacket",free:"spsPtr"})}l=null;try{r._free(d)}catch(e){k.send("worker",{name:"readPacket",free:"spsSubPtr"})}d=null;try{r._free(m)}catch(e){k.send("worker",{name:"readPacket",free:"ppsSubPtr"})}m=null;try{r._free(v)}catch(e){k.send("worker",{name:"readPacket",free:"seiSubPtr"})}v=null;try{r._free(w)}catch(e){k.send("worker",{name:"readPacket",free:"vlcSubPtr"})}return w=null,{nalu:s,vlc:u}};function F(){return F=Object.assign||function(e){for(var r=1;r0?r:e.DEFAULT_SAMPLERATE,sampleChannel:t>=0?t:e.DEFAULT_CHANNEL}:{sampleRate:0,sampleChannel:0,audioNone:!0})))}),"viiddddiiiii"),t._setCodecType(n,0,o,i),t.cwrap("initDecoder","number",["number"])(n);break;case p:var u=s.data,c=u.nalBuf,l=u.pts,b=u.flushDecoder,_=t._malloc(c.length);t.HEAP8.set(c,_);var S=parseInt(1e3*l+"");t._decodeCodecContext(n,_,c.length,S,b),t._free(_),_=null;break;case h:var O=s.data,T=O.buff;O.tsUrl,function(e,r,t,n){null!=M&&(e._free(M),M=null),M=e._malloc(r.length),e.HEAP8.set(r,M);try{var o=e.cwrap("demuxTsStream","number",["number","number","number"])(M,r.length,t);e._free(M),M=null,o>=0&&postMessage(w(g))}catch(e){k.send("worker",{name:"demuxTsStream",msg:e})}}(t,T,n);break;case v:!function(e,r){for(;;){var t=e.cwrap("getPacket","number",[])(),n=e.HEAPU32[t/4],o=e.HEAPU32[t/4+1],i=e.HEAPF64[t/8+1],a=e.HEAPF64[t/8+1+1],s=e.HEAPU32[t/4+1+1+2+2],u=e.HEAPU32[t/4+1+1+2+2+1],c=e.HEAPU8.subarray(u,u+o),l=null,d=[0,1].includes(n);if(d)try{l=P(e,r)}catch(e){}if(!d||o<=0)break;var f=a>0?a:i;f<0||0===t||(self.postMessage(w(v,{type:n,size:o,ptime:i,dtime:a,keyframe:s,data:Array.from(c),pts:f,layer:l})),c=null,l=null,t=null)}postMessage(w(E))}(t,a);break;case m:null!==o&&t.removeFunction(o),o=null,null!==i&&t.removeFunction(i),i=null,t.cwrap("destroy","number",["number"])(n),self.close()}}})).catch((function(e){self.postMessage(w(l,{data:e}))}))})); diff --git a/examples/vue-app/src/components/Player.vue b/examples/vue-app/src/components/Player.vue index 555ccaa..795ff5f 100644 --- a/examples/vue-app/src/components/Player.vue +++ b/examples/vue-app/src/components/Player.vue @@ -1,16 +1,17 @@ diff --git a/package.json b/package.json new file mode 100644 index 0000000..d192257 --- /dev/null +++ b/package.json @@ -0,0 +1,56 @@ +{ + "name": "@ezuikit/player-hls", + "version": "0.1.0", + "description": "hls播放器", + "main": "dist/index.js", + "umd": "dist/index.umd.js", + "types": "dist/types/index.d.ts", + "module": "dist/index.esm.js", + "scripts": { + "dev": "npm run clean && cross-env NODE_ENV=development rollup --config rollup.config.js --bundleConfigAsCjs --watch", + "build": "npm run clean && cross-env NODE_ENV=production rollup --config rollup.config.js --bundleConfigAsCjs", + "test": "jest", + "prebuild": "npm run clean", + "clean": "rimraf docs dist coverage", + "docs": "typedoc --tsconfig typedoc.config.js --exclude **/*.js" + }, + "files": [ + "dist", + "!dist/**/*.js.map" + ], + "keywords": [ + "hls", + "h265", + "live", + "player" + ], + "author": "Ezviz-OpenBiz", + "dependencies": { + "@ezuikit/utils-i18n": "^1.0.1", + "@ezuikit/utils-logger": "^1.0.1", + "@ezuikit/utils-tools": "^1.0.2", + "dayjs": "^1.11.10", + "eventemitter3": "^5.0.1", + "hls.js": "^1.5.7", + "lodash-es": "^4.17.21", + "screenfull": "^6.0.2", + "ua-parser-js": "1.0.37", + "@ezuikit/player-base": "0.1.0", + "@ezuikit/utils-collect": "^0.1.0" + }, + "devDependencies": {}, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "bugs": { + "url": "https://github.com/Ezviz-OpenBiz/EZUIKit-hls/issues" + }, + "homepage": "https://github.com/Ezviz-OpenBiz/EZUIKit-hls", + "repository": { + "type": "git", + "url": "git+https://github.com/Ezviz-OpenBiz/EZUIKit-hls.git", + "branch": "main", + "platform": "github" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..6a3038e --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,117 @@ +lockfileVersion: '6.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +dependencies: + '@ezuikit/player-base': + specifier: 0.1.0 + version: 0.1.0 + '@ezuikit/utils-collect': + specifier: ^0.1.0 + version: 0.1.0 + '@ezuikit/utils-i18n': + specifier: ^1.0.1 + version: 1.0.1 + '@ezuikit/utils-logger': + specifier: ^1.0.1 + version: 1.0.1 + '@ezuikit/utils-tools': + specifier: ^1.0.2 + version: 1.0.3 + dayjs: + specifier: ^1.11.10 + version: 1.11.12 + eventemitter3: + specifier: ^5.0.1 + version: 5.0.1 + hls.js: + specifier: ^1.5.7 + version: 1.5.13 + lodash-es: + specifier: ^4.17.21 + version: 4.17.21 + screenfull: + specifier: ^6.0.2 + version: 6.0.2 + ua-parser-js: + specifier: 1.0.37 + version: 1.0.37 + +packages: + + /@ezuikit/player-base@0.1.0: + resolution: {integrity: sha512-IcJqnZr9FmjBCnIrmqY7oHdyDuYxRWhDZB+K+gi+4oenFjFV4aLCCG7RFPxkidHzi3TTF2f1Bm5yObZzNDqkfw==} + dependencies: + '@ezuikit/utils-collect': 0.1.0 + '@ezuikit/utils-logger': 1.0.1 + '@ezuikit/utils-tools': 1.0.3 + eventemitter3: 5.0.1 + lodash-es: 4.17.21 + screenfull: 6.0.2 + ua-parser-js: 1.0.37 + dev: false + + /@ezuikit/utils-collect@0.1.0: + resolution: {integrity: sha512-85lWlB/VCaooPPkCK3nEB4F3UKgO+HbmoPEq4U1tH/ObVP7IJ7eURrFUmQT1CKsqjH5xz5g4DgZzHWgYrwGcCQ==} + dev: false + + /@ezuikit/utils-i18n@1.0.1: + resolution: {integrity: sha512-uUjN3ADHV2ZG4QznuA7FB89/ck8AGV4qS8hm/sqeSA6/ie4ryYw8MS4wIv71WgPBIgIVDfASuEapyLOwq7R2aQ==} + dependencies: + i18n-js: 4.4.3 + dev: false + + /@ezuikit/utils-logger@1.0.1: + resolution: {integrity: sha512-qak0MXh4vWZCji3aSCfHdWR3EbZCaqS0iMT8/QWuWPRr0vDmTRMP3kFOAw1MuMraR0ocjPBE2PaTEmUuwVqaAw==} + dev: false + + /@ezuikit/utils-tools@1.0.3: + resolution: {integrity: sha512-4vJOFAAmmIojfCf43LwXwQNffoyUad2c/HOZwNexHsMqcvC/yLeDmqm5Y5Kp4BoZT/LHfMpy9fJJ3W22+ikXaQ==} + dev: false + + /bignumber.js@9.1.2: + resolution: {integrity: sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug==} + dev: false + + /dayjs@1.11.12: + resolution: {integrity: sha512-Rt2g+nTbLlDWZTwwrIXjy9MeiZmSDI375FvZs72ngxx8PDC6YXOeR3q5LAuPzjZQxhiWdRKac7RKV+YyQYfYIg==} + dev: false + + /eventemitter3@5.0.1: + resolution: {integrity: sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==} + dev: false + + /hls.js@1.5.13: + resolution: {integrity: sha512-xRgKo84nsC7clEvSfIdgn/Tc0NOT+d7vdiL/wvkLO+0k0juc26NRBPPG1SfB8pd5bHXIjMW/F5VM8VYYkOYYdw==} + dev: false + + /i18n-js@4.4.3: + resolution: {integrity: sha512-QIIyvJ+wOKdigL4BlgwiFFrpoXeGdlC8EYgori64YSWm1mnhNYYjIfRu5wETFrmiNP2fyD6xIjVG8dlzaiQr/A==} + dependencies: + bignumber.js: 9.1.2 + lodash: 4.17.21 + make-plural: 7.4.0 + dev: false + + /lodash-es@4.17.21: + resolution: {integrity: sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==} + dev: false + + /lodash@4.17.21: + resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==} + dev: false + + /make-plural@7.4.0: + resolution: {integrity: sha512-4/gC9KVNTV6pvYg2gFeQYTW3mWaoJt7WZE5vrp1KnQDgW92JtYZnzmZT81oj/dUTqAIu0ufI2x3dkgu3bB1tYg==} + dev: false + + /screenfull@6.0.2: + resolution: {integrity: sha512-AQdy8s4WhNvUZ6P8F6PB21tSPIYKniic+Ogx0AacBMjKP1GUHN2E9URxQHtCusiwxudnCKkdy4GrHXPPJSkCCw==} + engines: {node: ^14.13.1 || >=16.0.0} + dev: false + + /ua-parser-js@1.0.37: + resolution: {integrity: sha512-bhTyI94tZofjo+Dn8SN6Zv8nBDvyXTymAdM3LDI/0IboIUwTu1rEhW7v2TfiVsoYWgkQ4kOVqnI8APUFbIQIFQ==} + dev: false diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 0000000..5f929f8 --- /dev/null +++ b/yarn.lock @@ -0,0 +1,92 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@ezuikit/player-base@0.1.0": + version "0.1.0" + resolved "https://registry.yarnpkg.com/@ezuikit/player-base/-/player-base-0.1.0.tgz#8e0a7c063e9b8e24dd70123294bad4df8eb2d61d" + integrity sha512-IcJqnZr9FmjBCnIrmqY7oHdyDuYxRWhDZB+K+gi+4oenFjFV4aLCCG7RFPxkidHzi3TTF2f1Bm5yObZzNDqkfw== + dependencies: + "@ezuikit/utils-collect" "^0.1.0" + "@ezuikit/utils-logger" "^1.0.1" + "@ezuikit/utils-tools" "^1.0.2" + eventemitter3 "^5.0.1" + lodash-es "^4.17.21" + screenfull "^6.0.2" + ua-parser-js "1.0.37" + +"@ezuikit/utils-collect@^0.1.0": + version "0.1.0" + resolved "https://registry.yarnpkg.com/@ezuikit/utils-collect/-/utils-collect-0.1.0.tgz#3954839a67ab8e8a0ecba4b4a9d7779fd79185cf" + integrity sha512-85lWlB/VCaooPPkCK3nEB4F3UKgO+HbmoPEq4U1tH/ObVP7IJ7eURrFUmQT1CKsqjH5xz5g4DgZzHWgYrwGcCQ== + +"@ezuikit/utils-i18n@^1.0.1": + version "1.0.1" + resolved "https://registry.yarnpkg.com/@ezuikit/utils-i18n/-/utils-i18n-1.0.1.tgz#938b192184482e91a6e8aadde0f602c268da3020" + integrity sha512-uUjN3ADHV2ZG4QznuA7FB89/ck8AGV4qS8hm/sqeSA6/ie4ryYw8MS4wIv71WgPBIgIVDfASuEapyLOwq7R2aQ== + dependencies: + i18n-js "^4.3.2" + +"@ezuikit/utils-logger@^1.0.1": + version "1.0.1" + resolved "https://registry.yarnpkg.com/@ezuikit/utils-logger/-/utils-logger-1.0.1.tgz#9f157c982acba73514fc7a46829768d5bf61f45e" + integrity sha512-qak0MXh4vWZCji3aSCfHdWR3EbZCaqS0iMT8/QWuWPRr0vDmTRMP3kFOAw1MuMraR0ocjPBE2PaTEmUuwVqaAw== + +"@ezuikit/utils-tools@^1.0.2": + version "1.0.3" + resolved "https://registry.yarnpkg.com/@ezuikit/utils-tools/-/utils-tools-1.0.3.tgz#d014c32905aae1dcfd92d5258453765fb7ffaa41" + integrity sha512-4vJOFAAmmIojfCf43LwXwQNffoyUad2c/HOZwNexHsMqcvC/yLeDmqm5Y5Kp4BoZT/LHfMpy9fJJ3W22+ikXaQ== + +bignumber.js@*: + version "9.1.2" + resolved "https://registry.yarnpkg.com/bignumber.js/-/bignumber.js-9.1.2.tgz#b7c4242259c008903b13707983b5f4bbd31eda0c" + integrity sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug== + +dayjs@^1.11.10: + version "1.11.12" + resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.11.12.tgz#5245226cc7f40a15bf52e0b99fd2a04669ccac1d" + integrity sha512-Rt2g+nTbLlDWZTwwrIXjy9MeiZmSDI375FvZs72ngxx8PDC6YXOeR3q5LAuPzjZQxhiWdRKac7RKV+YyQYfYIg== + +eventemitter3@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-5.0.1.tgz#53f5ffd0a492ac800721bb42c66b841de96423c4" + integrity sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA== + +hls.js@^1.5.7: + version "1.5.13" + resolved "https://registry.yarnpkg.com/hls.js/-/hls.js-1.5.13.tgz#27bf1c9b91c433e25e7a84635fe7491bb5988d93" + integrity sha512-xRgKo84nsC7clEvSfIdgn/Tc0NOT+d7vdiL/wvkLO+0k0juc26NRBPPG1SfB8pd5bHXIjMW/F5VM8VYYkOYYdw== + +i18n-js@^4.3.2: + version "4.4.3" + resolved "https://registry.yarnpkg.com/i18n-js/-/i18n-js-4.4.3.tgz#09744ddd377261f614502cc5622ce6981026ea4a" + integrity sha512-QIIyvJ+wOKdigL4BlgwiFFrpoXeGdlC8EYgori64YSWm1mnhNYYjIfRu5wETFrmiNP2fyD6xIjVG8dlzaiQr/A== + dependencies: + bignumber.js "*" + lodash "*" + make-plural "*" + +lodash-es@^4.17.21: + version "4.17.21" + resolved "https://registry.yarnpkg.com/lodash-es/-/lodash-es-4.17.21.tgz#43e626c46e6591b7750beb2b50117390c609e3ee" + integrity sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw== + +lodash@*: + version "4.17.21" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" + integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== + +make-plural@*: + version "7.4.0" + resolved "https://registry.yarnpkg.com/make-plural/-/make-plural-7.4.0.tgz#fa6990dd550dea4de6b20163f74e5ed83d8a8d6d" + integrity sha512-4/gC9KVNTV6pvYg2gFeQYTW3mWaoJt7WZE5vrp1KnQDgW92JtYZnzmZT81oj/dUTqAIu0ufI2x3dkgu3bB1tYg== + +screenfull@^6.0.2: + version "6.0.2" + resolved "https://registry.yarnpkg.com/screenfull/-/screenfull-6.0.2.tgz#3dbe4b8c4f8f49fb8e33caa8f69d0bca730ab238" + integrity sha512-AQdy8s4WhNvUZ6P8F6PB21tSPIYKniic+Ogx0AacBMjKP1GUHN2E9URxQHtCusiwxudnCKkdy4GrHXPPJSkCCw== + +ua-parser-js@1.0.37: + version "1.0.37" + resolved "https://registry.yarnpkg.com/ua-parser-js/-/ua-parser-js-1.0.37.tgz#b5dc7b163a5c1f0c510b08446aed4da92c46373f" + integrity sha512-bhTyI94tZofjo+Dn8SN6Zv8nBDvyXTymAdM3LDI/0IboIUwTu1rEhW7v2TfiVsoYWgkQ4kOVqnI8APUFbIQIFQ==