pr-player 0.5.1 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/dist/index.js +18 -11
- package/dist/index.umd.cjs +2 -2
- package/dist/render/Render.d.ts +2 -1
- package/dist/render/RenderWorker.d.ts +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -76,6 +76,7 @@ player.stop()
|
|
|
76
76
|
|
|
77
77
|
```js
|
|
78
78
|
// sx、sy、sw、sh 为原视频坐标系下的裁剪区域,通常配合 on.demuxer.info 中的 width、height 使用
|
|
79
|
+
// ⚠️ sx、sy、sw、sh 建议传入偶数,内部会自动将奇数修正为偶数
|
|
79
80
|
const { width, height } = info
|
|
80
81
|
player.cut.create('cut-any-key', { sx: width * 0.25, sy: height * 0.4, sw: width * 0.5, sh: height * 0.5 })
|
|
81
82
|
const stream = player.cut.getStream('cut-any-key')
|
|
@@ -84,6 +85,7 @@ const stream = player.cut.getStream('cut-any-key')
|
|
|
84
85
|
### 修改剪切区域
|
|
85
86
|
|
|
86
87
|
```js
|
|
88
|
+
// ⚠️ sx、sy、sw、sh 建议传入偶数,内部会自动将奇数修正为偶数
|
|
87
89
|
player.cut.setCut('cut-any-key', { sx: 100, sy: 100, sw: 640, sh: 360 })
|
|
88
90
|
```
|
|
89
91
|
|
|
@@ -111,7 +113,7 @@ player.on.demuxer.info = (info) => {
|
|
|
111
113
|
}
|
|
112
114
|
|
|
113
115
|
player.on.decoder.sei = (sei) => {
|
|
114
|
-
// 根据业务协议解析 sei
|
|
116
|
+
// 根据业务协议解析 sei,得到裁剪区域(建议 sx、sy、sw、sh 传入偶数)
|
|
115
117
|
const { sx, sy, sw, sh } = parseSeiRect(sei, videoInfo)
|
|
116
118
|
|
|
117
119
|
if (!player.cut.getStream('sei-cut')) {
|
|
@@ -152,9 +154,9 @@ new PrPlayer({ frameTrack?: boolean })
|
|
|
152
154
|
|
|
153
155
|
| 方法 | 说明 |
|
|
154
156
|
| --- | --- |
|
|
155
|
-
| `cut.create(key, { sx, sy, sw, sh })` | 创建剪切路,返回 cut 的 MediaStream |
|
|
157
|
+
| `cut.create(key, { sx, sy, sw, sh })` | 创建剪切路,返回 cut 的 MediaStream(⚠️ sx、sy、sw、sh 建议传入偶数) |
|
|
156
158
|
| `cut.getStream(key)` | 获取已创建的 cut MediaStream |
|
|
157
|
-
| `cut.setCut(key, cutOption)` |
|
|
159
|
+
| `cut.setCut(key, cutOption)` | 运行时修改裁剪区域(⚠️ sx、sy、sw、sh 建议传入偶数) |
|
|
158
160
|
| `cut.setPause(key, pause)` | 暂停/恢复指定 cut 路 |
|
|
159
161
|
| `cut.remove(key)` | 移除指定 cut 路 |
|
|
160
162
|
|
package/dist/index.js
CHANGED
|
@@ -116,7 +116,7 @@ var c = "pr-player-decoder", l = class {
|
|
|
116
116
|
destroy = () => {
|
|
117
117
|
this.worker.postMessage({ action: "destroy" }), this.worker.terminate();
|
|
118
118
|
};
|
|
119
|
-
}, u = "(function(){let e=new class{renderMap=new Map;constructor(){}push=async e=>{let t=e.frame,n=t.timestamp;try{let e=[...this.renderMap.entries()].filter(([,e])=>e&&!e.pause);if(e.length===1&&e[0][0]===\"default\"&&e[0][1].writer){e[0][1].writer.write(t).catch(()=>{}),t.close();return}for(let[r,i]of e){let{writer:e,offscreen:a,option:o}=i;if(e){let i;if(r===\"default\"||!o)i=new VideoFrame(t,{timestamp:n});else{let{sx:e=0,sy:r=0,sw:a=t.displayWidth,sh:s=t.displayHeight}=o;i=new VideoFrame(t,{visibleRect:{x:e,y:r,width:a,height:s},displayWidth:a,displayHeight:s,timestamp:n})}e.write(i).catch(()=>{}),i.close()}else if(a)if(r===\"default\"||!o)a.width=t.displayWidth,a.height=t.displayHeight,a.getContext(`2d`)?.drawImage(t,0,0);else{let{sx:e=0,sy:n=0,sw:r=t.displayWidth,sh:i=t.displayHeight}=o;a.width=r,a.height=i,a.getContext(`2d`)?.drawImage(t,e,n,r,i,0,0,r,i)}}}catch{}t.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,
|
|
119
|
+
}, u = "(function(){let e=new class{renderMap=new Map;constructor(){}push=async e=>{let t=e.frame,n=t.timestamp;try{let e=[...this.renderMap.entries()].filter(([,e])=>e&&!e.pause);if(e.length===1&&e[0][0]===\"default\"&&e[0][1].writer){e[0][1].writer.write(t).catch(()=>{}),t.close();return}for(let[r,i]of e){let{writer:e,offscreen:a,option:o}=i;if(e){let i;if(r===\"default\"||!o)i=new VideoFrame(t,{timestamp:n});else{let{sx:e=0,sy:r=0,sw:a=t.displayWidth,sh:s=t.displayHeight}=o;i=new VideoFrame(t,{visibleRect:{x:e,y:r,width:a,height:s},displayWidth:a,displayHeight:s,timestamp:n})}e.write(i).catch(()=>{}),i.close()}else if(a)if(r===\"default\"||!o)a.width=t.displayWidth,a.height=t.displayHeight,a.getContext(`2d`)?.drawImage(t,0,0);else{let{sx:e=0,sy:n=0,sw:r=t.displayWidth,sh:i=t.displayHeight}=o;a.width=r,a.height=i,a.getContext(`2d`)?.drawImage(t,e,n,r,i,0,0,r,i)}}}catch{}t.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,cutOption:i}={key:`default`,...e},a=this._getSafeSize(i);if(n){let e=n.getWriter();this.renderMap.set(t,{writer:e,option:a,pause:!1})}else this.renderMap.set(t,{offscreen:r,option:a,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{let{key:t,cutOption:n}={key:`default`,...e},r=this.renderMap.get(t);if(r){let e=this._getSafeSize(n);this.renderMap.set(t,{...r,option:e})}};setPause=e=>{let{key:t,pause:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,pause:n})};_getSafeSize=e=>{let t={...e};return t.sx%2!=0&&(t.sx+=1),t.sy%2!=0&&(t.sy+=1),t.sw%2!=0&&--t.sw,t.sh%2!=0&&--t.sh,t};destroy=()=>{this.renderMap=new Map}};onmessage=t=>{let{action:n,data:r}=t.data,i=e[n];i&&i(r)}})();", d = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", u], { type: "text/javascript;charset=utf-8" });
|
|
120
120
|
function f(e) {
|
|
121
121
|
let t;
|
|
122
122
|
try {
|
|
@@ -650,14 +650,14 @@ var p = "pr-player-render", m = class {
|
|
|
650
650
|
return this.renderWorker?.addCut({
|
|
651
651
|
key: e,
|
|
652
652
|
writable: n.writable,
|
|
653
|
-
|
|
653
|
+
cutOption: t
|
|
654
654
|
}), this.cutRenders.set(e, { stream: r }), r;
|
|
655
655
|
}
|
|
656
656
|
let n = document.createElement("canvas"), r = n.captureStream(), i = n.transferControlToOffscreen();
|
|
657
657
|
return this.renderWorker?.addCut({
|
|
658
658
|
key: e,
|
|
659
659
|
offscreen: i,
|
|
660
|
-
|
|
660
|
+
cutOption: t
|
|
661
661
|
}), this.cutRenders.set(e, { stream: r }), r;
|
|
662
662
|
},
|
|
663
663
|
setCut: (e, t) => {
|
|
@@ -2459,20 +2459,20 @@ var p = "pr-player-render", m = class {
|
|
|
2459
2459
|
t.close();
|
|
2460
2460
|
};
|
|
2461
2461
|
addCut = (e) => {
|
|
2462
|
-
let { key: t, writable: n, offscreen: r,
|
|
2462
|
+
let { key: t, writable: n, offscreen: r, cutOption: i } = {
|
|
2463
2463
|
key: "default",
|
|
2464
2464
|
...e
|
|
2465
|
-
};
|
|
2465
|
+
}, a = this._getSafeSize(i);
|
|
2466
2466
|
if (n) {
|
|
2467
2467
|
let e = n.getWriter();
|
|
2468
2468
|
this.renderMap.set(t, {
|
|
2469
2469
|
writer: e,
|
|
2470
|
-
option:
|
|
2470
|
+
option: a,
|
|
2471
2471
|
pause: !1
|
|
2472
2472
|
});
|
|
2473
2473
|
} else this.renderMap.set(t, {
|
|
2474
2474
|
offscreen: r,
|
|
2475
|
-
option:
|
|
2475
|
+
option: a,
|
|
2476
2476
|
pause: !1
|
|
2477
2477
|
});
|
|
2478
2478
|
};
|
|
@@ -2484,10 +2484,13 @@ var p = "pr-player-render", m = class {
|
|
|
2484
2484
|
key: "default",
|
|
2485
2485
|
...e
|
|
2486
2486
|
}, r = this.renderMap.get(t);
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2487
|
+
if (r) {
|
|
2488
|
+
let e = this._getSafeSize(n);
|
|
2489
|
+
this.renderMap.set(t, {
|
|
2490
|
+
...r,
|
|
2491
|
+
option: e
|
|
2492
|
+
});
|
|
2493
|
+
}
|
|
2491
2494
|
};
|
|
2492
2495
|
setPause = (e) => {
|
|
2493
2496
|
let { key: t, pause: n } = {
|
|
@@ -2499,6 +2502,10 @@ var p = "pr-player-render", m = class {
|
|
|
2499
2502
|
pause: n
|
|
2500
2503
|
});
|
|
2501
2504
|
};
|
|
2505
|
+
_getSafeSize = (e) => {
|
|
2506
|
+
let t = { ...e };
|
|
2507
|
+
return t.sx % 2 != 0 && (t.sx += 1), t.sy % 2 != 0 && (t.sy += 1), t.sw % 2 != 0 && --t.sw, t.sh % 2 != 0 && --t.sh, t;
|
|
2508
|
+
};
|
|
2502
2509
|
destroy = () => {
|
|
2503
2510
|
this.renderMap = /* @__PURE__ */ new Map();
|
|
2504
2511
|
};
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`pr-player`]={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t="(function(){var e=class{pendingPayloads=[];payload=new Uint8Array;chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);let t=this.pendingPayloads.shift();if(!t)return!1;let n=new Uint8Array(this.payload.byteLength+t.byteLength);return n.set(this.payload,0),n.set(t,this.payload.byteLength),this.payload=n,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};discardPayload=()=>{this.payload=new Uint8Array};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array,this.chunks=[]}};let t=(e,t)=>{let n=new Uint8Array(e),r=new Uint8Array(t),i=new Uint8Array(11+n.length+r.length),a=0;return i[a++]=1,i[a++]=n[1],i[a++]=n[2],i[a++]=n[3],i[a++]=255,i[a++]=225,i[a++]=n.length>>8&255,i[a++]=n.length&255,i.set(n,a),a+=n.length,i[a++]=1,i[a++]=r.length>>8&255,i[a++]=r.length&255,i.set(r,a),i},n=e=>{let t=0,n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(t);if(t+=1,r!==1)throw Error(`Invalid AVC version`);let i=n.getUint8(t)&255;t+=1;let a=n.getUint8(t)&255;t+=1;let o=n.getUint8(t)&255;t+=1;let s=`avc1.${Array.from([i,a,o],e=>e.toString(16).padStart(2,`0`)).join(``)}`;t+=1,t+=1;let c=n.getUint16(t,!1);t+=2;let l=new Uint8Array(e.buffer,e.byteOffset+t,c);t+=c,t+=1;let u=n.getUint16(t,!1);return t+=2,{version:r,codec:s,profile:i,compatibility:a,level:o,sps:l,pps:new Uint8Array(e.buffer,e.byteOffset+t,u)}},r=e=>{let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t},i=e=>{let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n},a=(e,t)=>e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),o=(e,t)=>{let n=a(e,t);return n&8388608&&(n|=-16777216),n},s=(e,t)=>t<<24|e,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];var l=class{audioConfig;videoConfig;header;textDecoder=new TextDecoder(`utf-8`);on={};constructor(){}parse=async e=>{let t=0;for(this.header||(this.parseHeader(e,t),t+=9);this.isSurplusTag(e,t)!==!1;){let{tagType:n,dataSize:r,dts:i}=this.parseTagHeader(e,t+4);if(n){let a=this.parseTagBody(n,e,t+4+11,r);if(!a){t=t+4+11+r,await new Promise(e=>setTimeout(()=>e(!0),8));continue}switch(n){case`script`:this.on.info&&this.on.info(a);break;case`audio`:{let{accPacketType:e}=a;if(e===0){let{codec:e,sampleRate:t,channelConfiguration:n,data:r}=a;this.audioConfig={kind:`audio`,codec:e,sampleRate:t,numberOfChannels:n,...r?{description:r}:{}},this.on.config&&this.on.config(this.audioConfig)}else{let{cts:e,data:t}=a,n=e===void 0?void 0:e+i;this.on.chunk&&this.on.chunk({kind:`audio`,type:`key`,dts:i,pts:n,cts:e,data:t})}}break;case`video`:{let{avcPacketType:e}=a;if(e===0){let{codec:e,sps:t,pps:n,data:r}=a;this.videoConfig={kind:`video`,codec:e,description:r,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}else{let{frameType:e,cts:t,data:n,nalus:r}=a,o=e===1?`key`:`delta`,s=t===void 0?void 0:t+i;this.on.chunk&&this.on.chunk({kind:`video`,type:o,dts:i,pts:s,cts:t,data:n,nalus:r})}}break}t=t+4+11+r}await new Promise(e=>setTimeout(()=>e(!0),8))}return t};parseHeader=(e,t)=>{let n,r,i,a;n=e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),r=e.getUint8(t+3);{let n=e.getUint8(t+4);i={audio:!!(n&4),video:!!(n&1)}}a=e.getUint32(t+5),this.header={signature:n,version:r,flags:i,dataOffset:a}};isSurplusTag=(e,t)=>{let n=!0,r=e.byteLength;if(t+4>r)n=!1;else if(t+4+11>r)n=!1;else{let i=a(e,t+4+1);t+4+11+i>r&&(n=!1)}return n};parseTagHeader=(e,t)=>{let n,r,i,o,c;{let r=e.getUint8(t),i;switch(r){case 18:i=`script`;break;case 8:i=`audio`;break;case 9:i=`video`;break}n=i}r=a(e,t+1),i=a(e,t+4),o=e.getUint8(t+7),c=a(e,t+8);let l=s(i,o);return{tagType:n,dataSize:r,timestamp:i,timestampExtended:o,dts:l,streamID:c}};parseTagBody=(e,t,n,r)=>{let i;switch(e){case`script`:i=this.parseMetaData(t,n);break;case`audio`:i=this.parseAudio(t,n,r);break;case`video`:i=this.parseVideo(t,n,r);break}return i};parseMetaData=(e,t)=>{let n=t;if(e.getUint8(n)!==2)return null;n+=1;let r=e.getUint16(n,!1);n+=2;{let t=new Int8Array(e.buffer.slice(n,n+r)),i=this.textDecoder?.decode(t)||``;if(n+=r,i!==`onMetaData`)return{name:i}}let i=this.getAmfType(e,n);return n+=1,this.getAMFValue(e,n,i).value};parseAudio=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i>>2&3,s=i>>1&1,l=i&1;r+=1;let u=e.getUint8(r);r+=1;let d=n-(r-t);if(d<=0)return{soundFormat:a,soundRate:o,soundSize:s,soundType:l,accPacketType:u,data:new Uint8Array};let f=new Uint8Array(e.buffer.slice(r,r+d));if(a===10&&u===0){let t=e.getUint8(r),n=e.getUint8(r+1),i=t>>3&31,d=(t&7)<<1|n>>7;return{soundFormat:a,soundRate:o,soundSize:s,soundType:l,accPacketType:u,data:f,samplingFrequencyIndex:d,channelConfiguration:n>>3&15,codec:`mp4a.40.${i}`,sampleRate:c[d]}}return{soundFormat:a,soundRate:o,soundSize:s,soundType:l,accPacketType:u,data:f}};parseVideo=(e,t,r)=>{let i=t,a=e.getUint8(i),s=a>>4&15,c=a&15;i+=1;let l=e.getUint8(i);i+=1;let u=o(e,i);i+=3;let d=r-5;if(d<0)return null;let f=new Uint8Array(e.buffer.slice(i,i+d));switch(c){case 7:if(l===0)return{frameType:s,codecID:c,avcPacketType:l,cts:u,data:f,...n(f)};if(l===1){let t=[],n=i+d;for(;!(i+4>n);){let r=e.getUint32(i,!1);if(r<=0||i+4+r>n)break;let a=new Uint8Array(e.buffer.slice(i,i+4+r));i+=4+r,t.push(a)}return{frameType:s,codecID:c,avcPacketType:l,cts:u,data:f,nalus:t}}break;default:return null}return{frameType:s,codecID:c,avcPacketType:l,cts:u,data:f}};getAmfType=(e,t)=>e.getUint8(t);getAMFName=(e,t,n)=>{let r=new Uint8Array(e.buffer.slice(t,t+n));return this.textDecoder?.decode(r)||``};getAMFValue=(e,t,n)=>{let r=t,i,a=0;switch(n){case 0:i=e.getFloat64(r,!1),a=8;break;case 1:i=!!e.getUint8(r),a=1;break;case 2:{i=``;let t=e.getUint16(r,!1);r+=2;let n=new Int8Array(e.buffer,r,t).filter(e=>e!==0);i=(this.textDecoder?.decode(n)||``).trim(),a=2+t}break;case 3:for(i={};r<e.byteLength;){let t=e.getUint16(r,!1);if(t===0)break;r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);if(o===6)break;r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}break;case 8:{i={};let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=e.getUint16(r,!1);r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}}break;case 10:{i=[];let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=this.getAmfType(e,r);r+=1;let n=this.getAMFValue(e,r,t);r+=n.length,i.push(n.value),a=1+n.length}}break}return{amfType:n,length:a,value:i}}};let u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],d=e=>{let t=`unknown`;switch(e){case 1:case 2:case 27:case 36:t=`video`;break;case 3:case 4:case 15:t=`audio`;break;case 6:t=`subtitle`;break;case 134:t=`ad`;break}return t};var f=class{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let t=0;for(;!(t+188>e.byteLength);){if(e.getInt8(t)!=71){t++;continue}await this.parsePacket(e,t),t+=188}return t};parsePacket=async(e,t)=>{if(t+188>e.byteLength||e.getUint8(t)!==71)throw Error(`Invalid TS packet`);let n=t,r=this.parseHeader(e,n);n+=4;let{transport_error_indicator:i,pid:a,payload_unit_start_indicator:o,adaptation_field_control:s}=r;if(i===1||a===void 0)return;let c=184;if(s===2||s===3){let t=e.getUint8(n);n+=1,t>0&&(this.parseAdaptationField(e,n),n+=t),c-=1+t}if(s===1||s===3){if(c<=0)return;let t=new Uint8Array(e.buffer.slice(n,n+c));if(a===0)return this.parsePAT(e,n);{let{programs:t=[]}=this.pat||{};if(t.find(e=>e.pmt_pid===a))return this.parsePMT(e,n)}let{streams:r=[]}=this.pmt||{},i=r.find(e=>e.elementary_pid===a);if(i){if(o===1){let e=this.payloadMap.get(a);if(e){switch(i.kind){case`audio`:{let t=await this.parseAudio(e);this.on.chunk&&this.on.chunk(t)}break;case`video`:{let t=await this.parseVideo(e);this.on.chunk&&this.on.chunk(t),await new Promise(e=>setTimeout(()=>e(!0),0))}break}this.payloadMap.delete(a)}}{this.payloadMap.has(a)||this.payloadMap.set(a,new Uint8Array);let e=this.payloadMap.get(a),n=new Uint8Array(e.byteLength+t.byteLength);n.set(e,0),n.set(t,e.byteLength),this.payloadMap.set(a,n)}}}};parseHeader=(e,t)=>{let n=t,r=e.getUint8(n),i=e.getUint8(n+1),a=e.getUint8(n+2),o=e.getUint8(n+3),s=(i&128)>>7;return s===1?{sync_byte:r,transport_error_indicator:s}:{sync_byte:r,transport_error_indicator:s,payload_unit_start_indicator:(i&64)>>6,transport_priority:(i&32)>>5,pid:(i&31)<<8|a,transport_scrambling_control:(o&192)>>6,adaptation_field_control:o>>4&3,continuity_counter:o&15}};parsePAT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==0)throw Error(`Invalid PAT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u}}let i=[];{let t=r.section_length-5-4,a=n+t;for(;n<a;){let t=e.getUint16(n),r=e.getUint16(n+2)&8191;n+=4,t!==0&&r>=32&&r<=8190&&i.push({program_number:t,pmt_pid:r})}}let a=e.getUint32(n);this.pat={header:r,programs:i,crc32:a}};parsePMT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==2)throw Error(`Invalid PMT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1;let d=e.getUint16(n)&8191;n+=2;let f=e.getUint16(n)&4095;n+=2,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u,pcr_pid:d,program_info_length:f}}n+=r.program_info_length;let i=[];{let t=r.section_length-9-4,a=n+t;for(;n<a;){let t=e.getUint8(n),r=d(t),a=e.getUint16(n+1)&8191,o=e.getUint16(n+3)&4095;if(n+=5+o,a<32||a>8190){console.warn(`Invalid elementary_pid: 0x${a.toString(16)}`);continue}i.push({kind:r,stream_type:t,elementary_pid:a,es_info_length:o})}}let a=e.getUint32(n);this.pmt={header:r,streams:i,crc32:a}};parseAdaptationField=(e,t)=>{let n=t,r,i,a,o,s=e.getUint8(n),c=!!(s&128),l=!!(s&64),u=!!(s&32),d=!!(s&16),f=!!(s&8),p=!!(s&4),m=!!(s&2),h=!!(s&1);n+=1;let g=(e,t)=>{let n=BigInt(0);n|=BigInt(e.getUint16(t))<<25n,n|=BigInt(e.getUint16(t+1))<<17n,n|=BigInt(e.getUint16(t+2))<<9n,n|=BigInt(e.getUint16(t+3))<<1n,n|=BigInt(e.getUint16(t+4)>>7);let r=(e.getUint16(t+4)&1)<<8|e.getUint16(t+5);return n=n*300n+BigInt(r),n};if(d&&(r=g(e,n),n+=6),f&&(i=g(e,n),n+=6),p&&(a=e.getInt8(n),n+=1),m){let t=e.getUint8(n);n+=1,o=new Uint8Array(e.buffer,n,t),n+=t}return{discontinuity_indicator:c,random_access_indicator:l,elementary_stream_priority_indicator:u,pcr_flag:d,opcr_flag:f,splicing_point_flag:p,transport_private_data_flag:m,adaptation_field_extension_flag:h,pcr:r,opcr:i,splice_countdown:a,transport_private_data:o}};parseAudio=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts audio payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{let e=this.parseAdts(i);!this.audioConfig&&e&&(this.audioConfig={kind:`audio`,codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.channelConfiguration},this.on.config&&this.on.config(this.audioConfig));let{dts:t=0,pts:n=0}=r;return{kind:`audio`,type:`key`,dts:t,pts:n,cts:n-t,data:e?i.slice(e.headerLength):i}}};parseAdts=e=>{if(e.length<7||e[0]!==255||(e[1]&240)!=240)return null;let t=e[1]&1?7:9;if(e.length<t)return null;let n=(e[2]>>6&3)+1,r=e[2]>>2&15,i=(e[2]&1)<<2|e[3]>>6,a=u[r]??44100;return{headerLength:t,codec:`mp4a.40.${n}`,sampleRate:a,channelConfiguration:i}};parseVideo=async e=>{let r=new DataView(e.buffer),a=0,o,s;{let e=r.getUint8(a)===0&&r.getUint8(a+1)===0&&r.getUint8(a+2)===1;if(a+=3,!e)throw Error(`invalid ts video payload.`);let t=r.getUint8(a);a+=1;let n=r.getUint8(a)<<8|r.getUint8(a+1);a+=2;let i,s,c,l,u;{let e=r.getUint8(a);a+=1,i=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=r.getUint8(a);a+=1;let t=e>>6,n=r.getUint8(a);a+=1,(t&2)==2&&(d=this.parsePtsDts(r,a)),f=(t&1)==1?this.parsePtsDts(r,a+5):d,a+=n}o={stream_id:t,pes_packet_length:n,scrambling_control:i,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}s=e.slice(a);{let e=this.getNalus(s);if(!this.videoConfig){let r,i;if(r=e.find(e=>e.type===7)?.nalu.slice(4),i=e.find(e=>e.type===8)?.nalu.slice(4),r&&i){let e=t(r,i),{codec:a}=n(e);this.videoConfig={kind:`video`,codec:a,description:e,sps:r,pps:i},this.on.config&&this.on.config(this.videoConfig)}}let r=[],a=`delta`;for(let t of e){let{type:e,nalu:n}=t;switch(e){case 6:case 9:r.push(n);break;case 1:a=`delta`,r.push(n);break;case 5:a=`key`,r.push(n);break}}let c=i(r),{dts:l=0,pts:u=0}=o,d=u-l;return{kind:`video`,type:a,dts:l,pts:u,cts:d,data:c,nalus:r}}};parsePtsDts(e,t){let n=e.getUint8(t),r=e.getUint8(t+1),i=e.getUint8(t+2),a=e.getUint8(t+3),o=e.getUint8(t+4),s=(BigInt(n)&14n)<<29n|(BigInt(r)&255n)<<22n|(BigInt(i)&254n)<<14n|(BigInt(a)&255n)<<7n|(BigInt(o)&254n)>>1n;return Number(s)/90}getNalus=e=>{let t=[],n=0;for(;n<e.byteLength-2;){let i=this.findAnnexBStart(e,n);if(!i)break;let a=e[i.naluOffset]&31,o=this.findAnnexBStart(e,i.nextSearchOffset),s=(o?o.startOffset:e.byteLength)-i.naluOffset;if(s>0){let n=e.slice(i.naluOffset,i.naluOffset+s);t.push({type:a,nalu:r(n)})}n=o?o.startOffset:e.byteLength}return t};findAnnexBStart=(e,t)=>{for(let n=t;n<e.length-2;n++)if(!(e[n]!==0||e[n+1]!==0)){if(e[n+2]===1)return{startOffset:n,naluOffset:n+3,nextSearchOffset:n+3};if(n+3<e.length&&e[n+2]===0&&e[n+3]===1)return{startOffset:n,naluOffset:n+4,nextSearchOffset:n+4}}return null}};let p=(e,t)=>String.fromCharCode(e.getUint8(t),e.getUint8(t+1),e.getUint8(t+2),e.getUint8(t+3)),m=(e,t,n)=>{if(t+8>n)return null;let r=e.getUint32(t,!1),i=p(e,t+4),a=8;if(r===1){if(t+16>n)return null;r=Number(e.getBigUint64(t+8,!1)),a=16}else r===0&&(r=n-t);return r<a||t+r>n?null:{offset:t,size:r,type:i,headerSize:a,contentStart:t+a}},h=(e,t,n,r)=>{let i=t;for(;i<n;){let t=m(e,i,n);if(!t)break;r(t),i+=t.size}},g=(e,t,n,r)=>{let i=null;return h(e,t,n,t=>{if(t.type===r)i=t;else if(t.type!==`mdat`){let n=g(e,t.contentStart,t.offset+t.size,r);n&&(i=n)}}),i},_=(e,t,n,r)=>{for(let i=t;i+8<=n;i++){if(p(e,i+4)!==r)continue;let t=m(e,i,n);if(t?.type===r)return t}return null},v=(e,t,n,r,i=86)=>_(e,t+i,n,r)||_(e,t+8,n,r),y=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],b=(e,t)=>{let n=0,r=t;for(;r<e.length;){if(n=n<<7|e[r]&127,!(e[r]&128))return{len:n,next:r+1};r++}return{len:0,next:t}};var x=class{audioConfig;videoConfig;tracks=new Map;mdatBox=null;progressiveParsed=!1;on={};getDiscardOffset=(e,t)=>this.progressiveParsed||g(t,0,e,`moof`)||this.tracks.size>0&&!g(t,0,e,`mdat`)?e:0;constructor(){}parse=async e=>{let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=t.byteLength,r=0;for(;r<n;){let i=m(e,r,n);if(!i)return 0;switch(i.type){case`moov`:this.parseMoov(e,i),this.tryRunProgressive(e,t);break;case`moof`:this.parseMoof(e,i,t);break;case`mdat`:this.mdatBox=i,this.tryRunProgressive(e,t);break;case`sidx`:case`styp`:case`free`:case`skip`:case`ftyp`:break;default:break}r+=i.size,(i.type===`moov`||i.type===`moof`||i.type===`mdat`)&&await new Promise(e=>setTimeout(()=>e(!0),8))}return this.progressiveParsed?n:0};tryRunProgressive=(e,t)=>{if(this.progressiveParsed||this.tracks.size===0)return;let n=this.mdatBox??g(e,0,t.byteLength,`mdat`),r=g(e,0,t.byteLength,`moov`);!n||!r||this.isProgressiveReady(n,r,t.byteLength)&&(this.parseProgressive(e,n,t),this.progressiveParsed=!0)};isProgressiveReady=(e,t,n)=>e.offset+e.size<=n&&t.offset+t.size<=n;parseMoov=(e,t)=>{h(e,t.contentStart,t.offset+t.size,t=>{t.type===`trak`&&this.parseTrak(e,t)});let n=g(e,t.contentStart,t.offset+t.size,`mvex`);n&&h(e,n.contentStart,n.offset+n.size,t=>{if(t.type!==`trex`)return;let n=e.getUint32(t.contentStart+4,!1),r=this.tracks.get(n);r&&(r.defaultSampleDuration=e.getUint32(t.contentStart+12,!1),r.defaultSampleSize=e.getUint32(t.contentStart+16,!1))});let r=g(e,t.contentStart,t.offset+t.size,`mvhd`);if(r){let t=e.getUint8(r.contentStart),n=e.getUint32(r.contentStart+(t===1?20:12),!1),i=t===1?Number(e.getBigUint64(r.contentStart+24,!1)):e.getUint32(r.contentStart+16,!1);this.on.info?.({width:[...this.tracks.values()].find(e=>e.kind===`video`)?.width,height:[...this.tracks.values()].find(e=>e.kind===`video`)?.height,duration:n?i/n:void 0})}};readTkhdSize=(e,t)=>{let n=e.getUint8(t.contentStart),r=n===1?72:64,i=n===1?76:68;return{width:e.getUint32(t.contentStart+r,!1)>>16,height:e.getUint32(t.contentStart+i,!1)>>16}};readSampleEntrySize=(e,t)=>({width:e.getUint16(t+32,!1),height:e.getUint16(t+34,!1)});parseTrak=(e,t)=>{let r=g(e,t.contentStart,t.offset+t.size,`tkhd`),i=g(e,t.contentStart,t.offset+t.size,`mdia`);if(!r||!i)return;let a=e.getUint8(r.contentStart),o=e.getUint32(r.contentStart+(a===1?20:12),!1),{width:s,height:c}=this.readTkhdSize(e,r),l=g(e,i.contentStart,i.offset+i.size,`hdlr`),u=g(e,i.contentStart,i.offset+i.size,`mdhd`);if(!l||!u)return;let d=p(e,l.contentStart+8),f=d===`vide`?`video`:d===`soun`?`audio`:void 0;if(!f)return;let m=e.getUint8(u.contentStart),h=e.getUint32(u.contentStart+(m===1?20:12),!1);this.tracks.set(o,{kind:f,trackId:o,timescale:h,width:s,height:c});let _=g(e,i.contentStart,i.offset+i.size,`minf`),y=_&&g(e,_.contentStart,_.offset+_.size,`stbl`),b=y&&g(e,y.contentStart,y.offset+y.size,`stsd`);if(!b)return;let x=b.contentStart+8,S=x+e.getUint32(x,!1),C=p(e,x+4);if(f===`video`&&(C===`avc1`||C===`avc3`)){let t=this.readSampleEntrySize(e,x);t.width&&t.height&&(s=t.width,c=t.height);let r=v(e,x,S,`avcC`,86);if(!r)return;let i=new Uint8Array(e.buffer,r.contentStart,r.size-r.headerSize),a=n(i),o=a.codec.replace(/^avc1\\./,`${C}.`);this.videoConfig={kind:`video`,codec:o,description:i,sps:a.sps,pps:a.pps},this.on.config?.(this.videoConfig)}if(f===`video`){let e=this.tracks.get(o);e&&(e.width=s,e.height=c)}if(f===`audio`&&C===`mp4a`){let t=v(e,x,S,`esds`,36),n=t&&this.parseEsds(e,t);n&&(this.audioConfig=n,this.on.config?.(n))}};parseEsds=(e,t)=>{let n=new Uint8Array(e.buffer,t.contentStart,t.size-t.headerSize);for(let e=0;e<n.length-2;e++){if(n[e]!==5)continue;let{len:t,next:r}=b(n,e+1);if(t<2||r+t>n.length)continue;let i=n.slice(r,r+t),a=i[0],o=i[1],s=a>>3&31,c=(a&7)<<1|o>>7,l=o>>3&15;return{kind:`audio`,codec:`mp4a.40.${s}`,sampleRate:y[c]??44100,numberOfChannels:l,description:i}}return null};findMdatForMoof=(e,t,n)=>{let r=t.offset+t.size;for(;r+8<=n;){let t=m(e,r,n);if(!t||t.type===`moof`)break;if(t.type===`mdat`)return t;r+=t.size}return null};parseMoof=(e,t,n)=>{let r=this.findMdatForMoof(e,t,n.byteLength);r&&h(e,t.contentStart,t.offset+t.size,i=>{i.type===`traf`&&this.parseTraf(e,i,t.offset,r,n)})};ticksToMs=(e,t)=>e/t*1e3;readCttsOffsets=(e,t,n)=>{let r=new Int32Array(n);if(!t||n===0)return r;let i=e.getUint32(t.contentStart+4,!1),a=0,o=0,s=0,c=t.contentStart+8;for(let t=0;t<n;t++)o===0&&a<i&&(o=e.getUint32(c,!1),s=e.getInt32(c+4,!1),c+=8,a++),r[t]=s,--o;return r};parseTraf=(e,t,n,r,i)=>{let a=g(e,t.contentStart,t.offset+t.size,`tfhd`),o=g(e,t.contentStart,t.offset+t.size,`tfdt`),s=g(e,t.contentStart,t.offset+t.size,`trun`);if(!a||!o||!s)return;let c=e.getUint32(a.contentStart+4,!1),l=this.tracks.get(c);if(!l)return;let u=e.getUint32(a.contentStart,!1)&16777215,d=(u&131072)!=0,f=a.contentStart+8,p=null,m=0,h=0;u&1&&(p=Number(e.getBigUint64(f,!1)),f+=8),u&2&&(f+=4),u&8&&(m=e.getUint32(f,!1),f+=4),u&16&&(h=e.getUint32(f,!1),f+=4),u&32&&(f+=4),u&8||(m=l.defaultSampleDuration??0),u&16||(h=l.defaultSampleSize??0);let _=e.getUint8(o.contentStart)===1?Number(e.getBigUint64(o.contentStart+4,!1)):e.getUint32(o.contentStart+4,!1),v=e.getUint32(s.contentStart,!1)&16777215,y=s.offset+s.size,b=s.contentStart+4;if(b+4>y)return;let x=e.getUint32(b,!1);if(b+=4,x===0||x>1e4)return;let S=0;if(v&1){if(b+4>y)return;S=e.getInt32(b,!1),b+=4}v&4&&(b+=4);let C;C=d?n:p===null?r.offset:p;let w=C+(v&1?S:0),T=_;for(let t=0;t<x;t++){let t=m,n=h,r=0;if(v&256){if(b+4>y)break;t=e.getUint32(b,!1),b+=4}if(v&512){if(b+4>y)break;n=e.getUint32(b,!1),b+=4}if(v&1024){if(b+4>y)break;r=e.getUint32(b,!1),b+=4}let a=0;if(v&2048){if(b+4>y)break;a=e.getInt32(b,!1),b+=4}if(t<=0&&l.kind===`audio`){let e=this.audioConfig?.sampleRate??l.timescale;t=Math.round(1024*l.timescale/e)}if(n<=0)continue;if(w+n>i.byteLength)break;let o=i.slice(w,w+n);w+=n;let s=this.ticksToMs(T,l.timescale),c=this.ticksToMs(T+a,l.timescale),u=c-s,d=l.kind!==`video`||!(r>>16&1)||this.isAvccKeyFrame(o)?`key`:`delta`;if(l.kind===`video`){let e=this.splitAvccNalus(o);this.on.chunk?.({kind:`video`,type:d,dts:s,pts:c,cts:u,data:o,nalus:e})}else this.on.chunk?.({kind:`audio`,type:`key`,dts:s,pts:c,cts:u,data:o});T+=t}};parseProgressive=(e,t,n)=>{let r=g(e,0,n.byteLength,`moov`);if(!r)return;let i=[];h(e,r.contentStart,r.offset+r.size,t=>{if(t.type!==`trak`)return;let r=this.collectProgressiveTrackSamples(e,t,n);i.push(...r)}),i.sort((e,t)=>e.dts-t.dts||(e.kind===`video`?-1:1));for(let e of i)this.on.chunk?.(e)};collectProgressiveTrackSamples=(e,t,n)=>{let r=[],i=g(e,t.contentStart,t.offset+t.size,`tkhd`),a=g(e,t.contentStart,t.offset+t.size,`mdia`);if(!i||!a)return r;let o=e.getUint32(i.contentStart+(e.getUint8(i.contentStart)===1?20:12),!1),s=this.tracks.get(o);if(!s)return r;let c=g(e,a.contentStart,a.offset+a.size,`minf`),l=c&&g(e,c.contentStart,c.offset+c.size,`stbl`);if(!l)return r;let u=g(e,l.contentStart,l.offset+l.size,`stsz`),d=g(e,l.contentStart,l.offset+l.size,`stco`),f=g(e,l.contentStart,l.offset+l.size,`co64`),p=g(e,l.contentStart,l.offset+l.size,`stsc`),m=g(e,l.contentStart,l.offset+l.size,`stts`),h=g(e,l.contentStart,l.offset+l.size,`stss`),_=g(e,l.contentStart,l.offset+l.size,`ctts`);if(!u||!d&&!f||!m)return r;let v=e.getUint32(u.contentStart+4,!1),y=e.getUint32(u.contentStart+8,!1),b=this.readCttsOffsets(e,_,y),x=d?e.getUint32(d.contentStart+4,!1):e.getUint32(f.contentStart+4,!1),S=t=>d?e.getUint32(d.contentStart+8+(t-1)*4,!1):Number(e.getBigUint64(f.contentStart+8+(t-1)*8,!1)),C=new Set;if(h){let t=e.getUint32(h.contentStart+4,!1);for(let n=0;n<t;n++)C.add(e.getUint32(h.contentStart+8+n*4,!1))}let w=[];if(p){let t=e.getUint32(p.contentStart+4,!1);for(let n=0;n<t;n++){let t=p.contentStart+8+n*12;w.push({firstChunk:e.getUint32(t,!1),samplesPerChunk:e.getUint32(t+4,!1)})}}let T=e=>{if(w.length===0)return y===x?1:Math.max(1,Math.ceil(y/x));let t=w[0].samplesPerChunk;for(let n of w)if(n.firstChunk<=e)t=n.samplesPerChunk;else break;return t},E=0,D=m.contentStart+8,O=e.getUint32(m.contentStart+4,!1),k=0,A=O>0?e.getUint32(D,!1):0,j=O>0?e.getUint32(D+4,!1):0;D+=8;let M=1;for(let t=1;t<=x&&M<=y;t++){let i=T(t),a=S(t);for(let t=0;t<i&&M<=y;t++,M++){let t=v===0?e.getUint32(u.contentStart+12+(M-1)*4,!1):v;if(a+t>n.byteLength)return r;let i=n.slice(a,a+t);a+=t;let o=this.ticksToMs(E,s.timescale),c=b[M-1]??0,l=this.ticksToMs(E+c,s.timescale),d=l-o,f=s.kind===`video`?this.isAvccKeyFrame(i)||C.has(M)||C.size===0:!0;s.kind===`video`?r.push({kind:`video`,type:f?`key`:`delta`,dts:o,pts:l,cts:d,data:i,nalus:this.splitAvccNalus(i)}):r.push({kind:`audio`,type:`key`,dts:o,pts:l,cts:d,data:i}),E+=j,--A,A===0&&k+1<O&&(k+=1,D=m.contentStart+8+k*8,A=e.getUint32(D,!1),j=e.getUint32(D+4,!1))}}return r};isAvccKeyFrame=e=>{let t=0,n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;t+4<=e.byteLength;){let r=n.getUint32(t,!1);if(r<=0||t+4+r>e.byteLength)break;if((e[t+4]&31)==5)return!0;t+=4+r}return!1};splitAvccNalus=e=>{let t=[],n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+4<=e.byteLength;){let i=r.getUint32(n,!1);if(i<=0||n+4+i>e.byteLength)break;t.push(e.slice(n,n+4+i)),n+=4+i}return t}};let S=new class{pattern;cacher=new e;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case`flv`:this.parser=new l;break;case`hls`:this.parser=new f;break;case`dash`:case`mp4`:this.parser=new x;break;default:throw Error(`is error pattern.`)}this.parser.on.info=e=>this.on.info&&this.on.info(e),this.parser.on.config=e=>this.on.config&&this.on.config(e),this.parser.on.chunk=e=>{this.cacher.pushChunk(e),this.on.chunk&&this.on.chunk(e)}};push=e=>{this.cacher.push(e),this.isParseing===!1&&this.parse()};destroy=()=>{this.cacher.destroy(),this.isParseing=!1,this.offset=0};parse=async()=>{try{if(this.isParseing=!0,!this.pattern)throw Error(`You need to set the pattern.`);if(!this.parser)throw Error(`You need to init parser.`);for(;;){let e=this.cacher.next(this.offset);if(this.offset=0,!e)break;try{let t=await this.parser.parse(e);if(this.pattern===`mp4`||this.pattern===`dash`){let t=this.parser;this.offset=t.getDiscardOffset(e.byteLength,e)}else this.offset=t}catch{this.cacher.discardPayload();continue}}this.isParseing=!1}catch{this.isParseing=!1,this.cacher.discardPayload()}}};S.on.info=e=>postMessage({action:`on.info`,data:e}),S.on.config=e=>postMessage({action:`on.config`,data:e}),S.on.chunk=e=>postMessage({action:`on.chunk`,data:e}),onmessage=e=>{let{action:t,data:n}=e.data,r=S[t];r&&r(n)}})();",n=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,t],{type:`text/javascript;charset=utf-8`});function r(e){let r;try{if(r=n&&(self.URL||self.webkitURL).createObjectURL(n),!r)throw``;let t=new Worker(r,{name:e?.name});return t.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(r)}),t}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(t),{name:e?.name})}}var i=`pr-player-demuxer`,a=class{worker=new r({name:i});on={};constructor(){this.worker.onmessage=e=>{let{action:t,data:n}=e.data;switch(t){case`on.info`:this.on.info&&this.on.info(n);break;case`on.config`:this.on.config&&this.on.config(n);break;case`on.chunk`:this.on.chunk&&this.on.chunk(n);break}}}init=e=>this.worker.postMessage({action:`init`,data:e});push=e=>this.worker.postMessage({action:`push`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`,data:{}}),this.worker.terminate()}},o="(function(){let e=new class{pattern=`flv`;audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;baseTime=0;pendingChunks=[];currentChunk;isProcessing=!1;decodeTimer=0;frameTrack=!1;isFrameTrack=!1;fameTrackOption={flv:[30,50],hls:[200,300],dash:[50,100],mp4:[30,50],rtmp:[50,100]};decodingSpeedRatio=1;maxDecodingSpeedRatio=2;decodingSpeed=16;fps=0;firstVideoChunkTimestamp;secondVideoChunkTimestamp;frameStartTime;lastRenderTime;nextRenderTime;on={audio:{},video:{}};constructor(){}init=e=>{this.destroy(),this.pattern=e,this.baseTime=new Date().getTime()-performance.now(),this.initDecodeInterval()};initAudio=async e=>{if(this.audio.destroy(),!(await AudioDecoder.isConfigSupported(e).catch(()=>({supported:!1}))).supported){console.warn(`[Decoder] audio config not supported:`,e.codec,`audio will be skipped`),this.audioDecoderConfig=void 0,this.audioDecoder=void 0;return}this.audioDecoderConfig={...e},this.audioDecoder=new AudioDecoder({output:e=>{let t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:e,playbackRate:t})},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:e=>{this.frameStartTime||=e.timestamp;try{let t=e.timestamp-this.frameStartTime+this.baseTime*1e3,n=new VideoFrame(e,{timestamp:t});if(e.close(),!n.displayWidth||!n.displayHeight){n.close();return}this.on.video.decode?.({timestamp:t,frame:n}),this.currentChunk?.kind===`video`&&this.currentChunk.nalus&&this.on.nalus?.(this.currentChunk.nalus)}catch{e.close()}},error:e=>{this.on.video.error&&this.on.video.error(e)}}),this.videoDecoder.configure(this.videoDecoderConfig)};setFrameTrack=e=>{this.frameTrack=e,this.frameTrack===!1&&(this.decodingSpeedRatio=1)};push=e=>{this.pendingChunks.push(e)};destroy=()=>{this.audio.destroy(),this.video.destroy(),this.pendingChunks=[],this.firstVideoChunkTimestamp=void 0,this.secondVideoChunkTimestamp=void 0,this.frameStartTime=void 0,this.lastRenderTime=void 0,this.nextRenderTime=void 0,clearInterval(this.decodeTimer)};initDecodeInterval=()=>{let e=this.decodingSpeed/this.decodingSpeedRatio,t=this.baseTime+performance.now();if(this.lastRenderTime||=t,this.fps=Math.round(1e3/(t-this.lastRenderTime)),this.lastRenderTime=t,this.nextRenderTime){let t=this.lastRenderTime-this.nextRenderTime;e-=t}this.nextRenderTime=this.lastRenderTime+e,this.decodeTimer=setTimeout(()=>{try{this.decode()}catch(e){console.error(`[Decoder] decode error:`,e)}this.initDecodeInterval()},e)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;this.currentChunk=this.pendingChunks.shift(),this.currentChunk;){let e=this.pendingChunks.length;if(this.frameTrack){let[t,n]=this.fameTrackOption[this.pattern];if(e<=t&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){let n=Math.min(1+(e-t)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(n.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){let{decodingSpeed:t,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:t,decodingSpeedRatio:n,fps:r,cacheLength:e})}let{kind:t,init:n}=this.currentChunk;switch(t){case`audio`:this.decodeAudio(n);break;case`video`:this.decodeVideo(n);break}if(t===`video`)break}this.isProcessing=!1}};decodeAudio=e=>{if(this.audioDecoder)try{let t=new EncodedAudioChunk(e);this.audioDecoder.decode(t)}catch(e){console.warn(`[Decoder] audio decode error (AudioDecoder may be unusable):`,e)}};decodeVideo=e=>{if(this.videoDecoder&&(e.type===`key`&&(this.hasKeyFrame=!0),this.firstVideoChunkTimestamp?this.secondVideoChunkTimestamp||(this.secondVideoChunkTimestamp=e.timestamp,this.decodingSpeed=(this.secondVideoChunkTimestamp-this.firstVideoChunkTimestamp)/1e3):this.firstVideoChunkTimestamp=e.timestamp,this.hasKeyFrame)){let t=new EncodedVideoChunk(e);this.videoDecoder.decode(t)}};audio={flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}};e.on.audio.decode=e=>postMessage({action:`on.audio.decode`,data:e},[e.audioData]),e.on.audio.error=e=>postMessage({action:`on.audio.error`,data:e}),e.on.video.decode=e=>postMessage({action:`on.video.decode`,data:e},[e.frame]),e.on.video.error=e=>postMessage({action:`on.video.error`,data:e}),e.on.nalus=e=>postMessage({action:`on.nalus`,data:e}),e.on.analysis=e=>postMessage({action:`on.analysis`,data:e}),onmessage=t=>{let{action:n,data:r}=t.data,i=e[n];i&&i(r)}})();",s=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,o],{type:`text/javascript;charset=utf-8`});function c(e){let t;try{if(t=s&&(self.URL||self.webkitURL).createObjectURL(s),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(o),{name:e?.name})}}var l=`pr-player-decoder`,u=class{worker=new c({name:l});on={audio:{},video:{}};constructor(){this.worker.onmessage=e=>{let{action:t,data:n}=e.data;switch(t){case`on.audio.decode`:this.on.audio.decode&&this.on.audio.decode(n);break;case`on.audio.error`:this.on.audio.error&&this.on.audio.error(n);break;case`on.video.decode`:this.on.video.decode&&this.on.video.decode(n);break;case`on.video.error`:this.on.video.error&&this.on.video.error(n);break;case`on.nalus`:this.on.nalus&&this.on.nalus(n);break;case`on.analysis`:this.on.analysis&&this.on.analysis(n);break}}}init=e=>this.worker.postMessage({action:`init`,data:e});initAudio=e=>this.worker.postMessage({action:`initAudio`,data:e});initVideo=e=>this.worker.postMessage({action:`initVideo`,data:e});push=e=>this.worker.postMessage({action:`push`,data:e});setFrameTrack=e=>this.worker.postMessage({action:`setFrameTrack`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`}),this.worker.terminate()}},d='(function(){let e=new class{renderMap=new Map;constructor(){}push=async e=>{let t=e.frame,n=t.timestamp;try{let e=[...this.renderMap.entries()].filter(([,e])=>e&&!e.pause);if(e.length===1&&e[0][0]==="default"&&e[0][1].writer){e[0][1].writer.write(t).catch(()=>{}),t.close();return}for(let[r,i]of e){let{writer:e,offscreen:a,option:o}=i;if(e){let i;if(r==="default"||!o)i=new VideoFrame(t,{timestamp:n});else{let{sx:e=0,sy:r=0,sw:a=t.displayWidth,sh:s=t.displayHeight}=o;i=new VideoFrame(t,{visibleRect:{x:e,y:r,width:a,height:s},displayWidth:a,displayHeight:s,timestamp:n})}e.write(i).catch(()=>{}),i.close()}else if(a)if(r==="default"||!o)a.width=t.displayWidth,a.height=t.displayHeight,a.getContext(`2d`)?.drawImage(t,0,0);else{let{sx:e=0,sy:n=0,sw:r=t.displayWidth,sh:i=t.displayHeight}=o;a.width=r,a.height=i,a.getContext(`2d`)?.drawImage(t,e,n,r,i,0,0,r,i)}}}catch{}t.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,option:i}={key:`default`,...e};if(n){let e=n.getWriter();this.renderMap.set(t,{writer:e,option:i,pause:!1})}else this.renderMap.set(t,{offscreen:r,option:i,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{let{key:t,cutOption:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,option:n})};setPause=e=>{let{key:t,pause:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,pause:n})};destroy=()=>{this.renderMap=new Map}};onmessage=t=>{let{action:n,data:r}=t.data,i=e[n];i&&i(r)}})();',f=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,d],{type:`text/javascript;charset=utf-8`});function p(e){let t;try{if(t=f&&(self.URL||self.webkitURL).createObjectURL(f),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(d),{name:e?.name})}}var m=`pr-player-render`,h=class{worker=new p({name:m});constructor(){}push=e=>this.worker.postMessage({action:`push`,data:e},[e.frame]);addCut=e=>{let t=[];e.writable&&t.push(e.writable),e.offscreen&&t.push(e.offscreen),this.worker.postMessage({action:`addCut`,data:e},t)};delCut=e=>this.worker.postMessage({action:`delCut`,data:e});setCut=e=>this.worker.postMessage({action:`setCut`,data:e});setPause=e=>this.worker.postMessage({action:`setPause`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`,data:{}}),this.worker.terminate()}},g=`data:text/javascript;base64,LyoqDQogKiDpnZnpn7Pml7bvvJrlnKjpopHln5/ku4Xkv53nlZkgYmluIDDvvZ4077yI6ZqP5py677yJ77yM5YW25L2Z5Li6IDDvvIzlho3lkIjmiJDml7bln5/lhpnlhaXovpPlh7og4oCUIOWNs+S/ruaUueecn+WuniBQQ03vvIznu48gQW5hbHlzZXIoZmZ0U2l6ZT01MTIpIOaXtuWJjSA1IOS4qiBiaW4g5pyJ6IO96YeP44CB5YW25L2Z5o6l6L+RIDDjgIINCiAqIFBFUklPRCDpobvkuI4gUHJBdWRpb1N0cmVhbSDkuK0gYW5hbHlzZXJOb2RlLmZmdFNpemUg5LiA6Ie044CCDQogKi8NCmNsYXNzIE5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3NvciBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3NvciB7DQogIGlzRGVzdHJveSA9IGZhbHNlDQogIGRlYnVnID0gZmFsc2UNCg0KICBzdGF0aWMgU0lMRU5DRV9FUFMgPSAxZS0xNQ0KDQogIC8qKiDkuI4gc3JjL1ByQXVkaW9TdHJlYW0udHMg6YeMIGFuYWx5c2VyTm9kZS5mZnRTaXplIOS/neaMgeS4gOiHtCAqLw0KICBzdGF0aWMgUEVSSU9EID0gNTEyDQoNCiAgLyoqIGJpbiAw772eNCDpmo/mnLrlpI3mlbDvvIjlrp7pg6gv6Jma6YOo77yJ55qE5aSn6Ie05bmF5bqm5bC65bqm77yM5Y+v5oyJ5ZCs5oSfL+e8lueggeWGjeiwgyAqLw0KICBzdGF0aWMgQklOX1NDQUxFID0gMC4wMg0KDQogIGNvbnN0cnVjdG9yKCkgew0KICAgIHN1cGVyKCkNCiAgICB0aGlzLl9zaWxlbnRQY20gPSBuZXcgRmxvYXQzMkFycmF5KE5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5QRVJJT0QpDQogICAgdGhpcy5fc2lsZW50T2ZmID0gTm90RW1wdHlGaWx0ZXJXb3JrbGV0UHJvY2Vzc29yLlBFUklPRA0KICB9DQoNCiAgc3RhdGljIGFsbElucHV0c1NpbGVudChpbnB1dHMpIHsNCiAgICBjb25zdCBlcHMgPSBOb3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuU0lMRU5DRV9FUFMNCiAgICBmb3IgKGxldCBuaSA9IDA7IG5pIDwgaW5wdXRzLmxlbmd0aDsgbmkrKykgew0KICAgICAgY29uc3QgaW5wdXQgPSBpbnB1dHNbbmldDQogICAgICBpZiAoIWlucHV0KSBjb250aW51ZQ0KICAgICAgZm9yIChsZXQgY2ggPSAwOyBjaCA8IGlucHV0Lmxlbmd0aDsgY2grKykgew0KICAgICAgICBjb25zdCBjaGFubmVsID0gaW5wdXRbY2hdDQogICAgICAgIGlmICghY2hhbm5lbCkgY29udGludWUNCiAgICAgICAgY29uc3QgbiA9IGNoYW5uZWwubGVuZ3RoDQogICAgICAgIGZvciAobGV0IGkgPSAwOyBpIDwgbjsgaSsrKSB7DQogICAgICAgICAgaWYgKE1hdGguYWJzKGNoYW5uZWxbaV0pID49IGVwcykgcmV0dXJuIGZhbHNlDQogICAgICAgIH0NCiAgICAgIH0NCiAgICB9DQogICAgcmV0dXJuIHRydWUNCiAgfQ0KDQogIC8qKg0KICAgKiDku4UgYmluIDAuLjQg6Z2e6Zu277yI6ZqP5py677yJ77yM5ruh6Laz5a6e5L+h5Y+3IElERlTvvIzlhpnlhaUgdGhpcy5fc2lsZW50UGNtDQogICAqLw0KICByZWZpbGxTaWxlbnRQY21Gcm9tRml2ZUJpbnMoKSB7DQogICAgY29uc3QgTiA9IE5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5QRVJJT0QNCiAgICBjb25zdCBzY2FsZSA9IE5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5CSU5fU0NBTEUNCiAgICBjb25zdCByZSA9IG5ldyBGbG9hdDY0QXJyYXkoNSkNCiAgICBjb25zdCBpbSA9IG5ldyBGbG9hdDY0QXJyYXkoNSkNCiAgICByZVswXSA9IChNYXRoLnJhbmRvbSgpICogMiAtIDEpICogc2NhbGUNCiAgICBpbVswXSA9IDANCiAgICBmb3IgKGxldCBrID0gMTsgayA8PSA0OyBrKyspIHsNCiAgICAgIHJlW2tdID0gKE1hdGgucmFuZG9tKCkgKiAyIC0gMSkgKiBzY2FsZQ0KICAgICAgaW1ba10gPSAoTWF0aC5yYW5kb20oKSAqIDIgLSAxKSAqIHNjYWxlDQogICAgfQ0KICAgIGNvbnN0IGludk4gPSAxIC8gTg0KICAgIGNvbnN0IHR3b1BpT3Zlck4gPSAoMiAqIE1hdGguUEkpIC8gTg0KICAgIGZvciAobGV0IG4gPSAwOyBuIDwgTjsgbisrKSB7DQogICAgICBsZXQgcyA9IHJlWzBdDQogICAgICBmb3IgKGxldCBrID0gMTsgayA8PSA0OyBrKyspIHsNCiAgICAgICAgY29uc3QgYW5nID0gdHdvUGlPdmVyTiAqIGsgKiBuDQogICAgICAgIHMgKz0gMiAqIChyZVtrXSAqIE1hdGguY29zKGFuZykgLSBpbVtrXSAqIE1hdGguc2luKGFuZykpDQogICAgICB9DQogICAgICB0aGlzLl9zaWxlbnRQY21bbl0gPSBzICogaW52Tg0KICAgIH0NCiAgICB0aGlzLl9zaWxlbnRPZmYgPSAwDQogIH0NCg0KICBmaWxsT3V0cHV0c1NwYXJzZUZpdmVCaW5zKG91dHB1dHMpIHsNCiAgICBjb25zdCBmaXJzdCA9IG91dHB1dHNbMF0NCiAgICBpZiAoIWZpcnN0IHx8ICFmaXJzdFswXSkgcmV0dXJuDQogICAgY29uc3QgZnJhbWVMZW4gPSBmaXJzdFswXS5sZW5ndGgNCg0KICAgIGZvciAobGV0IGkgPSAwOyBpIDwgZnJhbWVMZW47IGkrKykgew0KICAgICAgaWYgKHRoaXMuX3NpbGVudE9mZiA+PSBOb3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuUEVSSU9EKSB7DQogICAgICAgIHRoaXMucmVmaWxsU2lsZW50UGNtRnJvbUZpdmVCaW5zKCkNCiAgICAgIH0NCiAgICAgIGNvbnN0IHYgPSB0aGlzLl9zaWxlbnRQY21bdGhpcy5fc2lsZW50T2ZmKytdDQogICAgICBmb3IgKGxldCBubyA9IDA7IG5vIDwgb3V0cHV0cy5sZW5ndGg7IG5vKyspIHsNCiAgICAgICAgY29uc3Qgb3V0UG9ydHMgPSBvdXRwdXRzW25vXQ0KICAgICAgICBpZiAoIW91dFBvcnRzKSBjb250aW51ZQ0KICAgICAgICBmb3IgKGxldCBjaCA9IDA7IGNoIDwgb3V0UG9ydHMubGVuZ3RoOyBjaCsrKSB7DQogICAgICAgICAgY29uc3QgY2hhbm5lbCA9IG91dFBvcnRzW2NoXQ0KICAgICAgICAgIGlmIChjaGFubmVsKSBjaGFubmVsW2ldID0gdg0KICAgICAgICB9DQogICAgICB9DQogICAgfQ0KICB9DQoNCiAgc3RhdGljIGNvcHlJbnB1dHNUb091dHB1dHMoaW5wdXRzLCBvdXRwdXRzKSB7DQogICAgZm9yIChsZXQgbm8gPSAwOyBubyA8IG91dHB1dHMubGVuZ3RoOyBubysrKSB7DQogICAgICBjb25zdCBvdXRQb3J0cyA9IG91dHB1dHNbbm9dDQogICAgICBjb25zdCBpblBvcnRzID0gaW5wdXRzW25vXQ0KICAgICAgaWYgKCFvdXRQb3J0cykgY29udGludWUNCiAgICAgIGZvciAobGV0IGNoID0gMDsgY2ggPCBvdXRQb3J0cy5sZW5ndGg7IGNoKyspIHsNCiAgICAgICAgY29uc3Qgb3V0Q2ggPSBvdXRQb3J0c1tjaF0NCiAgICAgICAgaWYgKCFvdXRDaCkgY29udGludWUNCiAgICAgICAgY29uc3QgaW5DaCA9IGluUG9ydHMgJiYgaW5Qb3J0c1tjaF0NCiAgICAgICAgaWYgKGluQ2ggJiYgaW5DaC5sZW5ndGggPT09IG91dENoLmxlbmd0aCkgew0KICAgICAgICAgIG91dENoLnNldChpbkNoKQ0KICAgICAgICB9IGVsc2UgaWYgKGluQ2gpIHsNCiAgICAgICAgICBjb25zdCBuID0gTWF0aC5taW4oaW5DaC5sZW5ndGgsIG91dENoLmxlbmd0aCkNCiAgICAgICAgICBmb3IgKGxldCBpID0gMDsgaSA8IG47IGkrKykgb3V0Q2hbaV0gPSBpbkNoW2ldDQogICAgICAgICAgZm9yIChsZXQgaSA9IG47IGkgPCBvdXRDaC5sZW5ndGg7IGkrKykgb3V0Q2hbaV0gPSAwDQogICAgICAgIH0gZWxzZSB7DQogICAgICAgICAgb3V0Q2guZmlsbCgwKQ0KICAgICAgICB9DQogICAgICB9DQogICAgfQ0KICB9DQoNCiAgcHJvY2VzcyhpbnB1dHMsIG91dHB1dHMpIHsNCiAgICBpZiAodGhpcy5pc0Rlc3Ryb3kpIHJldHVybiBmYWxzZQ0KDQogICAgaWYgKHRoaXMuZGVidWcpIHsNCiAgICAgIGNvbnNvbGUubG9nKCdceDFiWzM4OzI7MDsxNTE7MjU1bSVjJXNceDFiWzBtJywgJ2NvbG9yOiMwMDk3ZmY7JywgJy0tLS0tLS0+QnJlYXRoZTogaW5wdXRzJywgaW5wdXRzKQ0KICAgIH0NCg0KICAgIGlmIChOb3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuYWxsSW5wdXRzU2lsZW50KGlucHV0cykpIHsNCiAgICAgIHRoaXMuZmlsbE91dHB1dHNTcGFyc2VGaXZlQmlucyhvdXRwdXRzKQ0KICAgIH0gZWxzZSB7DQogICAgICB0aGlzLl9zaWxlbnRPZmYgPSBOb3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuUEVSSU9EDQogICAgICBOb3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuY29weUlucHV0c1RvT3V0cHV0cyhpbnB1dHMsIG91dHB1dHMpDQogICAgfQ0KDQogICAgcmV0dXJuIHRydWUNCiAgfQ0KDQogIGRlc3Ryb3koKSB7DQogICAgdGhpcy5pc0Rlc3Ryb3kgPSB0cnVlDQogIH0NCn0NCg0KcmVnaXN0ZXJQcm9jZXNzb3IoJ25vdC1lbXB0eS1maWx0ZXItcHJvY2Vzc29yJywgTm90RW1wdHlGaWx0ZXJXb3JrbGV0UHJvY2Vzc29yKQ0K`,_=class{audioContext=new AudioContext;notEmptyFilterWorkletNode;constructor(){}createNotEmptyFilterWorkletNode=async e=>(this.destroy(),this.audioContext=e,await this.audioContext.audioWorklet.addModule(g),this.notEmptyFilterWorkletNode=new AudioWorkletNode(this.audioContext,`not-empty-filter-processor`),this.notEmptyFilterWorkletNode);destroy=()=>{this.notEmptyFilterWorkletNode?.disconnect(),this.notEmptyFilterWorkletNode?.port.postMessage({type:`destroy`}),this.notEmptyFilterWorkletNode=void 0}},v=class{inputStream=new MediaStream;outputStream=new MediaStream;inputGain=1;enhanceGain=1;bgsGain=1;bgmGain=1;outputGain=1;mixAudioMap=new Map;audioContext=new AudioContext;isExternalAudioContext=!1;sourceNode;inputGainNode;enhanceGainNode;bgsGainNode;bgmGainNode;rnnoiseNode;analyserNode;analyserArrayData;outputGainNode;destinationNode;denoise=!1;mute=!0;notEmpty=!1;rnnoiseWorklet;rnnoiseWorkletNode;notEmptyFilterWorklet=new _;notEmptyFilterWorkletNode;filterStream=e=>e;constructor(e,t){this.inputStream=e,t&&(this.audioContext=t,this.isExternalAudioContext=!0),this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.inputGainNode=this.audioContext.createGain(),this.inputGainNode.gain.setValueAtTime(this.inputGain,this.audioContext.currentTime),this.enhanceGainNode=this.audioContext.createGain(),this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime),this.bgsGainNode=this.audioContext.createGain(),this.bgsGainNode.gain.setValueAtTime(this.bgsGain,this.audioContext.currentTime),this.bgmGainNode=this.audioContext.createGain(),this.bgmGainNode.gain.setValueAtTime(this.bgmGain,this.audioContext.currentTime),this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=512,this.analyserArrayData=new Uint8Array(this.analyserNode.frequencyBinCount),this.outputGainNode=this.audioContext.createGain(),this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputStream=this.destinationNode.stream;{let{sourceNode:e,inputGainNode:t,enhanceGainNode:n,bgsGainNode:r,bgmGainNode:i,analyserNode:a,outputGainNode:o,destinationNode:s}=this;e.connect(t),t.connect(n),n.connect(a),r.connect(a),i.connect(a),n.connect(s),r.connect(s),i.connect(s),o.connect(this.audioContext.destination)}this.audioContext.resume()}use=({rnnoise:e})=>{this.rnnoiseWorklet=new e.RnnoiseWorklet};_changeSource=()=>{this.sourceNode.disconnect(),this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.sourceNode.connect(this.inputGainNode)};replaceTrack=e=>{let t=this.inputStream.getTracks();for(let e of t)this.inputStream.removeTrack(e);this.inputStream.addTrack(e),this._changeSource()};stop=()=>{{let e=this.inputStream.getTracks();for(let t of e)t.stop(),this.inputStream.removeTrack(t)}};pause=async e=>{let t=this.inputStream.getTracks();for(let n of t)n.enabled=!e};getStream=()=>this.filterStream(this.outputStream);setMute=(e=!0)=>{this.mute=e,this.analyserNode.disconnect(),e===!1&&this.analyserNode.connect(this.outputGainNode)};setDenoise=async(e=!0)=>{this.rnnoiseWorklet&&(this.inputGainNode.disconnect(),e?(this.rnnoiseWorkletNode=await this.rnnoiseWorklet.createRnnoiseWorkletNode(this.audioContext),this.inputGainNode.connect(this.rnnoiseWorkletNode),this.rnnoiseWorkletNode.connect(this.enhanceGainNode)):(this.inputGainNode.connect(this.enhanceGainNode),this.rnnoiseWorklet.destroy()),this.denoise=e)};setNotEmpty=async(e=!0)=>{this.notEmptyFilterWorklet&&(e?(this.notEmptyFilterWorkletNode=await this.notEmptyFilterWorklet.createNotEmptyFilterWorkletNode(this.audioContext),this.notEmptyFilterWorkletNode.connect(this.analyserNode),this.notEmptyFilterWorkletNode.connect(this.destinationNode)):(this.notEmptyFilterWorkletNode?.disconnect(),this.notEmptyFilterWorklet.destroy()),this.notEmpty=e)};setInputGain=e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setEnhanceGain=async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)};setBgsGain=e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setBgmGain=e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setOutputGain=e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)};getVolume=()=>{let{analyserNode:e,analyserArrayData:t}=this;e.getByteFrequencyData(t);let n=0;for(let e=0;e<t.length;e++)n+=t[e];return Math.ceil(n/t.length)};mixAudio=(e,t=`bgm`)=>new Promise(async(n,r)=>{try{{let e=this.mixAudioMap.get(t);e&&e.stop()}let r=t===`bgs`?this.bgsGainNode:this.bgmGainNode,i=this.audioContext.createBufferSource();this.mixAudioMap.set(t,i),i.buffer=e,i.connect(r),i.onended=()=>{i.disconnect(r),this.mixAudioMap.delete(t),n(!0)},i.start(0)}catch(e){r(e)}});mixAudioStop=e=>{this.mixAudioMap.get(e)?.stop()};changeMix=(e,t)=>{let n=e===`bgs`?this.bgsGainNode:this.bgmGainNode;t?n.connect(this.destinationNode):n.disconnect(this.destinationNode)};destroy=async()=>{for(let e of this.mixAudioMap.values())e.stop(),e.disconnect();this.mixAudioMap.clear(),this.notEmptyFilterWorklet.destroy(),this.rnnoiseWorklet?.destroy(),this.notEmptyFilterWorkletNode=void 0,this.rnnoiseWorkletNode=void 0,this.sourceNode.disconnect(),this.inputGainNode.disconnect(),this.enhanceGainNode.disconnect(),this.bgsGainNode.disconnect(),this.bgmGainNode.disconnect(),this.analyserNode.disconnect(),this.outputGainNode.disconnect();for(let e of this.inputStream.getTracks())e.stop(),this.inputStream.removeTrack(e);for(let e of this.outputStream.getTracks())e.stop(),this.outputStream.removeTrack(e);this.notEmpty=!1,this.denoise=!1,this.mute=!0,!this.isExternalAudioContext&&this.audioContext.state!==`closed`&&await this.audioContext.close()}},y=async(e,t)=>{try{let{format:n,numberOfChannels:r,numberOfFrames:i,sampleRate:a}=t,o=e.createBuffer(r,i,a);for(let e=0;e<r;e++){let r=t.allocationSize({planeIndex:e}),a=new Uint8Array(r);t.copyTo(a,{planeIndex:e});let s=new DataView(a.buffer),c=o.getChannelData(e);for(let e=0;e<i;e++){let t;switch(n){case`s16`:case`s16-planar`:t=s.getInt16(e*2,!0)/32768;break;case`f32`:case`f32-planar`:t=s.getFloat32(e*4,!0);break;case`u8`:case`u8-planar`:t=(s.getUint8(e)-128)/128;break;default:throw Error(`Unsupported audio format: ${n}`)}c[e]=Math.max(-1,Math.min(1,t))}}return o}catch(e){throw console.error(`Failed to convert AudioData to AudioBuffer:`,e),e}},b=class{prAudioStream;audioContext;destination;stream=new MediaStream;nextStartTime=0;pendingSources=[];constructor(){}init=e=>{e||=new(window.AudioContext||window.webkitAudioContext),this.audioContext=e,this.destination=this.audioContext.createMediaStreamDestination(),this.stream=new MediaStream,this.stream.addTrack(this.destination.stream.getAudioTracks()[0]),this.prAudioStream=new v(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(e){let{audioData:t,playbackRate:n=1}=e;if(!this.audioContext||!this.destination)return;let r=await y(this.audioContext,t);if(t.close(),!r)return;let i=this.audioContext.createBufferSource();i.buffer=r,i.playbackRate.value=n;let a=-1200*Math.log2(n);i.detune.value=a,i.connect(this.destination);let o=Math.max(this.nextStartTime,this.audioContext.currentTime),s=r.duration/n;this.nextStartTime=o+s,i.start(o),this.pendingSources.push(i),i.onended=()=>{this.pendingSources=this.pendingSources.filter(e=>e!==i)},this.audioContext.state===`suspended`&&await this.audioContext.resume()}getStream=()=>this.prAudioStream?.getStream();destroy(){this.audioContext?.close(),this.audioContext=void 0,this.destination=void 0,this.nextStartTime=0,this.prAudioStream?.stop(),this.prAudioStream?.destroy(),this.pendingSources.forEach(e=>e.stop()),this.pendingSources=[]}},x=e=>{let t=e.toLowerCase();return t.includes(`.m3u8`)||t.includes(`hls`)||t.includes(`master.m3u8`)||t.match(/index\d*\.m3u8/)?`hls`:t.includes(`.mpd`)||t.includes(`dash`)?`dash`:t.includes(`.mp4`)||t.includes(`.m4s`)?`mp4`:t.startsWith(`rtmp://`)||t.startsWith(`rtmps://`)?`rtmp`:t.includes(`.flv`)||t.includes(`flv`)&&!t.includes(`flash`)?`flv`:`unknown`},S=e=>{let t=e?.getTracks()||[];for(let e of t)e.stop()},C=class{resolvesMap=new Map;index=0;constructor(){}add=(e,t=()=>!1,n=0)=>new Promise(r=>{if(t())return r(!0);this.resolvesMap.has(e)||this.resolvesMap.set(e,new Map),this.index++;let i=`${this.index}`;if(n=Math.max(0,n),n===0){this.resolvesMap.get(e)?.set(i,{resolve:r,timer:0});return}let a=window.setTimeout(()=>{this.emit(e)},n);this.resolvesMap.get(e)?.set(i,{resolve:r,timer:a})});emit=async e=>{let t=this.resolvesMap.get(e);if(!t)return;let n=[...t.keys()];for(let e of n){let n=t.get(e);n&&(clearTimeout(n.timer),n.resolve(),t.delete(e))}}},w=(e,t)=>{let n=new Uint8Array(e),r=new Uint8Array(t),i=new Uint8Array(11+n.length+r.length),a=0;return i[a++]=1,i[a++]=n[1],i[a++]=n[2],i[a++]=n[3],i[a++]=255,i[a++]=225,i[a++]=n.length>>8&255,i[a++]=n.length&255,i.set(n,a),a+=n.length,i[a++]=1,i[a++]=r.length>>8&255,i[a++]=r.length&255,i.set(r,a),i},T=e=>{let t=0,n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(t);if(t+=1,r!==1)throw Error(`Invalid AVC version`);let i=n.getUint8(t)&255;t+=1;let a=n.getUint8(t)&255;t+=1;let o=n.getUint8(t)&255;t+=1;let s=`avc1.${Array.from([i,a,o],e=>e.toString(16).padStart(2,`0`)).join(``)}`;t+=1,t+=1;let c=n.getUint16(t,!1);t+=2;let l=new Uint8Array(e.buffer,e.byteOffset+t,c);t+=c,t+=1;let u=n.getUint16(t,!1);return t+=2,{version:r,codec:s,profile:i,compatibility:a,level:o,sps:l,pps:new Uint8Array(e.buffer,e.byteOffset+t,u)}},E=e=>{let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t},D=e=>{let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n},O=e=>{let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=0,r=t.getUint32(n,!1);n+=4;let i=t.getUint8(n),a={forbidden_zero_bit:i>>7&1,nal_ref_idc:i>>5&3,nal_unit_type:i&31};return n+=1,{size:r,header:a,data:new Uint8Array(e.buffer,e.byteOffset+n,r-1)}},k=(e,t)=>e.match(RegExp(`${t}="([^"]*)"`,`i`))?.[1],A=e=>{let[t,n]=e.split(`-`).map(e=>parseInt(e,10));return{start:t,end:n}},j=e=>{if(!e)return;let t=e.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:([\d.]+)S)?/i);if(!t)return;let n=parseInt(t[1]||`0`,10),r=parseInt(t[2]||`0`,10),i=parseFloat(t[3]||`0`);return n*3600+r*60+i},M=(e,t)=>{if(!t)return e;if(/^https?:\/\//i.test(t))return t;if(t.startsWith(`/`)){let n=e.match(/^(https?:\/\/[^/]+)/i)?.[1];return n?`${n}${t}`:t}return e+t},N=(e,t)=>e.replace(/\$(RepresentationID|\w+)(?:%0(\d+)d)?\$/g,(e,n,r)=>{let i=t[n]??t[n.toLowerCase()]??``;return r?String(i).padStart(Number(r),`0`):String(i)}),P=(e,t,n)=>M(e,N(t,n)),F=(e,t)=>{let n=e.match(/<SegmentList([^>]*)>([\s\S]*?)<\/SegmentList>/i)||t.match(/<SegmentList([^>]*)>([\s\S]*?)<\/SegmentList>/i);if(!n)return;let r=n[1],i=n[2],a=i.match(/<Initialization[^>]*range="([^"]+)"/i),o=[],s=/<SegmentURL[^>]*mediaRange="([^"]+)"/gi,c;for(;c=s.exec(i);)o.push(A(c[1]));if(!(o.length===0&&!a))return{timescale:parseInt(k(r,`timescale`)||`1000`,10),duration:parseInt(k(r,`duration`)||`0`,10),initRange:a?A(a[1]):void 0,segments:o}},I=(e,t)=>{let n=e.match(/<SegmentTemplate([^>]*)\/>/i)?.[1]||e.match(/<SegmentTemplate([^>]*)>/i)?.[1]||t.match(/<SegmentTemplate([^>]*)\/>/i)?.[1]||t.match(/<SegmentTemplate([^>]*)>/i)?.[1]||``;if(!n){let t=e.match(/<SegmentURL[^>]*initialization="([^"]*)"[^>]*media="([^"]*)"/i);return t?{initialization:t[1],media:t[2],timescale:1e3,duration:0,startNumber:1}:void 0}return{initialization:k(n,`initialization`),media:k(n,`media`),timescale:parseInt(k(n,`timescale`)||`1000`,10),duration:parseInt(k(n,`duration`)||`0`,10),startNumber:parseInt(k(n,`startNumber`)||`1`,10)}},L=(e,t)=>{let n=t.substring(0,t.lastIndexOf(`/`)+1),r=e.match(/<MPD[^>]*>/i)?.[0]||``,i=(k(r,`type`)||`static`)===`dynamic`,a=j(k(r,`mediaPresentationDuration`)),o=[],s=/<AdaptationSet([^>]*)>([\s\S]*?)<\/AdaptationSet>/gi,c;for(;c=s.exec(e);){let e=c[1],t=c[2],n=k(e,`mimeType`)||``,r=k(e,`contentType`)||``,i=n.includes(`video`)||r===`video`||/<ContentComponent[^>]*contentType="video"/i.test(t),a=n.includes(`audio`)||r===`audio`||/<ContentComponent[^>]*contentType="audio"/i.test(t),s;if(i&&a?s=`mux`:i?s=`video`:a&&(s=`audio`),!s)continue;let l=t.match(/<Representation([^>]*)(?:\/>|>([\s\S]*?)<\/Representation>)/i);if(!l)continue;let u=l[1],d=l[2]||``,f=k(u,`id`)||`0`,p=k(u,`codecs`)||``,m=parseInt(k(u,`bandwidth`)||`0`,10),h=parseInt(k(u,`width`)||`0`,10)||void 0,g=parseInt(k(u,`height`)||`0`,10)||void 0,_=d.match(/<BaseURL>([^<]+)<\/BaseURL>/i)?.[1]?.trim(),v=F(d,t),y=v?void 0:I(d,t);!v&&(!y||!y.media&&!y.initialization)||o.push({kind:s,mimeType:n||(i?`video/mp4`:`audio/mp4`),representation:{id:f,codecs:p,bandwidth:m,width:h,height:g,baseUrl:_,template:y,segmentList:v}})}return{isLive:i,duration:a,baseUrl:n,adaptations:o}},R=class{#e={timeout:5*1e3,check:!1};#t=null;constructor(e={}){this.#e={...this.#e,...e}}#n=(e,t)=>new Promise(async n=>{this.#t=new AbortController;let{signal:r}=this.#t,i=this.#e.timeout,a=setTimeout(()=>{this.#t?.abort(`Timeout (${i}ms)`)},i);await fetch(e,{cache:`no-store`,...t,method:`HEAD`,signal:r}).then(e=>{clearTimeout(a),n({status:e.status===200?`successed`:`failed`,reason:e.status===200?``:`HTTP ${e.status}`})}).catch(e=>{if(clearTimeout(a),e.name===`AbortError`){let e=r.reason||`Actively stopped`;n({status:e.includes(`Timeout`)?`timeout`:`stopped`,reason:e})}else n({status:`error`,reason:e.message})})});request=(e,t)=>new Promise(async(n,r)=>{try{this.stop(),this.#e.check&&await this.#n(e),this.#t=new AbortController;let{signal:r}=this.#t;n(await fetch(e,{cache:`no-store`,...t,signal:r}))}catch(e){r(e)}});stop=()=>{if(this.#t?.signal.aborted===!1){let e=Error(`Actively stopped.`);e.name=`AbortError`,this.#t.abort(e)}}},z=class{option={frameTrack:!1};converter=`MediaStreamTrackGenerator`in window?`generator`:`canvas`;prFetch=new R;getSegmentsFetch=new R;prResolves=new C;url=``;start_resolve;demuxerWorker;decoderWorker;audioPlayer;renderWorker;stream;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(e={}){this.option.frameTrack=e.frameTrack??!1}start=async e=>{await this.stop(),this.url=e;let t=x(e);if(t===`unknown`)throw Error(`This address cannot be parsed.`);switch(this.init(t),t){case`flv`:this.flv.start();break;case`hls`:this.hls.start();break;case`dash`:this.dash.start();break;case`mp4`:this.mp4.start();break;case`rtmp`:throw Error(`RTMP is not supported in browser. Please use HTTP-FLV or HLS.`)}};stop=async()=>{try{this.url=``,clearInterval(this.hls.getSegmentsTimer),clearInterval(this.dash.getSegmentsTimer),this.prFetch.stop(),this.getSegmentsFetch.stop(),this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy(),this.cutRenders=new Map,S(this.stream),this.audioPlayer?.destroy()}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: error`,e)}};getStream=()=>this.stream;setPause=e=>{this.renderWorker?.setPause({pause:e})};setMute=e=>this.audioPlayer?.prAudioStream?.setMute(e);setOutputGain=e=>{this.audioPlayer?.prAudioStream?.setOutputGain(e)};setFrameTrack=e=>{this.option.frameTrack=e,this.decoderWorker?.setFrameTrack(e)};isReady=()=>this.prResolves.add(`isReady`,()=>this.stream?.active===!0);cut={create:(e,t)=>{if(this.converter===`generator`){let n=new MediaStreamTrackGenerator({kind:`video`}),r=new MediaStream([n]);return this.renderWorker?.addCut({key:e,writable:n.writable,option:t}),this.cutRenders.set(e,{stream:r}),r}let n=document.createElement(`canvas`),r=n.captureStream(),i=n.transferControlToOffscreen();return this.renderWorker?.addCut({key:e,offscreen:i,option:t}),this.cutRenders.set(e,{stream:r}),r},setCut:(e,t)=>{this.renderWorker?.setCut({key:e,cutOption:t})},getStream:e=>this.cutRenders.get(e)?.stream,remove:e=>{this.renderWorker?.delCut(e),this.cutRenders.delete(e)},setPause:(e,t)=>{this.renderWorker?.setPause({key:e,pause:t})}};init=e=>{this.initRender(),this.initDecoder(e),this.initDemuxer(e),this.audioPlayer=new b,this.audioPlayer.init()};initDemuxer=e=>{this.demuxerWorker=new a,this.demuxerWorker.init(e),this.demuxerWorker.on.info=e=>{this.on.demuxer.info&&this.on.demuxer.info(e)},this.demuxerWorker.on.config=e=>{this.on.demuxer.config&&this.on.demuxer.config(e);let{kind:t}=e;switch(t){case`audio`:{let{codec:t,sampleRate:n,numberOfChannels:r,description:i}=e;this.decoderWorker?.initAudio({codec:t,sampleRate:n,numberOfChannels:r,...i?{description:i}:{}})}break;case`video`:{let{codec:t,description:n}=e;this.decoderWorker?.initVideo({codec:t,description:n})}break}},this.demuxerWorker.on.chunk=e=>{if(this.on.demuxer.chunk&&this.on.demuxer.chunk(e),!this.decoderWorker)return;let{kind:t}=e;switch(t){case`audio`:{let{type:n,dts:r,data:i}=e,a=r*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:a,data:i}})}break;case`video`:{let{type:n,dts:r,data:i,nalus:a=[]}=e,o=r*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:o,data:i},nalus:a})}break}}};initDecoder=e=>{this.decoderWorker=new u,this.decoderWorker.init(e);let{frameTrack:t=!1}=this.option;this.decoderWorker.setFrameTrack(t),this.decoderWorker.on.audio.error=e=>{this.on.error&&this.on.error(e)},this.decoderWorker.on.audio.decode=e=>{this.audioPlayer?.push(e),this.on.decoder.audio&&this.on.decoder.audio(e)},this.decoderWorker.on.video.decode=e=>{this.start_resolve&&=(this.start_resolve(!0),void 0),this.renderWorker?.push(e),this.on.decoder.video&&this.on.decoder.video(e)},this.decoderWorker.on.video.error=e=>{this.on.error&&this.on.error(e)},this.decoderWorker.on.nalus=async e=>{for(let t of e){if(t.byteLength<=4)continue;let{header:e,data:n}=O(t),{nal_unit_type:r}=e;r===6&&this.on.decoder.sei&&this.on.decoder.sei(n)}},this.decoderWorker.on.analysis=e=>{this.on.decoder.analysis&&this.on.decoder.analysis(e)}};initRender=()=>{if(this.renderWorker=new h,this.converter===`generator`){let e=new MediaStreamTrackGenerator({kind:`video`}),t=new MediaStream([e]);this.renderWorker?.addCut({writable:e.writable}),this.stream=t}else{let e=document.createElement(`canvas`),t=e.captureStream(),n=e.transferControlToOffscreen();this.renderWorker?.addCut({offscreen:n}),this.stream=t}this.renderWorker?.setPause({pause:!1})};flv={start:()=>new Promise(async(e,t)=>{try{this.start_resolve=e;let n,r=0;for(;;){r+=1;try{n=await this.prFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(n?.status===200||r===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!n||n.status!==200)return t(`request is error.`);let i=n.body?.getReader();if(!i)return t(`reader is error.`);for(;;){let{done:e,value:t}=await i.read();if(t&&this.demuxerWorker?.push(t),e||this.url===``)break}}catch(e){e.name!==`AbortError`&&t(e)}})};hls={isLive:!1,urls:[],url:``,getSegmentsTimer:0,parse:async e=>{let t=new TextDecoder(`utf-8`).decode(e).split(`
|
|
2
|
-
`).map(e=>e.replace(`\r`,``)),n=this.url.substring(0,this.url.lastIndexOf(`/`)+1),r=4,i=0,a=!1,o=[];for(let e of t)e.startsWith(`#EXTINF:`)?r=parseFloat(e.split(`:`)[1].split(`,`)[0]):e.startsWith(`#EXT-X-TARGETDURATION:`)?i=parseInt(e.split(`:`)[1]):e.startsWith(`#EXT-X-ENDLIST`)?a=!1:e.startsWith(`#EXT-X-MEDIA-SEQUENCE:`)?a=!0:e.includes(`.ts`)&&!e.startsWith(`#`)&&o.push({url:e.startsWith(`http`)?e:n+e,duration:r,isLive:a});return{baseUrl:n,targetDuration:i,isLive:a,segments:o}},getSegments:async()=>{try{let e,t=0;for(;;){t+=1;try{e=await this.getSegmentsFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(e?.status===200||t===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!e||e.status!==200)throw Error(`request is error.`);let n=e.body?.getReader();if(!n)throw Error(`reader is error.`);for(;;){let{done:e,value:t}=await n.read();if(t){let{segments:e=[],isLive:n=!1}=await this.hls.parse(t);this.hls.isLive=n,n===!1&&(this.option.frameTrack=!1);let r=Array.from(e,e=>e.url),i=r.findIndex(e=>e===this.hls.url);i!==-1&&(r=r.slice(i+1)),this.hls.urls=r}if(e||this.url===``)break}}catch(e){e.name!==`AbortError`&&this.on.error&&this.on.error(e)}},start:()=>new Promise(async(e,t)=>{try{for(this.start_resolve=e,this.hls.url=``,this.hls.urls=[],await this.hls.getSegments(),this.hls.getSegmentsTimer=window.setInterval(this.hls.getSegments,500),this.hls.isLive===!1&&(clearInterval(this.hls.getSegmentsTimer),this.decoderWorker?.setFrameTrack(!1));;){let e=this.hls.urls.shift();if(e){this.hls.url=e;let t=(await this.prFetch.request(e)).body?.getReader();if(!t)throw Error(`segment reader is error.`);for(;;){let{done:e,value:n}=await t.read();if(n&&this.demuxerWorker?.push(n),e||this.url===``)break}}else await new Promise(e=>setTimeout(()=>e(!0),300))}}catch(e){e.name!==`AbortError`&&t(e)}})};mp4={start:()=>new Promise(async(e,t)=>{try{this.start_resolve=e;let n,r=0;for(;;){r+=1;try{n=await this.prFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(n?.status===200||r===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!n||n.status!==200)return t(`request is error.`);let i=n.body?.getReader();if(!i)return t(`reader is error.`);for(this.decoderWorker?.setFrameTrack(!1);;){let{done:e,value:t}=await i.read();if(t&&this.demuxerWorker?.push(t),e||this.url===``)break}}catch(e){e.name!==`AbortError`&&t(e)}})};dash={isLive:!1,segmentNumber:1,mpdInfo:null,getSegmentsTimer:0,fetchSegment:async e=>{let t=await this.prFetch.request(e);if(!t||t.status!==200)return!1;let n=t.body?.getReader();if(!n)return!1;for(;;){let{done:e,value:t}=await n.read();if(t&&this.demuxerWorker?.push(t),e||this.url===``)break}return!0},fetchByteRange:async(e,t,n)=>{let r,i=0;for(;;){i+=1;try{r=await fetch(e,{headers:{Range:`bytes=${t}-${n}`}})}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(r?.ok&&(r.status===200||r.status===206)||i===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!r?.ok||r.status!==200&&r.status!==206)return!1;let a=new Uint8Array(await r.arrayBuffer());return a.byteLength>0&&this.demuxerWorker?.push(a),a.byteLength>0},getMpd:async()=>{try{let e,t=0;for(;;){t+=1;try{e=await this.getSegmentsFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(e?.status===200||t===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!e||e.status!==200)throw Error(`request is error.`);let n=e.body?.getReader();if(!n)throw Error(`reader is error.`);let r=[];for(;;){let{done:e,value:t}=await n.read();if(t&&r.push(t),e||this.url===``)break}let i=r.reduce((e,t)=>e+t.byteLength,0),a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;let s=L(new TextDecoder(`utf-8`).decode(a),this.url);return this.dash.mpdInfo=s,this.dash.isLive=s.isLive,this.dash.isLive||(this.option.frameTrack=!1),s}catch(e){return e.name!==`AbortError`&&this.on.error&&this.on.error(e),null}},start:()=>new Promise(async(e,t)=>{try{this.start_resolve=e,this.dash.segmentNumber=1,this.dash.mpdInfo=null;let n=await this.dash.getMpd();if(!n)return t(`mpd parse is error.`);let r=n.adaptations.find(e=>e.kind===`video`||e.kind===`mux`)?.representation;if(r?.width&&r?.height){let e={width:r.width,height:r.height,duration:n.duration};this.on.demuxer.info&&this.on.demuxer.info(e)}let i=n.adaptations.find(e=>e.representation.segmentList);if(i?.representation.segmentList){let{segmentList:e,baseUrl:r}=i.representation,a=M(n.baseUrl,r||``);if(e.initRange){let{start:n,end:r}=e.initRange;if(!await this.dash.fetchByteRange(a,n,r))return t(`dash init segment fetch failed.`)}this.decoderWorker?.setFrameTrack(!1);for(let t of e.segments){if(this.url===``)break;await this.dash.fetchByteRange(a,t.start,t.end)}return}let a=[n.adaptations.find(e=>e.kind===`video`),n.adaptations.find(e=>e.kind===`audio`),n.adaptations.find(e=>e.kind===`mux`)].filter(e=>!!e);if(a.length===0)return t(`no adaptation in mpd.`);for(let e of a){let{id:t,bandwidth:r,template:i}=e.representation;if(!i?.initialization)continue;let a=P(n.baseUrl,i.initialization,{RepresentationID:t,Bandwidth:r,Number:this.dash.segmentNumber});await this.dash.fetchSegment(a)}for(this.dash.isLive?this.dash.getSegmentsTimer=window.setInterval(this.dash.getMpd,3e3):this.decoderWorker?.setFrameTrack(!1);;){let e=this.dash.mpdInfo;if(!e||this.url===``)break;let{baseUrl:t}=e,n=!1;for(let e of a){let{id:r,bandwidth:i,template:a}=e.representation;if(!a?.media)continue;let o=P(t,a.media,{RepresentationID:r,Bandwidth:i,Number:this.dash.segmentNumber});await this.dash.fetchSegment(o)&&(n=!0)}if(!n){if(this.dash.isLive){await new Promise(e=>setTimeout(()=>e(!0),300));continue}break}this.dash.segmentNumber+=1}}catch(e){e.name!==`AbortError`&&t(e)}})}},B=class{pendingPayloads=[];payload=new Uint8Array;chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);let t=this.pendingPayloads.shift();if(!t)return!1;let n=new Uint8Array(this.payload.byteLength+t.byteLength);return n.set(this.payload,0),n.set(t,this.payload.byteLength),this.payload=n,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};discardPayload=()=>{this.payload=new Uint8Array};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array,this.chunks=[]}},V=(e,t)=>e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),H=(e,t)=>{let n=V(e,t);return n&8388608&&(n|=-16777216),n},U=(e,t)=>t<<24|e,W=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],G=class{audioConfig;videoConfig;header;textDecoder=new TextDecoder(`utf-8`);on={};constructor(){}parse=async e=>{let t=0;for(this.header||(this.parseHeader(e,t),t+=9);this.isSurplusTag(e,t)!==!1;){let{tagType:n,dataSize:r,dts:i}=this.parseTagHeader(e,t+4);if(n){let a=this.parseTagBody(n,e,t+4+11,r);if(!a){t=t+4+11+r,await new Promise(e=>setTimeout(()=>e(!0),8));continue}switch(n){case`script`:this.on.info&&this.on.info(a);break;case`audio`:{let{accPacketType:e}=a;if(e===0){let{codec:e,sampleRate:t,channelConfiguration:n,data:r}=a;this.audioConfig={kind:`audio`,codec:e,sampleRate:t,numberOfChannels:n,...r?{description:r}:{}},this.on.config&&this.on.config(this.audioConfig)}else{let{cts:e,data:t}=a,n=e===void 0?void 0:e+i;this.on.chunk&&this.on.chunk({kind:`audio`,type:`key`,dts:i,pts:n,cts:e,data:t})}}break;case`video`:{let{avcPacketType:e}=a;if(e===0){let{codec:e,sps:t,pps:n,data:r}=a;this.videoConfig={kind:`video`,codec:e,description:r,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}else{let{frameType:e,cts:t,data:n,nalus:r}=a,o=e===1?`key`:`delta`,s=t===void 0?void 0:t+i;this.on.chunk&&this.on.chunk({kind:`video`,type:o,dts:i,pts:s,cts:t,data:n,nalus:r})}}break}t=t+4+11+r}await new Promise(e=>setTimeout(()=>e(!0),8))}return t};parseHeader=(e,t)=>{let n,r,i,a;n=e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),r=e.getUint8(t+3);{let n=e.getUint8(t+4);i={audio:!!(n&4),video:!!(n&1)}}a=e.getUint32(t+5),this.header={signature:n,version:r,flags:i,dataOffset:a}};isSurplusTag=(e,t)=>{let n=!0,r=e.byteLength;if(t+4>r)n=!1;else if(t+4+11>r)n=!1;else{let i=V(e,t+4+1);t+4+11+i>r&&(n=!1)}return n};parseTagHeader=(e,t)=>{let n,r,i,a,o;{let r=e.getUint8(t),i;switch(r){case 18:i=`script`;break;case 8:i=`audio`;break;case 9:i=`video`;break}n=i}r=V(e,t+1),i=V(e,t+4),a=e.getUint8(t+7),o=V(e,t+8);let s=U(i,a);return{tagType:n,dataSize:r,timestamp:i,timestampExtended:a,dts:s,streamID:o}};parseTagBody=(e,t,n,r)=>{let i;switch(e){case`script`:i=this.parseMetaData(t,n);break;case`audio`:i=this.parseAudio(t,n,r);break;case`video`:i=this.parseVideo(t,n,r);break}return i};parseMetaData=(e,t)=>{let n=t;if(e.getUint8(n)!==2)return null;n+=1;let r=e.getUint16(n,!1);n+=2;{let t=new Int8Array(e.buffer.slice(n,n+r)),i=this.textDecoder?.decode(t)||``;if(n+=r,i!==`onMetaData`)return{name:i}}let i=this.getAmfType(e,n);return n+=1,this.getAMFValue(e,n,i).value};parseAudio=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i>>2&3,s=i>>1&1,c=i&1;r+=1;let l=e.getUint8(r);r+=1;let u=n-(r-t);if(u<=0)return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:new Uint8Array};let d=new Uint8Array(e.buffer.slice(r,r+u));if(a===10&&l===0){let t=e.getUint8(r),n=e.getUint8(r+1),i=t>>3&31,u=(t&7)<<1|n>>7;return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d,samplingFrequencyIndex:u,channelConfiguration:n>>3&15,codec:`mp4a.40.${i}`,sampleRate:W[u]}}return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d}};parseVideo=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i&15;r+=1;let s=e.getUint8(r);r+=1;let c=H(e,r);r+=3;let l=n-5;if(l<0)return null;let u=new Uint8Array(e.buffer.slice(r,r+l));switch(o){case 7:if(s===0)return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u,...T(u)};if(s===1){let t=[],n=r+l;for(;!(r+4>n);){let i=e.getUint32(r,!1);if(i<=0||r+4+i>n)break;let a=new Uint8Array(e.buffer.slice(r,r+4+i));r+=4+i,t.push(a)}return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u,nalus:t}}break;default:return null}return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u}};getAmfType=(e,t)=>e.getUint8(t);getAMFName=(e,t,n)=>{let r=new Uint8Array(e.buffer.slice(t,t+n));return this.textDecoder?.decode(r)||``};getAMFValue=(e,t,n)=>{let r=t,i,a=0;switch(n){case 0:i=e.getFloat64(r,!1),a=8;break;case 1:i=!!e.getUint8(r),a=1;break;case 2:{i=``;let t=e.getUint16(r,!1);r+=2;let n=new Int8Array(e.buffer,r,t).filter(e=>e!==0);i=(this.textDecoder?.decode(n)||``).trim(),a=2+t}break;case 3:for(i={};r<e.byteLength;){let t=e.getUint16(r,!1);if(t===0)break;r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);if(o===6)break;r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}break;case 8:{i={};let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=e.getUint16(r,!1);r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}}break;case 10:{i=[];let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=this.getAmfType(e,r);r+=1;let n=this.getAMFValue(e,r,t);r+=n.length,i.push(n.value),a=1+n.length}}break}return{amfType:n,length:a,value:i}}},K=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],q=e=>{let t=`unknown`;switch(e){case 1:case 2:case 27:case 36:t=`video`;break;case 3:case 4:case 15:t=`audio`;break;case 6:t=`subtitle`;break;case 134:t=`ad`;break}return t},ee=class{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let t=0;for(;!(t+188>e.byteLength);){if(e.getInt8(t)!=71){t++;continue}await this.parsePacket(e,t),t+=188}return t};parsePacket=async(e,t)=>{if(t+188>e.byteLength||e.getUint8(t)!==71)throw Error(`Invalid TS packet`);let n=t,r=this.parseHeader(e,n);n+=4;let{transport_error_indicator:i,pid:a,payload_unit_start_indicator:o,adaptation_field_control:s}=r;if(i===1||a===void 0)return;let c=184;if(s===2||s===3){let t=e.getUint8(n);n+=1,t>0&&(this.parseAdaptationField(e,n),n+=t),c-=1+t}if(s===1||s===3){if(c<=0)return;let t=new Uint8Array(e.buffer.slice(n,n+c));if(a===0)return this.parsePAT(e,n);{let{programs:t=[]}=this.pat||{};if(t.find(e=>e.pmt_pid===a))return this.parsePMT(e,n)}let{streams:r=[]}=this.pmt||{},i=r.find(e=>e.elementary_pid===a);if(i){if(o===1){let e=this.payloadMap.get(a);if(e){switch(i.kind){case`audio`:{let t=await this.parseAudio(e);this.on.chunk&&this.on.chunk(t)}break;case`video`:{let t=await this.parseVideo(e);this.on.chunk&&this.on.chunk(t),await new Promise(e=>setTimeout(()=>e(!0),0))}break}this.payloadMap.delete(a)}}{this.payloadMap.has(a)||this.payloadMap.set(a,new Uint8Array);let e=this.payloadMap.get(a),n=new Uint8Array(e.byteLength+t.byteLength);n.set(e,0),n.set(t,e.byteLength),this.payloadMap.set(a,n)}}}};parseHeader=(e,t)=>{let n=t,r=e.getUint8(n),i=e.getUint8(n+1),a=e.getUint8(n+2),o=e.getUint8(n+3),s=(i&128)>>7;return s===1?{sync_byte:r,transport_error_indicator:s}:{sync_byte:r,transport_error_indicator:s,payload_unit_start_indicator:(i&64)>>6,transport_priority:(i&32)>>5,pid:(i&31)<<8|a,transport_scrambling_control:(o&192)>>6,adaptation_field_control:o>>4&3,continuity_counter:o&15}};parsePAT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==0)throw Error(`Invalid PAT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u}}let i=[];{let t=r.section_length-5-4,a=n+t;for(;n<a;){let t=e.getUint16(n),r=e.getUint16(n+2)&8191;n+=4,t!==0&&r>=32&&r<=8190&&i.push({program_number:t,pmt_pid:r})}}let a=e.getUint32(n);this.pat={header:r,programs:i,crc32:a}};parsePMT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==2)throw Error(`Invalid PMT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1;let d=e.getUint16(n)&8191;n+=2;let f=e.getUint16(n)&4095;n+=2,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u,pcr_pid:d,program_info_length:f}}n+=r.program_info_length;let i=[];{let t=r.section_length-9-4,a=n+t;for(;n<a;){let t=e.getUint8(n),r=q(t),a=e.getUint16(n+1)&8191,o=e.getUint16(n+3)&4095;if(n+=5+o,a<32||a>8190){console.warn(`Invalid elementary_pid: 0x${a.toString(16)}`);continue}i.push({kind:r,stream_type:t,elementary_pid:a,es_info_length:o})}}let a=e.getUint32(n);this.pmt={header:r,streams:i,crc32:a}};parseAdaptationField=(e,t)=>{let n=t,r,i,a,o,s=e.getUint8(n),c=!!(s&128),l=!!(s&64),u=!!(s&32),d=!!(s&16),f=!!(s&8),p=!!(s&4),m=!!(s&2),h=!!(s&1);n+=1;let g=(e,t)=>{let n=BigInt(0);n|=BigInt(e.getUint16(t))<<25n,n|=BigInt(e.getUint16(t+1))<<17n,n|=BigInt(e.getUint16(t+2))<<9n,n|=BigInt(e.getUint16(t+3))<<1n,n|=BigInt(e.getUint16(t+4)>>7);let r=(e.getUint16(t+4)&1)<<8|e.getUint16(t+5);return n=n*300n+BigInt(r),n};if(d&&(r=g(e,n),n+=6),f&&(i=g(e,n),n+=6),p&&(a=e.getInt8(n),n+=1),m){let t=e.getUint8(n);n+=1,o=new Uint8Array(e.buffer,n,t),n+=t}return{discontinuity_indicator:c,random_access_indicator:l,elementary_stream_priority_indicator:u,pcr_flag:d,opcr_flag:f,splicing_point_flag:p,transport_private_data_flag:m,adaptation_field_extension_flag:h,pcr:r,opcr:i,splice_countdown:a,transport_private_data:o}};parseAudio=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts audio payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{let e=this.parseAdts(i);!this.audioConfig&&e&&(this.audioConfig={kind:`audio`,codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.channelConfiguration},this.on.config&&this.on.config(this.audioConfig));let{dts:t=0,pts:n=0}=r;return{kind:`audio`,type:`key`,dts:t,pts:n,cts:n-t,data:e?i.slice(e.headerLength):i}}};parseAdts=e=>{if(e.length<7||e[0]!==255||(e[1]&240)!=240)return null;let t=e[1]&1?7:9;if(e.length<t)return null;let n=(e[2]>>6&3)+1,r=e[2]>>2&15,i=(e[2]&1)<<2|e[3]>>6,a=K[r]??44100;return{headerLength:t,codec:`mp4a.40.${n}`,sampleRate:a,channelConfiguration:i}};parseVideo=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts video payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{let e=this.getNalus(i);if(!this.videoConfig){let t,n;if(t=e.find(e=>e.type===7)?.nalu.slice(4),n=e.find(e=>e.type===8)?.nalu.slice(4),t&&n){let e=w(t,n),{codec:r}=T(e);this.videoConfig={kind:`video`,codec:r,description:e,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}}let t=[],n=`delta`;for(let r of e){let{type:e,nalu:i}=r;switch(e){case 6:case 9:t.push(i);break;case 1:n=`delta`,t.push(i);break;case 5:n=`key`,t.push(i);break}}let a=D(t),{dts:o=0,pts:s=0}=r,c=s-o;return{kind:`video`,type:n,dts:o,pts:s,cts:c,data:a,nalus:t}}};parsePtsDts(e,t){let n=e.getUint8(t),r=e.getUint8(t+1),i=e.getUint8(t+2),a=e.getUint8(t+3),o=e.getUint8(t+4),s=(BigInt(n)&14n)<<29n|(BigInt(r)&255n)<<22n|(BigInt(i)&254n)<<14n|(BigInt(a)&255n)<<7n|(BigInt(o)&254n)>>1n;return Number(s)/90}getNalus=e=>{let t=[],n=0;for(;n<e.byteLength-2;){let r=this.findAnnexBStart(e,n);if(!r)break;let i=e[r.naluOffset]&31,a=this.findAnnexBStart(e,r.nextSearchOffset),o=(a?a.startOffset:e.byteLength)-r.naluOffset;if(o>0){let n=e.slice(r.naluOffset,r.naluOffset+o);t.push({type:i,nalu:E(n)})}n=a?a.startOffset:e.byteLength}return t};findAnnexBStart=(e,t)=>{for(let n=t;n<e.length-2;n++)if(!(e[n]!==0||e[n+1]!==0)){if(e[n+2]===1)return{startOffset:n,naluOffset:n+3,nextSearchOffset:n+3};if(n+3<e.length&&e[n+2]===0&&e[n+3]===1)return{startOffset:n,naluOffset:n+4,nextSearchOffset:n+4}}return null}},J=(e,t)=>String.fromCharCode(e.getUint8(t),e.getUint8(t+1),e.getUint8(t+2),e.getUint8(t+3)),Y=(e,t,n)=>{if(t+8>n)return null;let r=e.getUint32(t,!1),i=J(e,t+4),a=8;if(r===1){if(t+16>n)return null;r=Number(e.getBigUint64(t+8,!1)),a=16}else r===0&&(r=n-t);return r<a||t+r>n?null:{offset:t,size:r,type:i,headerSize:a,contentStart:t+a}},X=(e,t,n,r)=>{let i=t;for(;i<n;){let t=Y(e,i,n);if(!t)break;r(t),i+=t.size}},Z=(e,t,n,r)=>{let i=null;return X(e,t,n,t=>{if(t.type===r)i=t;else if(t.type!==`mdat`){let n=Z(e,t.contentStart,t.offset+t.size,r);n&&(i=n)}}),i},Q=(e,t,n,r)=>{for(let i=t;i+8<=n;i++){if(J(e,i+4)!==r)continue;let t=Y(e,i,n);if(t?.type===r)return t}return null},$=(e,t,n,r,i=86)=>Q(e,t+i,n,r)||Q(e,t+8,n,r),te=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ne=(e,t)=>{let n=0,r=t;for(;r<e.length;){if(n=n<<7|e[r]&127,!(e[r]&128))return{len:n,next:r+1};r++}return{len:0,next:t}},re=class{audioConfig;videoConfig;tracks=new Map;mdatBox=null;progressiveParsed=!1;on={};getDiscardOffset=(e,t)=>this.progressiveParsed||Z(t,0,e,`moof`)||this.tracks.size>0&&!Z(t,0,e,`mdat`)?e:0;constructor(){}parse=async e=>{let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=t.byteLength,r=0;for(;r<n;){let i=Y(e,r,n);if(!i)return 0;switch(i.type){case`moov`:this.parseMoov(e,i),this.tryRunProgressive(e,t);break;case`moof`:this.parseMoof(e,i,t);break;case`mdat`:this.mdatBox=i,this.tryRunProgressive(e,t);break;case`sidx`:case`styp`:case`free`:case`skip`:case`ftyp`:break;default:break}r+=i.size,(i.type===`moov`||i.type===`moof`||i.type===`mdat`)&&await new Promise(e=>setTimeout(()=>e(!0),8))}return this.progressiveParsed?n:0};tryRunProgressive=(e,t)=>{if(this.progressiveParsed||this.tracks.size===0)return;let n=this.mdatBox??Z(e,0,t.byteLength,`mdat`),r=Z(e,0,t.byteLength,`moov`);!n||!r||this.isProgressiveReady(n,r,t.byteLength)&&(this.parseProgressive(e,n,t),this.progressiveParsed=!0)};isProgressiveReady=(e,t,n)=>e.offset+e.size<=n&&t.offset+t.size<=n;parseMoov=(e,t)=>{X(e,t.contentStart,t.offset+t.size,t=>{t.type===`trak`&&this.parseTrak(e,t)});let n=Z(e,t.contentStart,t.offset+t.size,`mvex`);n&&X(e,n.contentStart,n.offset+n.size,t=>{if(t.type!==`trex`)return;let n=e.getUint32(t.contentStart+4,!1),r=this.tracks.get(n);r&&(r.defaultSampleDuration=e.getUint32(t.contentStart+12,!1),r.defaultSampleSize=e.getUint32(t.contentStart+16,!1))});let r=Z(e,t.contentStart,t.offset+t.size,`mvhd`);if(r){let t=e.getUint8(r.contentStart),n=e.getUint32(r.contentStart+(t===1?20:12),!1),i=t===1?Number(e.getBigUint64(r.contentStart+24,!1)):e.getUint32(r.contentStart+16,!1);this.on.info?.({width:[...this.tracks.values()].find(e=>e.kind===`video`)?.width,height:[...this.tracks.values()].find(e=>e.kind===`video`)?.height,duration:n?i/n:void 0})}};readTkhdSize=(e,t)=>{let n=e.getUint8(t.contentStart),r=n===1?72:64,i=n===1?76:68;return{width:e.getUint32(t.contentStart+r,!1)>>16,height:e.getUint32(t.contentStart+i,!1)>>16}};readSampleEntrySize=(e,t)=>({width:e.getUint16(t+32,!1),height:e.getUint16(t+34,!1)});parseTrak=(e,t)=>{let n=Z(e,t.contentStart,t.offset+t.size,`tkhd`),r=Z(e,t.contentStart,t.offset+t.size,`mdia`);if(!n||!r)return;let i=e.getUint8(n.contentStart),a=e.getUint32(n.contentStart+(i===1?20:12),!1),{width:o,height:s}=this.readTkhdSize(e,n),c=Z(e,r.contentStart,r.offset+r.size,`hdlr`),l=Z(e,r.contentStart,r.offset+r.size,`mdhd`);if(!c||!l)return;let u=J(e,c.contentStart+8),d=u===`vide`?`video`:u===`soun`?`audio`:void 0;if(!d)return;let f=e.getUint8(l.contentStart),p=e.getUint32(l.contentStart+(f===1?20:12),!1);this.tracks.set(a,{kind:d,trackId:a,timescale:p,width:o,height:s});let m=Z(e,r.contentStart,r.offset+r.size,`minf`),h=m&&Z(e,m.contentStart,m.offset+m.size,`stbl`),g=h&&Z(e,h.contentStart,h.offset+h.size,`stsd`);if(!g)return;let _=g.contentStart+8,v=_+e.getUint32(_,!1),y=J(e,_+4);if(d===`video`&&(y===`avc1`||y===`avc3`)){let t=this.readSampleEntrySize(e,_);t.width&&t.height&&(o=t.width,s=t.height);let n=$(e,_,v,`avcC`,86);if(!n)return;let r=new Uint8Array(e.buffer,n.contentStart,n.size-n.headerSize),i=T(r),a=i.codec.replace(/^avc1\./,`${y}.`);this.videoConfig={kind:`video`,codec:a,description:r,sps:i.sps,pps:i.pps},this.on.config?.(this.videoConfig)}if(d===`video`){let e=this.tracks.get(a);e&&(e.width=o,e.height=s)}if(d===`audio`&&y===`mp4a`){let t=$(e,_,v,`esds`,36),n=t&&this.parseEsds(e,t);n&&(this.audioConfig=n,this.on.config?.(n))}};parseEsds=(e,t)=>{let n=new Uint8Array(e.buffer,t.contentStart,t.size-t.headerSize);for(let e=0;e<n.length-2;e++){if(n[e]!==5)continue;let{len:t,next:r}=ne(n,e+1);if(t<2||r+t>n.length)continue;let i=n.slice(r,r+t),a=i[0],o=i[1],s=a>>3&31,c=(a&7)<<1|o>>7,l=o>>3&15;return{kind:`audio`,codec:`mp4a.40.${s}`,sampleRate:te[c]??44100,numberOfChannels:l,description:i}}return null};findMdatForMoof=(e,t,n)=>{let r=t.offset+t.size;for(;r+8<=n;){let t=Y(e,r,n);if(!t||t.type===`moof`)break;if(t.type===`mdat`)return t;r+=t.size}return null};parseMoof=(e,t,n)=>{let r=this.findMdatForMoof(e,t,n.byteLength);r&&X(e,t.contentStart,t.offset+t.size,i=>{i.type===`traf`&&this.parseTraf(e,i,t.offset,r,n)})};ticksToMs=(e,t)=>e/t*1e3;readCttsOffsets=(e,t,n)=>{let r=new Int32Array(n);if(!t||n===0)return r;let i=e.getUint32(t.contentStart+4,!1),a=0,o=0,s=0,c=t.contentStart+8;for(let t=0;t<n;t++)o===0&&a<i&&(o=e.getUint32(c,!1),s=e.getInt32(c+4,!1),c+=8,a++),r[t]=s,--o;return r};parseTraf=(e,t,n,r,i)=>{let a=Z(e,t.contentStart,t.offset+t.size,`tfhd`),o=Z(e,t.contentStart,t.offset+t.size,`tfdt`),s=Z(e,t.contentStart,t.offset+t.size,`trun`);if(!a||!o||!s)return;let c=e.getUint32(a.contentStart+4,!1),l=this.tracks.get(c);if(!l)return;let u=e.getUint32(a.contentStart,!1)&16777215,d=(u&131072)!=0,f=a.contentStart+8,p=null,m=0,h=0;u&1&&(p=Number(e.getBigUint64(f,!1)),f+=8),u&2&&(f+=4),u&8&&(m=e.getUint32(f,!1),f+=4),u&16&&(h=e.getUint32(f,!1),f+=4),u&32&&(f+=4),u&8||(m=l.defaultSampleDuration??0),u&16||(h=l.defaultSampleSize??0);let g=e.getUint8(o.contentStart)===1?Number(e.getBigUint64(o.contentStart+4,!1)):e.getUint32(o.contentStart+4,!1),_=e.getUint32(s.contentStart,!1)&16777215,v=s.offset+s.size,y=s.contentStart+4;if(y+4>v)return;let b=e.getUint32(y,!1);if(y+=4,b===0||b>1e4)return;let x=0;if(_&1){if(y+4>v)return;x=e.getInt32(y,!1),y+=4}_&4&&(y+=4);let S;S=d?n:p===null?r.offset:p;let C=S+(_&1?x:0),w=g;for(let t=0;t<b;t++){let t=m,n=h,r=0;if(_&256){if(y+4>v)break;t=e.getUint32(y,!1),y+=4}if(_&512){if(y+4>v)break;n=e.getUint32(y,!1),y+=4}if(_&1024){if(y+4>v)break;r=e.getUint32(y,!1),y+=4}let a=0;if(_&2048){if(y+4>v)break;a=e.getInt32(y,!1),y+=4}if(t<=0&&l.kind===`audio`){let e=this.audioConfig?.sampleRate??l.timescale;t=Math.round(1024*l.timescale/e)}if(n<=0)continue;if(C+n>i.byteLength)break;let o=i.slice(C,C+n);C+=n;let s=this.ticksToMs(w,l.timescale),c=this.ticksToMs(w+a,l.timescale),u=c-s,d=l.kind!==`video`||!(r>>16&1)||this.isAvccKeyFrame(o)?`key`:`delta`;if(l.kind===`video`){let e=this.splitAvccNalus(o);this.on.chunk?.({kind:`video`,type:d,dts:s,pts:c,cts:u,data:o,nalus:e})}else this.on.chunk?.({kind:`audio`,type:`key`,dts:s,pts:c,cts:u,data:o});w+=t}};parseProgressive=(e,t,n)=>{let r=Z(e,0,n.byteLength,`moov`);if(!r)return;let i=[];X(e,r.contentStart,r.offset+r.size,t=>{if(t.type!==`trak`)return;let r=this.collectProgressiveTrackSamples(e,t,n);i.push(...r)}),i.sort((e,t)=>e.dts-t.dts||(e.kind===`video`?-1:1));for(let e of i)this.on.chunk?.(e)};collectProgressiveTrackSamples=(e,t,n)=>{let r=[],i=Z(e,t.contentStart,t.offset+t.size,`tkhd`),a=Z(e,t.contentStart,t.offset+t.size,`mdia`);if(!i||!a)return r;let o=e.getUint32(i.contentStart+(e.getUint8(i.contentStart)===1?20:12),!1),s=this.tracks.get(o);if(!s)return r;let c=Z(e,a.contentStart,a.offset+a.size,`minf`),l=c&&Z(e,c.contentStart,c.offset+c.size,`stbl`);if(!l)return r;let u=Z(e,l.contentStart,l.offset+l.size,`stsz`),d=Z(e,l.contentStart,l.offset+l.size,`stco`),f=Z(e,l.contentStart,l.offset+l.size,`co64`),p=Z(e,l.contentStart,l.offset+l.size,`stsc`),m=Z(e,l.contentStart,l.offset+l.size,`stts`),h=Z(e,l.contentStart,l.offset+l.size,`stss`),g=Z(e,l.contentStart,l.offset+l.size,`ctts`);if(!u||!d&&!f||!m)return r;let _=e.getUint32(u.contentStart+4,!1),v=e.getUint32(u.contentStart+8,!1),y=this.readCttsOffsets(e,g,v),b=d?e.getUint32(d.contentStart+4,!1):e.getUint32(f.contentStart+4,!1),x=t=>d?e.getUint32(d.contentStart+8+(t-1)*4,!1):Number(e.getBigUint64(f.contentStart+8+(t-1)*8,!1)),S=new Set;if(h){let t=e.getUint32(h.contentStart+4,!1);for(let n=0;n<t;n++)S.add(e.getUint32(h.contentStart+8+n*4,!1))}let C=[];if(p){let t=e.getUint32(p.contentStart+4,!1);for(let n=0;n<t;n++){let t=p.contentStart+8+n*12;C.push({firstChunk:e.getUint32(t,!1),samplesPerChunk:e.getUint32(t+4,!1)})}}let w=e=>{if(C.length===0)return v===b?1:Math.max(1,Math.ceil(v/b));let t=C[0].samplesPerChunk;for(let n of C)if(n.firstChunk<=e)t=n.samplesPerChunk;else break;return t},T=0,E=m.contentStart+8,D=e.getUint32(m.contentStart+4,!1),O=0,k=D>0?e.getUint32(E,!1):0,A=D>0?e.getUint32(E+4,!1):0;E+=8;let j=1;for(let t=1;t<=b&&j<=v;t++){let i=w(t),a=x(t);for(let t=0;t<i&&j<=v;t++,j++){let t=_===0?e.getUint32(u.contentStart+12+(j-1)*4,!1):_;if(a+t>n.byteLength)return r;let i=n.slice(a,a+t);a+=t;let o=this.ticksToMs(T,s.timescale),c=y[j-1]??0,l=this.ticksToMs(T+c,s.timescale),d=l-o,f=s.kind===`video`?this.isAvccKeyFrame(i)||S.has(j)||S.size===0:!0;s.kind===`video`?r.push({kind:`video`,type:f?`key`:`delta`,dts:o,pts:l,cts:d,data:i,nalus:this.splitAvccNalus(i)}):r.push({kind:`audio`,type:`key`,dts:o,pts:l,cts:d,data:i}),T+=A,--k,k===0&&O+1<D&&(O+=1,E=m.contentStart+8+O*8,k=e.getUint32(E,!1),A=e.getUint32(E+4,!1))}}return r};isAvccKeyFrame=e=>{let t=0,n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;t+4<=e.byteLength;){let r=n.getUint32(t,!1);if(r<=0||t+4+r>e.byteLength)break;if((e[t+4]&31)==5)return!0;t+=4+r}return!1};splitAvccNalus=e=>{let t=[],n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+4<=e.byteLength;){let i=r.getUint32(n,!1);if(i<=0||n+4+i>e.byteLength)break;t.push(e.slice(n,n+4+i)),n+=4+i}return t}},ie=class{pattern;cacher=new B;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case`flv`:this.parser=new G;break;case`hls`:this.parser=new ee;break;case`dash`:case`mp4`:this.parser=new re;break;default:throw Error(`is error pattern.`)}this.parser.on.info=e=>this.on.info&&this.on.info(e),this.parser.on.config=e=>this.on.config&&this.on.config(e),this.parser.on.chunk=e=>{this.cacher.pushChunk(e),this.on.chunk&&this.on.chunk(e)}};push=e=>{this.cacher.push(e),this.isParseing===!1&&this.parse()};destroy=()=>{this.cacher.destroy(),this.isParseing=!1,this.offset=0};parse=async()=>{try{if(this.isParseing=!0,!this.pattern)throw Error(`You need to set the pattern.`);if(!this.parser)throw Error(`You need to init parser.`);for(;;){let e=this.cacher.next(this.offset);if(this.offset=0,!e)break;try{let t=await this.parser.parse(e);if(this.pattern===`mp4`||this.pattern===`dash`){let t=this.parser;this.offset=t.getDiscardOffset(e.byteLength,e)}else this.offset=t}catch{this.cacher.discardPayload();continue}}this.isParseing=!1}catch{this.isParseing=!1,this.cacher.discardPayload()}}},ae=class{pattern=`flv`;audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;baseTime=0;pendingChunks=[];currentChunk;isProcessing=!1;decodeTimer=0;frameTrack=!1;isFrameTrack=!1;fameTrackOption={flv:[30,50],hls:[200,300],dash:[50,100],mp4:[30,50],rtmp:[50,100]};decodingSpeedRatio=1;maxDecodingSpeedRatio=2;decodingSpeed=16;fps=0;firstVideoChunkTimestamp;secondVideoChunkTimestamp;frameStartTime;lastRenderTime;nextRenderTime;on={audio:{},video:{}};constructor(){}init=e=>{this.destroy(),this.pattern=e,this.baseTime=new Date().getTime()-performance.now(),this.initDecodeInterval()};initAudio=async e=>{if(this.audio.destroy(),!(await AudioDecoder.isConfigSupported(e).catch(()=>({supported:!1}))).supported){console.warn(`[Decoder] audio config not supported:`,e.codec,`audio will be skipped`),this.audioDecoderConfig=void 0,this.audioDecoder=void 0;return}this.audioDecoderConfig={...e},this.audioDecoder=new AudioDecoder({output:e=>{let t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:e,playbackRate:t})},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:e=>{this.frameStartTime||=e.timestamp;try{let t=e.timestamp-this.frameStartTime+this.baseTime*1e3,n=new VideoFrame(e,{timestamp:t});if(e.close(),!n.displayWidth||!n.displayHeight){n.close();return}this.on.video.decode?.({timestamp:t,frame:n}),this.currentChunk?.kind===`video`&&this.currentChunk.nalus&&this.on.nalus?.(this.currentChunk.nalus)}catch{e.close()}},error:e=>{this.on.video.error&&this.on.video.error(e)}}),this.videoDecoder.configure(this.videoDecoderConfig)};setFrameTrack=e=>{this.frameTrack=e,this.frameTrack===!1&&(this.decodingSpeedRatio=1)};push=e=>{this.pendingChunks.push(e)};destroy=()=>{this.audio.destroy(),this.video.destroy(),this.pendingChunks=[],this.firstVideoChunkTimestamp=void 0,this.secondVideoChunkTimestamp=void 0,this.frameStartTime=void 0,this.lastRenderTime=void 0,this.nextRenderTime=void 0,clearInterval(this.decodeTimer)};initDecodeInterval=()=>{let e=this.decodingSpeed/this.decodingSpeedRatio,t=this.baseTime+performance.now();if(this.lastRenderTime||=t,this.fps=Math.round(1e3/(t-this.lastRenderTime)),this.lastRenderTime=t,this.nextRenderTime){let t=this.lastRenderTime-this.nextRenderTime;e-=t}this.nextRenderTime=this.lastRenderTime+e,this.decodeTimer=setTimeout(()=>{try{this.decode()}catch(e){console.error(`[Decoder] decode error:`,e)}this.initDecodeInterval()},e)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;this.currentChunk=this.pendingChunks.shift(),this.currentChunk;){let e=this.pendingChunks.length;if(this.frameTrack){let[t,n]=this.fameTrackOption[this.pattern];if(e<=t&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){let n=Math.min(1+(e-t)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(n.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){let{decodingSpeed:t,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:t,decodingSpeedRatio:n,fps:r,cacheLength:e})}let{kind:t,init:n}=this.currentChunk;switch(t){case`audio`:this.decodeAudio(n);break;case`video`:this.decodeVideo(n);break}if(t===`video`)break}this.isProcessing=!1}};decodeAudio=e=>{if(this.audioDecoder)try{let t=new EncodedAudioChunk(e);this.audioDecoder.decode(t)}catch(e){console.warn(`[Decoder] audio decode error (AudioDecoder may be unusable):`,e)}};decodeVideo=e=>{if(this.videoDecoder&&(e.type===`key`&&(this.hasKeyFrame=!0),this.firstVideoChunkTimestamp?this.secondVideoChunkTimestamp||(this.secondVideoChunkTimestamp=e.timestamp,this.decodingSpeed=(this.secondVideoChunkTimestamp-this.firstVideoChunkTimestamp)/1e3):this.firstVideoChunkTimestamp=e.timestamp,this.hasKeyFrame)){let t=new EncodedVideoChunk(e);this.videoDecoder.decode(t)}};audio={flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}},oe=class{renderMap=new Map;constructor(){}push=async e=>{let t=e.frame,n=t.timestamp;try{let e=[...this.renderMap.entries()].filter(([,e])=>e&&!e.pause);if(e.length===1&&e[0][0]==="default"&&e[0][1].writer){e[0][1].writer.write(t).catch(()=>{}),t.close();return}for(let[r,i]of e){let{writer:e,offscreen:a,option:o}=i;if(e){let i;if(r==="default"||!o)i=new VideoFrame(t,{timestamp:n});else{let{sx:e=0,sy:r=0,sw:a=t.displayWidth,sh:s=t.displayHeight}=o;i=new VideoFrame(t,{visibleRect:{x:e,y:r,width:a,height:s},displayWidth:a,displayHeight:s,timestamp:n})}e.write(i).catch(()=>{}),i.close()}else if(a)if(r==="default"||!o)a.width=t.displayWidth,a.height=t.displayHeight,a.getContext(`2d`)?.drawImage(t,0,0);else{let{sx:e=0,sy:n=0,sw:r=t.displayWidth,sh:i=t.displayHeight}=o;a.width=r,a.height=i,a.getContext(`2d`)?.drawImage(t,e,n,r,i,0,0,r,i)}}}catch{}t.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,option:i}={key:`default`,...e};if(n){let e=n.getWriter();this.renderMap.set(t,{writer:e,option:i,pause:!1})}else this.renderMap.set(t,{offscreen:r,option:i,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{let{key:t,cutOption:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,option:n})};setPause=e=>{let{key:t,pause:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,pause:n})};destroy=()=>{this.renderMap=new Map}};e.Decoder=ae,e.DecoderWorker=u,e.Demuxer=ie,e.DemuxerWorker=a,e.PrPlayer=z,e.Render=oe,e.RenderWorker=h,e.buildSegmentUrl=P,e.parseMpd=L,e.resolveUrl=M});
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`pr-player`]={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t="(function(){var e=class{pendingPayloads=[];payload=new Uint8Array;chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);let t=this.pendingPayloads.shift();if(!t)return!1;let n=new Uint8Array(this.payload.byteLength+t.byteLength);return n.set(this.payload,0),n.set(t,this.payload.byteLength),this.payload=n,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};discardPayload=()=>{this.payload=new Uint8Array};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array,this.chunks=[]}};let t=(e,t)=>{let n=new Uint8Array(e),r=new Uint8Array(t),i=new Uint8Array(11+n.length+r.length),a=0;return i[a++]=1,i[a++]=n[1],i[a++]=n[2],i[a++]=n[3],i[a++]=255,i[a++]=225,i[a++]=n.length>>8&255,i[a++]=n.length&255,i.set(n,a),a+=n.length,i[a++]=1,i[a++]=r.length>>8&255,i[a++]=r.length&255,i.set(r,a),i},n=e=>{let t=0,n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(t);if(t+=1,r!==1)throw Error(`Invalid AVC version`);let i=n.getUint8(t)&255;t+=1;let a=n.getUint8(t)&255;t+=1;let o=n.getUint8(t)&255;t+=1;let s=`avc1.${Array.from([i,a,o],e=>e.toString(16).padStart(2,`0`)).join(``)}`;t+=1,t+=1;let c=n.getUint16(t,!1);t+=2;let l=new Uint8Array(e.buffer,e.byteOffset+t,c);t+=c,t+=1;let u=n.getUint16(t,!1);return t+=2,{version:r,codec:s,profile:i,compatibility:a,level:o,sps:l,pps:new Uint8Array(e.buffer,e.byteOffset+t,u)}},r=e=>{let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t},i=e=>{let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n},a=(e,t)=>e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),o=(e,t)=>{let n=a(e,t);return n&8388608&&(n|=-16777216),n},s=(e,t)=>t<<24|e,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];var l=class{audioConfig;videoConfig;header;textDecoder=new TextDecoder(`utf-8`);on={};constructor(){}parse=async e=>{let t=0;for(this.header||(this.parseHeader(e,t),t+=9);this.isSurplusTag(e,t)!==!1;){let{tagType:n,dataSize:r,dts:i}=this.parseTagHeader(e,t+4);if(n){let a=this.parseTagBody(n,e,t+4+11,r);if(!a){t=t+4+11+r,await new Promise(e=>setTimeout(()=>e(!0),8));continue}switch(n){case`script`:this.on.info&&this.on.info(a);break;case`audio`:{let{accPacketType:e}=a;if(e===0){let{codec:e,sampleRate:t,channelConfiguration:n,data:r}=a;this.audioConfig={kind:`audio`,codec:e,sampleRate:t,numberOfChannels:n,...r?{description:r}:{}},this.on.config&&this.on.config(this.audioConfig)}else{let{cts:e,data:t}=a,n=e===void 0?void 0:e+i;this.on.chunk&&this.on.chunk({kind:`audio`,type:`key`,dts:i,pts:n,cts:e,data:t})}}break;case`video`:{let{avcPacketType:e}=a;if(e===0){let{codec:e,sps:t,pps:n,data:r}=a;this.videoConfig={kind:`video`,codec:e,description:r,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}else{let{frameType:e,cts:t,data:n,nalus:r}=a,o=e===1?`key`:`delta`,s=t===void 0?void 0:t+i;this.on.chunk&&this.on.chunk({kind:`video`,type:o,dts:i,pts:s,cts:t,data:n,nalus:r})}}break}t=t+4+11+r}await new Promise(e=>setTimeout(()=>e(!0),8))}return t};parseHeader=(e,t)=>{let n,r,i,a;n=e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),r=e.getUint8(t+3);{let n=e.getUint8(t+4);i={audio:!!(n&4),video:!!(n&1)}}a=e.getUint32(t+5),this.header={signature:n,version:r,flags:i,dataOffset:a}};isSurplusTag=(e,t)=>{let n=!0,r=e.byteLength;if(t+4>r)n=!1;else if(t+4+11>r)n=!1;else{let i=a(e,t+4+1);t+4+11+i>r&&(n=!1)}return n};parseTagHeader=(e,t)=>{let n,r,i,o,c;{let r=e.getUint8(t),i;switch(r){case 18:i=`script`;break;case 8:i=`audio`;break;case 9:i=`video`;break}n=i}r=a(e,t+1),i=a(e,t+4),o=e.getUint8(t+7),c=a(e,t+8);let l=s(i,o);return{tagType:n,dataSize:r,timestamp:i,timestampExtended:o,dts:l,streamID:c}};parseTagBody=(e,t,n,r)=>{let i;switch(e){case`script`:i=this.parseMetaData(t,n);break;case`audio`:i=this.parseAudio(t,n,r);break;case`video`:i=this.parseVideo(t,n,r);break}return i};parseMetaData=(e,t)=>{let n=t;if(e.getUint8(n)!==2)return null;n+=1;let r=e.getUint16(n,!1);n+=2;{let t=new Int8Array(e.buffer.slice(n,n+r)),i=this.textDecoder?.decode(t)||``;if(n+=r,i!==`onMetaData`)return{name:i}}let i=this.getAmfType(e,n);return n+=1,this.getAMFValue(e,n,i).value};parseAudio=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i>>2&3,s=i>>1&1,l=i&1;r+=1;let u=e.getUint8(r);r+=1;let d=n-(r-t);if(d<=0)return{soundFormat:a,soundRate:o,soundSize:s,soundType:l,accPacketType:u,data:new Uint8Array};let f=new Uint8Array(e.buffer.slice(r,r+d));if(a===10&&u===0){let t=e.getUint8(r),n=e.getUint8(r+1),i=t>>3&31,d=(t&7)<<1|n>>7;return{soundFormat:a,soundRate:o,soundSize:s,soundType:l,accPacketType:u,data:f,samplingFrequencyIndex:d,channelConfiguration:n>>3&15,codec:`mp4a.40.${i}`,sampleRate:c[d]}}return{soundFormat:a,soundRate:o,soundSize:s,soundType:l,accPacketType:u,data:f}};parseVideo=(e,t,r)=>{let i=t,a=e.getUint8(i),s=a>>4&15,c=a&15;i+=1;let l=e.getUint8(i);i+=1;let u=o(e,i);i+=3;let d=r-5;if(d<0)return null;let f=new Uint8Array(e.buffer.slice(i,i+d));switch(c){case 7:if(l===0)return{frameType:s,codecID:c,avcPacketType:l,cts:u,data:f,...n(f)};if(l===1){let t=[],n=i+d;for(;!(i+4>n);){let r=e.getUint32(i,!1);if(r<=0||i+4+r>n)break;let a=new Uint8Array(e.buffer.slice(i,i+4+r));i+=4+r,t.push(a)}return{frameType:s,codecID:c,avcPacketType:l,cts:u,data:f,nalus:t}}break;default:return null}return{frameType:s,codecID:c,avcPacketType:l,cts:u,data:f}};getAmfType=(e,t)=>e.getUint8(t);getAMFName=(e,t,n)=>{let r=new Uint8Array(e.buffer.slice(t,t+n));return this.textDecoder?.decode(r)||``};getAMFValue=(e,t,n)=>{let r=t,i,a=0;switch(n){case 0:i=e.getFloat64(r,!1),a=8;break;case 1:i=!!e.getUint8(r),a=1;break;case 2:{i=``;let t=e.getUint16(r,!1);r+=2;let n=new Int8Array(e.buffer,r,t).filter(e=>e!==0);i=(this.textDecoder?.decode(n)||``).trim(),a=2+t}break;case 3:for(i={};r<e.byteLength;){let t=e.getUint16(r,!1);if(t===0)break;r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);if(o===6)break;r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}break;case 8:{i={};let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=e.getUint16(r,!1);r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}}break;case 10:{i=[];let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=this.getAmfType(e,r);r+=1;let n=this.getAMFValue(e,r,t);r+=n.length,i.push(n.value),a=1+n.length}}break}return{amfType:n,length:a,value:i}}};let u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],d=e=>{let t=`unknown`;switch(e){case 1:case 2:case 27:case 36:t=`video`;break;case 3:case 4:case 15:t=`audio`;break;case 6:t=`subtitle`;break;case 134:t=`ad`;break}return t};var f=class{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let t=0;for(;!(t+188>e.byteLength);){if(e.getInt8(t)!=71){t++;continue}await this.parsePacket(e,t),t+=188}return t};parsePacket=async(e,t)=>{if(t+188>e.byteLength||e.getUint8(t)!==71)throw Error(`Invalid TS packet`);let n=t,r=this.parseHeader(e,n);n+=4;let{transport_error_indicator:i,pid:a,payload_unit_start_indicator:o,adaptation_field_control:s}=r;if(i===1||a===void 0)return;let c=184;if(s===2||s===3){let t=e.getUint8(n);n+=1,t>0&&(this.parseAdaptationField(e,n),n+=t),c-=1+t}if(s===1||s===3){if(c<=0)return;let t=new Uint8Array(e.buffer.slice(n,n+c));if(a===0)return this.parsePAT(e,n);{let{programs:t=[]}=this.pat||{};if(t.find(e=>e.pmt_pid===a))return this.parsePMT(e,n)}let{streams:r=[]}=this.pmt||{},i=r.find(e=>e.elementary_pid===a);if(i){if(o===1){let e=this.payloadMap.get(a);if(e){switch(i.kind){case`audio`:{let t=await this.parseAudio(e);this.on.chunk&&this.on.chunk(t)}break;case`video`:{let t=await this.parseVideo(e);this.on.chunk&&this.on.chunk(t),await new Promise(e=>setTimeout(()=>e(!0),0))}break}this.payloadMap.delete(a)}}{this.payloadMap.has(a)||this.payloadMap.set(a,new Uint8Array);let e=this.payloadMap.get(a),n=new Uint8Array(e.byteLength+t.byteLength);n.set(e,0),n.set(t,e.byteLength),this.payloadMap.set(a,n)}}}};parseHeader=(e,t)=>{let n=t,r=e.getUint8(n),i=e.getUint8(n+1),a=e.getUint8(n+2),o=e.getUint8(n+3),s=(i&128)>>7;return s===1?{sync_byte:r,transport_error_indicator:s}:{sync_byte:r,transport_error_indicator:s,payload_unit_start_indicator:(i&64)>>6,transport_priority:(i&32)>>5,pid:(i&31)<<8|a,transport_scrambling_control:(o&192)>>6,adaptation_field_control:o>>4&3,continuity_counter:o&15}};parsePAT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==0)throw Error(`Invalid PAT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u}}let i=[];{let t=r.section_length-5-4,a=n+t;for(;n<a;){let t=e.getUint16(n),r=e.getUint16(n+2)&8191;n+=4,t!==0&&r>=32&&r<=8190&&i.push({program_number:t,pmt_pid:r})}}let a=e.getUint32(n);this.pat={header:r,programs:i,crc32:a}};parsePMT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==2)throw Error(`Invalid PMT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1;let d=e.getUint16(n)&8191;n+=2;let f=e.getUint16(n)&4095;n+=2,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u,pcr_pid:d,program_info_length:f}}n+=r.program_info_length;let i=[];{let t=r.section_length-9-4,a=n+t;for(;n<a;){let t=e.getUint8(n),r=d(t),a=e.getUint16(n+1)&8191,o=e.getUint16(n+3)&4095;if(n+=5+o,a<32||a>8190){console.warn(`Invalid elementary_pid: 0x${a.toString(16)}`);continue}i.push({kind:r,stream_type:t,elementary_pid:a,es_info_length:o})}}let a=e.getUint32(n);this.pmt={header:r,streams:i,crc32:a}};parseAdaptationField=(e,t)=>{let n=t,r,i,a,o,s=e.getUint8(n),c=!!(s&128),l=!!(s&64),u=!!(s&32),d=!!(s&16),f=!!(s&8),p=!!(s&4),m=!!(s&2),h=!!(s&1);n+=1;let g=(e,t)=>{let n=BigInt(0);n|=BigInt(e.getUint16(t))<<25n,n|=BigInt(e.getUint16(t+1))<<17n,n|=BigInt(e.getUint16(t+2))<<9n,n|=BigInt(e.getUint16(t+3))<<1n,n|=BigInt(e.getUint16(t+4)>>7);let r=(e.getUint16(t+4)&1)<<8|e.getUint16(t+5);return n=n*300n+BigInt(r),n};if(d&&(r=g(e,n),n+=6),f&&(i=g(e,n),n+=6),p&&(a=e.getInt8(n),n+=1),m){let t=e.getUint8(n);n+=1,o=new Uint8Array(e.buffer,n,t),n+=t}return{discontinuity_indicator:c,random_access_indicator:l,elementary_stream_priority_indicator:u,pcr_flag:d,opcr_flag:f,splicing_point_flag:p,transport_private_data_flag:m,adaptation_field_extension_flag:h,pcr:r,opcr:i,splice_countdown:a,transport_private_data:o}};parseAudio=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts audio payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{let e=this.parseAdts(i);!this.audioConfig&&e&&(this.audioConfig={kind:`audio`,codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.channelConfiguration},this.on.config&&this.on.config(this.audioConfig));let{dts:t=0,pts:n=0}=r;return{kind:`audio`,type:`key`,dts:t,pts:n,cts:n-t,data:e?i.slice(e.headerLength):i}}};parseAdts=e=>{if(e.length<7||e[0]!==255||(e[1]&240)!=240)return null;let t=e[1]&1?7:9;if(e.length<t)return null;let n=(e[2]>>6&3)+1,r=e[2]>>2&15,i=(e[2]&1)<<2|e[3]>>6,a=u[r]??44100;return{headerLength:t,codec:`mp4a.40.${n}`,sampleRate:a,channelConfiguration:i}};parseVideo=async e=>{let r=new DataView(e.buffer),a=0,o,s;{let e=r.getUint8(a)===0&&r.getUint8(a+1)===0&&r.getUint8(a+2)===1;if(a+=3,!e)throw Error(`invalid ts video payload.`);let t=r.getUint8(a);a+=1;let n=r.getUint8(a)<<8|r.getUint8(a+1);a+=2;let i,s,c,l,u;{let e=r.getUint8(a);a+=1,i=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=r.getUint8(a);a+=1;let t=e>>6,n=r.getUint8(a);a+=1,(t&2)==2&&(d=this.parsePtsDts(r,a)),f=(t&1)==1?this.parsePtsDts(r,a+5):d,a+=n}o={stream_id:t,pes_packet_length:n,scrambling_control:i,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}s=e.slice(a);{let e=this.getNalus(s);if(!this.videoConfig){let r,i;if(r=e.find(e=>e.type===7)?.nalu.slice(4),i=e.find(e=>e.type===8)?.nalu.slice(4),r&&i){let e=t(r,i),{codec:a}=n(e);this.videoConfig={kind:`video`,codec:a,description:e,sps:r,pps:i},this.on.config&&this.on.config(this.videoConfig)}}let r=[],a=`delta`;for(let t of e){let{type:e,nalu:n}=t;switch(e){case 6:case 9:r.push(n);break;case 1:a=`delta`,r.push(n);break;case 5:a=`key`,r.push(n);break}}let c=i(r),{dts:l=0,pts:u=0}=o,d=u-l;return{kind:`video`,type:a,dts:l,pts:u,cts:d,data:c,nalus:r}}};parsePtsDts(e,t){let n=e.getUint8(t),r=e.getUint8(t+1),i=e.getUint8(t+2),a=e.getUint8(t+3),o=e.getUint8(t+4),s=(BigInt(n)&14n)<<29n|(BigInt(r)&255n)<<22n|(BigInt(i)&254n)<<14n|(BigInt(a)&255n)<<7n|(BigInt(o)&254n)>>1n;return Number(s)/90}getNalus=e=>{let t=[],n=0;for(;n<e.byteLength-2;){let i=this.findAnnexBStart(e,n);if(!i)break;let a=e[i.naluOffset]&31,o=this.findAnnexBStart(e,i.nextSearchOffset),s=(o?o.startOffset:e.byteLength)-i.naluOffset;if(s>0){let n=e.slice(i.naluOffset,i.naluOffset+s);t.push({type:a,nalu:r(n)})}n=o?o.startOffset:e.byteLength}return t};findAnnexBStart=(e,t)=>{for(let n=t;n<e.length-2;n++)if(!(e[n]!==0||e[n+1]!==0)){if(e[n+2]===1)return{startOffset:n,naluOffset:n+3,nextSearchOffset:n+3};if(n+3<e.length&&e[n+2]===0&&e[n+3]===1)return{startOffset:n,naluOffset:n+4,nextSearchOffset:n+4}}return null}};let p=(e,t)=>String.fromCharCode(e.getUint8(t),e.getUint8(t+1),e.getUint8(t+2),e.getUint8(t+3)),m=(e,t,n)=>{if(t+8>n)return null;let r=e.getUint32(t,!1),i=p(e,t+4),a=8;if(r===1){if(t+16>n)return null;r=Number(e.getBigUint64(t+8,!1)),a=16}else r===0&&(r=n-t);return r<a||t+r>n?null:{offset:t,size:r,type:i,headerSize:a,contentStart:t+a}},h=(e,t,n,r)=>{let i=t;for(;i<n;){let t=m(e,i,n);if(!t)break;r(t),i+=t.size}},g=(e,t,n,r)=>{let i=null;return h(e,t,n,t=>{if(t.type===r)i=t;else if(t.type!==`mdat`){let n=g(e,t.contentStart,t.offset+t.size,r);n&&(i=n)}}),i},_=(e,t,n,r)=>{for(let i=t;i+8<=n;i++){if(p(e,i+4)!==r)continue;let t=m(e,i,n);if(t?.type===r)return t}return null},v=(e,t,n,r,i=86)=>_(e,t+i,n,r)||_(e,t+8,n,r),y=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],b=(e,t)=>{let n=0,r=t;for(;r<e.length;){if(n=n<<7|e[r]&127,!(e[r]&128))return{len:n,next:r+1};r++}return{len:0,next:t}};var x=class{audioConfig;videoConfig;tracks=new Map;mdatBox=null;progressiveParsed=!1;on={};getDiscardOffset=(e,t)=>this.progressiveParsed||g(t,0,e,`moof`)||this.tracks.size>0&&!g(t,0,e,`mdat`)?e:0;constructor(){}parse=async e=>{let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=t.byteLength,r=0;for(;r<n;){let i=m(e,r,n);if(!i)return 0;switch(i.type){case`moov`:this.parseMoov(e,i),this.tryRunProgressive(e,t);break;case`moof`:this.parseMoof(e,i,t);break;case`mdat`:this.mdatBox=i,this.tryRunProgressive(e,t);break;case`sidx`:case`styp`:case`free`:case`skip`:case`ftyp`:break;default:break}r+=i.size,(i.type===`moov`||i.type===`moof`||i.type===`mdat`)&&await new Promise(e=>setTimeout(()=>e(!0),8))}return this.progressiveParsed?n:0};tryRunProgressive=(e,t)=>{if(this.progressiveParsed||this.tracks.size===0)return;let n=this.mdatBox??g(e,0,t.byteLength,`mdat`),r=g(e,0,t.byteLength,`moov`);!n||!r||this.isProgressiveReady(n,r,t.byteLength)&&(this.parseProgressive(e,n,t),this.progressiveParsed=!0)};isProgressiveReady=(e,t,n)=>e.offset+e.size<=n&&t.offset+t.size<=n;parseMoov=(e,t)=>{h(e,t.contentStart,t.offset+t.size,t=>{t.type===`trak`&&this.parseTrak(e,t)});let n=g(e,t.contentStart,t.offset+t.size,`mvex`);n&&h(e,n.contentStart,n.offset+n.size,t=>{if(t.type!==`trex`)return;let n=e.getUint32(t.contentStart+4,!1),r=this.tracks.get(n);r&&(r.defaultSampleDuration=e.getUint32(t.contentStart+12,!1),r.defaultSampleSize=e.getUint32(t.contentStart+16,!1))});let r=g(e,t.contentStart,t.offset+t.size,`mvhd`);if(r){let t=e.getUint8(r.contentStart),n=e.getUint32(r.contentStart+(t===1?20:12),!1),i=t===1?Number(e.getBigUint64(r.contentStart+24,!1)):e.getUint32(r.contentStart+16,!1);this.on.info?.({width:[...this.tracks.values()].find(e=>e.kind===`video`)?.width,height:[...this.tracks.values()].find(e=>e.kind===`video`)?.height,duration:n?i/n:void 0})}};readTkhdSize=(e,t)=>{let n=e.getUint8(t.contentStart),r=n===1?72:64,i=n===1?76:68;return{width:e.getUint32(t.contentStart+r,!1)>>16,height:e.getUint32(t.contentStart+i,!1)>>16}};readSampleEntrySize=(e,t)=>({width:e.getUint16(t+32,!1),height:e.getUint16(t+34,!1)});parseTrak=(e,t)=>{let r=g(e,t.contentStart,t.offset+t.size,`tkhd`),i=g(e,t.contentStart,t.offset+t.size,`mdia`);if(!r||!i)return;let a=e.getUint8(r.contentStart),o=e.getUint32(r.contentStart+(a===1?20:12),!1),{width:s,height:c}=this.readTkhdSize(e,r),l=g(e,i.contentStart,i.offset+i.size,`hdlr`),u=g(e,i.contentStart,i.offset+i.size,`mdhd`);if(!l||!u)return;let d=p(e,l.contentStart+8),f=d===`vide`?`video`:d===`soun`?`audio`:void 0;if(!f)return;let m=e.getUint8(u.contentStart),h=e.getUint32(u.contentStart+(m===1?20:12),!1);this.tracks.set(o,{kind:f,trackId:o,timescale:h,width:s,height:c});let _=g(e,i.contentStart,i.offset+i.size,`minf`),y=_&&g(e,_.contentStart,_.offset+_.size,`stbl`),b=y&&g(e,y.contentStart,y.offset+y.size,`stsd`);if(!b)return;let x=b.contentStart+8,S=x+e.getUint32(x,!1),C=p(e,x+4);if(f===`video`&&(C===`avc1`||C===`avc3`)){let t=this.readSampleEntrySize(e,x);t.width&&t.height&&(s=t.width,c=t.height);let r=v(e,x,S,`avcC`,86);if(!r)return;let i=new Uint8Array(e.buffer,r.contentStart,r.size-r.headerSize),a=n(i),o=a.codec.replace(/^avc1\\./,`${C}.`);this.videoConfig={kind:`video`,codec:o,description:i,sps:a.sps,pps:a.pps},this.on.config?.(this.videoConfig)}if(f===`video`){let e=this.tracks.get(o);e&&(e.width=s,e.height=c)}if(f===`audio`&&C===`mp4a`){let t=v(e,x,S,`esds`,36),n=t&&this.parseEsds(e,t);n&&(this.audioConfig=n,this.on.config?.(n))}};parseEsds=(e,t)=>{let n=new Uint8Array(e.buffer,t.contentStart,t.size-t.headerSize);for(let e=0;e<n.length-2;e++){if(n[e]!==5)continue;let{len:t,next:r}=b(n,e+1);if(t<2||r+t>n.length)continue;let i=n.slice(r,r+t),a=i[0],o=i[1],s=a>>3&31,c=(a&7)<<1|o>>7,l=o>>3&15;return{kind:`audio`,codec:`mp4a.40.${s}`,sampleRate:y[c]??44100,numberOfChannels:l,description:i}}return null};findMdatForMoof=(e,t,n)=>{let r=t.offset+t.size;for(;r+8<=n;){let t=m(e,r,n);if(!t||t.type===`moof`)break;if(t.type===`mdat`)return t;r+=t.size}return null};parseMoof=(e,t,n)=>{let r=this.findMdatForMoof(e,t,n.byteLength);r&&h(e,t.contentStart,t.offset+t.size,i=>{i.type===`traf`&&this.parseTraf(e,i,t.offset,r,n)})};ticksToMs=(e,t)=>e/t*1e3;readCttsOffsets=(e,t,n)=>{let r=new Int32Array(n);if(!t||n===0)return r;let i=e.getUint32(t.contentStart+4,!1),a=0,o=0,s=0,c=t.contentStart+8;for(let t=0;t<n;t++)o===0&&a<i&&(o=e.getUint32(c,!1),s=e.getInt32(c+4,!1),c+=8,a++),r[t]=s,--o;return r};parseTraf=(e,t,n,r,i)=>{let a=g(e,t.contentStart,t.offset+t.size,`tfhd`),o=g(e,t.contentStart,t.offset+t.size,`tfdt`),s=g(e,t.contentStart,t.offset+t.size,`trun`);if(!a||!o||!s)return;let c=e.getUint32(a.contentStart+4,!1),l=this.tracks.get(c);if(!l)return;let u=e.getUint32(a.contentStart,!1)&16777215,d=(u&131072)!=0,f=a.contentStart+8,p=null,m=0,h=0;u&1&&(p=Number(e.getBigUint64(f,!1)),f+=8),u&2&&(f+=4),u&8&&(m=e.getUint32(f,!1),f+=4),u&16&&(h=e.getUint32(f,!1),f+=4),u&32&&(f+=4),u&8||(m=l.defaultSampleDuration??0),u&16||(h=l.defaultSampleSize??0);let _=e.getUint8(o.contentStart)===1?Number(e.getBigUint64(o.contentStart+4,!1)):e.getUint32(o.contentStart+4,!1),v=e.getUint32(s.contentStart,!1)&16777215,y=s.offset+s.size,b=s.contentStart+4;if(b+4>y)return;let x=e.getUint32(b,!1);if(b+=4,x===0||x>1e4)return;let S=0;if(v&1){if(b+4>y)return;S=e.getInt32(b,!1),b+=4}v&4&&(b+=4);let C;C=d?n:p===null?r.offset:p;let w=C+(v&1?S:0),T=_;for(let t=0;t<x;t++){let t=m,n=h,r=0;if(v&256){if(b+4>y)break;t=e.getUint32(b,!1),b+=4}if(v&512){if(b+4>y)break;n=e.getUint32(b,!1),b+=4}if(v&1024){if(b+4>y)break;r=e.getUint32(b,!1),b+=4}let a=0;if(v&2048){if(b+4>y)break;a=e.getInt32(b,!1),b+=4}if(t<=0&&l.kind===`audio`){let e=this.audioConfig?.sampleRate??l.timescale;t=Math.round(1024*l.timescale/e)}if(n<=0)continue;if(w+n>i.byteLength)break;let o=i.slice(w,w+n);w+=n;let s=this.ticksToMs(T,l.timescale),c=this.ticksToMs(T+a,l.timescale),u=c-s,d=l.kind!==`video`||!(r>>16&1)||this.isAvccKeyFrame(o)?`key`:`delta`;if(l.kind===`video`){let e=this.splitAvccNalus(o);this.on.chunk?.({kind:`video`,type:d,dts:s,pts:c,cts:u,data:o,nalus:e})}else this.on.chunk?.({kind:`audio`,type:`key`,dts:s,pts:c,cts:u,data:o});T+=t}};parseProgressive=(e,t,n)=>{let r=g(e,0,n.byteLength,`moov`);if(!r)return;let i=[];h(e,r.contentStart,r.offset+r.size,t=>{if(t.type!==`trak`)return;let r=this.collectProgressiveTrackSamples(e,t,n);i.push(...r)}),i.sort((e,t)=>e.dts-t.dts||(e.kind===`video`?-1:1));for(let e of i)this.on.chunk?.(e)};collectProgressiveTrackSamples=(e,t,n)=>{let r=[],i=g(e,t.contentStart,t.offset+t.size,`tkhd`),a=g(e,t.contentStart,t.offset+t.size,`mdia`);if(!i||!a)return r;let o=e.getUint32(i.contentStart+(e.getUint8(i.contentStart)===1?20:12),!1),s=this.tracks.get(o);if(!s)return r;let c=g(e,a.contentStart,a.offset+a.size,`minf`),l=c&&g(e,c.contentStart,c.offset+c.size,`stbl`);if(!l)return r;let u=g(e,l.contentStart,l.offset+l.size,`stsz`),d=g(e,l.contentStart,l.offset+l.size,`stco`),f=g(e,l.contentStart,l.offset+l.size,`co64`),p=g(e,l.contentStart,l.offset+l.size,`stsc`),m=g(e,l.contentStart,l.offset+l.size,`stts`),h=g(e,l.contentStart,l.offset+l.size,`stss`),_=g(e,l.contentStart,l.offset+l.size,`ctts`);if(!u||!d&&!f||!m)return r;let v=e.getUint32(u.contentStart+4,!1),y=e.getUint32(u.contentStart+8,!1),b=this.readCttsOffsets(e,_,y),x=d?e.getUint32(d.contentStart+4,!1):e.getUint32(f.contentStart+4,!1),S=t=>d?e.getUint32(d.contentStart+8+(t-1)*4,!1):Number(e.getBigUint64(f.contentStart+8+(t-1)*8,!1)),C=new Set;if(h){let t=e.getUint32(h.contentStart+4,!1);for(let n=0;n<t;n++)C.add(e.getUint32(h.contentStart+8+n*4,!1))}let w=[];if(p){let t=e.getUint32(p.contentStart+4,!1);for(let n=0;n<t;n++){let t=p.contentStart+8+n*12;w.push({firstChunk:e.getUint32(t,!1),samplesPerChunk:e.getUint32(t+4,!1)})}}let T=e=>{if(w.length===0)return y===x?1:Math.max(1,Math.ceil(y/x));let t=w[0].samplesPerChunk;for(let n of w)if(n.firstChunk<=e)t=n.samplesPerChunk;else break;return t},E=0,D=m.contentStart+8,O=e.getUint32(m.contentStart+4,!1),k=0,A=O>0?e.getUint32(D,!1):0,j=O>0?e.getUint32(D+4,!1):0;D+=8;let M=1;for(let t=1;t<=x&&M<=y;t++){let i=T(t),a=S(t);for(let t=0;t<i&&M<=y;t++,M++){let t=v===0?e.getUint32(u.contentStart+12+(M-1)*4,!1):v;if(a+t>n.byteLength)return r;let i=n.slice(a,a+t);a+=t;let o=this.ticksToMs(E,s.timescale),c=b[M-1]??0,l=this.ticksToMs(E+c,s.timescale),d=l-o,f=s.kind===`video`?this.isAvccKeyFrame(i)||C.has(M)||C.size===0:!0;s.kind===`video`?r.push({kind:`video`,type:f?`key`:`delta`,dts:o,pts:l,cts:d,data:i,nalus:this.splitAvccNalus(i)}):r.push({kind:`audio`,type:`key`,dts:o,pts:l,cts:d,data:i}),E+=j,--A,A===0&&k+1<O&&(k+=1,D=m.contentStart+8+k*8,A=e.getUint32(D,!1),j=e.getUint32(D+4,!1))}}return r};isAvccKeyFrame=e=>{let t=0,n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;t+4<=e.byteLength;){let r=n.getUint32(t,!1);if(r<=0||t+4+r>e.byteLength)break;if((e[t+4]&31)==5)return!0;t+=4+r}return!1};splitAvccNalus=e=>{let t=[],n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+4<=e.byteLength;){let i=r.getUint32(n,!1);if(i<=0||n+4+i>e.byteLength)break;t.push(e.slice(n,n+4+i)),n+=4+i}return t}};let S=new class{pattern;cacher=new e;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case`flv`:this.parser=new l;break;case`hls`:this.parser=new f;break;case`dash`:case`mp4`:this.parser=new x;break;default:throw Error(`is error pattern.`)}this.parser.on.info=e=>this.on.info&&this.on.info(e),this.parser.on.config=e=>this.on.config&&this.on.config(e),this.parser.on.chunk=e=>{this.cacher.pushChunk(e),this.on.chunk&&this.on.chunk(e)}};push=e=>{this.cacher.push(e),this.isParseing===!1&&this.parse()};destroy=()=>{this.cacher.destroy(),this.isParseing=!1,this.offset=0};parse=async()=>{try{if(this.isParseing=!0,!this.pattern)throw Error(`You need to set the pattern.`);if(!this.parser)throw Error(`You need to init parser.`);for(;;){let e=this.cacher.next(this.offset);if(this.offset=0,!e)break;try{let t=await this.parser.parse(e);if(this.pattern===`mp4`||this.pattern===`dash`){let t=this.parser;this.offset=t.getDiscardOffset(e.byteLength,e)}else this.offset=t}catch{this.cacher.discardPayload();continue}}this.isParseing=!1}catch{this.isParseing=!1,this.cacher.discardPayload()}}};S.on.info=e=>postMessage({action:`on.info`,data:e}),S.on.config=e=>postMessage({action:`on.config`,data:e}),S.on.chunk=e=>postMessage({action:`on.chunk`,data:e}),onmessage=e=>{let{action:t,data:n}=e.data,r=S[t];r&&r(n)}})();",n=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,t],{type:`text/javascript;charset=utf-8`});function r(e){let r;try{if(r=n&&(self.URL||self.webkitURL).createObjectURL(n),!r)throw``;let t=new Worker(r,{name:e?.name});return t.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(r)}),t}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(t),{name:e?.name})}}var i=`pr-player-demuxer`,a=class{worker=new r({name:i});on={};constructor(){this.worker.onmessage=e=>{let{action:t,data:n}=e.data;switch(t){case`on.info`:this.on.info&&this.on.info(n);break;case`on.config`:this.on.config&&this.on.config(n);break;case`on.chunk`:this.on.chunk&&this.on.chunk(n);break}}}init=e=>this.worker.postMessage({action:`init`,data:e});push=e=>this.worker.postMessage({action:`push`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`,data:{}}),this.worker.terminate()}},o="(function(){let e=new class{pattern=`flv`;audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;baseTime=0;pendingChunks=[];currentChunk;isProcessing=!1;decodeTimer=0;frameTrack=!1;isFrameTrack=!1;fameTrackOption={flv:[30,50],hls:[200,300],dash:[50,100],mp4:[30,50],rtmp:[50,100]};decodingSpeedRatio=1;maxDecodingSpeedRatio=2;decodingSpeed=16;fps=0;firstVideoChunkTimestamp;secondVideoChunkTimestamp;frameStartTime;lastRenderTime;nextRenderTime;on={audio:{},video:{}};constructor(){}init=e=>{this.destroy(),this.pattern=e,this.baseTime=new Date().getTime()-performance.now(),this.initDecodeInterval()};initAudio=async e=>{if(this.audio.destroy(),!(await AudioDecoder.isConfigSupported(e).catch(()=>({supported:!1}))).supported){console.warn(`[Decoder] audio config not supported:`,e.codec,`audio will be skipped`),this.audioDecoderConfig=void 0,this.audioDecoder=void 0;return}this.audioDecoderConfig={...e},this.audioDecoder=new AudioDecoder({output:e=>{let t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:e,playbackRate:t})},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:e=>{this.frameStartTime||=e.timestamp;try{let t=e.timestamp-this.frameStartTime+this.baseTime*1e3,n=new VideoFrame(e,{timestamp:t});if(e.close(),!n.displayWidth||!n.displayHeight){n.close();return}this.on.video.decode?.({timestamp:t,frame:n}),this.currentChunk?.kind===`video`&&this.currentChunk.nalus&&this.on.nalus?.(this.currentChunk.nalus)}catch{e.close()}},error:e=>{this.on.video.error&&this.on.video.error(e)}}),this.videoDecoder.configure(this.videoDecoderConfig)};setFrameTrack=e=>{this.frameTrack=e,this.frameTrack===!1&&(this.decodingSpeedRatio=1)};push=e=>{this.pendingChunks.push(e)};destroy=()=>{this.audio.destroy(),this.video.destroy(),this.pendingChunks=[],this.firstVideoChunkTimestamp=void 0,this.secondVideoChunkTimestamp=void 0,this.frameStartTime=void 0,this.lastRenderTime=void 0,this.nextRenderTime=void 0,clearInterval(this.decodeTimer)};initDecodeInterval=()=>{let e=this.decodingSpeed/this.decodingSpeedRatio,t=this.baseTime+performance.now();if(this.lastRenderTime||=t,this.fps=Math.round(1e3/(t-this.lastRenderTime)),this.lastRenderTime=t,this.nextRenderTime){let t=this.lastRenderTime-this.nextRenderTime;e-=t}this.nextRenderTime=this.lastRenderTime+e,this.decodeTimer=setTimeout(()=>{try{this.decode()}catch(e){console.error(`[Decoder] decode error:`,e)}this.initDecodeInterval()},e)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;this.currentChunk=this.pendingChunks.shift(),this.currentChunk;){let e=this.pendingChunks.length;if(this.frameTrack){let[t,n]=this.fameTrackOption[this.pattern];if(e<=t&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){let n=Math.min(1+(e-t)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(n.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){let{decodingSpeed:t,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:t,decodingSpeedRatio:n,fps:r,cacheLength:e})}let{kind:t,init:n}=this.currentChunk;switch(t){case`audio`:this.decodeAudio(n);break;case`video`:this.decodeVideo(n);break}if(t===`video`)break}this.isProcessing=!1}};decodeAudio=e=>{if(this.audioDecoder)try{let t=new EncodedAudioChunk(e);this.audioDecoder.decode(t)}catch(e){console.warn(`[Decoder] audio decode error (AudioDecoder may be unusable):`,e)}};decodeVideo=e=>{if(this.videoDecoder&&(e.type===`key`&&(this.hasKeyFrame=!0),this.firstVideoChunkTimestamp?this.secondVideoChunkTimestamp||(this.secondVideoChunkTimestamp=e.timestamp,this.decodingSpeed=(this.secondVideoChunkTimestamp-this.firstVideoChunkTimestamp)/1e3):this.firstVideoChunkTimestamp=e.timestamp,this.hasKeyFrame)){let t=new EncodedVideoChunk(e);this.videoDecoder.decode(t)}};audio={flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}};e.on.audio.decode=e=>postMessage({action:`on.audio.decode`,data:e},[e.audioData]),e.on.audio.error=e=>postMessage({action:`on.audio.error`,data:e}),e.on.video.decode=e=>postMessage({action:`on.video.decode`,data:e},[e.frame]),e.on.video.error=e=>postMessage({action:`on.video.error`,data:e}),e.on.nalus=e=>postMessage({action:`on.nalus`,data:e}),e.on.analysis=e=>postMessage({action:`on.analysis`,data:e}),onmessage=t=>{let{action:n,data:r}=t.data,i=e[n];i&&i(r)}})();",s=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,o],{type:`text/javascript;charset=utf-8`});function c(e){let t;try{if(t=s&&(self.URL||self.webkitURL).createObjectURL(s),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(o),{name:e?.name})}}var l=`pr-player-decoder`,u=class{worker=new c({name:l});on={audio:{},video:{}};constructor(){this.worker.onmessage=e=>{let{action:t,data:n}=e.data;switch(t){case`on.audio.decode`:this.on.audio.decode&&this.on.audio.decode(n);break;case`on.audio.error`:this.on.audio.error&&this.on.audio.error(n);break;case`on.video.decode`:this.on.video.decode&&this.on.video.decode(n);break;case`on.video.error`:this.on.video.error&&this.on.video.error(n);break;case`on.nalus`:this.on.nalus&&this.on.nalus(n);break;case`on.analysis`:this.on.analysis&&this.on.analysis(n);break}}}init=e=>this.worker.postMessage({action:`init`,data:e});initAudio=e=>this.worker.postMessage({action:`initAudio`,data:e});initVideo=e=>this.worker.postMessage({action:`initVideo`,data:e});push=e=>this.worker.postMessage({action:`push`,data:e});setFrameTrack=e=>this.worker.postMessage({action:`setFrameTrack`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`}),this.worker.terminate()}},d='(function(){let e=new class{renderMap=new Map;constructor(){}push=async e=>{let t=e.frame,n=t.timestamp;try{let e=[...this.renderMap.entries()].filter(([,e])=>e&&!e.pause);if(e.length===1&&e[0][0]==="default"&&e[0][1].writer){e[0][1].writer.write(t).catch(()=>{}),t.close();return}for(let[r,i]of e){let{writer:e,offscreen:a,option:o}=i;if(e){let i;if(r==="default"||!o)i=new VideoFrame(t,{timestamp:n});else{let{sx:e=0,sy:r=0,sw:a=t.displayWidth,sh:s=t.displayHeight}=o;i=new VideoFrame(t,{visibleRect:{x:e,y:r,width:a,height:s},displayWidth:a,displayHeight:s,timestamp:n})}e.write(i).catch(()=>{}),i.close()}else if(a)if(r==="default"||!o)a.width=t.displayWidth,a.height=t.displayHeight,a.getContext(`2d`)?.drawImage(t,0,0);else{let{sx:e=0,sy:n=0,sw:r=t.displayWidth,sh:i=t.displayHeight}=o;a.width=r,a.height=i,a.getContext(`2d`)?.drawImage(t,e,n,r,i,0,0,r,i)}}}catch{}t.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,cutOption:i}={key:`default`,...e},a=this._getSafeSize(i);if(n){let e=n.getWriter();this.renderMap.set(t,{writer:e,option:a,pause:!1})}else this.renderMap.set(t,{offscreen:r,option:a,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{let{key:t,cutOption:n}={key:`default`,...e},r=this.renderMap.get(t);if(r){let e=this._getSafeSize(n);this.renderMap.set(t,{...r,option:e})}};setPause=e=>{let{key:t,pause:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,pause:n})};_getSafeSize=e=>{let t={...e};return t.sx%2!=0&&(t.sx+=1),t.sy%2!=0&&(t.sy+=1),t.sw%2!=0&&--t.sw,t.sh%2!=0&&--t.sh,t};destroy=()=>{this.renderMap=new Map}};onmessage=t=>{let{action:n,data:r}=t.data,i=e[n];i&&i(r)}})();',f=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,d],{type:`text/javascript;charset=utf-8`});function p(e){let t;try{if(t=f&&(self.URL||self.webkitURL).createObjectURL(f),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(d),{name:e?.name})}}var m=`pr-player-render`,h=class{worker=new p({name:m});constructor(){}push=e=>this.worker.postMessage({action:`push`,data:e},[e.frame]);addCut=e=>{let t=[];e.writable&&t.push(e.writable),e.offscreen&&t.push(e.offscreen),this.worker.postMessage({action:`addCut`,data:e},t)};delCut=e=>this.worker.postMessage({action:`delCut`,data:e});setCut=e=>this.worker.postMessage({action:`setCut`,data:e});setPause=e=>this.worker.postMessage({action:`setPause`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`,data:{}}),this.worker.terminate()}},g=`data:text/javascript;base64,LyoqDQogKiDpnZnpn7Pml7bvvJrlnKjpopHln5/ku4Xkv53nlZkgYmluIDDvvZ4077yI6ZqP5py677yJ77yM5YW25L2Z5Li6IDDvvIzlho3lkIjmiJDml7bln5/lhpnlhaXovpPlh7og4oCUIOWNs+S/ruaUueecn+WuniBQQ03vvIznu48gQW5hbHlzZXIoZmZ0U2l6ZT01MTIpIOaXtuWJjSA1IOS4qiBiaW4g5pyJ6IO96YeP44CB5YW25L2Z5o6l6L+RIDDjgIINCiAqIFBFUklPRCDpobvkuI4gUHJBdWRpb1N0cmVhbSDkuK0gYW5hbHlzZXJOb2RlLmZmdFNpemUg5LiA6Ie044CCDQogKi8NCmNsYXNzIE5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3NvciBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3NvciB7DQogIGlzRGVzdHJveSA9IGZhbHNlDQogIGRlYnVnID0gZmFsc2UNCg0KICBzdGF0aWMgU0lMRU5DRV9FUFMgPSAxZS0xNQ0KDQogIC8qKiDkuI4gc3JjL1ByQXVkaW9TdHJlYW0udHMg6YeMIGFuYWx5c2VyTm9kZS5mZnRTaXplIOS/neaMgeS4gOiHtCAqLw0KICBzdGF0aWMgUEVSSU9EID0gNTEyDQoNCiAgLyoqIGJpbiAw772eNCDpmo/mnLrlpI3mlbDvvIjlrp7pg6gv6Jma6YOo77yJ55qE5aSn6Ie05bmF5bqm5bC65bqm77yM5Y+v5oyJ5ZCs5oSfL+e8lueggeWGjeiwgyAqLw0KICBzdGF0aWMgQklOX1NDQUxFID0gMC4wMg0KDQogIGNvbnN0cnVjdG9yKCkgew0KICAgIHN1cGVyKCkNCiAgICB0aGlzLl9zaWxlbnRQY20gPSBuZXcgRmxvYXQzMkFycmF5KE5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5QRVJJT0QpDQogICAgdGhpcy5fc2lsZW50T2ZmID0gTm90RW1wdHlGaWx0ZXJXb3JrbGV0UHJvY2Vzc29yLlBFUklPRA0KICB9DQoNCiAgc3RhdGljIGFsbElucHV0c1NpbGVudChpbnB1dHMpIHsNCiAgICBjb25zdCBlcHMgPSBOb3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuU0lMRU5DRV9FUFMNCiAgICBmb3IgKGxldCBuaSA9IDA7IG5pIDwgaW5wdXRzLmxlbmd0aDsgbmkrKykgew0KICAgICAgY29uc3QgaW5wdXQgPSBpbnB1dHNbbmldDQogICAgICBpZiAoIWlucHV0KSBjb250aW51ZQ0KICAgICAgZm9yIChsZXQgY2ggPSAwOyBjaCA8IGlucHV0Lmxlbmd0aDsgY2grKykgew0KICAgICAgICBjb25zdCBjaGFubmVsID0gaW5wdXRbY2hdDQogICAgICAgIGlmICghY2hhbm5lbCkgY29udGludWUNCiAgICAgICAgY29uc3QgbiA9IGNoYW5uZWwubGVuZ3RoDQogICAgICAgIGZvciAobGV0IGkgPSAwOyBpIDwgbjsgaSsrKSB7DQogICAgICAgICAgaWYgKE1hdGguYWJzKGNoYW5uZWxbaV0pID49IGVwcykgcmV0dXJuIGZhbHNlDQogICAgICAgIH0NCiAgICAgIH0NCiAgICB9DQogICAgcmV0dXJuIHRydWUNCiAgfQ0KDQogIC8qKg0KICAgKiDku4UgYmluIDAuLjQg6Z2e6Zu277yI6ZqP5py677yJ77yM5ruh6Laz5a6e5L+h5Y+3IElERlTvvIzlhpnlhaUgdGhpcy5fc2lsZW50UGNtDQogICAqLw0KICByZWZpbGxTaWxlbnRQY21Gcm9tRml2ZUJpbnMoKSB7DQogICAgY29uc3QgTiA9IE5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5QRVJJT0QNCiAgICBjb25zdCBzY2FsZSA9IE5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5CSU5fU0NBTEUNCiAgICBjb25zdCByZSA9IG5ldyBGbG9hdDY0QXJyYXkoNSkNCiAgICBjb25zdCBpbSA9IG5ldyBGbG9hdDY0QXJyYXkoNSkNCiAgICByZVswXSA9IChNYXRoLnJhbmRvbSgpICogMiAtIDEpICogc2NhbGUNCiAgICBpbVswXSA9IDANCiAgICBmb3IgKGxldCBrID0gMTsgayA8PSA0OyBrKyspIHsNCiAgICAgIHJlW2tdID0gKE1hdGgucmFuZG9tKCkgKiAyIC0gMSkgKiBzY2FsZQ0KICAgICAgaW1ba10gPSAoTWF0aC5yYW5kb20oKSAqIDIgLSAxKSAqIHNjYWxlDQogICAgfQ0KICAgIGNvbnN0IGludk4gPSAxIC8gTg0KICAgIGNvbnN0IHR3b1BpT3Zlck4gPSAoMiAqIE1hdGguUEkpIC8gTg0KICAgIGZvciAobGV0IG4gPSAwOyBuIDwgTjsgbisrKSB7DQogICAgICBsZXQgcyA9IHJlWzBdDQogICAgICBmb3IgKGxldCBrID0gMTsgayA8PSA0OyBrKyspIHsNCiAgICAgICAgY29uc3QgYW5nID0gdHdvUGlPdmVyTiAqIGsgKiBuDQogICAgICAgIHMgKz0gMiAqIChyZVtrXSAqIE1hdGguY29zKGFuZykgLSBpbVtrXSAqIE1hdGguc2luKGFuZykpDQogICAgICB9DQogICAgICB0aGlzLl9zaWxlbnRQY21bbl0gPSBzICogaW52Tg0KICAgIH0NCiAgICB0aGlzLl9zaWxlbnRPZmYgPSAwDQogIH0NCg0KICBmaWxsT3V0cHV0c1NwYXJzZUZpdmVCaW5zKG91dHB1dHMpIHsNCiAgICBjb25zdCBmaXJzdCA9IG91dHB1dHNbMF0NCiAgICBpZiAoIWZpcnN0IHx8ICFmaXJzdFswXSkgcmV0dXJuDQogICAgY29uc3QgZnJhbWVMZW4gPSBmaXJzdFswXS5sZW5ndGgNCg0KICAgIGZvciAobGV0IGkgPSAwOyBpIDwgZnJhbWVMZW47IGkrKykgew0KICAgICAgaWYgKHRoaXMuX3NpbGVudE9mZiA+PSBOb3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuUEVSSU9EKSB7DQogICAgICAgIHRoaXMucmVmaWxsU2lsZW50UGNtRnJvbUZpdmVCaW5zKCkNCiAgICAgIH0NCiAgICAgIGNvbnN0IHYgPSB0aGlzLl9zaWxlbnRQY21bdGhpcy5fc2lsZW50T2ZmKytdDQogICAgICBmb3IgKGxldCBubyA9IDA7IG5vIDwgb3V0cHV0cy5sZW5ndGg7IG5vKyspIHsNCiAgICAgICAgY29uc3Qgb3V0UG9ydHMgPSBvdXRwdXRzW25vXQ0KICAgICAgICBpZiAoIW91dFBvcnRzKSBjb250aW51ZQ0KICAgICAgICBmb3IgKGxldCBjaCA9IDA7IGNoIDwgb3V0UG9ydHMubGVuZ3RoOyBjaCsrKSB7DQogICAgICAgICAgY29uc3QgY2hhbm5lbCA9IG91dFBvcnRzW2NoXQ0KICAgICAgICAgIGlmIChjaGFubmVsKSBjaGFubmVsW2ldID0gdg0KICAgICAgICB9DQogICAgICB9DQogICAgfQ0KICB9DQoNCiAgc3RhdGljIGNvcHlJbnB1dHNUb091dHB1dHMoaW5wdXRzLCBvdXRwdXRzKSB7DQogICAgZm9yIChsZXQgbm8gPSAwOyBubyA8IG91dHB1dHMubGVuZ3RoOyBubysrKSB7DQogICAgICBjb25zdCBvdXRQb3J0cyA9IG91dHB1dHNbbm9dDQogICAgICBjb25zdCBpblBvcnRzID0gaW5wdXRzW25vXQ0KICAgICAgaWYgKCFvdXRQb3J0cykgY29udGludWUNCiAgICAgIGZvciAobGV0IGNoID0gMDsgY2ggPCBvdXRQb3J0cy5sZW5ndGg7IGNoKyspIHsNCiAgICAgICAgY29uc3Qgb3V0Q2ggPSBvdXRQb3J0c1tjaF0NCiAgICAgICAgaWYgKCFvdXRDaCkgY29udGludWUNCiAgICAgICAgY29uc3QgaW5DaCA9IGluUG9ydHMgJiYgaW5Qb3J0c1tjaF0NCiAgICAgICAgaWYgKGluQ2ggJiYgaW5DaC5sZW5ndGggPT09IG91dENoLmxlbmd0aCkgew0KICAgICAgICAgIG91dENoLnNldChpbkNoKQ0KICAgICAgICB9IGVsc2UgaWYgKGluQ2gpIHsNCiAgICAgICAgICBjb25zdCBuID0gTWF0aC5taW4oaW5DaC5sZW5ndGgsIG91dENoLmxlbmd0aCkNCiAgICAgICAgICBmb3IgKGxldCBpID0gMDsgaSA8IG47IGkrKykgb3V0Q2hbaV0gPSBpbkNoW2ldDQogICAgICAgICAgZm9yIChsZXQgaSA9IG47IGkgPCBvdXRDaC5sZW5ndGg7IGkrKykgb3V0Q2hbaV0gPSAwDQogICAgICAgIH0gZWxzZSB7DQogICAgICAgICAgb3V0Q2guZmlsbCgwKQ0KICAgICAgICB9DQogICAgICB9DQogICAgfQ0KICB9DQoNCiAgcHJvY2VzcyhpbnB1dHMsIG91dHB1dHMpIHsNCiAgICBpZiAodGhpcy5pc0Rlc3Ryb3kpIHJldHVybiBmYWxzZQ0KDQogICAgaWYgKHRoaXMuZGVidWcpIHsNCiAgICAgIGNvbnNvbGUubG9nKCdceDFiWzM4OzI7MDsxNTE7MjU1bSVjJXNceDFiWzBtJywgJ2NvbG9yOiMwMDk3ZmY7JywgJy0tLS0tLS0+QnJlYXRoZTogaW5wdXRzJywgaW5wdXRzKQ0KICAgIH0NCg0KICAgIGlmIChOb3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuYWxsSW5wdXRzU2lsZW50KGlucHV0cykpIHsNCiAgICAgIHRoaXMuZmlsbE91dHB1dHNTcGFyc2VGaXZlQmlucyhvdXRwdXRzKQ0KICAgIH0gZWxzZSB7DQogICAgICB0aGlzLl9zaWxlbnRPZmYgPSBOb3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuUEVSSU9EDQogICAgICBOb3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuY29weUlucHV0c1RvT3V0cHV0cyhpbnB1dHMsIG91dHB1dHMpDQogICAgfQ0KDQogICAgcmV0dXJuIHRydWUNCiAgfQ0KDQogIGRlc3Ryb3koKSB7DQogICAgdGhpcy5pc0Rlc3Ryb3kgPSB0cnVlDQogIH0NCn0NCg0KcmVnaXN0ZXJQcm9jZXNzb3IoJ25vdC1lbXB0eS1maWx0ZXItcHJvY2Vzc29yJywgTm90RW1wdHlGaWx0ZXJXb3JrbGV0UHJvY2Vzc29yKQ0K`,_=class{audioContext=new AudioContext;notEmptyFilterWorkletNode;constructor(){}createNotEmptyFilterWorkletNode=async e=>(this.destroy(),this.audioContext=e,await this.audioContext.audioWorklet.addModule(g),this.notEmptyFilterWorkletNode=new AudioWorkletNode(this.audioContext,`not-empty-filter-processor`),this.notEmptyFilterWorkletNode);destroy=()=>{this.notEmptyFilterWorkletNode?.disconnect(),this.notEmptyFilterWorkletNode?.port.postMessage({type:`destroy`}),this.notEmptyFilterWorkletNode=void 0}},v=class{inputStream=new MediaStream;outputStream=new MediaStream;inputGain=1;enhanceGain=1;bgsGain=1;bgmGain=1;outputGain=1;mixAudioMap=new Map;audioContext=new AudioContext;isExternalAudioContext=!1;sourceNode;inputGainNode;enhanceGainNode;bgsGainNode;bgmGainNode;rnnoiseNode;analyserNode;analyserArrayData;outputGainNode;destinationNode;denoise=!1;mute=!0;notEmpty=!1;rnnoiseWorklet;rnnoiseWorkletNode;notEmptyFilterWorklet=new _;notEmptyFilterWorkletNode;filterStream=e=>e;constructor(e,t){this.inputStream=e,t&&(this.audioContext=t,this.isExternalAudioContext=!0),this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.inputGainNode=this.audioContext.createGain(),this.inputGainNode.gain.setValueAtTime(this.inputGain,this.audioContext.currentTime),this.enhanceGainNode=this.audioContext.createGain(),this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime),this.bgsGainNode=this.audioContext.createGain(),this.bgsGainNode.gain.setValueAtTime(this.bgsGain,this.audioContext.currentTime),this.bgmGainNode=this.audioContext.createGain(),this.bgmGainNode.gain.setValueAtTime(this.bgmGain,this.audioContext.currentTime),this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=512,this.analyserArrayData=new Uint8Array(this.analyserNode.frequencyBinCount),this.outputGainNode=this.audioContext.createGain(),this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputStream=this.destinationNode.stream;{let{sourceNode:e,inputGainNode:t,enhanceGainNode:n,bgsGainNode:r,bgmGainNode:i,analyserNode:a,outputGainNode:o,destinationNode:s}=this;e.connect(t),t.connect(n),n.connect(a),r.connect(a),i.connect(a),n.connect(s),r.connect(s),i.connect(s),o.connect(this.audioContext.destination)}this.audioContext.resume()}use=({rnnoise:e})=>{this.rnnoiseWorklet=new e.RnnoiseWorklet};_changeSource=()=>{this.sourceNode.disconnect(),this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.sourceNode.connect(this.inputGainNode)};replaceTrack=e=>{let t=this.inputStream.getTracks();for(let e of t)this.inputStream.removeTrack(e);this.inputStream.addTrack(e),this._changeSource()};stop=()=>{{let e=this.inputStream.getTracks();for(let t of e)t.stop(),this.inputStream.removeTrack(t)}};pause=async e=>{let t=this.inputStream.getTracks();for(let n of t)n.enabled=!e};getStream=()=>this.filterStream(this.outputStream);setMute=(e=!0)=>{this.mute=e,this.analyserNode.disconnect(),e===!1&&this.analyserNode.connect(this.outputGainNode)};setDenoise=async(e=!0)=>{this.rnnoiseWorklet&&(this.inputGainNode.disconnect(),e?(this.rnnoiseWorkletNode=await this.rnnoiseWorklet.createRnnoiseWorkletNode(this.audioContext),this.inputGainNode.connect(this.rnnoiseWorkletNode),this.rnnoiseWorkletNode.connect(this.enhanceGainNode)):(this.inputGainNode.connect(this.enhanceGainNode),this.rnnoiseWorklet.destroy()),this.denoise=e)};setNotEmpty=async(e=!0)=>{this.notEmptyFilterWorklet&&(e?(this.notEmptyFilterWorkletNode=await this.notEmptyFilterWorklet.createNotEmptyFilterWorkletNode(this.audioContext),this.notEmptyFilterWorkletNode.connect(this.analyserNode),this.notEmptyFilterWorkletNode.connect(this.destinationNode)):(this.notEmptyFilterWorkletNode?.disconnect(),this.notEmptyFilterWorklet.destroy()),this.notEmpty=e)};setInputGain=e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setEnhanceGain=async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)};setBgsGain=e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setBgmGain=e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setOutputGain=e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)};getVolume=()=>{let{analyserNode:e,analyserArrayData:t}=this;e.getByteFrequencyData(t);let n=0;for(let e=0;e<t.length;e++)n+=t[e];return Math.ceil(n/t.length)};mixAudio=(e,t=`bgm`)=>new Promise(async(n,r)=>{try{{let e=this.mixAudioMap.get(t);e&&e.stop()}let r=t===`bgs`?this.bgsGainNode:this.bgmGainNode,i=this.audioContext.createBufferSource();this.mixAudioMap.set(t,i),i.buffer=e,i.connect(r),i.onended=()=>{i.disconnect(r),this.mixAudioMap.delete(t),n(!0)},i.start(0)}catch(e){r(e)}});mixAudioStop=e=>{this.mixAudioMap.get(e)?.stop()};changeMix=(e,t)=>{let n=e===`bgs`?this.bgsGainNode:this.bgmGainNode;t?n.connect(this.destinationNode):n.disconnect(this.destinationNode)};destroy=async()=>{for(let e of this.mixAudioMap.values())e.stop(),e.disconnect();this.mixAudioMap.clear(),this.notEmptyFilterWorklet.destroy(),this.rnnoiseWorklet?.destroy(),this.notEmptyFilterWorkletNode=void 0,this.rnnoiseWorkletNode=void 0,this.sourceNode.disconnect(),this.inputGainNode.disconnect(),this.enhanceGainNode.disconnect(),this.bgsGainNode.disconnect(),this.bgmGainNode.disconnect(),this.analyserNode.disconnect(),this.outputGainNode.disconnect();for(let e of this.inputStream.getTracks())e.stop(),this.inputStream.removeTrack(e);for(let e of this.outputStream.getTracks())e.stop(),this.outputStream.removeTrack(e);this.notEmpty=!1,this.denoise=!1,this.mute=!0,!this.isExternalAudioContext&&this.audioContext.state!==`closed`&&await this.audioContext.close()}},y=async(e,t)=>{try{let{format:n,numberOfChannels:r,numberOfFrames:i,sampleRate:a}=t,o=e.createBuffer(r,i,a);for(let e=0;e<r;e++){let r=t.allocationSize({planeIndex:e}),a=new Uint8Array(r);t.copyTo(a,{planeIndex:e});let s=new DataView(a.buffer),c=o.getChannelData(e);for(let e=0;e<i;e++){let t;switch(n){case`s16`:case`s16-planar`:t=s.getInt16(e*2,!0)/32768;break;case`f32`:case`f32-planar`:t=s.getFloat32(e*4,!0);break;case`u8`:case`u8-planar`:t=(s.getUint8(e)-128)/128;break;default:throw Error(`Unsupported audio format: ${n}`)}c[e]=Math.max(-1,Math.min(1,t))}}return o}catch(e){throw console.error(`Failed to convert AudioData to AudioBuffer:`,e),e}},b=class{prAudioStream;audioContext;destination;stream=new MediaStream;nextStartTime=0;pendingSources=[];constructor(){}init=e=>{e||=new(window.AudioContext||window.webkitAudioContext),this.audioContext=e,this.destination=this.audioContext.createMediaStreamDestination(),this.stream=new MediaStream,this.stream.addTrack(this.destination.stream.getAudioTracks()[0]),this.prAudioStream=new v(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(e){let{audioData:t,playbackRate:n=1}=e;if(!this.audioContext||!this.destination)return;let r=await y(this.audioContext,t);if(t.close(),!r)return;let i=this.audioContext.createBufferSource();i.buffer=r,i.playbackRate.value=n;let a=-1200*Math.log2(n);i.detune.value=a,i.connect(this.destination);let o=Math.max(this.nextStartTime,this.audioContext.currentTime),s=r.duration/n;this.nextStartTime=o+s,i.start(o),this.pendingSources.push(i),i.onended=()=>{this.pendingSources=this.pendingSources.filter(e=>e!==i)},this.audioContext.state===`suspended`&&await this.audioContext.resume()}getStream=()=>this.prAudioStream?.getStream();destroy(){this.audioContext?.close(),this.audioContext=void 0,this.destination=void 0,this.nextStartTime=0,this.prAudioStream?.stop(),this.prAudioStream?.destroy(),this.pendingSources.forEach(e=>e.stop()),this.pendingSources=[]}},x=e=>{let t=e.toLowerCase();return t.includes(`.m3u8`)||t.includes(`hls`)||t.includes(`master.m3u8`)||t.match(/index\d*\.m3u8/)?`hls`:t.includes(`.mpd`)||t.includes(`dash`)?`dash`:t.includes(`.mp4`)||t.includes(`.m4s`)?`mp4`:t.startsWith(`rtmp://`)||t.startsWith(`rtmps://`)?`rtmp`:t.includes(`.flv`)||t.includes(`flv`)&&!t.includes(`flash`)?`flv`:`unknown`},S=e=>{let t=e?.getTracks()||[];for(let e of t)e.stop()},C=class{resolvesMap=new Map;index=0;constructor(){}add=(e,t=()=>!1,n=0)=>new Promise(r=>{if(t())return r(!0);this.resolvesMap.has(e)||this.resolvesMap.set(e,new Map),this.index++;let i=`${this.index}`;if(n=Math.max(0,n),n===0){this.resolvesMap.get(e)?.set(i,{resolve:r,timer:0});return}let a=window.setTimeout(()=>{this.emit(e)},n);this.resolvesMap.get(e)?.set(i,{resolve:r,timer:a})});emit=async e=>{let t=this.resolvesMap.get(e);if(!t)return;let n=[...t.keys()];for(let e of n){let n=t.get(e);n&&(clearTimeout(n.timer),n.resolve(),t.delete(e))}}},w=(e,t)=>{let n=new Uint8Array(e),r=new Uint8Array(t),i=new Uint8Array(11+n.length+r.length),a=0;return i[a++]=1,i[a++]=n[1],i[a++]=n[2],i[a++]=n[3],i[a++]=255,i[a++]=225,i[a++]=n.length>>8&255,i[a++]=n.length&255,i.set(n,a),a+=n.length,i[a++]=1,i[a++]=r.length>>8&255,i[a++]=r.length&255,i.set(r,a),i},T=e=>{let t=0,n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(t);if(t+=1,r!==1)throw Error(`Invalid AVC version`);let i=n.getUint8(t)&255;t+=1;let a=n.getUint8(t)&255;t+=1;let o=n.getUint8(t)&255;t+=1;let s=`avc1.${Array.from([i,a,o],e=>e.toString(16).padStart(2,`0`)).join(``)}`;t+=1,t+=1;let c=n.getUint16(t,!1);t+=2;let l=new Uint8Array(e.buffer,e.byteOffset+t,c);t+=c,t+=1;let u=n.getUint16(t,!1);return t+=2,{version:r,codec:s,profile:i,compatibility:a,level:o,sps:l,pps:new Uint8Array(e.buffer,e.byteOffset+t,u)}},E=e=>{let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t},D=e=>{let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n},O=e=>{let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=0,r=t.getUint32(n,!1);n+=4;let i=t.getUint8(n),a={forbidden_zero_bit:i>>7&1,nal_ref_idc:i>>5&3,nal_unit_type:i&31};return n+=1,{size:r,header:a,data:new Uint8Array(e.buffer,e.byteOffset+n,r-1)}},k=(e,t)=>e.match(RegExp(`${t}="([^"]*)"`,`i`))?.[1],A=e=>{let[t,n]=e.split(`-`).map(e=>parseInt(e,10));return{start:t,end:n}},j=e=>{if(!e)return;let t=e.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:([\d.]+)S)?/i);if(!t)return;let n=parseInt(t[1]||`0`,10),r=parseInt(t[2]||`0`,10),i=parseFloat(t[3]||`0`);return n*3600+r*60+i},M=(e,t)=>{if(!t)return e;if(/^https?:\/\//i.test(t))return t;if(t.startsWith(`/`)){let n=e.match(/^(https?:\/\/[^/]+)/i)?.[1];return n?`${n}${t}`:t}return e+t},N=(e,t)=>e.replace(/\$(RepresentationID|\w+)(?:%0(\d+)d)?\$/g,(e,n,r)=>{let i=t[n]??t[n.toLowerCase()]??``;return r?String(i).padStart(Number(r),`0`):String(i)}),P=(e,t,n)=>M(e,N(t,n)),F=(e,t)=>{let n=e.match(/<SegmentList([^>]*)>([\s\S]*?)<\/SegmentList>/i)||t.match(/<SegmentList([^>]*)>([\s\S]*?)<\/SegmentList>/i);if(!n)return;let r=n[1],i=n[2],a=i.match(/<Initialization[^>]*range="([^"]+)"/i),o=[],s=/<SegmentURL[^>]*mediaRange="([^"]+)"/gi,c;for(;c=s.exec(i);)o.push(A(c[1]));if(!(o.length===0&&!a))return{timescale:parseInt(k(r,`timescale`)||`1000`,10),duration:parseInt(k(r,`duration`)||`0`,10),initRange:a?A(a[1]):void 0,segments:o}},I=(e,t)=>{let n=e.match(/<SegmentTemplate([^>]*)\/>/i)?.[1]||e.match(/<SegmentTemplate([^>]*)>/i)?.[1]||t.match(/<SegmentTemplate([^>]*)\/>/i)?.[1]||t.match(/<SegmentTemplate([^>]*)>/i)?.[1]||``;if(!n){let t=e.match(/<SegmentURL[^>]*initialization="([^"]*)"[^>]*media="([^"]*)"/i);return t?{initialization:t[1],media:t[2],timescale:1e3,duration:0,startNumber:1}:void 0}return{initialization:k(n,`initialization`),media:k(n,`media`),timescale:parseInt(k(n,`timescale`)||`1000`,10),duration:parseInt(k(n,`duration`)||`0`,10),startNumber:parseInt(k(n,`startNumber`)||`1`,10)}},L=(e,t)=>{let n=t.substring(0,t.lastIndexOf(`/`)+1),r=e.match(/<MPD[^>]*>/i)?.[0]||``,i=(k(r,`type`)||`static`)===`dynamic`,a=j(k(r,`mediaPresentationDuration`)),o=[],s=/<AdaptationSet([^>]*)>([\s\S]*?)<\/AdaptationSet>/gi,c;for(;c=s.exec(e);){let e=c[1],t=c[2],n=k(e,`mimeType`)||``,r=k(e,`contentType`)||``,i=n.includes(`video`)||r===`video`||/<ContentComponent[^>]*contentType="video"/i.test(t),a=n.includes(`audio`)||r===`audio`||/<ContentComponent[^>]*contentType="audio"/i.test(t),s;if(i&&a?s=`mux`:i?s=`video`:a&&(s=`audio`),!s)continue;let l=t.match(/<Representation([^>]*)(?:\/>|>([\s\S]*?)<\/Representation>)/i);if(!l)continue;let u=l[1],d=l[2]||``,f=k(u,`id`)||`0`,p=k(u,`codecs`)||``,m=parseInt(k(u,`bandwidth`)||`0`,10),h=parseInt(k(u,`width`)||`0`,10)||void 0,g=parseInt(k(u,`height`)||`0`,10)||void 0,_=d.match(/<BaseURL>([^<]+)<\/BaseURL>/i)?.[1]?.trim(),v=F(d,t),y=v?void 0:I(d,t);!v&&(!y||!y.media&&!y.initialization)||o.push({kind:s,mimeType:n||(i?`video/mp4`:`audio/mp4`),representation:{id:f,codecs:p,bandwidth:m,width:h,height:g,baseUrl:_,template:y,segmentList:v}})}return{isLive:i,duration:a,baseUrl:n,adaptations:o}},R=class{#e={timeout:5*1e3,check:!1};#t=null;constructor(e={}){this.#e={...this.#e,...e}}#n=(e,t)=>new Promise(async n=>{this.#t=new AbortController;let{signal:r}=this.#t,i=this.#e.timeout,a=setTimeout(()=>{this.#t?.abort(`Timeout (${i}ms)`)},i);await fetch(e,{cache:`no-store`,...t,method:`HEAD`,signal:r}).then(e=>{clearTimeout(a),n({status:e.status===200?`successed`:`failed`,reason:e.status===200?``:`HTTP ${e.status}`})}).catch(e=>{if(clearTimeout(a),e.name===`AbortError`){let e=r.reason||`Actively stopped`;n({status:e.includes(`Timeout`)?`timeout`:`stopped`,reason:e})}else n({status:`error`,reason:e.message})})});request=(e,t)=>new Promise(async(n,r)=>{try{this.stop(),this.#e.check&&await this.#n(e),this.#t=new AbortController;let{signal:r}=this.#t;n(await fetch(e,{cache:`no-store`,...t,signal:r}))}catch(e){r(e)}});stop=()=>{if(this.#t?.signal.aborted===!1){let e=Error(`Actively stopped.`);e.name=`AbortError`,this.#t.abort(e)}}},z=class{option={frameTrack:!1};converter=`MediaStreamTrackGenerator`in window?`generator`:`canvas`;prFetch=new R;getSegmentsFetch=new R;prResolves=new C;url=``;start_resolve;demuxerWorker;decoderWorker;audioPlayer;renderWorker;stream;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(e={}){this.option.frameTrack=e.frameTrack??!1}start=async e=>{await this.stop(),this.url=e;let t=x(e);if(t===`unknown`)throw Error(`This address cannot be parsed.`);switch(this.init(t),t){case`flv`:this.flv.start();break;case`hls`:this.hls.start();break;case`dash`:this.dash.start();break;case`mp4`:this.mp4.start();break;case`rtmp`:throw Error(`RTMP is not supported in browser. Please use HTTP-FLV or HLS.`)}};stop=async()=>{try{this.url=``,clearInterval(this.hls.getSegmentsTimer),clearInterval(this.dash.getSegmentsTimer),this.prFetch.stop(),this.getSegmentsFetch.stop(),this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy(),this.cutRenders=new Map,S(this.stream),this.audioPlayer?.destroy()}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: error`,e)}};getStream=()=>this.stream;setPause=e=>{this.renderWorker?.setPause({pause:e})};setMute=e=>this.audioPlayer?.prAudioStream?.setMute(e);setOutputGain=e=>{this.audioPlayer?.prAudioStream?.setOutputGain(e)};setFrameTrack=e=>{this.option.frameTrack=e,this.decoderWorker?.setFrameTrack(e)};isReady=()=>this.prResolves.add(`isReady`,()=>this.stream?.active===!0);cut={create:(e,t)=>{if(this.converter===`generator`){let n=new MediaStreamTrackGenerator({kind:`video`}),r=new MediaStream([n]);return this.renderWorker?.addCut({key:e,writable:n.writable,cutOption:t}),this.cutRenders.set(e,{stream:r}),r}let n=document.createElement(`canvas`),r=n.captureStream(),i=n.transferControlToOffscreen();return this.renderWorker?.addCut({key:e,offscreen:i,cutOption:t}),this.cutRenders.set(e,{stream:r}),r},setCut:(e,t)=>{this.renderWorker?.setCut({key:e,cutOption:t})},getStream:e=>this.cutRenders.get(e)?.stream,remove:e=>{this.renderWorker?.delCut(e),this.cutRenders.delete(e)},setPause:(e,t)=>{this.renderWorker?.setPause({key:e,pause:t})}};init=e=>{this.initRender(),this.initDecoder(e),this.initDemuxer(e),this.audioPlayer=new b,this.audioPlayer.init()};initDemuxer=e=>{this.demuxerWorker=new a,this.demuxerWorker.init(e),this.demuxerWorker.on.info=e=>{this.on.demuxer.info&&this.on.demuxer.info(e)},this.demuxerWorker.on.config=e=>{this.on.demuxer.config&&this.on.demuxer.config(e);let{kind:t}=e;switch(t){case`audio`:{let{codec:t,sampleRate:n,numberOfChannels:r,description:i}=e;this.decoderWorker?.initAudio({codec:t,sampleRate:n,numberOfChannels:r,...i?{description:i}:{}})}break;case`video`:{let{codec:t,description:n}=e;this.decoderWorker?.initVideo({codec:t,description:n})}break}},this.demuxerWorker.on.chunk=e=>{if(this.on.demuxer.chunk&&this.on.demuxer.chunk(e),!this.decoderWorker)return;let{kind:t}=e;switch(t){case`audio`:{let{type:n,dts:r,data:i}=e,a=r*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:a,data:i}})}break;case`video`:{let{type:n,dts:r,data:i,nalus:a=[]}=e,o=r*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:o,data:i},nalus:a})}break}}};initDecoder=e=>{this.decoderWorker=new u,this.decoderWorker.init(e);let{frameTrack:t=!1}=this.option;this.decoderWorker.setFrameTrack(t),this.decoderWorker.on.audio.error=e=>{this.on.error&&this.on.error(e)},this.decoderWorker.on.audio.decode=e=>{this.audioPlayer?.push(e),this.on.decoder.audio&&this.on.decoder.audio(e)},this.decoderWorker.on.video.decode=e=>{this.start_resolve&&=(this.start_resolve(!0),void 0),this.renderWorker?.push(e),this.on.decoder.video&&this.on.decoder.video(e)},this.decoderWorker.on.video.error=e=>{this.on.error&&this.on.error(e)},this.decoderWorker.on.nalus=async e=>{for(let t of e){if(t.byteLength<=4)continue;let{header:e,data:n}=O(t),{nal_unit_type:r}=e;r===6&&this.on.decoder.sei&&this.on.decoder.sei(n)}},this.decoderWorker.on.analysis=e=>{this.on.decoder.analysis&&this.on.decoder.analysis(e)}};initRender=()=>{if(this.renderWorker=new h,this.converter===`generator`){let e=new MediaStreamTrackGenerator({kind:`video`}),t=new MediaStream([e]);this.renderWorker?.addCut({writable:e.writable}),this.stream=t}else{let e=document.createElement(`canvas`),t=e.captureStream(),n=e.transferControlToOffscreen();this.renderWorker?.addCut({offscreen:n}),this.stream=t}this.renderWorker?.setPause({pause:!1})};flv={start:()=>new Promise(async(e,t)=>{try{this.start_resolve=e;let n,r=0;for(;;){r+=1;try{n=await this.prFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(n?.status===200||r===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!n||n.status!==200)return t(`request is error.`);let i=n.body?.getReader();if(!i)return t(`reader is error.`);for(;;){let{done:e,value:t}=await i.read();if(t&&this.demuxerWorker?.push(t),e||this.url===``)break}}catch(e){e.name!==`AbortError`&&t(e)}})};hls={isLive:!1,urls:[],url:``,getSegmentsTimer:0,parse:async e=>{let t=new TextDecoder(`utf-8`).decode(e).split(`
|
|
2
|
+
`).map(e=>e.replace(`\r`,``)),n=this.url.substring(0,this.url.lastIndexOf(`/`)+1),r=4,i=0,a=!1,o=[];for(let e of t)e.startsWith(`#EXTINF:`)?r=parseFloat(e.split(`:`)[1].split(`,`)[0]):e.startsWith(`#EXT-X-TARGETDURATION:`)?i=parseInt(e.split(`:`)[1]):e.startsWith(`#EXT-X-ENDLIST`)?a=!1:e.startsWith(`#EXT-X-MEDIA-SEQUENCE:`)?a=!0:e.includes(`.ts`)&&!e.startsWith(`#`)&&o.push({url:e.startsWith(`http`)?e:n+e,duration:r,isLive:a});return{baseUrl:n,targetDuration:i,isLive:a,segments:o}},getSegments:async()=>{try{let e,t=0;for(;;){t+=1;try{e=await this.getSegmentsFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(e?.status===200||t===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!e||e.status!==200)throw Error(`request is error.`);let n=e.body?.getReader();if(!n)throw Error(`reader is error.`);for(;;){let{done:e,value:t}=await n.read();if(t){let{segments:e=[],isLive:n=!1}=await this.hls.parse(t);this.hls.isLive=n,n===!1&&(this.option.frameTrack=!1);let r=Array.from(e,e=>e.url),i=r.findIndex(e=>e===this.hls.url);i!==-1&&(r=r.slice(i+1)),this.hls.urls=r}if(e||this.url===``)break}}catch(e){e.name!==`AbortError`&&this.on.error&&this.on.error(e)}},start:()=>new Promise(async(e,t)=>{try{for(this.start_resolve=e,this.hls.url=``,this.hls.urls=[],await this.hls.getSegments(),this.hls.getSegmentsTimer=window.setInterval(this.hls.getSegments,500),this.hls.isLive===!1&&(clearInterval(this.hls.getSegmentsTimer),this.decoderWorker?.setFrameTrack(!1));;){let e=this.hls.urls.shift();if(e){this.hls.url=e;let t=(await this.prFetch.request(e)).body?.getReader();if(!t)throw Error(`segment reader is error.`);for(;;){let{done:e,value:n}=await t.read();if(n&&this.demuxerWorker?.push(n),e||this.url===``)break}}else await new Promise(e=>setTimeout(()=>e(!0),300))}}catch(e){e.name!==`AbortError`&&t(e)}})};mp4={start:()=>new Promise(async(e,t)=>{try{this.start_resolve=e;let n,r=0;for(;;){r+=1;try{n=await this.prFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(n?.status===200||r===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!n||n.status!==200)return t(`request is error.`);let i=n.body?.getReader();if(!i)return t(`reader is error.`);for(this.decoderWorker?.setFrameTrack(!1);;){let{done:e,value:t}=await i.read();if(t&&this.demuxerWorker?.push(t),e||this.url===``)break}}catch(e){e.name!==`AbortError`&&t(e)}})};dash={isLive:!1,segmentNumber:1,mpdInfo:null,getSegmentsTimer:0,fetchSegment:async e=>{let t=await this.prFetch.request(e);if(!t||t.status!==200)return!1;let n=t.body?.getReader();if(!n)return!1;for(;;){let{done:e,value:t}=await n.read();if(t&&this.demuxerWorker?.push(t),e||this.url===``)break}return!0},fetchByteRange:async(e,t,n)=>{let r,i=0;for(;;){i+=1;try{r=await fetch(e,{headers:{Range:`bytes=${t}-${n}`}})}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(r?.ok&&(r.status===200||r.status===206)||i===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!r?.ok||r.status!==200&&r.status!==206)return!1;let a=new Uint8Array(await r.arrayBuffer());return a.byteLength>0&&this.demuxerWorker?.push(a),a.byteLength>0},getMpd:async()=>{try{let e,t=0;for(;;){t+=1;try{e=await this.getSegmentsFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(e?.status===200||t===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!e||e.status!==200)throw Error(`request is error.`);let n=e.body?.getReader();if(!n)throw Error(`reader is error.`);let r=[];for(;;){let{done:e,value:t}=await n.read();if(t&&r.push(t),e||this.url===``)break}let i=r.reduce((e,t)=>e+t.byteLength,0),a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;let s=L(new TextDecoder(`utf-8`).decode(a),this.url);return this.dash.mpdInfo=s,this.dash.isLive=s.isLive,this.dash.isLive||(this.option.frameTrack=!1),s}catch(e){return e.name!==`AbortError`&&this.on.error&&this.on.error(e),null}},start:()=>new Promise(async(e,t)=>{try{this.start_resolve=e,this.dash.segmentNumber=1,this.dash.mpdInfo=null;let n=await this.dash.getMpd();if(!n)return t(`mpd parse is error.`);let r=n.adaptations.find(e=>e.kind===`video`||e.kind===`mux`)?.representation;if(r?.width&&r?.height){let e={width:r.width,height:r.height,duration:n.duration};this.on.demuxer.info&&this.on.demuxer.info(e)}let i=n.adaptations.find(e=>e.representation.segmentList);if(i?.representation.segmentList){let{segmentList:e,baseUrl:r}=i.representation,a=M(n.baseUrl,r||``);if(e.initRange){let{start:n,end:r}=e.initRange;if(!await this.dash.fetchByteRange(a,n,r))return t(`dash init segment fetch failed.`)}this.decoderWorker?.setFrameTrack(!1);for(let t of e.segments){if(this.url===``)break;await this.dash.fetchByteRange(a,t.start,t.end)}return}let a=[n.adaptations.find(e=>e.kind===`video`),n.adaptations.find(e=>e.kind===`audio`),n.adaptations.find(e=>e.kind===`mux`)].filter(e=>!!e);if(a.length===0)return t(`no adaptation in mpd.`);for(let e of a){let{id:t,bandwidth:r,template:i}=e.representation;if(!i?.initialization)continue;let a=P(n.baseUrl,i.initialization,{RepresentationID:t,Bandwidth:r,Number:this.dash.segmentNumber});await this.dash.fetchSegment(a)}for(this.dash.isLive?this.dash.getSegmentsTimer=window.setInterval(this.dash.getMpd,3e3):this.decoderWorker?.setFrameTrack(!1);;){let e=this.dash.mpdInfo;if(!e||this.url===``)break;let{baseUrl:t}=e,n=!1;for(let e of a){let{id:r,bandwidth:i,template:a}=e.representation;if(!a?.media)continue;let o=P(t,a.media,{RepresentationID:r,Bandwidth:i,Number:this.dash.segmentNumber});await this.dash.fetchSegment(o)&&(n=!0)}if(!n){if(this.dash.isLive){await new Promise(e=>setTimeout(()=>e(!0),300));continue}break}this.dash.segmentNumber+=1}}catch(e){e.name!==`AbortError`&&t(e)}})}},B=class{pendingPayloads=[];payload=new Uint8Array;chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);let t=this.pendingPayloads.shift();if(!t)return!1;let n=new Uint8Array(this.payload.byteLength+t.byteLength);return n.set(this.payload,0),n.set(t,this.payload.byteLength),this.payload=n,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};discardPayload=()=>{this.payload=new Uint8Array};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array,this.chunks=[]}},V=(e,t)=>e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),H=(e,t)=>{let n=V(e,t);return n&8388608&&(n|=-16777216),n},U=(e,t)=>t<<24|e,W=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],G=class{audioConfig;videoConfig;header;textDecoder=new TextDecoder(`utf-8`);on={};constructor(){}parse=async e=>{let t=0;for(this.header||(this.parseHeader(e,t),t+=9);this.isSurplusTag(e,t)!==!1;){let{tagType:n,dataSize:r,dts:i}=this.parseTagHeader(e,t+4);if(n){let a=this.parseTagBody(n,e,t+4+11,r);if(!a){t=t+4+11+r,await new Promise(e=>setTimeout(()=>e(!0),8));continue}switch(n){case`script`:this.on.info&&this.on.info(a);break;case`audio`:{let{accPacketType:e}=a;if(e===0){let{codec:e,sampleRate:t,channelConfiguration:n,data:r}=a;this.audioConfig={kind:`audio`,codec:e,sampleRate:t,numberOfChannels:n,...r?{description:r}:{}},this.on.config&&this.on.config(this.audioConfig)}else{let{cts:e,data:t}=a,n=e===void 0?void 0:e+i;this.on.chunk&&this.on.chunk({kind:`audio`,type:`key`,dts:i,pts:n,cts:e,data:t})}}break;case`video`:{let{avcPacketType:e}=a;if(e===0){let{codec:e,sps:t,pps:n,data:r}=a;this.videoConfig={kind:`video`,codec:e,description:r,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}else{let{frameType:e,cts:t,data:n,nalus:r}=a,o=e===1?`key`:`delta`,s=t===void 0?void 0:t+i;this.on.chunk&&this.on.chunk({kind:`video`,type:o,dts:i,pts:s,cts:t,data:n,nalus:r})}}break}t=t+4+11+r}await new Promise(e=>setTimeout(()=>e(!0),8))}return t};parseHeader=(e,t)=>{let n,r,i,a;n=e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),r=e.getUint8(t+3);{let n=e.getUint8(t+4);i={audio:!!(n&4),video:!!(n&1)}}a=e.getUint32(t+5),this.header={signature:n,version:r,flags:i,dataOffset:a}};isSurplusTag=(e,t)=>{let n=!0,r=e.byteLength;if(t+4>r)n=!1;else if(t+4+11>r)n=!1;else{let i=V(e,t+4+1);t+4+11+i>r&&(n=!1)}return n};parseTagHeader=(e,t)=>{let n,r,i,a,o;{let r=e.getUint8(t),i;switch(r){case 18:i=`script`;break;case 8:i=`audio`;break;case 9:i=`video`;break}n=i}r=V(e,t+1),i=V(e,t+4),a=e.getUint8(t+7),o=V(e,t+8);let s=U(i,a);return{tagType:n,dataSize:r,timestamp:i,timestampExtended:a,dts:s,streamID:o}};parseTagBody=(e,t,n,r)=>{let i;switch(e){case`script`:i=this.parseMetaData(t,n);break;case`audio`:i=this.parseAudio(t,n,r);break;case`video`:i=this.parseVideo(t,n,r);break}return i};parseMetaData=(e,t)=>{let n=t;if(e.getUint8(n)!==2)return null;n+=1;let r=e.getUint16(n,!1);n+=2;{let t=new Int8Array(e.buffer.slice(n,n+r)),i=this.textDecoder?.decode(t)||``;if(n+=r,i!==`onMetaData`)return{name:i}}let i=this.getAmfType(e,n);return n+=1,this.getAMFValue(e,n,i).value};parseAudio=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i>>2&3,s=i>>1&1,c=i&1;r+=1;let l=e.getUint8(r);r+=1;let u=n-(r-t);if(u<=0)return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:new Uint8Array};let d=new Uint8Array(e.buffer.slice(r,r+u));if(a===10&&l===0){let t=e.getUint8(r),n=e.getUint8(r+1),i=t>>3&31,u=(t&7)<<1|n>>7;return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d,samplingFrequencyIndex:u,channelConfiguration:n>>3&15,codec:`mp4a.40.${i}`,sampleRate:W[u]}}return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d}};parseVideo=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i&15;r+=1;let s=e.getUint8(r);r+=1;let c=H(e,r);r+=3;let l=n-5;if(l<0)return null;let u=new Uint8Array(e.buffer.slice(r,r+l));switch(o){case 7:if(s===0)return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u,...T(u)};if(s===1){let t=[],n=r+l;for(;!(r+4>n);){let i=e.getUint32(r,!1);if(i<=0||r+4+i>n)break;let a=new Uint8Array(e.buffer.slice(r,r+4+i));r+=4+i,t.push(a)}return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u,nalus:t}}break;default:return null}return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u}};getAmfType=(e,t)=>e.getUint8(t);getAMFName=(e,t,n)=>{let r=new Uint8Array(e.buffer.slice(t,t+n));return this.textDecoder?.decode(r)||``};getAMFValue=(e,t,n)=>{let r=t,i,a=0;switch(n){case 0:i=e.getFloat64(r,!1),a=8;break;case 1:i=!!e.getUint8(r),a=1;break;case 2:{i=``;let t=e.getUint16(r,!1);r+=2;let n=new Int8Array(e.buffer,r,t).filter(e=>e!==0);i=(this.textDecoder?.decode(n)||``).trim(),a=2+t}break;case 3:for(i={};r<e.byteLength;){let t=e.getUint16(r,!1);if(t===0)break;r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);if(o===6)break;r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}break;case 8:{i={};let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=e.getUint16(r,!1);r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}}break;case 10:{i=[];let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=this.getAmfType(e,r);r+=1;let n=this.getAMFValue(e,r,t);r+=n.length,i.push(n.value),a=1+n.length}}break}return{amfType:n,length:a,value:i}}},K=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],q=e=>{let t=`unknown`;switch(e){case 1:case 2:case 27:case 36:t=`video`;break;case 3:case 4:case 15:t=`audio`;break;case 6:t=`subtitle`;break;case 134:t=`ad`;break}return t},ee=class{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let t=0;for(;!(t+188>e.byteLength);){if(e.getInt8(t)!=71){t++;continue}await this.parsePacket(e,t),t+=188}return t};parsePacket=async(e,t)=>{if(t+188>e.byteLength||e.getUint8(t)!==71)throw Error(`Invalid TS packet`);let n=t,r=this.parseHeader(e,n);n+=4;let{transport_error_indicator:i,pid:a,payload_unit_start_indicator:o,adaptation_field_control:s}=r;if(i===1||a===void 0)return;let c=184;if(s===2||s===3){let t=e.getUint8(n);n+=1,t>0&&(this.parseAdaptationField(e,n),n+=t),c-=1+t}if(s===1||s===3){if(c<=0)return;let t=new Uint8Array(e.buffer.slice(n,n+c));if(a===0)return this.parsePAT(e,n);{let{programs:t=[]}=this.pat||{};if(t.find(e=>e.pmt_pid===a))return this.parsePMT(e,n)}let{streams:r=[]}=this.pmt||{},i=r.find(e=>e.elementary_pid===a);if(i){if(o===1){let e=this.payloadMap.get(a);if(e){switch(i.kind){case`audio`:{let t=await this.parseAudio(e);this.on.chunk&&this.on.chunk(t)}break;case`video`:{let t=await this.parseVideo(e);this.on.chunk&&this.on.chunk(t),await new Promise(e=>setTimeout(()=>e(!0),0))}break}this.payloadMap.delete(a)}}{this.payloadMap.has(a)||this.payloadMap.set(a,new Uint8Array);let e=this.payloadMap.get(a),n=new Uint8Array(e.byteLength+t.byteLength);n.set(e,0),n.set(t,e.byteLength),this.payloadMap.set(a,n)}}}};parseHeader=(e,t)=>{let n=t,r=e.getUint8(n),i=e.getUint8(n+1),a=e.getUint8(n+2),o=e.getUint8(n+3),s=(i&128)>>7;return s===1?{sync_byte:r,transport_error_indicator:s}:{sync_byte:r,transport_error_indicator:s,payload_unit_start_indicator:(i&64)>>6,transport_priority:(i&32)>>5,pid:(i&31)<<8|a,transport_scrambling_control:(o&192)>>6,adaptation_field_control:o>>4&3,continuity_counter:o&15}};parsePAT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==0)throw Error(`Invalid PAT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u}}let i=[];{let t=r.section_length-5-4,a=n+t;for(;n<a;){let t=e.getUint16(n),r=e.getUint16(n+2)&8191;n+=4,t!==0&&r>=32&&r<=8190&&i.push({program_number:t,pmt_pid:r})}}let a=e.getUint32(n);this.pat={header:r,programs:i,crc32:a}};parsePMT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==2)throw Error(`Invalid PMT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1;let d=e.getUint16(n)&8191;n+=2;let f=e.getUint16(n)&4095;n+=2,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u,pcr_pid:d,program_info_length:f}}n+=r.program_info_length;let i=[];{let t=r.section_length-9-4,a=n+t;for(;n<a;){let t=e.getUint8(n),r=q(t),a=e.getUint16(n+1)&8191,o=e.getUint16(n+3)&4095;if(n+=5+o,a<32||a>8190){console.warn(`Invalid elementary_pid: 0x${a.toString(16)}`);continue}i.push({kind:r,stream_type:t,elementary_pid:a,es_info_length:o})}}let a=e.getUint32(n);this.pmt={header:r,streams:i,crc32:a}};parseAdaptationField=(e,t)=>{let n=t,r,i,a,o,s=e.getUint8(n),c=!!(s&128),l=!!(s&64),u=!!(s&32),d=!!(s&16),f=!!(s&8),p=!!(s&4),m=!!(s&2),h=!!(s&1);n+=1;let g=(e,t)=>{let n=BigInt(0);n|=BigInt(e.getUint16(t))<<25n,n|=BigInt(e.getUint16(t+1))<<17n,n|=BigInt(e.getUint16(t+2))<<9n,n|=BigInt(e.getUint16(t+3))<<1n,n|=BigInt(e.getUint16(t+4)>>7);let r=(e.getUint16(t+4)&1)<<8|e.getUint16(t+5);return n=n*300n+BigInt(r),n};if(d&&(r=g(e,n),n+=6),f&&(i=g(e,n),n+=6),p&&(a=e.getInt8(n),n+=1),m){let t=e.getUint8(n);n+=1,o=new Uint8Array(e.buffer,n,t),n+=t}return{discontinuity_indicator:c,random_access_indicator:l,elementary_stream_priority_indicator:u,pcr_flag:d,opcr_flag:f,splicing_point_flag:p,transport_private_data_flag:m,adaptation_field_extension_flag:h,pcr:r,opcr:i,splice_countdown:a,transport_private_data:o}};parseAudio=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts audio payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{let e=this.parseAdts(i);!this.audioConfig&&e&&(this.audioConfig={kind:`audio`,codec:e.codec,sampleRate:e.sampleRate,numberOfChannels:e.channelConfiguration},this.on.config&&this.on.config(this.audioConfig));let{dts:t=0,pts:n=0}=r;return{kind:`audio`,type:`key`,dts:t,pts:n,cts:n-t,data:e?i.slice(e.headerLength):i}}};parseAdts=e=>{if(e.length<7||e[0]!==255||(e[1]&240)!=240)return null;let t=e[1]&1?7:9;if(e.length<t)return null;let n=(e[2]>>6&3)+1,r=e[2]>>2&15,i=(e[2]&1)<<2|e[3]>>6,a=K[r]??44100;return{headerLength:t,codec:`mp4a.40.${n}`,sampleRate:a,channelConfiguration:i}};parseVideo=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts video payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{let e=this.getNalus(i);if(!this.videoConfig){let t,n;if(t=e.find(e=>e.type===7)?.nalu.slice(4),n=e.find(e=>e.type===8)?.nalu.slice(4),t&&n){let e=w(t,n),{codec:r}=T(e);this.videoConfig={kind:`video`,codec:r,description:e,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}}let t=[],n=`delta`;for(let r of e){let{type:e,nalu:i}=r;switch(e){case 6:case 9:t.push(i);break;case 1:n=`delta`,t.push(i);break;case 5:n=`key`,t.push(i);break}}let a=D(t),{dts:o=0,pts:s=0}=r,c=s-o;return{kind:`video`,type:n,dts:o,pts:s,cts:c,data:a,nalus:t}}};parsePtsDts(e,t){let n=e.getUint8(t),r=e.getUint8(t+1),i=e.getUint8(t+2),a=e.getUint8(t+3),o=e.getUint8(t+4),s=(BigInt(n)&14n)<<29n|(BigInt(r)&255n)<<22n|(BigInt(i)&254n)<<14n|(BigInt(a)&255n)<<7n|(BigInt(o)&254n)>>1n;return Number(s)/90}getNalus=e=>{let t=[],n=0;for(;n<e.byteLength-2;){let r=this.findAnnexBStart(e,n);if(!r)break;let i=e[r.naluOffset]&31,a=this.findAnnexBStart(e,r.nextSearchOffset),o=(a?a.startOffset:e.byteLength)-r.naluOffset;if(o>0){let n=e.slice(r.naluOffset,r.naluOffset+o);t.push({type:i,nalu:E(n)})}n=a?a.startOffset:e.byteLength}return t};findAnnexBStart=(e,t)=>{for(let n=t;n<e.length-2;n++)if(!(e[n]!==0||e[n+1]!==0)){if(e[n+2]===1)return{startOffset:n,naluOffset:n+3,nextSearchOffset:n+3};if(n+3<e.length&&e[n+2]===0&&e[n+3]===1)return{startOffset:n,naluOffset:n+4,nextSearchOffset:n+4}}return null}},J=(e,t)=>String.fromCharCode(e.getUint8(t),e.getUint8(t+1),e.getUint8(t+2),e.getUint8(t+3)),Y=(e,t,n)=>{if(t+8>n)return null;let r=e.getUint32(t,!1),i=J(e,t+4),a=8;if(r===1){if(t+16>n)return null;r=Number(e.getBigUint64(t+8,!1)),a=16}else r===0&&(r=n-t);return r<a||t+r>n?null:{offset:t,size:r,type:i,headerSize:a,contentStart:t+a}},X=(e,t,n,r)=>{let i=t;for(;i<n;){let t=Y(e,i,n);if(!t)break;r(t),i+=t.size}},Z=(e,t,n,r)=>{let i=null;return X(e,t,n,t=>{if(t.type===r)i=t;else if(t.type!==`mdat`){let n=Z(e,t.contentStart,t.offset+t.size,r);n&&(i=n)}}),i},Q=(e,t,n,r)=>{for(let i=t;i+8<=n;i++){if(J(e,i+4)!==r)continue;let t=Y(e,i,n);if(t?.type===r)return t}return null},$=(e,t,n,r,i=86)=>Q(e,t+i,n,r)||Q(e,t+8,n,r),te=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ne=(e,t)=>{let n=0,r=t;for(;r<e.length;){if(n=n<<7|e[r]&127,!(e[r]&128))return{len:n,next:r+1};r++}return{len:0,next:t}},re=class{audioConfig;videoConfig;tracks=new Map;mdatBox=null;progressiveParsed=!1;on={};getDiscardOffset=(e,t)=>this.progressiveParsed||Z(t,0,e,`moof`)||this.tracks.size>0&&!Z(t,0,e,`mdat`)?e:0;constructor(){}parse=async e=>{let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=t.byteLength,r=0;for(;r<n;){let i=Y(e,r,n);if(!i)return 0;switch(i.type){case`moov`:this.parseMoov(e,i),this.tryRunProgressive(e,t);break;case`moof`:this.parseMoof(e,i,t);break;case`mdat`:this.mdatBox=i,this.tryRunProgressive(e,t);break;case`sidx`:case`styp`:case`free`:case`skip`:case`ftyp`:break;default:break}r+=i.size,(i.type===`moov`||i.type===`moof`||i.type===`mdat`)&&await new Promise(e=>setTimeout(()=>e(!0),8))}return this.progressiveParsed?n:0};tryRunProgressive=(e,t)=>{if(this.progressiveParsed||this.tracks.size===0)return;let n=this.mdatBox??Z(e,0,t.byteLength,`mdat`),r=Z(e,0,t.byteLength,`moov`);!n||!r||this.isProgressiveReady(n,r,t.byteLength)&&(this.parseProgressive(e,n,t),this.progressiveParsed=!0)};isProgressiveReady=(e,t,n)=>e.offset+e.size<=n&&t.offset+t.size<=n;parseMoov=(e,t)=>{X(e,t.contentStart,t.offset+t.size,t=>{t.type===`trak`&&this.parseTrak(e,t)});let n=Z(e,t.contentStart,t.offset+t.size,`mvex`);n&&X(e,n.contentStart,n.offset+n.size,t=>{if(t.type!==`trex`)return;let n=e.getUint32(t.contentStart+4,!1),r=this.tracks.get(n);r&&(r.defaultSampleDuration=e.getUint32(t.contentStart+12,!1),r.defaultSampleSize=e.getUint32(t.contentStart+16,!1))});let r=Z(e,t.contentStart,t.offset+t.size,`mvhd`);if(r){let t=e.getUint8(r.contentStart),n=e.getUint32(r.contentStart+(t===1?20:12),!1),i=t===1?Number(e.getBigUint64(r.contentStart+24,!1)):e.getUint32(r.contentStart+16,!1);this.on.info?.({width:[...this.tracks.values()].find(e=>e.kind===`video`)?.width,height:[...this.tracks.values()].find(e=>e.kind===`video`)?.height,duration:n?i/n:void 0})}};readTkhdSize=(e,t)=>{let n=e.getUint8(t.contentStart),r=n===1?72:64,i=n===1?76:68;return{width:e.getUint32(t.contentStart+r,!1)>>16,height:e.getUint32(t.contentStart+i,!1)>>16}};readSampleEntrySize=(e,t)=>({width:e.getUint16(t+32,!1),height:e.getUint16(t+34,!1)});parseTrak=(e,t)=>{let n=Z(e,t.contentStart,t.offset+t.size,`tkhd`),r=Z(e,t.contentStart,t.offset+t.size,`mdia`);if(!n||!r)return;let i=e.getUint8(n.contentStart),a=e.getUint32(n.contentStart+(i===1?20:12),!1),{width:o,height:s}=this.readTkhdSize(e,n),c=Z(e,r.contentStart,r.offset+r.size,`hdlr`),l=Z(e,r.contentStart,r.offset+r.size,`mdhd`);if(!c||!l)return;let u=J(e,c.contentStart+8),d=u===`vide`?`video`:u===`soun`?`audio`:void 0;if(!d)return;let f=e.getUint8(l.contentStart),p=e.getUint32(l.contentStart+(f===1?20:12),!1);this.tracks.set(a,{kind:d,trackId:a,timescale:p,width:o,height:s});let m=Z(e,r.contentStart,r.offset+r.size,`minf`),h=m&&Z(e,m.contentStart,m.offset+m.size,`stbl`),g=h&&Z(e,h.contentStart,h.offset+h.size,`stsd`);if(!g)return;let _=g.contentStart+8,v=_+e.getUint32(_,!1),y=J(e,_+4);if(d===`video`&&(y===`avc1`||y===`avc3`)){let t=this.readSampleEntrySize(e,_);t.width&&t.height&&(o=t.width,s=t.height);let n=$(e,_,v,`avcC`,86);if(!n)return;let r=new Uint8Array(e.buffer,n.contentStart,n.size-n.headerSize),i=T(r),a=i.codec.replace(/^avc1\./,`${y}.`);this.videoConfig={kind:`video`,codec:a,description:r,sps:i.sps,pps:i.pps},this.on.config?.(this.videoConfig)}if(d===`video`){let e=this.tracks.get(a);e&&(e.width=o,e.height=s)}if(d===`audio`&&y===`mp4a`){let t=$(e,_,v,`esds`,36),n=t&&this.parseEsds(e,t);n&&(this.audioConfig=n,this.on.config?.(n))}};parseEsds=(e,t)=>{let n=new Uint8Array(e.buffer,t.contentStart,t.size-t.headerSize);for(let e=0;e<n.length-2;e++){if(n[e]!==5)continue;let{len:t,next:r}=ne(n,e+1);if(t<2||r+t>n.length)continue;let i=n.slice(r,r+t),a=i[0],o=i[1],s=a>>3&31,c=(a&7)<<1|o>>7,l=o>>3&15;return{kind:`audio`,codec:`mp4a.40.${s}`,sampleRate:te[c]??44100,numberOfChannels:l,description:i}}return null};findMdatForMoof=(e,t,n)=>{let r=t.offset+t.size;for(;r+8<=n;){let t=Y(e,r,n);if(!t||t.type===`moof`)break;if(t.type===`mdat`)return t;r+=t.size}return null};parseMoof=(e,t,n)=>{let r=this.findMdatForMoof(e,t,n.byteLength);r&&X(e,t.contentStart,t.offset+t.size,i=>{i.type===`traf`&&this.parseTraf(e,i,t.offset,r,n)})};ticksToMs=(e,t)=>e/t*1e3;readCttsOffsets=(e,t,n)=>{let r=new Int32Array(n);if(!t||n===0)return r;let i=e.getUint32(t.contentStart+4,!1),a=0,o=0,s=0,c=t.contentStart+8;for(let t=0;t<n;t++)o===0&&a<i&&(o=e.getUint32(c,!1),s=e.getInt32(c+4,!1),c+=8,a++),r[t]=s,--o;return r};parseTraf=(e,t,n,r,i)=>{let a=Z(e,t.contentStart,t.offset+t.size,`tfhd`),o=Z(e,t.contentStart,t.offset+t.size,`tfdt`),s=Z(e,t.contentStart,t.offset+t.size,`trun`);if(!a||!o||!s)return;let c=e.getUint32(a.contentStart+4,!1),l=this.tracks.get(c);if(!l)return;let u=e.getUint32(a.contentStart,!1)&16777215,d=(u&131072)!=0,f=a.contentStart+8,p=null,m=0,h=0;u&1&&(p=Number(e.getBigUint64(f,!1)),f+=8),u&2&&(f+=4),u&8&&(m=e.getUint32(f,!1),f+=4),u&16&&(h=e.getUint32(f,!1),f+=4),u&32&&(f+=4),u&8||(m=l.defaultSampleDuration??0),u&16||(h=l.defaultSampleSize??0);let g=e.getUint8(o.contentStart)===1?Number(e.getBigUint64(o.contentStart+4,!1)):e.getUint32(o.contentStart+4,!1),_=e.getUint32(s.contentStart,!1)&16777215,v=s.offset+s.size,y=s.contentStart+4;if(y+4>v)return;let b=e.getUint32(y,!1);if(y+=4,b===0||b>1e4)return;let x=0;if(_&1){if(y+4>v)return;x=e.getInt32(y,!1),y+=4}_&4&&(y+=4);let S;S=d?n:p===null?r.offset:p;let C=S+(_&1?x:0),w=g;for(let t=0;t<b;t++){let t=m,n=h,r=0;if(_&256){if(y+4>v)break;t=e.getUint32(y,!1),y+=4}if(_&512){if(y+4>v)break;n=e.getUint32(y,!1),y+=4}if(_&1024){if(y+4>v)break;r=e.getUint32(y,!1),y+=4}let a=0;if(_&2048){if(y+4>v)break;a=e.getInt32(y,!1),y+=4}if(t<=0&&l.kind===`audio`){let e=this.audioConfig?.sampleRate??l.timescale;t=Math.round(1024*l.timescale/e)}if(n<=0)continue;if(C+n>i.byteLength)break;let o=i.slice(C,C+n);C+=n;let s=this.ticksToMs(w,l.timescale),c=this.ticksToMs(w+a,l.timescale),u=c-s,d=l.kind!==`video`||!(r>>16&1)||this.isAvccKeyFrame(o)?`key`:`delta`;if(l.kind===`video`){let e=this.splitAvccNalus(o);this.on.chunk?.({kind:`video`,type:d,dts:s,pts:c,cts:u,data:o,nalus:e})}else this.on.chunk?.({kind:`audio`,type:`key`,dts:s,pts:c,cts:u,data:o});w+=t}};parseProgressive=(e,t,n)=>{let r=Z(e,0,n.byteLength,`moov`);if(!r)return;let i=[];X(e,r.contentStart,r.offset+r.size,t=>{if(t.type!==`trak`)return;let r=this.collectProgressiveTrackSamples(e,t,n);i.push(...r)}),i.sort((e,t)=>e.dts-t.dts||(e.kind===`video`?-1:1));for(let e of i)this.on.chunk?.(e)};collectProgressiveTrackSamples=(e,t,n)=>{let r=[],i=Z(e,t.contentStart,t.offset+t.size,`tkhd`),a=Z(e,t.contentStart,t.offset+t.size,`mdia`);if(!i||!a)return r;let o=e.getUint32(i.contentStart+(e.getUint8(i.contentStart)===1?20:12),!1),s=this.tracks.get(o);if(!s)return r;let c=Z(e,a.contentStart,a.offset+a.size,`minf`),l=c&&Z(e,c.contentStart,c.offset+c.size,`stbl`);if(!l)return r;let u=Z(e,l.contentStart,l.offset+l.size,`stsz`),d=Z(e,l.contentStart,l.offset+l.size,`stco`),f=Z(e,l.contentStart,l.offset+l.size,`co64`),p=Z(e,l.contentStart,l.offset+l.size,`stsc`),m=Z(e,l.contentStart,l.offset+l.size,`stts`),h=Z(e,l.contentStart,l.offset+l.size,`stss`),g=Z(e,l.contentStart,l.offset+l.size,`ctts`);if(!u||!d&&!f||!m)return r;let _=e.getUint32(u.contentStart+4,!1),v=e.getUint32(u.contentStart+8,!1),y=this.readCttsOffsets(e,g,v),b=d?e.getUint32(d.contentStart+4,!1):e.getUint32(f.contentStart+4,!1),x=t=>d?e.getUint32(d.contentStart+8+(t-1)*4,!1):Number(e.getBigUint64(f.contentStart+8+(t-1)*8,!1)),S=new Set;if(h){let t=e.getUint32(h.contentStart+4,!1);for(let n=0;n<t;n++)S.add(e.getUint32(h.contentStart+8+n*4,!1))}let C=[];if(p){let t=e.getUint32(p.contentStart+4,!1);for(let n=0;n<t;n++){let t=p.contentStart+8+n*12;C.push({firstChunk:e.getUint32(t,!1),samplesPerChunk:e.getUint32(t+4,!1)})}}let w=e=>{if(C.length===0)return v===b?1:Math.max(1,Math.ceil(v/b));let t=C[0].samplesPerChunk;for(let n of C)if(n.firstChunk<=e)t=n.samplesPerChunk;else break;return t},T=0,E=m.contentStart+8,D=e.getUint32(m.contentStart+4,!1),O=0,k=D>0?e.getUint32(E,!1):0,A=D>0?e.getUint32(E+4,!1):0;E+=8;let j=1;for(let t=1;t<=b&&j<=v;t++){let i=w(t),a=x(t);for(let t=0;t<i&&j<=v;t++,j++){let t=_===0?e.getUint32(u.contentStart+12+(j-1)*4,!1):_;if(a+t>n.byteLength)return r;let i=n.slice(a,a+t);a+=t;let o=this.ticksToMs(T,s.timescale),c=y[j-1]??0,l=this.ticksToMs(T+c,s.timescale),d=l-o,f=s.kind===`video`?this.isAvccKeyFrame(i)||S.has(j)||S.size===0:!0;s.kind===`video`?r.push({kind:`video`,type:f?`key`:`delta`,dts:o,pts:l,cts:d,data:i,nalus:this.splitAvccNalus(i)}):r.push({kind:`audio`,type:`key`,dts:o,pts:l,cts:d,data:i}),T+=A,--k,k===0&&O+1<D&&(O+=1,E=m.contentStart+8+O*8,k=e.getUint32(E,!1),A=e.getUint32(E+4,!1))}}return r};isAvccKeyFrame=e=>{let t=0,n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;t+4<=e.byteLength;){let r=n.getUint32(t,!1);if(r<=0||t+4+r>e.byteLength)break;if((e[t+4]&31)==5)return!0;t+=4+r}return!1};splitAvccNalus=e=>{let t=[],n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+4<=e.byteLength;){let i=r.getUint32(n,!1);if(i<=0||n+4+i>e.byteLength)break;t.push(e.slice(n,n+4+i)),n+=4+i}return t}},ie=class{pattern;cacher=new B;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case`flv`:this.parser=new G;break;case`hls`:this.parser=new ee;break;case`dash`:case`mp4`:this.parser=new re;break;default:throw Error(`is error pattern.`)}this.parser.on.info=e=>this.on.info&&this.on.info(e),this.parser.on.config=e=>this.on.config&&this.on.config(e),this.parser.on.chunk=e=>{this.cacher.pushChunk(e),this.on.chunk&&this.on.chunk(e)}};push=e=>{this.cacher.push(e),this.isParseing===!1&&this.parse()};destroy=()=>{this.cacher.destroy(),this.isParseing=!1,this.offset=0};parse=async()=>{try{if(this.isParseing=!0,!this.pattern)throw Error(`You need to set the pattern.`);if(!this.parser)throw Error(`You need to init parser.`);for(;;){let e=this.cacher.next(this.offset);if(this.offset=0,!e)break;try{let t=await this.parser.parse(e);if(this.pattern===`mp4`||this.pattern===`dash`){let t=this.parser;this.offset=t.getDiscardOffset(e.byteLength,e)}else this.offset=t}catch{this.cacher.discardPayload();continue}}this.isParseing=!1}catch{this.isParseing=!1,this.cacher.discardPayload()}}},ae=class{pattern=`flv`;audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;baseTime=0;pendingChunks=[];currentChunk;isProcessing=!1;decodeTimer=0;frameTrack=!1;isFrameTrack=!1;fameTrackOption={flv:[30,50],hls:[200,300],dash:[50,100],mp4:[30,50],rtmp:[50,100]};decodingSpeedRatio=1;maxDecodingSpeedRatio=2;decodingSpeed=16;fps=0;firstVideoChunkTimestamp;secondVideoChunkTimestamp;frameStartTime;lastRenderTime;nextRenderTime;on={audio:{},video:{}};constructor(){}init=e=>{this.destroy(),this.pattern=e,this.baseTime=new Date().getTime()-performance.now(),this.initDecodeInterval()};initAudio=async e=>{if(this.audio.destroy(),!(await AudioDecoder.isConfigSupported(e).catch(()=>({supported:!1}))).supported){console.warn(`[Decoder] audio config not supported:`,e.codec,`audio will be skipped`),this.audioDecoderConfig=void 0,this.audioDecoder=void 0;return}this.audioDecoderConfig={...e},this.audioDecoder=new AudioDecoder({output:e=>{let t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:e,playbackRate:t})},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:e=>{this.frameStartTime||=e.timestamp;try{let t=e.timestamp-this.frameStartTime+this.baseTime*1e3,n=new VideoFrame(e,{timestamp:t});if(e.close(),!n.displayWidth||!n.displayHeight){n.close();return}this.on.video.decode?.({timestamp:t,frame:n}),this.currentChunk?.kind===`video`&&this.currentChunk.nalus&&this.on.nalus?.(this.currentChunk.nalus)}catch{e.close()}},error:e=>{this.on.video.error&&this.on.video.error(e)}}),this.videoDecoder.configure(this.videoDecoderConfig)};setFrameTrack=e=>{this.frameTrack=e,this.frameTrack===!1&&(this.decodingSpeedRatio=1)};push=e=>{this.pendingChunks.push(e)};destroy=()=>{this.audio.destroy(),this.video.destroy(),this.pendingChunks=[],this.firstVideoChunkTimestamp=void 0,this.secondVideoChunkTimestamp=void 0,this.frameStartTime=void 0,this.lastRenderTime=void 0,this.nextRenderTime=void 0,clearInterval(this.decodeTimer)};initDecodeInterval=()=>{let e=this.decodingSpeed/this.decodingSpeedRatio,t=this.baseTime+performance.now();if(this.lastRenderTime||=t,this.fps=Math.round(1e3/(t-this.lastRenderTime)),this.lastRenderTime=t,this.nextRenderTime){let t=this.lastRenderTime-this.nextRenderTime;e-=t}this.nextRenderTime=this.lastRenderTime+e,this.decodeTimer=setTimeout(()=>{try{this.decode()}catch(e){console.error(`[Decoder] decode error:`,e)}this.initDecodeInterval()},e)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;this.currentChunk=this.pendingChunks.shift(),this.currentChunk;){let e=this.pendingChunks.length;if(this.frameTrack){let[t,n]=this.fameTrackOption[this.pattern];if(e<=t&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){let n=Math.min(1+(e-t)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(n.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){let{decodingSpeed:t,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:t,decodingSpeedRatio:n,fps:r,cacheLength:e})}let{kind:t,init:n}=this.currentChunk;switch(t){case`audio`:this.decodeAudio(n);break;case`video`:this.decodeVideo(n);break}if(t===`video`)break}this.isProcessing=!1}};decodeAudio=e=>{if(this.audioDecoder)try{let t=new EncodedAudioChunk(e);this.audioDecoder.decode(t)}catch(e){console.warn(`[Decoder] audio decode error (AudioDecoder may be unusable):`,e)}};decodeVideo=e=>{if(this.videoDecoder&&(e.type===`key`&&(this.hasKeyFrame=!0),this.firstVideoChunkTimestamp?this.secondVideoChunkTimestamp||(this.secondVideoChunkTimestamp=e.timestamp,this.decodingSpeed=(this.secondVideoChunkTimestamp-this.firstVideoChunkTimestamp)/1e3):this.firstVideoChunkTimestamp=e.timestamp,this.hasKeyFrame)){let t=new EncodedVideoChunk(e);this.videoDecoder.decode(t)}};audio={flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}},oe=class{renderMap=new Map;constructor(){}push=async e=>{let t=e.frame,n=t.timestamp;try{let e=[...this.renderMap.entries()].filter(([,e])=>e&&!e.pause);if(e.length===1&&e[0][0]==="default"&&e[0][1].writer){e[0][1].writer.write(t).catch(()=>{}),t.close();return}for(let[r,i]of e){let{writer:e,offscreen:a,option:o}=i;if(e){let i;if(r==="default"||!o)i=new VideoFrame(t,{timestamp:n});else{let{sx:e=0,sy:r=0,sw:a=t.displayWidth,sh:s=t.displayHeight}=o;i=new VideoFrame(t,{visibleRect:{x:e,y:r,width:a,height:s},displayWidth:a,displayHeight:s,timestamp:n})}e.write(i).catch(()=>{}),i.close()}else if(a)if(r==="default"||!o)a.width=t.displayWidth,a.height=t.displayHeight,a.getContext(`2d`)?.drawImage(t,0,0);else{let{sx:e=0,sy:n=0,sw:r=t.displayWidth,sh:i=t.displayHeight}=o;a.width=r,a.height=i,a.getContext(`2d`)?.drawImage(t,e,n,r,i,0,0,r,i)}}}catch{}t.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,cutOption:i}={key:`default`,...e},a=this._getSafeSize(i);if(n){let e=n.getWriter();this.renderMap.set(t,{writer:e,option:a,pause:!1})}else this.renderMap.set(t,{offscreen:r,option:a,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{let{key:t,cutOption:n}={key:`default`,...e},r=this.renderMap.get(t);if(r){let e=this._getSafeSize(n);this.renderMap.set(t,{...r,option:e})}};setPause=e=>{let{key:t,pause:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,pause:n})};_getSafeSize=e=>{let t={...e};return t.sx%2!=0&&(t.sx+=1),t.sy%2!=0&&(t.sy+=1),t.sw%2!=0&&--t.sw,t.sh%2!=0&&--t.sh,t};destroy=()=>{this.renderMap=new Map}};e.Decoder=ae,e.DecoderWorker=u,e.Demuxer=ie,e.DemuxerWorker=a,e.PrPlayer=z,e.Render=oe,e.RenderWorker=h,e.buildSegmentUrl=P,e.parseMpd=L,e.resolveUrl=M});
|
package/dist/render/Render.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ export declare class Render {
|
|
|
13
13
|
key?: string;
|
|
14
14
|
writable: any;
|
|
15
15
|
offscreen?: OffscreenCanvas;
|
|
16
|
-
|
|
16
|
+
cutOption: CutOption;
|
|
17
17
|
}) => void;
|
|
18
18
|
/**
|
|
19
19
|
* 删除剪切
|
|
@@ -33,5 +33,6 @@ export declare class Render {
|
|
|
33
33
|
key?: string;
|
|
34
34
|
pause: boolean;
|
|
35
35
|
}) => void;
|
|
36
|
+
private _getSafeSize;
|
|
36
37
|
destroy: () => void;
|
|
37
38
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pr-player",
|
|
3
3
|
"description": "对 flv hls dash mp4 格式的地址进行解析 并输出 MediaStream,提供 demuxer 层(info、chunk)回调、 decoder 层(audio、video、sei)回调 ,提供 cut 等相关能力,以支持根据业务层 SEI 对视频进行剪切渲染。",
|
|
4
|
-
"version": "0.5.
|
|
4
|
+
"version": "0.5.3",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
7
7
|
"dist"
|
|
@@ -24,9 +24,9 @@
|
|
|
24
24
|
"pr-fetch": "^0.0.4"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
|
-
"typescript": "^6.0.
|
|
28
|
-
"vite": "^8.
|
|
29
|
-
"vite-plugin-dts": "^5.0.
|
|
27
|
+
"typescript": "^6.0.3",
|
|
28
|
+
"vite": "^8.1.3",
|
|
29
|
+
"vite-plugin-dts": "^5.0.3"
|
|
30
30
|
},
|
|
31
31
|
"private": false,
|
|
32
32
|
"author": "Breathe",
|