pr-player 0.3.5 → 0.3.7
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 +1801 -1706
- package/dist/index.umd.cjs +2 -4
- package/package.json +4 -4
- /package/dist/{PrPlayer.d.ts → src/PrPlayer.d.ts} +0 -0
- /package/dist/{PrResolves.d.ts → src/PrResolves.d.ts} +0 -0
- /package/dist/{audioPlayer → src/audioPlayer}/audioPlayer.d.ts +0 -0
- /package/dist/{decoder → src/decoder}/Decoder.d.ts +0 -0
- /package/dist/{decoder → src/decoder}/DecoderWorker.d.ts +0 -0
- /package/dist/{decoder → src/decoder}/decoder.worker.d.ts +0 -0
- /package/dist/{decoder → src/decoder}/type.d.ts +0 -0
- /package/dist/{demuxer → src/demuxer}/264Parser.d.ts +0 -0
- /package/dist/{demuxer → src/demuxer}/Cacher.d.ts +0 -0
- /package/dist/{demuxer → src/demuxer}/Demuxer.d.ts +0 -0
- /package/dist/{demuxer → src/demuxer}/DemuxerWorker.d.ts +0 -0
- /package/dist/{demuxer → src/demuxer}/demuxer.worker.d.ts +0 -0
- /package/dist/{demuxer → src/demuxer}/flv264Parser.d.ts +0 -0
- /package/dist/{demuxer → src/demuxer}/ts264Parser.d.ts +0 -0
- /package/dist/{demuxer → src/demuxer}/type.d.ts +0 -0
- /package/dist/{index.d.ts → src/index.d.ts} +0 -0
- /package/dist/{render → src/render}/Render.d.ts +0 -0
- /package/dist/{render → src/render}/RenderWorker.d.ts +0 -0
- /package/dist/{render → src/render}/render.worker.d.ts +0 -0
- /package/dist/{render → src/render}/type.d.ts +0 -0
- /package/dist/{tools.d.ts → src/tools.d.ts} +0 -0
- /package/dist/{type.d.ts → src/type.d.ts} +0 -0
package/dist/index.umd.cjs
CHANGED
|
@@ -1,4 +1,2 @@
|
|
|
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"})}));
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`pr-player`]={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t="(function(){var e=class{pendingPayloads=[];payload=new Uint8Array;chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);let t=this.pendingPayloads.shift();if(!t)return!1;let n=new Uint8Array(this.payload.byteLength+t.byteLength);return n.set(this.payload,0),n.set(t,this.payload.byteLength),this.payload=n,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array,this.chunks=[]}};let t=(e,t)=>{let n=new Uint8Array(e),r=new Uint8Array(t),i=new Uint8Array(11+n.length+r.length),a=0;return i[a++]=1,i[a++]=n[1],i[a++]=n[2],i[a++]=n[3],i[a++]=255,i[a++]=225,i[a++]=n.length>>8&255,i[a++]=n.length&255,i.set(n,a),a+=n.length,i[a++]=1,i[a++]=r.length>>8&255,i[a++]=r.length&255,i.set(r,a),i},n=e=>{let t=0,n=new DataView(e.buffer),r=n.getUint8(t);if(t+=1,r!==1)throw Error(`Invalid AVC version`);let i=n.getUint8(t)&255;t+=1;let a=n.getUint8(t)&255;t+=1;let o=n.getUint8(t)&255;t+=1;let s=`avc1.${Array.from([i,a,o],e=>e.toString(16).padStart(2,`0`)).join(``)}`,c=(n.getUint8(t)&3)-1;t+=1;let l=n.getUint8(t)&31;t+=1;let u=n.getUint16(t,!1);t+=2;let d=new Uint8Array(n.buffer.slice(t,t+u));t+=u;let f=n.getUint8(t)&31;t+=1;let p=n.getUint16(t,!1);t+=2;let m=new Uint8Array(n.buffer.slice(t,t+p));return t+=p,{version:r,codec:s,profile:i,compatibility:a,level:o,lengthSizeMinusOne:c,numOfSequenceParameterSets:l,sequenceParameterSetLength:u,sps:d,numOfPictureParameterSets:f,pictureParameterSetLength:p,pps:m}},r=e=>{let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t},i=e=>{let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e){let e=t;n.set(e,r),r+=e.length}return n},a=e=>{let t=`unknown`;switch(e){case 1:case 2:case 27:case 36:t=`video`;break;case 3:case 4:case 15:t=`audio`;break;case 6:t=`subtitle`;break;case 134:t=`ad`;break}return t};var o=class{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let t=0;for(;!(t+188>e.byteLength);){if(e.getInt8(t)!=71){t++;continue}await this.parsePacket(e,t),t+=188}return t};parsePacket=async(e,t)=>{if(t+188>e.byteLength||e.getUint8(t)!==71)throw Error(`Invalid TS packet`);let n=t,r=this.parseHeader(e,n);n+=4;let{transport_error_indicator:i,pid:a,payload_unit_start_indicator:o,adaptation_field_control:s}=r;if(i===1||a===void 0)return;let c=184;if(s===2||s===3){let t=e.getUint8(n);n+=1,this.parseAdaptationField(e,n),n+=t,c-=t}if(s===3&&--c,s===1||s===3){let t=new Uint8Array(e.buffer.slice(n,n+c));if(a===0)return this.parsePAT(e,n);{let{programs:t=[]}=this.pat||{};if(t.find(e=>e.pmt_pid===a))return this.parsePMT(e,n)}let{streams:r=[]}=this.pmt||{},i=r.find(e=>e.elementary_pid===a);if(i){if(o===1){let e=this.payloadMap.get(a);if(e){switch(i.kind){case`audio`:{let t=await this.parseAudio(e);this.on.chunk&&this.on.chunk(t)}break;case`video`:{let t=await this.parseVideo(e);this.on.chunk&&this.on.chunk(t),await new Promise(e=>setTimeout(()=>e(!0),0))}break}this.payloadMap.delete(a)}}{this.payloadMap.has(a)||this.payloadMap.set(a,new Uint8Array);let e=this.payloadMap.get(a),n=new Uint8Array(e.byteLength+t.byteLength);n.set(e,0),n.set(t,e.byteLength),this.payloadMap.set(a,n)}}}};parseHeader=(e,t)=>{let n=t,r=e.getUint8(n),i=e.getUint8(n+1),a=e.getUint8(n+2),o=e.getUint8(n+3),s=(i&128)>>7;return s===1?{sync_byte:r,transport_error_indicator:s}:{sync_byte:r,transport_error_indicator:s,payload_unit_start_indicator:(i&64)>>6,transport_priority:(i&32)>>5,pid:(i&31)<<8|a,transport_scrambling_control:(o&192)>>6,adaptation_field_control:o>>4&3,continuity_counter:o&15}};parsePAT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==0)throw Error(`Invalid PAT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u}}let i=[];{let t=r.section_length-5-4,a=n+t;for(;n<a;){let t=e.getUint16(n),r=e.getUint16(n+2)&8191;n+=4,t!==0&&r>=32&&r<=8190&&i.push({program_number:t,pmt_pid:r})}}let a=e.getUint32(n);this.pat={header:r,programs:i,crc32:a},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==2)throw Error(`Invalid PMT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1;let d=e.getUint16(n)&8191;n+=2;let f=e.getUint16(n)&4095;n+=2,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u,pcr_pid:d,program_info_length:f}}let i=[];{let t=r.section_length-9-4,o=n+t;for(;n<o;){let t=e.getUint8(n),r=a(t),o=e.getUint16(n+1)&8191,s=e.getUint16(n+3)&4095;if(n+=5,o<32||o>8190){console.warn(`Invalid elementary_pid: 0x${o.toString(16)}`);continue}i.push({kind:r,stream_type:t,elementary_pid:o,es_info_length:s})}}let o=e.getUint32(n);this.pmt={header:r,streams:i,crc32:o},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(e,t)=>{let n=t,r,i,a,o,s=e.getUint8(n),c=!!(s&128),l=!!(s&64),u=!!(s&32),d=!!(s&16),f=!!(s&8),p=!!(s&4),m=!!(s&2),h=!!(s&1);n+=1;let g=(e,t)=>{let n=BigInt(0);n|=BigInt(e.getUint16(t))<<25n,n|=BigInt(e.getUint16(t+1))<<17n,n|=BigInt(e.getUint16(t+2))<<9n,n|=BigInt(e.getUint16(t+3))<<1n,n|=BigInt(e.getUint16(t+4)>>7);let r=(e.getUint16(t+4)&1)<<8|e.getUint16(t+5);return n=n*300n+BigInt(r),n};if(d&&(r=g(e,n),n+=6),f&&(i=g(e,n),n+=6),p&&(a=e.getInt8(n),n+=1),m){let t=e.getUint8(n);n+=1,o=new Uint8Array(e.buffer,n,t),n+=t}return{discontinuity_indicator:c,random_access_indicator:l,elementary_stream_priority_indicator:u,pcr_flag:d,opcr_flag:f,splicing_point_flag:p,transport_private_data_flag:m,adaptation_field_extension_flag:h,pcr:r,opcr:i,splice_countdown:a,transport_private_data:o}};parseAudio=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts audio payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{if(!this.audioConfig&&t.getUint8(n)===255){let e=t.getUint8(n+2),r=t.getUint8(n+3),i,a;a=e>>2&15,i=(e&1)<<2|r>>6,this.audioConfig={kind:`audio`,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],numberOfChannels:i},this.on.config&&this.on.config(this.audioConfig)}let{dts:e=0,pts:a=0}=r;return{kind:`audio`,type:`key`,dts:e,pts:a,cts:a-e,data:i.slice(7)}}};parseVideo=async e=>{let r=new DataView(e.buffer),a=0,o,s;{let e=r.getUint8(a)===0&&r.getUint8(a+1)===0&&r.getUint8(a+2)===1;if(a+=3,!e)throw Error(`invalid ts video payload.`);let t=r.getUint8(a);a+=1;let n=r.getUint8(a)<<8|r.getUint8(a+1);a+=2;let i,s,c,l,u;{let e=r.getUint8(a);a+=1,i=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=r.getUint8(a);a+=1;let t=e>>6,n=r.getUint8(a);a+=1,(t&2)==2&&(d=this.parsePtsDts(r,a)),f=(t&1)==1?this.parsePtsDts(r,a+5):d,a+=n}o={stream_id:t,pes_packet_length:n,scrambling_control:i,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}s=e.slice(a);{let e=this.getNalus(s);if(!this.videoConfig){let r,i;if(r=e.find(e=>e.type===7)?.nalu.slice(4),i=e.find(e=>e.type===8)?.nalu.slice(4),r&&i){let e=t(r,i),{codec:a}=n(e);this.videoConfig={kind:`video`,codec:a,description:e,sps:r,pps:i},this.on.config&&this.on.config(this.videoConfig)}}let r=[],a=`delta`;for(let t of e){let{type:e,nalu:n}=t;switch(e){case 6:case 9:r.push(n);break;case 1:a=`delta`,r.push(n);break;case 5:a=`key`,r.push(n);break}}let c=i(r),{dts:l=0,pts:u=0}=o,d=u-l;return{kind:`video`,type:a,dts:l,pts:u,cts:d,data:c,nalus:r}}};parsePtsDts(e,t){let n=e.getUint8(t),r=e.getUint8(t+1),i=e.getUint8(t+2),a=e.getUint8(t+3),o=e.getUint8(t+4),s=(BigInt(n)&14n)<<29n|(BigInt(r)&255n)<<22n|(BigInt(i)&254n)<<14n|(BigInt(a)&255n)<<7n|(BigInt(o)&254n)>>1n;return Number(s)/90}getNalus=e=>{let t=[],n=0;for(;!(n+4>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}n+=3;let i=n,a=e[n]&31;for(n+=1;!(n+1>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}break}let o=n-i;if(e[n-1]===0&&--o,o!==0){let n=r(e.slice(i,i+o));t.push({type:a,nalu:n})}}return t}};let s=(e,t)=>e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2);var c=class{audioConfig;videoConfig;header;textDecoder=new TextDecoder(`utf-8`);on={};constructor(){}parse=async e=>{let t=0;for(this.header||(this.parseHeader(e,t),t+=9);this.isSurplusTag(e,t)!==!1;){let{tagType:n,dataSize:r,timestamp:i}=this.parseTagHeader(e,t+4);if(n){let a=this.parseTagBody(n,e,t+4+11,r);switch(n){case`script`:this.on.info&&this.on.info(a);break;case`audio`:{let{accPacketType:e}=a;if(e===0){let{codec:e,sampleRate:t,channelConfiguration:n}=a;this.audioConfig={kind:`audio`,codec:e,sampleRate:t,numberOfChannels:n},this.on.config&&this.on.config(this.audioConfig)}else{let{cts:e,data:t}=a,n=e===void 0?void 0:e+i;this.on.chunk&&this.on.chunk({kind:`audio`,type:`key`,dts:i,pts:n,cts:e,data:t})}}break;case`video`:{let{avcPacketType:e}=a;if(e===0){let{codec:e,sps:t,pps:n,data:r}=a;this.videoConfig={kind:`video`,codec:e,description:r,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}else{let{frameType:e,cts:t,data:n,nalus:r}=a,o=e===1?`key`:`delta`,s=t===void 0?void 0:t+i;this.on.chunk&&this.on.chunk({kind:`video`,type:o,dts:i,pts:s,cts:t,data:n,nalus:r})}}break}t=t+4+11+r}await new Promise(e=>setTimeout(()=>e(!0),8))}return t};parseHeader=(e,t)=>{let n,r,i,a;n=e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),r=e.getUint8(3);{let[,,t,,n]=e.getUint8(0).toString(2).padStart(5,`0`).split(``);i={audio:n===`1`,video:t===`1`}}a=e.getUint32(5),this.header={signature:n,version:r,flags:i,dataOffset:a}};isSurplusTag=(e,t)=>{let n=!0,r=e.byteLength;if(t+4>r)n=!1;else if(t+4+11>r)n=!1;else{let i=s(e,t+4+1);t+4+11+i>r&&(n=!1)}return n};parseTagHeader=(e,t)=>{let n,r,i,a,o;{let r=e.getUint8(t),i;switch(r){case 18:i=`script`;break;case 8:i=`audio`;break;case 9:i=`video`;break}n=i}return r=s(e,t+1),i=s(e,t+4),a=e.getUint8(t+7),o=s(e,t+8),{tagType:n,dataSize:r,timestamp:i,timestampExtended:a,streamID:o}};parseTagBody=(e,t,n,r)=>{let i;switch(e){case`script`:i=this.parseMetaData(t,n);break;case`audio`:i=this.parseAudio(t,n,r);break;case`video`:i=this.parseVideo(t,n,r);break}return i};parseMetaData=(e,t)=>{let n=t;if(e.getUint8(n)!==2)throw Error(`Invalid AMF type for onMetaData (expected 0x02)`);n+=1;let r=e.getUint16(n,!1);n+=2;{let t=new Int8Array(e.buffer.slice(n,n+r));if((this.textDecoder?.decode(t)||``)!==`onMetaData`)throw Error(`Expected 'onMetaData' string`);n+=r}let i=this.getAmfType(e,n);return n+=1,this.getAMFValue(e,n,i).value};parseAudio=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i>>2&3,s=i>>1&1,c=i&1;r+=1;let l=e.getUint8(r);r+=1;let u=n,d=new Uint8Array(e.buffer.slice(r,r+u));if(a===10&&l===0){let t=e.getUint8(r),n=e.getUint8(r+1),i=t>>3&31,u=(t&7)<<1|n>>7;return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d,samplingFrequencyIndex:u,channelConfiguration:n>>3&15,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][u]}}return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d}};parseVideo=(e,t,r)=>{let i=t,a=e.getUint8(i),o=a>>4&15,c=a&15;i+=1;let l=e.getUint8(i);i+=1;let u=s(e,i);i+=3;let d=r-5,f=new Uint8Array(e.buffer.slice(i,i+d));switch(c){case 7:if(l===0)return{frameType:o,codecID:c,avcPacketType:l,cts:u,data:f,...n(f)};if(l===1){let t=[],n=i+r-5;for(;!(i+4>n);){let n=e.getUint32(i,!1),r=new Uint8Array(e.buffer.slice(i,i+4+n));i+=4+n,t.push(r)}return{frameType:o,codecID:c,avcPacketType:l,cts:u,data:f,nalus:t}}break;default:throw Error(`Unsupported codecID`)}return{frameType:o,codecID:c,avcPacketType:l,cts:u,data:f}};getAmfType=(e,t)=>e.getUint8(t);getAMFName=(e,t,n)=>{let r=new Uint8Array(e.buffer.slice(t,t+n));return this.textDecoder?.decode(r)||``};getAMFValue=(e,t,n)=>{let r=t,i,a=0;switch(n){case 0:i=e.getFloat64(r,!1),a=8;break;case 1:i=!!e.getUint8(r),a=1;break;case 2:{i=``;let t=e.getUint16(r,!1);r+=2;let n=new Int8Array(e.buffer,r,t).filter(e=>e!==0);i=(this.textDecoder?.decode(n)||``).trim(),a=2+t}break;case 3:for(i={};r<e.byteLength;){let t=e.getUint16(r,!1);if(t===0)break;r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);if(o===6)break;r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}break;case 8:{i={};let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=e.getUint16(r,!1);r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}}break;case 10:{i=[];let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=this.getAmfType(e,r);r+=1;let n=this.getAMFValue(e,r,t);r+=n.length,i.push(n.value),a=1+n.length}}break}return{amfType:n,length:a,value:i}}};let l=new class{pattern;cacher=new e;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case`flv`:this.parser=new c;break;case`hls`:this.parser=new o;break;default:throw Error(`is error pattern.`)}this.parser.on.debug=e=>this.on.debug&&this.on.debug(e),this.parser.on.info=e=>this.on.info&&this.on.info(e),this.parser.on.config=e=>this.on.config&&this.on.config(e),this.parser.on.chunk=e=>{this.cacher.pushChunk(e),this.on.chunk&&this.on.chunk(e)}};push=e=>{this.cacher.push(e),this.isParseing===!1&&this.parse()};destroy=()=>{this.cacher.destroy(),this.isParseing=!1,this.offset=0};parse=async()=>{try{if(this.isParseing=!0,!this.pattern)throw Error(`You need to set the pattern.`);if(!this.parser)throw Error(`You need to init parser.`);for(;;){let e=this.cacher.next(this.offset);if(this.offset=0,!e)break;this.offset=await this.parser.parse(e)}this.isParseing=!1}catch{this.destroy()}}};l.on.info=e=>postMessage({action:`on.info`,data:e}),l.on.config=e=>postMessage({action:`on.config`,data:e}),l.on.chunk=e=>postMessage({action:`on.chunk`,data:e}),l.on.debug=e=>postMessage({action:`on.debug`,data:e}),onmessage=e=>{let{action:t,data:n}=e.data,r=l[t];r&&r(n)}})();",n=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,t],{type:`text/javascript;charset=utf-8`});function r(e){let r;try{if(r=n&&(self.URL||self.webkitURL).createObjectURL(n),!r)throw``;let t=new Worker(r,{name:e?.name});return t.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(r)}),t}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(t),{name:e?.name})}}var i=class{worker=new r;on={};constructor(){this.worker.onmessage=e=>{let{action:t,data:n}=e.data;switch(t){case`on.info`:this.on.info&&this.on.info(n);break;case`on.config`:this.on.config&&this.on.config(n);break;case`on.chunk`:this.on.chunk&&this.on.chunk(n);break;case`on.debug`:this.on.debug&&this.on.debug(n);break}}}init=e=>this.worker.postMessage({action:`init`,data:e});push=e=>this.worker.postMessage({action:`push`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`,data:{}}),this.worker.terminate()}},a="(function(){let e=new class{pattern=`flv`;audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;baseTime=0;pendingChunks=[];currentChunk;isProcessing=!1;decodeTimer=0;frameTrack=!1;isFrameTrack=!1;fameTrackOption={flv:[30,50],hls:[200,300],dash:[50,100],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:e=>{let t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:e,playbackRate:t})},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:async e=>{this.frameStartTime||=e.timestamp;try{let t=e.timestamp-this.frameStartTime+this.baseTime*1e3,n=await createImageBitmap(e);if(e.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{e.close()}},error:e=>{this.on.video.error&&this.on.video.error(e)}}),this.videoDecoder.configure(this.videoDecoderConfig)};setFrameTrack=e=>{this.frameTrack=e,this.frameTrack===!1&&(this.decodingSpeedRatio=1)};push=e=>{this.pendingChunks.push(e)};destroy=()=>{this.audio.destroy(),this.video.destroy(),this.pendingChunks=[],this.firstVideoChunkTimestamp=void 0,this.secondVideoChunkTimestamp=void 0,this.frameStartTime=void 0,this.lastRenderTime=void 0,this.nextRenderTime=void 0,clearInterval(this.decodeTimer)};initDecodeInterval=()=>{let e=this.decodingSpeed/this.decodingSpeedRatio,t=this.baseTime+performance.now();if(this.lastRenderTime||=t,this.fps=Math.round(1e3/(t-this.lastRenderTime)),this.lastRenderTime=t,this.nextRenderTime){let t=this.lastRenderTime-this.nextRenderTime;e-=t}this.nextRenderTime=this.lastRenderTime+e,this.decodeTimer=setTimeout(()=>{this.decode(),this.initDecodeInterval()},e)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;this.currentChunk=this.pendingChunks.shift(),this.currentChunk;){let e=this.pendingChunks.length;if(this.frameTrack){let[t,n]=this.fameTrackOption[this.pattern];if(e<=t&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){let n=Math.min(1+(e-t)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(n.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){let{decodingSpeed:t,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:t,decodingSpeedRatio:n,fps:r,cacheLength:e})}let{kind:t,init:n}=this.currentChunk;switch(t){case`audio`:this.decodeAudio(n);break;case`video`:this.decodeVideo(n);break}if(t===`video`)break}this.isProcessing=!1}};decodeAudio=e=>{if(!this.audioDecoder)return;let t=new EncodedAudioChunk(e);this.audioDecoder.decode(t)};decodeVideo=e=>{if(this.videoDecoder&&(e.type===`key`&&(this.hasKeyFrame=!0),this.firstVideoChunkTimestamp?this.secondVideoChunkTimestamp||(this.secondVideoChunkTimestamp=e.timestamp,this.decodingSpeed=(this.secondVideoChunkTimestamp-this.firstVideoChunkTimestamp)/1e3):this.firstVideoChunkTimestamp=e.timestamp,this.hasKeyFrame)){let t=new EncodedVideoChunk(e);this.videoDecoder.decode(t)}};audio={flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}};e.on.audio.decode=e=>postMessage({action:`on.audio.decode`,data:e},[e.audioData]),e.on.audio.error=e=>postMessage({action:`on.audio.error`,data:e}),e.on.video.decode=e=>postMessage({action:`on.video.decode`,data:e},[e.bitmap]),e.on.video.error=e=>postMessage({action:`on.video.error`,data:e}),e.on.nalus=e=>postMessage({action:`on.nalus`,data:e}),e.on.analysis=e=>postMessage({action:`on.analysis`,data:e}),onmessage=t=>{let{action:n,data:r}=t.data,i=e[n];i&&i(r)}})();",o=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,a],{type:`text/javascript;charset=utf-8`});function s(e){let t;try{if(t=o&&(self.URL||self.webkitURL).createObjectURL(o),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(a),{name:e?.name})}}var c=class{worker=new s;on={audio:{},video:{}};constructor(){this.worker.onmessage=e=>{let{action:t,data:n}=e.data;switch(t){case`on.audio.decode`:this.on.audio.decode&&this.on.audio.decode(n);break;case`on.audio.error`:this.on.audio.error&&this.on.audio.error(n);break;case`on.video.decode`:this.on.video.decode&&this.on.video.decode(n);break;case`on.video.error`:this.on.video.error&&this.on.video.error(n);break;case`on.nalus`:this.on.nalus&&this.on.nalus(n);break;case`on.analysis`:this.on.analysis&&this.on.analysis(n);break}}}init=e=>this.worker.postMessage({action:`init`,data:e});initAudio=e=>this.worker.postMessage({action:`initAudio`,data:e});initVideo=e=>this.worker.postMessage({action:`initVideo`,data:e});push=e=>this.worker.postMessage({action:`push`,data:e});setFrameTrack=e=>this.worker.postMessage({action:`setFrameTrack`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`}),this.worker.terminate()}},l="(function(){let e=new class{renderMap=new Map;constructor(){}push=async e=>{let{timestamp:t}=e,{bitmap:n}=e;try{let e=[...this.renderMap.keys()];for(let r of e){let e=this.renderMap.get(r);if(!e)continue;let{pause:i=!1,writer:a,offscreen:o,option:s}=e;if(i===!0)continue;let c=async e=>{if(a){let n=new VideoFrame(e,{timestamp:t});try{await a.write(n)}catch{}n.close()}else o&&(o.width=e.width,o.height=e.height,o?.getContext(`2d`)?.drawImage(e,0,0))};if(r===`default`)await c(n);else if(s){let{sx:e=0,sy:t=0,sw:r=n.width,sh:i=n.height}=s;await c(await createImageBitmap(n,e,t,r,i))}}}catch{}n.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,option:i}={key:`default`,...e};if(n){let e=n.getWriter();this.renderMap.set(t,{writer:e,option:i,pause:!1})}else this.renderMap.set(t,{offscreen:r,option:i,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{let{key:t,cutOption:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,option:n})};setPause=e=>{let{key:t,pause:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,pause:n})};destroy=()=>{this.renderMap=new Map}};onmessage=t=>{let{action:n,data:r}=t.data,i=e[n];i&&i(r)}})();",u=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,l],{type:`text/javascript;charset=utf-8`});function d(e){let t;try{if(t=u&&(self.URL||self.webkitURL).createObjectURL(u),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(l),{name:e?.name})}}var f=class{worker=new d;constructor(){}push=e=>this.worker.postMessage({action:`push`,data:e},[e.bitmap]);addCut=e=>{let t=[];e.writable&&t.push(e.writable),e.offscreen&&t.push(e.offscreen),this.worker.postMessage({action:`addCut`,data:e},t)};delCut=e=>this.worker.postMessage({action:`delCut`,data:e});setCut=e=>this.worker.postMessage({action:`setCut`,data:e});setPause=e=>this.worker.postMessage({action:`setPause`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`,data:{}}),this.worker.terminate()}},p=class{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,t){this.inputStream=e,t&&(this.audioContext=t),this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.inputGainNode=this.audioContext.createGain(),this.inputGainNode.gain.setValueAtTime(this.inputGain,this.audioContext.currentTime),this.enhanceGainNode=this.audioContext.createGain(),this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime),this.bgsGainNode=this.audioContext.createGain(),this.bgsGainNode.gain.setValueAtTime(this.bgsGain,this.audioContext.currentTime),this.bgmGainNode=this.audioContext.createGain(),this.bgmGainNode.gain.setValueAtTime(this.bgmGain,this.audioContext.currentTime),this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=512,this.analyserArrayData=new Uint8Array(this.analyserNode.frequencyBinCount),this.outputGainNode=this.audioContext.createGain(),this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputStream=this.destinationNode.stream;{let{sourceNode:e,inputGainNode:t,enhanceGainNode:n,bgsGainNode:r,bgmGainNode:i,analyserNode:a,outputGainNode:o,destinationNode:s}=this;e.connect(t),t.connect(n),n.connect(a),r.connect(a),i.connect(a),n.connect(s),r.connect(s),i.connect(s),o.connect(this.audioContext.destination)}this.audioContext.resume()}use=({rnnoise:e})=>{this.rnnoiseWorklet=new e.RnnoiseWorklet};_changeSource=()=>{this.sourceNode.disconnect(),this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.sourceNode.connect(this.inputGainNode)};replaceTrack=e=>{let t=this.inputStream.getTracks();for(let e of t)this.inputStream.removeTrack(e);this.inputStream.addTrack(e),this._changeSource()};stop=()=>{{let e=this.inputStream.getTracks();for(let t of e)t.stop(),this.inputStream.removeTrack(t)}};pause=async e=>{let t=this.inputStream.getTracks();for(let n of t)n.enabled=!e};getStream=()=>this.filterStream(this.outputStream);setMute=(e=!0)=>{this.mute=e,this.analyserNode.disconnect(),e===!1&&this.analyserNode.connect(this.outputGainNode)};setDenoise=async(e=!0)=>{this.rnnoiseWorklet&&(this.inputGainNode.disconnect(),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=()=>{let{analyserNode:e,analyserArrayData:t}=this;e.getByteFrequencyData(t);let n=0;for(let e=0;e<t.length;e++)n+=t[e];return Math.ceil(n/t.length)};mixAudio=(e,t=`bgm`)=>new Promise(async(n,r)=>{try{{let e=this.mixAudioMap.get(t);e&&e.stop()}let r=t===`bgs`?this.bgsGainNode:this.bgmGainNode,i=this.audioContext.createBufferSource();this.mixAudioMap.set(t,i),i.buffer=e,i.connect(r),i.onended=()=>{i.disconnect(r),this.mixAudioMap.delete(t),n(!0)},i.start(0)}catch(e){r(e)}});mixAudioStop=e=>{this.mixAudioMap.get(e)?.stop()};changeMix=(e,t)=>{let n=e===`bgs`?this.bgsGainNode:this.bgmGainNode;t?n.connect(this.destinationNode):n.disconnect(this.destinationNode)}},m=async(e,t)=>{try{let{format:n,numberOfChannels:r,numberOfFrames:i,sampleRate:a}=t,o=e.createBuffer(r,i,a);for(let e=0;e<r;e++){let r=t.allocationSize({planeIndex:e}),a=new Uint8Array(r);t.copyTo(a,{planeIndex:e});let s=new DataView(a.buffer),c=o.getChannelData(e);for(let e=0;e<i;e++){let t;switch(n){case`s16`:case`s16-planar`:t=s.getInt16(e*2,!0)/32768;break;case`f32`:case`f32-planar`:t=s.getFloat32(e*4,!0);break;case`u8`:case`u8-planar`:t=(s.getUint8(e)-128)/128;break;default:throw Error(`Unsupported audio format: ${n}`)}c[e]=Math.max(-1,Math.min(1,t))}}return o}catch(e){throw console.error(`Failed to convert AudioData to AudioBuffer:`,e),e}},h=class{prAudioStream;audioContext;destination;stream=new MediaStream;nextStartTime=0;pendingSources=[];constructor(){}init=e=>{e||=new(window.AudioContext||window.webkitAudioContext),this.audioContext=e,this.destination=this.audioContext.createMediaStreamDestination(),this.stream=new MediaStream,this.stream.addTrack(this.destination.stream.getAudioTracks()[0]),this.prAudioStream=new p(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(e){let{audioData:t,playbackRate:n=1}=e;if(!this.audioContext||!this.destination)return;let r=await m(this.audioContext,t);if(t.close(),!r)return;let i=this.audioContext.createBufferSource();i.buffer=r,i.playbackRate.value=n;let a=-1200*Math.log2(n);i.detune.value=a,i.connect(this.destination);let o=Math.max(this.nextStartTime,this.audioContext.currentTime);this.nextStartTime=o+r.duration/n,i.start(o),this.pendingSources.push(i),i.onended=()=>{this.pendingSources=this.pendingSources.filter(e=>e!==i)},this.audioContext.state===`suspended`&&await this.audioContext.resume()}getStream=()=>this.prAudioStream?.getStream();destroy(){this.audioContext?.close(),this.audioContext=void 0,this.destination=void 0,this.nextStartTime=0,this.prAudioStream?.stop(),this.pendingSources.forEach(e=>e.stop()),this.pendingSources=[]}},g=e=>{let t=e.toLowerCase();return t.includes(`.m3u8`)||t.includes(`hls`)||t.includes(`master.m3u8`)||t.match(/index\d*\.m3u8/)?`hls`:t.includes(`.mpd`)||t.includes(`dash`)?`dash`:t.startsWith(`rtmp://`)||t.startsWith(`rtmps://`)?`rtmp`:t.includes(`.flv`)||t.includes(`flv`)&&!t.includes(`flash`)?`flv`:`unknown`},_=e=>{let t=e?.getTracks()||[];for(let e of t)e.stop()},v=class{resolvesMap=new Map;index=0;constructor(){}add=(e,t=()=>!1,n=0)=>new Promise(r=>{if(t())return r(!0);this.resolvesMap.has(e)||this.resolvesMap.set(e,new Map),this.index++;let i=`${this.index}`;if(n=Math.max(0,n),n===0){this.resolvesMap.get(e)?.set(i,{resolve:r,timer:0});return}let a=window.setTimeout(()=>{this.emit(e)},n);this.resolvesMap.get(e)?.set(i,{resolve:r,timer:a})});emit=async e=>{let t=this.resolvesMap.get(e);if(!t)return;let n=[...t.keys()];for(let e of n){let n=t.get(e);n&&(clearTimeout(n.timer),n.resolve(),t.delete(e))}}},y=(e,t)=>{let n=new Uint8Array(e),r=new Uint8Array(t),i=new Uint8Array(11+n.length+r.length),a=0;return i[a++]=1,i[a++]=n[1],i[a++]=n[2],i[a++]=n[3],i[a++]=255,i[a++]=225,i[a++]=n.length>>8&255,i[a++]=n.length&255,i.set(n,a),a+=n.length,i[a++]=1,i[a++]=r.length>>8&255,i[a++]=r.length&255,i.set(r,a),i},b=e=>{let t=0,n=new DataView(e.buffer),r=n.getUint8(t);if(t+=1,r!==1)throw Error(`Invalid AVC version`);let i=n.getUint8(t)&255;t+=1;let a=n.getUint8(t)&255;t+=1;let o=n.getUint8(t)&255;t+=1;let s=`avc1.${Array.from([i,a,o],e=>e.toString(16).padStart(2,`0`)).join(``)}`,c=(n.getUint8(t)&3)-1;t+=1;let l=n.getUint8(t)&31;t+=1;let u=n.getUint16(t,!1);t+=2;let d=new Uint8Array(n.buffer.slice(t,t+u));t+=u;let f=n.getUint8(t)&31;t+=1;let p=n.getUint16(t,!1);t+=2;let m=new Uint8Array(n.buffer.slice(t,t+p));return t+=p,{version:r,codec:s,profile:i,compatibility:a,level:o,lengthSizeMinusOne:c,numOfSequenceParameterSets:l,sequenceParameterSetLength:u,sps:d,numOfPictureParameterSets:f,pictureParameterSetLength:p,pps:m}},x=e=>{let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t},S=e=>{let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e){let e=t;n.set(e,r),r+=e.length}return n},C=e=>{let t=new DataView(e.buffer),n=0,r,i,a;r=t.getUint32(n,!1),n+=4;{let e=t.getUint8(n);i={forbidden_zero_bit:e>>7&1,nal_ref_idc:e>>5&3,nal_unit_type:e&31},n+=1}{let e=r-1;a=new Uint8Array(t.buffer.slice(n,n+e))}return{size:r,header:i,data:a}},w=class{#e={timeout:5*1e3,check:!1};#t=null;constructor(e={}){this.#e={...this.#e,...e}}#n=(e,t)=>new Promise(async n=>{this.#t=new AbortController;let{signal:r}=this.#t,i=this.#e.timeout,a=setTimeout(()=>{this.#t?.abort(`Timeout (${i}ms)`)},i);await fetch(e,{cache:`no-store`,...t,method:`HEAD`,signal:r}).then(e=>{clearTimeout(a),n({status:e.status===200?`successed`:`failed`,reason:e.status===200?``:`HTTP ${e.status}`})}).catch(e=>{if(clearTimeout(a),e.name===`AbortError`){let e=r.reason||`Actively stopped`;n({status:e.includes(`Timeout`)?`timeout`:`stopped`,reason:e})}else n({status:`error`,reason:e.message})})});request=(e,t)=>new Promise(async(n,r)=>{try{this.stop(),this.#e.check&&await this.#n(e),this.#t=new AbortController;let{signal:r}=this.#t;n(await fetch(e,{cache:`no-store`,...t,signal:r}))}catch(e){r(e)}});stop=()=>{if(this.#t?.signal.aborted===!1){let e=Error(`Actively stopped.`);e.name=`AbortError`,this.#t.abort(e)}}},T=class{option={debug:!1,frameTrack:!1};converter=`MediaStreamTrackGenerator`in window?`generator`:`canvas`;prFetch=new w;getSegmentsFetch=new w;prResolves=new v;url=``;start_resolve;demuxerWorker;decoderWorker;audioPlayer;renderWorker;stream;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(e={}){let{debug:t=!1}=e;this.option.debug=t}start=async e=>{await this.stop(),this.url=e;let t=g(e);if(t===`unknown`)throw Error(`This address cannot be parsed.`);switch(this.init(t),t){case`flv`:this.flv.start();break;case`hls`:this.hls.start();break}};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,_(this.stream),this.audioPlayer?.destroy()}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: error`,e)}};getStream=()=>this.stream;setPause=e=>{this.renderWorker?.setPause({pause:e})};setMute=e=>this.audioPlayer?.prAudioStream?.setMute(e);setOutputGain=e=>{this.audioPlayer?.prAudioStream?.setOutputGain(e)};setFrameTrack=e=>{this.option.frameTrack=e,this.decoderWorker?.setFrameTrack(e)};isReady=()=>this.prResolves.add(`isReady`,()=>this.stream?.active===!0);cut={create:(e,t)=>{if(this.converter===`generator`){let n=new MediaStreamTrackGenerator({kind:`video`}),r=new MediaStream([n]);return this.renderWorker?.addCut({key:e,writable:n.writable,option:t}),this.cutRenders.set(e,{stream:r}),r}let n=document.createElement(`canvas`),r=n.captureStream(),i=n.transferControlToOffscreen();return this.renderWorker?.addCut({key:e,offscreen:i,option:t}),this.cutRenders.set(e,{stream:r}),r},setCut:(e,t)=>{this.renderWorker?.setCut({key:e,cutOption:t})},getStream:e=>this.cutRenders.get(e)?.stream,remove:e=>{this.renderWorker?.delCut(e),this.cutRenders.delete(e)},setPause:(e,t)=>{this.renderWorker?.setPause({key:e,pause:t})}};init=e=>{this.initRender(),this.initDecoder(e),this.initDemuxer(e),this.audioPlayer=new h,this.audioPlayer.init()};initDemuxer=e=>{this.demuxerWorker=new i,this.demuxerWorker.init(e),this.demuxerWorker.on.debug=e=>{this.option.debug&&this.on.debug&&this.on.debug(e)},this.demuxerWorker.on.info=e=>{this.option.debug&&console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: info`,e),this.on.demuxer.info&&this.on.demuxer.info(e)},this.demuxerWorker.on.config=e=>{this.option.debug&&console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: config`,e),this.on.demuxer.config&&this.on.demuxer.config(e);let{kind:t}=e;switch(t){case`audio`:{let{codec:t,sampleRate:n,numberOfChannels:r}=e;this.decoderWorker?.initAudio({codec:t,sampleRate:n,numberOfChannels:r})}break;case`video`:{let{codec:t,description:n}=e;this.decoderWorker?.initVideo({codec:t,description:n})}break}},this.demuxerWorker.on.chunk=e=>{if(this.on.demuxer.chunk&&this.on.demuxer.chunk(e),!this.decoderWorker)return;let{kind:t}=e;switch(t){case`audio`:{let{type:n,dts:r,data:i}=e,a=r*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:a,data:i}})}break;case`video`:{let{type:n,dts:r,data:i,nalus:a=[]}=e,o=r*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:o,data:i},nalus:a})}break}}};initDecoder=e=>{this.decoderWorker=new c,this.decoderWorker.init(e);let{frameTrack:t=!1}=this.option;this.decoderWorker.setFrameTrack(t),this.decoderWorker.on.audio.decode=e=>{this.audioPlayer?.push(e),this.on.decoder.audio&&this.on.decoder.audio(e)},this.decoderWorker.on.audio.error=e=>{this.option.debug&&console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: audio.error `,e),this.on.error&&this.on.error(e)},this.decoderWorker.on.video.decode=async e=>{this.start_resolve&&=(this.start_resolve(!0),void 0),this.renderWorker?.push(e),this.on.decoder.video&&this.on.decoder.video(e)},this.decoderWorker.on.video.error=e=>{this.on.error&&this.on.error(e)},this.decoderWorker.on.nalus=async e=>{for(let t of e){if(t.byteLength<=4)continue;let{header:e,data:n}=C(t),{nal_unit_type:r}=e;r===6&&this.on.decoder.sei&&this.on.decoder.sei(n)}},this.decoderWorker.on.analysis=e=>{this.on.decoder.analysis&&this.on.decoder.analysis(e)}};initRender=()=>{if(this.renderWorker=new f,this.converter===`generator`){let e=new MediaStreamTrackGenerator({kind:`video`}),t=new MediaStream([e]);this.renderWorker?.addCut({writable:e.writable}),this.stream=t}else{let e=document.createElement(`canvas`),t=e.captureStream(),n=e.transferControlToOffscreen();this.renderWorker?.addCut({offscreen:n}),this.stream=t}this.renderWorker?.setPause({pause:!1})};flv={start:()=>new Promise(async(e,t)=>{try{this.start_resolve=e;let n,r=0;for(;;){r+=1;try{n=await this.prFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(n?.status===200||r===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!n||n.status!==200)return t(`request is error.`);let i=n.body?.getReader();if(!i)return t(`reader is error.`);for(;;){let{done:e,value:t}=await i.read();if(t&&this.demuxerWorker?.push(t),e||this.url===``)break}}catch(e){e.name!==`AbortError`&&t(e)}})};hls={isLive:!1,urls:[],url:``,getSegmentsTimer:0,parse:async e=>{let t=new TextDecoder(`utf-8`).decode(e).split(`
|
|
2
|
+
`).map(e=>e.replace(`\r`,``)),n=this.url.substring(0,this.url.lastIndexOf(`/`)+1),r=4,i=0,a=!1,o=[];for(let e of t)e.startsWith(`#EXTINF:`)?r=parseFloat(e.split(`:`)[1].split(`,`)[0]):e.startsWith(`#EXT-X-TARGETDURATION:`)?i=parseInt(e.split(`:`)[1]):e.startsWith(`#EXT-X-ENDLIST`)?a=!1:e.startsWith(`#EXT-X-MEDIA-SEQUENCE:`)?a=!0:e.includes(`.ts`)&&!e.startsWith(`#`)&&o.push({url:e.startsWith(`http`)?e:n+e,duration:r,isLive:a});return{baseUrl:n,targetDuration:i,isLive:a,segments:o}},getSegments:async()=>{try{let e,t=0;for(;;){t+=1;try{e=await this.getSegmentsFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(e?.status===200||t===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!e||e.status!==200)throw Error(`request is error.`);let n=e.body?.getReader();if(!n)throw Error(`reader is error.`);for(;;){let{done:e,value:t}=await n.read();if(t){let{segments:e=[],isLive:n=!1}=await this.hls.parse(t);this.hls.isLive=n,n===!1&&(this.option.frameTrack=!1);let r=Array.from(e,e=>e.url),i=r.findIndex(e=>e===this.hls.url);i!==-1&&(r=r.slice(i+1)),this.hls.urls=r}if(e||this.url===``)break}}catch(e){e.name!==`AbortError`&&this.on.error&&this.on.error(e)}},start:()=>new Promise(async(e,t)=>{try{for(this.start_resolve=e,this.hls.url=``,this.hls.urls=[],await this.hls.getSegments(),this.hls.getSegmentsTimer=window.setInterval(this.hls.getSegments,500),this.hls.isLive===!1&&(clearInterval(this.hls.getSegmentsTimer),this.decoderWorker?.setFrameTrack(!1));;){let e=this.hls.urls.shift();if(e){this.hls.url=e;let t=(await this.prFetch.request(e)).body?.getReader();if(!t)throw Error(`segment reader is error.`);for(;;){let{done:e,value:n}=await t.read();if(n&&this.demuxerWorker?.push(n),e||this.url===``)break}}else await new Promise(e=>setTimeout(()=>e(!0),300))}}catch(e){e.name!==`AbortError`&&t(e)}})}},E=class{pendingPayloads=[];payload=new Uint8Array;chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);let t=this.pendingPayloads.shift();if(!t)return!1;let n=new Uint8Array(this.payload.byteLength+t.byteLength);return n.set(this.payload,0),n.set(t,this.payload.byteLength),this.payload=n,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array,this.chunks=[]}},D=e=>{let t=`unknown`;switch(e){case 1:case 2:case 27:case 36:t=`video`;break;case 3:case 4:case 15:t=`audio`;break;case 6:t=`subtitle`;break;case 134:t=`ad`;break}return t},O=class{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let t=0;for(;!(t+188>e.byteLength);){if(e.getInt8(t)!=71){t++;continue}await this.parsePacket(e,t),t+=188}return t};parsePacket=async(e,t)=>{if(t+188>e.byteLength||e.getUint8(t)!==71)throw Error(`Invalid TS packet`);let n=t,r=this.parseHeader(e,n);n+=4;let{transport_error_indicator:i,pid:a,payload_unit_start_indicator:o,adaptation_field_control:s}=r;if(i===1||a===void 0)return;let c=184;if(s===2||s===3){let t=e.getUint8(n);n+=1,this.parseAdaptationField(e,n),n+=t,c-=t}if(s===3&&--c,s===1||s===3){let t=new Uint8Array(e.buffer.slice(n,n+c));if(a===0)return this.parsePAT(e,n);{let{programs:t=[]}=this.pat||{};if(t.find(e=>e.pmt_pid===a))return this.parsePMT(e,n)}let{streams:r=[]}=this.pmt||{},i=r.find(e=>e.elementary_pid===a);if(i){if(o===1){let e=this.payloadMap.get(a);if(e){switch(i.kind){case`audio`:{let t=await this.parseAudio(e);this.on.chunk&&this.on.chunk(t)}break;case`video`:{let t=await this.parseVideo(e);this.on.chunk&&this.on.chunk(t),await new Promise(e=>setTimeout(()=>e(!0),0))}break}this.payloadMap.delete(a)}}{this.payloadMap.has(a)||this.payloadMap.set(a,new Uint8Array);let e=this.payloadMap.get(a),n=new Uint8Array(e.byteLength+t.byteLength);n.set(e,0),n.set(t,e.byteLength),this.payloadMap.set(a,n)}}}};parseHeader=(e,t)=>{let n=t,r=e.getUint8(n),i=e.getUint8(n+1),a=e.getUint8(n+2),o=e.getUint8(n+3),s=(i&128)>>7;return s===1?{sync_byte:r,transport_error_indicator:s}:{sync_byte:r,transport_error_indicator:s,payload_unit_start_indicator:(i&64)>>6,transport_priority:(i&32)>>5,pid:(i&31)<<8|a,transport_scrambling_control:(o&192)>>6,adaptation_field_control:o>>4&3,continuity_counter:o&15}};parsePAT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==0)throw Error(`Invalid PAT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u}}let i=[];{let t=r.section_length-5-4,a=n+t;for(;n<a;){let t=e.getUint16(n),r=e.getUint16(n+2)&8191;n+=4,t!==0&&r>=32&&r<=8190&&i.push({program_number:t,pmt_pid:r})}}let a=e.getUint32(n);this.pat={header:r,programs:i,crc32:a},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==2)throw Error(`Invalid PMT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1;let d=e.getUint16(n)&8191;n+=2;let f=e.getUint16(n)&4095;n+=2,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u,pcr_pid:d,program_info_length:f}}let i=[];{let t=r.section_length-9-4,a=n+t;for(;n<a;){let t=e.getUint8(n),r=D(t),a=e.getUint16(n+1)&8191,o=e.getUint16(n+3)&4095;if(n+=5,a<32||a>8190){console.warn(`Invalid elementary_pid: 0x${a.toString(16)}`);continue}i.push({kind:r,stream_type:t,elementary_pid:a,es_info_length:o})}}let a=e.getUint32(n);this.pmt={header:r,streams:i,crc32:a},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(e,t)=>{let n=t,r,i,a,o,s=e.getUint8(n),c=!!(s&128),l=!!(s&64),u=!!(s&32),d=!!(s&16),f=!!(s&8),p=!!(s&4),m=!!(s&2),h=!!(s&1);n+=1;let g=(e,t)=>{let n=BigInt(0);n|=BigInt(e.getUint16(t))<<25n,n|=BigInt(e.getUint16(t+1))<<17n,n|=BigInt(e.getUint16(t+2))<<9n,n|=BigInt(e.getUint16(t+3))<<1n,n|=BigInt(e.getUint16(t+4)>>7);let r=(e.getUint16(t+4)&1)<<8|e.getUint16(t+5);return n=n*300n+BigInt(r),n};if(d&&(r=g(e,n),n+=6),f&&(i=g(e,n),n+=6),p&&(a=e.getInt8(n),n+=1),m){let t=e.getUint8(n);n+=1,o=new Uint8Array(e.buffer,n,t),n+=t}return{discontinuity_indicator:c,random_access_indicator:l,elementary_stream_priority_indicator:u,pcr_flag:d,opcr_flag:f,splicing_point_flag:p,transport_private_data_flag:m,adaptation_field_extension_flag:h,pcr:r,opcr:i,splice_countdown:a,transport_private_data:o}};parseAudio=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts audio payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{if(!this.audioConfig&&t.getUint8(n)===255){let e=t.getUint8(n+2),r=t.getUint8(n+3),i,a;a=e>>2&15,i=(e&1)<<2|r>>6,this.audioConfig={kind:`audio`,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],numberOfChannels:i},this.on.config&&this.on.config(this.audioConfig)}let{dts:e=0,pts:a=0}=r;return{kind:`audio`,type:`key`,dts:e,pts:a,cts:a-e,data:i.slice(7)}}};parseVideo=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts video payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{let e=this.getNalus(i);if(!this.videoConfig){let t,n;if(t=e.find(e=>e.type===7)?.nalu.slice(4),n=e.find(e=>e.type===8)?.nalu.slice(4),t&&n){let e=y(t,n),{codec:r}=b(e);this.videoConfig={kind:`video`,codec:r,description:e,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}}let t=[],n=`delta`;for(let r of e){let{type:e,nalu:i}=r;switch(e){case 6:case 9:t.push(i);break;case 1:n=`delta`,t.push(i);break;case 5:n=`key`,t.push(i);break}}let a=S(t),{dts:o=0,pts:s=0}=r,c=s-o;return{kind:`video`,type:n,dts:o,pts:s,cts:c,data:a,nalus:t}}};parsePtsDts(e,t){let n=e.getUint8(t),r=e.getUint8(t+1),i=e.getUint8(t+2),a=e.getUint8(t+3),o=e.getUint8(t+4),s=(BigInt(n)&14n)<<29n|(BigInt(r)&255n)<<22n|(BigInt(i)&254n)<<14n|(BigInt(a)&255n)<<7n|(BigInt(o)&254n)>>1n;return Number(s)/90}getNalus=e=>{let t=[],n=0;for(;!(n+4>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}n+=3;let r=n,i=e[n]&31;for(n+=1;!(n+1>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}break}let a=n-r;if(e[n-1]===0&&--a,a!==0){let n=x(e.slice(r,r+a));t.push({type:i,nalu:n})}}return t}},k=(e,t)=>e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),A=class{audioConfig;videoConfig;header;textDecoder=new TextDecoder(`utf-8`);on={};constructor(){}parse=async e=>{let t=0;for(this.header||(this.parseHeader(e,t),t+=9);this.isSurplusTag(e,t)!==!1;){let{tagType:n,dataSize:r,timestamp:i}=this.parseTagHeader(e,t+4);if(n){let a=this.parseTagBody(n,e,t+4+11,r);switch(n){case`script`:this.on.info&&this.on.info(a);break;case`audio`:{let{accPacketType:e}=a;if(e===0){let{codec:e,sampleRate:t,channelConfiguration:n}=a;this.audioConfig={kind:`audio`,codec:e,sampleRate:t,numberOfChannels:n},this.on.config&&this.on.config(this.audioConfig)}else{let{cts:e,data:t}=a,n=e===void 0?void 0:e+i;this.on.chunk&&this.on.chunk({kind:`audio`,type:`key`,dts:i,pts:n,cts:e,data:t})}}break;case`video`:{let{avcPacketType:e}=a;if(e===0){let{codec:e,sps:t,pps:n,data:r}=a;this.videoConfig={kind:`video`,codec:e,description:r,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}else{let{frameType:e,cts:t,data:n,nalus:r}=a,o=e===1?`key`:`delta`,s=t===void 0?void 0:t+i;this.on.chunk&&this.on.chunk({kind:`video`,type:o,dts:i,pts:s,cts:t,data:n,nalus:r})}}break}t=t+4+11+r}await new Promise(e=>setTimeout(()=>e(!0),8))}return t};parseHeader=(e,t)=>{let n,r,i,a;n=e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),r=e.getUint8(3);{let[,,t,,n]=e.getUint8(0).toString(2).padStart(5,`0`).split(``);i={audio:n===`1`,video:t===`1`}}a=e.getUint32(5),this.header={signature:n,version:r,flags:i,dataOffset:a}};isSurplusTag=(e,t)=>{let n=!0,r=e.byteLength;if(t+4>r)n=!1;else if(t+4+11>r)n=!1;else{let i=k(e,t+4+1);t+4+11+i>r&&(n=!1)}return n};parseTagHeader=(e,t)=>{let n,r,i,a,o;{let r=e.getUint8(t),i;switch(r){case 18:i=`script`;break;case 8:i=`audio`;break;case 9:i=`video`;break}n=i}return r=k(e,t+1),i=k(e,t+4),a=e.getUint8(t+7),o=k(e,t+8),{tagType:n,dataSize:r,timestamp:i,timestampExtended:a,streamID:o}};parseTagBody=(e,t,n,r)=>{let i;switch(e){case`script`:i=this.parseMetaData(t,n);break;case`audio`:i=this.parseAudio(t,n,r);break;case`video`:i=this.parseVideo(t,n,r);break}return i};parseMetaData=(e,t)=>{let n=t;if(e.getUint8(n)!==2)throw Error(`Invalid AMF type for onMetaData (expected 0x02)`);n+=1;let r=e.getUint16(n,!1);n+=2;{let t=new Int8Array(e.buffer.slice(n,n+r));if((this.textDecoder?.decode(t)||``)!==`onMetaData`)throw Error(`Expected 'onMetaData' string`);n+=r}let i=this.getAmfType(e,n);return n+=1,this.getAMFValue(e,n,i).value};parseAudio=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i>>2&3,s=i>>1&1,c=i&1;r+=1;let l=e.getUint8(r);r+=1;let u=n,d=new Uint8Array(e.buffer.slice(r,r+u));if(a===10&&l===0){let t=e.getUint8(r),n=e.getUint8(r+1),i=t>>3&31,u=(t&7)<<1|n>>7;return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d,samplingFrequencyIndex:u,channelConfiguration:n>>3&15,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][u]}}return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d}};parseVideo=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i&15;r+=1;let s=e.getUint8(r);r+=1;let c=k(e,r);r+=3;let l=n-5,u=new Uint8Array(e.buffer.slice(r,r+l));switch(o){case 7:if(s===0)return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u,...b(u)};if(s===1){let t=[],i=r+n-5;for(;!(r+4>i);){let n=e.getUint32(r,!1),i=new Uint8Array(e.buffer.slice(r,r+4+n));r+=4+n,t.push(i)}return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u,nalus:t}}break;default:throw Error(`Unsupported codecID`)}return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u}};getAmfType=(e,t)=>e.getUint8(t);getAMFName=(e,t,n)=>{let r=new Uint8Array(e.buffer.slice(t,t+n));return this.textDecoder?.decode(r)||``};getAMFValue=(e,t,n)=>{let r=t,i,a=0;switch(n){case 0:i=e.getFloat64(r,!1),a=8;break;case 1:i=!!e.getUint8(r),a=1;break;case 2:{i=``;let t=e.getUint16(r,!1);r+=2;let n=new Int8Array(e.buffer,r,t).filter(e=>e!==0);i=(this.textDecoder?.decode(n)||``).trim(),a=2+t}break;case 3:for(i={};r<e.byteLength;){let t=e.getUint16(r,!1);if(t===0)break;r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);if(o===6)break;r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}break;case 8:{i={};let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=e.getUint16(r,!1);r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}}break;case 10:{i=[];let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=this.getAmfType(e,r);r+=1;let n=this.getAMFValue(e,r,t);r+=n.length,i.push(n.value),a=1+n.length}}break}return{amfType:n,length:a,value:i}}},j=class{pattern;cacher=new E;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case`flv`:this.parser=new A;break;case`hls`:this.parser=new O;break;default:throw Error(`is error pattern.`)}this.parser.on.debug=e=>this.on.debug&&this.on.debug(e),this.parser.on.info=e=>this.on.info&&this.on.info(e),this.parser.on.config=e=>this.on.config&&this.on.config(e),this.parser.on.chunk=e=>{this.cacher.pushChunk(e),this.on.chunk&&this.on.chunk(e)}};push=e=>{this.cacher.push(e),this.isParseing===!1&&this.parse()};destroy=()=>{this.cacher.destroy(),this.isParseing=!1,this.offset=0};parse=async()=>{try{if(this.isParseing=!0,!this.pattern)throw Error(`You need to set the pattern.`);if(!this.parser)throw Error(`You need to init parser.`);for(;;){let e=this.cacher.next(this.offset);if(this.offset=0,!e)break;this.offset=await this.parser.parse(e)}this.isParseing=!1}catch{this.destroy()}}},M=class{pattern=`flv`;audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;baseTime=0;pendingChunks=[];currentChunk;isProcessing=!1;decodeTimer=0;frameTrack=!1;isFrameTrack=!1;fameTrackOption={flv:[30,50],hls:[200,300],dash:[50,100],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:e=>{let t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:e,playbackRate:t})},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:async e=>{this.frameStartTime||=e.timestamp;try{let t=e.timestamp-this.frameStartTime+this.baseTime*1e3,n=await createImageBitmap(e);if(e.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{e.close()}},error:e=>{this.on.video.error&&this.on.video.error(e)}}),this.videoDecoder.configure(this.videoDecoderConfig)};setFrameTrack=e=>{this.frameTrack=e,this.frameTrack===!1&&(this.decodingSpeedRatio=1)};push=e=>{this.pendingChunks.push(e)};destroy=()=>{this.audio.destroy(),this.video.destroy(),this.pendingChunks=[],this.firstVideoChunkTimestamp=void 0,this.secondVideoChunkTimestamp=void 0,this.frameStartTime=void 0,this.lastRenderTime=void 0,this.nextRenderTime=void 0,clearInterval(this.decodeTimer)};initDecodeInterval=()=>{let e=this.decodingSpeed/this.decodingSpeedRatio,t=this.baseTime+performance.now();if(this.lastRenderTime||=t,this.fps=Math.round(1e3/(t-this.lastRenderTime)),this.lastRenderTime=t,this.nextRenderTime){let t=this.lastRenderTime-this.nextRenderTime;e-=t}this.nextRenderTime=this.lastRenderTime+e,this.decodeTimer=setTimeout(()=>{this.decode(),this.initDecodeInterval()},e)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;this.currentChunk=this.pendingChunks.shift(),this.currentChunk;){let e=this.pendingChunks.length;if(this.frameTrack){let[t,n]=this.fameTrackOption[this.pattern];if(e<=t&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){let n=Math.min(1+(e-t)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(n.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){let{decodingSpeed:t,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:t,decodingSpeedRatio:n,fps:r,cacheLength:e})}let{kind:t,init:n}=this.currentChunk;switch(t){case`audio`:this.decodeAudio(n);break;case`video`:this.decodeVideo(n);break}if(t===`video`)break}this.isProcessing=!1}};decodeAudio=e=>{if(!this.audioDecoder)return;let t=new EncodedAudioChunk(e);this.audioDecoder.decode(t)};decodeVideo=e=>{if(this.videoDecoder&&(e.type===`key`&&(this.hasKeyFrame=!0),this.firstVideoChunkTimestamp?this.secondVideoChunkTimestamp||(this.secondVideoChunkTimestamp=e.timestamp,this.decodingSpeed=(this.secondVideoChunkTimestamp-this.firstVideoChunkTimestamp)/1e3):this.firstVideoChunkTimestamp=e.timestamp,this.hasKeyFrame)){let t=new EncodedVideoChunk(e);this.videoDecoder.decode(t)}};audio={flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}},N=class{renderMap=new Map;constructor(){}push=async e=>{let{timestamp:t}=e,{bitmap:n}=e;try{let e=[...this.renderMap.keys()];for(let r of e){let e=this.renderMap.get(r);if(!e)continue;let{pause:i=!1,writer:a,offscreen:o,option:s}=e;if(i===!0)continue;let c=async e=>{if(a){let n=new VideoFrame(e,{timestamp:t});try{await a.write(n)}catch{}n.close()}else o&&(o.width=e.width,o.height=e.height,o?.getContext(`2d`)?.drawImage(e,0,0))};if(r===`default`)await c(n);else if(s){let{sx:e=0,sy:t=0,sw:r=n.width,sh:i=n.height}=s;await c(await createImageBitmap(n,e,t,r,i))}}}catch{}n.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,option:i}={key:`default`,...e};if(n){let e=n.getWriter();this.renderMap.set(t,{writer:e,option:i,pause:!1})}else this.renderMap.set(t,{offscreen:r,option:i,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{let{key:t,cutOption:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,option:n})};setPause=e=>{let{key:t,pause:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,pause:n})};destroy=()=>{this.renderMap=new Map}};e.Decoder=M,e.DecoderWorker=c,e.Demuxer=j,e.DemuxerWorker=i,e.PrPlayer=T,e.Render=N,e.RenderWorker=f});
|
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.
|
|
4
|
+
"version": "0.3.7",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
7
7
|
"dist"
|
|
@@ -23,9 +23,9 @@
|
|
|
23
23
|
"pr-fetch": "^0.0.4"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
|
-
"typescript": "^
|
|
27
|
-
"vite": "^
|
|
28
|
-
"vite-plugin-dts": "^4.5.
|
|
26
|
+
"typescript": "^6.0.2",
|
|
27
|
+
"vite": "^8.0.2",
|
|
28
|
+
"vite-plugin-dts": "^4.5.4"
|
|
29
29
|
},
|
|
30
30
|
"private": false,
|
|
31
31
|
"author": "Breathe",
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|