pr-player 0.3.5 → 0.3.6

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/dist/index.js CHANGED
@@ -104,7 +104,7 @@ class N {
104
104
  this.worker.postMessage({ action: "destroy" }), this.worker.terminate();
105
105
  };
106
106
  }
107
- const S = `(function(){"use strict";class l{renderMap=new Map;constructor(){}push=async t=>{const{timestamp:s}=t,{bitmap:e}=t;if(e.height===0||e.width===0)return e.close();try{const n=[...this.renderMap.keys()];for(const i of n){const a=this.renderMap.get(i);if(!a)continue;const{pause:y=!1,writer:h,offscreen:c,option:u}=a;if(y===!0)continue;const f=r=>{if(h){const o=new VideoFrame(r,{timestamp:s});try{o&&h.write(o)}catch{}o.close()}else c&&(c.width=r.width,c.height=r.height,c?.getContext("2d")?.drawImage(r,0,0))};if(i==="default")f(e);else if(u){const{sx:r=0,sy:o=0,sw:p=e.width,sh:g=e.height}=u,M=await createImageBitmap(e,r,o,p,g);f(M)}}}catch{}e.close()};addCut=t=>{const{key:s,writable:e,offscreen:n,option:i}={key:"default",...t};if(e){const a=e.getWriter();this.renderMap.set(s,{writer:a,option:i,pause:!1})}else this.renderMap.set(s,{offscreen:n,option:i,pause:!1})};delCut=t=>{this.renderMap.delete(t)};setCut=t=>{const{key:s,cutOption:e}={key:"default",...t},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,option:e})};setPause=t=>{const{key:s,pause:e}={key:"default",...t},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,pause:e})};destroy=()=>{this.renderMap=new Map}}const w=new l;onmessage=d=>{const{action:t,data:s}=d.data,e=w[t];e&&e(s)}})();
107
+ const S = `(function(){"use strict";class w{renderMap=new Map;constructor(){}push=async t=>{const{timestamp:s}=t,{bitmap:e}=t;try{const n=[...this.renderMap.keys()];for(const a of n){const i=this.renderMap.get(a);if(!i)continue;const{pause:y=!1,writer:u,offscreen:o,option:f}=i;if(y===!0)continue;const h=async r=>{if(u){const c=new VideoFrame(r,{timestamp:s});try{await u.write(c)}catch{}c.close()}else o&&(o.width=r.width,o.height=r.height,o?.getContext("2d")?.drawImage(r,0,0))};if(a==="default")await h(e);else if(f){const{sx:r=0,sy:c=0,sw:p=e.width,sh:M=e.height}=f,g=await createImageBitmap(e,r,c,p,M);await h(g)}}}catch{}e.close()};addCut=t=>{const{key:s,writable:e,offscreen:n,option:a}={key:"default",...t};if(e){const i=e.getWriter();this.renderMap.set(s,{writer:i,option:a,pause:!1})}else this.renderMap.set(s,{offscreen:n,option:a,pause:!1})};delCut=t=>{this.renderMap.delete(t)};setCut=t=>{const{key:s,cutOption:e}={key:"default",...t},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,option:e})};setPause=t=>{const{key:s,pause:e}={key:"default",...t},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,pause:e})};destroy=()=>{this.renderMap=new Map}}const l=new w;onmessage=d=>{const{action:t,data:s}=d.data,e=l[t];e&&e(s)}})();
108
108
  `, C = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", S], { type: "text/javascript;charset=utf-8" });
109
109
  function L(g) {
110
110
  let t;
@@ -668,7 +668,7 @@ class Q {
668
668
  * 初始化
669
669
  */
670
670
  init = (t) => {
671
- this.initDecoder(t), this.initRender(), this.initDemuxer(t), this.audioPlayer = new B(), this.audioPlayer.init();
671
+ this.initRender(), this.initDecoder(t), this.initDemuxer(t), this.audioPlayer = new B(), this.audioPlayer.init();
672
672
  };
673
673
  /**
674
674
  * 初始化解复器
@@ -1635,7 +1635,6 @@ class tt {
1635
1635
  }
1636
1636
  push = async (t) => {
1637
1637
  const { timestamp: s } = t, { bitmap: e } = t;
1638
- if (e.height === 0 || e.width === 0) return e.close();
1639
1638
  try {
1640
1639
  const n = [...this.renderMap.keys()];
1641
1640
  for (const i of n) {
@@ -1643,21 +1642,21 @@ class tt {
1643
1642
  if (!o) continue;
1644
1643
  const { pause: a = !1, writer: r, offscreen: d, option: c } = o;
1645
1644
  if (a === !0) continue;
1646
- const h = (l) => {
1645
+ const h = async (l) => {
1647
1646
  if (r) {
1648
1647
  const u = new VideoFrame(l, { timestamp: s });
1649
1648
  try {
1650
- u && r.write(u);
1649
+ await r.write(u);
1651
1650
  } catch {
1652
1651
  }
1653
1652
  u.close();
1654
1653
  } else d && (d.width = l.width, d.height = l.height, d?.getContext("2d")?.drawImage(l, 0, 0));
1655
1654
  };
1656
1655
  if (i === "default")
1657
- h(e);
1656
+ await h(e);
1658
1657
  else if (c) {
1659
1658
  const { sx: l = 0, sy: u = 0, sw: p = e.width, sh: f = e.height } = c, m = await createImageBitmap(e, l, u, p, f);
1660
- h(m);
1659
+ await h(m);
1661
1660
  }
1662
1661
  }
1663
1662
  } catch {
@@ -1,4 +1,4 @@
1
1
  (function(b,T){typeof exports=="object"&&typeof module<"u"?T(exports):typeof define=="function"&&define.amd?define(["exports"],T):(b=typeof globalThis<"u"?globalThis:b||self,T(b["pr-player"]={}))})(this,(function(b){"use strict";const T='(function(){"use strict";class P{pendingPayloads=[];payload=new Uint8Array(0);chunks=[];push=t=>{this.pendingPayloads.push(t)};next=(t=0)=>{this.payload=this.payload.slice(t);const s=this.pendingPayloads.shift();if(!s)return!1;const e=new Uint8Array(this.payload.byteLength+s.byteLength);return e.set(this.payload,0),e.set(s,this.payload.byteLength),this.payload=e,new DataView(this.payload.buffer)};pushChunk=t=>{this.chunks.push(t),this.chunks.length>100&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.chunks=[]}}const I=(y,t)=>{const s=new Uint8Array(y),e=new Uint8Array(t),n=new Uint8Array(11+s.length+e.length);let a=0;return n[a++]=1,n[a++]=s[1],n[a++]=s[2],n[a++]=s[3],n[a++]=255,n[a++]=225,n[a++]=s.length>>8&255,n[a++]=s.length&255,n.set(s,a),a+=s.length,n[a++]=1,n[a++]=e.length>>8&255,n[a++]=e.length&255,n.set(e,a),n},T=y=>{let t=0;const s=new DataView(y.buffer),e=s.getUint8(t);if(t=t+1,e!==1)throw new Error("Invalid AVC version");const n=s.getUint8(t)&255;t=t+1;const a=s.getUint8(t)&255;t=t+1;const o=s.getUint8(t)&255;t=t+1;const c=`avc1.${Array.from([n,a,o],U=>U.toString(16).padStart(2,"0")).join("")}`,r=(s.getUint8(t)&3)-1;t=t+1;const g=s.getUint8(t)&31;t=t+1;const p=s.getUint16(t,!1);t=t+2;const h=new Uint8Array(s.buffer.slice(t,t+p));t=t+p;const d=s.getUint8(t)&31;t=t+1;const u=s.getUint16(t,!1);t=t+2;const f=new Uint8Array(s.buffer.slice(t,t+u));return t=t+u,{version:e,codec:c,profile:n,compatibility:a,level:o,lengthSizeMinusOne:r,numOfSequenceParameterSets:g,sequenceParameterSetLength:p,sps:h,numOfPictureParameterSets:d,pictureParameterSetLength:u,pps:f}},M=y=>{const t=new Uint8Array(4+y.length);return new DataView(t.buffer).setUint32(0,y.length,!1),t.set(y,4),t},C=y=>{let t=0;for(const n of y)t+=n.length;const s=new Uint8Array(t);let e=0;for(const n of y){const a=n;s.set(a,e),e+=a.length}return s},D=y=>{let t="unknown";switch(y){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};class x{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async t=>{let s=0;for(;!(s+188>t.byteLength);){if(t.getInt8(s)!=71){s++;continue}await this.parsePacket(t,s),s+=188}return s};parsePacket=async(t,s)=>{if(s+188>t.byteLength)throw new Error("Invalid TS packet");if(t.getUint8(s)!==71)throw new Error("Invalid TS packet");let e=s;const n=this.parseHeader(t,e);e+=4;const{transport_error_indicator:a,pid:o,payload_unit_start_indicator:l,adaptation_field_control:i}=n;if(a===1||o===void 0)return;let c=184;if(i===2||i===3){const r=t.getUint8(e);e+=1,this.parseAdaptationField(t,e),e+=r,c-=r}if(i===3&&(c-=1),i===1||i===3){const r=new Uint8Array(t.buffer.slice(e,e+c));if(o===0)return this.parsePAT(t,e);{const{programs:h=[]}=this.pat||{};if(h.find(u=>u.pmt_pid===o))return this.parsePMT(t,e)}const{streams:g=[]}=this.pmt||{},p=g.find(h=>h.elementary_pid===o);if(p){if(l===1){const h=this.payloadMap.get(o);if(h){switch(p.kind){case"audio":{const d=await this.parseAudio(h);this.on.chunk&&this.on.chunk(d)}break;case"video":{const d=await this.parseVideo(h);this.on.chunk&&this.on.chunk(d),await new Promise(u=>setTimeout(()=>u(!0),0))}break}this.payloadMap.delete(o)}}{this.payloadMap.has(o)||this.payloadMap.set(o,new Uint8Array);const h=this.payloadMap.get(o),d=new Uint8Array(h.byteLength+r.byteLength);d.set(h,0),d.set(r,h.byteLength),this.payloadMap.set(o,d)}}}};parseHeader=(t,s)=>{let e=s;const n=t.getUint8(e),a=t.getUint8(e+1),o=t.getUint8(e+2),l=t.getUint8(e+3),i=(a&128)>>7;if(i===1)return{sync_byte:n,transport_error_indicator:i};const c=(a&64)>>6,r=(a&32)>>5,g=(a&31)<<8|o,p=(l&192)>>6,h=l>>4&3,d=l&15;return{sync_byte:n,transport_error_indicator:i,payload_unit_start_indicator:c,transport_priority:r,pid:g,transport_scrambling_control:p,adaptation_field_control:h,continuity_counter:d}};parsePAT=(t,s)=>{let e=s,n;{const l=t.getUint8(e);e+=1;const i=t.getUint8(e);if(e+=1,i!==0)throw new Error("Invalid PAT table_id");const c=t.getUint16(e)&4095;e+=2;const r=t.getUint16(e);e+=2;const g=(t.getUint8(e)&62)>>1,p=t.getUint8(e)&1;e+=1;const h=t.getUint8(e);e+=1;const d=t.getUint8(e);e+=1,n={pointer_field:l,table_id:i,section_length:c,transport_stream_id:r,version_number:g,current_next_indicator:p,section_number:h,last_section_number:d}}const a=[];{const l=n.section_length-5-4,i=e+l;for(;e<i;){const c=t.getUint16(e),r=t.getUint16(e+2)&8191;e+=4,c!==0&&r>=32&&r<=8190&&a.push({program_number:c,pmt_pid:r})}}const o=t.getUint32(e);this.pat={header:n,programs:a,crc32:o},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(t,s)=>{let e=s,n;{const l=t.getUint8(e);e+=1;const i=t.getUint8(e);if(e+=1,i!==2)throw new Error("Invalid PMT table_id");const c=t.getUint16(e)&4095;e+=2;const r=t.getUint16(e);e+=2;const g=(t.getUint8(e)&62)>>1,p=t.getUint8(e)&1;e+=1;const h=t.getUint8(e);e+=1;const d=t.getUint8(e);e+=1;const u=t.getUint16(e)&8191;e+=2;const f=t.getUint16(e)&4095;e+=2,n={pointer_field:l,table_id:i,section_length:c,transport_stream_id:r,version_number:g,current_next_indicator:p,section_number:h,last_section_number:d,pcr_pid:u,program_info_length:f}}const a=[];{const l=n.section_length-9-4,i=e+l;for(;e<i;){const c=t.getUint8(e),r=D(c),g=t.getUint16(e+1)&8191,p=t.getUint16(e+3)&4095;if(e+=5,g<32||g>8190){console.warn(`Invalid elementary_pid: 0x${g.toString(16)}`);continue}a.push({kind:r,stream_type:c,elementary_pid:g,es_info_length:p})}}const o=t.getUint32(e);this.pmt={header:n,streams:a,crc32:o},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(t,s)=>{let e=s,n,a,o,l;const i=t.getUint8(e),c=!!(i&128),r=!!(i&64),g=!!(i&32),p=!!(i&16),h=!!(i&8),d=!!(i&4),u=!!(i&2),f=!!(i&1);e+=1;const U=(_,b)=>{let m=BigInt(0);m|=BigInt(_.getUint16(b))<<25n,m|=BigInt(_.getUint16(b+1))<<17n,m|=BigInt(_.getUint16(b+2))<<9n,m|=BigInt(_.getUint16(b+3))<<1n,m|=BigInt(_.getUint16(b+4)>>7);const S=(_.getUint16(b+4)&1)<<8|_.getUint16(b+5);return m=m*300n+BigInt(S),m};if(p&&(n=U(t,e),e+=6),h&&(a=U(t,e),e+=6),d&&(o=t.getInt8(e),e+=1),u){const _=t.getUint8(e);e+=1,l=new Uint8Array(t.buffer,e,_),e+=_}return{discontinuity_indicator:c,random_access_indicator:r,elementary_stream_priority_indicator:g,pcr_flag:p,opcr_flag:h,splicing_point_flag:d,transport_private_data_flag:u,adaptation_field_extension_flag:f,pcr:n,opcr:a,splice_countdown:o,transport_private_data:l}};parseAudio=async t=>{const s=new DataView(t.buffer);let e=0,n,a;{const o=s.getUint8(e)===0&&s.getUint8(e+1)===0&&s.getUint8(e+2)===1;if(e+=3,!o)throw new Error("invalid ts audio payload.");const l=s.getUint8(e);e+=1;const i=s.getUint8(e)<<8|s.getUint8(e+1);e+=2;let c,r,g,p,h;{const f=s.getUint8(e);e+=1,c=f>>4&3,r=(f>>3&1)===1,g=(f>>2&1)===1,p=(f>>1&1)===1,h=(f&1)===1}let d,u;{const f=s.getUint8(e);e+=1;const U=f>>6,_=s.getUint8(e);e+=1,(U&2)===2&&(d=this.parsePtsDts(s,e)),(U&1)===1?u=this.parsePtsDts(s,e+5):u=d,e+=_}n={stream_id:l,pes_packet_length:i,scrambling_control:c,priority:r,data_alignment:g,copyright:p,original_copy:h,pts:d,dts:u}}a=t.slice(e);{if(!this.audioConfig&&s.getUint8(e)===255){const g=s.getUint8(e+2),p=s.getUint8(e+3);let h,d;d=g>>2&15,h=(g&1)<<2|p>>6;const u=`mp4a.40.${h}`,U=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][d];this.audioConfig={kind:"audio",codec:u,sampleRate:U,numberOfChannels:h},this.on.config&&this.on.config(this.audioConfig)}const{dts:o=0,pts:l=0}=n,i=l-o,c=a.slice(7);return{kind:"audio",type:"key",dts:o,pts:l,cts:i,data:c}}};parseVideo=async t=>{const s=new DataView(t.buffer);let e=0,n,a;{const o=s.getUint8(e)===0&&s.getUint8(e+1)===0&&s.getUint8(e+2)===1;if(e+=3,!o)throw new Error("invalid ts video payload.");const l=s.getUint8(e);e+=1;const i=s.getUint8(e)<<8|s.getUint8(e+1);e+=2;let c,r,g,p,h;{const f=s.getUint8(e);e+=1,c=f>>4&3,r=(f>>3&1)===1,g=(f>>2&1)===1,p=(f>>1&1)===1,h=(f&1)===1}let d,u;{const f=s.getUint8(e);e+=1;const U=f>>6,_=s.getUint8(e);e+=1,(U&2)===2&&(d=this.parsePtsDts(s,e)),(U&1)===1?u=this.parsePtsDts(s,e+5):u=d,e+=_}n={stream_id:l,pes_packet_length:i,scrambling_control:c,priority:r,data_alignment:g,copyright:p,original_copy:h,pts:d,dts:u}}a=t.slice(e);{const o=this.getNalus(a);if(!this.videoConfig){let h,d;if(h=o.find(f=>f.type===7)?.nalu.slice(4),d=o.find(f=>f.type===8)?.nalu.slice(4),h&&d){const u=I(h,d),{codec:f}=T(u);this.videoConfig={kind:"video",codec:f,description:u,sps:h,pps:d},this.on.config&&this.on.config(this.videoConfig)}}const l=[];let i="delta";for(const h of o){const{type:d,nalu:u}=h;switch(d){case 6:case 9:l.push(u);break;case 1:i="delta",l.push(u);break;case 5:i="key",l.push(u);break}}const c=C(l),{dts:r=0,pts:g=0}=n,p=g-r;return{kind:"video",type:i,dts:r,pts:g,cts:p,data:c,nalus:l}}};parsePtsDts(t,s){const e=t.getUint8(s),n=t.getUint8(s+1),a=t.getUint8(s+2),o=t.getUint8(s+3),l=t.getUint8(s+4),i=(BigInt(e)&0b00001110n)<<29n|(BigInt(n)&0b11111111n)<<22n|(BigInt(a)&0b11111110n)<<14n|(BigInt(o)&0b11111111n)<<7n|(BigInt(l)&0b11111110n)>>1n;return Number(i)/90}getNalus=t=>{const s=[];let e=0;for(;!(e+4>t.byteLength);){if(t[e]!==0||t[e+1]!==0||t[e+2]!==1){e+=1;continue}e+=3;let n=e;const a=t[e]&31;for(e+=1;!(e+1>t.byteLength);){if(t[e]!==0||t[e+1]!==0||t[e+2]!==1){e+=1;continue}break}let o=e-n;if(t[e-1]===0&&(o-=1),o!==0){const l=t.slice(n,n+o),i=M(l);s.push({type:a,nalu:i})}}return s}}const k=(y,t)=>y.getUint8(t)<<16|y.getUint8(t+1)<<8|y.getUint8(t+2);class L{audioConfig;videoConfig;header;textDecoder=new TextDecoder("utf-8");on={};constructor(){}parse=async t=>{let s=0;for(this.header||(this.parseHeader(t,s),s+=9);this.isSurplusTag(t,s)!==!1;){const n=this.parseTagHeader(t,s+4),{tagType:a,dataSize:o,timestamp:l}=n;if(a){const i=this.parseTagBody(a,t,s+4+11,o);switch(a){case"script":this.on.info&&this.on.info(i);break;case"audio":{const{accPacketType:c}=i;if(c===0){const{codec:r,sampleRate:g,channelConfiguration:p}=i;this.audioConfig={kind:"audio",codec:r,sampleRate:g,numberOfChannels:p},this.on.config&&this.on.config(this.audioConfig)}else{const{cts:r,data:g}=i,p="key",h=r===void 0?void 0:r+l;this.on.chunk&&this.on.chunk({kind:"audio",type:p,dts:l,pts:h,cts:r,data:g})}}break;case"video":{const{avcPacketType:c}=i;if(c===0){const{codec:r,sps:g,pps:p,data:h}=i;this.videoConfig={kind:"video",codec:r,description:h,sps:g,pps:p},this.on.config&&this.on.config(this.videoConfig)}else{const{frameType:r,cts:g,data:p,nalus:h}=i,d=r===1?"key":"delta",u=g===void 0?void 0:g+l;this.on.chunk&&this.on.chunk({kind:"video",type:d,dts:l,pts:u,cts:g,data:p,nalus:h})}}break}s=s+4+11+o}await new Promise(i=>setTimeout(()=>i(!0),8))}return s};parseHeader=(t,s)=>{let e,n,a,o;e=t.getUint8(s)<<16|t.getUint8(s+1)<<8|t.getUint8(s+2),n=t.getUint8(3);{const i=t.getUint8(0).toString(2).padStart(5,"0").split(""),[,,c,,r]=i;a={audio:r==="1",video:c==="1"}}o=t.getUint32(5),this.header={signature:e,version:n,flags:a,dataOffset:o}};isSurplusTag=(t,s)=>{let e=!0;const n=t.byteLength;if(s+4>n)e=!1;else if(s+4+11>n)e=!1;else{const a=k(t,s+4+1);s+4+11+a>n&&(e=!1)}return e};parseTagHeader=(t,s)=>{let e,n,a,o,l;{const i=t.getUint8(s);let c;switch(i){case 18:c="script";break;case 8:c="audio";break;case 9:c="video";break}e=c}return n=k(t,s+1),a=k(t,s+4),o=t.getUint8(s+7),l=k(t,s+8),{tagType:e,dataSize:n,timestamp:a,timestampExtended:o,streamID:l}};parseTagBody=(t,s,e,n)=>{let a;switch(t){case"script":a=this.parseMetaData(s,e);break;case"audio":a=this.parseAudio(s,e,n);break;case"video":a=this.parseVideo(s,e,n);break}return a};parseMetaData=(t,s)=>{let e=s;{if(t.getUint8(e)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");e=e+1}const n=t.getUint16(e,!1);e=e+2;{const l=new Int8Array(t.buffer.slice(e,e+n));if((this.textDecoder?.decode(l)||"")!=="onMetaData")throw new Error("Expected \'onMetaData\' string");e=e+n}const a=this.getAmfType(t,e);return e=e+1,this.getAMFValue(t,e,a).value};parseAudio=(t,s,e)=>{let n=s;const a=t.getUint8(n),o=a>>4&15,l=a>>2&3,i=a>>1&1,c=a&1;n=n+1;const r=t.getUint8(n);n=n+1;const g=e,p=new Uint8Array(t.buffer.slice(n,n+g));if(o===10&&r===0){const h=t.getUint8(n),d=t.getUint8(n+1),u=h>>3&31,f=(h&7)<<1|d>>7,U=d>>3&15,_=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],b=`mp4a.40.${u}`,m=_[f];return{soundFormat:o,soundRate:l,soundSize:i,soundType:c,accPacketType:r,data:p,samplingFrequencyIndex:f,channelConfiguration:U,codec:b,sampleRate:m}}return{soundFormat:o,soundRate:l,soundSize:i,soundType:c,accPacketType:r,data:p}};parseVideo=(t,s,e)=>{let n=s;const a=t.getUint8(n),o=a>>4&15,l=a&15;n=n+1;const i=t.getUint8(n);n=n+1;const c=k(t,n);n=n+3;const r=e-5,g=new Uint8Array(t.buffer.slice(n,n+r));switch(l){case 7:if(i===0){const p=T(g);return{frameType:o,codecID:l,avcPacketType:i,cts:c,data:g,...p}}else if(i===1){const p=[],h=n+e-5;for(;!(n+4>h);){const d=t.getUint32(n,!1),u=new Uint8Array(t.buffer.slice(n,n+4+d));n+=4+d,p.push(u)}return{frameType:o,codecID:l,avcPacketType:i,cts:c,data:g,nalus:p}}break;default:throw new Error("Unsupported codecID")}return{frameType:o,codecID:l,avcPacketType:i,cts:c,data:g}};getAmfType=(t,s)=>t.getUint8(s);getAMFName=(t,s,e)=>{const n=new Uint8Array(t.buffer.slice(s,s+e));return this.textDecoder?.decode(n)||""};getAMFValue=(t,s,e)=>{let n=s,a,o=0;switch(e){case 0:a=t.getFloat64(n,!1),o=8;break;case 1:a=!!t.getUint8(n),o=1;break;case 2:{a="";const i=t.getUint16(n,!1);n=n+2;const c=new Int8Array(t.buffer,n,i).filter(g=>g!==0);a=(this.textDecoder?.decode(c)||"").trim(),o=2+i}break;case 3:for(a={};n<t.byteLength;){const i=t.getUint16(n,!1);if(i===0)break;n=n+2;const c=this.getAMFName(t,n,i);n=n+i;const r=this.getAmfType(t,n);if(r===6)break;n=n+1;const g=this.getAMFValue(t,n,r);n=n+g.length,a[c]=g.value,o=2+i+1+g.length}break;case 8:{a={};const i=t.getUint32(n,!1);n=n+4;for(let c=0;c<i;c++){const r=t.getUint16(n,!1);n=n+2;const g=this.getAMFName(t,n,r);n=n+r;const p=this.getAmfType(t,n);n=n+1;const h=this.getAMFValue(t,n,p);n=n+h.length,a[g]=h.value,o=2+r+1+h.length}}break;case 10:{a=[];const i=t.getUint32(n,!1);n=n+4;for(let c=0;c<i;c++){const r=this.getAmfType(t,n);n=n+1;const g=this.getAMFValue(t,n,r);n=n+g.length,a.push(g.value),o=1+g.length}}break}return{amfType:e,length:o,value:a}}}class O{pattern;cacher=new P;isParseing=!1;offset=0;parser;on={};constructor(){}init=t=>{switch(this.destroy(),this.pattern=t,this.pattern){case"flv":this.parser=new L;break;case"hls":this.parser=new x;break;default:throw new Error("is error pattern.")}this.parser.on.debug=s=>this.on.debug&&this.on.debug(s),this.parser.on.info=s=>this.on.info&&this.on.info(s),this.parser.on.config=s=>this.on.config&&this.on.config(s),this.parser.on.chunk=s=>{this.cacher.pushChunk(s),this.on.chunk&&this.on.chunk(s)}};push=t=>{this.cacher.push(t),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 new Error("You need to set the pattern.");if(!this.parser)throw new Error("You need to init parser.");for(;;){const t=this.cacher.next(this.offset);if(this.offset=0,!t)break;this.offset=await this.parser.parse(t)}this.isParseing=!1}catch{this.destroy()}}}const A=new O;A.on.info=y=>postMessage({action:"on.info",data:y}),A.on.config=y=>postMessage({action:"on.config",data:y}),A.on.chunk=y=>postMessage({action:"on.chunk",data:y}),A.on.debug=y=>postMessage({action:"on.debug",data:y}),onmessage=y=>{const{action:t,data:s}=y.data,e=A[t];e&&e(s)}})();\n',C=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",T],{type:"text/javascript;charset=utf-8"});function N(g){let e;try{if(e=C&&(self.URL||self.webkitURL).createObjectURL(C),!e)throw"";const s=new Worker(e,{name:g?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(T),{name:g?.name})}}class v{worker=new N;on={};constructor(){this.worker.onmessage=e=>{const{action:s,data:t}=e.data;switch(s){case"on.info":this.on.info&&this.on.info(t);break;case"on.config":this.on.config&&this.on.config(t);break;case"on.chunk":this.on.chunk&&this.on.chunk(t);break;case"on.debug":this.on.debug&&this.on.debug(t);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()}}const A=`(function(){"use strict";class a{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],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=e=>{this.audio.destroy(),this.audioDecoderConfig={...e},this.audioDecoder=new AudioDecoder({output:i=>{const o=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:i,playbackRate:o})},error:i=>{this.on.audio.error&&this.on.audio.error(i)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:async i=>{this.frameStartTime||(this.frameStartTime=i.timestamp);try{const o=i.timestamp-this.frameStartTime+this.baseTime*1e3,s=await createImageBitmap(i);if(i.close(),!s.width||!s.height)return s.close();this.on.video.decode&&this.on.video.decode({timestamp:o,bitmap:s}),this.currentChunk&&this.currentChunk.kind==="video"&&this.currentChunk.nalus&&this.on.nalus&&this.on.nalus(this.currentChunk.nalus)}catch{i.close()}},error:i=>{this.on.video.error&&this.on.video.error(i)}}),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;const i=this.baseTime+performance.now();if(this.lastRenderTime||(this.lastRenderTime=i),this.fps=Math.round(1e3/(i-this.lastRenderTime)),this.lastRenderTime=i,this.nextRenderTime){const o=this.lastRenderTime-this.nextRenderTime;e-=o}this.nextRenderTime=this.lastRenderTime+e,this.decodeTimer=setTimeout(()=>{this.decode(),this.initDecodeInterval()},e)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;this.currentChunk=this.pendingChunks.shift(),!!this.currentChunk;){const e=this.pendingChunks.length;if(this.frameTrack){const[s,n]=this.fameTrackOption[this.pattern];if(e<=s&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){const r=Math.min(1+(e-s)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(r.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){const{decodingSpeed:s,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:s,decodingSpeedRatio:n,fps:r,cacheLength:e})}const{kind:i,init:o}=this.currentChunk;switch(i){case"audio":this.decodeAudio(o);break;case"video":this.decodeVideo(o);break}if(i==="video")break}this.isProcessing=!1}};decodeAudio=e=>{if(!this.audioDecoder)return;const i=new EncodedAudioChunk(e);this.audioDecoder.decode(i)};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)){const i=new EncodedVideoChunk(e);this.videoDecoder.decode(i)}};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}}}const d=new a;d.on.audio.decode=t=>postMessage({action:"on.audio.decode",data:t},[t.audioData]),d.on.audio.error=t=>postMessage({action:"on.audio.error",data:t}),d.on.video.decode=t=>postMessage({action:"on.video.decode",data:t},[t.bitmap]),d.on.video.error=t=>postMessage({action:"on.video.error",data:t}),d.on.nalus=t=>postMessage({action:"on.nalus",data:t}),d.on.analysis=t=>postMessage({action:"on.analysis",data:t}),onmessage=t=>{const{action:e,data:i}=t.data,o=d[e];o&&o(i)}})();
2
- `,x=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",A],{type:"text/javascript;charset=utf-8"});function L(g){let e;try{if(e=x&&(self.URL||self.webkitURL).createObjectURL(x),!e)throw"";const s=new Worker(e,{name:g?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(A),{name:g?.name})}}class S{worker=new L;on={audio:{},video:{}};constructor(){this.worker.onmessage=e=>{const{action:s,data:t}=e.data;switch(s){case"on.audio.decode":this.on.audio.decode&&this.on.audio.decode(t);break;case"on.audio.error":this.on.audio.error&&this.on.audio.error(t);break;case"on.video.decode":this.on.video.decode&&this.on.video.decode(t);break;case"on.video.error":this.on.video.error&&this.on.video.error(t);break;case"on.nalus":this.on.nalus&&this.on.nalus(t);break;case"on.analysis":this.on.analysis&&this.on.analysis(t);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()}}const M=`(function(){"use strict";class l{renderMap=new Map;constructor(){}push=async t=>{const{timestamp:s}=t,{bitmap:e}=t;if(e.height===0||e.width===0)return e.close();try{const n=[...this.renderMap.keys()];for(const i of n){const a=this.renderMap.get(i);if(!a)continue;const{pause:y=!1,writer:h,offscreen:c,option:u}=a;if(y===!0)continue;const f=r=>{if(h){const o=new VideoFrame(r,{timestamp:s});try{o&&h.write(o)}catch{}o.close()}else c&&(c.width=r.width,c.height=r.height,c?.getContext("2d")?.drawImage(r,0,0))};if(i==="default")f(e);else if(u){const{sx:r=0,sy:o=0,sw:p=e.width,sh:g=e.height}=u,M=await createImageBitmap(e,r,o,p,g);f(M)}}}catch{}e.close()};addCut=t=>{const{key:s,writable:e,offscreen:n,option:i}={key:"default",...t};if(e){const a=e.getWriter();this.renderMap.set(s,{writer:a,option:i,pause:!1})}else this.renderMap.set(s,{offscreen:n,option:i,pause:!1})};delCut=t=>{this.renderMap.delete(t)};setCut=t=>{const{key:s,cutOption:e}={key:"default",...t},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,option:e})};setPause=t=>{const{key:s,pause:e}={key:"default",...t},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,pause:e})};destroy=()=>{this.renderMap=new Map}}const w=new l;onmessage=d=>{const{action:t,data:s}=d.data,e=w[t];e&&e(s)}})();
3
- `,D=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",M],{type:"text/javascript;charset=utf-8"});function V(g){let e;try{if(e=D&&(self.URL||self.webkitURL).createObjectURL(D),!e)throw"";const s=new Worker(e,{name:g?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(M),{name:g?.name})}}class R{worker=new V;constructor(){}push=e=>this.worker.postMessage({action:"push",data:e},[e.bitmap]);addCut=e=>{const s=[];e.writable&&s.push(e.writable),e.offscreen&&s.push(e.offscreen),this.worker.postMessage({action:"addCut",data:e},s)};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()}}class W{inputStream=new MediaStream;outputStream=new MediaStream;inputGain=1;enhanceGain=1;bgsGain=1;bgmGain=1;outputGain=1;mixAudioMap=new Map;audioContext=new AudioContext;sourceNode;inputGainNode;enhanceGainNode;bgsGainNode;bgmGainNode;rnnoiseNode;analyserNode;analyserArrayData;outputGainNode;destinationNode;denoise=!1;mute=!0;rnnoiseWorklet;rnnoiseWorkletNode;filterStream=e=>e;constructor(e,s){this.inputStream=e,s&&(this.audioContext=s),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;{const{sourceNode:t,inputGainNode:n,enhanceGainNode:i,bgsGainNode:o,bgmGainNode:a,analyserNode:r,outputGainNode:d,destinationNode:c}=this;t.connect(n),n.connect(i),i.connect(r),o.connect(r),a.connect(r),i.connect(c),o.connect(c),a.connect(c),d.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=>{const s=this.inputStream.getTracks();for(const t of s)this.inputStream.removeTrack(t);this.inputStream.addTrack(e),this._changeSource()};stop=()=>{{const e=this.inputStream.getTracks();for(const s of e)s.stop(),this.inputStream.removeTrack(s)}};pause=async e=>{const s=this.inputStream.getTracks();for(const t of s)t.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(),this.rnnoiseWorklet.destroy(),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.denoise=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=()=>{const{analyserNode:e,analyserArrayData:s}=this;e.getByteFrequencyData(s);let t=0;for(let n=0;n<s.length;n++)t+=s[n];return Math.ceil(t/s.length)};mixAudio=(e,s="bgm")=>new Promise(async(t,n)=>{try{{const a=this.mixAudioMap.get(s);a&&a.stop()}const i=s==="bgs"?this.bgsGainNode:this.bgmGainNode,o=this.audioContext.createBufferSource();this.mixAudioMap.set(s,o),o.buffer=e,o.connect(i),o.onended=()=>{o.disconnect(i),this.mixAudioMap.delete(s),t(!0)},o.start(0)}catch(i){n(i)}});mixAudioStop=e=>{this.mixAudioMap.get(e)?.stop()};changeMix=(e,s)=>{const t=e==="bgs"?this.bgsGainNode:this.bgmGainNode;s?t.connect(this.destinationNode):t.disconnect(this.destinationNode)}}const F=async(g,e)=>{try{const{format:s,numberOfChannels:t,numberOfFrames:n,sampleRate:i}=e,o=g.createBuffer(t,n,i);for(let a=0;a<t;a++){const r=e.allocationSize({planeIndex:a}),d=new Uint8Array(r);e.copyTo(d,{planeIndex:a});const c=new DataView(d.buffer),h=o.getChannelData(a);for(let l=0;l<n;l++){let u;switch(s){case"s16":case"s16-planar":u=c.getInt16(l*2,!0)/32768;break;case"f32":case"f32-planar":u=c.getFloat32(l*4,!0);break;case"u8":case"u8-planar":u=(c.getUint8(l)-128)/128;break;default:throw new Error(`Unsupported audio format: ${s}`)}h[l]=Math.max(-1,Math.min(1,u))}}return o}catch(s){throw console.error("Failed to convert AudioData to AudioBuffer:",s),s}};class B{prAudioStream;audioContext;destination;stream=new MediaStream;nextStartTime=0;pendingSources=[];constructor(){}init=e=>{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 W(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(e){const{audioData:s,playbackRate:t=1}=e;if(!this.audioContext||!this.destination)return;let n=await F(this.audioContext,s);if(s.close(),!n)return;const i=this.audioContext.createBufferSource();i.buffer=n,i.playbackRate.value=t;const o=-1200*Math.log2(t);i.detune.value=o,i.connect(this.destination);const a=Math.max(this.nextStartTime,this.audioContext.currentTime),r=n.duration/t;this.nextStartTime=a+r,i.start(a),this.pendingSources.push(i),i.onended=()=>{this.pendingSources=this.pendingSources.filter(d=>d!==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.pendingSources.forEach(e=>e.stop()),this.pendingSources=[]}}const G=g=>{const e=g.toLowerCase();return e.includes(".m3u8")||e.includes("hls")||e.includes("master.m3u8")||e.match(/index\d*\.m3u8/)?"hls":e.includes(".mpd")||e.includes("dash")?"dash":e.startsWith("rtmp://")||e.startsWith("rtmps://")?"rtmp":e.includes(".flv")||e.includes("flv")&&!e.includes("flash")?"flv":"unknown"},E=g=>{const e=g?.getTracks()||[];for(const s of e)s.stop()};class O{resolvesMap=new Map;index=0;constructor(){}add=(e,s=()=>!1,t=0)=>new Promise(n=>{if(s())return n(!0);this.resolvesMap.has(e)||this.resolvesMap.set(e,new Map),this.index++;const a=`${this.index}`;if(t=Math.max(0,t),t===0){this.resolvesMap.get(e)?.set(a,{resolve:n,timer:0});return}const r=window.setTimeout(()=>{this.emit(e)},t);this.resolvesMap.get(e)?.set(a,{resolve:n,timer:r})});emit=async e=>{const s=this.resolvesMap.get(e);if(!s)return;const t=[...s.keys()];for(const n of t){const i=s.get(n);i&&(clearTimeout(i.timer),i.resolve(),s.delete(n))}}}const j=(g,e)=>{const s=new Uint8Array(g),t=new Uint8Array(e),n=new Uint8Array(11+s.length+t.length);let i=0;return n[i++]=1,n[i++]=s[1],n[i++]=s[2],n[i++]=s[3],n[i++]=255,n[i++]=225,n[i++]=s.length>>8&255,n[i++]=s.length&255,n.set(s,i),i+=s.length,n[i++]=1,n[i++]=t.length>>8&255,n[i++]=t.length&255,n.set(t,i),n},P=g=>{let e=0;const s=new DataView(g.buffer),t=s.getUint8(e);if(e=e+1,t!==1)throw new Error("Invalid AVC version");const n=s.getUint8(e)&255;e=e+1;const i=s.getUint8(e)&255;e=e+1;const o=s.getUint8(e)&255;e=e+1;const d=`avc1.${Array.from([n,i,o],k=>k.toString(16).padStart(2,"0")).join("")}`,c=(s.getUint8(e)&3)-1;e=e+1;const h=s.getUint8(e)&31;e=e+1;const l=s.getUint16(e,!1);e=e+2;const u=new Uint8Array(s.buffer.slice(e,e+l));e=e+l;const p=s.getUint8(e)&31;e=e+1;const f=s.getUint16(e,!1);e=e+2;const m=new Uint8Array(s.buffer.slice(e,e+f));return e=e+f,{version:t,codec:d,profile:n,compatibility:i,level:o,lengthSizeMinusOne:c,numOfSequenceParameterSets:h,sequenceParameterSetLength:l,sps:u,numOfPictureParameterSets:p,pictureParameterSetLength:f,pps:m}},z=g=>{const e=new Uint8Array(4+g.length);return new DataView(e.buffer).setUint32(0,g.length,!1),e.set(g,4),e},$=g=>{let e=0;for(const n of g)e+=n.length;const s=new Uint8Array(e);let t=0;for(const n of g){const i=n;s.set(i,t),t+=i.length}return s},q=g=>{const e=new DataView(g.buffer);let s=0,t,n,i;t=e.getUint32(s,!1),s+=4;{const o=e.getUint8(s),a=o>>7&1,r=o>>5&3,d=o&31;n={forbidden_zero_bit:a,nal_ref_idc:r,nal_unit_type:d},s+=1}{const o=t-1;i=new Uint8Array(e.buffer.slice(s,s+o))}return{size:t,header:n,data:i}};class I{#t={timeout:5*1e3,check:!1};#e=null;constructor(e={}){this.#t={...this.#t,...e}}#s=(e,s)=>new Promise(async t=>{this.#e=new AbortController;const{signal:n}=this.#e,i=this.#t.timeout,o=setTimeout(()=>{this.#e?.abort(`Timeout (${i}ms)`)},i);await fetch(e,{cache:"no-store",...s,method:"HEAD",signal:n}).then(a=>{clearTimeout(o),t({status:a.status===200?"successed":"failed",reason:a.status===200?"":`HTTP ${a.status}`})}).catch(a=>{if(clearTimeout(o),a.name==="AbortError"){const r=n.reason||"Actively stopped";t({status:r.includes("Timeout")?"timeout":"stopped",reason:r})}else t({status:"error",reason:a.message})})});request=(e,s)=>new Promise(async(t,n)=>{try{this.stop(),this.#t.check&&await this.#s(e),this.#e=new AbortController;const{signal:i}=this.#e,o=await fetch(e,{cache:"no-store",...s,signal:i});t(o)}catch(i){n(i)}});stop=()=>{if(this.#e?.signal.aborted===!1){const e=new Error("Actively stopped.");e.name="AbortError",this.#e.abort(e)}}}class H{option={debug:!1,frameTrack:!1};converter="MediaStreamTrackGenerator"in window?"generator":"canvas";prFetch=new I;getSegmentsFetch=new I;prResolves=new O;url="";start_resolve;demuxerWorker;decoderWorker;audioPlayer;renderWorker;stream;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(e={}){const{debug:s=!1}=e;this.option.debug=s}start=async e=>{await this.stop(),this.url=e;const s=G(e);if(s==="unknown")throw new Error("This address cannot be parsed.");switch(this.init(s),s){case"flv":this.flv.start();break;case"hls":this.hls.start();break}};stop=async()=>{try{this.url="",clearInterval(this.hls.getSegmentsTimer),this.prFetch.stop(),this.getSegmentsFetch.stop(),this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy(),this.cutRenders=new Map,E(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=()=>{const e=()=>this.stream?.active===!0;return this.prResolves.add("isReady",e)};cut={create:(e,s)=>{if(this.converter==="generator"){const o=new MediaStreamTrackGenerator({kind:"video"}),a=new MediaStream([o]);return this.renderWorker?.addCut({key:e,writable:o.writable,option:s}),this.cutRenders.set(e,{stream:a}),a}const t=document.createElement("canvas"),n=t.captureStream(),i=t.transferControlToOffscreen();return this.renderWorker?.addCut({key:e,offscreen:i,option:s}),this.cutRenders.set(e,{stream:n}),n},setCut:(e,s)=>{this.renderWorker?.setCut({key:e,cutOption:s})},getStream:e=>this.cutRenders.get(e)?.stream,remove:e=>{this.renderWorker?.delCut(e),this.cutRenders.delete(e)},setPause:(e,s)=>{this.renderWorker?.setPause({key:e,pause:s})}};init=e=>{this.initDecoder(e),this.initRender(),this.initDemuxer(e),this.audioPlayer=new B,this.audioPlayer.init()};initDemuxer=e=>{this.demuxerWorker=new v,this.demuxerWorker.init(e),this.demuxerWorker.on.debug=s=>{this.option.debug&&this.on.debug&&this.on.debug(s)},this.demuxerWorker.on.info=s=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: info",s),this.on.demuxer.info&&this.on.demuxer.info(s)},this.demuxerWorker.on.config=s=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: config",s),this.on.demuxer.config&&this.on.demuxer.config(s);const{kind:t}=s;switch(t){case"audio":{const{codec:n,sampleRate:i,numberOfChannels:o}=s;this.decoderWorker?.initAudio({codec:n,sampleRate:i,numberOfChannels:o})}break;case"video":{const{codec:n,description:i}=s;this.decoderWorker?.initVideo({codec:n,description:i})}break}},this.demuxerWorker.on.chunk=s=>{if(this.on.demuxer.chunk&&this.on.demuxer.chunk(s),!this.decoderWorker)return;const{kind:t}=s;switch(t){case"audio":{const{type:n,dts:i,data:o}=s,a=i*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:a,data:o}})}break;case"video":{const{type:n,dts:i,data:o,nalus:a=[]}=s,r=i*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:r,data:o},nalus:a})}break}}};initDecoder=e=>{this.decoderWorker=new S,this.decoderWorker.init(e);const{frameTrack:s=!1}=this.option;this.decoderWorker.setFrameTrack(s),this.decoderWorker.on.audio.decode=t=>{this.audioPlayer?.push(t),this.on.decoder.audio&&this.on.decoder.audio(t)},this.decoderWorker.on.audio.error=t=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: audio.error ",t),this.on.error&&this.on.error(t)},this.decoderWorker.on.video.decode=async t=>{this.start_resolve&&(this.start_resolve(!0),this.start_resolve=void 0),this.renderWorker?.push(t),this.on.decoder.video&&this.on.decoder.video(t)},this.decoderWorker.on.video.error=t=>{this.on.error&&this.on.error(t)},this.decoderWorker.on.nalus=async t=>{for(const n of t){if(n.byteLength<=4)continue;const{header:i,data:o}=q(n),{nal_unit_type:a}=i;a===6&&this.on.decoder.sei&&this.on.decoder.sei(o)}},this.decoderWorker.on.analysis=t=>{this.on.decoder.analysis&&this.on.decoder.analysis(t)}};initRender=()=>{if(this.renderWorker=new R,this.converter==="generator"){const e=new MediaStreamTrackGenerator({kind:"video"}),s=new MediaStream([e]);this.renderWorker?.addCut({writable:e.writable}),this.stream=s}else{const e=document.createElement("canvas"),s=e.captureStream(),t=e.transferControlToOffscreen();this.renderWorker?.addCut({offscreen:t}),this.stream=s}this.renderWorker?.setPause({pause:!1})};flv={start:()=>new Promise(async(e,s)=>{try{this.start_resolve=e;let t,n=0;for(;;){n+=1;try{t=await this.prFetch.request(this.url)}catch(o){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: error",o)}if(t?.status===200||n===3)break;await new Promise(o=>setTimeout(()=>o(!0),500))}if(!t||t.status!==200)return s("request is error.");const i=t.body?.getReader();if(!i)return s("reader is error.");for(;;){const{done:o,value:a}=await i.read();if(a&&this.demuxerWorker?.push(a),o||this.url==="")break}}catch(t){t.name!=="AbortError"&&s(t)}})};hls={isLive:!1,urls:[],url:"",getSegmentsTimer:0,parse:async e=>{const n=new TextDecoder("utf-8").decode(e).split(`
4
- `).map(c=>c.replace("\r","")),i=this.url.substring(0,this.url.lastIndexOf("/")+1);let o=4,a=0,r=!1;const d=[];for(const c of n)c.startsWith("#EXTINF:")?o=parseFloat(c.split(":")[1].split(",")[0]):c.startsWith("#EXT-X-TARGETDURATION:")?a=parseInt(c.split(":")[1]):c.startsWith("#EXT-X-ENDLIST")?r=!1:c.startsWith("#EXT-X-MEDIA-SEQUENCE:")?r=!0:c.includes(".ts")&&!c.startsWith("#")&&d.push({url:c.startsWith("http")?c:i+c,duration:o,isLive:r});return{baseUrl:i,targetDuration:a,isLive:r,segments:d}},getSegments:async()=>{try{let e,s=0;for(;;){s+=1;try{e=await this.getSegmentsFetch.request(this.url)}catch(n){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: error",n)}if(e?.status===200||s===3)break;await new Promise(n=>setTimeout(()=>n(!0),500))}if(!e||e.status!==200)throw new Error("request is error.");const t=e.body?.getReader();if(!t)throw new Error("reader is error.");for(;;){const{done:n,value:i}=await t.read();if(i){const o=await this.hls.parse(i),{segments:a=[],isLive:r=!1}=o;this.hls.isLive=r,r===!1&&(this.option.frameTrack=!1);let d=Array.from(a,h=>h.url);const c=d.findIndex(h=>h===this.hls.url);c!==-1&&(d=d.slice(c+1)),this.hls.urls=d}if(n||this.url==="")break}}catch(e){e.name!=="AbortError"&&this.on.error&&this.on.error(e)}},start:()=>new Promise(async(e,s)=>{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));;){const t=this.hls.urls.shift();if(t){this.hls.url=t;const i=(await this.prFetch.request(t)).body?.getReader();if(!i)throw new Error("segment reader is error.");for(;;){const{done:o,value:a}=await i.read();if(a&&this.demuxerWorker?.push(a),o||this.url==="")break}}else await new Promise(n=>setTimeout(()=>n(!0),300))}}catch(t){t.name!=="AbortError"&&s(t)}})}}class K{pendingPayloads=[];payload=new Uint8Array(0);chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);const s=this.pendingPayloads.shift();if(!s)return!1;const t=new Uint8Array(this.payload.byteLength+s.byteLength);return t.set(this.payload,0),t.set(s,this.payload.byteLength),this.payload=t,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.chunks=[]}}const X=g=>{let e="unknown";switch(g){case 1:case 2:case 27:case 36:e="video";break;case 3:case 4:case 15:e="audio";break;case 6:e="subtitle";break;case 134:e="ad";break}return e};class Y{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let s=0;for(;!(s+188>e.byteLength);){if(e.getInt8(s)!=71){s++;continue}await this.parsePacket(e,s),s+=188}return s};parsePacket=async(e,s)=>{if(s+188>e.byteLength)throw new Error("Invalid TS packet");if(e.getUint8(s)!==71)throw new Error("Invalid TS packet");let t=s;const n=this.parseHeader(e,t);t+=4;const{transport_error_indicator:i,pid:o,payload_unit_start_indicator:a,adaptation_field_control:r}=n;if(i===1||o===void 0)return;let d=184;if(r===2||r===3){const c=e.getUint8(t);t+=1,this.parseAdaptationField(e,t),t+=c,d-=c}if(r===3&&(d-=1),r===1||r===3){const c=new Uint8Array(e.buffer.slice(t,t+d));if(o===0)return this.parsePAT(e,t);{const{programs:u=[]}=this.pat||{};if(u.find(f=>f.pmt_pid===o))return this.parsePMT(e,t)}const{streams:h=[]}=this.pmt||{},l=h.find(u=>u.elementary_pid===o);if(l){if(a===1){const u=this.payloadMap.get(o);if(u){switch(l.kind){case"audio":{const p=await this.parseAudio(u);this.on.chunk&&this.on.chunk(p)}break;case"video":{const p=await this.parseVideo(u);this.on.chunk&&this.on.chunk(p),await new Promise(f=>setTimeout(()=>f(!0),0))}break}this.payloadMap.delete(o)}}{this.payloadMap.has(o)||this.payloadMap.set(o,new Uint8Array);const u=this.payloadMap.get(o),p=new Uint8Array(u.byteLength+c.byteLength);p.set(u,0),p.set(c,u.byteLength),this.payloadMap.set(o,p)}}}};parseHeader=(e,s)=>{let t=s;const n=e.getUint8(t),i=e.getUint8(t+1),o=e.getUint8(t+2),a=e.getUint8(t+3),r=(i&128)>>7;if(r===1)return{sync_byte:n,transport_error_indicator:r};const d=(i&64)>>6,c=(i&32)>>5,h=(i&31)<<8|o,l=(a&192)>>6,u=a>>4&3,p=a&15;return{sync_byte:n,transport_error_indicator:r,payload_unit_start_indicator:d,transport_priority:c,pid:h,transport_scrambling_control:l,adaptation_field_control:u,continuity_counter:p}};parsePAT=(e,s)=>{let t=s,n;{const a=e.getUint8(t);t+=1;const r=e.getUint8(t);if(t+=1,r!==0)throw new Error("Invalid PAT table_id");const d=e.getUint16(t)&4095;t+=2;const c=e.getUint16(t);t+=2;const h=(e.getUint8(t)&62)>>1,l=e.getUint8(t)&1;t+=1;const u=e.getUint8(t);t+=1;const p=e.getUint8(t);t+=1,n={pointer_field:a,table_id:r,section_length:d,transport_stream_id:c,version_number:h,current_next_indicator:l,section_number:u,last_section_number:p}}const i=[];{const a=n.section_length-5-4,r=t+a;for(;t<r;){const d=e.getUint16(t),c=e.getUint16(t+2)&8191;t+=4,d!==0&&c>=32&&c<=8190&&i.push({program_number:d,pmt_pid:c})}}const o=e.getUint32(t);this.pat={header:n,programs:i,crc32:o},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(e,s)=>{let t=s,n;{const a=e.getUint8(t);t+=1;const r=e.getUint8(t);if(t+=1,r!==2)throw new Error("Invalid PMT table_id");const d=e.getUint16(t)&4095;t+=2;const c=e.getUint16(t);t+=2;const h=(e.getUint8(t)&62)>>1,l=e.getUint8(t)&1;t+=1;const u=e.getUint8(t);t+=1;const p=e.getUint8(t);t+=1;const f=e.getUint16(t)&8191;t+=2;const m=e.getUint16(t)&4095;t+=2,n={pointer_field:a,table_id:r,section_length:d,transport_stream_id:c,version_number:h,current_next_indicator:l,section_number:u,last_section_number:p,pcr_pid:f,program_info_length:m}}const i=[];{const a=n.section_length-9-4,r=t+a;for(;t<r;){const d=e.getUint8(t),c=X(d),h=e.getUint16(t+1)&8191,l=e.getUint16(t+3)&4095;if(t+=5,h<32||h>8190){console.warn(`Invalid elementary_pid: 0x${h.toString(16)}`);continue}i.push({kind:c,stream_type:d,elementary_pid:h,es_info_length:l})}}const o=e.getUint32(t);this.pmt={header:n,streams:i,crc32:o},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(e,s)=>{let t=s,n,i,o,a;const r=e.getUint8(t),d=!!(r&128),c=!!(r&64),h=!!(r&32),l=!!(r&16),u=!!(r&8),p=!!(r&4),f=!!(r&2),m=!!(r&1);t+=1;const k=(y,w)=>{let U=BigInt(0);U|=BigInt(y.getUint16(w))<<25n,U|=BigInt(y.getUint16(w+1))<<17n,U|=BigInt(y.getUint16(w+2))<<9n,U|=BigInt(y.getUint16(w+3))<<1n,U|=BigInt(y.getUint16(w+4)>>7);const te=(y.getUint16(w+4)&1)<<8|y.getUint16(w+5);return U=U*300n+BigInt(te),U};if(l&&(n=k(e,t),t+=6),u&&(i=k(e,t),t+=6),p&&(o=e.getInt8(t),t+=1),f){const y=e.getUint8(t);t+=1,a=new Uint8Array(e.buffer,t,y),t+=y}return{discontinuity_indicator:d,random_access_indicator:c,elementary_stream_priority_indicator:h,pcr_flag:l,opcr_flag:u,splicing_point_flag:p,transport_private_data_flag:f,adaptation_field_extension_flag:m,pcr:n,opcr:i,splice_countdown:o,transport_private_data:a}};parseAudio=async e=>{const s=new DataView(e.buffer);let t=0,n,i;{const o=s.getUint8(t)===0&&s.getUint8(t+1)===0&&s.getUint8(t+2)===1;if(t+=3,!o)throw new Error("invalid ts audio payload.");const a=s.getUint8(t);t+=1;const r=s.getUint8(t)<<8|s.getUint8(t+1);t+=2;let d,c,h,l,u;{const m=s.getUint8(t);t+=1,d=m>>4&3,c=(m>>3&1)===1,h=(m>>2&1)===1,l=(m>>1&1)===1,u=(m&1)===1}let p,f;{const m=s.getUint8(t);t+=1;const k=m>>6,y=s.getUint8(t);t+=1,(k&2)===2&&(p=this.parsePtsDts(s,t)),(k&1)===1?f=this.parsePtsDts(s,t+5):f=p,t+=y}n={stream_id:a,pes_packet_length:r,scrambling_control:d,priority:c,data_alignment:h,copyright:l,original_copy:u,pts:p,dts:f}}i=e.slice(t);{if(!this.audioConfig&&s.getUint8(t)===255){const h=s.getUint8(t+2),l=s.getUint8(t+3);let u,p;p=h>>2&15,u=(h&1)<<2|l>>6;const f=`mp4a.40.${u}`,k=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][p];this.audioConfig={kind:"audio",codec:f,sampleRate:k,numberOfChannels:u},this.on.config&&this.on.config(this.audioConfig)}const{dts:o=0,pts:a=0}=n,r=a-o,d=i.slice(7);return{kind:"audio",type:"key",dts:o,pts:a,cts:r,data:d}}};parseVideo=async e=>{const s=new DataView(e.buffer);let t=0,n,i;{const o=s.getUint8(t)===0&&s.getUint8(t+1)===0&&s.getUint8(t+2)===1;if(t+=3,!o)throw new Error("invalid ts video payload.");const a=s.getUint8(t);t+=1;const r=s.getUint8(t)<<8|s.getUint8(t+1);t+=2;let d,c,h,l,u;{const m=s.getUint8(t);t+=1,d=m>>4&3,c=(m>>3&1)===1,h=(m>>2&1)===1,l=(m>>1&1)===1,u=(m&1)===1}let p,f;{const m=s.getUint8(t);t+=1;const k=m>>6,y=s.getUint8(t);t+=1,(k&2)===2&&(p=this.parsePtsDts(s,t)),(k&1)===1?f=this.parsePtsDts(s,t+5):f=p,t+=y}n={stream_id:a,pes_packet_length:r,scrambling_control:d,priority:c,data_alignment:h,copyright:l,original_copy:u,pts:p,dts:f}}i=e.slice(t);{const o=this.getNalus(i);if(!this.videoConfig){let u,p;if(u=o.find(m=>m.type===7)?.nalu.slice(4),p=o.find(m=>m.type===8)?.nalu.slice(4),u&&p){const f=j(u,p),{codec:m}=P(f);this.videoConfig={kind:"video",codec:m,description:f,sps:u,pps:p},this.on.config&&this.on.config(this.videoConfig)}}const a=[];let r="delta";for(const u of o){const{type:p,nalu:f}=u;switch(p){case 6:case 9:a.push(f);break;case 1:r="delta",a.push(f);break;case 5:r="key",a.push(f);break}}const d=$(a),{dts:c=0,pts:h=0}=n,l=h-c;return{kind:"video",type:r,dts:c,pts:h,cts:l,data:d,nalus:a}}};parsePtsDts(e,s){const t=e.getUint8(s),n=e.getUint8(s+1),i=e.getUint8(s+2),o=e.getUint8(s+3),a=e.getUint8(s+4),r=(BigInt(t)&0b00001110n)<<29n|(BigInt(n)&0b11111111n)<<22n|(BigInt(i)&0b11111110n)<<14n|(BigInt(o)&0b11111111n)<<7n|(BigInt(a)&0b11111110n)>>1n;return Number(r)/90}getNalus=e=>{const s=[];let t=0;for(;!(t+4>e.byteLength);){if(e[t]!==0||e[t+1]!==0||e[t+2]!==1){t+=1;continue}t+=3;let n=t;const i=e[t]&31;for(t+=1;!(t+1>e.byteLength);){if(e[t]!==0||e[t+1]!==0||e[t+2]!==1){t+=1;continue}break}let o=t-n;if(e[t-1]===0&&(o-=1),o!==0){const a=e.slice(n,n+o),r=z(a);s.push({type:i,nalu:r})}}return s}}const _=(g,e)=>g.getUint8(e)<<16|g.getUint8(e+1)<<8|g.getUint8(e+2);class Q{audioConfig;videoConfig;header;textDecoder=new TextDecoder("utf-8");on={};constructor(){}parse=async e=>{let s=0;for(this.header||(this.parseHeader(e,s),s+=9);this.isSurplusTag(e,s)!==!1;){const n=this.parseTagHeader(e,s+4),{tagType:i,dataSize:o,timestamp:a}=n;if(i){const r=this.parseTagBody(i,e,s+4+11,o);switch(i){case"script":this.on.info&&this.on.info(r);break;case"audio":{const{accPacketType:d}=r;if(d===0){const{codec:c,sampleRate:h,channelConfiguration:l}=r;this.audioConfig={kind:"audio",codec:c,sampleRate:h,numberOfChannels:l},this.on.config&&this.on.config(this.audioConfig)}else{const{cts:c,data:h}=r,l="key",u=c===void 0?void 0:c+a;this.on.chunk&&this.on.chunk({kind:"audio",type:l,dts:a,pts:u,cts:c,data:h})}}break;case"video":{const{avcPacketType:d}=r;if(d===0){const{codec:c,sps:h,pps:l,data:u}=r;this.videoConfig={kind:"video",codec:c,description:u,sps:h,pps:l},this.on.config&&this.on.config(this.videoConfig)}else{const{frameType:c,cts:h,data:l,nalus:u}=r,p=c===1?"key":"delta",f=h===void 0?void 0:h+a;this.on.chunk&&this.on.chunk({kind:"video",type:p,dts:a,pts:f,cts:h,data:l,nalus:u})}}break}s=s+4+11+o}await new Promise(r=>setTimeout(()=>r(!0),8))}return s};parseHeader=(e,s)=>{let t,n,i,o;t=e.getUint8(s)<<16|e.getUint8(s+1)<<8|e.getUint8(s+2),n=e.getUint8(3);{const r=e.getUint8(0).toString(2).padStart(5,"0").split(""),[,,d,,c]=r;i={audio:c==="1",video:d==="1"}}o=e.getUint32(5),this.header={signature:t,version:n,flags:i,dataOffset:o}};isSurplusTag=(e,s)=>{let t=!0;const n=e.byteLength;if(s+4>n)t=!1;else if(s+4+11>n)t=!1;else{const i=_(e,s+4+1);s+4+11+i>n&&(t=!1)}return t};parseTagHeader=(e,s)=>{let t,n,i,o,a;{const r=e.getUint8(s);let d;switch(r){case 18:d="script";break;case 8:d="audio";break;case 9:d="video";break}t=d}return n=_(e,s+1),i=_(e,s+4),o=e.getUint8(s+7),a=_(e,s+8),{tagType:t,dataSize:n,timestamp:i,timestampExtended:o,streamID:a}};parseTagBody=(e,s,t,n)=>{let i;switch(e){case"script":i=this.parseMetaData(s,t);break;case"audio":i=this.parseAudio(s,t,n);break;case"video":i=this.parseVideo(s,t,n);break}return i};parseMetaData=(e,s)=>{let t=s;{if(e.getUint8(t)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");t=t+1}const n=e.getUint16(t,!1);t=t+2;{const a=new Int8Array(e.buffer.slice(t,t+n));if((this.textDecoder?.decode(a)||"")!=="onMetaData")throw new Error("Expected 'onMetaData' string");t=t+n}const i=this.getAmfType(e,t);return t=t+1,this.getAMFValue(e,t,i).value};parseAudio=(e,s,t)=>{let n=s;const i=e.getUint8(n),o=i>>4&15,a=i>>2&3,r=i>>1&1,d=i&1;n=n+1;const c=e.getUint8(n);n=n+1;const h=t,l=new Uint8Array(e.buffer.slice(n,n+h));if(o===10&&c===0){const u=e.getUint8(n),p=e.getUint8(n+1),f=u>>3&31,m=(u&7)<<1|p>>7,k=p>>3&15,y=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],w=`mp4a.40.${f}`,U=y[m];return{soundFormat:o,soundRate:a,soundSize:r,soundType:d,accPacketType:c,data:l,samplingFrequencyIndex:m,channelConfiguration:k,codec:w,sampleRate:U}}return{soundFormat:o,soundRate:a,soundSize:r,soundType:d,accPacketType:c,data:l}};parseVideo=(e,s,t)=>{let n=s;const i=e.getUint8(n),o=i>>4&15,a=i&15;n=n+1;const r=e.getUint8(n);n=n+1;const d=_(e,n);n=n+3;const c=t-5,h=new Uint8Array(e.buffer.slice(n,n+c));switch(a){case 7:if(r===0){const l=P(h);return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h,...l}}else if(r===1){const l=[],u=n+t-5;for(;!(n+4>u);){const p=e.getUint32(n,!1),f=new Uint8Array(e.buffer.slice(n,n+4+p));n+=4+p,l.push(f)}return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h,nalus:l}}break;default:throw new Error("Unsupported codecID")}return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h}};getAmfType=(e,s)=>e.getUint8(s);getAMFName=(e,s,t)=>{const n=new Uint8Array(e.buffer.slice(s,s+t));return this.textDecoder?.decode(n)||""};getAMFValue=(e,s,t)=>{let n=s,i,o=0;switch(t){case 0:i=e.getFloat64(n,!1),o=8;break;case 1:i=!!e.getUint8(n),o=1;break;case 2:{i="";const r=e.getUint16(n,!1);n=n+2;const d=new Int8Array(e.buffer,n,r).filter(h=>h!==0);i=(this.textDecoder?.decode(d)||"").trim(),o=2+r}break;case 3:for(i={};n<e.byteLength;){const r=e.getUint16(n,!1);if(r===0)break;n=n+2;const d=this.getAMFName(e,n,r);n=n+r;const c=this.getAmfType(e,n);if(c===6)break;n=n+1;const h=this.getAMFValue(e,n,c);n=n+h.length,i[d]=h.value,o=2+r+1+h.length}break;case 8:{i={};const r=e.getUint32(n,!1);n=n+4;for(let d=0;d<r;d++){const c=e.getUint16(n,!1);n=n+2;const h=this.getAMFName(e,n,c);n=n+c;const l=this.getAmfType(e,n);n=n+1;const u=this.getAMFValue(e,n,l);n=n+u.length,i[h]=u.value,o=2+c+1+u.length}}break;case 10:{i=[];const r=e.getUint32(n,!1);n=n+4;for(let d=0;d<r;d++){const c=this.getAmfType(e,n);n=n+1;const h=this.getAMFValue(e,n,c);n=n+h.length,i.push(h.value),o=1+h.length}}break}return{amfType:t,length:o,value:i}}}class J{pattern;cacher=new K;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case"flv":this.parser=new Q;break;case"hls":this.parser=new Y;break;default:throw new Error("is error pattern.")}this.parser.on.debug=s=>this.on.debug&&this.on.debug(s),this.parser.on.info=s=>this.on.info&&this.on.info(s),this.parser.on.config=s=>this.on.config&&this.on.config(s),this.parser.on.chunk=s=>{this.cacher.pushChunk(s),this.on.chunk&&this.on.chunk(s)}};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 new Error("You need to set the pattern.");if(!this.parser)throw new Error("You need to init parser.");for(;;){const e=this.cacher.next(this.offset);if(this.offset=0,!e)break;this.offset=await this.parser.parse(e)}this.isParseing=!1}catch{this.destroy()}}}class Z{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],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=e=>{this.audio.destroy(),this.audioDecoderConfig={...e},this.audioDecoder=new AudioDecoder({output:s=>{const t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:s,playbackRate:t})},error:s=>{this.on.audio.error&&this.on.audio.error(s)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:async s=>{this.frameStartTime||(this.frameStartTime=s.timestamp);try{const t=s.timestamp-this.frameStartTime+this.baseTime*1e3,n=await createImageBitmap(s);if(s.close(),!n.width||!n.height)return n.close();this.on.video.decode&&this.on.video.decode({timestamp:t,bitmap:n}),this.currentChunk&&this.currentChunk.kind==="video"&&this.currentChunk.nalus&&this.on.nalus&&this.on.nalus(this.currentChunk.nalus)}catch{s.close()}},error:s=>{this.on.video.error&&this.on.video.error(s)}}),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;const s=this.baseTime+performance.now();if(this.lastRenderTime||(this.lastRenderTime=s),this.fps=Math.round(1e3/(s-this.lastRenderTime)),this.lastRenderTime=s,this.nextRenderTime){const t=this.lastRenderTime-this.nextRenderTime;e-=t}this.nextRenderTime=this.lastRenderTime+e,this.decodeTimer=setTimeout(()=>{this.decode(),this.initDecodeInterval()},e)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;this.currentChunk=this.pendingChunks.shift(),!!this.currentChunk;){const e=this.pendingChunks.length;if(this.frameTrack){const[n,i]=this.fameTrackOption[this.pattern];if(e<=n&&(this.isFrameTrack=!1),e>=i&&(this.isFrameTrack=!0),this.isFrameTrack){const o=Math.min(1+(e-n)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(o.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){const{decodingSpeed:n,decodingSpeedRatio:i,fps:o}=this;this.on.analysis({decodingSpeed:n,decodingSpeedRatio:i,fps:o,cacheLength:e})}const{kind:s,init:t}=this.currentChunk;switch(s){case"audio":this.decodeAudio(t);break;case"video":this.decodeVideo(t);break}if(s==="video")break}this.isProcessing=!1}};decodeAudio=e=>{if(!this.audioDecoder)return;const s=new EncodedAudioChunk(e);this.audioDecoder.decode(s)};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)){const s=new EncodedVideoChunk(e);this.videoDecoder.decode(s)}};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}}}class ee{renderMap=new Map;constructor(){}push=async e=>{const{timestamp:s}=e,{bitmap:t}=e;if(t.height===0||t.width===0)return t.close();try{const n=[...this.renderMap.keys()];for(const i of n){const o=this.renderMap.get(i);if(!o)continue;const{pause:a=!1,writer:r,offscreen:d,option:c}=o;if(a===!0)continue;const h=l=>{if(r){const u=new VideoFrame(l,{timestamp:s});try{u&&r.write(u)}catch{}u.close()}else d&&(d.width=l.width,d.height=l.height,d?.getContext("2d")?.drawImage(l,0,0))};if(i==="default")h(t);else if(c){const{sx:l=0,sy:u=0,sw:p=t.width,sh:f=t.height}=c,m=await createImageBitmap(t,l,u,p,f);h(m)}}}catch{}t.close()};addCut=e=>{const{key:s,writable:t,offscreen:n,option:i}={key:"default",...e};if(t){const o=t.getWriter();this.renderMap.set(s,{writer:o,option:i,pause:!1})}else this.renderMap.set(s,{offscreen:n,option:i,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{const{key:s,cutOption:t}={key:"default",...e},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,option:t})};setPause=e=>{const{key:s,pause:t}={key:"default",...e},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,pause:t})};destroy=()=>{this.renderMap=new Map}}b.Decoder=Z,b.DecoderWorker=S,b.Demuxer=J,b.DemuxerWorker=v,b.PrPlayer=H,b.Render=ee,b.RenderWorker=R,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})}));
2
+ `,x=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",A],{type:"text/javascript;charset=utf-8"});function L(g){let e;try{if(e=x&&(self.URL||self.webkitURL).createObjectURL(x),!e)throw"";const s=new Worker(e,{name:g?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(A),{name:g?.name})}}class S{worker=new L;on={audio:{},video:{}};constructor(){this.worker.onmessage=e=>{const{action:s,data:t}=e.data;switch(s){case"on.audio.decode":this.on.audio.decode&&this.on.audio.decode(t);break;case"on.audio.error":this.on.audio.error&&this.on.audio.error(t);break;case"on.video.decode":this.on.video.decode&&this.on.video.decode(t);break;case"on.video.error":this.on.video.error&&this.on.video.error(t);break;case"on.nalus":this.on.nalus&&this.on.nalus(t);break;case"on.analysis":this.on.analysis&&this.on.analysis(t);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()}}const M=`(function(){"use strict";class w{renderMap=new Map;constructor(){}push=async t=>{const{timestamp:s}=t,{bitmap:e}=t;try{const n=[...this.renderMap.keys()];for(const a of n){const i=this.renderMap.get(a);if(!i)continue;const{pause:y=!1,writer:u,offscreen:o,option:f}=i;if(y===!0)continue;const h=async r=>{if(u){const c=new VideoFrame(r,{timestamp:s});try{await u.write(c)}catch{}c.close()}else o&&(o.width=r.width,o.height=r.height,o?.getContext("2d")?.drawImage(r,0,0))};if(a==="default")await h(e);else if(f){const{sx:r=0,sy:c=0,sw:p=e.width,sh:M=e.height}=f,g=await createImageBitmap(e,r,c,p,M);await h(g)}}}catch{}e.close()};addCut=t=>{const{key:s,writable:e,offscreen:n,option:a}={key:"default",...t};if(e){const i=e.getWriter();this.renderMap.set(s,{writer:i,option:a,pause:!1})}else this.renderMap.set(s,{offscreen:n,option:a,pause:!1})};delCut=t=>{this.renderMap.delete(t)};setCut=t=>{const{key:s,cutOption:e}={key:"default",...t},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,option:e})};setPause=t=>{const{key:s,pause:e}={key:"default",...t},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,pause:e})};destroy=()=>{this.renderMap=new Map}}const l=new w;onmessage=d=>{const{action:t,data:s}=d.data,e=l[t];e&&e(s)}})();
3
+ `,D=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",M],{type:"text/javascript;charset=utf-8"});function V(g){let e;try{if(e=D&&(self.URL||self.webkitURL).createObjectURL(D),!e)throw"";const s=new Worker(e,{name:g?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(M),{name:g?.name})}}class R{worker=new V;constructor(){}push=e=>this.worker.postMessage({action:"push",data:e},[e.bitmap]);addCut=e=>{const s=[];e.writable&&s.push(e.writable),e.offscreen&&s.push(e.offscreen),this.worker.postMessage({action:"addCut",data:e},s)};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()}}class W{inputStream=new MediaStream;outputStream=new MediaStream;inputGain=1;enhanceGain=1;bgsGain=1;bgmGain=1;outputGain=1;mixAudioMap=new Map;audioContext=new AudioContext;sourceNode;inputGainNode;enhanceGainNode;bgsGainNode;bgmGainNode;rnnoiseNode;analyserNode;analyserArrayData;outputGainNode;destinationNode;denoise=!1;mute=!0;rnnoiseWorklet;rnnoiseWorkletNode;filterStream=e=>e;constructor(e,s){this.inputStream=e,s&&(this.audioContext=s),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;{const{sourceNode:t,inputGainNode:n,enhanceGainNode:i,bgsGainNode:o,bgmGainNode:a,analyserNode:r,outputGainNode:d,destinationNode:c}=this;t.connect(n),n.connect(i),i.connect(r),o.connect(r),a.connect(r),i.connect(c),o.connect(c),a.connect(c),d.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=>{const s=this.inputStream.getTracks();for(const t of s)this.inputStream.removeTrack(t);this.inputStream.addTrack(e),this._changeSource()};stop=()=>{{const e=this.inputStream.getTracks();for(const s of e)s.stop(),this.inputStream.removeTrack(s)}};pause=async e=>{const s=this.inputStream.getTracks();for(const t of s)t.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(),this.rnnoiseWorklet.destroy(),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.denoise=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=()=>{const{analyserNode:e,analyserArrayData:s}=this;e.getByteFrequencyData(s);let t=0;for(let n=0;n<s.length;n++)t+=s[n];return Math.ceil(t/s.length)};mixAudio=(e,s="bgm")=>new Promise(async(t,n)=>{try{{const a=this.mixAudioMap.get(s);a&&a.stop()}const i=s==="bgs"?this.bgsGainNode:this.bgmGainNode,o=this.audioContext.createBufferSource();this.mixAudioMap.set(s,o),o.buffer=e,o.connect(i),o.onended=()=>{o.disconnect(i),this.mixAudioMap.delete(s),t(!0)},o.start(0)}catch(i){n(i)}});mixAudioStop=e=>{this.mixAudioMap.get(e)?.stop()};changeMix=(e,s)=>{const t=e==="bgs"?this.bgsGainNode:this.bgmGainNode;s?t.connect(this.destinationNode):t.disconnect(this.destinationNode)}}const F=async(g,e)=>{try{const{format:s,numberOfChannels:t,numberOfFrames:n,sampleRate:i}=e,o=g.createBuffer(t,n,i);for(let a=0;a<t;a++){const r=e.allocationSize({planeIndex:a}),d=new Uint8Array(r);e.copyTo(d,{planeIndex:a});const c=new DataView(d.buffer),h=o.getChannelData(a);for(let l=0;l<n;l++){let u;switch(s){case"s16":case"s16-planar":u=c.getInt16(l*2,!0)/32768;break;case"f32":case"f32-planar":u=c.getFloat32(l*4,!0);break;case"u8":case"u8-planar":u=(c.getUint8(l)-128)/128;break;default:throw new Error(`Unsupported audio format: ${s}`)}h[l]=Math.max(-1,Math.min(1,u))}}return o}catch(s){throw console.error("Failed to convert AudioData to AudioBuffer:",s),s}};class B{prAudioStream;audioContext;destination;stream=new MediaStream;nextStartTime=0;pendingSources=[];constructor(){}init=e=>{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 W(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(e){const{audioData:s,playbackRate:t=1}=e;if(!this.audioContext||!this.destination)return;let n=await F(this.audioContext,s);if(s.close(),!n)return;const i=this.audioContext.createBufferSource();i.buffer=n,i.playbackRate.value=t;const o=-1200*Math.log2(t);i.detune.value=o,i.connect(this.destination);const a=Math.max(this.nextStartTime,this.audioContext.currentTime),r=n.duration/t;this.nextStartTime=a+r,i.start(a),this.pendingSources.push(i),i.onended=()=>{this.pendingSources=this.pendingSources.filter(d=>d!==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.pendingSources.forEach(e=>e.stop()),this.pendingSources=[]}}const G=g=>{const e=g.toLowerCase();return e.includes(".m3u8")||e.includes("hls")||e.includes("master.m3u8")||e.match(/index\d*\.m3u8/)?"hls":e.includes(".mpd")||e.includes("dash")?"dash":e.startsWith("rtmp://")||e.startsWith("rtmps://")?"rtmp":e.includes(".flv")||e.includes("flv")&&!e.includes("flash")?"flv":"unknown"},E=g=>{const e=g?.getTracks()||[];for(const s of e)s.stop()};class O{resolvesMap=new Map;index=0;constructor(){}add=(e,s=()=>!1,t=0)=>new Promise(n=>{if(s())return n(!0);this.resolvesMap.has(e)||this.resolvesMap.set(e,new Map),this.index++;const a=`${this.index}`;if(t=Math.max(0,t),t===0){this.resolvesMap.get(e)?.set(a,{resolve:n,timer:0});return}const r=window.setTimeout(()=>{this.emit(e)},t);this.resolvesMap.get(e)?.set(a,{resolve:n,timer:r})});emit=async e=>{const s=this.resolvesMap.get(e);if(!s)return;const t=[...s.keys()];for(const n of t){const i=s.get(n);i&&(clearTimeout(i.timer),i.resolve(),s.delete(n))}}}const j=(g,e)=>{const s=new Uint8Array(g),t=new Uint8Array(e),n=new Uint8Array(11+s.length+t.length);let i=0;return n[i++]=1,n[i++]=s[1],n[i++]=s[2],n[i++]=s[3],n[i++]=255,n[i++]=225,n[i++]=s.length>>8&255,n[i++]=s.length&255,n.set(s,i),i+=s.length,n[i++]=1,n[i++]=t.length>>8&255,n[i++]=t.length&255,n.set(t,i),n},P=g=>{let e=0;const s=new DataView(g.buffer),t=s.getUint8(e);if(e=e+1,t!==1)throw new Error("Invalid AVC version");const n=s.getUint8(e)&255;e=e+1;const i=s.getUint8(e)&255;e=e+1;const o=s.getUint8(e)&255;e=e+1;const d=`avc1.${Array.from([n,i,o],k=>k.toString(16).padStart(2,"0")).join("")}`,c=(s.getUint8(e)&3)-1;e=e+1;const h=s.getUint8(e)&31;e=e+1;const l=s.getUint16(e,!1);e=e+2;const u=new Uint8Array(s.buffer.slice(e,e+l));e=e+l;const p=s.getUint8(e)&31;e=e+1;const f=s.getUint16(e,!1);e=e+2;const m=new Uint8Array(s.buffer.slice(e,e+f));return e=e+f,{version:t,codec:d,profile:n,compatibility:i,level:o,lengthSizeMinusOne:c,numOfSequenceParameterSets:h,sequenceParameterSetLength:l,sps:u,numOfPictureParameterSets:p,pictureParameterSetLength:f,pps:m}},z=g=>{const e=new Uint8Array(4+g.length);return new DataView(e.buffer).setUint32(0,g.length,!1),e.set(g,4),e},$=g=>{let e=0;for(const n of g)e+=n.length;const s=new Uint8Array(e);let t=0;for(const n of g){const i=n;s.set(i,t),t+=i.length}return s},q=g=>{const e=new DataView(g.buffer);let s=0,t,n,i;t=e.getUint32(s,!1),s+=4;{const o=e.getUint8(s),a=o>>7&1,r=o>>5&3,d=o&31;n={forbidden_zero_bit:a,nal_ref_idc:r,nal_unit_type:d},s+=1}{const o=t-1;i=new Uint8Array(e.buffer.slice(s,s+o))}return{size:t,header:n,data:i}};class I{#t={timeout:5*1e3,check:!1};#e=null;constructor(e={}){this.#t={...this.#t,...e}}#s=(e,s)=>new Promise(async t=>{this.#e=new AbortController;const{signal:n}=this.#e,i=this.#t.timeout,o=setTimeout(()=>{this.#e?.abort(`Timeout (${i}ms)`)},i);await fetch(e,{cache:"no-store",...s,method:"HEAD",signal:n}).then(a=>{clearTimeout(o),t({status:a.status===200?"successed":"failed",reason:a.status===200?"":`HTTP ${a.status}`})}).catch(a=>{if(clearTimeout(o),a.name==="AbortError"){const r=n.reason||"Actively stopped";t({status:r.includes("Timeout")?"timeout":"stopped",reason:r})}else t({status:"error",reason:a.message})})});request=(e,s)=>new Promise(async(t,n)=>{try{this.stop(),this.#t.check&&await this.#s(e),this.#e=new AbortController;const{signal:i}=this.#e,o=await fetch(e,{cache:"no-store",...s,signal:i});t(o)}catch(i){n(i)}});stop=()=>{if(this.#e?.signal.aborted===!1){const e=new Error("Actively stopped.");e.name="AbortError",this.#e.abort(e)}}}class H{option={debug:!1,frameTrack:!1};converter="MediaStreamTrackGenerator"in window?"generator":"canvas";prFetch=new I;getSegmentsFetch=new I;prResolves=new O;url="";start_resolve;demuxerWorker;decoderWorker;audioPlayer;renderWorker;stream;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(e={}){const{debug:s=!1}=e;this.option.debug=s}start=async e=>{await this.stop(),this.url=e;const s=G(e);if(s==="unknown")throw new Error("This address cannot be parsed.");switch(this.init(s),s){case"flv":this.flv.start();break;case"hls":this.hls.start();break}};stop=async()=>{try{this.url="",clearInterval(this.hls.getSegmentsTimer),this.prFetch.stop(),this.getSegmentsFetch.stop(),this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy(),this.cutRenders=new Map,E(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=()=>{const e=()=>this.stream?.active===!0;return this.prResolves.add("isReady",e)};cut={create:(e,s)=>{if(this.converter==="generator"){const o=new MediaStreamTrackGenerator({kind:"video"}),a=new MediaStream([o]);return this.renderWorker?.addCut({key:e,writable:o.writable,option:s}),this.cutRenders.set(e,{stream:a}),a}const t=document.createElement("canvas"),n=t.captureStream(),i=t.transferControlToOffscreen();return this.renderWorker?.addCut({key:e,offscreen:i,option:s}),this.cutRenders.set(e,{stream:n}),n},setCut:(e,s)=>{this.renderWorker?.setCut({key:e,cutOption:s})},getStream:e=>this.cutRenders.get(e)?.stream,remove:e=>{this.renderWorker?.delCut(e),this.cutRenders.delete(e)},setPause:(e,s)=>{this.renderWorker?.setPause({key:e,pause:s})}};init=e=>{this.initRender(),this.initDecoder(e),this.initDemuxer(e),this.audioPlayer=new B,this.audioPlayer.init()};initDemuxer=e=>{this.demuxerWorker=new v,this.demuxerWorker.init(e),this.demuxerWorker.on.debug=s=>{this.option.debug&&this.on.debug&&this.on.debug(s)},this.demuxerWorker.on.info=s=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: info",s),this.on.demuxer.info&&this.on.demuxer.info(s)},this.demuxerWorker.on.config=s=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: config",s),this.on.demuxer.config&&this.on.demuxer.config(s);const{kind:t}=s;switch(t){case"audio":{const{codec:n,sampleRate:i,numberOfChannels:o}=s;this.decoderWorker?.initAudio({codec:n,sampleRate:i,numberOfChannels:o})}break;case"video":{const{codec:n,description:i}=s;this.decoderWorker?.initVideo({codec:n,description:i})}break}},this.demuxerWorker.on.chunk=s=>{if(this.on.demuxer.chunk&&this.on.demuxer.chunk(s),!this.decoderWorker)return;const{kind:t}=s;switch(t){case"audio":{const{type:n,dts:i,data:o}=s,a=i*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:a,data:o}})}break;case"video":{const{type:n,dts:i,data:o,nalus:a=[]}=s,r=i*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:r,data:o},nalus:a})}break}}};initDecoder=e=>{this.decoderWorker=new S,this.decoderWorker.init(e);const{frameTrack:s=!1}=this.option;this.decoderWorker.setFrameTrack(s),this.decoderWorker.on.audio.decode=t=>{this.audioPlayer?.push(t),this.on.decoder.audio&&this.on.decoder.audio(t)},this.decoderWorker.on.audio.error=t=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: audio.error ",t),this.on.error&&this.on.error(t)},this.decoderWorker.on.video.decode=async t=>{this.start_resolve&&(this.start_resolve(!0),this.start_resolve=void 0),this.renderWorker?.push(t),this.on.decoder.video&&this.on.decoder.video(t)},this.decoderWorker.on.video.error=t=>{this.on.error&&this.on.error(t)},this.decoderWorker.on.nalus=async t=>{for(const n of t){if(n.byteLength<=4)continue;const{header:i,data:o}=q(n),{nal_unit_type:a}=i;a===6&&this.on.decoder.sei&&this.on.decoder.sei(o)}},this.decoderWorker.on.analysis=t=>{this.on.decoder.analysis&&this.on.decoder.analysis(t)}};initRender=()=>{if(this.renderWorker=new R,this.converter==="generator"){const e=new MediaStreamTrackGenerator({kind:"video"}),s=new MediaStream([e]);this.renderWorker?.addCut({writable:e.writable}),this.stream=s}else{const e=document.createElement("canvas"),s=e.captureStream(),t=e.transferControlToOffscreen();this.renderWorker?.addCut({offscreen:t}),this.stream=s}this.renderWorker?.setPause({pause:!1})};flv={start:()=>new Promise(async(e,s)=>{try{this.start_resolve=e;let t,n=0;for(;;){n+=1;try{t=await this.prFetch.request(this.url)}catch(o){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: error",o)}if(t?.status===200||n===3)break;await new Promise(o=>setTimeout(()=>o(!0),500))}if(!t||t.status!==200)return s("request is error.");const i=t.body?.getReader();if(!i)return s("reader is error.");for(;;){const{done:o,value:a}=await i.read();if(a&&this.demuxerWorker?.push(a),o||this.url==="")break}}catch(t){t.name!=="AbortError"&&s(t)}})};hls={isLive:!1,urls:[],url:"",getSegmentsTimer:0,parse:async e=>{const n=new TextDecoder("utf-8").decode(e).split(`
4
+ `).map(c=>c.replace("\r","")),i=this.url.substring(0,this.url.lastIndexOf("/")+1);let o=4,a=0,r=!1;const d=[];for(const c of n)c.startsWith("#EXTINF:")?o=parseFloat(c.split(":")[1].split(",")[0]):c.startsWith("#EXT-X-TARGETDURATION:")?a=parseInt(c.split(":")[1]):c.startsWith("#EXT-X-ENDLIST")?r=!1:c.startsWith("#EXT-X-MEDIA-SEQUENCE:")?r=!0:c.includes(".ts")&&!c.startsWith("#")&&d.push({url:c.startsWith("http")?c:i+c,duration:o,isLive:r});return{baseUrl:i,targetDuration:a,isLive:r,segments:d}},getSegments:async()=>{try{let e,s=0;for(;;){s+=1;try{e=await this.getSegmentsFetch.request(this.url)}catch(n){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: error",n)}if(e?.status===200||s===3)break;await new Promise(n=>setTimeout(()=>n(!0),500))}if(!e||e.status!==200)throw new Error("request is error.");const t=e.body?.getReader();if(!t)throw new Error("reader is error.");for(;;){const{done:n,value:i}=await t.read();if(i){const o=await this.hls.parse(i),{segments:a=[],isLive:r=!1}=o;this.hls.isLive=r,r===!1&&(this.option.frameTrack=!1);let d=Array.from(a,h=>h.url);const c=d.findIndex(h=>h===this.hls.url);c!==-1&&(d=d.slice(c+1)),this.hls.urls=d}if(n||this.url==="")break}}catch(e){e.name!=="AbortError"&&this.on.error&&this.on.error(e)}},start:()=>new Promise(async(e,s)=>{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));;){const t=this.hls.urls.shift();if(t){this.hls.url=t;const i=(await this.prFetch.request(t)).body?.getReader();if(!i)throw new Error("segment reader is error.");for(;;){const{done:o,value:a}=await i.read();if(a&&this.demuxerWorker?.push(a),o||this.url==="")break}}else await new Promise(n=>setTimeout(()=>n(!0),300))}}catch(t){t.name!=="AbortError"&&s(t)}})}}class K{pendingPayloads=[];payload=new Uint8Array(0);chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);const s=this.pendingPayloads.shift();if(!s)return!1;const t=new Uint8Array(this.payload.byteLength+s.byteLength);return t.set(this.payload,0),t.set(s,this.payload.byteLength),this.payload=t,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.chunks=[]}}const X=g=>{let e="unknown";switch(g){case 1:case 2:case 27:case 36:e="video";break;case 3:case 4:case 15:e="audio";break;case 6:e="subtitle";break;case 134:e="ad";break}return e};class Y{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let s=0;for(;!(s+188>e.byteLength);){if(e.getInt8(s)!=71){s++;continue}await this.parsePacket(e,s),s+=188}return s};parsePacket=async(e,s)=>{if(s+188>e.byteLength)throw new Error("Invalid TS packet");if(e.getUint8(s)!==71)throw new Error("Invalid TS packet");let t=s;const n=this.parseHeader(e,t);t+=4;const{transport_error_indicator:i,pid:o,payload_unit_start_indicator:a,adaptation_field_control:r}=n;if(i===1||o===void 0)return;let d=184;if(r===2||r===3){const c=e.getUint8(t);t+=1,this.parseAdaptationField(e,t),t+=c,d-=c}if(r===3&&(d-=1),r===1||r===3){const c=new Uint8Array(e.buffer.slice(t,t+d));if(o===0)return this.parsePAT(e,t);{const{programs:u=[]}=this.pat||{};if(u.find(f=>f.pmt_pid===o))return this.parsePMT(e,t)}const{streams:h=[]}=this.pmt||{},l=h.find(u=>u.elementary_pid===o);if(l){if(a===1){const u=this.payloadMap.get(o);if(u){switch(l.kind){case"audio":{const p=await this.parseAudio(u);this.on.chunk&&this.on.chunk(p)}break;case"video":{const p=await this.parseVideo(u);this.on.chunk&&this.on.chunk(p),await new Promise(f=>setTimeout(()=>f(!0),0))}break}this.payloadMap.delete(o)}}{this.payloadMap.has(o)||this.payloadMap.set(o,new Uint8Array);const u=this.payloadMap.get(o),p=new Uint8Array(u.byteLength+c.byteLength);p.set(u,0),p.set(c,u.byteLength),this.payloadMap.set(o,p)}}}};parseHeader=(e,s)=>{let t=s;const n=e.getUint8(t),i=e.getUint8(t+1),o=e.getUint8(t+2),a=e.getUint8(t+3),r=(i&128)>>7;if(r===1)return{sync_byte:n,transport_error_indicator:r};const d=(i&64)>>6,c=(i&32)>>5,h=(i&31)<<8|o,l=(a&192)>>6,u=a>>4&3,p=a&15;return{sync_byte:n,transport_error_indicator:r,payload_unit_start_indicator:d,transport_priority:c,pid:h,transport_scrambling_control:l,adaptation_field_control:u,continuity_counter:p}};parsePAT=(e,s)=>{let t=s,n;{const a=e.getUint8(t);t+=1;const r=e.getUint8(t);if(t+=1,r!==0)throw new Error("Invalid PAT table_id");const d=e.getUint16(t)&4095;t+=2;const c=e.getUint16(t);t+=2;const h=(e.getUint8(t)&62)>>1,l=e.getUint8(t)&1;t+=1;const u=e.getUint8(t);t+=1;const p=e.getUint8(t);t+=1,n={pointer_field:a,table_id:r,section_length:d,transport_stream_id:c,version_number:h,current_next_indicator:l,section_number:u,last_section_number:p}}const i=[];{const a=n.section_length-5-4,r=t+a;for(;t<r;){const d=e.getUint16(t),c=e.getUint16(t+2)&8191;t+=4,d!==0&&c>=32&&c<=8190&&i.push({program_number:d,pmt_pid:c})}}const o=e.getUint32(t);this.pat={header:n,programs:i,crc32:o},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(e,s)=>{let t=s,n;{const a=e.getUint8(t);t+=1;const r=e.getUint8(t);if(t+=1,r!==2)throw new Error("Invalid PMT table_id");const d=e.getUint16(t)&4095;t+=2;const c=e.getUint16(t);t+=2;const h=(e.getUint8(t)&62)>>1,l=e.getUint8(t)&1;t+=1;const u=e.getUint8(t);t+=1;const p=e.getUint8(t);t+=1;const f=e.getUint16(t)&8191;t+=2;const m=e.getUint16(t)&4095;t+=2,n={pointer_field:a,table_id:r,section_length:d,transport_stream_id:c,version_number:h,current_next_indicator:l,section_number:u,last_section_number:p,pcr_pid:f,program_info_length:m}}const i=[];{const a=n.section_length-9-4,r=t+a;for(;t<r;){const d=e.getUint8(t),c=X(d),h=e.getUint16(t+1)&8191,l=e.getUint16(t+3)&4095;if(t+=5,h<32||h>8190){console.warn(`Invalid elementary_pid: 0x${h.toString(16)}`);continue}i.push({kind:c,stream_type:d,elementary_pid:h,es_info_length:l})}}const o=e.getUint32(t);this.pmt={header:n,streams:i,crc32:o},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(e,s)=>{let t=s,n,i,o,a;const r=e.getUint8(t),d=!!(r&128),c=!!(r&64),h=!!(r&32),l=!!(r&16),u=!!(r&8),p=!!(r&4),f=!!(r&2),m=!!(r&1);t+=1;const k=(y,w)=>{let U=BigInt(0);U|=BigInt(y.getUint16(w))<<25n,U|=BigInt(y.getUint16(w+1))<<17n,U|=BigInt(y.getUint16(w+2))<<9n,U|=BigInt(y.getUint16(w+3))<<1n,U|=BigInt(y.getUint16(w+4)>>7);const te=(y.getUint16(w+4)&1)<<8|y.getUint16(w+5);return U=U*300n+BigInt(te),U};if(l&&(n=k(e,t),t+=6),u&&(i=k(e,t),t+=6),p&&(o=e.getInt8(t),t+=1),f){const y=e.getUint8(t);t+=1,a=new Uint8Array(e.buffer,t,y),t+=y}return{discontinuity_indicator:d,random_access_indicator:c,elementary_stream_priority_indicator:h,pcr_flag:l,opcr_flag:u,splicing_point_flag:p,transport_private_data_flag:f,adaptation_field_extension_flag:m,pcr:n,opcr:i,splice_countdown:o,transport_private_data:a}};parseAudio=async e=>{const s=new DataView(e.buffer);let t=0,n,i;{const o=s.getUint8(t)===0&&s.getUint8(t+1)===0&&s.getUint8(t+2)===1;if(t+=3,!o)throw new Error("invalid ts audio payload.");const a=s.getUint8(t);t+=1;const r=s.getUint8(t)<<8|s.getUint8(t+1);t+=2;let d,c,h,l,u;{const m=s.getUint8(t);t+=1,d=m>>4&3,c=(m>>3&1)===1,h=(m>>2&1)===1,l=(m>>1&1)===1,u=(m&1)===1}let p,f;{const m=s.getUint8(t);t+=1;const k=m>>6,y=s.getUint8(t);t+=1,(k&2)===2&&(p=this.parsePtsDts(s,t)),(k&1)===1?f=this.parsePtsDts(s,t+5):f=p,t+=y}n={stream_id:a,pes_packet_length:r,scrambling_control:d,priority:c,data_alignment:h,copyright:l,original_copy:u,pts:p,dts:f}}i=e.slice(t);{if(!this.audioConfig&&s.getUint8(t)===255){const h=s.getUint8(t+2),l=s.getUint8(t+3);let u,p;p=h>>2&15,u=(h&1)<<2|l>>6;const f=`mp4a.40.${u}`,k=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][p];this.audioConfig={kind:"audio",codec:f,sampleRate:k,numberOfChannels:u},this.on.config&&this.on.config(this.audioConfig)}const{dts:o=0,pts:a=0}=n,r=a-o,d=i.slice(7);return{kind:"audio",type:"key",dts:o,pts:a,cts:r,data:d}}};parseVideo=async e=>{const s=new DataView(e.buffer);let t=0,n,i;{const o=s.getUint8(t)===0&&s.getUint8(t+1)===0&&s.getUint8(t+2)===1;if(t+=3,!o)throw new Error("invalid ts video payload.");const a=s.getUint8(t);t+=1;const r=s.getUint8(t)<<8|s.getUint8(t+1);t+=2;let d,c,h,l,u;{const m=s.getUint8(t);t+=1,d=m>>4&3,c=(m>>3&1)===1,h=(m>>2&1)===1,l=(m>>1&1)===1,u=(m&1)===1}let p,f;{const m=s.getUint8(t);t+=1;const k=m>>6,y=s.getUint8(t);t+=1,(k&2)===2&&(p=this.parsePtsDts(s,t)),(k&1)===1?f=this.parsePtsDts(s,t+5):f=p,t+=y}n={stream_id:a,pes_packet_length:r,scrambling_control:d,priority:c,data_alignment:h,copyright:l,original_copy:u,pts:p,dts:f}}i=e.slice(t);{const o=this.getNalus(i);if(!this.videoConfig){let u,p;if(u=o.find(m=>m.type===7)?.nalu.slice(4),p=o.find(m=>m.type===8)?.nalu.slice(4),u&&p){const f=j(u,p),{codec:m}=P(f);this.videoConfig={kind:"video",codec:m,description:f,sps:u,pps:p},this.on.config&&this.on.config(this.videoConfig)}}const a=[];let r="delta";for(const u of o){const{type:p,nalu:f}=u;switch(p){case 6:case 9:a.push(f);break;case 1:r="delta",a.push(f);break;case 5:r="key",a.push(f);break}}const d=$(a),{dts:c=0,pts:h=0}=n,l=h-c;return{kind:"video",type:r,dts:c,pts:h,cts:l,data:d,nalus:a}}};parsePtsDts(e,s){const t=e.getUint8(s),n=e.getUint8(s+1),i=e.getUint8(s+2),o=e.getUint8(s+3),a=e.getUint8(s+4),r=(BigInt(t)&0b00001110n)<<29n|(BigInt(n)&0b11111111n)<<22n|(BigInt(i)&0b11111110n)<<14n|(BigInt(o)&0b11111111n)<<7n|(BigInt(a)&0b11111110n)>>1n;return Number(r)/90}getNalus=e=>{const s=[];let t=0;for(;!(t+4>e.byteLength);){if(e[t]!==0||e[t+1]!==0||e[t+2]!==1){t+=1;continue}t+=3;let n=t;const i=e[t]&31;for(t+=1;!(t+1>e.byteLength);){if(e[t]!==0||e[t+1]!==0||e[t+2]!==1){t+=1;continue}break}let o=t-n;if(e[t-1]===0&&(o-=1),o!==0){const a=e.slice(n,n+o),r=z(a);s.push({type:i,nalu:r})}}return s}}const _=(g,e)=>g.getUint8(e)<<16|g.getUint8(e+1)<<8|g.getUint8(e+2);class Q{audioConfig;videoConfig;header;textDecoder=new TextDecoder("utf-8");on={};constructor(){}parse=async e=>{let s=0;for(this.header||(this.parseHeader(e,s),s+=9);this.isSurplusTag(e,s)!==!1;){const n=this.parseTagHeader(e,s+4),{tagType:i,dataSize:o,timestamp:a}=n;if(i){const r=this.parseTagBody(i,e,s+4+11,o);switch(i){case"script":this.on.info&&this.on.info(r);break;case"audio":{const{accPacketType:d}=r;if(d===0){const{codec:c,sampleRate:h,channelConfiguration:l}=r;this.audioConfig={kind:"audio",codec:c,sampleRate:h,numberOfChannels:l},this.on.config&&this.on.config(this.audioConfig)}else{const{cts:c,data:h}=r,l="key",u=c===void 0?void 0:c+a;this.on.chunk&&this.on.chunk({kind:"audio",type:l,dts:a,pts:u,cts:c,data:h})}}break;case"video":{const{avcPacketType:d}=r;if(d===0){const{codec:c,sps:h,pps:l,data:u}=r;this.videoConfig={kind:"video",codec:c,description:u,sps:h,pps:l},this.on.config&&this.on.config(this.videoConfig)}else{const{frameType:c,cts:h,data:l,nalus:u}=r,p=c===1?"key":"delta",f=h===void 0?void 0:h+a;this.on.chunk&&this.on.chunk({kind:"video",type:p,dts:a,pts:f,cts:h,data:l,nalus:u})}}break}s=s+4+11+o}await new Promise(r=>setTimeout(()=>r(!0),8))}return s};parseHeader=(e,s)=>{let t,n,i,o;t=e.getUint8(s)<<16|e.getUint8(s+1)<<8|e.getUint8(s+2),n=e.getUint8(3);{const r=e.getUint8(0).toString(2).padStart(5,"0").split(""),[,,d,,c]=r;i={audio:c==="1",video:d==="1"}}o=e.getUint32(5),this.header={signature:t,version:n,flags:i,dataOffset:o}};isSurplusTag=(e,s)=>{let t=!0;const n=e.byteLength;if(s+4>n)t=!1;else if(s+4+11>n)t=!1;else{const i=_(e,s+4+1);s+4+11+i>n&&(t=!1)}return t};parseTagHeader=(e,s)=>{let t,n,i,o,a;{const r=e.getUint8(s);let d;switch(r){case 18:d="script";break;case 8:d="audio";break;case 9:d="video";break}t=d}return n=_(e,s+1),i=_(e,s+4),o=e.getUint8(s+7),a=_(e,s+8),{tagType:t,dataSize:n,timestamp:i,timestampExtended:o,streamID:a}};parseTagBody=(e,s,t,n)=>{let i;switch(e){case"script":i=this.parseMetaData(s,t);break;case"audio":i=this.parseAudio(s,t,n);break;case"video":i=this.parseVideo(s,t,n);break}return i};parseMetaData=(e,s)=>{let t=s;{if(e.getUint8(t)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");t=t+1}const n=e.getUint16(t,!1);t=t+2;{const a=new Int8Array(e.buffer.slice(t,t+n));if((this.textDecoder?.decode(a)||"")!=="onMetaData")throw new Error("Expected 'onMetaData' string");t=t+n}const i=this.getAmfType(e,t);return t=t+1,this.getAMFValue(e,t,i).value};parseAudio=(e,s,t)=>{let n=s;const i=e.getUint8(n),o=i>>4&15,a=i>>2&3,r=i>>1&1,d=i&1;n=n+1;const c=e.getUint8(n);n=n+1;const h=t,l=new Uint8Array(e.buffer.slice(n,n+h));if(o===10&&c===0){const u=e.getUint8(n),p=e.getUint8(n+1),f=u>>3&31,m=(u&7)<<1|p>>7,k=p>>3&15,y=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],w=`mp4a.40.${f}`,U=y[m];return{soundFormat:o,soundRate:a,soundSize:r,soundType:d,accPacketType:c,data:l,samplingFrequencyIndex:m,channelConfiguration:k,codec:w,sampleRate:U}}return{soundFormat:o,soundRate:a,soundSize:r,soundType:d,accPacketType:c,data:l}};parseVideo=(e,s,t)=>{let n=s;const i=e.getUint8(n),o=i>>4&15,a=i&15;n=n+1;const r=e.getUint8(n);n=n+1;const d=_(e,n);n=n+3;const c=t-5,h=new Uint8Array(e.buffer.slice(n,n+c));switch(a){case 7:if(r===0){const l=P(h);return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h,...l}}else if(r===1){const l=[],u=n+t-5;for(;!(n+4>u);){const p=e.getUint32(n,!1),f=new Uint8Array(e.buffer.slice(n,n+4+p));n+=4+p,l.push(f)}return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h,nalus:l}}break;default:throw new Error("Unsupported codecID")}return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h}};getAmfType=(e,s)=>e.getUint8(s);getAMFName=(e,s,t)=>{const n=new Uint8Array(e.buffer.slice(s,s+t));return this.textDecoder?.decode(n)||""};getAMFValue=(e,s,t)=>{let n=s,i,o=0;switch(t){case 0:i=e.getFloat64(n,!1),o=8;break;case 1:i=!!e.getUint8(n),o=1;break;case 2:{i="";const r=e.getUint16(n,!1);n=n+2;const d=new Int8Array(e.buffer,n,r).filter(h=>h!==0);i=(this.textDecoder?.decode(d)||"").trim(),o=2+r}break;case 3:for(i={};n<e.byteLength;){const r=e.getUint16(n,!1);if(r===0)break;n=n+2;const d=this.getAMFName(e,n,r);n=n+r;const c=this.getAmfType(e,n);if(c===6)break;n=n+1;const h=this.getAMFValue(e,n,c);n=n+h.length,i[d]=h.value,o=2+r+1+h.length}break;case 8:{i={};const r=e.getUint32(n,!1);n=n+4;for(let d=0;d<r;d++){const c=e.getUint16(n,!1);n=n+2;const h=this.getAMFName(e,n,c);n=n+c;const l=this.getAmfType(e,n);n=n+1;const u=this.getAMFValue(e,n,l);n=n+u.length,i[h]=u.value,o=2+c+1+u.length}}break;case 10:{i=[];const r=e.getUint32(n,!1);n=n+4;for(let d=0;d<r;d++){const c=this.getAmfType(e,n);n=n+1;const h=this.getAMFValue(e,n,c);n=n+h.length,i.push(h.value),o=1+h.length}}break}return{amfType:t,length:o,value:i}}}class J{pattern;cacher=new K;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case"flv":this.parser=new Q;break;case"hls":this.parser=new Y;break;default:throw new Error("is error pattern.")}this.parser.on.debug=s=>this.on.debug&&this.on.debug(s),this.parser.on.info=s=>this.on.info&&this.on.info(s),this.parser.on.config=s=>this.on.config&&this.on.config(s),this.parser.on.chunk=s=>{this.cacher.pushChunk(s),this.on.chunk&&this.on.chunk(s)}};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 new Error("You need to set the pattern.");if(!this.parser)throw new Error("You need to init parser.");for(;;){const e=this.cacher.next(this.offset);if(this.offset=0,!e)break;this.offset=await this.parser.parse(e)}this.isParseing=!1}catch{this.destroy()}}}class Z{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],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=e=>{this.audio.destroy(),this.audioDecoderConfig={...e},this.audioDecoder=new AudioDecoder({output:s=>{const t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:s,playbackRate:t})},error:s=>{this.on.audio.error&&this.on.audio.error(s)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:async s=>{this.frameStartTime||(this.frameStartTime=s.timestamp);try{const t=s.timestamp-this.frameStartTime+this.baseTime*1e3,n=await createImageBitmap(s);if(s.close(),!n.width||!n.height)return n.close();this.on.video.decode&&this.on.video.decode({timestamp:t,bitmap:n}),this.currentChunk&&this.currentChunk.kind==="video"&&this.currentChunk.nalus&&this.on.nalus&&this.on.nalus(this.currentChunk.nalus)}catch{s.close()}},error:s=>{this.on.video.error&&this.on.video.error(s)}}),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;const s=this.baseTime+performance.now();if(this.lastRenderTime||(this.lastRenderTime=s),this.fps=Math.round(1e3/(s-this.lastRenderTime)),this.lastRenderTime=s,this.nextRenderTime){const t=this.lastRenderTime-this.nextRenderTime;e-=t}this.nextRenderTime=this.lastRenderTime+e,this.decodeTimer=setTimeout(()=>{this.decode(),this.initDecodeInterval()},e)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;this.currentChunk=this.pendingChunks.shift(),!!this.currentChunk;){const e=this.pendingChunks.length;if(this.frameTrack){const[n,i]=this.fameTrackOption[this.pattern];if(e<=n&&(this.isFrameTrack=!1),e>=i&&(this.isFrameTrack=!0),this.isFrameTrack){const o=Math.min(1+(e-n)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(o.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){const{decodingSpeed:n,decodingSpeedRatio:i,fps:o}=this;this.on.analysis({decodingSpeed:n,decodingSpeedRatio:i,fps:o,cacheLength:e})}const{kind:s,init:t}=this.currentChunk;switch(s){case"audio":this.decodeAudio(t);break;case"video":this.decodeVideo(t);break}if(s==="video")break}this.isProcessing=!1}};decodeAudio=e=>{if(!this.audioDecoder)return;const s=new EncodedAudioChunk(e);this.audioDecoder.decode(s)};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)){const s=new EncodedVideoChunk(e);this.videoDecoder.decode(s)}};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}}}class ee{renderMap=new Map;constructor(){}push=async e=>{const{timestamp:s}=e,{bitmap:t}=e;try{const n=[...this.renderMap.keys()];for(const i of n){const o=this.renderMap.get(i);if(!o)continue;const{pause:a=!1,writer:r,offscreen:d,option:c}=o;if(a===!0)continue;const h=async l=>{if(r){const u=new VideoFrame(l,{timestamp:s});try{await r.write(u)}catch{}u.close()}else d&&(d.width=l.width,d.height=l.height,d?.getContext("2d")?.drawImage(l,0,0))};if(i==="default")await h(t);else if(c){const{sx:l=0,sy:u=0,sw:p=t.width,sh:f=t.height}=c,m=await createImageBitmap(t,l,u,p,f);await h(m)}}}catch{}t.close()};addCut=e=>{const{key:s,writable:t,offscreen:n,option:i}={key:"default",...e};if(t){const o=t.getWriter();this.renderMap.set(s,{writer:o,option:i,pause:!1})}else this.renderMap.set(s,{offscreen:n,option:i,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{const{key:s,cutOption:t}={key:"default",...e},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,option:t})};setPause=e=>{const{key:s,pause:t}={key:"default",...e},n=this.renderMap.get(s);n&&this.renderMap.set(s,{...n,pause:t})};destroy=()=>{this.renderMap=new Map}}b.Decoder=Z,b.DecoderWorker=S,b.Demuxer=J,b.DemuxerWorker=v,b.PrPlayer=H,b.Render=ee,b.RenderWorker=R,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pr-player",
3
3
  "description": "对 flv hls 格式的地址进行解析 并输出 MediaStream,提供 demuxer 层(info、chunk)回调、 decoder 层(audio、video、sei)回调 ,提供 cut 等相关能力,以支持根据业务层 SEI 对视频进行剪切渲染。",
4
- "version": "0.3.5",
4
+ "version": "0.3.6",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist"