pr-player 0.1.0 → 0.1.1
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/PrFetch.d.ts +28 -0
- package/dist/PrPlayer.d.ts +23 -20
- package/dist/PrResolves.d.ts +19 -0
- package/dist/cacher/Cacher.d.ts +18 -0
- package/dist/decoder/Decoder.d.ts +4 -4
- package/dist/demuxer/264Parser.d.ts +26 -0
- package/dist/demuxer/Demuxer.d.ts +27 -10
- package/dist/demuxer/DemuxerWorker.d.ts +2 -2
- package/dist/demuxer/flv264Parser.d.ts +27 -419
- package/dist/demuxer/ts264Parser.d.ts +76 -0
- package/dist/demuxer/type.d.ts +0 -4
- package/dist/index.js +1008 -484
- package/dist/index.umd.cjs +4 -3
- package/dist/render/Render.d.ts +5 -2
- package/dist/render/RenderWorker.d.ts +2 -2
- package/dist/tools.d.ts +9 -0
- package/package.json +2 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
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',M=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",b],{type:"text/javascript;charset=utf-8"});function E(i){let t;try{if(t=M&&(self.URL||self.webkitURL).createObjectURL(M),!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 P{worker=new E;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 G=`(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
|
-
`,
|
|
3
|
-
`,O=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",F],{type:"text/javascript;charset=utf-8"});function V(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(F),{name:i?.name})}}class W{worker=new V;constructor(){}init=({offscreenCanvas:t,baseTime:s=0,writable:e})=>this.worker.postMessage({action:"init",data:{offscreenCanvas:t,baseTime:s,writable:e}},[t,e]);setShader=t=>this.worker.postMessage({action:"setShader",data:t});setSize=({width:t,height:s})=>this.worker.postMessage({action:"setSize",data:{width:t,height:s}});push=t=>this.worker.postMessage({action:"push",data:t});setCut=async t=>this.worker.postMessage({action:"setCut",data:t});setPause=t=>this.worker.postMessage({action:"setPause",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}var j=Object.defineProperty,H=(i,t,s)=>t in i?j(i,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):i[t]=s,c=(i,t,s)=>H(i,typeof t!="symbol"?t+"":t,s);class ${constructor(t,s){c(this,"inputStream",new MediaStream),c(this,"outputStream",new MediaStream),c(this,"inputGain",1),c(this,"enhanceGain",1),c(this,"bgsGain",1),c(this,"bgmGain",1),c(this,"outputGain",1),c(this,"mixAudioMap",new Map),c(this,"audioContext",new AudioContext),c(this,"sourceNode"),c(this,"inputGainNode"),c(this,"enhanceGainNode"),c(this,"bgsGainNode"),c(this,"bgmGainNode"),c(this,"analyserNode"),c(this,"analyserArrayData"),c(this,"outputGainNode"),c(this,"destinationNode"),c(this,"filterStream",e=>e),c(this,"stop",()=>{{const e=this.inputStream.getTracks();for(const a of e)a.stop(),this.inputStream.removeTrack(a)}}),c(this,"getStream",()=>this.filterStream(this.outputStream)),c(this,"setMute",(e=!0)=>{e?this.analyserNode.disconnect(this.outputGainNode):this.analyserNode.connect(this.outputGainNode)}),c(this,"setInputGain",e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),c(this,"setEnhanceGain",async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)}),c(this,"setBgsGain",e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),c(this,"setBgmGain",e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),c(this,"setOutputGain",e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)}),c(this,"getVolume",()=>{const{analyserNode:e,analyserArrayData:a}=this;e.getByteFrequencyData(a);let o=0;for(let r=0;r<a.length;r++)o+=a[r];return Math.ceil(o/a.length)}),c(this,"mixAudio",(e,a="bgm")=>new Promise(async(o,r)=>{try{{const u=this.mixAudioMap.get(a);u&&u.stop()}const n=a==="bgs"?this.bgsGainNode:this.bgmGainNode,d=this.audioContext.createBufferSource();this.mixAudioMap.set(a,d),d.buffer=e,d.connect(n),d.onended=()=>{d.disconnect(n),this.mixAudioMap.delete(a),o(!0)},d.start(0)}catch(n){r(n)}})),c(this,"mixAudioStop",e=>{const a=this.mixAudioMap.get(e);a?.stop()}),c(this,"changeMix",(e,a)=>{const o=e==="bgs"?this.bgsGainNode:this.bgmGainNode;a?o.connect(this.destinationNode):o.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:a,enhanceGainNode:o,bgsGainNode:r,bgmGainNode:n,analyserNode:d,outputGainNode:u,destinationNode:h}=this;e.connect(a),a.connect(o),o.connect(d),r.connect(d),n.connect(d),o.connect(h),r.connect(h),n.connect(h),d.connect(u),u.connect(this.audioContext.destination)}this.setMute(!0),this.audioContext.resume()}}const q=async(i,t)=>{try{const{format:s,numberOfChannels:e,numberOfFrames:a,sampleRate:o}=t,r=i.createBuffer(e,a,o);for(let n=0;n<e;n++){const d=t.allocationSize({planeIndex:n}),u=new Uint8Array(d);t.copyTo(u,{planeIndex:n});const h=new DataView(u.buffer),f=r.getChannelData(n);for(let g=0;g<a;g++){let p;switch(s){case"s16":case"s16-planar":p=h.getInt16(g*2,!0)/32768;break;case"f32":case"f32-planar":p=h.getFloat32(g*4,!0);break;case"u8":case"u8-planar":p=(h.getUint8(g)-128)/128;break;default:throw new Error(`Unsupported audio format: ${s}`)}f[g]=Math.max(-1,Math.min(1,p))}}return r}catch(s){throw console.error("Failed to convert AudioData to AudioBuffer:",s),s}};class K{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 $(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(t){try{if(!this.audioContext||!this.destination)return;const s=await q(this.audioContext,t);if(!s)return;const e=this.audioContext.createBufferSource();e.buffer=s,e.connect(this.destination);const a=Math.max(this.nextStartTime,this.audioContext.currentTime);this.nextStartTime=a+s.duration,e.start(a),this.pendingSources.push(e),e.onended=()=>{this.pendingSources=this.pendingSources.filter(o=>o!==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,a)=>{this.stop(),this.#e=new AbortController;const o=window.setTimeout(()=>{this.#e?.abort("Timeout."),a({status:"timeout",reason:""})},this.#t.timeout);try{const r=await fetch(t,{...s,method:"HEAD",signal:this.#e?.signal});r.status===200?e({status:"successed",reason:""}):a({status:"failed",reason:`${r.status}`})}catch(r){a({status:"error",reason:r.message})}clearTimeout(o)});request=async(t,s)=>new Promise(async(e,a)=>{try{await this.check(t,s),this.#e=new AbortController;const o=await fetch(t,{...s,signal:this.#e?.signal});e(o)}catch(o){this.stop(),a(o)}});stop=()=>{this.#e?.signal.aborted===!1&&this.#e.abort("Actively stop.")}}const I=i=>{const t=i?.getTracks()||[];for(const s of t)s.stop()},B=i=>{const t=new W,s=document.createElement("canvas"),e=s.transferControlToOffscreen(),a=new MediaStreamTrackGenerator({kind:"video"}),o=new MediaStream([a]),r=()=>{t.destroy(),I(o)};return t.init({offscreenCanvas:e,baseTime:i,writable:a.writable}),{worker:t,canvas:s,stream:o,destroy:r}};class J{prFetch=new Q;demuxerWorker;decoderWorker;audioPlayer;renderWorker;renderBaseTime=0;stream;canvas;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(){}init=()=>{this.initDemuxer(),this.initDecoder(),this.audioPlayer=new K,this.audioPlayer.init(),this.initRender()};start=async t=>(this.stop(),this.renderBaseTime=new Date().getTime(),this.init(),this.prFetch.request(t).then(async s=>{const e=s.body?.getReader();if(!e)throw new Error("Reader is error.");const a=()=>{e.read().then(({done:o,value:r})=>{r&&this.demuxerWorker?.push(r),!o&&a()}).catch(o=>{if(o.name!=="AbortError")throw o})};a()}).catch(s=>{console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: err",s)}));stop=async()=>{try{this.prFetch.stop()}catch(s){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: error",s)}this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy(),I(this.stream);const t=[...this.cutRenders.keys()];for(const s of t)this.cut.remove(s);this.audioPlayer?.destroy(),this.renderBaseTime=0,this.canvas=void 0};onTag=t=>{if(!this.decoderWorker)return;const{header:s,body:e}=t,{tagType:a,timestamp:o}=s;switch(a){case"script":{const{width:r,height:n}=e;this.renderWorker?.setSize({width:r,height:n}),this.on.demuxer.script&&this.on.demuxer.script(t)}break;case"audio":{const{accPacketType:r,data:n}=e;if(r===0){const{codec:d,sampleRate:u,channelConfiguration:h}=e,f={codec:d,sampleRate:u,numberOfChannels:h,description:new Uint8Array([])};this.decoderWorker.audio.init(f)}else r===1&&this.decoderWorker.audio.decode({type:"key",timestamp:o*1,data:n});this.on.demuxer.audio&&this.on.demuxer.audio(t)}break;case"video":{const{avcPacketType:r,frameType:n,data:d,nalus:u=[]}=e;if(r===0){const{codec:h,data:f}=e;this.decoderWorker.video.init({codec:h,description:f})}else if(r===1){const h=n===1?"key":"delta";this.decoderWorker.video.decode({type:h,timestamp:o*1e3,data:d});for(const f of u){const{header:g,payload:p}=f,{nal_unit_type:y}=g;y===6&&this.on.demuxer.sei&&this.on.demuxer.sei(p)}}this.on.demuxer.video&&this.on.demuxer.video(t)}break}};initDemuxer=()=>{this.demuxerWorker=new P,this.demuxerWorker.init(),this.demuxerWorker.on.tag=this.onTag};initDecoder=()=>{this.decoderWorker=new N,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=async t=>{this.renderWorker?.push(t);const s=[...this.cutRenders.keys()];for(const e of s)this.cutRenders.get(e)?.worker.push(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=()=>{const{worker:t,canvas:s,stream:e}=B(this.renderBaseTime);this.renderWorker=t,this.canvas=s,this.stream=e,this.renderWorker.setPause(!1)};getCanvas=()=>this.canvas;getStream=()=>this.stream;setPause=t=>{this.renderWorker?.setPause(t)};setShader=t=>{this.renderWorker?.setShader(t)};setMute=t=>this.audioPlayer?.prAudioStream?.setMute(t);cut={create:(t,s)=>{let e=this.cutRenders.get(t);return e?(e.worker.setCut(s),e.worker.setPause(!1),e):(e=B(this.renderBaseTime),e.worker.setCut(s),this.cutRenders.set(t,e),e)},getCanvas:t=>this.cutRenders.get(t)?.canvas,getStream:t=>this.cutRenders.get(t)?.stream,setPause:(t,s)=>{this.cutRenders.get(t)?.worker.setPause(s)},setShader:(t,s)=>{this.cutRenders.get(t)?.worker.setShader(s)},remove:t=>{this.cutRenders.get(t)?.destroy(),this.cutRenders.delete(t)}}}const T=new TextDecoder("utf-8"),X=(i,t)=>{const s=i.getUint8(t),e=s>>7&1,a=s>>5&3,o=s&31;return{forbidden_zero_bit:e,nal_ref_idc:a,nal_unit_type:o}},U=(i,t)=>i.getUint8(t),z=(i,t,s)=>{const e=new Uint8Array(i.buffer.slice(t,t+s));return T?.decode(e)||""},v=(i,t,s)=>{let e=t,a,o=0;switch(s){case 0:a=i.getFloat64(e,!1),o=8;break;case 1:a=!!i.getUint8(e),o=1;break;case 2:{a="";const n=i.getUint16(e,!1);e=e+2;const d=new Int8Array(i.buffer,e,n).filter(h=>h!==0);a=(T?.decode(d)||"").trim(),o=2+n}break;case 3:for(a={};e<i.byteLength;){const n=i.getUint16(e,!1);if(n===0)break;e=e+2;const d=z(i,e,n);e=e+n;const u=U(i,e);if(u===6)break;e=e+1;const h=v(i,e,u);e=e+h.length,a[d]=h.value,o=2+n+1+h.length}break;case 8:{a={};const n=i.getUint32(e,!1);e=e+4;for(let d=0;d<n;d++){const u=i.getUint16(e,!1);e=e+2;const h=z(i,e,u);e=e+u;const f=U(i,e);e=e+1;const g=v(i,e,f);e=e+g.length,a[h]=g.value,o=2+u+1+g.length}}break;case 10:{a=[];const n=i.getUint32(e,!1);e=e+4;for(let d=0;d<n;d++){const u=U(i,e);e=e+1;const h=v(i,e,u);e=e+h.length,a.push(h.value),o=1+h.length}}break}return{amfType:s,length:o,value:a}},w=(i,t)=>i.getUint8(t)<<16|i.getUint8(t+1)<<8|i.getUint8(t+2),l={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,,a]=s;return{audio:a==="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 a=w(i,t+4+1);t+4+11+a>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 a=i.getUint8(e),o=a>>4&15,r=a>>2&3,n=a>>1&1,d=a&1;e=e+1;const u=i.getUint8(e);e=e+1;const h=s-2,f=new Uint8Array(i.buffer.slice(e,e+h));if(o===10&&u===0){const g=i.getUint8(e),p=i.getUint8(e+1),y=(g&248)>>3,k=(g&7)<<1|p>>7,x=(p&120)>>3,S=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],D=`mp4a.40.${y}`,C=S[k];return{soundFormat:o,soundRate:r,soundSize:n,soundType:d,accPacketType:u,data:f,audioObjectType:y,samplingFrequencyIndex:k,channelConfiguration:x,codec:D,sampleRate:C}}return{soundFormat:o,soundRate:r,soundSize:n,soundType:d,accPacketType:u,data:f}},parseVideo:(i,t,s)=>{let e=t;const a=i.getUint8(e),o=a>>4&15,r=a&15;e=e+1;const n=i.getUint8(e);e=e+1;const d=w(i,e);e=e+3;const u=s-5,h=new Uint8Array(i.buffer.slice(e,e+u));switch(r){case 7:if(n===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 p=i.getUint8(e)&255;e=e+1;const y=i.getUint8(e)&255;e=e+1;const S=`avc1.${Array.from([g,p,y],ae=>ae.toString(16).padStart(2,"0")).join("")}`,D=(i.getUint8(e)&3)-1;e=e+1;const C=i.getUint8(e)&31;e=e+1;const A=i.getUint16(e,!1);e=e+2;const te=new Uint8Array(i.buffer.slice(e,e+A));e=e+A;const se=i.getUint8(e)&31;e=e+1;const R=i.getUint16(e,!1);e=e+2;const ie=new Uint8Array(i.buffer.slice(e,e+R));return e=e+R,{frameType:o,codecID:r,avcPacketType:n,cts:d,data:h,version:f,codec:S,profile:g,compatibility:p,level:y,lengthSizeMinusOne:D,numOfSequenceParameterSets:C,sequenceParameterSetLength:A,sps:te,numOfPictureParameterSets:se,pictureParameterSetLength:R,pps:ie}}else if(n===1){const f=[],g=e+s-5;for(;e+4<g;){const p=i.getUint32(e,!1);e=e+4;const y=X(i,e);e=e+1;const k=p-1,x=new Uint8Array(i.buffer.slice(e,e+k));e=e+k,f.push({size:p,header:y,payload:x})}return{frameType:o,codecID:r,avcPacketType:n,cts:d,data:h,nalus:f}}break;default:throw new Error("Unsupported codecID")}return{frameType:o,codecID:r,avcPacketType:n,cts:d,data:h}},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 r=new Int8Array(i.buffer.slice(s,s+e));if((T?.decode(r)||"")!=="onMetaData")throw new Error("Expected 'onMetaData' string");s=s+e}const a=U(i,s);return s=s+1,v(i,s,a).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:l.header.getSignature(t),version:l.header.getVersion(t),flags:l.header.getFlags(t),dataOffset:l.header.getDataOffset(t)},this.offset=this.header?.dataOffset,this.on.header&&this.on.header(this.header),this.header);parseTag=async t=>{const s=(a,o)=>({tagType:l.tag.tagHeader.getTagType(a,o),dataSize:l.tag.tagHeader.getDataSize(a,o),timestamp:l.tag.tagHeader.getTimestamp(a,o),timestampExtended:l.tag.tagHeader.getTimestampExtended(a,o),streamID:l.tag.tagHeader.getStreamID(a,o)}),e=(a,o,r,n)=>{let d;switch(a){case"script":d=l.tag.tagBody.parseMetaData(o,r);break;case"audio":d=l.tag.tagBody.parseAudio(o,r,n);break;case"video":d=l.tag.tagBody.parseVideo(o,r,n);break}return d};for(;this.offset<t.byteLength;){if(l.isSurplusTag(t,this.offset)===!1){this.payload=this.payload.slice(this.offset),this.offset=0;break}const o=s(t,this.offset+4),{tagType:r,dataSize:n}=o;if(!r)break;const d=e(r,t,this.offset+4+11,n);this.tag={header:o,body:d},this.on.tag&&this.on.tag(this.tag),this.offset=this.offset+4+11+n,await new Promise(u=>setTimeout(()=>u(!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),a=s.timestamp;s.close(),e.width>0&&e.height>0?this.on.video.decode&&this.on.video.decode({timestamp:a,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;writable;writer;ctx;cutOption;baseTime=0;pause=!1;shader=["stream"];constructor(){}init=({offscreenCanvas:t,baseTime:s=performance.timeOrigin,writable:e})=>{this.destroy(),this.offscreenCanvas=t,this.writable=e,this.writer=this.writable.getWriter(),this.ctx=this.offscreenCanvas.getContext("2d"),this.baseTime=s};setShader=t=>{this.shader=t};setSize=({width:t,height:s})=>{this.offscreenCanvas&&(this.offscreenCanvas.width=t,this.offscreenCanvas.height=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)};setCut=t=>{this.cutOption=t};setPause=t=>{this.pause=t,this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=t=>{const s=performance.timeOrigin+performance.now(),a=this.baseTime+t/1e3-s;return Math.max(0,a)};renderFrame=async()=>{for(this.isRendering=!0;;){const t=this.pendingFrames.shift();if(!t)break;let{timestamp:s,bitmap:e}=t;if(this.cutOption){const{sx:o=0,sy:r=0,sw:n=e.width,sh:d=e.height}=this.cutOption;e=await createImageBitmap(e,o,r,n,d)}const a=this.calculateTimeUntilNextFrame(s);await new Promise(o=>setTimeout(()=>o(!0),a)),this.drawImage({timestamp:s,bitmap:e}),this.cutOption&&e.close()}this.isRendering=!1};drawImage=t=>{if(this.pause!==!0){if(this.shader.includes("stream")){const s=new VideoFrame(t.bitmap,{timestamp:t.timestamp});this.writer.write(s),s.close()}this.shader.includes("canvas")&&this.ctx&&this.offscreenCanvas&&this.ctx.drawImage(t.bitmap,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height)}}}m.Decoder=Z,m.DecoderWorker=N,m.Demuxer=Y,m.DemuxerWorker=P,m.PrPlayer=J,m.Render=ee,m.RenderWorker=W,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(b,_){typeof exports=="object"&&typeof module<"u"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):(b=typeof globalThis<"u"?globalThis:b||self,_(b["pr-player"]={}))})(this,(function(b){"use strict";const _='(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>1e3&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.chunks=[]}}const M=(u,t)=>{const s=new Uint8Array(u),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},C=u=>{const t=new Uint8Array(4+u.length);return new DataView(t.buffer).setUint32(0,u.length,!1),t.set(u,4),t},I=u=>{let t=0;for(const n of u)t+=4+n.length;const s=new Uint8Array(t);let e=0;for(const n of u){const a=C(n);s.set(a,e),e+=a.length}return s},T=u=>{let t=0;const s=new DataView(u.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 i=s.getUint8(t)&255;t=t+1;const h=`avc1.${Array.from([n,a,i],m=>m.toString(16).padStart(2,"0")).join("")}`,c=(s.getUint8(t)&3)-1;t=t+1;const g=s.getUint8(t)&31;t=t+1;const d=s.getUint16(t,!1);t=t+2;const l=new Uint8Array(s.buffer.slice(t,t+d));t=t+d;const p=s.getUint8(t)&31;t=t+1;const f=s.getUint16(t,!1);t=t+2;const y=new Uint8Array(s.buffer.slice(t,t+f));return t=t+f,{version:e,codec:h,profile:n,compatibility:a,level:i,lengthSizeMinusOne:c,numOfSequenceParameterSets:g,sequenceParameterSetLength:d,sps:l,numOfPictureParameterSets:p,pictureParameterSetLength:f,pps:y}},D=u=>{let t="unknown";switch(u){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:i,payload_unit_start_indicator:o,adaptation_field_control:r}=n;if(a===1||i===void 0)return;let h=184;if(r===2||r===3){const c=t.getUint8(e);e+=1,this.parseAdaptationField(t,e),e+=c,h-=c}if(r===3&&(h-=1),r===1||r===3){const c=new Uint8Array(t.buffer.slice(e,e+h));if(i===0)return this.parsePAT(t,e);{const{programs:l=[]}=this.pat||{};if(l.find(f=>f.pmt_pid===i))return this.parsePMT(t,e)}const{streams:g=[]}=this.pmt||{},d=g.find(l=>l.elementary_pid===i);if(d){if(o===1){const l=this.payloadMap.get(i);if(l){switch(d.kind){case"audio":break;case"video":{const p=await this.parseVideo(l);this.on.chunk&&this.on.chunk(p),await new Promise(f=>setTimeout(()=>f(!0),8))}break}this.payloadMap.delete(i)}}{this.payloadMap.has(i)||this.payloadMap.set(i,new Uint8Array);const l=this.payloadMap.get(i),p=new Uint8Array(l.byteLength+c.byteLength);p.set(l,0),p.set(c,l.byteLength),this.payloadMap.set(i,p)}}}};parseHeader=(t,s)=>{let e=s;const n=t.getUint8(e),a=t.getUint8(e+1),i=t.getUint8(e+2),o=t.getUint8(e+3),r=(a&128)>>7;if(r===1)return{sync_byte:n,transport_error_indicator:r};const h=(a&64)>>6,c=(a&32)>>5,g=(a&31)<<8|i,d=(o&192)>>6,l=o>>4&3,p=o&15;return{sync_byte:n,transport_error_indicator:r,payload_unit_start_indicator:h,transport_priority:c,pid:g,transport_scrambling_control:d,adaptation_field_control:l,continuity_counter:p}};parsePAT=(t,s)=>{let e=s,n;{const o=t.getUint8(e);e+=1;const r=t.getUint8(e);if(e+=1,r!==0)throw new Error("Invalid PAT table_id");const h=t.getUint16(e)&4095;e+=2;const c=t.getUint16(e);e+=2;const g=(t.getUint8(e)&62)>>1,d=t.getUint8(e)&1;e+=1;const l=t.getUint8(e);e+=1;const p=t.getUint8(e);e+=1,n={pointer_field:o,table_id:r,section_length:h,transport_stream_id:c,version_number:g,current_next_indicator:d,section_number:l,last_section_number:p}}const a=[];{const o=n.section_length-5-4,r=e+o;for(;e<r;){const h=t.getUint16(e),c=t.getUint16(e+2)&8191;e+=4,h!==0&&c>=32&&c<=8190&&a.push({program_number:h,pmt_pid:c})}}const i=t.getUint32(e);this.pat={header:n,programs:a,crc32:i},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(t,s)=>{let e=s,n;{const o=t.getUint8(e);e+=1;const r=t.getUint8(e);if(e+=1,r!==2)throw new Error("Invalid PMT table_id");const h=t.getUint16(e)&4095;e+=2;const c=t.getUint16(e);e+=2;const g=(t.getUint8(e)&62)>>1,d=t.getUint8(e)&1;e+=1;const l=t.getUint8(e);e+=1;const p=t.getUint8(e);e+=1;const f=t.getUint16(e)&8191;e+=2;const y=t.getUint16(e)&4095;e+=2,n={pointer_field:o,table_id:r,section_length:h,transport_stream_id:c,version_number:g,current_next_indicator:d,section_number:l,last_section_number:p,pcr_pid:f,program_info_length:y}}const a=[];{const o=n.section_length-9-4,r=e+o;for(;e<r;){const h=t.getUint8(e),c=D(h),g=t.getUint16(e+1)&8191,d=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:c,stream_type:h,elementary_pid:g,es_info_length:d})}}const i=t.getUint32(e);this.pmt={header:n,streams:a,crc32:i},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(t,s)=>{let e=s,n,a,i,o;const r=t.getUint8(e),h=!!(r&128),c=!!(r&64),g=!!(r&32),d=!!(r&16),l=!!(r&8),p=!!(r&4),f=!!(r&2),y=!!(r&1);e+=1;const m=(U,b)=>{let _=BigInt(0);_|=BigInt(U.getUint16(b))<<25n,_|=BigInt(U.getUint16(b+1))<<17n,_|=BigInt(U.getUint16(b+2))<<9n,_|=BigInt(U.getUint16(b+3))<<1n,_|=BigInt(U.getUint16(b+4)>>7);const B=(U.getUint16(b+4)&1)<<8|U.getUint16(b+5);return _=_*300n+BigInt(B),_};if(d&&(n=m(t,e),e+=6),l&&(a=m(t,e),e+=6),p&&(i=t.getInt8(e),e+=1),f){const U=t.getUint8(e);e+=1,o=new Uint8Array(t.buffer,e,U),e+=U}return{discontinuity_indicator:h,random_access_indicator:c,elementary_stream_priority_indicator:g,pcr_flag:d,opcr_flag:l,splicing_point_flag:p,transport_private_data_flag:f,adaptation_field_extension_flag:y,pcr:n,opcr:a,splice_countdown:i,transport_private_data:o}};parseVideo=async t=>{const s=new DataView(t.buffer);let e=0,n,a;{const i=s.getUint8(e)===0&&s.getUint8(e+1)===0&&s.getUint8(e+2)===1;if(e+=3,!i)throw new Error("invalid ts video payload.");const o=s.getUint8(e);e+=1;const r=s.getUint8(e)<<8|s.getUint8(e+1);e+=2;let h,c;const g=o!==188&&o!==190&&o!==191&&o!==240&&o!==241&&o!==255&&o!==242;if(g){e+=1;const d=s.getUint8(e);e+=1;const l=d>>6,p=s.getUint8(e);e+=1,(l&2)===2&&(h=this.parsePtsDts(s,e),e+=5),(l&1)===1?(c=this.parsePtsDts(s,e),e+=5):c=h,e+=p-(e-9)}n={stream_id:o,pes_packet_length:r,pts:h,dts:c,optional_header_exist:g}}a=t.slice(e);{const i=this.getNalus(a);if(!this.videoConfig){let l,p;if(l=i.find(y=>y.type===7)?.data,p=i.find(y=>y.type===8)?.data,l&&p){const f=M(l,p),{codec:y}=T(f);this.videoConfig={kind:"video",codec:y,description:f,sps:l,pps:p},this.on.config&&this.on.config(this.videoConfig)}}const o=[];let r="delta";for(const l of i){const{type:p,data:f}=l;switch(p){case 9:break;case 1:r="delta",o.push(f);break;case 5:r="key",o.push(f);break}}const h=I(o),{dts:c=0,pts:g=0}=n,d=g-c;return{kind:"video",type:r,dts:c,pts:g,cts:d,data:h,nalus:o,nalusa:i}}};parsePtsDts(t,s){const e=t.getUint8(s),n=t.getUint8(s+1),a=t.getUint8(s+2),i=t.getUint8(s+3),o=t.getUint8(s+4),r=(BigInt(e)&0b00001110n)<<29n|(BigInt(n)&0b11111111n)<<22n|(BigInt(a)&0b11111110n)<<14n|(BigInt(i)&0b11111111n)<<7n|(BigInt(o)&0b11111110n)>>1n;return Number(r)/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 i=e-n;if(t[e-1]===0&&(i-=1),i!==0){const o=t.slice(n,n+i);s.push({type:a,data:o})}}return s}}const k=(u,t)=>u.getUint8(t)<<16|u.getUint8(t+1)<<8|u.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:i,timestamp:o}=n;if(a){const r=this.parseTagBody(a,t,s+4+11,i);switch(a){case"script":this.on.info&&this.on.info(r);break;case"audio":{const{accPacketType:h}=r;if(h===0){const{codec:c,sampleRate:g,channelConfiguration:d}=r;this.audioConfig={kind:"audio",codec:c,sampleRate:g,numberOfChannels:d},this.on.config&&this.on.config(this.audioConfig)}else{const{cts:c,data:g}=r,d="key",l=c===void 0?void 0:c+o;this.on.chunk&&this.on.chunk({kind:"audio",type:d,dts:o,pts:l,cts:c,data:g})}}break;case"video":{const{avcPacketType:h}=r;if(h===0){const{codec:c,sps:g,pps:d,data:l}=r;this.videoConfig={kind:"video",codec:c,description:l,sps:g,pps:d},this.on.config&&this.on.config(this.videoConfig)}else{const{frameType:c,cts:g,data:d,nalus:l}=r,p=c===1?"key":"delta",f=g===void 0?void 0:g+o;this.on.chunk&&this.on.chunk({kind:"video",type:p,dts:o,pts:f,cts:g,data:d,nalus:l})}}break}s=s+4+11+i}await new Promise(r=>setTimeout(()=>r(!0),8))}return s};parseHeader=(t,s)=>{let e,n,a,i;e=t.getUint8(s)<<16|t.getUint8(s+1)<<8|t.getUint8(s+2),n=t.getUint8(3);{const r=t.getUint8(0).toString(2).padStart(5,"0").split(""),[,,h,,c]=r;a={audio:c==="1",video:h==="1"}}i=t.getUint32(5),this.header={signature:e,version:n,flags:a,dataOffset:i}};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,i,o;{const r=t.getUint8(s);let h;switch(r){case 18:h="script";break;case 8:h="audio";break;case 9:h="video";break}e=h}return n=k(t,s+1),a=k(t,s+4),i=t.getUint8(s+7),o=k(t,s+8),{tagType:e,dataSize:n,timestamp:a,timestampExtended:i,streamID:o}};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 o=new Int8Array(t.buffer.slice(e,e+n));if((this.textDecoder?.decode(o)||"")!=="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),i=a>>4&15,o=a>>2&3,r=a>>1&1,h=a&1;n=n+1;const c=t.getUint8(n);n=n+1;const g=e-2,d=new Uint8Array(t.buffer.slice(n,n+g));if(i===10&&c===0){const l=t.getUint8(n),p=t.getUint8(n+1),f=(l&248)>>3,y=(l&7)<<1|p>>7,m=(p&120)>>3,U=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],b=`mp4a.40.${f}`,_=U[y];return{soundFormat:i,soundRate:o,soundSize:r,soundType:h,accPacketType:c,data:d,audioObjectType:f,samplingFrequencyIndex:y,channelConfiguration:m,codec:b,sampleRate:_}}return{soundFormat:i,soundRate:o,soundSize:r,soundType:h,accPacketType:c,data:d}};parseVideo=(t,s,e)=>{let n=s;const a=t.getUint8(n),i=a>>4&15,o=a&15;n=n+1;const r=t.getUint8(n);n=n+1;const h=k(t,n);n=n+3;const c=e-5,g=new Uint8Array(t.buffer.slice(n,n+c));switch(o){case 7:if(r===0){const d=T(g);return{frameType:i,codecID:o,avcPacketType:r,cts:h,data:g,...d}}else if(r===1){const d=[],l=n+e-5;for(;!(n+4>l);){const p=t.getUint32(n,!1),f=new Uint8Array(t.buffer.slice(n,n+p));n+=4+p,d.push(f)}return{frameType:i,codecID:o,avcPacketType:r,cts:h,data:g,nalus:d}}break;default:throw new Error("Unsupported codecID")}return{frameType:i,codecID:o,avcPacketType:r,cts:h,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,i=0;switch(e){case 0:a=t.getFloat64(n,!1),i=8;break;case 1:a=!!t.getUint8(n),i=1;break;case 2:{a="";const r=t.getUint16(n,!1);n=n+2;const h=new Int8Array(t.buffer,n,r).filter(g=>g!==0);a=(this.textDecoder?.decode(h)||"").trim(),i=2+r}break;case 3:for(a={};n<t.byteLength;){const r=t.getUint16(n,!1);if(r===0)break;n=n+2;const h=this.getAMFName(t,n,r);n=n+r;const c=this.getAmfType(t,n);if(c===6)break;n=n+1;const g=this.getAMFValue(t,n,c);n=n+g.length,a[h]=g.value,i=2+r+1+g.length}break;case 8:{a={};const r=t.getUint32(n,!1);n=n+4;for(let h=0;h<r;h++){const c=t.getUint16(n,!1);n=n+2;const g=this.getAMFName(t,n,c);n=n+c;const d=this.getAmfType(t,n);n=n+1;const l=this.getAMFValue(t,n,d);n=n+l.length,a[g]=l.value,i=2+c+1+l.length}}break;case 10:{a=[];const r=t.getUint32(n,!1);n=n+4;for(let h=0;h<r;h++){const c=this.getAmfType(t,n);n=n+1;const g=this.getAMFValue(t,n,c);n=n+g.length,a.push(g.value),i=1+g.length}}break}return{amfType:e,length:i,value:a}}}class S{pattern;cacher=new P;isParseing=!1;offset=0;on={};parser;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 S;A.on.debug=u=>postMessage({action:"onDebug",data:u}),A.on.info=u=>postMessage({action:"onInfo",data:u}),A.on.config=u=>postMessage({action:"onConfig",data:u}),A.on.chunk=u=>postMessage({action:"onChunk",data:u}),onmessage=u=>{const{action:t,data:s}=u.data,e=A[t];e&&e(s)}})();\n',x=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",_],{type:"text/javascript;charset=utf-8"});function N(u){let t;try{if(t=x&&(self.URL||self.webkitURL).createObjectURL(x),!t)throw"";const s=new Worker(t,{name:u?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(_),{name:u?.name})}}class A{worker=new N;on={};constructor(){this.worker.onmessage=t=>{const{action:s,data:e}=t.data;switch(s){case"onInfo":this.on.info&&this.on.info(e);break;case"onConfig":this.on.config&&this.on.config(e);break;case"onDebug":this.on.debug&&this.on.debug(e);break;case"onChunk":this.on.chunk&&this.on.chunk(e);break}}}init=t=>this.worker.postMessage({action:"init",data:t});push=t=>this.worker.postMessage({action:"push",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}const C=`(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=>{console.log("\\x1B[38;2;0;151;255m%c%s\\x1B[0m","color:#0097ff;","------->Breathe: e",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
|
+
`,D=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",C],{type:"text/javascript;charset=utf-8"});function E(u){let t;try{if(t=D&&(self.URL||self.webkitURL).createObjectURL(D),!t)throw"";const s=new Worker(t,{name:u?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(C),{name:u?.name})}}class M{worker=new E;on={audio:{},video:{}};constructor(){this.worker.onmessage=t=>{const{type:s,action:e,data:n}=t.data;switch(s){case"audio":e==="onDecode"&&this.on.audio.decode&&this.on.audio.decode(n),e==="onError"&&this.on.audio.error&&this.on.audio.error(n);break;case"video":e==="onDecode"&&this.on.video.decode&&this.on.video.decode(n),e==="onError"&&this.on.video.error&&this.on.video.error(n);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()}}var G=Object.defineProperty,W=(u,t,s)=>t in u?G(u,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):u[t]=s,f=(u,t,s)=>W(u,typeof t!="symbol"?t+"":t,s);class O{constructor(t,s){f(this,"inputStream",new MediaStream),f(this,"outputStream",new MediaStream),f(this,"inputGain",1),f(this,"enhanceGain",1),f(this,"bgsGain",1),f(this,"bgmGain",1),f(this,"outputGain",1),f(this,"mixAudioMap",new Map),f(this,"audioContext",new AudioContext),f(this,"sourceNode"),f(this,"inputGainNode"),f(this,"enhanceGainNode"),f(this,"bgsGainNode"),f(this,"bgmGainNode"),f(this,"analyserNode"),f(this,"analyserArrayData"),f(this,"outputGainNode"),f(this,"destinationNode"),f(this,"filterStream",e=>e),f(this,"stop",()=>{{const e=this.inputStream.getTracks();for(const n of e)n.stop(),this.inputStream.removeTrack(n)}}),f(this,"getStream",()=>this.filterStream(this.outputStream)),f(this,"setMute",(e=!0)=>{e?this.analyserNode.disconnect(this.outputGainNode):this.analyserNode.connect(this.outputGainNode)}),f(this,"setInputGain",e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),f(this,"setEnhanceGain",async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)}),f(this,"setBgsGain",e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),f(this,"setBgmGain",e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),f(this,"setOutputGain",e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)}),f(this,"getVolume",()=>{const{analyserNode:e,analyserArrayData:n}=this;e.getByteFrequencyData(n);let i=0;for(let o=0;o<n.length;o++)i+=n[o];return Math.ceil(i/n.length)}),f(this,"mixAudio",(e,n="bgm")=>new Promise(async(i,o)=>{try{{const d=this.mixAudioMap.get(n);d&&d.stop()}const a=n==="bgs"?this.bgsGainNode:this.bgmGainNode,r=this.audioContext.createBufferSource();this.mixAudioMap.set(n,r),r.buffer=e,r.connect(a),r.onended=()=>{r.disconnect(a),this.mixAudioMap.delete(n),i(!0)},r.start(0)}catch(a){o(a)}})),f(this,"mixAudioStop",e=>{const n=this.mixAudioMap.get(e);n?.stop()}),f(this,"changeMix",(e,n)=>{const i=e==="bgs"?this.bgsGainNode:this.bgmGainNode;n?i.connect(this.destinationNode):i.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:n,enhanceGainNode:i,bgsGainNode:o,bgmGainNode:a,analyserNode:r,outputGainNode:d,destinationNode:c}=this;e.connect(n),n.connect(i),i.connect(r),o.connect(r),a.connect(r),i.connect(c),o.connect(c),a.connect(c),r.connect(d),d.connect(this.audioContext.destination)}this.setMute(!0),this.audioContext.resume()}}const V=async(u,t)=>{try{const{format:s,numberOfChannels:e,numberOfFrames:n,sampleRate:i}=t,o=u.createBuffer(e,n,i);for(let a=0;a<e;a++){const r=t.allocationSize({planeIndex:a}),d=new Uint8Array(r);t.copyTo(d,{planeIndex:a});const c=new DataView(d.buffer),h=o.getChannelData(a);for(let p=0;p<n;p++){let l;switch(s){case"s16":case"s16-planar":l=c.getInt16(p*2,!0)/32768;break;case"f32":case"f32-planar":l=c.getFloat32(p*4,!0);break;case"u8":case"u8-planar":l=(c.getUint8(p)-128)/128;break;default:throw new Error(`Unsupported audio format: ${s}`)}h[p]=Math.max(-1,Math.min(1,l))}}return o}catch(s){throw console.error("Failed to convert AudioData to AudioBuffer:",s),s}};class z{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 O(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(t){try{if(!this.audioContext||!this.destination)return;const s=await V(this.audioContext,t);if(!s)return;const e=this.audioContext.createBufferSource();e.buffer=s,e.connect(this.destination);const n=Math.max(this.nextStartTime,this.audioContext.currentTime);this.nextStartTime=n+s.duration,e.start(n),this.pendingSources.push(e),e.onended=()=>{this.pendingSources=this.pendingSources.filter(i=>i!==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=[]}}const S=`(function(){"use strict";class r{isRendering=!1;pendingFrames=[];offscreenCanvas;writable;writer;ctx;cutOption;baseTime=0;pause=!1;shader=["stream"];constructor(){}init=({offscreenCanvas:e,writable:t})=>{this.destroy(),this.offscreenCanvas=e,this.writable=t,this.writer=this.writable.getWriter(),this.ctx=this.offscreenCanvas.getContext("2d")};setBaseTime=e=>{this.baseTime=e};setShader=e=>{this.shader=e};setSize=({width:e,height:t})=>{this.offscreenCanvas&&(this.offscreenCanvas.width=e,this.offscreenCanvas.height=t)};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)};setCut=e=>{this.cutOption=e};setPause=e=>{this.pause=e,this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=e=>{const t=performance.timeOrigin+performance.now(),i=this.baseTime+e/1e3-t;return Math.max(0,i)};renderFrame=async()=>{for(this.isRendering=!0;;){const e=this.pendingFrames.shift();if(!e)break;let{timestamp:t,bitmap:s}=e;if(this.cutOption){const{sx:a=0,sy:c=0,sw:m=s.width,sh:o=s.height}=this.cutOption;s=await createImageBitmap(s,a,c,m,o)}const i=this.calculateTimeUntilNextFrame(t);await new Promise(a=>setTimeout(()=>a(!0),i)),this.drawImage({timestamp:t,bitmap:s}),this.cutOption&&s.close()}this.isRendering=!1};drawImage=e=>{if(this.pause!==!0){if(this.shader.includes("stream")){const t=new VideoFrame(e.bitmap,{timestamp:e.timestamp});this.writer.write(t),t.close()}this.shader.includes("canvas")&&this.ctx&&this.offscreenCanvas&&this.ctx.drawImage(e.bitmap,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height)}}}const h=new r;onmessage=n=>{const{action:e,data:t}=n.data,s=h[e];s&&s(t)}})();
|
|
3
|
+
`,P=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",S],{type:"text/javascript;charset=utf-8"});function j(u){let t;try{if(t=P&&(self.URL||self.webkitURL).createObjectURL(P),!t)throw"";const s=new Worker(t,{name:u?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(S),{name:u?.name})}}class I{worker=new j;constructor(){}init=({offscreenCanvas:t,writable:s})=>this.worker.postMessage({action:"init",data:{offscreenCanvas:t,writable:s}},[t,s]);setShader=t=>this.worker.postMessage({action:"setShader",data:t});setBaseTime=t=>this.worker.postMessage({action:"setBaseTime",data:t});setSize=({width:t,height:s})=>this.worker.postMessage({action:"setSize",data:{width:t,height:s}});push=t=>this.worker.postMessage({action:"push",data:t});setCut=async t=>this.worker.postMessage({action:"setCut",data:t});setPause=t=>this.worker.postMessage({action:"setPause",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}const $=u=>{const t=u.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"},B=u=>{const t=u?.getTracks()||[];for(const s of t)s.stop()},R=()=>{const u=new I,t=document.createElement("canvas"),s=t.transferControlToOffscreen(),e=new MediaStreamTrackGenerator({kind:"video"}),n=new MediaStream([e]),i=()=>{u.destroy(),B(n)};return u.init({offscreenCanvas:s,writable:e.writable}),{worker:u,canvas:t,stream:n,destroy:i}};class H{resolvesMap=new Map;index=0;constructor(){}add=(t,s=()=>!1,e=0)=>new Promise(n=>{if(s())return n(!0);this.resolvesMap.has(t)||this.resolvesMap.set(t,new Map),this.index++;const a=`${this.index}`;if(e=Math.max(0,e),e===0){this.resolvesMap.get(t)?.set(a,{resolve:n,timer:0});return}const r=window.setTimeout(()=>{this.emit(t)},e);this.resolvesMap.get(t)?.set(a,{resolve:n,timer:r})});emit=async t=>{const s=this.resolvesMap.get(t);if(!s)return;const e=[...s.keys()];for(const n of e){const i=s.get(n);i&&(clearTimeout(i.timer),i.resolve(),s.delete(n))}}}const q=(u,t)=>{const s=new Uint8Array(u),e=new Uint8Array(t),n=new Uint8Array(11+s.length+e.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++]=e.length>>8&255,n[i++]=e.length&255,n.set(e,i),n},K=u=>{const t=new Uint8Array(4+u.length);return new DataView(t.buffer).setUint32(0,u.length,!1),t.set(u,4),t},X=u=>{let t=0;for(const n of u)t+=4+n.length;const s=new Uint8Array(t);let e=0;for(const n of u){const i=K(n);s.set(i,e),e+=i.length}return s},L=u=>{let t=0;const s=new DataView(u.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 i=s.getUint8(t)&255;t=t+1;const o=s.getUint8(t)&255;t=t+1;const d=`avc1.${Array.from([n,i,o],T=>T.toString(16).padStart(2,"0")).join("")}`,c=(s.getUint8(t)&3)-1;t=t+1;const h=s.getUint8(t)&31;t=t+1;const p=s.getUint16(t,!1);t=t+2;const l=new Uint8Array(s.buffer.slice(t,t+p));t=t+p;const g=s.getUint8(t)&31;t=t+1;const m=s.getUint16(t,!1);t=t+2;const y=new Uint8Array(s.buffer.slice(t,t+m));return t=t+m,{version:e,codec:d,profile:n,compatibility:i,level:o,lengthSizeMinusOne:c,numOfSequenceParameterSets:h,sequenceParameterSetLength:p,sps:l,numOfPictureParameterSets:g,pictureParameterSetLength:m,pps:y}},Y=u=>{const t=new DataView(u.buffer);let s=0,e,n,i;e=t.getUint32(s,!1),s=s+4;{const o=t.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=s+1}{const o=e-1;i=new Uint8Array(t.buffer.slice(s,s+o))}return{size:e,header:n,data:i}};class F{#e={timeout:5*1e3,check:!1};#t;constructor(t={}){this.#e={...this.#e,...t}}check=(t,s)=>new Promise(async(e,n)=>{this.stop(),this.#t=new AbortController;const i=window.setTimeout(()=>{this.#t?.abort("Timeout."),n({status:"timeout",reason:""})},this.#e.timeout);try{const o=await fetch(t,{...s,method:"HEAD",signal:this.#t?.signal});o.status===200?e({status:"successed",reason:""}):n({status:"failed",reason:`${o.status}`})}catch(o){n({status:"error",reason:o.message})}clearTimeout(i)});request=async(t,s)=>new Promise(async(e,n)=>{try{this.#e.check&&await this.check(t,s),this.#t=new AbortController;const i=await fetch(t,{...s,signal:this.#t?.signal});e(i)}catch(i){this.stop(),n(i)}});stop=()=>{this.#t?.signal.aborted===!1&&this.#t.abort("Actively stop.")}}class Q{prFetch=new F;prResolves=new H;url="";demuxerWorker;decoderWorker;audioPlayer;renderWorker;renderBaseTime;stream;canvas;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(){}init=()=>{this.initDecoder(),this.audioPlayer=new z,this.audioPlayer.init(),this.initRender()};start=async t=>{this.stop(),this.url=t,this.init();const s=$(t);if(s==="unknown")throw new Error("This address cannot be parsed.");switch(this.initDemuxer(s),s){case"flv":this.flv.start();break;case"hls":this.hls.start();break}};stop=async()=>{try{clearInterval(this.hls.getSegmentsTimer),this.prFetch.stop()}catch(s){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: error",s)}this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy(),B(this.stream);const t=[...this.cutRenders.keys()];for(const s of t)this.cut.remove(s);this.audioPlayer?.destroy(),this.renderBaseTime=void 0,this.canvas=void 0};getCanvas=()=>this.canvas;getStream=()=>this.stream;setPause=t=>{this.renderWorker?.setPause(t)};setShader=t=>{this.renderWorker?.setShader(t)};setMute=t=>this.audioPlayer?.prAudioStream?.setMute(t);isReady=()=>{const t=()=>this.stream?.active===!0;return this.prResolves.add("isReady",t)};cut={create:(t,s)=>{let e=this.cutRenders.get(t);return e?(e.worker.setCut(s),e.worker.setPause(!1),e):(e=R(),e.worker.setBaseTime(this.renderBaseTime||0),e.worker.setCut(s),this.cutRenders.set(t,e),e)},getCanvas:t=>this.cutRenders.get(t)?.canvas,getStream:t=>this.cutRenders.get(t)?.stream,setPause:(t,s)=>{this.cutRenders.get(t)?.worker.setPause(s)},setShader:(t,s)=>{this.cutRenders.get(t)?.worker.setShader(s)},remove:t=>{this.cutRenders.get(t)?.destroy(),this.cutRenders.delete(t)}};initDemuxer=t=>{this.demuxerWorker=new A,this.demuxerWorker.init(t),this.demuxerWorker.on.debug=s=>{},this.demuxerWorker.on.info=s=>{console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: info",s),this.on.demuxer.info&&this.on.demuxer.info(s)},this.demuxerWorker.on.config=s=>{console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: config",s),this.on.demuxer.config&&this.on.demuxer.config(s);const{kind:e}=s;switch(e){case"audio":{const{codec:n,sampleRate:i,numberOfChannels:o}=s;this.decoderWorker?.audio.init({codec:n,sampleRate:i,numberOfChannels:o})}break;case"video":{const{codec:n,description:i}=s;this.decoderWorker?.video.init({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:e}=s;switch(e){case"audio":{const{type:n,dts:i,data:o}=s,a=i*1;this.decoderWorker.audio.decode({type:n,timestamp:a,data:o})}break;case"video":{const{type:n,dts:i,data:o,nalus:a=[]}=s;if(this.renderBaseTime===void 0){const d=new Date().getTime();this.renderBaseTime=d-i,this.renderWorker?.setBaseTime(this.renderBaseTime)}const r=i*1e3;this.decoderWorker.video.decode({type:n,timestamp:r,data:o});for(const d of a){if(d.byteLength<=4)continue;const{header:c,data:h}=Y(d),{nal_unit_type:p}=c;p===6&&this.on.demuxer.sei&&this.on.demuxer.sei(h)}}break}}};initDecoder=()=>{this.decoderWorker=new M,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=async t=>{this.renderWorker?.push(t);const s=[...this.cutRenders.keys()];for(const e of s)this.cutRenders.get(e)?.worker.push(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=()=>{const{worker:t,canvas:s,stream:e}=R();this.renderWorker=t,this.canvas=s,this.stream=e,this.renderWorker.setPause(!1)};flv={start:async()=>{try{const s=(await this.prFetch.request(this.url)).body?.getReader();if(!s)throw new Error("reader is error.");for(;;){const{done:e,value:n}=await s.read();if(n&&this.demuxerWorker?.push(n),e)break}}catch(t){if(t?.name!=="AbortError")throw Error(t)}}};hls={isLive:!1,urls:[],url:"",getSegmentsTimer:0,parse:async t=>{const n=new TextDecoder("utf-8").decode(t).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()=>{const e=(await new F().request(this.url)).body?.getReader();if(!e)throw new Error("reader is error.");for(;;){const{done:n,value:i}=await e.read();if(i){const o=await this.hls.parse(i),{segments:a=[],isLive:r=!1}=o;this.hls.isLive=r;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)break}},getData:async()=>{},start:async()=>{try{for(await this.hls.getSegments(),this.hls.getSegmentsTimer=window.setInterval(this.hls.getSegments,1e3),this.hls.isLive===!1&&clearInterval(this.hls.getSegmentsTimer);;){const t=this.hls.urls.shift();if(t){this.hls.url=t;const e=(await this.prFetch.request(t)).body?.getReader();if(!e)throw new Error("segment reader is error.");for(;;){const{done:n,value:i}=await e.read();if(i&&this.demuxerWorker?.push(i),n)break}}await new Promise(s=>setTimeout(()=>s(!0),500))}}catch(t){if(t?.name!=="AbortError")throw Error(t)}}}}class J{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>1e3&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.chunks=[]}}const Z=u=>{let t="unknown";switch(u){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 tt{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: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=t.getUint8(e);e+=1,this.parseAdaptationField(t,e),e+=c,d-=c}if(r===3&&(d-=1),r===1||r===3){const c=new Uint8Array(t.buffer.slice(e,e+d));if(o===0)return this.parsePAT(t,e);{const{programs:l=[]}=this.pat||{};if(l.find(m=>m.pmt_pid===o))return this.parsePMT(t,e)}const{streams:h=[]}=this.pmt||{},p=h.find(l=>l.elementary_pid===o);if(p){if(a===1){const l=this.payloadMap.get(o);if(l){switch(p.kind){case"audio":break;case"video":{const g=await this.parseVideo(l);this.on.chunk&&this.on.chunk(g),await new Promise(m=>setTimeout(()=>m(!0),8))}break}this.payloadMap.delete(o)}}{this.payloadMap.has(o)||this.payloadMap.set(o,new Uint8Array);const l=this.payloadMap.get(o),g=new Uint8Array(l.byteLength+c.byteLength);g.set(l,0),g.set(c,l.byteLength),this.payloadMap.set(o,g)}}}};parseHeader=(t,s)=>{let e=s;const n=t.getUint8(e),i=t.getUint8(e+1),o=t.getUint8(e+2),a=t.getUint8(e+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,p=(a&192)>>6,l=a>>4&3,g=a&15;return{sync_byte:n,transport_error_indicator:r,payload_unit_start_indicator:d,transport_priority:c,pid:h,transport_scrambling_control:p,adaptation_field_control:l,continuity_counter:g}};parsePAT=(t,s)=>{let e=s,n;{const a=t.getUint8(e);e+=1;const r=t.getUint8(e);if(e+=1,r!==0)throw new Error("Invalid PAT table_id");const d=t.getUint16(e)&4095;e+=2;const c=t.getUint16(e);e+=2;const h=(t.getUint8(e)&62)>>1,p=t.getUint8(e)&1;e+=1;const l=t.getUint8(e);e+=1;const g=t.getUint8(e);e+=1,n={pointer_field:a,table_id:r,section_length:d,transport_stream_id:c,version_number:h,current_next_indicator:p,section_number:l,last_section_number:g}}const i=[];{const a=n.section_length-5-4,r=e+a;for(;e<r;){const d=t.getUint16(e),c=t.getUint16(e+2)&8191;e+=4,d!==0&&c>=32&&c<=8190&&i.push({program_number:d,pmt_pid:c})}}const o=t.getUint32(e);this.pat={header:n,programs:i,crc32:o},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(t,s)=>{let e=s,n;{const a=t.getUint8(e);e+=1;const r=t.getUint8(e);if(e+=1,r!==2)throw new Error("Invalid PMT table_id");const d=t.getUint16(e)&4095;e+=2;const c=t.getUint16(e);e+=2;const h=(t.getUint8(e)&62)>>1,p=t.getUint8(e)&1;e+=1;const l=t.getUint8(e);e+=1;const g=t.getUint8(e);e+=1;const m=t.getUint16(e)&8191;e+=2;const y=t.getUint16(e)&4095;e+=2,n={pointer_field:a,table_id:r,section_length:d,transport_stream_id:c,version_number:h,current_next_indicator:p,section_number:l,last_section_number:g,pcr_pid:m,program_info_length:y}}const i=[];{const a=n.section_length-9-4,r=e+a;for(;e<r;){const d=t.getUint8(e),c=Z(d),h=t.getUint16(e+1)&8191,p=t.getUint16(e+3)&4095;if(e+=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:p})}}const o=t.getUint32(e);this.pmt={header:n,streams:i,crc32:o},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(t,s)=>{let e=s,n,i,o,a;const r=t.getUint8(e),d=!!(r&128),c=!!(r&64),h=!!(r&32),p=!!(r&16),l=!!(r&8),g=!!(r&4),m=!!(r&2),y=!!(r&1);e+=1;const T=(k,U)=>{let w=BigInt(0);w|=BigInt(k.getUint16(U))<<25n,w|=BigInt(k.getUint16(U+1))<<17n,w|=BigInt(k.getUint16(U+2))<<9n,w|=BigInt(k.getUint16(U+3))<<1n,w|=BigInt(k.getUint16(U+4)>>7);const rt=(k.getUint16(U+4)&1)<<8|k.getUint16(U+5);return w=w*300n+BigInt(rt),w};if(p&&(n=T(t,e),e+=6),l&&(i=T(t,e),e+=6),g&&(o=t.getInt8(e),e+=1),m){const k=t.getUint8(e);e+=1,a=new Uint8Array(t.buffer,e,k),e+=k}return{discontinuity_indicator:d,random_access_indicator:c,elementary_stream_priority_indicator:h,pcr_flag:p,opcr_flag:l,splicing_point_flag:g,transport_private_data_flag:m,adaptation_field_extension_flag:y,pcr:n,opcr:i,splice_countdown:o,transport_private_data:a}};parseVideo=async t=>{const s=new DataView(t.buffer);let e=0,n,i;{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 a=s.getUint8(e);e+=1;const r=s.getUint8(e)<<8|s.getUint8(e+1);e+=2;let d,c;const h=a!==188&&a!==190&&a!==191&&a!==240&&a!==241&&a!==255&&a!==242;if(h){e+=1;const p=s.getUint8(e);e+=1;const l=p>>6,g=s.getUint8(e);e+=1,(l&2)===2&&(d=this.parsePtsDts(s,e),e+=5),(l&1)===1?(c=this.parsePtsDts(s,e),e+=5):c=d,e+=g-(e-9)}n={stream_id:a,pes_packet_length:r,pts:d,dts:c,optional_header_exist:h}}i=t.slice(e);{const o=this.getNalus(i);if(!this.videoConfig){let l,g;if(l=o.find(y=>y.type===7)?.data,g=o.find(y=>y.type===8)?.data,l&&g){const m=q(l,g),{codec:y}=L(m);this.videoConfig={kind:"video",codec:y,description:m,sps:l,pps:g},this.on.config&&this.on.config(this.videoConfig)}}const a=[];let r="delta";for(const l of o){const{type:g,data:m}=l;switch(g){case 9:break;case 1:r="delta",a.push(m);break;case 5:r="key",a.push(m);break}}const d=X(a),{dts:c=0,pts:h=0}=n,p=h-c;return{kind:"video",type:r,dts:c,pts:h,cts:p,data:d,nalus:a,nalusa:o}}};parsePtsDts(t,s){const e=t.getUint8(s),n=t.getUint8(s+1),i=t.getUint8(s+2),o=t.getUint8(s+3),a=t.getUint8(s+4),r=(BigInt(e)&0b00001110n)<<29n|(BigInt(n)&0b11111111n)<<22n|(BigInt(i)&0b11111110n)<<14n|(BigInt(o)&0b11111111n)<<7n|(BigInt(a)&0b11111110n)>>1n;return Number(r)/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 i=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 a=t.slice(n,n+o);s.push({type:i,data:a})}}return s}}const v=(u,t)=>u.getUint8(t)<<16|u.getUint8(t+1)<<8|u.getUint8(t+2);class et{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:i,dataSize:o,timestamp:a}=n;if(i){const r=this.parseTagBody(i,t,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:p}=r;this.audioConfig={kind:"audio",codec:c,sampleRate:h,numberOfChannels:p},this.on.config&&this.on.config(this.audioConfig)}else{const{cts:c,data:h}=r,p="key",l=c===void 0?void 0:c+a;this.on.chunk&&this.on.chunk({kind:"audio",type:p,dts:a,pts:l,cts:c,data:h})}}break;case"video":{const{avcPacketType:d}=r;if(d===0){const{codec:c,sps:h,pps:p,data:l}=r;this.videoConfig={kind:"video",codec:c,description:l,sps:h,pps:p},this.on.config&&this.on.config(this.videoConfig)}else{const{frameType:c,cts:h,data:p,nalus:l}=r,g=c===1?"key":"delta",m=h===void 0?void 0:h+a;this.on.chunk&&this.on.chunk({kind:"video",type:g,dts:a,pts:m,cts:h,data:p,nalus:l})}}break}s=s+4+11+o}await new Promise(r=>setTimeout(()=>r(!0),8))}return s};parseHeader=(t,s)=>{let e,n,i,o;e=t.getUint8(s)<<16|t.getUint8(s+1)<<8|t.getUint8(s+2),n=t.getUint8(3);{const r=t.getUint8(0).toString(2).padStart(5,"0").split(""),[,,d,,c]=r;i={audio:c==="1",video:d==="1"}}o=t.getUint32(5),this.header={signature:e,version:n,flags:i,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 i=v(t,s+4+1);s+4+11+i>n&&(e=!1)}return e};parseTagHeader=(t,s)=>{let e,n,i,o,a;{const r=t.getUint8(s);let d;switch(r){case 18:d="script";break;case 8:d="audio";break;case 9:d="video";break}e=d}return n=v(t,s+1),i=v(t,s+4),o=t.getUint8(s+7),a=v(t,s+8),{tagType:e,dataSize:n,timestamp:i,timestampExtended:o,streamID:a}};parseTagBody=(t,s,e,n)=>{let i;switch(t){case"script":i=this.parseMetaData(s,e);break;case"audio":i=this.parseAudio(s,e,n);break;case"video":i=this.parseVideo(s,e,n);break}return i};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 a=new Int8Array(t.buffer.slice(e,e+n));if((this.textDecoder?.decode(a)||"")!=="onMetaData")throw new Error("Expected 'onMetaData' string");e=e+n}const i=this.getAmfType(t,e);return e=e+1,this.getAMFValue(t,e,i).value};parseAudio=(t,s,e)=>{let n=s;const i=t.getUint8(n),o=i>>4&15,a=i>>2&3,r=i>>1&1,d=i&1;n=n+1;const c=t.getUint8(n);n=n+1;const h=e-2,p=new Uint8Array(t.buffer.slice(n,n+h));if(o===10&&c===0){const l=t.getUint8(n),g=t.getUint8(n+1),m=(l&248)>>3,y=(l&7)<<1|g>>7,T=(g&120)>>3,k=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],U=`mp4a.40.${m}`,w=k[y];return{soundFormat:o,soundRate:a,soundSize:r,soundType:d,accPacketType:c,data:p,audioObjectType:m,samplingFrequencyIndex:y,channelConfiguration:T,codec:U,sampleRate:w}}return{soundFormat:o,soundRate:a,soundSize:r,soundType:d,accPacketType:c,data:p}};parseVideo=(t,s,e)=>{let n=s;const i=t.getUint8(n),o=i>>4&15,a=i&15;n=n+1;const r=t.getUint8(n);n=n+1;const d=v(t,n);n=n+3;const c=e-5,h=new Uint8Array(t.buffer.slice(n,n+c));switch(a){case 7:if(r===0){const p=L(h);return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h,...p}}else if(r===1){const p=[],l=n+e-5;for(;!(n+4>l);){const g=t.getUint32(n,!1),m=new Uint8Array(t.buffer.slice(n,n+g));n+=4+g,p.push(m)}return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h,nalus:p}}break;default:throw new Error("Unsupported codecID")}return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h}};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,i,o=0;switch(e){case 0:i=t.getFloat64(n,!1),o=8;break;case 1:i=!!t.getUint8(n),o=1;break;case 2:{i="";const r=t.getUint16(n,!1);n=n+2;const d=new Int8Array(t.buffer,n,r).filter(h=>h!==0);i=(this.textDecoder?.decode(d)||"").trim(),o=2+r}break;case 3:for(i={};n<t.byteLength;){const r=t.getUint16(n,!1);if(r===0)break;n=n+2;const d=this.getAMFName(t,n,r);n=n+r;const c=this.getAmfType(t,n);if(c===6)break;n=n+1;const h=this.getAMFValue(t,n,c);n=n+h.length,i[d]=h.value,o=2+r+1+h.length}break;case 8:{i={};const r=t.getUint32(n,!1);n=n+4;for(let d=0;d<r;d++){const c=t.getUint16(n,!1);n=n+2;const h=this.getAMFName(t,n,c);n=n+c;const p=this.getAmfType(t,n);n=n+1;const l=this.getAMFValue(t,n,p);n=n+l.length,i[h]=l.value,o=2+c+1+l.length}}break;case 10:{i=[];const r=t.getUint32(n,!1);n=n+4;for(let d=0;d<r;d++){const c=this.getAmfType(t,n);n=n+1;const h=this.getAMFValue(t,n,c);n=n+h.length,i.push(h.value),o=1+h.length}}break}return{amfType:e,length:o,value:i}}}class st{pattern;cacher=new J;isParseing=!1;offset=0;on={};parser;constructor(){}init=t=>{switch(this.destroy(),this.pattern=t,this.pattern){case"flv":this.parser=new et;break;case"hls":this.parser=new tt;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()}}}class nt{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),n=s.timestamp;s.close(),e.width>0&&e.height>0?this.on.video.decode&&this.on.video.decode({timestamp:n,bitmap:e}):e.close()},error:s=>{console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: e",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 it{isRendering=!1;pendingFrames=[];offscreenCanvas;writable;writer;ctx;cutOption;baseTime=0;pause=!1;shader=["stream"];constructor(){}init=({offscreenCanvas:t,writable:s})=>{this.destroy(),this.offscreenCanvas=t,this.writable=s,this.writer=this.writable.getWriter(),this.ctx=this.offscreenCanvas.getContext("2d")};setBaseTime=t=>{this.baseTime=t};setShader=t=>{this.shader=t};setSize=({width:t,height:s})=>{this.offscreenCanvas&&(this.offscreenCanvas.width=t,this.offscreenCanvas.height=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)};setCut=t=>{this.cutOption=t};setPause=t=>{this.pause=t,this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=t=>{const s=performance.timeOrigin+performance.now(),n=this.baseTime+t/1e3-s;return Math.max(0,n)};renderFrame=async()=>{for(this.isRendering=!0;;){const t=this.pendingFrames.shift();if(!t)break;let{timestamp:s,bitmap:e}=t;if(this.cutOption){const{sx:i=0,sy:o=0,sw:a=e.width,sh:r=e.height}=this.cutOption;e=await createImageBitmap(e,i,o,a,r)}const n=this.calculateTimeUntilNextFrame(s);await new Promise(i=>setTimeout(()=>i(!0),n)),this.drawImage({timestamp:s,bitmap:e}),this.cutOption&&e.close()}this.isRendering=!1};drawImage=t=>{if(this.pause!==!0){if(this.shader.includes("stream")){const s=new VideoFrame(t.bitmap,{timestamp:t.timestamp});this.writer.write(s),s.close()}this.shader.includes("canvas")&&this.ctx&&this.offscreenCanvas&&this.ctx.drawImage(t.bitmap,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height)}}}b.Decoder=nt,b.DecoderWorker=M,b.Demuxer=st,b.DemuxerWorker=A,b.PrPlayer=Q,b.Render=it,b.RenderWorker=I,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})}));
|
package/dist/render/Render.d.ts
CHANGED
|
@@ -11,11 +11,14 @@ export declare class Render {
|
|
|
11
11
|
private pause;
|
|
12
12
|
private shader;
|
|
13
13
|
constructor();
|
|
14
|
-
init: ({ offscreenCanvas,
|
|
14
|
+
init: ({ offscreenCanvas, writable }: {
|
|
15
15
|
offscreenCanvas: OffscreenCanvas;
|
|
16
|
-
baseTime?: number;
|
|
17
16
|
writable: any;
|
|
18
17
|
}) => void;
|
|
18
|
+
/**
|
|
19
|
+
* 设置渲染基准时间
|
|
20
|
+
*/
|
|
21
|
+
setBaseTime: (baseTime: number) => void;
|
|
19
22
|
/**
|
|
20
23
|
* 设置渲染模式
|
|
21
24
|
*/
|
|
@@ -2,12 +2,12 @@ import { CutOption, Shader } from './type';
|
|
|
2
2
|
export declare class RenderWorker {
|
|
3
3
|
worker: Worker;
|
|
4
4
|
constructor();
|
|
5
|
-
init: ({ offscreenCanvas,
|
|
5
|
+
init: ({ offscreenCanvas, writable }: {
|
|
6
6
|
offscreenCanvas: OffscreenCanvas;
|
|
7
|
-
baseTime?: number;
|
|
8
7
|
writable: any;
|
|
9
8
|
}) => void;
|
|
10
9
|
setShader: (shader: Shader[]) => void;
|
|
10
|
+
setBaseTime: (baseTime: number) => void;
|
|
11
11
|
setSize: ({ width, height }: {
|
|
12
12
|
width: number;
|
|
13
13
|
height: number;
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { RenderWorker } from './render/RenderWorker';
|
|
2
|
+
export declare const getFormatFromUrlPattern: (url: string) => "unknown" | "hls" | "dash" | "rtmp" | "flv";
|
|
3
|
+
export declare const stopStream: (stream: MediaStream | undefined) => void;
|
|
4
|
+
export declare const createRender: () => {
|
|
5
|
+
worker: RenderWorker;
|
|
6
|
+
canvas: HTMLCanvasElement;
|
|
7
|
+
stream: MediaStream;
|
|
8
|
+
destroy: () => void;
|
|
9
|
+
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pr-player",
|
|
3
3
|
"description": "对 flv 格式的地址进行解析 并输出 canvas、stream,提供 SEI 回调,以及 cut 等相关能力,以支持根据业务层 SEI 对视频进行剪切渲染。",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.1",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
7
7
|
"dist"
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
"build": "tsc && vite build"
|
|
20
20
|
},
|
|
21
21
|
"dependencies": {
|
|
22
|
+
"demuxer": "^2.3.0",
|
|
22
23
|
"pr-audio-stream": "^0.1.3",
|
|
23
24
|
"pr-fetch": "^0.0.1"
|
|
24
25
|
},
|