pr-player 0.0.2 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/dist/index.umd.cjs +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -398,11 +398,11 @@ class be {
|
|
|
398
398
|
*/
|
|
399
399
|
initDecoder = () => {
|
|
400
400
|
this.decoderWorker = new _(), this.decoderWorker.on.audio.decode = (t) => {
|
|
401
|
-
this.
|
|
401
|
+
this.on.decoder.audio && this.on.decoder.audio(t), this.audioPlayer?.push(t);
|
|
402
402
|
}, this.decoderWorker.on.audio.error = (t) => {
|
|
403
403
|
this.stop(), this.on.error && this.on.error(t);
|
|
404
404
|
}, this.decoderWorker.on.video.decode = (t) => {
|
|
405
|
-
this.
|
|
405
|
+
this.on.decoder.video && this.on.decoder.video(t), X(this.cutVideoPlayerWorkers, t), this.videoPlayerWorker?.push(t), t.bitmap.close();
|
|
406
406
|
}, this.decoderWorker.on.video.error = (t) => {
|
|
407
407
|
this.stop(), this.on.error && this.on.error(t);
|
|
408
408
|
};
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
(function(m,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(m=typeof globalThis<"u"?globalThis:m||self,b(m["pr-player"]={}))})(this,(function(m){"use strict";const b='(function(){"use strict";const U=new TextDecoder("utf-8"),H=(e,s)=>{const a=e.getUint8(s),t=a>>7&1,n=a>>5&3,r=a&31;return{forbidden_zero_bit:t,nal_ref_idc:n,nal_unit_type:r}},b=(e,s)=>e.getUint8(s),P=(e,s,a)=>{const t=new Uint8Array(e.buffer.slice(s,s+a));return U?.decode(t)||""},T=(e,s,a)=>{let t=s,n,r=0;switch(a){case 0:n=e.getFloat64(t,!1),r=8;break;case 1:n=!!e.getUint8(t),r=1;break;case 2:{n="";const o=e.getUint16(t,!1);t=t+2;const c=new Int8Array(e.buffer,t,o).filter(d=>d!==0);n=(U?.decode(c)||"").trim(),r=2+o}break;case 3:for(n={};t<e.byteLength;){const o=e.getUint16(t,!1);if(o===0)break;t=t+2;const c=P(e,t,o);t=t+o;const g=b(e,t);if(g===6)break;t=t+1;const d=T(e,t,g);t=t+d.length,n[c]=d.value,r=2+o+1+d.length}break;case 8:{n={};const o=e.getUint32(t,!1);t=t+4;for(let c=0;c<o;c++){const g=e.getUint16(t,!1);t=t+2;const d=P(e,t,g);t=t+g;const h=b(e,t);t=t+1;const l=T(e,t,h);t=t+l.length,n[d]=l.value,r=2+g+1+l.length}}break;case 10:{n=[];const o=e.getUint32(t,!1);t=t+4;for(let c=0;c<o;c++){const g=b(e,t);t=t+1;const d=T(e,t,g);t=t+d.length,n.push(d.value),r=1+d.length}}break}return{amfType:a,length:r,value:n}},m=(e,s)=>e.getUint8(s)<<16|e.getUint8(s+1)<<8|e.getUint8(s+2);var u={header:{getSignature:e=>{const s=new Int8Array(e.buffer.slice(0,3));return U?.decode(s)||""},getVersion:e=>e.getUint8(3),getFlags:e=>{const a=e.getUint8(0).toString(2).padStart(5,"0").split(""),[,,t,,n]=a;return{audio:n==="1",video:t==="1"}},getDataOffset:e=>e.getUint32(5)},getPreviousTagSize:(e,s)=>e.getUint32(s),isSurplusTag:(e,s)=>{let a=!0;const t=e.byteLength;if(s+4>t)a=!1;else if(s+4+11>t)a=!1;else{const n=m(e,s+4+1);s+4+11+n>t&&(a=!1)}return a},tag:{tagHeader:{getTagType:(e,s)=>{const a=e.getUint8(s);let t;switch(a){case 18:t="script";break;case 8:t="audio";break;case 9:t="video";break}return t},getDataSize:(e,s)=>m(e,s+1),getTimestamp:(e,s)=>m(e,s+4),getTimestampExtended:(e,s)=>e.getUint8(s+7),getStreamID:(e,s)=>m(e,s+8)},tagBody:{parseAudio:(e,s,a)=>{let t=s;const n=e.getUint8(t),r=n>>4&15,i=n>>2&3,o=n>>1&1,c=n&1;t=t+1;const g=e.getUint8(t);t=t+1;const d=a-2,h=new Uint8Array(e.buffer.slice(t,t+d));if(r===10&&g===0){const l=e.getUint8(t),p=e.getUint8(t+1),f=(l&248)>>3,y=(l&7)<<1|p>>7,S=(p&120)>>3,A=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],D=`mp4a.40.${f}`,z=A[y];return{soundFormat:r,soundRate:i,soundSize:o,soundType:c,accPacketType:g,data:h,audioObjectType:f,samplingFrequencyIndex:y,channelConfiguration:S,codec:D,sampleRate:z}}return{soundFormat:r,soundRate:i,soundSize:o,soundType:c,accPacketType:g,data:h}},parseVideo:(e,s,a)=>{let t=s;const n=e.getUint8(t),r=n>>4&15,i=n&15;t=t+1;const o=e.getUint8(t);t=t+1;const c=m(e,t);t=t+3;const g=a-5,d=new Uint8Array(e.buffer.slice(t,t+g));switch(i){case 7:if(o===0){const h=e.getUint8(t);if(t=t+1,h!==1)throw new Error("Invalid AVC version");const l=e.getUint8(t)&255;t=t+1;const p=e.getUint8(t)&255;t=t+1;const f=e.getUint8(t)&255;t=t+1;const A=`avc1.${Array.from([l,p,f],E=>E.toString(16).padStart(2,"0")).join("")}`,D=(e.getUint8(t)&3)-1;t=t+1;const z=e.getUint8(t)&31;t=t+1;const _=e.getUint16(t,!1);t=t+2;const O=new Uint8Array(e.buffer.slice(t,t+_));t=t+_;const I=e.getUint8(t)&31;t=t+1;const x=e.getUint16(t,!1);t=t+2;const M=new Uint8Array(e.buffer.slice(t,t+x));return t=t+x,{frameType:r,codecID:i,avcPacketType:o,cts:c,data:d,version:h,codec:A,profile:l,compatibility:p,level:f,lengthSizeMinusOne:D,numOfSequenceParameterSets:z,sequenceParameterSetLength:_,sps:O,numOfPictureParameterSets:I,pictureParameterSetLength:x,pps:M}}else if(o===1){const h=[],l=t+a-5;for(;t+4<l;){const p=e.getUint32(t,!1);t=t+4;const f=H(e,t);t=t+1;const y=p-1,S=new Uint8Array(e.buffer.slice(t,t+y));t=t+y,h.push({size:p,header:f,payload:S})}return{frameType:r,codecID:i,avcPacketType:o,cts:c,data:d,nalus:h}}break;default:throw new Error("Unsupported codecID")}return{frameType:r,codecID:i,avcPacketType:o,cts:c,data:d}},parseMetaData:(e,s)=>{let a=s;{if(e.getUint8(a)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");a=a+1}const t=e.getUint16(a,!1);a=a+2;{const i=new Int8Array(e.buffer.slice(a,a+t));if((U?.decode(i)||"")!=="onMetaData")throw new Error("Expected \'onMetaData\' string");a=a+t}const n=b(e,a);return a=a+1,T(e,a,n).value}}}};class L{parseSpeed=8;pendingPayloads=[];payload=new Uint8Array(0);offset=0;is_parsing=!1;header;tag;on={};constructor(){}init=()=>{this.destroy()};push=s=>{this.pendingPayloads.push(s),this.is_parsing||this.parse()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.offset=0,this.is_parsing=!1,this.header=void 0,this.tag=void 0};parse=async()=>{for(this.is_parsing=!0;;){const s=this.pendingPayloads.shift();if(!s)break;const a=new Uint8Array(this.payload.byteLength+s.byteLength);a.set(this.payload,0),a.set(s,this.payload.byteLength),this.payload=a;const t=new DataView(this.payload.buffer);this.header||this.parseHeader(t),await this.parseTag(t)}this.is_parsing=!1};parseHeader=s=>(this.header={signature:u.header.getSignature(s),version:u.header.getVersion(s),flags:u.header.getFlags(s),dataOffset:u.header.getDataOffset(s)},this.offset=this.header?.dataOffset,this.on.header&&this.on.header(this.header),this.header);parseTag=async s=>{const a=(n,r)=>({tagType:u.tag.tagHeader.getTagType(n,r),dataSize:u.tag.tagHeader.getDataSize(n,r),timestamp:u.tag.tagHeader.getTimestamp(n,r),timestampExtended:u.tag.tagHeader.getTimestampExtended(n,r),streamID:u.tag.tagHeader.getStreamID(n,r)}),t=(n,r,i,o)=>{let c;switch(n){case"script":c=u.tag.tagBody.parseMetaData(r,i);break;case"audio":c=u.tag.tagBody.parseAudio(r,i,o);break;case"video":c=u.tag.tagBody.parseVideo(r,i,o);break}return c};for(;this.offset<s.byteLength;){if(u.isSurplusTag(s,this.offset)===!1){this.payload=this.payload.slice(this.offset),this.offset=0;break}const r=a(s,this.offset+4),{tagType:i,dataSize:o}=r;if(!i)break;const c=t(i,s,this.offset+4+11,o);this.tag={header:r,body:c},this.on.tag&&this.on.tag(this.tag),this.offset=this.offset+4+11+o,await new Promise(g=>setTimeout(()=>g(!0),this.parseSpeed))}}}const k=new L;k.on.header=e=>postMessage({action:"onHeader",data:e}),k.on.tag=e=>postMessage({action:"onTag",data:e}),onmessage=e=>{const{action:s,data:a}=e.data,t=k[s];t&&t(a)}})();\n',R=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",b],{type:"text/javascript;charset=utf-8"});function B(i){let t;try{if(t=R&&(self.URL||self.webkitURL).createObjectURL(R),!t)throw"";const s=new Worker(t,{name:i?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(b),{name:i?.name})}}class G{worker=new B;on={};constructor(){this.worker.onmessage=t=>{const{action:s,data:e}=t.data;s==="onHeader"&&this.on.header&&this.on.header(e),s==="onTag"&&this.on.tag&&this.on.tag(e)}}init=()=>this.worker.postMessage({action:"init"});push=t=>this.worker.postMessage({action:"push",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}const L=`(function(){"use strict";class r{audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;on={audio:{},video:{}};constructor(){}audio={init:i=>{this.audio.destroy(),this.audioDecoderConfig={...i},this.audioDecoder=new AudioDecoder({output:e=>{this.on.audio.decode&&this.on.audio.decode(e)},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)},decode:i=>{if(!this.audioDecoder)return;const e=new EncodedAudioChunk(i);this.audioDecoder.decode(e)},flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={init:i=>{this.video.destroy(),this.videoDecoderConfig={...i},this.videoDecoder=new VideoDecoder({output:async e=>{const d=await createImageBitmap(e),s=e.timestamp;e.close(),d.width>0&&d.height>0?this.on.video.decode&&this.on.video.decode({timestamp:s,bitmap:d}):d.close()},error:e=>{this.on.video.error&&this.on.video.error(e)}}),this.videoDecoder.configure(this.videoDecoderConfig)},decode:i=>{if(this.videoDecoder&&(i.type==="key"&&(this.hasKeyFrame=!0),this.hasKeyFrame&&this.videoDecoder.decodeQueueSize<2)){const e=new EncodedVideoChunk(i);this.videoDecoder.decode(e)}},flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}}const t=new r;t.on.audio.decode=o=>postMessage({type:"audio",action:"onDecode",data:o}),t.on.audio.error=o=>postMessage({type:"audio",action:"onError",data:o}),t.on.video.decode=o=>postMessage({type:"video",action:"onDecode",data:o}),t.on.video.error=o=>postMessage({type:"video",action:"onError",data:o}),onmessage=o=>{const{type:i,action:e,data:d}=o.data,s=t[i][e];s&&s(d)}})();
|
|
2
2
|
`,N=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",L],{type:"text/javascript;charset=utf-8"});function V(i){let t;try{if(t=N&&(self.URL||self.webkitURL).createObjectURL(N),!t)throw"";const s=new Worker(t,{name:i?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(L),{name:i?.name})}}class F{worker=new V;on={audio:{},video:{}};constructor(){this.worker.onmessage=t=>{const{type:s,action:e,data:o}=t.data;switch(s){case"audio":e==="onDecode"&&this.on.audio.decode&&this.on.audio.decode(o),e==="onError"&&this.on.audio.error&&this.on.audio.error(o);break;case"video":e==="onDecode"&&this.on.video.decode&&this.on.video.decode(o),e==="onError"&&this.on.video.error&&this.on.video.error(o);break}}}audio={init:t=>this.worker.postMessage({type:"audio",action:"init",data:t}),decode:t=>this.worker.postMessage({type:"audio",action:"decode",data:t}),flush:()=>this.worker.postMessage({type:"audio",action:"flush"}),destroy:()=>{this.worker.postMessage({type:"audio",action:"destroy"})}};video={init:t=>this.worker.postMessage({type:"video",action:"init",data:t}),decode:t=>this.worker.postMessage({type:"video",action:"decode",data:t}),flush:()=>this.worker.postMessage({type:"video",action:"flush"}),destroy:()=>{this.worker.postMessage({type:"video",action:"destroy",data:{}})}};destroy=()=>{this.worker.postMessage({type:"audio",action:"destroy"}),this.worker.postMessage({type:"video",action:"destroy",data:{}}),this.worker.terminate()}}const W=`(function(){"use strict";class a{isRendering=!1;pendingFrames=[];offscreenCanvas;ctx;baseTime=0;constructor(){}init=({offscreenCanvas:e,baseTime:i=performance.timeOrigin})=>{this.destroy(),this.offscreenCanvas=e,this.ctx=this.offscreenCanvas.getContext("2d"),this.baseTime=i};destroy=()=>{this.isRendering=!1,this.pendingFrames=[],this.offscreenCanvas=void 0,this.ctx=void 0,this.baseTime=0};push=e=>{this.pendingFrames.push(e),this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=e=>{const i=performance.timeOrigin+performance.now(),t=this.baseTime+e/1e3-i;return Math.max(0,t)};renderFrame=async()=>{for(this.isRendering=!0;;){const e=this.pendingFrames.shift();if(!e)break;this.isRendering=!1,this.isRendering=!0;let{timestamp:i,bitmap:s}=e;const t=this.calculateTimeUntilNextFrame(i);this.ctx&&this.offscreenCanvas&&(await new Promise(c=>setTimeout(()=>c(!0),t)),this.ctx.drawImage(s,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height)),s.close()}this.isRendering=!1}}const r=new a;onmessage=n=>{const{action:e,data:i}=n.data,s=r[e];s&&s(i)}})();
|
|
3
|
-
`,O=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",W],{type:"text/javascript;charset=utf-8"});function E(i){let t;try{if(t=O&&(self.URL||self.webkitURL).createObjectURL(O),!t)throw"";const s=new Worker(t,{name:i?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(W),{name:i?.name})}}class D{worker=new E;constructor(){}setCut=async t=>this.worker.postMessage({action:"setCut",data:t});init=({offscreenCanvas:t,baseTime:s=0})=>this.worker.postMessage({action:"init",data:{offscreenCanvas:t,baseTime:s}},[t]);push=t=>this.worker.postMessage({action:"push",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}var z=Object.defineProperty,_=(i,t,s)=>t in i?z(i,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):i[t]=s,u=(i,t,s)=>_(i,typeof t!="symbol"?t+"":t,s);class j{constructor(t,s){u(this,"inputStream",new MediaStream),u(this,"outputStream",new MediaStream),u(this,"inputGain",1),u(this,"enhanceGain",1),u(this,"bgsGain",1),u(this,"bgmGain",1),u(this,"outputGain",1),u(this,"mixAudioMap",new Map),u(this,"audioContext",new AudioContext),u(this,"sourceNode"),u(this,"inputGainNode"),u(this,"enhanceGainNode"),u(this,"bgsGainNode"),u(this,"bgmGainNode"),u(this,"analyserNode"),u(this,"analyserArrayData"),u(this,"outputGainNode"),u(this,"destinationNode"),u(this,"filterStream",e=>e),u(this,"stop",()=>{{const e=this.inputStream.getTracks();for(const o of e)o.stop(),this.inputStream.removeTrack(o)}}),u(this,"getStream",()=>this.filterStream(this.outputStream)),u(this,"setMute",(e=!0)=>{e?this.analyserNode.disconnect(this.outputGainNode):this.analyserNode.connect(this.outputGainNode)}),u(this,"setInputGain",e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),u(this,"setEnhanceGain",async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)}),u(this,"setBgsGain",e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),u(this,"setBgmGain",e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),u(this,"setOutputGain",e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)}),u(this,"getVolume",()=>{const{analyserNode:e,analyserArrayData:o}=this;e.getByteFrequencyData(o);let a=0;for(let n=0;n<o.length;n++)a+=o[n];return Math.ceil(a/o.length)}),u(this,"mixAudio",(e,o="bgm")=>new Promise(async(a,n)=>{try{{const h=this.mixAudioMap.get(o);h&&h.stop()}const r=o==="bgs"?this.bgsGainNode:this.bgmGainNode,d=this.audioContext.createBufferSource();this.mixAudioMap.set(o,d),d.buffer=e,d.connect(r),d.onended=()=>{d.disconnect(r),this.mixAudioMap.delete(o),a(!0)},d.start(0)}catch(r){n(r)}})),u(this,"mixAudioStop",e=>{const o=this.mixAudioMap.get(e);o?.stop()}),u(this,"changeMix",(e,o)=>{const a=e==="bgs"?this.bgsGainNode:this.bgmGainNode;o?a.connect(this.destinationNode):a.disconnect(this.destinationNode)}),s&&(this.audioContext=s),this.inputStream=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;{const{sourceNode:e,inputGainNode:o,enhanceGainNode:a,bgsGainNode:n,bgmGainNode:r,analyserNode:d,outputGainNode:h,destinationNode:c}=this;e.connect(o),o.connect(a),a.connect(d),n.connect(d),r.connect(d),a.connect(c),n.connect(c),r.connect(c),d.connect(h),h.connect(this.audioContext.destination)}this.setMute(!0),this.audioContext.resume()}}const H=async(i,t)=>{try{const{format:s,numberOfChannels:e,numberOfFrames:o,sampleRate:a}=t,n=i.createBuffer(e,o,a);for(let r=0;r<e;r++){const d=t.allocationSize({planeIndex:r}),h=new Uint8Array(d);t.copyTo(h,{planeIndex:r});const c=new DataView(h.buffer),f=n.getChannelData(r);for(let g=0;g<o;g++){let l;switch(s){case"s16":case"s16-planar":l=c.getInt16(g*2,!0)/32768;break;case"f32":case"f32-planar":l=c.getFloat32(g*4,!0);break;case"u8":case"u8-planar":l=(c.getUint8(g)-128)/128;break;default:throw new Error(`Unsupported audio format: ${s}`)}f[g]=Math.max(-1,Math.min(1,l))}}return n}catch(s){throw console.error("Failed to convert AudioData to AudioBuffer:",s),s}};class ${prAudioStream;audioContext;destination;stream=new MediaStream;nextStartTime=0;pendingSources=[];constructor(){}init=t=>{t||(t=new(window.AudioContext||window.webkitAudioContext)),this.audioContext=t,this.destination=this.audioContext.createMediaStreamDestination(),this.stream=new MediaStream,this.stream.addTrack(this.destination.stream.getAudioTracks()[0]),this.prAudioStream=new j(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(t){try{if(!this.audioContext||!this.destination)return;const s=await H(this.audioContext,t);if(!s)return;const e=this.audioContext.createBufferSource();e.buffer=s,e.connect(this.destination);const o=Math.max(this.nextStartTime,this.audioContext.currentTime);this.nextStartTime=o+s.duration,e.start(o),this.pendingSources.push(e),e.onended=()=>{this.pendingSources=this.pendingSources.filter(a=>a!==e)},this.audioContext.state==="suspended"&&await this.audioContext.resume()}finally{t.close()}}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(t=>t.stop()),this.pendingSources=[]}}class q{#t={timeout:5*1e3};#e;constructor(t={}){this.#t={...this.#t,...t}}check=(t,s)=>new Promise(async(e,o)=>{this.stop(),this.#e=new AbortController;const a=window.setTimeout(()=>{this.#e?.abort("Timeout."),o({status:"timeout",reason:""})},this.#t.timeout);try{const n=await fetch(t,{...s,method:"HEAD",signal:this.#e?.signal});n.status===200?e({status:"successed",reason:""}):o({status:"failed",reason:`${n.status}`})}catch(n){o({status:"error",reason:n.message})}clearTimeout(a)});request=async(t,s)=>new Promise(async(e,o)=>{try{await this.check(t,s),this.#e=new AbortController;const a=await fetch(t,{...s,signal:this.#e?.signal});e(a)}catch(a){this.stop(),o(a)}});stop=()=>{this.#e?.signal.aborted===!1&&this.#e.abort("Actively stop.")}}const K=async(i,t)=>{const s=[...i.keys()],{timestamp:e,bitmap:o}=t;for(const a of s){const n=i.get(a);if(!n)continue;const{options:r,worker:d}=n,{sx:h=0,sy:c=0,sw:f=o.width,sh:g=o.height}=r,l=await createImageBitmap(o,h,c,f,g);d.push({timestamp:e,bitmap:l})}},Q=i=>{const t=[...i.keys()];for(const s of t)i.get(s)?.worker.destroy(),i.delete(s)};class J{prFetch=new q;demuxerWorker;decoderWorker;audioPlayer;videoPlayerWorker;renderBaseTime=0;cutVideoPlayerWorkers=new Map;canvas;on={demuxer:{},decoder:{}};constructor(){}init=()=>{this.stop(),this.initDemuxer(),this.initDecoder(),this.renderBaseTime=new Date().getTime(),this.audioPlayer=new $,this.audioPlayer.init()};start=async t=>{try{const e=(await this.prFetch.request(t)).body?.getReader();if(!e)throw new Error("Reader is error.");for(;;){const{done:o,value:a}=await e.read();if(a&&this.demuxerWorker?.push(a),o)break}}catch{}};stop=()=>{this.prFetch.stop(),this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.videoPlayerWorker?.destroy(),Q(this.cutVideoPlayerWorkers),this.audioPlayer?.destroy(),this.renderBaseTime=0,this.canvas=void 0};onTag=t=>{if(!this.decoderWorker)return;const{header:s,body:e}=t,{tagType:o,timestamp:a}=s;switch(o){case"script":{const{width:n,height:r}=e;this.initRender({width:n,height:r}),this.on.demuxer.script&&this.on.demuxer.script(t)}break;case"audio":{const{accPacketType:n,data:r}=e;if(n===0){const{codec:d,sampleRate:h,channelConfiguration:c}=e,f={codec:d,sampleRate:h,numberOfChannels:c,description:new Uint8Array([])};this.decoderWorker.audio.init(f)}else n===1&&this.decoderWorker.audio.decode({type:"key",timestamp:a*1,data:r});this.on.demuxer.audio&&this.on.demuxer.audio(t)}break;case"video":{const{avcPacketType:n,frameType:r,data:d,nalus:h=[]}=e;if(n===0){const{codec:c,data:f}=e;this.decoderWorker.video.init({codec:c,description:f})}else if(n===1){const c=r===1?"key":"delta";this.decoderWorker.video.decode({type:c,timestamp:a*1e3,data:d});for(const f of h){const{header:g,payload:l}=f,{nal_unit_type:y}=g;y===6&&this.on.demuxer.sei&&this.on.demuxer.sei(l)}}this.on.demuxer.video&&this.on.demuxer.video(t)}break}};initDemuxer=()=>{this.demuxerWorker=new G,this.demuxerWorker.init(),this.demuxerWorker.on.tag=this.onTag};initDecoder=()=>{this.decoderWorker=new F,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.stop(),this.on.error&&this.on.error(t)},this.decoderWorker.on.video.decode=t=>{this.videoPlayerWorker?.push(t),K(this.cutVideoPlayerWorkers,t),this.on.decoder.video&&this.on.decoder.video(t),t.bitmap.close()},this.decoderWorker.on.video.error=t=>{this.stop(),this.on.error&&this.on.error(t)}};initRender=({width:t=256,height:s=256}={})=>{if(!this.on.video)return;this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=s;const e=this.canvas.transferControlToOffscreen();this.videoPlayerWorker=new D,this.videoPlayerWorker.init({offscreenCanvas:e,baseTime:this.renderBaseTime}),this.on.video(this.canvas)};audio={setMute:t=>this.audioPlayer?.prAudioStream?.setMute(t)};video={createCut:(t,s)=>{this.cutVideoPlayerWorkers.has(t)&&this.cutVideoPlayerWorkers.get(t)?.worker.destroy();const e=document.createElement("canvas"),{sw:o,sh:a}=s;e.width=o||e.width,e.height=a||e.height;const n=new D,r=e.transferControlToOffscreen();n.init({offscreenCanvas:r,baseTime:this.renderBaseTime}),n.setCut(s),this.cutVideoPlayerWorkers.set(t,{options:s,worker:n}),this.on.cut&&this.on.cut(t,e)}}}const T=new TextDecoder("utf-8"),X=(i,t)=>{const s=i.getUint8(t),e=s>>7&1,o=s>>5&3,a=s&31;return{forbidden_zero_bit:e,nal_ref_idc:o,nal_unit_type:a}},U=(i,t)=>i.getUint8(t),I=(i,t,s)=>{const e=new Uint8Array(i.buffer.slice(t,t+s));return T?.decode(e)||""},v=(i,t,s)=>{let e=t,o,a=0;switch(s){case 0:o=i.getFloat64(e,!1),a=8;break;case 1:o=!!i.getUint8(e),a=1;break;case 2:{o="";const r=i.getUint16(e,!1);e=e+2;const d=new Int8Array(i.buffer,e,r).filter(c=>c!==0);o=(T?.decode(d)||"").trim(),a=2+r}break;case 3:for(o={};e<i.byteLength;){const r=i.getUint16(e,!1);if(r===0)break;e=e+2;const d=I(i,e,r);e=e+r;const h=U(i,e);if(h===6)break;e=e+1;const c=v(i,e,h);e=e+c.length,o[d]=c.value,a=2+r+1+c.length}break;case 8:{o={};const r=i.getUint32(e,!1);e=e+4;for(let d=0;d<r;d++){const h=i.getUint16(e,!1);e=e+2;const c=I(i,e,h);e=e+h;const f=U(i,e);e=e+1;const g=v(i,e,f);e=e+g.length,o[c]=g.value,a=2+h+1+g.length}}break;case 10:{o=[];const r=i.getUint32(e,!1);e=e+4;for(let d=0;d<r;d++){const h=U(i,e);e=e+1;const c=v(i,e,h);e=e+c.length,o.push(c.value),a=1+c.length}}break}return{amfType:s,length:a,value:o}},w=(i,t)=>i.getUint8(t)<<16|i.getUint8(t+1)<<8|i.getUint8(t+2),p={header:{getSignature:i=>{const t=new Int8Array(i.buffer.slice(0,3));return T?.decode(t)||""},getVersion:i=>i.getUint8(3),getFlags:i=>{const s=i.getUint8(0).toString(2).padStart(5,"0").split(""),[,,e,,o]=s;return{audio:o==="1",video:e==="1"}},getDataOffset:i=>i.getUint32(5)},getPreviousTagSize:(i,t)=>i.getUint32(t),isSurplusTag:(i,t)=>{let s=!0;const e=i.byteLength;if(t+4>e)s=!1;else if(t+4+11>e)s=!1;else{const o=w(i,t+4+1);t+4+11+o>e&&(s=!1)}return s},tag:{tagHeader:{getTagType:(i,t)=>{const s=i.getUint8(t);let e;switch(s){case 18:e="script";break;case 8:e="audio";break;case 9:e="video";break}return e},getDataSize:(i,t)=>w(i,t+1),getTimestamp:(i,t)=>w(i,t+4),getTimestampExtended:(i,t)=>i.getUint8(t+7),getStreamID:(i,t)=>w(i,t+8)},tagBody:{parseAudio:(i,t,s)=>{let e=t;const o=i.getUint8(e),a=o>>4&15,n=o>>2&3,r=o>>1&1,d=o&1;e=e+1;const h=i.getUint8(e);e=e+1;const c=s-2,f=new Uint8Array(i.buffer.slice(e,e+c));if(a===10&&h===0){const g=i.getUint8(e),l=i.getUint8(e+1),y=(g&248)>>3,k=(g&7)<<1|l>>7,x=(l&120)>>3,S=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],C=`mp4a.40.${y}`,A=S[k];return{soundFormat:a,soundRate:n,soundSize:r,soundType:d,accPacketType:h,data:f,audioObjectType:y,samplingFrequencyIndex:k,channelConfiguration:x,codec:C,sampleRate:A}}return{soundFormat:a,soundRate:n,soundSize:r,soundType:d,accPacketType:h,data:f}},parseVideo:(i,t,s)=>{let e=t;const o=i.getUint8(e),a=o>>4&15,n=o&15;e=e+1;const r=i.getUint8(e);e=e+1;const d=w(i,e);e=e+3;const h=s-5,c=new Uint8Array(i.buffer.slice(e,e+h));switch(n){case 7:if(r===0){const f=i.getUint8(e);if(e=e+1,f!==1)throw new Error("Invalid AVC version");const g=i.getUint8(e)&255;e=e+1;const l=i.getUint8(e)&255;e=e+1;const y=i.getUint8(e)&255;e=e+1;const S=`avc1.${Array.from([g,l,y],oe=>oe.toString(16).padStart(2,"0")).join("")}`,C=(i.getUint8(e)&3)-1;e=e+1;const A=i.getUint8(e)&31;e=e+1;const M=i.getUint16(e,!1);e=e+2;const te=new Uint8Array(i.buffer.slice(e,e+M));e=e+M;const se=i.getUint8(e)&31;e=e+1;const P=i.getUint16(e,!1);e=e+2;const ie=new Uint8Array(i.buffer.slice(e,e+P));return e=e+P,{frameType:a,codecID:n,avcPacketType:r,cts:d,data:c,version:f,codec:S,profile:g,compatibility:l,level:y,lengthSizeMinusOne:C,numOfSequenceParameterSets:A,sequenceParameterSetLength:M,sps:te,numOfPictureParameterSets:se,pictureParameterSetLength:P,pps:ie}}else if(r===1){const f=[],g=e+s-5;for(;e+4<g;){const l=i.getUint32(e,!1);e=e+4;const y=X(i,e);e=e+1;const k=l-1,x=new Uint8Array(i.buffer.slice(e,e+k));e=e+k,f.push({size:l,header:y,payload:x})}return{frameType:a,codecID:n,avcPacketType:r,cts:d,data:c,nalus:f}}break;default:throw new Error("Unsupported codecID")}return{frameType:a,codecID:n,avcPacketType:r,cts:d,data:c}},parseMetaData:(i,t)=>{let s=t;{if(i.getUint8(s)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");s=s+1}const e=i.getUint16(s,!1);s=s+2;{const n=new Int8Array(i.buffer.slice(s,s+e));if((T?.decode(n)||"")!=="onMetaData")throw new Error("Expected 'onMetaData' string");s=s+e}const o=U(i,s);return s=s+1,v(i,s,o).value}}}};class Y{parseSpeed=8;pendingPayloads=[];payload=new Uint8Array(0);offset=0;is_parsing=!1;header;tag;on={};constructor(){}init=()=>{this.destroy()};push=t=>{this.pendingPayloads.push(t),this.is_parsing||this.parse()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.offset=0,this.is_parsing=!1,this.header=void 0,this.tag=void 0};parse=async()=>{for(this.is_parsing=!0;;){const t=this.pendingPayloads.shift();if(!t)break;const s=new Uint8Array(this.payload.byteLength+t.byteLength);s.set(this.payload,0),s.set(t,this.payload.byteLength),this.payload=s;const e=new DataView(this.payload.buffer);this.header||this.parseHeader(e),await this.parseTag(e)}this.is_parsing=!1};parseHeader=t=>(this.header={signature:p.header.getSignature(t),version:p.header.getVersion(t),flags:p.header.getFlags(t),dataOffset:p.header.getDataOffset(t)},this.offset=this.header?.dataOffset,this.on.header&&this.on.header(this.header),this.header);parseTag=async t=>{const s=(o,a)=>({tagType:p.tag.tagHeader.getTagType(o,a),dataSize:p.tag.tagHeader.getDataSize(o,a),timestamp:p.tag.tagHeader.getTimestamp(o,a),timestampExtended:p.tag.tagHeader.getTimestampExtended(o,a),streamID:p.tag.tagHeader.getStreamID(o,a)}),e=(o,a,n,r)=>{let d;switch(o){case"script":d=p.tag.tagBody.parseMetaData(a,n);break;case"audio":d=p.tag.tagBody.parseAudio(a,n,r);break;case"video":d=p.tag.tagBody.parseVideo(a,n,r);break}return d};for(;this.offset<t.byteLength;){if(p.isSurplusTag(t,this.offset)===!1){this.payload=this.payload.slice(this.offset),this.offset=0;break}const a=s(t,this.offset+4),{tagType:n,dataSize:r}=a;if(!n)break;const d=e(n,t,this.offset+4+11,r);this.tag={header:a,body:d},this.on.tag&&this.on.tag(this.tag),this.offset=this.offset+4+11+r,await new Promise(h=>setTimeout(()=>h(!0),this.parseSpeed))}}}class Z{audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;on={audio:{},video:{}};constructor(){}audio={init:t=>{this.audio.destroy(),this.audioDecoderConfig={...t},this.audioDecoder=new AudioDecoder({output:s=>{this.on.audio.decode&&this.on.audio.decode(s)},error:s=>{this.on.audio.error&&this.on.audio.error(s)}}),this.audioDecoder.configure(this.audioDecoderConfig)},decode:t=>{if(!this.audioDecoder)return;const s=new EncodedAudioChunk(t);this.audioDecoder.decode(s)},flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={init:t=>{this.video.destroy(),this.videoDecoderConfig={...t},this.videoDecoder=new VideoDecoder({output:async s=>{const e=await createImageBitmap(s),o=s.timestamp;s.close(),e.width>0&&e.height>0?this.on.video.decode&&this.on.video.decode({timestamp:o,bitmap:e}):e.close()},error:s=>{this.on.video.error&&this.on.video.error(s)}}),this.videoDecoder.configure(this.videoDecoderConfig)},decode:t=>{if(this.videoDecoder&&(t.type==="key"&&(this.hasKeyFrame=!0),this.hasKeyFrame&&this.videoDecoder.decodeQueueSize<2)){const s=new EncodedVideoChunk(t);this.videoDecoder.decode(s)}},flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}}class ee{isRendering=!1;pendingFrames=[];offscreenCanvas;ctx;baseTime=0;constructor(){}init=({offscreenCanvas:t,baseTime:s=performance.timeOrigin})=>{this.destroy(),this.offscreenCanvas=t,this.ctx=this.offscreenCanvas.getContext("2d"),this.baseTime=s};destroy=()=>{this.isRendering=!1,this.pendingFrames=[],this.offscreenCanvas=void 0,this.ctx=void 0,this.baseTime=0};push=t=>{this.pendingFrames.push(t),this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=t=>{const s=performance.timeOrigin+performance.now(),o=this.baseTime+t/1e3-s;return Math.max(0,o)};renderFrame=async()=>{for(this.isRendering=!0;;){const t=this.pendingFrames.shift();if(!t)break;this.isRendering=!1,this.isRendering=!0;let{timestamp:s,bitmap:e}=t;const o=this.calculateTimeUntilNextFrame(s);this.ctx&&this.offscreenCanvas&&(await new Promise(a=>setTimeout(()=>a(!0),o)),this.ctx.drawImage(e,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height)),e.close()}this.isRendering=!1}}m.Decoder=Z,m.DecoderWorker=F,m.Demuxer=Y,m.DemuxerWorker=G,m.PrPlayer=J,m.VideoPlayer=ee,m.VideoPlayerWorker=D,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
|
|
3
|
+
`,O=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",W],{type:"text/javascript;charset=utf-8"});function E(i){let t;try{if(t=O&&(self.URL||self.webkitURL).createObjectURL(O),!t)throw"";const s=new Worker(t,{name:i?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(W),{name:i?.name})}}class D{worker=new E;constructor(){}setCut=async t=>this.worker.postMessage({action:"setCut",data:t});init=({offscreenCanvas:t,baseTime:s=0})=>this.worker.postMessage({action:"init",data:{offscreenCanvas:t,baseTime:s}},[t]);push=t=>this.worker.postMessage({action:"push",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}var z=Object.defineProperty,_=(i,t,s)=>t in i?z(i,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):i[t]=s,u=(i,t,s)=>_(i,typeof t!="symbol"?t+"":t,s);class j{constructor(t,s){u(this,"inputStream",new MediaStream),u(this,"outputStream",new MediaStream),u(this,"inputGain",1),u(this,"enhanceGain",1),u(this,"bgsGain",1),u(this,"bgmGain",1),u(this,"outputGain",1),u(this,"mixAudioMap",new Map),u(this,"audioContext",new AudioContext),u(this,"sourceNode"),u(this,"inputGainNode"),u(this,"enhanceGainNode"),u(this,"bgsGainNode"),u(this,"bgmGainNode"),u(this,"analyserNode"),u(this,"analyserArrayData"),u(this,"outputGainNode"),u(this,"destinationNode"),u(this,"filterStream",e=>e),u(this,"stop",()=>{{const e=this.inputStream.getTracks();for(const o of e)o.stop(),this.inputStream.removeTrack(o)}}),u(this,"getStream",()=>this.filterStream(this.outputStream)),u(this,"setMute",(e=!0)=>{e?this.analyserNode.disconnect(this.outputGainNode):this.analyserNode.connect(this.outputGainNode)}),u(this,"setInputGain",e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),u(this,"setEnhanceGain",async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)}),u(this,"setBgsGain",e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),u(this,"setBgmGain",e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),u(this,"setOutputGain",e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)}),u(this,"getVolume",()=>{const{analyserNode:e,analyserArrayData:o}=this;e.getByteFrequencyData(o);let a=0;for(let n=0;n<o.length;n++)a+=o[n];return Math.ceil(a/o.length)}),u(this,"mixAudio",(e,o="bgm")=>new Promise(async(a,n)=>{try{{const h=this.mixAudioMap.get(o);h&&h.stop()}const r=o==="bgs"?this.bgsGainNode:this.bgmGainNode,d=this.audioContext.createBufferSource();this.mixAudioMap.set(o,d),d.buffer=e,d.connect(r),d.onended=()=>{d.disconnect(r),this.mixAudioMap.delete(o),a(!0)},d.start(0)}catch(r){n(r)}})),u(this,"mixAudioStop",e=>{const o=this.mixAudioMap.get(e);o?.stop()}),u(this,"changeMix",(e,o)=>{const a=e==="bgs"?this.bgsGainNode:this.bgmGainNode;o?a.connect(this.destinationNode):a.disconnect(this.destinationNode)}),s&&(this.audioContext=s),this.inputStream=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;{const{sourceNode:e,inputGainNode:o,enhanceGainNode:a,bgsGainNode:n,bgmGainNode:r,analyserNode:d,outputGainNode:h,destinationNode:c}=this;e.connect(o),o.connect(a),a.connect(d),n.connect(d),r.connect(d),a.connect(c),n.connect(c),r.connect(c),d.connect(h),h.connect(this.audioContext.destination)}this.setMute(!0),this.audioContext.resume()}}const H=async(i,t)=>{try{const{format:s,numberOfChannels:e,numberOfFrames:o,sampleRate:a}=t,n=i.createBuffer(e,o,a);for(let r=0;r<e;r++){const d=t.allocationSize({planeIndex:r}),h=new Uint8Array(d);t.copyTo(h,{planeIndex:r});const c=new DataView(h.buffer),f=n.getChannelData(r);for(let g=0;g<o;g++){let l;switch(s){case"s16":case"s16-planar":l=c.getInt16(g*2,!0)/32768;break;case"f32":case"f32-planar":l=c.getFloat32(g*4,!0);break;case"u8":case"u8-planar":l=(c.getUint8(g)-128)/128;break;default:throw new Error(`Unsupported audio format: ${s}`)}f[g]=Math.max(-1,Math.min(1,l))}}return n}catch(s){throw console.error("Failed to convert AudioData to AudioBuffer:",s),s}};class ${prAudioStream;audioContext;destination;stream=new MediaStream;nextStartTime=0;pendingSources=[];constructor(){}init=t=>{t||(t=new(window.AudioContext||window.webkitAudioContext)),this.audioContext=t,this.destination=this.audioContext.createMediaStreamDestination(),this.stream=new MediaStream,this.stream.addTrack(this.destination.stream.getAudioTracks()[0]),this.prAudioStream=new j(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(t){try{if(!this.audioContext||!this.destination)return;const s=await H(this.audioContext,t);if(!s)return;const e=this.audioContext.createBufferSource();e.buffer=s,e.connect(this.destination);const o=Math.max(this.nextStartTime,this.audioContext.currentTime);this.nextStartTime=o+s.duration,e.start(o),this.pendingSources.push(e),e.onended=()=>{this.pendingSources=this.pendingSources.filter(a=>a!==e)},this.audioContext.state==="suspended"&&await this.audioContext.resume()}finally{t.close()}}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(t=>t.stop()),this.pendingSources=[]}}class q{#t={timeout:5*1e3};#e;constructor(t={}){this.#t={...this.#t,...t}}check=(t,s)=>new Promise(async(e,o)=>{this.stop(),this.#e=new AbortController;const a=window.setTimeout(()=>{this.#e?.abort("Timeout."),o({status:"timeout",reason:""})},this.#t.timeout);try{const n=await fetch(t,{...s,method:"HEAD",signal:this.#e?.signal});n.status===200?e({status:"successed",reason:""}):o({status:"failed",reason:`${n.status}`})}catch(n){o({status:"error",reason:n.message})}clearTimeout(a)});request=async(t,s)=>new Promise(async(e,o)=>{try{await this.check(t,s),this.#e=new AbortController;const a=await fetch(t,{...s,signal:this.#e?.signal});e(a)}catch(a){this.stop(),o(a)}});stop=()=>{this.#e?.signal.aborted===!1&&this.#e.abort("Actively stop.")}}const K=async(i,t)=>{const s=[...i.keys()],{timestamp:e,bitmap:o}=t;for(const a of s){const n=i.get(a);if(!n)continue;const{options:r,worker:d}=n,{sx:h=0,sy:c=0,sw:f=o.width,sh:g=o.height}=r,l=await createImageBitmap(o,h,c,f,g);d.push({timestamp:e,bitmap:l})}},Q=i=>{const t=[...i.keys()];for(const s of t)i.get(s)?.worker.destroy(),i.delete(s)};class J{prFetch=new q;demuxerWorker;decoderWorker;audioPlayer;videoPlayerWorker;renderBaseTime=0;cutVideoPlayerWorkers=new Map;canvas;on={demuxer:{},decoder:{}};constructor(){}init=()=>{this.stop(),this.initDemuxer(),this.initDecoder(),this.renderBaseTime=new Date().getTime(),this.audioPlayer=new $,this.audioPlayer.init()};start=async t=>{try{const e=(await this.prFetch.request(t)).body?.getReader();if(!e)throw new Error("Reader is error.");for(;;){const{done:o,value:a}=await e.read();if(a&&this.demuxerWorker?.push(a),o)break}}catch{}};stop=()=>{this.prFetch.stop(),this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.videoPlayerWorker?.destroy(),Q(this.cutVideoPlayerWorkers),this.audioPlayer?.destroy(),this.renderBaseTime=0,this.canvas=void 0};onTag=t=>{if(!this.decoderWorker)return;const{header:s,body:e}=t,{tagType:o,timestamp:a}=s;switch(o){case"script":{const{width:n,height:r}=e;this.initRender({width:n,height:r}),this.on.demuxer.script&&this.on.demuxer.script(t)}break;case"audio":{const{accPacketType:n,data:r}=e;if(n===0){const{codec:d,sampleRate:h,channelConfiguration:c}=e,f={codec:d,sampleRate:h,numberOfChannels:c,description:new Uint8Array([])};this.decoderWorker.audio.init(f)}else n===1&&this.decoderWorker.audio.decode({type:"key",timestamp:a*1,data:r});this.on.demuxer.audio&&this.on.demuxer.audio(t)}break;case"video":{const{avcPacketType:n,frameType:r,data:d,nalus:h=[]}=e;if(n===0){const{codec:c,data:f}=e;this.decoderWorker.video.init({codec:c,description:f})}else if(n===1){const c=r===1?"key":"delta";this.decoderWorker.video.decode({type:c,timestamp:a*1e3,data:d});for(const f of h){const{header:g,payload:l}=f,{nal_unit_type:y}=g;y===6&&this.on.demuxer.sei&&this.on.demuxer.sei(l)}}this.on.demuxer.video&&this.on.demuxer.video(t)}break}};initDemuxer=()=>{this.demuxerWorker=new G,this.demuxerWorker.init(),this.demuxerWorker.on.tag=this.onTag};initDecoder=()=>{this.decoderWorker=new F,this.decoderWorker.on.audio.decode=t=>{this.on.decoder.audio&&this.on.decoder.audio(t),this.audioPlayer?.push(t)},this.decoderWorker.on.audio.error=t=>{this.stop(),this.on.error&&this.on.error(t)},this.decoderWorker.on.video.decode=t=>{this.on.decoder.video&&this.on.decoder.video(t),K(this.cutVideoPlayerWorkers,t),this.videoPlayerWorker?.push(t),t.bitmap.close()},this.decoderWorker.on.video.error=t=>{this.stop(),this.on.error&&this.on.error(t)}};initRender=({width:t=256,height:s=256}={})=>{if(!this.on.video)return;this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=s;const e=this.canvas.transferControlToOffscreen();this.videoPlayerWorker=new D,this.videoPlayerWorker.init({offscreenCanvas:e,baseTime:this.renderBaseTime}),this.on.video(this.canvas)};audio={setMute:t=>this.audioPlayer?.prAudioStream?.setMute(t)};video={createCut:(t,s)=>{this.cutVideoPlayerWorkers.has(t)&&this.cutVideoPlayerWorkers.get(t)?.worker.destroy();const e=document.createElement("canvas"),{sw:o,sh:a}=s;e.width=o||e.width,e.height=a||e.height;const n=new D,r=e.transferControlToOffscreen();n.init({offscreenCanvas:r,baseTime:this.renderBaseTime}),n.setCut(s),this.cutVideoPlayerWorkers.set(t,{options:s,worker:n}),this.on.cut&&this.on.cut(t,e)}}}const T=new TextDecoder("utf-8"),X=(i,t)=>{const s=i.getUint8(t),e=s>>7&1,o=s>>5&3,a=s&31;return{forbidden_zero_bit:e,nal_ref_idc:o,nal_unit_type:a}},U=(i,t)=>i.getUint8(t),I=(i,t,s)=>{const e=new Uint8Array(i.buffer.slice(t,t+s));return T?.decode(e)||""},v=(i,t,s)=>{let e=t,o,a=0;switch(s){case 0:o=i.getFloat64(e,!1),a=8;break;case 1:o=!!i.getUint8(e),a=1;break;case 2:{o="";const r=i.getUint16(e,!1);e=e+2;const d=new Int8Array(i.buffer,e,r).filter(c=>c!==0);o=(T?.decode(d)||"").trim(),a=2+r}break;case 3:for(o={};e<i.byteLength;){const r=i.getUint16(e,!1);if(r===0)break;e=e+2;const d=I(i,e,r);e=e+r;const h=U(i,e);if(h===6)break;e=e+1;const c=v(i,e,h);e=e+c.length,o[d]=c.value,a=2+r+1+c.length}break;case 8:{o={};const r=i.getUint32(e,!1);e=e+4;for(let d=0;d<r;d++){const h=i.getUint16(e,!1);e=e+2;const c=I(i,e,h);e=e+h;const f=U(i,e);e=e+1;const g=v(i,e,f);e=e+g.length,o[c]=g.value,a=2+h+1+g.length}}break;case 10:{o=[];const r=i.getUint32(e,!1);e=e+4;for(let d=0;d<r;d++){const h=U(i,e);e=e+1;const c=v(i,e,h);e=e+c.length,o.push(c.value),a=1+c.length}}break}return{amfType:s,length:a,value:o}},w=(i,t)=>i.getUint8(t)<<16|i.getUint8(t+1)<<8|i.getUint8(t+2),p={header:{getSignature:i=>{const t=new Int8Array(i.buffer.slice(0,3));return T?.decode(t)||""},getVersion:i=>i.getUint8(3),getFlags:i=>{const s=i.getUint8(0).toString(2).padStart(5,"0").split(""),[,,e,,o]=s;return{audio:o==="1",video:e==="1"}},getDataOffset:i=>i.getUint32(5)},getPreviousTagSize:(i,t)=>i.getUint32(t),isSurplusTag:(i,t)=>{let s=!0;const e=i.byteLength;if(t+4>e)s=!1;else if(t+4+11>e)s=!1;else{const o=w(i,t+4+1);t+4+11+o>e&&(s=!1)}return s},tag:{tagHeader:{getTagType:(i,t)=>{const s=i.getUint8(t);let e;switch(s){case 18:e="script";break;case 8:e="audio";break;case 9:e="video";break}return e},getDataSize:(i,t)=>w(i,t+1),getTimestamp:(i,t)=>w(i,t+4),getTimestampExtended:(i,t)=>i.getUint8(t+7),getStreamID:(i,t)=>w(i,t+8)},tagBody:{parseAudio:(i,t,s)=>{let e=t;const o=i.getUint8(e),a=o>>4&15,n=o>>2&3,r=o>>1&1,d=o&1;e=e+1;const h=i.getUint8(e);e=e+1;const c=s-2,f=new Uint8Array(i.buffer.slice(e,e+c));if(a===10&&h===0){const g=i.getUint8(e),l=i.getUint8(e+1),y=(g&248)>>3,k=(g&7)<<1|l>>7,x=(l&120)>>3,S=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],C=`mp4a.40.${y}`,A=S[k];return{soundFormat:a,soundRate:n,soundSize:r,soundType:d,accPacketType:h,data:f,audioObjectType:y,samplingFrequencyIndex:k,channelConfiguration:x,codec:C,sampleRate:A}}return{soundFormat:a,soundRate:n,soundSize:r,soundType:d,accPacketType:h,data:f}},parseVideo:(i,t,s)=>{let e=t;const o=i.getUint8(e),a=o>>4&15,n=o&15;e=e+1;const r=i.getUint8(e);e=e+1;const d=w(i,e);e=e+3;const h=s-5,c=new Uint8Array(i.buffer.slice(e,e+h));switch(n){case 7:if(r===0){const f=i.getUint8(e);if(e=e+1,f!==1)throw new Error("Invalid AVC version");const g=i.getUint8(e)&255;e=e+1;const l=i.getUint8(e)&255;e=e+1;const y=i.getUint8(e)&255;e=e+1;const S=`avc1.${Array.from([g,l,y],oe=>oe.toString(16).padStart(2,"0")).join("")}`,C=(i.getUint8(e)&3)-1;e=e+1;const A=i.getUint8(e)&31;e=e+1;const M=i.getUint16(e,!1);e=e+2;const te=new Uint8Array(i.buffer.slice(e,e+M));e=e+M;const se=i.getUint8(e)&31;e=e+1;const P=i.getUint16(e,!1);e=e+2;const ie=new Uint8Array(i.buffer.slice(e,e+P));return e=e+P,{frameType:a,codecID:n,avcPacketType:r,cts:d,data:c,version:f,codec:S,profile:g,compatibility:l,level:y,lengthSizeMinusOne:C,numOfSequenceParameterSets:A,sequenceParameterSetLength:M,sps:te,numOfPictureParameterSets:se,pictureParameterSetLength:P,pps:ie}}else if(r===1){const f=[],g=e+s-5;for(;e+4<g;){const l=i.getUint32(e,!1);e=e+4;const y=X(i,e);e=e+1;const k=l-1,x=new Uint8Array(i.buffer.slice(e,e+k));e=e+k,f.push({size:l,header:y,payload:x})}return{frameType:a,codecID:n,avcPacketType:r,cts:d,data:c,nalus:f}}break;default:throw new Error("Unsupported codecID")}return{frameType:a,codecID:n,avcPacketType:r,cts:d,data:c}},parseMetaData:(i,t)=>{let s=t;{if(i.getUint8(s)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");s=s+1}const e=i.getUint16(s,!1);s=s+2;{const n=new Int8Array(i.buffer.slice(s,s+e));if((T?.decode(n)||"")!=="onMetaData")throw new Error("Expected 'onMetaData' string");s=s+e}const o=U(i,s);return s=s+1,v(i,s,o).value}}}};class Y{parseSpeed=8;pendingPayloads=[];payload=new Uint8Array(0);offset=0;is_parsing=!1;header;tag;on={};constructor(){}init=()=>{this.destroy()};push=t=>{this.pendingPayloads.push(t),this.is_parsing||this.parse()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.offset=0,this.is_parsing=!1,this.header=void 0,this.tag=void 0};parse=async()=>{for(this.is_parsing=!0;;){const t=this.pendingPayloads.shift();if(!t)break;const s=new Uint8Array(this.payload.byteLength+t.byteLength);s.set(this.payload,0),s.set(t,this.payload.byteLength),this.payload=s;const e=new DataView(this.payload.buffer);this.header||this.parseHeader(e),await this.parseTag(e)}this.is_parsing=!1};parseHeader=t=>(this.header={signature:p.header.getSignature(t),version:p.header.getVersion(t),flags:p.header.getFlags(t),dataOffset:p.header.getDataOffset(t)},this.offset=this.header?.dataOffset,this.on.header&&this.on.header(this.header),this.header);parseTag=async t=>{const s=(o,a)=>({tagType:p.tag.tagHeader.getTagType(o,a),dataSize:p.tag.tagHeader.getDataSize(o,a),timestamp:p.tag.tagHeader.getTimestamp(o,a),timestampExtended:p.tag.tagHeader.getTimestampExtended(o,a),streamID:p.tag.tagHeader.getStreamID(o,a)}),e=(o,a,n,r)=>{let d;switch(o){case"script":d=p.tag.tagBody.parseMetaData(a,n);break;case"audio":d=p.tag.tagBody.parseAudio(a,n,r);break;case"video":d=p.tag.tagBody.parseVideo(a,n,r);break}return d};for(;this.offset<t.byteLength;){if(p.isSurplusTag(t,this.offset)===!1){this.payload=this.payload.slice(this.offset),this.offset=0;break}const a=s(t,this.offset+4),{tagType:n,dataSize:r}=a;if(!n)break;const d=e(n,t,this.offset+4+11,r);this.tag={header:a,body:d},this.on.tag&&this.on.tag(this.tag),this.offset=this.offset+4+11+r,await new Promise(h=>setTimeout(()=>h(!0),this.parseSpeed))}}}class Z{audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;on={audio:{},video:{}};constructor(){}audio={init:t=>{this.audio.destroy(),this.audioDecoderConfig={...t},this.audioDecoder=new AudioDecoder({output:s=>{this.on.audio.decode&&this.on.audio.decode(s)},error:s=>{this.on.audio.error&&this.on.audio.error(s)}}),this.audioDecoder.configure(this.audioDecoderConfig)},decode:t=>{if(!this.audioDecoder)return;const s=new EncodedAudioChunk(t);this.audioDecoder.decode(s)},flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={init:t=>{this.video.destroy(),this.videoDecoderConfig={...t},this.videoDecoder=new VideoDecoder({output:async s=>{const e=await createImageBitmap(s),o=s.timestamp;s.close(),e.width>0&&e.height>0?this.on.video.decode&&this.on.video.decode({timestamp:o,bitmap:e}):e.close()},error:s=>{this.on.video.error&&this.on.video.error(s)}}),this.videoDecoder.configure(this.videoDecoderConfig)},decode:t=>{if(this.videoDecoder&&(t.type==="key"&&(this.hasKeyFrame=!0),this.hasKeyFrame&&this.videoDecoder.decodeQueueSize<2)){const s=new EncodedVideoChunk(t);this.videoDecoder.decode(s)}},flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}}class ee{isRendering=!1;pendingFrames=[];offscreenCanvas;ctx;baseTime=0;constructor(){}init=({offscreenCanvas:t,baseTime:s=performance.timeOrigin})=>{this.destroy(),this.offscreenCanvas=t,this.ctx=this.offscreenCanvas.getContext("2d"),this.baseTime=s};destroy=()=>{this.isRendering=!1,this.pendingFrames=[],this.offscreenCanvas=void 0,this.ctx=void 0,this.baseTime=0};push=t=>{this.pendingFrames.push(t),this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=t=>{const s=performance.timeOrigin+performance.now(),o=this.baseTime+t/1e3-s;return Math.max(0,o)};renderFrame=async()=>{for(this.isRendering=!0;;){const t=this.pendingFrames.shift();if(!t)break;this.isRendering=!1,this.isRendering=!0;let{timestamp:s,bitmap:e}=t;const o=this.calculateTimeUntilNextFrame(s);this.ctx&&this.offscreenCanvas&&(await new Promise(a=>setTimeout(()=>a(!0),o)),this.ctx.drawImage(e,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height)),e.close()}this.isRendering=!1}}m.Decoder=Z,m.DecoderWorker=F,m.Demuxer=Y,m.DemuxerWorker=G,m.PrPlayer=J,m.VideoPlayer=ee,m.VideoPlayerWorker=D,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
|