pr-player 0.0.1 → 0.0.2

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.
@@ -13,8 +13,9 @@ interface On {
13
13
  bitmap: ImageBitmap;
14
14
  }) => void;
15
15
  };
16
- stream?: (_stream: MediaStream) => void;
17
- cutStream?: (_key: string, _stream: MediaStream) => void;
16
+ video?: (canvas: HTMLCanvasElement) => void;
17
+ cut?: (key: string, canvas: HTMLCanvasElement) => void;
18
+ error?: (_e: any) => void;
18
19
  }
19
20
  export declare class PrPlayer {
20
21
  private prFetch;
@@ -27,20 +28,10 @@ export declare class PrPlayer {
27
28
  private canvas;
28
29
  on: On;
29
30
  constructor();
30
- /**
31
- * 创建剪切
32
- */
33
- createCut: (key: string, cutOption: {
34
- sx?: number;
35
- sy?: number;
36
- sw?: number;
37
- sh?: number;
38
- }, canvas?: HTMLCanvasElement, fps?: number) => HTMLCanvasElement;
39
31
  /**
40
32
  * 初始化
41
- * @param canvas?: HTMLCanvasElement
42
33
  */
43
- init: (canvas?: HTMLCanvasElement) => void;
34
+ init: () => void;
44
35
  /**
45
36
  * 开始播放
46
37
  * @param url : string
@@ -50,11 +41,6 @@ export declare class PrPlayer {
50
41
  * 停止
51
42
  */
52
43
  stop: () => void;
53
- /**
54
- * 是否静音 默认为true
55
- * @param state?: boolean
56
- */
57
- setMute: (state?: boolean) => void | undefined;
58
44
  /**
59
45
  * 监听媒体 tag
60
46
  */
@@ -63,9 +49,31 @@ export declare class PrPlayer {
63
49
  * 初始化分离器
64
50
  */
65
51
  private initDemuxer;
52
+ /**
53
+ * 初始化解码器
54
+ */
55
+ private initDecoder;
66
56
  /**
67
57
  * 初始化渲染器
68
58
  */
69
59
  private initRender;
60
+ audio: {
61
+ /**
62
+ * 是否静音 默认为true
63
+ * @param state?: boolean
64
+ */
65
+ setMute: (state?: boolean) => void | undefined;
66
+ };
67
+ video: {
68
+ /**
69
+ * 创建剪切
70
+ */
71
+ createCut: (key: string, cutOption: {
72
+ sx?: number;
73
+ sy?: number;
74
+ sw?: number;
75
+ sh?: number;
76
+ }) => void;
77
+ };
70
78
  }
71
79
  export {};
@@ -15,4 +15,5 @@ export declare class DecoderWorker {
15
15
  flush: () => void;
16
16
  destroy: () => void;
17
17
  };
18
+ destroy: () => void;
18
19
  }
@@ -1,6 +1,6 @@
1
1
  export interface On {
2
2
  audio: {
3
- decode?: (_AudioData: AudioData) => void;
3
+ decode?: (_audioData: AudioData) => void;
4
4
  error?: (_e: DOMException) => void;
5
5
  };
6
6
  video: {
@@ -1,8 +1,7 @@
1
1
  import { On } from './type';
2
2
  export declare class Demuxer {
3
3
  private parseSpeed;
4
- private parseTimer;
5
- private pushFuncs;
4
+ private pendingPayloads;
6
5
  private payload;
7
6
  private offset;
8
7
  private is_parsing;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- const L = '(function(){"use strict";const U=new TextDecoder("utf-8"),I=(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}},T=(e,s)=>e.getUint8(s),F=(e,s,a)=>{const t=new Uint8Array(e.buffer.slice(s,s+a));return U?.decode(t)||""},b=(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(u=>u!==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=F(e,t,o);t=t+o;const g=T(e,t);if(g===6)break;t=t+1;const u=b(e,t,g);t=t+u.length,n[c]=u.value,r=2+o+1+u.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 u=F(e,t,g);t=t+g;const l=T(e,t);t=t+1;const h=b(e,t,l);t=t+h.length,n[u]=h.value,r=2+g+1+h.length}}break;case 10:{n=[];const o=e.getUint32(t,!1);t=t+4;for(let c=0;c<o;c++){const g=T(e,t);t=t+1;const u=b(e,t,g);t=t+u.length,n.push(u.value),r=1+u.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 d={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 u=a-2,l=new Uint8Array(e.buffer.slice(t,t+u));if(r===10&&g===0){const h=e.getUint8(t),p=e.getUint8(t+1),f=(h&248)>>3,y=(h&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:l,audioObjectType:f,samplingFrequencyIndex:y,channelConfiguration:S,codec:D,sampleRate:z}}return{soundFormat:r,soundRate:i,soundSize:o,soundType:c,accPacketType:g,data:l}},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,u=new Uint8Array(e.buffer.slice(t,t+g));switch(i){case 7:if(o===0){const l=e.getUint8(t);if(t=t+1,l!==1)throw new Error("Invalid AVC version");const h=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([h,p,f],P=>P.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 L=new Uint8Array(e.buffer.slice(t,t+_));t=t+_;const O=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:u,version:l,codec:A,profile:h,compatibility:p,level:f,lengthSizeMinusOne:D,numOfSequenceParameterSets:z,sequenceParameterSetLength:_,sps:L,numOfPictureParameterSets:O,pictureParameterSetLength:x,pps:M}}else if(o===1){const l=[],h=t+a-5;for(;t+4<h;){const p=e.getUint32(t,!1);t=t+4;const f=I(e,t);t=t+1;const y=p-1,S=new Uint8Array(e.buffer.slice(t,t+y));t=t+y,l.push({size:p,header:f,payload:S})}return{frameType:r,codecID:i,avcPacketType:o,cts:c,data:u,nalus:l}}break;default:throw new Error("Unsupported codecID")}return{frameType:r,codecID:i,avcPacketType:o,cts:c,data:u}},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=T(e,a);return a=a+1,b(e,a,n).value}}}};class H{parseSpeed=8;parseTimer=0;pushFuncs=[];payload=new Uint8Array(0);offset=0;is_parsing=!1;header;tag;on={};constructor(){}init=()=>{this.destroy(),this.parseTimer=setInterval(this.parse,this.parseSpeed)};push=s=>{const a=()=>{const t=new Uint8Array(this.payload.byteLength+s.byteLength);t.set(this.payload,0),t.set(s,this.payload.byteLength),this.payload=t};this.pushFuncs.push(a)};destroy=()=>{clearInterval(this.parseTimer),this.pushFuncs=[],this.payload=new Uint8Array(0),this.offset=0,this.is_parsing=!1,this.header=void 0,this.tag=void 0};parse=async()=>{if(this.pushFuncs.length===0||this.is_parsing===!0)return;this.is_parsing=!0;{const a=this.pushFuncs.shift();a&&a()}const s=new DataView(this.payload.buffer);this.header||this.parseHeader(s),await this.parseTag(s),this.is_parsing=!1};parseHeader=s=>(this.header={signature:d.header.getSignature(s),version:d.header.getVersion(s),flags:d.header.getFlags(s),dataOffset:d.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:d.tag.tagHeader.getTagType(n,r),dataSize:d.tag.tagHeader.getDataSize(n,r),timestamp:d.tag.tagHeader.getTimestamp(n,r),timestampExtended:d.tag.tagHeader.getTimestampExtended(n,r),streamID:d.tag.tagHeader.getStreamID(n,r)}),t=(n,r,i,o)=>{let c;switch(n){case"script":c=d.tag.tagBody.parseMetaData(r,i);break;case"audio":c=d.tag.tagBody.parseAudio(r,i,o);break;case"video":c=d.tag.tagBody.parseVideo(r,i,o);break}return c};for(;this.offset<s.byteLength;){if(d.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 H;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', A = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", L], { type: "text/javascript;charset=utf-8" });
2
- function V(i) {
1
+ const L = '(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', A = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", L], { type: "text/javascript;charset=utf-8" });
2
+ function E(i) {
3
3
  let t;
4
4
  try {
5
5
  if (t = A && (self.URL || self.webkitURL).createObjectURL(A), !t) throw "";
@@ -18,8 +18,8 @@ function V(i) {
18
18
  );
19
19
  }
20
20
  }
21
- class E {
22
- worker = new V();
21
+ class z {
22
+ worker = new E();
23
23
  on = {};
24
24
  constructor() {
25
25
  this.worker.onmessage = (t) => {
@@ -29,11 +29,13 @@ class E {
29
29
  }
30
30
  init = () => this.worker.postMessage({ action: "init" });
31
31
  push = (t) => this.worker.postMessage({ action: "push", data: t });
32
- destroy = () => this.worker.postMessage({ action: "destroy" });
32
+ destroy = () => {
33
+ this.worker.postMessage({ action: "destroy", data: {} }), this.worker.terminate();
34
+ };
33
35
  }
34
- const P = `(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)}})();
35
- `, M = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", P], { type: "text/javascript;charset=utf-8" });
36
- function z(i) {
36
+ const N = `(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)}})();
37
+ `, M = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", N], { type: "text/javascript;charset=utf-8" });
38
+ function V(i) {
37
39
  let t;
38
40
  try {
39
41
  if (t = M && (self.URL || self.webkitURL).createObjectURL(M), !t) throw "";
@@ -45,7 +47,7 @@ function z(i) {
45
47
  }), s;
46
48
  } catch {
47
49
  return new Worker(
48
- "data:text/javascript;charset=utf-8," + encodeURIComponent(P),
50
+ "data:text/javascript;charset=utf-8," + encodeURIComponent(N),
49
51
  {
50
52
  name: i?.name
51
53
  }
@@ -53,7 +55,7 @@ function z(i) {
53
55
  }
54
56
  }
55
57
  class _ {
56
- worker = new z();
58
+ worker = new V();
57
59
  on = { audio: {}, video: {} };
58
60
  constructor() {
59
61
  this.worker.onmessage = (t) => {
@@ -72,21 +74,28 @@ class _ {
72
74
  init: (t) => this.worker.postMessage({ type: "audio", action: "init", data: t }),
73
75
  decode: (t) => this.worker.postMessage({ type: "audio", action: "decode", data: t }),
74
76
  flush: () => this.worker.postMessage({ type: "audio", action: "flush" }),
75
- destroy: () => this.worker.postMessage({ type: "audio", action: "destroy" })
77
+ destroy: () => {
78
+ this.worker.postMessage({ type: "audio", action: "destroy" });
79
+ }
76
80
  };
77
81
  video = {
78
82
  init: (t) => this.worker.postMessage({ type: "video", action: "init", data: t }),
79
83
  decode: (t) => this.worker.postMessage({ type: "video", action: "decode", data: t }),
80
84
  flush: () => this.worker.postMessage({ type: "video", action: "flush" }),
81
- destroy: () => this.worker.postMessage({ type: "video", action: "destroy" })
85
+ destroy: () => {
86
+ this.worker.postMessage({ type: "video", action: "destroy", data: {} });
87
+ }
88
+ };
89
+ destroy = () => {
90
+ this.worker.postMessage({ type: "audio", action: "destroy" }), this.worker.postMessage({ type: "video", action: "destroy", data: {} }), this.worker.terminate();
82
91
  };
83
92
  }
84
- const N = `(function(){"use strict";class a{isRendering=!1;pendingFrames=[];offscreenCanvas;ctx;baseTime=0;cutOption;constructor(){}setCut=async e=>{this.cutOption={...this.cutOption,...e}};init=({offscreenCanvas:e,baseTime:s=0})=>{this.destroy(),this.offscreenCanvas=e,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,this.cutOption=void 0};push=e=>{this.pendingFrames.push(e),this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=e=>{this.baseTime==0&&(this.baseTime=performance.now());let s=performance.now()-this.baseTime;return Math.max(0,e/1e3-s)};renderFrame=async()=>{const e=this.pendingFrames.shift();if(this.isRendering=!!e,!e){this.isRendering=!1;return}this.isRendering=!0;let{timestamp:s,bitmap:t}=e;if(this.cutOption){const{sx:i=0,sy:c=0,sw:h=t.width,sh:m=t.height}=this.cutOption,f=await createImageBitmap(t,i,c,h,m);t.close(),t=f}const o=this.calculateTimeUntilNextFrame(s);await new Promise(i=>setTimeout(i,o)),this.ctx&&this.offscreenCanvas&&this.ctx.drawImage(t,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),t.close(),setTimeout(this.renderFrame,0)}}const r=new a;onmessage=n=>{const{action:e,data:s}=n.data,t=r[e];t&&t(s)}})();
85
- `, F = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", N], { type: "text/javascript;charset=utf-8" });
93
+ const F = `(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)}})();
94
+ `, P = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", F], { type: "text/javascript;charset=utf-8" });
86
95
  function j(i) {
87
96
  let t;
88
97
  try {
89
- if (t = F && (self.URL || self.webkitURL).createObjectURL(F), !t) throw "";
98
+ if (t = P && (self.URL || self.webkitURL).createObjectURL(P), !t) throw "";
90
99
  const s = new Worker(t, {
91
100
  name: i?.name
92
101
  });
@@ -95,21 +104,23 @@ function j(i) {
95
104
  }), s;
96
105
  } catch {
97
106
  return new Worker(
98
- "data:text/javascript;charset=utf-8," + encodeURIComponent(N),
107
+ "data:text/javascript;charset=utf-8," + encodeURIComponent(F),
99
108
  {
100
109
  name: i?.name
101
110
  }
102
111
  );
103
112
  }
104
113
  }
105
- class G {
114
+ class R {
106
115
  worker = new j();
107
116
  constructor() {
108
117
  }
109
118
  setCut = async (t) => this.worker.postMessage({ action: "setCut", data: t });
110
119
  init = ({ offscreenCanvas: t, baseTime: s = 0 }) => this.worker.postMessage({ action: "init", data: { offscreenCanvas: t, baseTime: s } }, [t]);
111
- destroy = () => this.worker.postMessage({ action: "destroy", data: {} });
112
120
  push = (t) => this.worker.postMessage({ action: "push", data: t });
121
+ destroy = () => {
122
+ this.worker.postMessage({ action: "destroy", data: {} }), this.worker.terminate();
123
+ };
113
124
  }
114
125
  var H = Object.defineProperty, $ = (i, t, s) => t in i ? H(i, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : i[t] = s, u = (i, t, s) => $(i, typeof t != "symbol" ? t + "" : t, s);
115
126
  class q {
@@ -136,21 +147,21 @@ class q {
136
147
  const { analyserNode: e, analyserArrayData: o } = this;
137
148
  e.getByteFrequencyData(o);
138
149
  let a = 0;
139
- for (let c = 0; c < o.length; c++)
140
- a += o[c];
150
+ for (let n = 0; n < o.length; n++)
151
+ a += o[n];
141
152
  return Math.ceil(a / o.length);
142
- }), u(this, "mixAudio", (e, o = "bgm") => new Promise(async (a, c) => {
153
+ }), u(this, "mixAudio", (e, o = "bgm") => new Promise(async (a, n) => {
143
154
  try {
144
155
  {
145
- const d = this.mixAudioMap.get(o);
146
- d && d.stop();
156
+ const h = this.mixAudioMap.get(o);
157
+ h && h.stop();
147
158
  }
148
- const n = o === "bgs" ? this.bgsGainNode : this.bgmGainNode, r = this.audioContext.createBufferSource();
149
- this.mixAudioMap.set(o, r), r.buffer = e, r.connect(n), r.onended = () => {
150
- r.disconnect(n), this.mixAudioMap.delete(o), a(!0);
151
- }, r.start(0);
152
- } catch (n) {
153
- c(n);
159
+ const r = o === "bgs" ? this.bgsGainNode : this.bgmGainNode, d = this.audioContext.createBufferSource();
160
+ this.mixAudioMap.set(o, d), d.buffer = e, d.connect(r), d.onended = () => {
161
+ d.disconnect(r), this.mixAudioMap.delete(o), a(!0);
162
+ }, d.start(0);
163
+ } catch (r) {
164
+ n(r);
154
165
  }
155
166
  })), u(this, "mixAudioStop", (e) => {
156
167
  const o = this.mixAudioMap.get(e);
@@ -160,36 +171,36 @@ class q {
160
171
  o ? a.connect(this.destinationNode) : a.disconnect(this.destinationNode);
161
172
  }), 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;
162
173
  {
163
- const { sourceNode: e, inputGainNode: o, enhanceGainNode: a, bgsGainNode: c, bgmGainNode: n, analyserNode: r, outputGainNode: d, destinationNode: h } = this;
164
- e.connect(o), o.connect(a), a.connect(r), c.connect(r), n.connect(r), a.connect(h), c.connect(h), n.connect(h), r.connect(d), d.connect(this.audioContext.destination);
174
+ const { sourceNode: e, inputGainNode: o, enhanceGainNode: a, bgsGainNode: n, bgmGainNode: r, analyserNode: d, outputGainNode: h, destinationNode: c } = this;
175
+ 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);
165
176
  }
166
177
  this.setMute(!0), this.audioContext.resume();
167
178
  }
168
179
  }
169
180
  const K = async (i, t) => {
170
181
  try {
171
- const { format: s, numberOfChannels: e, numberOfFrames: o, sampleRate: a } = t, c = i.createBuffer(e, o, a);
172
- for (let n = 0; n < e; n++) {
173
- const r = t.allocationSize({ planeIndex: n }), d = new Uint8Array(r);
174
- t.copyTo(d, { planeIndex: n });
175
- const h = new DataView(d.buffer), f = c.getChannelData(n);
182
+ const { format: s, numberOfChannels: e, numberOfFrames: o, sampleRate: a } = t, n = i.createBuffer(e, o, a);
183
+ for (let r = 0; r < e; r++) {
184
+ const d = t.allocationSize({ planeIndex: r }), h = new Uint8Array(d);
185
+ t.copyTo(h, { planeIndex: r });
186
+ const c = new DataView(h.buffer), f = n.getChannelData(r);
176
187
  for (let g = 0; g < o; g++) {
177
188
  let l;
178
189
  switch (s) {
179
190
  case "s16":
180
191
  // 16-bit signed PCM (范围: -32768 ~ 32767)
181
192
  case "s16-planar":
182
- l = h.getInt16(g * 2, !0) / 32768;
193
+ l = c.getInt16(g * 2, !0) / 32768;
183
194
  break;
184
195
  case "f32":
185
196
  // 32-bit float (范围: -1.0 ~ 1.0)
186
197
  case "f32-planar":
187
- l = h.getFloat32(g * 4, !0);
198
+ l = c.getFloat32(g * 4, !0);
188
199
  break;
189
200
  case "u8":
190
201
  // 8-bit unsigned (范围: 0 ~ 255)
191
202
  case "u8-planar":
192
- l = (h.getUint8(g) - 128) / 128;
203
+ l = (c.getUint8(g) - 128) / 128;
193
204
  break;
194
205
  default:
195
206
  throw new Error(`Unsupported audio format: ${s}`);
@@ -197,7 +208,7 @@ const K = async (i, t) => {
197
208
  f[g] = Math.max(-1, Math.min(1, l));
198
209
  }
199
210
  }
200
- return c;
211
+ return n;
201
212
  } catch (s) {
202
213
  throw console.error("Failed to convert AudioData to AudioBuffer:", s), s;
203
214
  }
@@ -253,10 +264,10 @@ class J {
253
264
  this.#e?.abort("Timeout."), o({ status: "timeout", reason: "" });
254
265
  }, this.#t.timeout);
255
266
  try {
256
- const c = await fetch(t, { ...s, method: "HEAD", signal: this.#e?.signal });
257
- c.status === 200 ? e({ status: "successed", reason: "" }) : o({ status: "failed", reason: `${c.status}` });
258
- } catch (c) {
259
- o({ status: "error", reason: c.message });
267
+ const n = await fetch(t, { ...s, method: "HEAD", signal: this.#e?.signal });
268
+ n.status === 200 ? e({ status: "successed", reason: "" }) : o({ status: "failed", reason: `${n.status}` });
269
+ } catch (n) {
270
+ o({ status: "error", reason: n.message });
260
271
  }
261
272
  clearTimeout(a);
262
273
  });
@@ -281,51 +292,36 @@ class J {
281
292
  this.#e?.signal.aborted === !1 && this.#e.abort("Actively stop.");
282
293
  };
283
294
  }
284
- class me {
295
+ const X = async (i, t) => {
296
+ const s = [...i.keys()], { timestamp: e, bitmap: o } = t;
297
+ for (const a of s) {
298
+ const n = i.get(a);
299
+ if (!n) continue;
300
+ 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);
301
+ d.push({ timestamp: e, bitmap: l });
302
+ }
303
+ }, Y = (i) => {
304
+ const t = [...i.keys()];
305
+ for (const s of t)
306
+ i.get(s)?.worker.destroy(), i.delete(s);
307
+ };
308
+ class be {
285
309
  prFetch = new J();
286
- demuxerWorker = new E();
287
- decoderWorker = new _();
288
- audioPlayer = new Q();
289
- videoPlayerWorker = new G();
310
+ demuxerWorker;
311
+ decoderWorker;
312
+ audioPlayer;
313
+ videoPlayerWorker;
290
314
  renderBaseTime = 0;
291
315
  cutVideoPlayerWorkers = /* @__PURE__ */ new Map();
292
316
  canvas;
293
317
  on = { demuxer: {}, decoder: {} };
294
318
  constructor() {
295
- this.decoderWorker.on.audio.decode = (t) => {
296
- this.audioPlayer.push(t), this.on.decoder.audio && this.on.decoder.audio(t);
297
- }, this.decoderWorker.on.audio.error = (t) => {
298
- console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m", "color:#0097ff;", "------->decoderWorker.audio.onError: e", t), this.stop();
299
- }, this.decoderWorker.on.video.decode = (t) => {
300
- this.videoPlayerWorker.push(t);
301
- const s = [...this.cutVideoPlayerWorkers.keys()];
302
- for (const e of s)
303
- this.cutVideoPlayerWorkers.get(e).push(t);
304
- this.on.decoder.video && this.on.decoder.video(t);
305
- }, this.decoderWorker.on.video.error = (t) => {
306
- console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m", "color:#0097ff;", "------->decoderWorker.video.onError: e", t), this.stop();
307
- };
308
319
  }
309
- /**
310
- * 创建剪切
311
- */
312
- createCut = (t, s, e, o = 25) => {
313
- e || (e = document.createElement("canvas")), this.cutVideoPlayerWorkers.has(t) && this.cutVideoPlayerWorkers.get(t).destroy();
314
- const { sw: a, sh: c } = s;
315
- e.width = a || e.width, e.height = c || e.height;
316
- const n = new G(), r = e.transferControlToOffscreen();
317
- if (n.init({ offscreenCanvas: r, baseTime: this.renderBaseTime }), n.setCut(s), this.cutVideoPlayerWorkers.set(t, n), this.on.cutStream) {
318
- const d = e.captureStream(o);
319
- this.on.cutStream(t, d);
320
- }
321
- return e;
322
- };
323
320
  /**
324
321
  * 初始化
325
- * @param canvas?: HTMLCanvasElement
326
322
  */
327
- init = (t) => {
328
- this.stop(), this.initDemuxer(), t || (t = document.createElement("canvas")), this.canvas = t, this.audioPlayer.init();
323
+ init = () => {
324
+ this.stop(), this.initDemuxer(), this.initDecoder(), this.renderBaseTime = (/* @__PURE__ */ new Date()).getTime(), this.audioPlayer = new Q(), this.audioPlayer.init();
329
325
  };
330
326
  /**
331
327
  * 开始播放
@@ -337,7 +333,7 @@ class me {
337
333
  if (!e) throw new Error("Reader is error.");
338
334
  for (; ; ) {
339
335
  const { done: o, value: a } = await e.read();
340
- if (a && this.demuxerWorker.push(a), o)
336
+ if (a && this.demuxerWorker?.push(a), o)
341
337
  break;
342
338
  }
343
339
  } catch {
@@ -347,49 +343,41 @@ class me {
347
343
  * 停止
348
344
  */
349
345
  stop = () => {
350
- this.prFetch.stop(), this.demuxerWorker.destroy(), this.decoderWorker.audio.destroy(), this.decoderWorker.video.destroy(), this.videoPlayerWorker.destroy();
351
- const t = [...this.cutVideoPlayerWorkers.keys()];
352
- for (const s of t)
353
- this.cutVideoPlayerWorkers.get(s).destroy(), this.cutVideoPlayerWorkers.delete(s);
354
- this.audioPlayer.destroy(), this.renderBaseTime = 0, this.canvas = void 0;
346
+ this.prFetch.stop(), this.demuxerWorker?.destroy(), this.decoderWorker?.destroy(), this.videoPlayerWorker?.destroy(), Y(this.cutVideoPlayerWorkers), this.audioPlayer?.destroy(), this.renderBaseTime = 0, this.canvas = void 0;
355
347
  };
356
- /**
357
- * 是否静音 默认为true
358
- * @param state?: boolean
359
- */
360
- setMute = (t) => this.audioPlayer.prAudioStream?.setMute(t);
361
348
  /**
362
349
  * 监听媒体 tag
363
350
  */
364
351
  onTag = (t) => {
352
+ if (!this.decoderWorker) return;
365
353
  const { header: s, body: e } = t, { tagType: o, timestamp: a } = s;
366
354
  switch (o) {
367
355
  case "script":
368
356
  {
369
- const { width: c, height: n } = e;
370
- this.initRender({ width: c, height: n }), this.on.demuxer.script && this.on.demuxer.script(t);
357
+ const { width: n, height: r } = e;
358
+ this.initRender({ width: n, height: r }), this.on.demuxer.script && this.on.demuxer.script(t);
371
359
  }
372
360
  break;
373
361
  case "audio":
374
362
  {
375
- const { accPacketType: c, data: n } = e;
376
- if (c === 0) {
377
- const { codec: r, sampleRate: d, channelConfiguration: h } = e, f = { codec: r, sampleRate: d, numberOfChannels: h, description: new Uint8Array([]) };
363
+ const { accPacketType: n, data: r } = e;
364
+ if (n === 0) {
365
+ const { codec: d, sampleRate: h, channelConfiguration: c } = e, f = { codec: d, sampleRate: h, numberOfChannels: c, description: new Uint8Array([]) };
378
366
  this.decoderWorker.audio.init(f);
379
- } else c === 1 && this.decoderWorker.audio.decode({ type: "key", timestamp: a * 1, data: n });
367
+ } else n === 1 && this.decoderWorker.audio.decode({ type: "key", timestamp: a * 1, data: r });
380
368
  this.on.demuxer.audio && this.on.demuxer.audio(t);
381
369
  }
382
370
  break;
383
371
  case "video":
384
372
  {
385
- const { avcPacketType: c, frameType: n, data: r, nalus: d = [] } = e;
386
- if (c === 0) {
387
- const { codec: h, data: f } = e;
388
- this.decoderWorker.video.init({ codec: h, description: f });
389
- } else if (c === 1) {
390
- const h = n === 1 ? "key" : "delta";
391
- this.decoderWorker.video.decode({ type: h, timestamp: a * 1e3, data: r });
392
- for (const f of d) {
373
+ const { avcPacketType: n, frameType: r, data: d, nalus: h = [] } = e;
374
+ if (n === 0) {
375
+ const { codec: c, data: f } = e;
376
+ this.decoderWorker.video.init({ codec: c, description: f });
377
+ } else if (n === 1) {
378
+ const c = r === 1 ? "key" : "delta";
379
+ this.decoderWorker.video.decode({ type: c, timestamp: a * 1e3, data: d });
380
+ for (const f of h) {
393
381
  const { header: g, payload: l } = f, { nal_unit_type: m } = g;
394
382
  m === 6 && this.on.demuxer.sei && this.on.demuxer.sei(l);
395
383
  }
@@ -403,36 +391,58 @@ class me {
403
391
  * 初始化分离器
404
392
  */
405
393
  initDemuxer = () => {
406
- this.demuxerWorker.init(), this.demuxerWorker.on.tag = this.onTag;
394
+ this.demuxerWorker = new z(), this.demuxerWorker.init(), this.demuxerWorker.on.tag = this.onTag;
395
+ };
396
+ /**
397
+ * 初始化解码器
398
+ */
399
+ initDecoder = () => {
400
+ this.decoderWorker = new _(), this.decoderWorker.on.audio.decode = (t) => {
401
+ this.audioPlayer?.push(t), this.on.decoder.audio && this.on.decoder.audio(t);
402
+ }, this.decoderWorker.on.audio.error = (t) => {
403
+ this.stop(), this.on.error && this.on.error(t);
404
+ }, this.decoderWorker.on.video.decode = (t) => {
405
+ this.videoPlayerWorker?.push(t), X(this.cutVideoPlayerWorkers, t), this.on.decoder.video && this.on.decoder.video(t), t.bitmap.close();
406
+ }, this.decoderWorker.on.video.error = (t) => {
407
+ this.stop(), this.on.error && this.on.error(t);
408
+ };
407
409
  };
408
410
  /**
409
411
  * 初始化渲染器
410
412
  */
411
- initRender = ({ width: t = 256, height: s = 256, fps: e = 25 } = {}) => {
412
- if (!this.canvas) return;
413
- this.canvas.width = t, this.canvas.height = s, this.renderBaseTime = (/* @__PURE__ */ new Date()).getTime() + 1e3 * 3;
414
- const o = this.canvas.transferControlToOffscreen();
415
- if (this.videoPlayerWorker.init({ offscreenCanvas: o, baseTime: this.renderBaseTime }), this.on.stream) {
416
- const a = new MediaStream(), c = this.audioPlayer.getStream(), n = this.canvas?.captureStream(e);
417
- {
418
- const [r] = c?.getAudioTracks() || [];
419
- r && a.addTrack(r);
420
- }
421
- {
422
- const [r] = n.getVideoTracks() || [];
423
- r && a.addTrack(r);
424
- }
425
- this.on.stream(a);
413
+ initRender = ({ width: t = 256, height: s = 256 } = {}) => {
414
+ if (!this.on.video) return;
415
+ this.canvas = document.createElement("canvas"), this.canvas.width = t, this.canvas.height = s;
416
+ const e = this.canvas.transferControlToOffscreen();
417
+ this.videoPlayerWorker = new R(), this.videoPlayerWorker.init({ offscreenCanvas: e, baseTime: this.renderBaseTime }), this.on.video(this.canvas);
418
+ };
419
+ audio = {
420
+ /**
421
+ * 是否静音 默认为true
422
+ * @param state?: boolean
423
+ */
424
+ setMute: (t) => this.audioPlayer?.prAudioStream?.setMute(t)
425
+ };
426
+ video = {
427
+ /**
428
+ * 创建剪切
429
+ */
430
+ createCut: (t, s) => {
431
+ this.cutVideoPlayerWorkers.has(t) && this.cutVideoPlayerWorkers.get(t)?.worker.destroy();
432
+ const e = document.createElement("canvas"), { sw: o, sh: a } = s;
433
+ e.width = o || e.width, e.height = a || e.height;
434
+ const n = new R(), r = e.transferControlToOffscreen();
435
+ 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);
426
436
  }
427
437
  };
428
438
  }
429
- const U = new TextDecoder("utf-8"), X = (i, t) => {
439
+ const U = new TextDecoder("utf-8"), Z = (i, t) => {
430
440
  const s = i.getUint8(t), e = s >> 7 & 1, o = s >> 5 & 3, a = s & 31;
431
441
  return { forbidden_zero_bit: e, nal_ref_idc: o, nal_unit_type: a };
432
- }, T = (i, t) => i.getUint8(t), R = (i, t, s) => {
442
+ }, w = (i, t) => i.getUint8(t), G = (i, t, s) => {
433
443
  const e = new Uint8Array(i.buffer.slice(t, t + s));
434
444
  return U?.decode(e) || "";
435
- }, w = (i, t, s) => {
445
+ }, T = (i, t, s) => {
436
446
  let e = t, o, a = 0;
437
447
  switch (s) {
438
448
  case 0:
@@ -444,68 +454,68 @@ const U = new TextDecoder("utf-8"), X = (i, t) => {
444
454
  case 2:
445
455
  {
446
456
  o = "";
447
- const n = i.getUint16(e, !1);
457
+ const r = i.getUint16(e, !1);
448
458
  e = e + 2;
449
- const r = new Int8Array(i.buffer, e, n).filter((h) => h !== 0);
450
- o = (U?.decode(r) || "").trim(), a = 2 + n;
459
+ const d = new Int8Array(i.buffer, e, r).filter((c) => c !== 0);
460
+ o = (U?.decode(d) || "").trim(), a = 2 + r;
451
461
  }
452
462
  break;
453
463
  case 3:
454
464
  for (o = {}; e < i.byteLength; ) {
455
- const n = i.getUint16(e, !1);
456
- if (n === 0) break;
465
+ const r = i.getUint16(e, !1);
466
+ if (r === 0) break;
457
467
  e = e + 2;
458
- const r = R(i, e, n);
459
- e = e + n;
460
- const d = T(i, e);
461
- if (d === 6) break;
468
+ const d = G(i, e, r);
469
+ e = e + r;
470
+ const h = w(i, e);
471
+ if (h === 6) break;
462
472
  e = e + 1;
463
- const h = w(i, e, d);
464
- e = e + h.length, o[r] = h.value, a = 2 + n + 1 + h.length;
473
+ const c = T(i, e, h);
474
+ e = e + c.length, o[d] = c.value, a = 2 + r + 1 + c.length;
465
475
  }
466
476
  break;
467
477
  case 8:
468
478
  {
469
479
  o = {};
470
- const n = i.getUint32(e, !1);
480
+ const r = i.getUint32(e, !1);
471
481
  e = e + 4;
472
- for (let r = 0; r < n; r++) {
473
- const d = i.getUint16(e, !1);
482
+ for (let d = 0; d < r; d++) {
483
+ const h = i.getUint16(e, !1);
474
484
  e = e + 2;
475
- const h = R(i, e, d);
476
- e = e + d;
477
- const f = T(i, e);
485
+ const c = G(i, e, h);
486
+ e = e + h;
487
+ const f = w(i, e);
478
488
  e = e + 1;
479
- const g = w(i, e, f);
480
- e = e + g.length, o[h] = g.value, a = 2 + d + 1 + g.length;
489
+ const g = T(i, e, f);
490
+ e = e + g.length, o[c] = g.value, a = 2 + h + 1 + g.length;
481
491
  }
482
492
  }
483
493
  break;
484
494
  case 10:
485
495
  {
486
496
  o = [];
487
- const n = i.getUint32(e, !1);
497
+ const r = i.getUint32(e, !1);
488
498
  e = e + 4;
489
- for (let r = 0; r < n; r++) {
490
- const d = T(i, e);
499
+ for (let d = 0; d < r; d++) {
500
+ const h = w(i, e);
491
501
  e = e + 1;
492
- const h = w(i, e, d);
493
- e = e + h.length, o.push(h.value), a = 1 + h.length;
502
+ const c = T(i, e, h);
503
+ e = e + c.length, o.push(c.value), a = 1 + c.length;
494
504
  }
495
505
  }
496
506
  break;
497
507
  }
498
508
  return { amfType: s, length: a, value: o };
499
- }, b = (i, t) => i.getUint8(t) << 16 | i.getUint8(t + 1) << 8 | i.getUint8(t + 2), Y = (i) => {
509
+ }, b = (i, t) => i.getUint8(t) << 16 | i.getUint8(t + 1) << 8 | i.getUint8(t + 2), ee = (i) => {
500
510
  const t = new Int8Array(i.buffer.slice(0, 3));
501
511
  return U?.decode(t) || "";
502
- }, Z = (i) => i.getUint8(3), ee = (i) => {
512
+ }, te = (i) => i.getUint8(3), se = (i) => {
503
513
  const s = i.getUint8(0).toString(2).padStart(5, "0").split(""), [, , e, , o] = s;
504
514
  return {
505
515
  audio: o === "1",
506
516
  video: e === "1"
507
517
  };
508
- }, te = (i) => i.getUint32(5), se = { getSignature: Y, getVersion: Z, getFlags: ee, getDataOffset: te }, ie = (i, t) => {
518
+ }, ie = (i) => i.getUint32(5), oe = { getSignature: ee, getVersion: te, getFlags: se, getDataOffset: ie }, ae = (i, t) => {
509
519
  let s = !0;
510
520
  const e = i.byteLength;
511
521
  if (t + 4 > e)
@@ -517,7 +527,7 @@ const U = new TextDecoder("utf-8"), X = (i, t) => {
517
527
  t + 4 + 11 + o > e && (s = !1);
518
528
  }
519
529
  return s;
520
- }, oe = (i, t) => i.getUint32(t), ae = (i, t) => {
530
+ }, ne = (i, t) => i.getUint32(t), re = (i, t) => {
521
531
  const s = i.getUint8(t);
522
532
  let e;
523
533
  switch (s) {
@@ -532,7 +542,7 @@ const U = new TextDecoder("utf-8"), X = (i, t) => {
532
542
  break;
533
543
  }
534
544
  return e;
535
- }, ne = (i, t) => b(i, t + 1), re = (i, t) => b(i, t + 4), ce = (i, t) => i.getUint8(t + 7), de = (i, t) => b(i, t + 8), he = (i, t) => {
545
+ }, de = (i, t) => b(i, t + 1), ce = (i, t) => b(i, t + 4), he = (i, t) => i.getUint8(t + 7), ue = (i, t) => b(i, t + 8), ge = (i, t) => {
536
546
  let s = t;
537
547
  {
538
548
  if (i.getUint8(s) !== 2) throw new Error("Invalid AMF type for onMetaData (expected 0x02)");
@@ -541,36 +551,36 @@ const U = new TextDecoder("utf-8"), X = (i, t) => {
541
551
  const e = i.getUint16(s, !1);
542
552
  s = s + 2;
543
553
  {
544
- const c = new Int8Array(i.buffer.slice(s, s + e));
545
- if ((U?.decode(c) || "") !== "onMetaData") throw new Error("Expected 'onMetaData' string");
554
+ const n = new Int8Array(i.buffer.slice(s, s + e));
555
+ if ((U?.decode(n) || "") !== "onMetaData") throw new Error("Expected 'onMetaData' string");
546
556
  s = s + e;
547
557
  }
548
- const o = T(i, s);
549
- return s = s + 1, w(i, s, o).value;
550
- }, ue = (i, t, s) => {
558
+ const o = w(i, s);
559
+ return s = s + 1, T(i, s, o).value;
560
+ }, fe = (i, t, s) => {
551
561
  let e = t;
552
- const o = i.getUint8(e), a = o >> 4 & 15, c = o >> 2 & 3, n = o >> 1 & 1, r = o & 1;
562
+ const o = i.getUint8(e), a = o >> 4 & 15, n = o >> 2 & 3, r = o >> 1 & 1, d = o & 1;
553
563
  e = e + 1;
554
- const d = i.getUint8(e);
564
+ const h = i.getUint8(e);
555
565
  e = e + 1;
556
- const h = s - 2, f = new Uint8Array(i.buffer.slice(e, e + h));
557
- if (a === 10 && d === 0) {
558
- const g = i.getUint8(e), l = i.getUint8(e + 1), m = (g & 248) >> 3, y = (g & 7) << 1 | l >> 7, k = (l & 120) >> 3, x = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350], v = `mp4a.40.${m}`, D = x[y];
559
- return { soundFormat: a, soundRate: c, soundSize: n, soundType: r, accPacketType: d, data: f, audioObjectType: m, samplingFrequencyIndex: y, channelConfiguration: k, codec: v, sampleRate: D };
566
+ const c = s - 2, f = new Uint8Array(i.buffer.slice(e, e + c));
567
+ if (a === 10 && h === 0) {
568
+ const g = i.getUint8(e), l = i.getUint8(e + 1), m = (g & 248) >> 3, y = (g & 7) << 1 | l >> 7, k = (l & 120) >> 3, v = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350], x = `mp4a.40.${m}`, D = v[y];
569
+ return { soundFormat: a, soundRate: n, soundSize: r, soundType: d, accPacketType: h, data: f, audioObjectType: m, samplingFrequencyIndex: y, channelConfiguration: k, codec: x, sampleRate: D };
560
570
  }
561
- return { soundFormat: a, soundRate: c, soundSize: n, soundType: r, accPacketType: d, data: f };
562
- }, ge = (i, t, s) => {
571
+ return { soundFormat: a, soundRate: n, soundSize: r, soundType: d, accPacketType: h, data: f };
572
+ }, le = (i, t, s) => {
563
573
  let e = t;
564
- const o = i.getUint8(e), a = o >> 4 & 15, c = o & 15;
574
+ const o = i.getUint8(e), a = o >> 4 & 15, n = o & 15;
565
575
  e = e + 1;
566
- const n = i.getUint8(e);
576
+ const r = i.getUint8(e);
567
577
  e = e + 1;
568
- const r = b(i, e);
578
+ const d = b(i, e);
569
579
  e = e + 3;
570
- const d = s - 5, h = new Uint8Array(i.buffer.slice(e, e + d));
571
- switch (c) {
580
+ const h = s - 5, c = new Uint8Array(i.buffer.slice(e, e + h));
581
+ switch (n) {
572
582
  case 7:
573
- if (n === 0) {
583
+ if (r === 0) {
574
584
  const f = i.getUint8(e);
575
585
  if (e = e + 1, f !== 1) throw new Error("Invalid AVC version");
576
586
  const g = i.getUint8(e) & 255;
@@ -579,42 +589,41 @@ const U = new TextDecoder("utf-8"), X = (i, t) => {
579
589
  e = e + 1;
580
590
  const m = i.getUint8(e) & 255;
581
591
  e = e + 1;
582
- const x = `avc1.${Array.from([g, l, m], (I) => I.toString(16).padStart(2, "0")).join("")}`, v = (i.getUint8(e) & 3) - 1;
592
+ const v = `avc1.${Array.from([g, l, m], (B) => B.toString(16).padStart(2, "0")).join("")}`, x = (i.getUint8(e) & 3) - 1;
583
593
  e = e + 1;
584
594
  const D = i.getUint8(e) & 31;
585
595
  e = e + 1;
586
596
  const S = i.getUint16(e, !1);
587
597
  e = e + 2;
588
- const O = new Uint8Array(i.buffer.slice(e, e + S));
598
+ const W = new Uint8Array(i.buffer.slice(e, e + S));
589
599
  e = e + S;
590
- const W = i.getUint8(e) & 31;
600
+ const O = i.getUint8(e) & 31;
591
601
  e = e + 1;
592
602
  const C = i.getUint16(e, !1);
593
603
  e = e + 2;
594
- const B = new Uint8Array(i.buffer.slice(e, e + C));
595
- return e = e + C, { frameType: a, codecID: c, avcPacketType: n, cts: r, data: h, version: f, codec: x, profile: g, compatibility: l, level: m, lengthSizeMinusOne: v, numOfSequenceParameterSets: D, sequenceParameterSetLength: S, sps: O, numOfPictureParameterSets: W, pictureParameterSetLength: C, pps: B };
596
- } else if (n === 1) {
604
+ const I = new Uint8Array(i.buffer.slice(e, e + C));
605
+ return e = e + C, { frameType: a, codecID: n, avcPacketType: r, cts: d, data: c, version: f, codec: v, profile: g, compatibility: l, level: m, lengthSizeMinusOne: x, numOfSequenceParameterSets: D, sequenceParameterSetLength: S, sps: W, numOfPictureParameterSets: O, pictureParameterSetLength: C, pps: I };
606
+ } else if (r === 1) {
597
607
  const f = [], g = e + s - 5;
598
608
  for (; e + 4 < g; ) {
599
609
  const l = i.getUint32(e, !1);
600
610
  e = e + 4;
601
- const m = X(i, e);
611
+ const m = Z(i, e);
602
612
  e = e + 1;
603
613
  const y = l - 1, k = new Uint8Array(i.buffer.slice(e, e + y));
604
614
  e = e + y, f.push({ size: l, header: m, payload: k });
605
615
  }
606
- return { frameType: a, codecID: c, avcPacketType: n, cts: r, data: h, nalus: f };
616
+ return { frameType: a, codecID: n, avcPacketType: r, cts: d, data: c, nalus: f };
607
617
  }
608
618
  break;
609
619
  default:
610
620
  throw new Error("Unsupported codecID");
611
621
  }
612
- return { frameType: a, codecID: c, avcPacketType: n, cts: r, data: h };
613
- }, fe = { getTagType: ae, getDataSize: ne, getTimestamp: re, getTimestampExtended: ce, getStreamID: de }, le = { parseAudio: ue, parseVideo: ge, parseMetaData: he }, pe = { tagHeader: fe, tagBody: le }, p = { header: se, getPreviousTagSize: oe, isSurplusTag: ie, tag: pe };
614
- class ye {
622
+ return { frameType: a, codecID: n, avcPacketType: r, cts: d, data: c };
623
+ }, pe = { getTagType: re, getDataSize: de, getTimestamp: ce, getTimestampExtended: he, getStreamID: ue }, me = { parseAudio: fe, parseVideo: le, parseMetaData: ge }, ye = { tagHeader: pe, tagBody: me }, p = { header: oe, getPreviousTagSize: ne, isSurplusTag: ae, tag: ye };
624
+ class ke {
615
625
  parseSpeed = 8;
616
- parseTimer = 0;
617
- pushFuncs = [];
626
+ pendingPayloads = [];
618
627
  payload = new Uint8Array(0);
619
628
  offset = 0;
620
629
  is_parsing = !1;
@@ -625,27 +634,24 @@ class ye {
625
634
  constructor() {
626
635
  }
627
636
  init = () => {
628
- this.destroy(), this.parseTimer = setInterval(this.parse, this.parseSpeed);
637
+ this.destroy();
629
638
  };
630
639
  push = (t) => {
631
- const s = () => {
632
- const e = new Uint8Array(this.payload.byteLength + t.byteLength);
633
- e.set(this.payload, 0), e.set(t, this.payload.byteLength), this.payload = e;
634
- };
635
- this.pushFuncs.push(s);
640
+ this.pendingPayloads.push(t), this.is_parsing || this.parse();
636
641
  };
637
642
  destroy = () => {
638
- clearInterval(this.parseTimer), this.pushFuncs = [], this.payload = new Uint8Array(0), this.offset = 0, this.is_parsing = !1, this.header = void 0, this.tag = void 0;
643
+ this.pendingPayloads = [], this.payload = new Uint8Array(0), this.offset = 0, this.is_parsing = !1, this.header = void 0, this.tag = void 0;
639
644
  };
640
645
  parse = async () => {
641
- if (this.pushFuncs.length === 0 || this.is_parsing === !0) return;
642
- this.is_parsing = !0;
643
- {
644
- const s = this.pushFuncs.shift();
645
- s && s();
646
+ for (this.is_parsing = !0; ; ) {
647
+ const t = this.pendingPayloads.shift();
648
+ if (!t) break;
649
+ const s = new Uint8Array(this.payload.byteLength + t.byteLength);
650
+ s.set(this.payload, 0), s.set(t, this.payload.byteLength), this.payload = s;
651
+ const e = new DataView(this.payload.buffer);
652
+ this.header || this.parseHeader(e), await this.parseTag(e);
646
653
  }
647
- const t = new DataView(this.payload.buffer);
648
- this.header || this.parseHeader(t), await this.parseTag(t), this.is_parsing = !1;
654
+ this.is_parsing = !1;
649
655
  };
650
656
  parseHeader = (t) => (this.header = {
651
657
  signature: p.header.getSignature(t),
@@ -660,34 +666,34 @@ class ye {
660
666
  timestamp: p.tag.tagHeader.getTimestamp(o, a),
661
667
  timestampExtended: p.tag.tagHeader.getTimestampExtended(o, a),
662
668
  streamID: p.tag.tagHeader.getStreamID(o, a)
663
- }), e = (o, a, c, n) => {
664
- let r;
669
+ }), e = (o, a, n, r) => {
670
+ let d;
665
671
  switch (o) {
666
672
  case "script":
667
- r = p.tag.tagBody.parseMetaData(a, c);
673
+ d = p.tag.tagBody.parseMetaData(a, n);
668
674
  break;
669
675
  case "audio":
670
- r = p.tag.tagBody.parseAudio(a, c, n);
676
+ d = p.tag.tagBody.parseAudio(a, n, r);
671
677
  break;
672
678
  case "video":
673
- r = p.tag.tagBody.parseVideo(a, c, n);
679
+ d = p.tag.tagBody.parseVideo(a, n, r);
674
680
  break;
675
681
  }
676
- return r;
682
+ return d;
677
683
  };
678
684
  for (; this.offset < t.byteLength; ) {
679
685
  if (p.isSurplusTag(t, this.offset) === !1) {
680
686
  this.payload = this.payload.slice(this.offset), this.offset = 0;
681
687
  break;
682
688
  }
683
- const a = s(t, this.offset + 4), { tagType: c, dataSize: n } = a;
684
- if (!c) break;
685
- const r = e(c, t, this.offset + 4 + 11, n);
686
- this.tag = { header: a, body: r }, this.on.tag && this.on.tag(this.tag), this.offset = this.offset + 4 + 11 + n, await new Promise((d) => setTimeout(() => d(!0), this.parseSpeed));
689
+ const a = s(t, this.offset + 4), { tagType: n, dataSize: r } = a;
690
+ if (!n) break;
691
+ const d = e(n, t, this.offset + 4 + 11, r);
692
+ 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));
687
693
  }
688
694
  };
689
695
  }
690
- class be {
696
+ class we {
691
697
  audioDecoderConfig;
692
698
  audioDecoder;
693
699
  videoDecoderConfig;
@@ -745,54 +751,45 @@ class be {
745
751
  }
746
752
  };
747
753
  }
748
- class ke {
754
+ class Te {
749
755
  isRendering = !1;
750
756
  pendingFrames = [];
751
757
  offscreenCanvas;
752
758
  ctx;
753
759
  baseTime = 0;
754
- cutOption;
755
760
  constructor() {
756
761
  }
757
- setCut = async (t) => {
758
- this.cutOption = { ...this.cutOption, ...t };
759
- };
760
- init = ({ offscreenCanvas: t, baseTime: s = 0 }) => {
762
+ init = ({ offscreenCanvas: t, baseTime: s = performance.timeOrigin }) => {
761
763
  this.destroy(), this.offscreenCanvas = t, this.ctx = this.offscreenCanvas.getContext("2d"), this.baseTime = s;
762
764
  };
763
765
  destroy = () => {
764
- this.isRendering = !1, this.pendingFrames = [], this.offscreenCanvas = void 0, this.ctx = void 0, this.baseTime = 0, this.cutOption = void 0;
766
+ this.isRendering = !1, this.pendingFrames = [], this.offscreenCanvas = void 0, this.ctx = void 0, this.baseTime = 0;
765
767
  };
766
768
  push = (t) => {
767
769
  this.pendingFrames.push(t), this.isRendering === !1 && setTimeout(this.renderFrame, 0);
768
770
  };
769
771
  calculateTimeUntilNextFrame = (t) => {
770
- this.baseTime == 0 && (this.baseTime = performance.now());
771
- let s = performance.now() - this.baseTime;
772
- return Math.max(0, t / 1e3 - s);
772
+ const s = performance.timeOrigin + performance.now(), o = this.baseTime + t / 1e3 - s;
773
+ return Math.max(0, o);
773
774
  };
774
775
  renderFrame = async () => {
775
- const t = this.pendingFrames.shift();
776
- if (this.isRendering = !!t, !t) {
777
- this.isRendering = !1;
778
- return;
779
- }
780
- this.isRendering = !0;
781
- let { timestamp: s, bitmap: e } = t;
782
- if (this.cutOption) {
783
- const { sx: a = 0, sy: c = 0, sw: n = e.width, sh: r = e.height } = this.cutOption, d = await createImageBitmap(e, a, c, n, r);
784
- e.close(), e = d;
776
+ for (this.isRendering = !0; ; ) {
777
+ const t = this.pendingFrames.shift();
778
+ if (!t) break;
779
+ this.isRendering = !1, this.isRendering = !0;
780
+ let { timestamp: s, bitmap: e } = t;
781
+ const o = this.calculateTimeUntilNextFrame(s);
782
+ 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();
785
783
  }
786
- const o = this.calculateTimeUntilNextFrame(s);
787
- await new Promise((a) => setTimeout(a, o)), this.ctx && this.offscreenCanvas && this.ctx.drawImage(e, 0, 0, this.offscreenCanvas.width, this.offscreenCanvas.height), e.close(), setTimeout(this.renderFrame, 0);
784
+ this.isRendering = !1;
788
785
  };
789
786
  }
790
787
  export {
791
- be as Decoder,
788
+ we as Decoder,
792
789
  _ as DecoderWorker,
793
- ye as Demuxer,
794
- E as DemuxerWorker,
795
- me as PrPlayer,
796
- ke as VideoPlayer,
797
- G as VideoPlayerWorker
790
+ ke as Demuxer,
791
+ z as DemuxerWorker,
792
+ be as PrPlayer,
793
+ Te as VideoPlayer,
794
+ R as VideoPlayerWorker
798
795
  };
@@ -1,3 +1,3 @@
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"),I=(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}},T=(e,s)=>e.getUint8(s),F=(e,s,a)=>{const t=new Uint8Array(e.buffer.slice(s,s+a));return U?.decode(t)||""},b=(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(u=>u!==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=F(e,t,o);t=t+o;const g=T(e,t);if(g===6)break;t=t+1;const u=b(e,t,g);t=t+u.length,n[c]=u.value,r=2+o+1+u.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 u=F(e,t,g);t=t+g;const l=T(e,t);t=t+1;const h=b(e,t,l);t=t+h.length,n[u]=h.value,r=2+g+1+h.length}}break;case 10:{n=[];const o=e.getUint32(t,!1);t=t+4;for(let c=0;c<o;c++){const g=T(e,t);t=t+1;const u=b(e,t,g);t=t+u.length,n.push(u.value),r=1+u.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 d={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 u=a-2,l=new Uint8Array(e.buffer.slice(t,t+u));if(r===10&&g===0){const h=e.getUint8(t),p=e.getUint8(t+1),f=(h&248)>>3,y=(h&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:l,audioObjectType:f,samplingFrequencyIndex:y,channelConfiguration:S,codec:D,sampleRate:z}}return{soundFormat:r,soundRate:i,soundSize:o,soundType:c,accPacketType:g,data:l}},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,u=new Uint8Array(e.buffer.slice(t,t+g));switch(i){case 7:if(o===0){const l=e.getUint8(t);if(t=t+1,l!==1)throw new Error("Invalid AVC version");const h=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([h,p,f],P=>P.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 L=new Uint8Array(e.buffer.slice(t,t+_));t=t+_;const O=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:u,version:l,codec:A,profile:h,compatibility:p,level:f,lengthSizeMinusOne:D,numOfSequenceParameterSets:z,sequenceParameterSetLength:_,sps:L,numOfPictureParameterSets:O,pictureParameterSetLength:x,pps:M}}else if(o===1){const l=[],h=t+a-5;for(;t+4<h;){const p=e.getUint32(t,!1);t=t+4;const f=I(e,t);t=t+1;const y=p-1,S=new Uint8Array(e.buffer.slice(t,t+y));t=t+y,l.push({size:p,header:f,payload:S})}return{frameType:r,codecID:i,avcPacketType:o,cts:c,data:u,nalus:l}}break;default:throw new Error("Unsupported codecID")}return{frameType:r,codecID:i,avcPacketType:o,cts:c,data:u}},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=T(e,a);return a=a+1,b(e,a,n).value}}}};class H{parseSpeed=8;parseTimer=0;pushFuncs=[];payload=new Uint8Array(0);offset=0;is_parsing=!1;header;tag;on={};constructor(){}init=()=>{this.destroy(),this.parseTimer=setInterval(this.parse,this.parseSpeed)};push=s=>{const a=()=>{const t=new Uint8Array(this.payload.byteLength+s.byteLength);t.set(this.payload,0),t.set(s,this.payload.byteLength),this.payload=t};this.pushFuncs.push(a)};destroy=()=>{clearInterval(this.parseTimer),this.pushFuncs=[],this.payload=new Uint8Array(0),this.offset=0,this.is_parsing=!1,this.header=void 0,this.tag=void 0};parse=async()=>{if(this.pushFuncs.length===0||this.is_parsing===!0)return;this.is_parsing=!0;{const a=this.pushFuncs.shift();a&&a()}const s=new DataView(this.payload.buffer);this.header||this.parseHeader(s),await this.parseTag(s),this.is_parsing=!1};parseHeader=s=>(this.header={signature:d.header.getSignature(s),version:d.header.getVersion(s),flags:d.header.getFlags(s),dataOffset:d.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:d.tag.tagHeader.getTagType(n,r),dataSize:d.tag.tagHeader.getDataSize(n,r),timestamp:d.tag.tagHeader.getTimestamp(n,r),timestampExtended:d.tag.tagHeader.getTimestampExtended(n,r),streamID:d.tag.tagHeader.getStreamID(n,r)}),t=(n,r,i,o)=>{let c;switch(n){case"script":c=d.tag.tagBody.parseMetaData(r,i);break;case"audio":c=d.tag.tagBody.parseAudio(r,i,o);break;case"video":c=d.tag.tagBody.parseVideo(r,i,o);break}return c};for(;this.offset<s.byteLength;){if(d.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 H;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',P=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=P&&(self.URL||self.webkitURL).createObjectURL(P),!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"})}const R=`(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
- `,L=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",R],{type:"text/javascript;charset=utf-8"});function I(i){let t;try{if(t=L&&(self.URL||self.webkitURL).createObjectURL(L),!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(R),{name:i?.name})}}class N{worker=new I;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"})}}const O=`(function(){"use strict";class a{isRendering=!1;pendingFrames=[];offscreenCanvas;ctx;baseTime=0;cutOption;constructor(){}setCut=async e=>{this.cutOption={...this.cutOption,...e}};init=({offscreenCanvas:e,baseTime:s=0})=>{this.destroy(),this.offscreenCanvas=e,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,this.cutOption=void 0};push=e=>{this.pendingFrames.push(e),this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=e=>{this.baseTime==0&&(this.baseTime=performance.now());let s=performance.now()-this.baseTime;return Math.max(0,e/1e3-s)};renderFrame=async()=>{const e=this.pendingFrames.shift();if(this.isRendering=!!e,!e){this.isRendering=!1;return}this.isRendering=!0;let{timestamp:s,bitmap:t}=e;if(this.cutOption){const{sx:i=0,sy:c=0,sw:h=t.width,sh:m=t.height}=this.cutOption,f=await createImageBitmap(t,i,c,h,m);t.close(),t=f}const o=this.calculateTimeUntilNextFrame(s);await new Promise(i=>setTimeout(i,o)),this.ctx&&this.offscreenCanvas&&this.ctx.drawImage(t,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),t.close(),setTimeout(this.renderFrame,0)}}const r=new a;onmessage=n=>{const{action:e,data:s}=n.data,t=r[e];t&&t(s)}})();
3
- `,W=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",O],{type:"text/javascript;charset=utf-8"});function E(i){let t;try{if(t=W&&(self.URL||self.webkitURL).createObjectURL(W),!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(O),{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]);destroy=()=>this.worker.postMessage({action:"destroy",data:{}});push=t=>this.worker.postMessage({action:"push",data:t})}var z=Object.defineProperty,_=(i,t,s)=>t in i?z(i,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):i[t]=s,h=(i,t,s)=>_(i,typeof t!="symbol"?t+"":t,s);class j{constructor(t,s){h(this,"inputStream",new MediaStream),h(this,"outputStream",new MediaStream),h(this,"inputGain",1),h(this,"enhanceGain",1),h(this,"bgsGain",1),h(this,"bgmGain",1),h(this,"outputGain",1),h(this,"mixAudioMap",new Map),h(this,"audioContext",new AudioContext),h(this,"sourceNode"),h(this,"inputGainNode"),h(this,"enhanceGainNode"),h(this,"bgsGainNode"),h(this,"bgmGainNode"),h(this,"analyserNode"),h(this,"analyserArrayData"),h(this,"outputGainNode"),h(this,"destinationNode"),h(this,"filterStream",e=>e),h(this,"stop",()=>{{const e=this.inputStream.getTracks();for(const o of e)o.stop(),this.inputStream.removeTrack(o)}}),h(this,"getStream",()=>this.filterStream(this.outputStream)),h(this,"setMute",(e=!0)=>{e?this.analyserNode.disconnect(this.outputGainNode):this.analyserNode.connect(this.outputGainNode)}),h(this,"setInputGain",e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),h(this,"setEnhanceGain",async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)}),h(this,"setBgsGain",e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),h(this,"setBgmGain",e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),h(this,"setOutputGain",e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)}),h(this,"getVolume",()=>{const{analyserNode:e,analyserArrayData:o}=this;e.getByteFrequencyData(o);let a=0;for(let c=0;c<o.length;c++)a+=o[c];return Math.ceil(a/o.length)}),h(this,"mixAudio",(e,o="bgm")=>new Promise(async(a,c)=>{try{{const d=this.mixAudioMap.get(o);d&&d.stop()}const n=o==="bgs"?this.bgsGainNode:this.bgmGainNode,r=this.audioContext.createBufferSource();this.mixAudioMap.set(o,r),r.buffer=e,r.connect(n),r.onended=()=>{r.disconnect(n),this.mixAudioMap.delete(o),a(!0)},r.start(0)}catch(n){c(n)}})),h(this,"mixAudioStop",e=>{const o=this.mixAudioMap.get(e);o?.stop()}),h(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:c,bgmGainNode:n,analyserNode:r,outputGainNode:d,destinationNode:u}=this;e.connect(o),o.connect(a),a.connect(r),c.connect(r),n.connect(r),a.connect(u),c.connect(u),n.connect(u),r.connect(d),d.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,c=i.createBuffer(e,o,a);for(let n=0;n<e;n++){const r=t.allocationSize({planeIndex:n}),d=new Uint8Array(r);t.copyTo(d,{planeIndex:n});const u=new DataView(d.buffer),f=c.getChannelData(n);for(let g=0;g<o;g++){let l;switch(s){case"s16":case"s16-planar":l=u.getInt16(g*2,!0)/32768;break;case"f32":case"f32-planar":l=u.getFloat32(g*4,!0);break;case"u8":case"u8-planar":l=(u.getUint8(g)-128)/128;break;default:throw new Error(`Unsupported audio format: ${s}`)}f[g]=Math.max(-1,Math.min(1,l))}}return c}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 c=await fetch(t,{...s,method:"HEAD",signal:this.#e?.signal});c.status===200?e({status:"successed",reason:""}):o({status:"failed",reason:`${c.status}`})}catch(c){o({status:"error",reason:c.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.")}}class K{prFetch=new q;demuxerWorker=new G;decoderWorker=new N;audioPlayer=new $;videoPlayerWorker=new D;renderBaseTime=0;cutVideoPlayerWorkers=new Map;canvas;on={demuxer:{},decoder:{}};constructor(){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=>{console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->decoderWorker.audio.onError: e",t),this.stop()},this.decoderWorker.on.video.decode=t=>{this.videoPlayerWorker.push(t);const s=[...this.cutVideoPlayerWorkers.keys()];for(const e of s)this.cutVideoPlayerWorkers.get(e).push(t);this.on.decoder.video&&this.on.decoder.video(t)},this.decoderWorker.on.video.error=t=>{console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->decoderWorker.video.onError: e",t),this.stop()}}createCut=(t,s,e,o=25)=>{e||(e=document.createElement("canvas")),this.cutVideoPlayerWorkers.has(t)&&this.cutVideoPlayerWorkers.get(t).destroy();const{sw:a,sh:c}=s;e.width=a||e.width,e.height=c||e.height;const n=new D,r=e.transferControlToOffscreen();if(n.init({offscreenCanvas:r,baseTime:this.renderBaseTime}),n.setCut(s),this.cutVideoPlayerWorkers.set(t,n),this.on.cutStream){const d=e.captureStream(o);this.on.cutStream(t,d)}return e};init=t=>{this.stop(),this.initDemuxer(),t||(t=document.createElement("canvas")),this.canvas=t,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.audio.destroy(),this.decoderWorker.video.destroy(),this.videoPlayerWorker.destroy();const t=[...this.cutVideoPlayerWorkers.keys()];for(const s of t)this.cutVideoPlayerWorkers.get(s).destroy(),this.cutVideoPlayerWorkers.delete(s);this.audioPlayer.destroy(),this.renderBaseTime=0,this.canvas=void 0};setMute=t=>this.audioPlayer.prAudioStream?.setMute(t);onTag=t=>{const{header:s,body:e}=t,{tagType:o,timestamp:a}=s;switch(o){case"script":{const{width:c,height:n}=e;this.initRender({width:c,height:n}),this.on.demuxer.script&&this.on.demuxer.script(t)}break;case"audio":{const{accPacketType:c,data:n}=e;if(c===0){const{codec:r,sampleRate:d,channelConfiguration:u}=e,f={codec:r,sampleRate:d,numberOfChannels:u,description:new Uint8Array([])};this.decoderWorker.audio.init(f)}else c===1&&this.decoderWorker.audio.decode({type:"key",timestamp:a*1,data:n});this.on.demuxer.audio&&this.on.demuxer.audio(t)}break;case"video":{const{avcPacketType:c,frameType:n,data:r,nalus:d=[]}=e;if(c===0){const{codec:u,data:f}=e;this.decoderWorker.video.init({codec:u,description:f})}else if(c===1){const u=n===1?"key":"delta";this.decoderWorker.video.decode({type:u,timestamp:a*1e3,data:r});for(const f of d){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.init(),this.demuxerWorker.on.tag=this.onTag};initRender=({width:t=256,height:s=256,fps:e=25}={})=>{if(!this.canvas)return;this.canvas.width=t,this.canvas.height=s,this.renderBaseTime=new Date().getTime()+1e3*3;const o=this.canvas.transferControlToOffscreen();if(this.videoPlayerWorker.init({offscreenCanvas:o,baseTime:this.renderBaseTime}),this.on.stream){const a=new MediaStream,c=this.audioPlayer.getStream(),n=this.canvas?.captureStream(e);{const[r]=c?.getAudioTracks()||[];r&&a.addTrack(r)}{const[r]=n.getVideoTracks()||[];r&&a.addTrack(r)}this.on.stream(a)}}}const w=new TextDecoder("utf-8"),Q=(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),V=(i,t,s)=>{const e=new Uint8Array(i.buffer.slice(t,t+s));return w?.decode(e)||""},x=(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 n=i.getUint16(e,!1);e=e+2;const r=new Int8Array(i.buffer,e,n).filter(u=>u!==0);o=(w?.decode(r)||"").trim(),a=2+n}break;case 3:for(o={};e<i.byteLength;){const n=i.getUint16(e,!1);if(n===0)break;e=e+2;const r=V(i,e,n);e=e+n;const d=U(i,e);if(d===6)break;e=e+1;const u=x(i,e,d);e=e+u.length,o[r]=u.value,a=2+n+1+u.length}break;case 8:{o={};const n=i.getUint32(e,!1);e=e+4;for(let r=0;r<n;r++){const d=i.getUint16(e,!1);e=e+2;const u=V(i,e,d);e=e+d;const f=U(i,e);e=e+1;const g=x(i,e,f);e=e+g.length,o[u]=g.value,a=2+d+1+g.length}}break;case 10:{o=[];const n=i.getUint32(e,!1);e=e+4;for(let r=0;r<n;r++){const d=U(i,e);e=e+1;const u=x(i,e,d);e=e+u.length,o.push(u.value),a=1+u.length}}break}return{amfType:s,length:a,value:o}},T=(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 w?.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=T(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)=>T(i,t+1),getTimestamp:(i,t)=>T(i,t+4),getTimestampExtended:(i,t)=>i.getUint8(t+7),getStreamID:(i,t)=>T(i,t+8)},tagBody:{parseAudio:(i,t,s)=>{let e=t;const o=i.getUint8(e),a=o>>4&15,c=o>>2&3,n=o>>1&1,r=o&1;e=e+1;const d=i.getUint8(e);e=e+1;const u=s-2,f=new Uint8Array(i.buffer.slice(e,e+u));if(a===10&&d===0){const g=i.getUint8(e),l=i.getUint8(e+1),y=(g&248)>>3,k=(g&7)<<1|l>>7,v=(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:c,soundSize:n,soundType:r,accPacketType:d,data:f,audioObjectType:y,samplingFrequencyIndex:k,channelConfiguration:v,codec:C,sampleRate:A}}return{soundFormat:a,soundRate:c,soundSize:n,soundType:r,accPacketType:d,data:f}},parseVideo:(i,t,s)=>{let e=t;const o=i.getUint8(e),a=o>>4&15,c=o&15;e=e+1;const n=i.getUint8(e);e=e+1;const r=T(i,e);e=e+3;const d=s-5,u=new Uint8Array(i.buffer.slice(e,e+d));switch(c){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 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],se=>se.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 Z=new Uint8Array(i.buffer.slice(e,e+M));e=e+M;const ee=i.getUint8(e)&31;e=e+1;const F=i.getUint16(e,!1);e=e+2;const te=new Uint8Array(i.buffer.slice(e,e+F));return e=e+F,{frameType:a,codecID:c,avcPacketType:n,cts:r,data:u,version:f,codec:S,profile:g,compatibility:l,level:y,lengthSizeMinusOne:C,numOfSequenceParameterSets:A,sequenceParameterSetLength:M,sps:Z,numOfPictureParameterSets:ee,pictureParameterSetLength:F,pps:te}}else if(n===1){const f=[],g=e+s-5;for(;e+4<g;){const l=i.getUint32(e,!1);e=e+4;const y=Q(i,e);e=e+1;const k=l-1,v=new Uint8Array(i.buffer.slice(e,e+k));e=e+k,f.push({size:l,header:y,payload:v})}return{frameType:a,codecID:c,avcPacketType:n,cts:r,data:u,nalus:f}}break;default:throw new Error("Unsupported codecID")}return{frameType:a,codecID:c,avcPacketType:n,cts:r,data:u}},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 c=new Int8Array(i.buffer.slice(s,s+e));if((w?.decode(c)||"")!=="onMetaData")throw new Error("Expected 'onMetaData' string");s=s+e}const o=U(i,s);return s=s+1,x(i,s,o).value}}}};class J{parseSpeed=8;parseTimer=0;pushFuncs=[];payload=new Uint8Array(0);offset=0;is_parsing=!1;header;tag;on={};constructor(){}init=()=>{this.destroy(),this.parseTimer=setInterval(this.parse,this.parseSpeed)};push=t=>{const s=()=>{const e=new Uint8Array(this.payload.byteLength+t.byteLength);e.set(this.payload,0),e.set(t,this.payload.byteLength),this.payload=e};this.pushFuncs.push(s)};destroy=()=>{clearInterval(this.parseTimer),this.pushFuncs=[],this.payload=new Uint8Array(0),this.offset=0,this.is_parsing=!1,this.header=void 0,this.tag=void 0};parse=async()=>{if(this.pushFuncs.length===0||this.is_parsing===!0)return;this.is_parsing=!0;{const s=this.pushFuncs.shift();s&&s()}const t=new DataView(this.payload.buffer);this.header||this.parseHeader(t),await this.parseTag(t),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,c,n)=>{let r;switch(o){case"script":r=p.tag.tagBody.parseMetaData(a,c);break;case"audio":r=p.tag.tagBody.parseAudio(a,c,n);break;case"video":r=p.tag.tagBody.parseVideo(a,c,n);break}return r};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:c,dataSize:n}=a;if(!c)break;const r=e(c,t,this.offset+4+11,n);this.tag={header:a,body:r},this.on.tag&&this.on.tag(this.tag),this.offset=this.offset+4+11+n,await new Promise(d=>setTimeout(()=>d(!0),this.parseSpeed))}}}class X{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 Y{isRendering=!1;pendingFrames=[];offscreenCanvas;ctx;baseTime=0;cutOption;constructor(){}setCut=async t=>{this.cutOption={...this.cutOption,...t}};init=({offscreenCanvas:t,baseTime:s=0})=>{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,this.cutOption=void 0};push=t=>{this.pendingFrames.push(t),this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=t=>{this.baseTime==0&&(this.baseTime=performance.now());let s=performance.now()-this.baseTime;return Math.max(0,t/1e3-s)};renderFrame=async()=>{const t=this.pendingFrames.shift();if(this.isRendering=!!t,!t){this.isRendering=!1;return}this.isRendering=!0;let{timestamp:s,bitmap:e}=t;if(this.cutOption){const{sx:a=0,sy:c=0,sw:n=e.width,sh:r=e.height}=this.cutOption,d=await createImageBitmap(e,a,c,n,r);e.close(),e=d}const o=this.calculateTimeUntilNextFrame(s);await new Promise(a=>setTimeout(a,o)),this.ctx&&this.offscreenCanvas&&this.ctx.drawImage(e,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),e.close(),setTimeout(this.renderFrame,0)}}m.Decoder=X,m.DecoderWorker=N,m.Demuxer=J,m.DemuxerWorker=G,m.PrPlayer=K,m.VideoPlayer=Y,m.VideoPlayerWorker=D,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
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
+ `,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"})}));
@@ -1,13 +1,10 @@
1
- import { CutOption } from './type';
2
1
  export declare class VideoPlayer {
3
2
  private isRendering;
4
3
  private pendingFrames;
5
4
  private offscreenCanvas;
6
5
  private ctx;
7
6
  private baseTime;
8
- private cutOption;
9
7
  constructor();
10
- setCut: (cutOption: CutOption) => Promise<void>;
11
8
  init: ({ offscreenCanvas, baseTime }: {
12
9
  offscreenCanvas: OffscreenCanvas;
13
10
  baseTime?: number;
@@ -7,9 +7,9 @@ export declare class VideoPlayerWorker {
7
7
  offscreenCanvas: OffscreenCanvas;
8
8
  baseTime?: number;
9
9
  }) => void;
10
- destroy: () => void;
11
10
  push: (frame: {
12
11
  timestamp: number;
13
12
  bitmap: ImageBitmap;
14
13
  }) => void;
14
+ destroy: () => void;
15
15
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pr-player",
3
3
  "description": "基于web-codecs解码flv视频流并输出帧数据。",
4
- "version": "0.0.1",
4
+ "version": "0.0.2",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist"