pr-player 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -42,7 +42,7 @@ export declare class PrPlayer {
42
42
  /**
43
43
  * 停止
44
44
  */
45
- stop: () => void;
45
+ stop: () => Promise<void>;
46
46
  /**
47
47
  * 监听媒体 tag
48
48
  */
package/dist/index.js CHANGED
@@ -150,21 +150,21 @@ class Q {
150
150
  const { analyserNode: e, analyserArrayData: a } = this;
151
151
  e.getByteFrequencyData(a);
152
152
  let o = 0;
153
- for (let n = 0; n < a.length; n++)
154
- o += a[n];
153
+ for (let r = 0; r < a.length; r++)
154
+ o += a[r];
155
155
  return Math.ceil(o / a.length);
156
- }), h(this, "mixAudio", (e, a = "bgm") => new Promise(async (o, n) => {
156
+ }), h(this, "mixAudio", (e, a = "bgm") => new Promise(async (o, r) => {
157
157
  try {
158
158
  {
159
159
  const u = this.mixAudioMap.get(a);
160
160
  u && u.stop();
161
161
  }
162
- const r = a === "bgs" ? this.bgsGainNode : this.bgmGainNode, d = this.audioContext.createBufferSource();
163
- this.mixAudioMap.set(a, d), d.buffer = e, d.connect(r), d.onended = () => {
164
- d.disconnect(r), this.mixAudioMap.delete(a), o(!0);
162
+ const n = a === "bgs" ? this.bgsGainNode : this.bgmGainNode, d = this.audioContext.createBufferSource();
163
+ this.mixAudioMap.set(a, d), d.buffer = e, d.connect(n), d.onended = () => {
164
+ d.disconnect(n), this.mixAudioMap.delete(a), o(!0);
165
165
  }, d.start(0);
166
- } catch (r) {
167
- n(r);
166
+ } catch (n) {
167
+ r(n);
168
168
  }
169
169
  })), h(this, "mixAudioStop", (e) => {
170
170
  const a = this.mixAudioMap.get(e);
@@ -174,19 +174,19 @@ class Q {
174
174
  a ? o.connect(this.destinationNode) : o.disconnect(this.destinationNode);
175
175
  }), 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;
176
176
  {
177
- const { sourceNode: e, inputGainNode: a, enhanceGainNode: o, bgsGainNode: n, bgmGainNode: r, analyserNode: d, outputGainNode: u, destinationNode: c } = this;
178
- e.connect(a), a.connect(o), o.connect(d), n.connect(d), r.connect(d), o.connect(c), n.connect(c), r.connect(c), d.connect(u), u.connect(this.audioContext.destination);
177
+ const { sourceNode: e, inputGainNode: a, enhanceGainNode: o, bgsGainNode: r, bgmGainNode: n, analyserNode: d, outputGainNode: u, destinationNode: c } = this;
178
+ e.connect(a), a.connect(o), o.connect(d), r.connect(d), n.connect(d), o.connect(c), r.connect(c), n.connect(c), d.connect(u), u.connect(this.audioContext.destination);
179
179
  }
180
180
  this.setMute(!0), this.audioContext.resume();
181
181
  }
182
182
  }
183
183
  const J = async (i, t) => {
184
184
  try {
185
- const { format: s, numberOfChannels: e, numberOfFrames: a, sampleRate: o } = t, n = i.createBuffer(e, a, o);
186
- for (let r = 0; r < e; r++) {
187
- const d = t.allocationSize({ planeIndex: r }), u = new Uint8Array(d);
188
- t.copyTo(u, { planeIndex: r });
189
- const c = new DataView(u.buffer), f = n.getChannelData(r);
185
+ const { format: s, numberOfChannels: e, numberOfFrames: a, sampleRate: o } = t, r = i.createBuffer(e, a, o);
186
+ for (let n = 0; n < e; n++) {
187
+ const d = t.allocationSize({ planeIndex: n }), u = new Uint8Array(d);
188
+ t.copyTo(u, { planeIndex: n });
189
+ const c = new DataView(u.buffer), f = r.getChannelData(n);
190
190
  for (let g = 0; g < a; g++) {
191
191
  let p;
192
192
  switch (s) {
@@ -211,7 +211,7 @@ const J = async (i, t) => {
211
211
  f[g] = Math.max(-1, Math.min(1, p));
212
212
  }
213
213
  }
214
- return n;
214
+ return r;
215
215
  } catch (s) {
216
216
  throw console.error("Failed to convert AudioData to AudioBuffer:", s), s;
217
217
  }
@@ -267,10 +267,10 @@ class Y {
267
267
  this.#e?.abort("Timeout."), a({ status: "timeout", reason: "" });
268
268
  }, this.#t.timeout);
269
269
  try {
270
- const n = await fetch(t, { ...s, method: "HEAD", signal: this.#e?.signal });
271
- n.status === 200 ? e({ status: "successed", reason: "" }) : a({ status: "failed", reason: `${n.status}` });
272
- } catch (n) {
273
- a({ status: "error", reason: n.message });
270
+ const r = await fetch(t, { ...s, method: "HEAD", signal: this.#e?.signal });
271
+ r.status === 200 ? e({ status: "successed", reason: "" }) : a({ status: "failed", reason: `${r.status}` });
272
+ } catch (r) {
273
+ a({ status: "error", reason: r.message });
274
274
  }
275
275
  clearTimeout(o);
276
276
  });
@@ -300,10 +300,10 @@ const O = (i) => {
300
300
  for (const s of t)
301
301
  s.stop();
302
302
  }, G = (i) => {
303
- const t = new $(), s = document.createElement("canvas"), e = s.transferControlToOffscreen(), a = new MediaStreamTrackGenerator({ kind: "video" }), o = new MediaStream([a]), n = () => {
303
+ const t = new $(), s = document.createElement("canvas"), e = s.transferControlToOffscreen(), a = new MediaStreamTrackGenerator({ kind: "video" }), o = new MediaStream([a]), r = () => {
304
304
  t.destroy(), O(o);
305
305
  };
306
- return t.init({ offscreenCanvas: e, baseTime: i, writable: a.writable }), { worker: t, canvas: s, stream: o, destroy: n };
306
+ return t.init({ offscreenCanvas: e, baseTime: i, writable: a.writable }), { worker: t, canvas: s, stream: o, destroy: r };
307
307
  };
308
308
  class be {
309
309
  prFetch = new Y();
@@ -330,24 +330,28 @@ class be {
330
330
  * 开始播放
331
331
  * @param url : string
332
332
  */
333
- start = async (t) => {
334
- try {
335
- this.stop(), this.renderBaseTime = (/* @__PURE__ */ new Date()).getTime(), this.init();
336
- const e = (await this.prFetch.request(t)).body?.getReader();
337
- if (!e) throw new Error("Reader is error.");
338
- for (; ; ) {
339
- const { done: a, value: o } = await e.read();
340
- if (o && this.demuxerWorker?.push(o), a)
341
- break;
342
- }
343
- } catch {
344
- }
345
- };
333
+ start = async (t) => (this.stop(), this.renderBaseTime = (/* @__PURE__ */ new Date()).getTime(), this.init(), this.prFetch.request(t).then(async (s) => {
334
+ const e = s.body?.getReader();
335
+ if (!e) throw new Error("Reader is error.");
336
+ const a = () => e.read().then(({ done: o, value: r }) => {
337
+ r && this.demuxerWorker?.push(r), !o && a();
338
+ }).catch((o) => {
339
+ if (o.name !== "AbortError") throw o;
340
+ });
341
+ a();
342
+ }).catch((s) => {
343
+ console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m", "color:#0097ff;", "------->Breathe: err", s);
344
+ }));
346
345
  /**
347
346
  * 停止
348
347
  */
349
- stop = () => {
350
- this.prFetch.stop(), this.demuxerWorker?.destroy(), this.decoderWorker?.destroy(), this.renderWorker?.destroy(), O(this.stream);
348
+ stop = async () => {
349
+ try {
350
+ this.prFetch.stop();
351
+ } catch (s) {
352
+ console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m", "color:#0097ff;", "------->Breathe: error", s);
353
+ }
354
+ this.demuxerWorker?.destroy(), this.decoderWorker?.destroy(), this.renderWorker?.destroy(), O(this.stream);
351
355
  const t = [...this.cutRenders.keys()];
352
356
  for (const s of t)
353
357
  this.cut.remove(s);
@@ -362,28 +366,28 @@ class be {
362
366
  switch (a) {
363
367
  case "script":
364
368
  {
365
- const { width: n, height: r } = e;
366
- this.renderWorker?.setSize({ width: n, height: r }), this.on.demuxer.script && this.on.demuxer.script(t);
369
+ const { width: r, height: n } = e;
370
+ this.renderWorker?.setSize({ width: r, height: n }), this.on.demuxer.script && this.on.demuxer.script(t);
367
371
  }
368
372
  break;
369
373
  case "audio":
370
374
  {
371
- const { accPacketType: n, data: r } = e;
372
- if (n === 0) {
375
+ const { accPacketType: r, data: n } = e;
376
+ if (r === 0) {
373
377
  const { codec: d, sampleRate: u, channelConfiguration: c } = e, f = { codec: d, sampleRate: u, numberOfChannels: c, description: new Uint8Array([]) };
374
378
  this.decoderWorker.audio.init(f);
375
- } else n === 1 && this.decoderWorker.audio.decode({ type: "key", timestamp: o * 1, data: r });
379
+ } else r === 1 && this.decoderWorker.audio.decode({ type: "key", timestamp: o * 1, data: n });
376
380
  this.on.demuxer.audio && this.on.demuxer.audio(t);
377
381
  }
378
382
  break;
379
383
  case "video":
380
384
  {
381
- const { avcPacketType: n, frameType: r, data: d, nalus: u = [] } = e;
382
- if (n === 0) {
385
+ const { avcPacketType: r, frameType: n, data: d, nalus: u = [] } = e;
386
+ if (r === 0) {
383
387
  const { codec: c, data: f } = e;
384
388
  this.decoderWorker.video.init({ codec: c, description: f });
385
- } else if (n === 1) {
386
- const c = r === 1 ? "key" : "delta";
389
+ } else if (r === 1) {
390
+ const c = n === 1 ? "key" : "delta";
387
391
  this.decoderWorker.video.decode({ type: c, timestamp: o * 1e3, data: d });
388
392
  for (const f of u) {
389
393
  const { header: g, payload: p } = f, { nal_unit_type: m } = g;
@@ -487,32 +491,32 @@ const U = new TextDecoder("utf-8"), Z = (i, t) => {
487
491
  case 2:
488
492
  {
489
493
  a = "";
490
- const r = i.getUint16(e, !1);
494
+ const n = i.getUint16(e, !1);
491
495
  e = e + 2;
492
- const d = new Int8Array(i.buffer, e, r).filter((c) => c !== 0);
493
- a = (U?.decode(d) || "").trim(), o = 2 + r;
496
+ const d = new Int8Array(i.buffer, e, n).filter((c) => c !== 0);
497
+ a = (U?.decode(d) || "").trim(), o = 2 + n;
494
498
  }
495
499
  break;
496
500
  case 3:
497
501
  for (a = {}; e < i.byteLength; ) {
498
- const r = i.getUint16(e, !1);
499
- if (r === 0) break;
502
+ const n = i.getUint16(e, !1);
503
+ if (n === 0) break;
500
504
  e = e + 2;
501
- const d = P(i, e, r);
502
- e = e + r;
505
+ const d = P(i, e, n);
506
+ e = e + n;
503
507
  const u = w(i, e);
504
508
  if (u === 6) break;
505
509
  e = e + 1;
506
510
  const c = T(i, e, u);
507
- e = e + c.length, a[d] = c.value, o = 2 + r + 1 + c.length;
511
+ e = e + c.length, a[d] = c.value, o = 2 + n + 1 + c.length;
508
512
  }
509
513
  break;
510
514
  case 8:
511
515
  {
512
516
  a = {};
513
- const r = i.getUint32(e, !1);
517
+ const n = i.getUint32(e, !1);
514
518
  e = e + 4;
515
- for (let d = 0; d < r; d++) {
519
+ for (let d = 0; d < n; d++) {
516
520
  const u = i.getUint16(e, !1);
517
521
  e = e + 2;
518
522
  const c = P(i, e, u);
@@ -527,9 +531,9 @@ const U = new TextDecoder("utf-8"), Z = (i, t) => {
527
531
  case 10:
528
532
  {
529
533
  a = [];
530
- const r = i.getUint32(e, !1);
534
+ const n = i.getUint32(e, !1);
531
535
  e = e + 4;
532
- for (let d = 0; d < r; d++) {
536
+ for (let d = 0; d < n; d++) {
533
537
  const u = w(i, e);
534
538
  e = e + 1;
535
539
  const c = T(i, e, u);
@@ -584,36 +588,36 @@ const U = new TextDecoder("utf-8"), Z = (i, t) => {
584
588
  const e = i.getUint16(s, !1);
585
589
  s = s + 2;
586
590
  {
587
- const n = new Int8Array(i.buffer.slice(s, s + e));
588
- if ((U?.decode(n) || "") !== "onMetaData") throw new Error("Expected 'onMetaData' string");
591
+ const r = new Int8Array(i.buffer.slice(s, s + e));
592
+ if ((U?.decode(r) || "") !== "onMetaData") throw new Error("Expected 'onMetaData' string");
589
593
  s = s + e;
590
594
  }
591
595
  const a = w(i, s);
592
596
  return s = s + 1, T(i, s, a).value;
593
597
  }, fe = (i, t, s) => {
594
598
  let e = t;
595
- const a = i.getUint8(e), o = a >> 4 & 15, n = a >> 2 & 3, r = a >> 1 & 1, d = a & 1;
599
+ const a = i.getUint8(e), o = a >> 4 & 15, r = a >> 2 & 3, n = a >> 1 & 1, d = a & 1;
596
600
  e = e + 1;
597
601
  const u = i.getUint8(e);
598
602
  e = e + 1;
599
603
  const c = s - 2, f = new Uint8Array(i.buffer.slice(e, e + c));
600
604
  if (o === 10 && u === 0) {
601
605
  const g = i.getUint8(e), p = i.getUint8(e + 1), m = (g & 248) >> 3, y = (g & 7) << 1 | p >> 7, k = (p & 120) >> 3, v = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350], x = `mp4a.40.${m}`, S = v[y];
602
- return { soundFormat: o, soundRate: n, soundSize: r, soundType: d, accPacketType: u, data: f, audioObjectType: m, samplingFrequencyIndex: y, channelConfiguration: k, codec: x, sampleRate: S };
606
+ return { soundFormat: o, soundRate: r, soundSize: n, soundType: d, accPacketType: u, data: f, audioObjectType: m, samplingFrequencyIndex: y, channelConfiguration: k, codec: x, sampleRate: S };
603
607
  }
604
- return { soundFormat: o, soundRate: n, soundSize: r, soundType: d, accPacketType: u, data: f };
608
+ return { soundFormat: o, soundRate: r, soundSize: n, soundType: d, accPacketType: u, data: f };
605
609
  }, pe = (i, t, s) => {
606
610
  let e = t;
607
- const a = i.getUint8(e), o = a >> 4 & 15, n = a & 15;
611
+ const a = i.getUint8(e), o = a >> 4 & 15, r = a & 15;
608
612
  e = e + 1;
609
- const r = i.getUint8(e);
613
+ const n = i.getUint8(e);
610
614
  e = e + 1;
611
615
  const d = b(i, e);
612
616
  e = e + 3;
613
617
  const u = s - 5, c = new Uint8Array(i.buffer.slice(e, e + u));
614
- switch (n) {
618
+ switch (r) {
615
619
  case 7:
616
- if (r === 0) {
620
+ if (n === 0) {
617
621
  const f = i.getUint8(e);
618
622
  if (e = e + 1, f !== 1) throw new Error("Invalid AVC version");
619
623
  const g = i.getUint8(e) & 255;
@@ -622,7 +626,7 @@ const U = new TextDecoder("utf-8"), Z = (i, t) => {
622
626
  e = e + 1;
623
627
  const m = i.getUint8(e) & 255;
624
628
  e = e + 1;
625
- const v = `avc1.${Array.from([g, p, m], (B) => B.toString(16).padStart(2, "0")).join("")}`, x = (i.getUint8(e) & 3) - 1;
629
+ const v = `avc1.${Array.from([g, p, m], (z) => z.toString(16).padStart(2, "0")).join("")}`, x = (i.getUint8(e) & 3) - 1;
626
630
  e = e + 1;
627
631
  const S = i.getUint8(e) & 31;
628
632
  e = e + 1;
@@ -630,13 +634,13 @@ const U = new TextDecoder("utf-8"), Z = (i, t) => {
630
634
  e = e + 2;
631
635
  const I = new Uint8Array(i.buffer.slice(e, e + D));
632
636
  e = e + D;
633
- const W = i.getUint8(e) & 31;
637
+ const B = i.getUint8(e) & 31;
634
638
  e = e + 1;
635
639
  const C = i.getUint16(e, !1);
636
640
  e = e + 2;
637
- const z = new Uint8Array(i.buffer.slice(e, e + C));
638
- return e = e + C, { frameType: o, codecID: n, avcPacketType: r, cts: d, data: c, version: f, codec: v, profile: g, compatibility: p, level: m, lengthSizeMinusOne: x, numOfSequenceParameterSets: S, sequenceParameterSetLength: D, sps: I, numOfPictureParameterSets: W, pictureParameterSetLength: C, pps: z };
639
- } else if (r === 1) {
641
+ const W = new Uint8Array(i.buffer.slice(e, e + C));
642
+ return e = e + C, { frameType: o, codecID: r, avcPacketType: n, cts: d, data: c, version: f, codec: v, profile: g, compatibility: p, level: m, lengthSizeMinusOne: x, numOfSequenceParameterSets: S, sequenceParameterSetLength: D, sps: I, numOfPictureParameterSets: B, pictureParameterSetLength: C, pps: W };
643
+ } else if (n === 1) {
640
644
  const f = [], g = e + s - 5;
641
645
  for (; e + 4 < g; ) {
642
646
  const p = i.getUint32(e, !1);
@@ -646,13 +650,13 @@ const U = new TextDecoder("utf-8"), Z = (i, t) => {
646
650
  const y = p - 1, k = new Uint8Array(i.buffer.slice(e, e + y));
647
651
  e = e + y, f.push({ size: p, header: m, payload: k });
648
652
  }
649
- return { frameType: o, codecID: n, avcPacketType: r, cts: d, data: c, nalus: f };
653
+ return { frameType: o, codecID: r, avcPacketType: n, cts: d, data: c, nalus: f };
650
654
  }
651
655
  break;
652
656
  default:
653
657
  throw new Error("Unsupported codecID");
654
658
  }
655
- return { frameType: o, codecID: n, avcPacketType: r, cts: d, data: c };
659
+ return { frameType: o, codecID: r, avcPacketType: n, cts: d, data: c };
656
660
  }, le = { getTagType: ne, getDataSize: de, getTimestamp: ce, getTimestampExtended: he, getStreamID: ue }, me = { parseAudio: fe, parseVideo: pe, parseMetaData: ge }, ye = { tagHeader: le, tagBody: me }, l = { header: ae, getPreviousTagSize: re, isSurplusTag: oe, tag: ye };
657
661
  class ke {
658
662
  parseSpeed = 8;
@@ -699,17 +703,17 @@ class ke {
699
703
  timestamp: l.tag.tagHeader.getTimestamp(a, o),
700
704
  timestampExtended: l.tag.tagHeader.getTimestampExtended(a, o),
701
705
  streamID: l.tag.tagHeader.getStreamID(a, o)
702
- }), e = (a, o, n, r) => {
706
+ }), e = (a, o, r, n) => {
703
707
  let d;
704
708
  switch (a) {
705
709
  case "script":
706
- d = l.tag.tagBody.parseMetaData(o, n);
710
+ d = l.tag.tagBody.parseMetaData(o, r);
707
711
  break;
708
712
  case "audio":
709
- d = l.tag.tagBody.parseAudio(o, n, r);
713
+ d = l.tag.tagBody.parseAudio(o, r, n);
710
714
  break;
711
715
  case "video":
712
- d = l.tag.tagBody.parseVideo(o, n, r);
716
+ d = l.tag.tagBody.parseVideo(o, r, n);
713
717
  break;
714
718
  }
715
719
  return d;
@@ -719,10 +723,10 @@ class ke {
719
723
  this.payload = this.payload.slice(this.offset), this.offset = 0;
720
724
  break;
721
725
  }
722
- const o = s(t, this.offset + 4), { tagType: n, dataSize: r } = o;
723
- if (!n) break;
724
- const d = e(n, t, this.offset + 4 + 11, r);
725
- this.tag = { header: o, body: d }, this.on.tag && this.on.tag(this.tag), this.offset = this.offset + 4 + 11 + r, await new Promise((u) => setTimeout(() => u(!0), this.parseSpeed));
726
+ const o = s(t, this.offset + 4), { tagType: r, dataSize: n } = o;
727
+ if (!r) break;
728
+ const d = e(r, t, this.offset + 4 + 11, n);
729
+ this.tag = { header: o, body: d }, this.on.tag && this.on.tag(this.tag), this.offset = this.offset + 4 + 11 + n, await new Promise((u) => setTimeout(() => u(!0), this.parseSpeed));
726
730
  }
727
731
  };
728
732
  }
@@ -840,8 +844,8 @@ class Te {
840
844
  if (!t) break;
841
845
  let { timestamp: s, bitmap: e } = t;
842
846
  if (this.cutOption) {
843
- const { sx: o = 0, sy: n = 0, sw: r = e.width, sh: d = e.height } = this.cutOption;
844
- e = await createImageBitmap(e, o, n, r, d);
847
+ const { sx: o = 0, sy: r = 0, sw: n = e.width, sh: d = e.height } = this.cutOption;
848
+ e = await createImageBitmap(e, o, r, n, d);
845
849
  }
846
850
  const a = this.calculateTimeUntilNextFrame(s);
847
851
  await new Promise((o) => setTimeout(() => o(!0), a)), this.drawImage({ timestamp: s, bitmap: e }), this.cutOption && e.close();
@@ -1,3 +1,3 @@
1
1
  (function(m,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(m=typeof globalThis<"u"?globalThis:m||self,b(m["pr-player"]={}))})(this,(function(m){"use strict";const b='(function(){"use strict";const U=new TextDecoder("utf-8"),H=(e,s)=>{const a=e.getUint8(s),t=a>>7&1,n=a>>5&3,r=a&31;return{forbidden_zero_bit:t,nal_ref_idc:n,nal_unit_type:r}},b=(e,s)=>e.getUint8(s),P=(e,s,a)=>{const t=new Uint8Array(e.buffer.slice(s,s+a));return U?.decode(t)||""},T=(e,s,a)=>{let t=s,n,r=0;switch(a){case 0:n=e.getFloat64(t,!1),r=8;break;case 1:n=!!e.getUint8(t),r=1;break;case 2:{n="";const o=e.getUint16(t,!1);t=t+2;const c=new Int8Array(e.buffer,t,o).filter(d=>d!==0);n=(U?.decode(c)||"").trim(),r=2+o}break;case 3:for(n={};t<e.byteLength;){const o=e.getUint16(t,!1);if(o===0)break;t=t+2;const c=P(e,t,o);t=t+o;const g=b(e,t);if(g===6)break;t=t+1;const d=T(e,t,g);t=t+d.length,n[c]=d.value,r=2+o+1+d.length}break;case 8:{n={};const o=e.getUint32(t,!1);t=t+4;for(let c=0;c<o;c++){const g=e.getUint16(t,!1);t=t+2;const d=P(e,t,g);t=t+g;const h=b(e,t);t=t+1;const l=T(e,t,h);t=t+l.length,n[d]=l.value,r=2+g+1+l.length}}break;case 10:{n=[];const o=e.getUint32(t,!1);t=t+4;for(let c=0;c<o;c++){const g=b(e,t);t=t+1;const d=T(e,t,g);t=t+d.length,n.push(d.value),r=1+d.length}}break}return{amfType:a,length:r,value:n}},m=(e,s)=>e.getUint8(s)<<16|e.getUint8(s+1)<<8|e.getUint8(s+2);var u={header:{getSignature:e=>{const s=new Int8Array(e.buffer.slice(0,3));return U?.decode(s)||""},getVersion:e=>e.getUint8(3),getFlags:e=>{const a=e.getUint8(0).toString(2).padStart(5,"0").split(""),[,,t,,n]=a;return{audio:n==="1",video:t==="1"}},getDataOffset:e=>e.getUint32(5)},getPreviousTagSize:(e,s)=>e.getUint32(s),isSurplusTag:(e,s)=>{let a=!0;const t=e.byteLength;if(s+4>t)a=!1;else if(s+4+11>t)a=!1;else{const n=m(e,s+4+1);s+4+11+n>t&&(a=!1)}return a},tag:{tagHeader:{getTagType:(e,s)=>{const a=e.getUint8(s);let t;switch(a){case 18:t="script";break;case 8:t="audio";break;case 9:t="video";break}return t},getDataSize:(e,s)=>m(e,s+1),getTimestamp:(e,s)=>m(e,s+4),getTimestampExtended:(e,s)=>e.getUint8(s+7),getStreamID:(e,s)=>m(e,s+8)},tagBody:{parseAudio:(e,s,a)=>{let t=s;const n=e.getUint8(t),r=n>>4&15,i=n>>2&3,o=n>>1&1,c=n&1;t=t+1;const g=e.getUint8(t);t=t+1;const d=a-2,h=new Uint8Array(e.buffer.slice(t,t+d));if(r===10&&g===0){const l=e.getUint8(t),p=e.getUint8(t+1),f=(l&248)>>3,y=(l&7)<<1|p>>7,S=(p&120)>>3,A=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],D=`mp4a.40.${f}`,z=A[y];return{soundFormat:r,soundRate:i,soundSize:o,soundType:c,accPacketType:g,data:h,audioObjectType:f,samplingFrequencyIndex:y,channelConfiguration:S,codec:D,sampleRate:z}}return{soundFormat:r,soundRate:i,soundSize:o,soundType:c,accPacketType:g,data:h}},parseVideo:(e,s,a)=>{let t=s;const n=e.getUint8(t),r=n>>4&15,i=n&15;t=t+1;const o=e.getUint8(t);t=t+1;const c=m(e,t);t=t+3;const g=a-5,d=new Uint8Array(e.buffer.slice(t,t+g));switch(i){case 7:if(o===0){const h=e.getUint8(t);if(t=t+1,h!==1)throw new Error("Invalid AVC version");const l=e.getUint8(t)&255;t=t+1;const p=e.getUint8(t)&255;t=t+1;const f=e.getUint8(t)&255;t=t+1;const A=`avc1.${Array.from([l,p,f],E=>E.toString(16).padStart(2,"0")).join("")}`,D=(e.getUint8(t)&3)-1;t=t+1;const z=e.getUint8(t)&31;t=t+1;const _=e.getUint16(t,!1);t=t+2;const O=new Uint8Array(e.buffer.slice(t,t+_));t=t+_;const I=e.getUint8(t)&31;t=t+1;const x=e.getUint16(t,!1);t=t+2;const M=new Uint8Array(e.buffer.slice(t,t+x));return t=t+x,{frameType:r,codecID:i,avcPacketType:o,cts:c,data:d,version:h,codec:A,profile:l,compatibility:p,level:f,lengthSizeMinusOne:D,numOfSequenceParameterSets:z,sequenceParameterSetLength:_,sps:O,numOfPictureParameterSets:I,pictureParameterSetLength:x,pps:M}}else if(o===1){const h=[],l=t+a-5;for(;t+4<l;){const p=e.getUint32(t,!1);t=t+4;const f=H(e,t);t=t+1;const y=p-1,S=new Uint8Array(e.buffer.slice(t,t+y));t=t+y,h.push({size:p,header:f,payload:S})}return{frameType:r,codecID:i,avcPacketType:o,cts:c,data:d,nalus:h}}break;default:throw new Error("Unsupported codecID")}return{frameType:r,codecID:i,avcPacketType:o,cts:c,data:d}},parseMetaData:(e,s)=>{let a=s;{if(e.getUint8(a)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");a=a+1}const t=e.getUint16(a,!1);a=a+2;{const i=new Int8Array(e.buffer.slice(a,a+t));if((U?.decode(i)||"")!=="onMetaData")throw new Error("Expected \'onMetaData\' string");a=a+t}const n=b(e,a);return a=a+1,T(e,a,n).value}}}};class L{parseSpeed=8;pendingPayloads=[];payload=new Uint8Array(0);offset=0;is_parsing=!1;header;tag;on={};constructor(){}init=()=>{this.destroy()};push=s=>{this.pendingPayloads.push(s),this.is_parsing||this.parse()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.offset=0,this.is_parsing=!1,this.header=void 0,this.tag=void 0};parse=async()=>{for(this.is_parsing=!0;;){const s=this.pendingPayloads.shift();if(!s)break;const a=new Uint8Array(this.payload.byteLength+s.byteLength);a.set(this.payload,0),a.set(s,this.payload.byteLength),this.payload=a;const t=new DataView(this.payload.buffer);this.header||this.parseHeader(t),await this.parseTag(t)}this.is_parsing=!1};parseHeader=s=>(this.header={signature:u.header.getSignature(s),version:u.header.getVersion(s),flags:u.header.getFlags(s),dataOffset:u.header.getDataOffset(s)},this.offset=this.header?.dataOffset,this.on.header&&this.on.header(this.header),this.header);parseTag=async s=>{const a=(n,r)=>({tagType:u.tag.tagHeader.getTagType(n,r),dataSize:u.tag.tagHeader.getDataSize(n,r),timestamp:u.tag.tagHeader.getTimestamp(n,r),timestampExtended:u.tag.tagHeader.getTimestampExtended(n,r),streamID:u.tag.tagHeader.getStreamID(n,r)}),t=(n,r,i,o)=>{let c;switch(n){case"script":c=u.tag.tagBody.parseMetaData(r,i);break;case"audio":c=u.tag.tagBody.parseAudio(r,i,o);break;case"video":c=u.tag.tagBody.parseVideo(r,i,o);break}return c};for(;this.offset<s.byteLength;){if(u.isSurplusTag(s,this.offset)===!1){this.payload=this.payload.slice(this.offset),this.offset=0;break}const r=a(s,this.offset+4),{tagType:i,dataSize:o}=r;if(!i)break;const c=t(i,s,this.offset+4+11,o);this.tag={header:r,body:c},this.on.tag&&this.on.tag(this.tag),this.offset=this.offset+4+11+o,await new Promise(g=>setTimeout(()=>g(!0),this.parseSpeed))}}}const k=new L;k.on.header=e=>postMessage({action:"onHeader",data:e}),k.on.tag=e=>postMessage({action:"onTag",data:e}),onmessage=e=>{const{action:s,data:a}=e.data,t=k[s];t&&t(a)}})();\n',M=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",b],{type:"text/javascript;charset=utf-8"});function E(i){let t;try{if(t=M&&(self.URL||self.webkitURL).createObjectURL(M),!t)throw"";const s=new Worker(t,{name:i?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(b),{name:i?.name})}}class P{worker=new E;on={};constructor(){this.worker.onmessage=t=>{const{action:s,data:e}=t.data;s==="onHeader"&&this.on.header&&this.on.header(e),s==="onTag"&&this.on.tag&&this.on.tag(e)}}init=()=>this.worker.postMessage({action:"init"});push=t=>this.worker.postMessage({action:"push",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}const G=`(function(){"use strict";class r{audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;on={audio:{},video:{}};constructor(){}audio={init:i=>{this.audio.destroy(),this.audioDecoderConfig={...i},this.audioDecoder=new AudioDecoder({output:e=>{this.on.audio.decode&&this.on.audio.decode(e)},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)},decode:i=>{if(!this.audioDecoder)return;const e=new EncodedAudioChunk(i);this.audioDecoder.decode(e)},flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={init:i=>{this.video.destroy(),this.videoDecoderConfig={...i},this.videoDecoder=new VideoDecoder({output:async e=>{const d=await createImageBitmap(e),s=e.timestamp;e.close(),d.width>0&&d.height>0?this.on.video.decode&&this.on.video.decode({timestamp:s,bitmap:d}):d.close()},error:e=>{this.on.video.error&&this.on.video.error(e)}}),this.videoDecoder.configure(this.videoDecoderConfig)},decode:i=>{if(this.videoDecoder&&(i.type==="key"&&(this.hasKeyFrame=!0),this.hasKeyFrame&&this.videoDecoder.decodeQueueSize<2)){const e=new EncodedVideoChunk(i);this.videoDecoder.decode(e)}},flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}}const t=new r;t.on.audio.decode=o=>postMessage({type:"audio",action:"onDecode",data:o}),t.on.audio.error=o=>postMessage({type:"audio",action:"onError",data:o}),t.on.video.decode=o=>postMessage({type:"video",action:"onDecode",data:o}),t.on.video.error=o=>postMessage({type:"video",action:"onError",data:o}),onmessage=o=>{const{type:i,action:e,data:d}=o.data,s=t[i][e];s&&s(d)}})();
2
2
  `,L=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",G],{type:"text/javascript;charset=utf-8"});function _(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(G),{name:i?.name})}}class N{worker=new _;on={audio:{},video:{}};constructor(){this.worker.onmessage=t=>{const{type:s,action:e,data:a}=t.data;switch(s){case"audio":e==="onDecode"&&this.on.audio.decode&&this.on.audio.decode(a),e==="onError"&&this.on.audio.error&&this.on.audio.error(a);break;case"video":e==="onDecode"&&this.on.video.decode&&this.on.video.decode(a),e==="onError"&&this.on.video.error&&this.on.video.error(a);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 F=`(function(){"use strict";class r{isRendering=!1;pendingFrames=[];offscreenCanvas;writable;writer;ctx;cutOption;baseTime=0;pause=!1;shader=["stream"];constructor(){}init=({offscreenCanvas:e,baseTime:t=performance.timeOrigin,writable:i})=>{this.destroy(),this.offscreenCanvas=e,this.writable=i,this.writer=this.writable.getWriter(),this.ctx=this.offscreenCanvas.getContext("2d"),this.baseTime=t};setShader=e=>{this.shader=e};setSize=({width:e,height:t})=>{this.offscreenCanvas&&(this.offscreenCanvas.width=e,this.offscreenCanvas.height=t)};destroy=()=>{this.isRendering=!1,this.pendingFrames=[],this.offscreenCanvas=void 0,this.ctx=void 0,this.baseTime=0};push=e=>{this.pendingFrames.push(e),this.isRendering===!1&&setTimeout(this.renderFrame,0)};setCut=e=>{this.cutOption=e};setPause=e=>{this.pause=e,this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=e=>{const t=performance.timeOrigin+performance.now(),s=this.baseTime+e/1e3-t;return Math.max(0,s)};renderFrame=async()=>{for(this.isRendering=!0;;){const e=this.pendingFrames.shift();if(!e)break;let{timestamp:t,bitmap:i}=e;if(this.cutOption){const{sx:a=0,sy:c=0,sw:m=i.width,sh:o=i.height}=this.cutOption;i=await createImageBitmap(i,a,c,m,o)}const s=this.calculateTimeUntilNextFrame(t);await new Promise(a=>setTimeout(()=>a(!0),s)),this.drawImage({timestamp:t,bitmap:i}),this.cutOption&&i.close()}this.isRendering=!1};drawImage=e=>{if(this.pause!==!0){if(this.shader.includes("stream")){const t=new VideoFrame(e.bitmap,{timestamp:e.timestamp});this.writer.write(t),t.close()}this.shader.includes("canvas")&&this.ctx&&this.offscreenCanvas&&this.ctx.drawImage(e.bitmap,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height)}}}const h=new r;onmessage=n=>{const{action:e,data:t}=n.data,i=h[e];i&&i(t)}})();
3
- `,O=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",F],{type:"text/javascript;charset=utf-8"});function V(i){let t;try{if(t=O&&(self.URL||self.webkitURL).createObjectURL(O),!t)throw"";const s=new Worker(t,{name:i?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(F),{name:i?.name})}}class W{worker=new V;constructor(){}init=({offscreenCanvas:t,baseTime:s=0,writable:e})=>this.worker.postMessage({action:"init",data:{offscreenCanvas:t,baseTime:s,writable:e}},[t,e]);setShader=t=>this.worker.postMessage({action:"setShader",data:t});setSize=({width:t,height:s})=>this.worker.postMessage({action:"setSize",data:{width:t,height:s}});push=t=>this.worker.postMessage({action:"push",data:t});setCut=async t=>this.worker.postMessage({action:"setCut",data:t});setPause=t=>this.worker.postMessage({action:"setPause",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}var j=Object.defineProperty,H=(i,t,s)=>t in i?j(i,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):i[t]=s,c=(i,t,s)=>H(i,typeof t!="symbol"?t+"":t,s);class ${constructor(t,s){c(this,"inputStream",new MediaStream),c(this,"outputStream",new MediaStream),c(this,"inputGain",1),c(this,"enhanceGain",1),c(this,"bgsGain",1),c(this,"bgmGain",1),c(this,"outputGain",1),c(this,"mixAudioMap",new Map),c(this,"audioContext",new AudioContext),c(this,"sourceNode"),c(this,"inputGainNode"),c(this,"enhanceGainNode"),c(this,"bgsGainNode"),c(this,"bgmGainNode"),c(this,"analyserNode"),c(this,"analyserArrayData"),c(this,"outputGainNode"),c(this,"destinationNode"),c(this,"filterStream",e=>e),c(this,"stop",()=>{{const e=this.inputStream.getTracks();for(const a of e)a.stop(),this.inputStream.removeTrack(a)}}),c(this,"getStream",()=>this.filterStream(this.outputStream)),c(this,"setMute",(e=!0)=>{e?this.analyserNode.disconnect(this.outputGainNode):this.analyserNode.connect(this.outputGainNode)}),c(this,"setInputGain",e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),c(this,"setEnhanceGain",async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)}),c(this,"setBgsGain",e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),c(this,"setBgmGain",e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),c(this,"setOutputGain",e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)}),c(this,"getVolume",()=>{const{analyserNode:e,analyserArrayData:a}=this;e.getByteFrequencyData(a);let o=0;for(let n=0;n<a.length;n++)o+=a[n];return Math.ceil(o/a.length)}),c(this,"mixAudio",(e,a="bgm")=>new Promise(async(o,n)=>{try{{const u=this.mixAudioMap.get(a);u&&u.stop()}const r=a==="bgs"?this.bgsGainNode:this.bgmGainNode,d=this.audioContext.createBufferSource();this.mixAudioMap.set(a,d),d.buffer=e,d.connect(r),d.onended=()=>{d.disconnect(r),this.mixAudioMap.delete(a),o(!0)},d.start(0)}catch(r){n(r)}})),c(this,"mixAudioStop",e=>{const a=this.mixAudioMap.get(e);a?.stop()}),c(this,"changeMix",(e,a)=>{const o=e==="bgs"?this.bgsGainNode:this.bgmGainNode;a?o.connect(this.destinationNode):o.disconnect(this.destinationNode)}),s&&(this.audioContext=s),this.inputStream=t,this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.inputGainNode=this.audioContext.createGain(),this.inputGainNode.gain.setValueAtTime(this.inputGain,this.audioContext.currentTime),this.enhanceGainNode=this.audioContext.createGain(),this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime),this.bgsGainNode=this.audioContext.createGain(),this.bgsGainNode.gain.setValueAtTime(this.bgsGain,this.audioContext.currentTime),this.bgmGainNode=this.audioContext.createGain(),this.bgmGainNode.gain.setValueAtTime(this.bgmGain,this.audioContext.currentTime),this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=512,this.analyserArrayData=new Uint8Array(this.analyserNode.frequencyBinCount),this.outputGainNode=this.audioContext.createGain(),this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputStream=this.destinationNode.stream;{const{sourceNode:e,inputGainNode:a,enhanceGainNode:o,bgsGainNode:n,bgmGainNode:r,analyserNode:d,outputGainNode:u,destinationNode:h}=this;e.connect(a),a.connect(o),o.connect(d),n.connect(d),r.connect(d),o.connect(h),n.connect(h),r.connect(h),d.connect(u),u.connect(this.audioContext.destination)}this.setMute(!0),this.audioContext.resume()}}const q=async(i,t)=>{try{const{format:s,numberOfChannels:e,numberOfFrames:a,sampleRate:o}=t,n=i.createBuffer(e,a,o);for(let r=0;r<e;r++){const d=t.allocationSize({planeIndex:r}),u=new Uint8Array(d);t.copyTo(u,{planeIndex:r});const h=new DataView(u.buffer),f=n.getChannelData(r);for(let g=0;g<a;g++){let p;switch(s){case"s16":case"s16-planar":p=h.getInt16(g*2,!0)/32768;break;case"f32":case"f32-planar":p=h.getFloat32(g*4,!0);break;case"u8":case"u8-planar":p=(h.getUint8(g)-128)/128;break;default:throw new Error(`Unsupported audio format: ${s}`)}f[g]=Math.max(-1,Math.min(1,p))}}return n}catch(s){throw console.error("Failed to convert AudioData to AudioBuffer:",s),s}};class K{prAudioStream;audioContext;destination;stream=new MediaStream;nextStartTime=0;pendingSources=[];constructor(){}init=t=>{t||(t=new(window.AudioContext||window.webkitAudioContext)),this.audioContext=t,this.destination=this.audioContext.createMediaStreamDestination(),this.stream=new MediaStream,this.stream.addTrack(this.destination.stream.getAudioTracks()[0]),this.prAudioStream=new $(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(t){try{if(!this.audioContext||!this.destination)return;const s=await q(this.audioContext,t);if(!s)return;const e=this.audioContext.createBufferSource();e.buffer=s,e.connect(this.destination);const a=Math.max(this.nextStartTime,this.audioContext.currentTime);this.nextStartTime=a+s.duration,e.start(a),this.pendingSources.push(e),e.onended=()=>{this.pendingSources=this.pendingSources.filter(o=>o!==e)},this.audioContext.state==="suspended"&&await this.audioContext.resume()}finally{t.close()}}getStream=()=>this.prAudioStream?.getStream();destroy(){this.audioContext?.close(),this.audioContext=void 0,this.destination=void 0,this.nextStartTime=0,this.prAudioStream?.stop(),this.pendingSources.forEach(t=>t.stop()),this.pendingSources=[]}}class Q{#t={timeout:5*1e3};#e;constructor(t={}){this.#t={...this.#t,...t}}check=(t,s)=>new Promise(async(e,a)=>{this.stop(),this.#e=new AbortController;const o=window.setTimeout(()=>{this.#e?.abort("Timeout."),a({status:"timeout",reason:""})},this.#t.timeout);try{const n=await fetch(t,{...s,method:"HEAD",signal:this.#e?.signal});n.status===200?e({status:"successed",reason:""}):a({status:"failed",reason:`${n.status}`})}catch(n){a({status:"error",reason:n.message})}clearTimeout(o)});request=async(t,s)=>new Promise(async(e,a)=>{try{await this.check(t,s),this.#e=new AbortController;const o=await fetch(t,{...s,signal:this.#e?.signal});e(o)}catch(o){this.stop(),a(o)}});stop=()=>{this.#e?.signal.aborted===!1&&this.#e.abort("Actively stop.")}}const I=i=>{const t=i?.getTracks()||[];for(const s of t)s.stop()},z=i=>{const t=new W,s=document.createElement("canvas"),e=s.transferControlToOffscreen(),a=new MediaStreamTrackGenerator({kind:"video"}),o=new MediaStream([a]),n=()=>{t.destroy(),I(o)};return t.init({offscreenCanvas:e,baseTime:i,writable:a.writable}),{worker:t,canvas:s,stream:o,destroy:n}};class J{prFetch=new Q;demuxerWorker;decoderWorker;audioPlayer;renderWorker;renderBaseTime=0;stream;canvas;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(){}init=()=>{this.initDemuxer(),this.initDecoder(),this.audioPlayer=new K,this.audioPlayer.init(),this.initRender()};start=async t=>{try{this.stop(),this.renderBaseTime=new Date().getTime(),this.init();const e=(await this.prFetch.request(t)).body?.getReader();if(!e)throw new Error("Reader is error.");for(;;){const{done:a,value:o}=await e.read();if(o&&this.demuxerWorker?.push(o),a)break}}catch{}};stop=()=>{this.prFetch.stop(),this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy(),I(this.stream);const t=[...this.cutRenders.keys()];for(const s of t)this.cut.remove(s);this.audioPlayer?.destroy(),this.renderBaseTime=0,this.canvas=void 0};onTag=t=>{if(!this.decoderWorker)return;const{header:s,body:e}=t,{tagType:a,timestamp:o}=s;switch(a){case"script":{const{width:n,height:r}=e;this.renderWorker?.setSize({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:u,channelConfiguration:h}=e,f={codec:d,sampleRate:u,numberOfChannels:h,description:new Uint8Array([])};this.decoderWorker.audio.init(f)}else n===1&&this.decoderWorker.audio.decode({type:"key",timestamp:o*1,data:r});this.on.demuxer.audio&&this.on.demuxer.audio(t)}break;case"video":{const{avcPacketType:n,frameType:r,data:d,nalus:u=[]}=e;if(n===0){const{codec:h,data:f}=e;this.decoderWorker.video.init({codec:h,description:f})}else if(n===1){const h=r===1?"key":"delta";this.decoderWorker.video.decode({type:h,timestamp:o*1e3,data:d});for(const f of u){const{header:g,payload:p}=f,{nal_unit_type:y}=g;y===6&&this.on.demuxer.sei&&this.on.demuxer.sei(p)}}this.on.demuxer.video&&this.on.demuxer.video(t)}break}};initDemuxer=()=>{this.demuxerWorker=new P,this.demuxerWorker.init(),this.demuxerWorker.on.tag=this.onTag};initDecoder=()=>{this.decoderWorker=new N,this.decoderWorker.on.audio.decode=t=>{this.audioPlayer?.push(t),this.on.decoder.audio&&this.on.decoder.audio(t)},this.decoderWorker.on.audio.error=t=>{this.stop(),this.on.error&&this.on.error(t)},this.decoderWorker.on.video.decode=async t=>{this.renderWorker?.push(t);const s=[...this.cutRenders.keys()];for(const e of s)this.cutRenders.get(e)?.worker.push(t);this.on.decoder.video&&this.on.decoder.video(t),t.bitmap.close()},this.decoderWorker.on.video.error=t=>{this.stop(),this.on.error&&this.on.error(t)}};initRender=()=>{const{worker:t,canvas:s,stream:e}=z(this.renderBaseTime);this.renderWorker=t,this.canvas=s,this.stream=e,this.renderWorker.setPause(!1)};getCanvas=()=>this.canvas;getStream=()=>this.stream;getCutCanvas=t=>this.cutRenders.get(t)?.canvas;getCutStream=t=>this.cutRenders.get(t)?.stream;setPause=t=>{this.renderWorker?.setPause(t)};setShader=t=>{this.renderWorker?.setShader(t)};setMute=t=>this.audioPlayer?.prAudioStream?.setMute(t);cut={create:(t,s)=>{let e=this.cutRenders.get(t);return e?(e.worker.setCut(s),e.worker.setPause(!1),e):(e=z(this.renderBaseTime),e.worker.setCut(s),this.cutRenders.set(t,e),e)},setPause:(t,s)=>{this.cutRenders.get(t)?.worker.setPause(s)},setShader:(t,s)=>{this.cutRenders.get(t)?.worker.setShader(s)},remove:t=>{this.cutRenders.get(t)?.destroy(),this.cutRenders.delete(t)}}}const T=new TextDecoder("utf-8"),X=(i,t)=>{const s=i.getUint8(t),e=s>>7&1,a=s>>5&3,o=s&31;return{forbidden_zero_bit:e,nal_ref_idc:a,nal_unit_type:o}},U=(i,t)=>i.getUint8(t),B=(i,t,s)=>{const e=new Uint8Array(i.buffer.slice(t,t+s));return T?.decode(e)||""},v=(i,t,s)=>{let e=t,a,o=0;switch(s){case 0:a=i.getFloat64(e,!1),o=8;break;case 1:a=!!i.getUint8(e),o=1;break;case 2:{a="";const r=i.getUint16(e,!1);e=e+2;const d=new Int8Array(i.buffer,e,r).filter(h=>h!==0);a=(T?.decode(d)||"").trim(),o=2+r}break;case 3:for(a={};e<i.byteLength;){const r=i.getUint16(e,!1);if(r===0)break;e=e+2;const d=B(i,e,r);e=e+r;const u=U(i,e);if(u===6)break;e=e+1;const h=v(i,e,u);e=e+h.length,a[d]=h.value,o=2+r+1+h.length}break;case 8:{a={};const r=i.getUint32(e,!1);e=e+4;for(let d=0;d<r;d++){const u=i.getUint16(e,!1);e=e+2;const h=B(i,e,u);e=e+u;const f=U(i,e);e=e+1;const g=v(i,e,f);e=e+g.length,a[h]=g.value,o=2+u+1+g.length}}break;case 10:{a=[];const r=i.getUint32(e,!1);e=e+4;for(let d=0;d<r;d++){const u=U(i,e);e=e+1;const h=v(i,e,u);e=e+h.length,a.push(h.value),o=1+h.length}}break}return{amfType:s,length:o,value:a}},w=(i,t)=>i.getUint8(t)<<16|i.getUint8(t+1)<<8|i.getUint8(t+2),l={header:{getSignature:i=>{const t=new Int8Array(i.buffer.slice(0,3));return T?.decode(t)||""},getVersion:i=>i.getUint8(3),getFlags:i=>{const s=i.getUint8(0).toString(2).padStart(5,"0").split(""),[,,e,,a]=s;return{audio:a==="1",video:e==="1"}},getDataOffset:i=>i.getUint32(5)},getPreviousTagSize:(i,t)=>i.getUint32(t),isSurplusTag:(i,t)=>{let s=!0;const e=i.byteLength;if(t+4>e)s=!1;else if(t+4+11>e)s=!1;else{const a=w(i,t+4+1);t+4+11+a>e&&(s=!1)}return s},tag:{tagHeader:{getTagType:(i,t)=>{const s=i.getUint8(t);let e;switch(s){case 18:e="script";break;case 8:e="audio";break;case 9:e="video";break}return e},getDataSize:(i,t)=>w(i,t+1),getTimestamp:(i,t)=>w(i,t+4),getTimestampExtended:(i,t)=>i.getUint8(t+7),getStreamID:(i,t)=>w(i,t+8)},tagBody:{parseAudio:(i,t,s)=>{let e=t;const a=i.getUint8(e),o=a>>4&15,n=a>>2&3,r=a>>1&1,d=a&1;e=e+1;const u=i.getUint8(e);e=e+1;const h=s-2,f=new Uint8Array(i.buffer.slice(e,e+h));if(o===10&&u===0){const g=i.getUint8(e),p=i.getUint8(e+1),y=(g&248)>>3,k=(g&7)<<1|p>>7,S=(p&120)>>3,x=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],D=`mp4a.40.${y}`,C=x[k];return{soundFormat:o,soundRate:n,soundSize:r,soundType:d,accPacketType:u,data:f,audioObjectType:y,samplingFrequencyIndex:k,channelConfiguration:S,codec:D,sampleRate:C}}return{soundFormat:o,soundRate:n,soundSize:r,soundType:d,accPacketType:u,data:f}},parseVideo:(i,t,s)=>{let e=t;const a=i.getUint8(e),o=a>>4&15,n=a&15;e=e+1;const r=i.getUint8(e);e=e+1;const d=w(i,e);e=e+3;const u=s-5,h=new Uint8Array(i.buffer.slice(e,e+u));switch(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 p=i.getUint8(e)&255;e=e+1;const y=i.getUint8(e)&255;e=e+1;const x=`avc1.${Array.from([g,p,y],ae=>ae.toString(16).padStart(2,"0")).join("")}`,D=(i.getUint8(e)&3)-1;e=e+1;const C=i.getUint8(e)&31;e=e+1;const A=i.getUint16(e,!1);e=e+2;const te=new Uint8Array(i.buffer.slice(e,e+A));e=e+A;const se=i.getUint8(e)&31;e=e+1;const R=i.getUint16(e,!1);e=e+2;const ie=new Uint8Array(i.buffer.slice(e,e+R));return e=e+R,{frameType:o,codecID:n,avcPacketType:r,cts:d,data:h,version:f,codec:x,profile:g,compatibility:p,level:y,lengthSizeMinusOne:D,numOfSequenceParameterSets:C,sequenceParameterSetLength:A,sps:te,numOfPictureParameterSets:se,pictureParameterSetLength:R,pps:ie}}else if(r===1){const f=[],g=e+s-5;for(;e+4<g;){const p=i.getUint32(e,!1);e=e+4;const y=X(i,e);e=e+1;const k=p-1,S=new Uint8Array(i.buffer.slice(e,e+k));e=e+k,f.push({size:p,header:y,payload:S})}return{frameType:o,codecID:n,avcPacketType:r,cts:d,data:h,nalus:f}}break;default:throw new Error("Unsupported codecID")}return{frameType:o,codecID:n,avcPacketType:r,cts:d,data:h}},parseMetaData:(i,t)=>{let s=t;{if(i.getUint8(s)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");s=s+1}const e=i.getUint16(s,!1);s=s+2;{const n=new Int8Array(i.buffer.slice(s,s+e));if((T?.decode(n)||"")!=="onMetaData")throw new Error("Expected 'onMetaData' string");s=s+e}const a=U(i,s);return s=s+1,v(i,s,a).value}}}};class Y{parseSpeed=8;pendingPayloads=[];payload=new Uint8Array(0);offset=0;is_parsing=!1;header;tag;on={};constructor(){}init=()=>{this.destroy()};push=t=>{this.pendingPayloads.push(t),this.is_parsing||this.parse()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.offset=0,this.is_parsing=!1,this.header=void 0,this.tag=void 0};parse=async()=>{for(this.is_parsing=!0;;){const t=this.pendingPayloads.shift();if(!t)break;const s=new Uint8Array(this.payload.byteLength+t.byteLength);s.set(this.payload,0),s.set(t,this.payload.byteLength),this.payload=s;const e=new DataView(this.payload.buffer);this.header||this.parseHeader(e),await this.parseTag(e)}this.is_parsing=!1};parseHeader=t=>(this.header={signature:l.header.getSignature(t),version:l.header.getVersion(t),flags:l.header.getFlags(t),dataOffset:l.header.getDataOffset(t)},this.offset=this.header?.dataOffset,this.on.header&&this.on.header(this.header),this.header);parseTag=async t=>{const s=(a,o)=>({tagType:l.tag.tagHeader.getTagType(a,o),dataSize:l.tag.tagHeader.getDataSize(a,o),timestamp:l.tag.tagHeader.getTimestamp(a,o),timestampExtended:l.tag.tagHeader.getTimestampExtended(a,o),streamID:l.tag.tagHeader.getStreamID(a,o)}),e=(a,o,n,r)=>{let d;switch(a){case"script":d=l.tag.tagBody.parseMetaData(o,n);break;case"audio":d=l.tag.tagBody.parseAudio(o,n,r);break;case"video":d=l.tag.tagBody.parseVideo(o,n,r);break}return d};for(;this.offset<t.byteLength;){if(l.isSurplusTag(t,this.offset)===!1){this.payload=this.payload.slice(this.offset),this.offset=0;break}const o=s(t,this.offset+4),{tagType:n,dataSize:r}=o;if(!n)break;const d=e(n,t,this.offset+4+11,r);this.tag={header:o,body:d},this.on.tag&&this.on.tag(this.tag),this.offset=this.offset+4+11+r,await new Promise(u=>setTimeout(()=>u(!0),this.parseSpeed))}}}class Z{audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;on={audio:{},video:{}};constructor(){}audio={init:t=>{this.audio.destroy(),this.audioDecoderConfig={...t},this.audioDecoder=new AudioDecoder({output:s=>{this.on.audio.decode&&this.on.audio.decode(s)},error:s=>{this.on.audio.error&&this.on.audio.error(s)}}),this.audioDecoder.configure(this.audioDecoderConfig)},decode:t=>{if(!this.audioDecoder)return;const s=new EncodedAudioChunk(t);this.audioDecoder.decode(s)},flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={init:t=>{this.video.destroy(),this.videoDecoderConfig={...t},this.videoDecoder=new VideoDecoder({output:async s=>{const e=await createImageBitmap(s),a=s.timestamp;s.close(),e.width>0&&e.height>0?this.on.video.decode&&this.on.video.decode({timestamp:a,bitmap:e}):e.close()},error:s=>{this.on.video.error&&this.on.video.error(s)}}),this.videoDecoder.configure(this.videoDecoderConfig)},decode:t=>{if(this.videoDecoder&&(t.type==="key"&&(this.hasKeyFrame=!0),this.hasKeyFrame&&this.videoDecoder.decodeQueueSize<2)){const s=new EncodedVideoChunk(t);this.videoDecoder.decode(s)}},flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}}class ee{isRendering=!1;pendingFrames=[];offscreenCanvas;writable;writer;ctx;cutOption;baseTime=0;pause=!1;shader=["stream"];constructor(){}init=({offscreenCanvas:t,baseTime:s=performance.timeOrigin,writable:e})=>{this.destroy(),this.offscreenCanvas=t,this.writable=e,this.writer=this.writable.getWriter(),this.ctx=this.offscreenCanvas.getContext("2d"),this.baseTime=s};setShader=t=>{this.shader=t};setSize=({width:t,height:s})=>{this.offscreenCanvas&&(this.offscreenCanvas.width=t,this.offscreenCanvas.height=s)};destroy=()=>{this.isRendering=!1,this.pendingFrames=[],this.offscreenCanvas=void 0,this.ctx=void 0,this.baseTime=0};push=t=>{this.pendingFrames.push(t),this.isRendering===!1&&setTimeout(this.renderFrame,0)};setCut=t=>{this.cutOption=t};setPause=t=>{this.pause=t,this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=t=>{const s=performance.timeOrigin+performance.now(),a=this.baseTime+t/1e3-s;return Math.max(0,a)};renderFrame=async()=>{for(this.isRendering=!0;;){const t=this.pendingFrames.shift();if(!t)break;let{timestamp:s,bitmap:e}=t;if(this.cutOption){const{sx:o=0,sy:n=0,sw:r=e.width,sh:d=e.height}=this.cutOption;e=await createImageBitmap(e,o,n,r,d)}const a=this.calculateTimeUntilNextFrame(s);await new Promise(o=>setTimeout(()=>o(!0),a)),this.drawImage({timestamp:s,bitmap:e}),this.cutOption&&e.close()}this.isRendering=!1};drawImage=t=>{if(this.pause!==!0){if(this.shader.includes("stream")){const s=new VideoFrame(t.bitmap,{timestamp:t.timestamp});this.writer.write(s),s.close()}this.shader.includes("canvas")&&this.ctx&&this.offscreenCanvas&&this.ctx.drawImage(t.bitmap,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height)}}}m.Decoder=Z,m.DecoderWorker=N,m.Demuxer=Y,m.DemuxerWorker=P,m.PrPlayer=J,m.Render=ee,m.RenderWorker=W,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
3
+ `,O=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",F],{type:"text/javascript;charset=utf-8"});function V(i){let t;try{if(t=O&&(self.URL||self.webkitURL).createObjectURL(O),!t)throw"";const s=new Worker(t,{name:i?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(F),{name:i?.name})}}class W{worker=new V;constructor(){}init=({offscreenCanvas:t,baseTime:s=0,writable:e})=>this.worker.postMessage({action:"init",data:{offscreenCanvas:t,baseTime:s,writable:e}},[t,e]);setShader=t=>this.worker.postMessage({action:"setShader",data:t});setSize=({width:t,height:s})=>this.worker.postMessage({action:"setSize",data:{width:t,height:s}});push=t=>this.worker.postMessage({action:"push",data:t});setCut=async t=>this.worker.postMessage({action:"setCut",data:t});setPause=t=>this.worker.postMessage({action:"setPause",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}var j=Object.defineProperty,H=(i,t,s)=>t in i?j(i,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):i[t]=s,c=(i,t,s)=>H(i,typeof t!="symbol"?t+"":t,s);class ${constructor(t,s){c(this,"inputStream",new MediaStream),c(this,"outputStream",new MediaStream),c(this,"inputGain",1),c(this,"enhanceGain",1),c(this,"bgsGain",1),c(this,"bgmGain",1),c(this,"outputGain",1),c(this,"mixAudioMap",new Map),c(this,"audioContext",new AudioContext),c(this,"sourceNode"),c(this,"inputGainNode"),c(this,"enhanceGainNode"),c(this,"bgsGainNode"),c(this,"bgmGainNode"),c(this,"analyserNode"),c(this,"analyserArrayData"),c(this,"outputGainNode"),c(this,"destinationNode"),c(this,"filterStream",e=>e),c(this,"stop",()=>{{const e=this.inputStream.getTracks();for(const a of e)a.stop(),this.inputStream.removeTrack(a)}}),c(this,"getStream",()=>this.filterStream(this.outputStream)),c(this,"setMute",(e=!0)=>{e?this.analyserNode.disconnect(this.outputGainNode):this.analyserNode.connect(this.outputGainNode)}),c(this,"setInputGain",e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),c(this,"setEnhanceGain",async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)}),c(this,"setBgsGain",e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),c(this,"setBgmGain",e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),c(this,"setOutputGain",e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)}),c(this,"getVolume",()=>{const{analyserNode:e,analyserArrayData:a}=this;e.getByteFrequencyData(a);let o=0;for(let r=0;r<a.length;r++)o+=a[r];return Math.ceil(o/a.length)}),c(this,"mixAudio",(e,a="bgm")=>new Promise(async(o,r)=>{try{{const u=this.mixAudioMap.get(a);u&&u.stop()}const n=a==="bgs"?this.bgsGainNode:this.bgmGainNode,d=this.audioContext.createBufferSource();this.mixAudioMap.set(a,d),d.buffer=e,d.connect(n),d.onended=()=>{d.disconnect(n),this.mixAudioMap.delete(a),o(!0)},d.start(0)}catch(n){r(n)}})),c(this,"mixAudioStop",e=>{const a=this.mixAudioMap.get(e);a?.stop()}),c(this,"changeMix",(e,a)=>{const o=e==="bgs"?this.bgsGainNode:this.bgmGainNode;a?o.connect(this.destinationNode):o.disconnect(this.destinationNode)}),s&&(this.audioContext=s),this.inputStream=t,this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.inputGainNode=this.audioContext.createGain(),this.inputGainNode.gain.setValueAtTime(this.inputGain,this.audioContext.currentTime),this.enhanceGainNode=this.audioContext.createGain(),this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime),this.bgsGainNode=this.audioContext.createGain(),this.bgsGainNode.gain.setValueAtTime(this.bgsGain,this.audioContext.currentTime),this.bgmGainNode=this.audioContext.createGain(),this.bgmGainNode.gain.setValueAtTime(this.bgmGain,this.audioContext.currentTime),this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=512,this.analyserArrayData=new Uint8Array(this.analyserNode.frequencyBinCount),this.outputGainNode=this.audioContext.createGain(),this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime),this.destinationNode=this.audioContext.createMediaStreamDestination(),this.outputStream=this.destinationNode.stream;{const{sourceNode:e,inputGainNode:a,enhanceGainNode:o,bgsGainNode:r,bgmGainNode:n,analyserNode:d,outputGainNode:u,destinationNode:h}=this;e.connect(a),a.connect(o),o.connect(d),r.connect(d),n.connect(d),o.connect(h),r.connect(h),n.connect(h),d.connect(u),u.connect(this.audioContext.destination)}this.setMute(!0),this.audioContext.resume()}}const q=async(i,t)=>{try{const{format:s,numberOfChannels:e,numberOfFrames:a,sampleRate:o}=t,r=i.createBuffer(e,a,o);for(let n=0;n<e;n++){const d=t.allocationSize({planeIndex:n}),u=new Uint8Array(d);t.copyTo(u,{planeIndex:n});const h=new DataView(u.buffer),f=r.getChannelData(n);for(let g=0;g<a;g++){let p;switch(s){case"s16":case"s16-planar":p=h.getInt16(g*2,!0)/32768;break;case"f32":case"f32-planar":p=h.getFloat32(g*4,!0);break;case"u8":case"u8-planar":p=(h.getUint8(g)-128)/128;break;default:throw new Error(`Unsupported audio format: ${s}`)}f[g]=Math.max(-1,Math.min(1,p))}}return r}catch(s){throw console.error("Failed to convert AudioData to AudioBuffer:",s),s}};class K{prAudioStream;audioContext;destination;stream=new MediaStream;nextStartTime=0;pendingSources=[];constructor(){}init=t=>{t||(t=new(window.AudioContext||window.webkitAudioContext)),this.audioContext=t,this.destination=this.audioContext.createMediaStreamDestination(),this.stream=new MediaStream,this.stream.addTrack(this.destination.stream.getAudioTracks()[0]),this.prAudioStream=new $(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(t){try{if(!this.audioContext||!this.destination)return;const s=await q(this.audioContext,t);if(!s)return;const e=this.audioContext.createBufferSource();e.buffer=s,e.connect(this.destination);const a=Math.max(this.nextStartTime,this.audioContext.currentTime);this.nextStartTime=a+s.duration,e.start(a),this.pendingSources.push(e),e.onended=()=>{this.pendingSources=this.pendingSources.filter(o=>o!==e)},this.audioContext.state==="suspended"&&await this.audioContext.resume()}finally{t.close()}}getStream=()=>this.prAudioStream?.getStream();destroy(){this.audioContext?.close(),this.audioContext=void 0,this.destination=void 0,this.nextStartTime=0,this.prAudioStream?.stop(),this.pendingSources.forEach(t=>t.stop()),this.pendingSources=[]}}class Q{#t={timeout:5*1e3};#e;constructor(t={}){this.#t={...this.#t,...t}}check=(t,s)=>new Promise(async(e,a)=>{this.stop(),this.#e=new AbortController;const o=window.setTimeout(()=>{this.#e?.abort("Timeout."),a({status:"timeout",reason:""})},this.#t.timeout);try{const r=await fetch(t,{...s,method:"HEAD",signal:this.#e?.signal});r.status===200?e({status:"successed",reason:""}):a({status:"failed",reason:`${r.status}`})}catch(r){a({status:"error",reason:r.message})}clearTimeout(o)});request=async(t,s)=>new Promise(async(e,a)=>{try{await this.check(t,s),this.#e=new AbortController;const o=await fetch(t,{...s,signal:this.#e?.signal});e(o)}catch(o){this.stop(),a(o)}});stop=()=>{this.#e?.signal.aborted===!1&&this.#e.abort("Actively stop.")}}const I=i=>{const t=i?.getTracks()||[];for(const s of t)s.stop()},B=i=>{const t=new W,s=document.createElement("canvas"),e=s.transferControlToOffscreen(),a=new MediaStreamTrackGenerator({kind:"video"}),o=new MediaStream([a]),r=()=>{t.destroy(),I(o)};return t.init({offscreenCanvas:e,baseTime:i,writable:a.writable}),{worker:t,canvas:s,stream:o,destroy:r}};class J{prFetch=new Q;demuxerWorker;decoderWorker;audioPlayer;renderWorker;renderBaseTime=0;stream;canvas;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(){}init=()=>{this.initDemuxer(),this.initDecoder(),this.audioPlayer=new K,this.audioPlayer.init(),this.initRender()};start=async t=>(this.stop(),this.renderBaseTime=new Date().getTime(),this.init(),this.prFetch.request(t).then(async s=>{const e=s.body?.getReader();if(!e)throw new Error("Reader is error.");const a=()=>e.read().then(({done:o,value:r})=>{r&&this.demuxerWorker?.push(r),!o&&a()}).catch(o=>{if(o.name!=="AbortError")throw o});a()}).catch(s=>{console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: err",s)}));stop=async()=>{try{this.prFetch.stop()}catch(s){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->Breathe: error",s)}this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy(),I(this.stream);const t=[...this.cutRenders.keys()];for(const s of t)this.cut.remove(s);this.audioPlayer?.destroy(),this.renderBaseTime=0,this.canvas=void 0};onTag=t=>{if(!this.decoderWorker)return;const{header:s,body:e}=t,{tagType:a,timestamp:o}=s;switch(a){case"script":{const{width:r,height:n}=e;this.renderWorker?.setSize({width:r,height:n}),this.on.demuxer.script&&this.on.demuxer.script(t)}break;case"audio":{const{accPacketType:r,data:n}=e;if(r===0){const{codec:d,sampleRate:u,channelConfiguration:h}=e,f={codec:d,sampleRate:u,numberOfChannels:h,description:new Uint8Array([])};this.decoderWorker.audio.init(f)}else r===1&&this.decoderWorker.audio.decode({type:"key",timestamp:o*1,data:n});this.on.demuxer.audio&&this.on.demuxer.audio(t)}break;case"video":{const{avcPacketType:r,frameType:n,data:d,nalus:u=[]}=e;if(r===0){const{codec:h,data:f}=e;this.decoderWorker.video.init({codec:h,description:f})}else if(r===1){const h=n===1?"key":"delta";this.decoderWorker.video.decode({type:h,timestamp:o*1e3,data:d});for(const f of u){const{header:g,payload:p}=f,{nal_unit_type:y}=g;y===6&&this.on.demuxer.sei&&this.on.demuxer.sei(p)}}this.on.demuxer.video&&this.on.demuxer.video(t)}break}};initDemuxer=()=>{this.demuxerWorker=new P,this.demuxerWorker.init(),this.demuxerWorker.on.tag=this.onTag};initDecoder=()=>{this.decoderWorker=new N,this.decoderWorker.on.audio.decode=t=>{this.audioPlayer?.push(t),this.on.decoder.audio&&this.on.decoder.audio(t)},this.decoderWorker.on.audio.error=t=>{this.stop(),this.on.error&&this.on.error(t)},this.decoderWorker.on.video.decode=async t=>{this.renderWorker?.push(t);const s=[...this.cutRenders.keys()];for(const e of s)this.cutRenders.get(e)?.worker.push(t);this.on.decoder.video&&this.on.decoder.video(t),t.bitmap.close()},this.decoderWorker.on.video.error=t=>{this.stop(),this.on.error&&this.on.error(t)}};initRender=()=>{const{worker:t,canvas:s,stream:e}=B(this.renderBaseTime);this.renderWorker=t,this.canvas=s,this.stream=e,this.renderWorker.setPause(!1)};getCanvas=()=>this.canvas;getStream=()=>this.stream;getCutCanvas=t=>this.cutRenders.get(t)?.canvas;getCutStream=t=>this.cutRenders.get(t)?.stream;setPause=t=>{this.renderWorker?.setPause(t)};setShader=t=>{this.renderWorker?.setShader(t)};setMute=t=>this.audioPlayer?.prAudioStream?.setMute(t);cut={create:(t,s)=>{let e=this.cutRenders.get(t);return e?(e.worker.setCut(s),e.worker.setPause(!1),e):(e=B(this.renderBaseTime),e.worker.setCut(s),this.cutRenders.set(t,e),e)},setPause:(t,s)=>{this.cutRenders.get(t)?.worker.setPause(s)},setShader:(t,s)=>{this.cutRenders.get(t)?.worker.setShader(s)},remove:t=>{this.cutRenders.get(t)?.destroy(),this.cutRenders.delete(t)}}}const T=new TextDecoder("utf-8"),X=(i,t)=>{const s=i.getUint8(t),e=s>>7&1,a=s>>5&3,o=s&31;return{forbidden_zero_bit:e,nal_ref_idc:a,nal_unit_type:o}},U=(i,t)=>i.getUint8(t),z=(i,t,s)=>{const e=new Uint8Array(i.buffer.slice(t,t+s));return T?.decode(e)||""},v=(i,t,s)=>{let e=t,a,o=0;switch(s){case 0:a=i.getFloat64(e,!1),o=8;break;case 1:a=!!i.getUint8(e),o=1;break;case 2:{a="";const n=i.getUint16(e,!1);e=e+2;const d=new Int8Array(i.buffer,e,n).filter(h=>h!==0);a=(T?.decode(d)||"").trim(),o=2+n}break;case 3:for(a={};e<i.byteLength;){const n=i.getUint16(e,!1);if(n===0)break;e=e+2;const d=z(i,e,n);e=e+n;const u=U(i,e);if(u===6)break;e=e+1;const h=v(i,e,u);e=e+h.length,a[d]=h.value,o=2+n+1+h.length}break;case 8:{a={};const n=i.getUint32(e,!1);e=e+4;for(let d=0;d<n;d++){const u=i.getUint16(e,!1);e=e+2;const h=z(i,e,u);e=e+u;const f=U(i,e);e=e+1;const g=v(i,e,f);e=e+g.length,a[h]=g.value,o=2+u+1+g.length}}break;case 10:{a=[];const n=i.getUint32(e,!1);e=e+4;for(let d=0;d<n;d++){const u=U(i,e);e=e+1;const h=v(i,e,u);e=e+h.length,a.push(h.value),o=1+h.length}}break}return{amfType:s,length:o,value:a}},w=(i,t)=>i.getUint8(t)<<16|i.getUint8(t+1)<<8|i.getUint8(t+2),l={header:{getSignature:i=>{const t=new Int8Array(i.buffer.slice(0,3));return T?.decode(t)||""},getVersion:i=>i.getUint8(3),getFlags:i=>{const s=i.getUint8(0).toString(2).padStart(5,"0").split(""),[,,e,,a]=s;return{audio:a==="1",video:e==="1"}},getDataOffset:i=>i.getUint32(5)},getPreviousTagSize:(i,t)=>i.getUint32(t),isSurplusTag:(i,t)=>{let s=!0;const e=i.byteLength;if(t+4>e)s=!1;else if(t+4+11>e)s=!1;else{const a=w(i,t+4+1);t+4+11+a>e&&(s=!1)}return s},tag:{tagHeader:{getTagType:(i,t)=>{const s=i.getUint8(t);let e;switch(s){case 18:e="script";break;case 8:e="audio";break;case 9:e="video";break}return e},getDataSize:(i,t)=>w(i,t+1),getTimestamp:(i,t)=>w(i,t+4),getTimestampExtended:(i,t)=>i.getUint8(t+7),getStreamID:(i,t)=>w(i,t+8)},tagBody:{parseAudio:(i,t,s)=>{let e=t;const a=i.getUint8(e),o=a>>4&15,r=a>>2&3,n=a>>1&1,d=a&1;e=e+1;const u=i.getUint8(e);e=e+1;const h=s-2,f=new Uint8Array(i.buffer.slice(e,e+h));if(o===10&&u===0){const g=i.getUint8(e),p=i.getUint8(e+1),y=(g&248)>>3,k=(g&7)<<1|p>>7,x=(p&120)>>3,S=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],D=`mp4a.40.${y}`,C=S[k];return{soundFormat:o,soundRate:r,soundSize:n,soundType:d,accPacketType:u,data:f,audioObjectType:y,samplingFrequencyIndex:k,channelConfiguration:x,codec:D,sampleRate:C}}return{soundFormat:o,soundRate:r,soundSize:n,soundType:d,accPacketType:u,data:f}},parseVideo:(i,t,s)=>{let e=t;const a=i.getUint8(e),o=a>>4&15,r=a&15;e=e+1;const n=i.getUint8(e);e=e+1;const d=w(i,e);e=e+3;const u=s-5,h=new Uint8Array(i.buffer.slice(e,e+u));switch(r){case 7:if(n===0){const f=i.getUint8(e);if(e=e+1,f!==1)throw new Error("Invalid AVC version");const g=i.getUint8(e)&255;e=e+1;const p=i.getUint8(e)&255;e=e+1;const y=i.getUint8(e)&255;e=e+1;const S=`avc1.${Array.from([g,p,y],ae=>ae.toString(16).padStart(2,"0")).join("")}`,D=(i.getUint8(e)&3)-1;e=e+1;const C=i.getUint8(e)&31;e=e+1;const A=i.getUint16(e,!1);e=e+2;const te=new Uint8Array(i.buffer.slice(e,e+A));e=e+A;const se=i.getUint8(e)&31;e=e+1;const R=i.getUint16(e,!1);e=e+2;const ie=new Uint8Array(i.buffer.slice(e,e+R));return e=e+R,{frameType:o,codecID:r,avcPacketType:n,cts:d,data:h,version:f,codec:S,profile:g,compatibility:p,level:y,lengthSizeMinusOne:D,numOfSequenceParameterSets:C,sequenceParameterSetLength:A,sps:te,numOfPictureParameterSets:se,pictureParameterSetLength:R,pps:ie}}else if(n===1){const f=[],g=e+s-5;for(;e+4<g;){const p=i.getUint32(e,!1);e=e+4;const y=X(i,e);e=e+1;const k=p-1,x=new Uint8Array(i.buffer.slice(e,e+k));e=e+k,f.push({size:p,header:y,payload:x})}return{frameType:o,codecID:r,avcPacketType:n,cts:d,data:h,nalus:f}}break;default:throw new Error("Unsupported codecID")}return{frameType:o,codecID:r,avcPacketType:n,cts:d,data:h}},parseMetaData:(i,t)=>{let s=t;{if(i.getUint8(s)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");s=s+1}const e=i.getUint16(s,!1);s=s+2;{const r=new Int8Array(i.buffer.slice(s,s+e));if((T?.decode(r)||"")!=="onMetaData")throw new Error("Expected 'onMetaData' string");s=s+e}const a=U(i,s);return s=s+1,v(i,s,a).value}}}};class Y{parseSpeed=8;pendingPayloads=[];payload=new Uint8Array(0);offset=0;is_parsing=!1;header;tag;on={};constructor(){}init=()=>{this.destroy()};push=t=>{this.pendingPayloads.push(t),this.is_parsing||this.parse()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.offset=0,this.is_parsing=!1,this.header=void 0,this.tag=void 0};parse=async()=>{for(this.is_parsing=!0;;){const t=this.pendingPayloads.shift();if(!t)break;const s=new Uint8Array(this.payload.byteLength+t.byteLength);s.set(this.payload,0),s.set(t,this.payload.byteLength),this.payload=s;const e=new DataView(this.payload.buffer);this.header||this.parseHeader(e),await this.parseTag(e)}this.is_parsing=!1};parseHeader=t=>(this.header={signature:l.header.getSignature(t),version:l.header.getVersion(t),flags:l.header.getFlags(t),dataOffset:l.header.getDataOffset(t)},this.offset=this.header?.dataOffset,this.on.header&&this.on.header(this.header),this.header);parseTag=async t=>{const s=(a,o)=>({tagType:l.tag.tagHeader.getTagType(a,o),dataSize:l.tag.tagHeader.getDataSize(a,o),timestamp:l.tag.tagHeader.getTimestamp(a,o),timestampExtended:l.tag.tagHeader.getTimestampExtended(a,o),streamID:l.tag.tagHeader.getStreamID(a,o)}),e=(a,o,r,n)=>{let d;switch(a){case"script":d=l.tag.tagBody.parseMetaData(o,r);break;case"audio":d=l.tag.tagBody.parseAudio(o,r,n);break;case"video":d=l.tag.tagBody.parseVideo(o,r,n);break}return d};for(;this.offset<t.byteLength;){if(l.isSurplusTag(t,this.offset)===!1){this.payload=this.payload.slice(this.offset),this.offset=0;break}const o=s(t,this.offset+4),{tagType:r,dataSize:n}=o;if(!r)break;const d=e(r,t,this.offset+4+11,n);this.tag={header:o,body:d},this.on.tag&&this.on.tag(this.tag),this.offset=this.offset+4+11+n,await new Promise(u=>setTimeout(()=>u(!0),this.parseSpeed))}}}class Z{audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;on={audio:{},video:{}};constructor(){}audio={init:t=>{this.audio.destroy(),this.audioDecoderConfig={...t},this.audioDecoder=new AudioDecoder({output:s=>{this.on.audio.decode&&this.on.audio.decode(s)},error:s=>{this.on.audio.error&&this.on.audio.error(s)}}),this.audioDecoder.configure(this.audioDecoderConfig)},decode:t=>{if(!this.audioDecoder)return;const s=new EncodedAudioChunk(t);this.audioDecoder.decode(s)},flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={init:t=>{this.video.destroy(),this.videoDecoderConfig={...t},this.videoDecoder=new VideoDecoder({output:async s=>{const e=await createImageBitmap(s),a=s.timestamp;s.close(),e.width>0&&e.height>0?this.on.video.decode&&this.on.video.decode({timestamp:a,bitmap:e}):e.close()},error:s=>{this.on.video.error&&this.on.video.error(s)}}),this.videoDecoder.configure(this.videoDecoderConfig)},decode:t=>{if(this.videoDecoder&&(t.type==="key"&&(this.hasKeyFrame=!0),this.hasKeyFrame&&this.videoDecoder.decodeQueueSize<2)){const s=new EncodedVideoChunk(t);this.videoDecoder.decode(s)}},flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}}class ee{isRendering=!1;pendingFrames=[];offscreenCanvas;writable;writer;ctx;cutOption;baseTime=0;pause=!1;shader=["stream"];constructor(){}init=({offscreenCanvas:t,baseTime:s=performance.timeOrigin,writable:e})=>{this.destroy(),this.offscreenCanvas=t,this.writable=e,this.writer=this.writable.getWriter(),this.ctx=this.offscreenCanvas.getContext("2d"),this.baseTime=s};setShader=t=>{this.shader=t};setSize=({width:t,height:s})=>{this.offscreenCanvas&&(this.offscreenCanvas.width=t,this.offscreenCanvas.height=s)};destroy=()=>{this.isRendering=!1,this.pendingFrames=[],this.offscreenCanvas=void 0,this.ctx=void 0,this.baseTime=0};push=t=>{this.pendingFrames.push(t),this.isRendering===!1&&setTimeout(this.renderFrame,0)};setCut=t=>{this.cutOption=t};setPause=t=>{this.pause=t,this.isRendering===!1&&setTimeout(this.renderFrame,0)};calculateTimeUntilNextFrame=t=>{const s=performance.timeOrigin+performance.now(),a=this.baseTime+t/1e3-s;return Math.max(0,a)};renderFrame=async()=>{for(this.isRendering=!0;;){const t=this.pendingFrames.shift();if(!t)break;let{timestamp:s,bitmap:e}=t;if(this.cutOption){const{sx:o=0,sy:r=0,sw:n=e.width,sh:d=e.height}=this.cutOption;e=await createImageBitmap(e,o,r,n,d)}const a=this.calculateTimeUntilNextFrame(s);await new Promise(o=>setTimeout(()=>o(!0),a)),this.drawImage({timestamp:s,bitmap:e}),this.cutOption&&e.close()}this.isRendering=!1};drawImage=t=>{if(this.pause!==!0){if(this.shader.includes("stream")){const s=new VideoFrame(t.bitmap,{timestamp:t.timestamp});this.writer.write(s),s.close()}this.shader.includes("canvas")&&this.ctx&&this.offscreenCanvas&&this.ctx.drawImage(t.bitmap,0,0,this.offscreenCanvas.width,this.offscreenCanvas.height)}}}m.Decoder=Z,m.DecoderWorker=N,m.Demuxer=Y,m.DemuxerWorker=P,m.PrPlayer=J,m.Render=ee,m.RenderWorker=W,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
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.5",
4
+ "version": "0.0.7",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist"