pr-player 0.2.12 → 0.2.14

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.
@@ -1,4 +1,5 @@
1
1
  import { RenderWorker } from './render/RenderWorker';
2
+ import { AudioPlayer } from './audioPlayer/audioPlayer';
2
3
  interface On {
3
4
  demuxer: {
4
5
  info?: (_info: any) => void;
@@ -27,11 +28,12 @@ interface PrPlayerOption {
27
28
  export declare class PrPlayer {
28
29
  private option;
29
30
  private prFetch;
31
+ private getSegmentsFetch;
30
32
  private prResolves;
31
33
  private url;
32
34
  private demuxerWorker;
33
35
  private decoderWorker;
34
- private audioPlayer;
36
+ audioPlayer: AudioPlayer | undefined;
35
37
  private renderWorker;
36
38
  private stream;
37
39
  on: On;
package/dist/index.js CHANGED
@@ -129,21 +129,21 @@ class O {
129
129
  const { analyserNode: e, analyserArrayData: i } = this;
130
130
  e.getByteFrequencyData(i);
131
131
  let n = 0;
132
- for (let o = 0; o < i.length; o++)
133
- n += i[o];
132
+ for (let r = 0; r < i.length; r++)
133
+ n += i[r];
134
134
  return Math.ceil(n / i.length);
135
- }), y(this, "mixAudio", (e, i = "bgm") => new Promise(async (n, o) => {
135
+ }), y(this, "mixAudio", (e, i = "bgm") => new Promise(async (n, r) => {
136
136
  try {
137
137
  {
138
138
  const d = this.mixAudioMap.get(i);
139
139
  d && d.stop();
140
140
  }
141
- const a = i === "bgs" ? this.bgsGainNode : this.bgmGainNode, r = this.audioContext.createBufferSource();
142
- this.mixAudioMap.set(i, r), r.buffer = e, r.connect(a), r.onended = () => {
143
- r.disconnect(a), this.mixAudioMap.delete(i), n(!0);
144
- }, r.start(0);
141
+ const a = i === "bgs" ? this.bgsGainNode : this.bgmGainNode, o = this.audioContext.createBufferSource();
142
+ this.mixAudioMap.set(i, o), o.buffer = e, o.connect(a), o.onended = () => {
143
+ o.disconnect(a), this.mixAudioMap.delete(i), n(!0);
144
+ }, o.start(0);
145
145
  } catch (a) {
146
- o(a);
146
+ r(a);
147
147
  }
148
148
  })), y(this, "mixAudioStop", (e) => {
149
149
  const i = this.mixAudioMap.get(e);
@@ -153,44 +153,44 @@ class O {
153
153
  i ? n.connect(this.destinationNode) : n.disconnect(this.destinationNode);
154
154
  }), 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;
155
155
  {
156
- const { sourceNode: e, inputGainNode: i, enhanceGainNode: n, bgsGainNode: o, bgmGainNode: a, analyserNode: r, outputGainNode: d, destinationNode: c } = this;
157
- e.connect(i), i.connect(n), n.connect(r), o.connect(r), a.connect(r), n.connect(c), o.connect(c), a.connect(c), r.connect(d), d.connect(this.audioContext.destination);
156
+ const { sourceNode: e, inputGainNode: i, enhanceGainNode: n, bgsGainNode: r, bgmGainNode: a, analyserNode: o, outputGainNode: d, destinationNode: c } = this;
157
+ e.connect(i), i.connect(n), n.connect(o), r.connect(o), a.connect(o), n.connect(c), r.connect(c), a.connect(c), o.connect(d), d.connect(this.audioContext.destination);
158
158
  }
159
159
  this.setMute(!0), this.audioContext.resume();
160
160
  }
161
161
  }
162
162
  const E = async (l, t) => {
163
163
  try {
164
- const { format: s, numberOfChannels: e, numberOfFrames: i, sampleRate: n } = t, o = l.createBuffer(e, i, n);
164
+ const { format: s, numberOfChannels: e, numberOfFrames: i, sampleRate: n } = t, r = l.createBuffer(e, i, n);
165
165
  for (let a = 0; a < e; a++) {
166
- const r = t.allocationSize({ planeIndex: a }), d = new Uint8Array(r);
166
+ const o = t.allocationSize({ planeIndex: a }), d = new Uint8Array(o);
167
167
  t.copyTo(d, { planeIndex: a });
168
- const c = new DataView(d.buffer), h = o.getChannelData(a);
168
+ const c = new DataView(d.buffer), u = r.getChannelData(a);
169
169
  for (let p = 0; p < i; p++) {
170
- let u;
170
+ let h;
171
171
  switch (s) {
172
172
  case "s16":
173
173
  // 16-bit signed PCM (范围: -32768 ~ 32767)
174
174
  case "s16-planar":
175
- u = c.getInt16(p * 2, !0) / 32768;
175
+ h = c.getInt16(p * 2, !0) / 32768;
176
176
  break;
177
177
  case "f32":
178
178
  // 32-bit float (范围: -1.0 ~ 1.0)
179
179
  case "f32-planar":
180
- u = c.getFloat32(p * 4, !0);
180
+ h = c.getFloat32(p * 4, !0);
181
181
  break;
182
182
  case "u8":
183
183
  // 8-bit unsigned (范围: 0 ~ 255)
184
184
  case "u8-planar":
185
- u = (c.getUint8(p) - 128) / 128;
185
+ h = (c.getUint8(p) - 128) / 128;
186
186
  break;
187
187
  default:
188
188
  throw new Error(`Unsupported audio format: ${s}`);
189
189
  }
190
- h[p] = Math.max(-1, Math.min(1, u));
190
+ u[p] = Math.max(-1, Math.min(1, h));
191
191
  }
192
192
  }
193
- return o;
193
+ return r;
194
194
  } catch (s) {
195
195
  throw console.error("Failed to convert AudioData to AudioBuffer:", s), s;
196
196
  }
@@ -215,10 +215,10 @@ class W {
215
215
  if (!i) return;
216
216
  const n = this.audioContext.createBufferSource();
217
217
  n.buffer = i, n.playbackRate.value = e;
218
- const o = -1200 * Math.log2(e);
219
- n.detune.value = o, n.connect(this.destination);
220
- const a = Math.max(this.nextStartTime, this.audioContext.currentTime), r = i.duration / e;
221
- this.nextStartTime = a + r, n.start(a), this.pendingSources.push(n), n.onended = () => {
218
+ const r = -1200 * Math.log2(e);
219
+ n.detune.value = r, n.connect(this.destination);
220
+ const a = Math.max(this.nextStartTime, this.audioContext.currentTime), o = i.duration / e;
221
+ this.nextStartTime = a + o, n.start(a), this.pendingSources.push(n), n.onended = () => {
222
222
  this.pendingSources = this.pendingSources.filter((d) => d !== n);
223
223
  }, this.audioContext.state === "suspended" && await this.audioContext.resume();
224
224
  } finally {
@@ -296,10 +296,10 @@ class $ {
296
296
  this.resolvesMap.get(t)?.set(a, { resolve: i, timer: 0 });
297
297
  return;
298
298
  }
299
- const r = window.setTimeout(() => {
299
+ const o = window.setTimeout(() => {
300
300
  this.emit(t);
301
301
  }, e);
302
- this.resolvesMap.get(t)?.set(a, { resolve: i, timer: r });
302
+ this.resolvesMap.get(t)?.set(a, { resolve: i, timer: o });
303
303
  });
304
304
  emit = async (t) => {
305
305
  const s = this.resolvesMap.get(t);
@@ -323,22 +323,22 @@ const H = (l, t) => {
323
323
  t = t + 1;
324
324
  const n = s.getUint8(t) & 255;
325
325
  t = t + 1;
326
- const o = s.getUint8(t) & 255;
326
+ const r = s.getUint8(t) & 255;
327
327
  t = t + 1;
328
- const d = `avc1.${Array.from([i, n, o], (b) => b.toString(16).padStart(2, "0")).join("")}`, c = (s.getUint8(t) & 3) - 1;
328
+ const d = `avc1.${Array.from([i, n, r], (b) => b.toString(16).padStart(2, "0")).join("")}`, c = (s.getUint8(t) & 3) - 1;
329
329
  t = t + 1;
330
- const h = s.getUint8(t) & 31;
330
+ const u = s.getUint8(t) & 31;
331
331
  t = t + 1;
332
332
  const p = s.getUint16(t, !1);
333
333
  t = t + 2;
334
- const u = new Uint8Array(s.buffer.slice(t, t + p));
334
+ const h = new Uint8Array(s.buffer.slice(t, t + p));
335
335
  t = t + p;
336
336
  const g = s.getUint8(t) & 31;
337
337
  t = t + 1;
338
338
  const f = s.getUint16(t, !1);
339
339
  t = t + 2;
340
340
  const m = new Uint8Array(s.buffer.slice(t, t + f));
341
- return t = t + f, { version: e, codec: d, profile: i, compatibility: n, level: o, lengthSizeMinusOne: c, numOfSequenceParameterSets: h, sequenceParameterSetLength: p, sps: u, numOfPictureParameterSets: g, pictureParameterSetLength: f, pps: m };
341
+ return t = t + f, { version: e, codec: d, profile: i, compatibility: n, level: r, lengthSizeMinusOne: c, numOfSequenceParameterSets: u, sequenceParameterSetLength: p, sps: h, numOfPictureParameterSets: g, pictureParameterSetLength: f, pps: m };
342
342
  }, K = (l) => {
343
343
  const t = new Uint8Array(4 + l.length);
344
344
  return new DataView(t.buffer).setUint32(0, l.length, !1), t.set(l, 4), t;
@@ -358,19 +358,18 @@ const H = (l, t) => {
358
358
  let s = 0, e, i, n;
359
359
  e = t.getUint32(s, !1), s += 4;
360
360
  {
361
- const o = t.getUint8(s), a = o >> 7 & 1, r = o >> 5 & 3, d = o & 31;
362
- i = { forbidden_zero_bit: a, nal_ref_idc: r, nal_unit_type: d }, s += 1;
361
+ const r = t.getUint8(s), a = r >> 7 & 1, o = r >> 5 & 3, d = r & 31;
362
+ i = { forbidden_zero_bit: a, nal_ref_idc: o, nal_unit_type: d }, s += 1;
363
363
  }
364
364
  {
365
- const o = e - 1;
366
- n = new Uint8Array(t.buffer.slice(s, s + o));
365
+ const r = e - 1;
366
+ n = new Uint8Array(t.buffer.slice(s, s + r));
367
367
  }
368
368
  return { size: e, header: i, data: n };
369
369
  };
370
370
  class x {
371
371
  #e = {
372
- timeout: 5 * 1e3,
373
- check: !1
372
+ timeout: 5 * 1e3
374
373
  };
375
374
  #t;
376
375
  constructor(t = {}) {
@@ -387,10 +386,10 @@ class x {
387
386
  this.#t?.abort("Timeout."), i({ status: "timeout", reason: "" });
388
387
  }, this.#e.timeout);
389
388
  try {
390
- const o = await fetch(t, { ...s, method: "HEAD", signal: this.#t?.signal });
391
- o.status === 200 ? e({ status: "successed", reason: "" }) : i({ status: "failed", reason: `${o.status}` });
392
- } catch (o) {
393
- i({ status: "error", reason: o.message });
389
+ const r = await fetch(t, { ...s, method: "HEAD", signal: this.#t?.signal });
390
+ r.status === 200 ? e({ status: "successed", reason: "" }) : i({ status: "failed", reason: `${r.status}` });
391
+ } catch (r) {
392
+ i({ status: "error", reason: r.message });
394
393
  }
395
394
  clearTimeout(n);
396
395
  });
@@ -401,7 +400,7 @@ class x {
401
400
  */
402
401
  request = async (t, s) => new Promise(async (e, i) => {
403
402
  try {
404
- this.#e.check && await this.check(t, s), this.#t = new AbortController();
403
+ await this.check(t, s), this.#t = new AbortController();
405
404
  const n = await fetch(t, { ...s, signal: this.#t?.signal });
406
405
  e(n);
407
406
  } catch (n) {
@@ -421,6 +420,7 @@ class et {
421
420
  frameTrack: !1
422
421
  };
423
422
  prFetch = new x();
423
+ getSegmentsFetch = new x();
424
424
  prResolves = new $();
425
425
  url = "";
426
426
  demuxerWorker;
@@ -441,7 +441,7 @@ class et {
441
441
  * @param url : string
442
442
  */
443
443
  start = async (t) => {
444
- this.stop(), this.url = t;
444
+ await this.stop(), this.url = t;
445
445
  const s = q(t);
446
446
  if (s === "unknown") throw new Error("This address cannot be parsed.");
447
447
  switch (this.init(s), s) {
@@ -458,7 +458,7 @@ class et {
458
458
  */
459
459
  stop = async () => {
460
460
  try {
461
- clearInterval(this.hls.getSegmentsTimer), this.prFetch.stop();
461
+ this.url = "", clearInterval(this.hls.getSegmentsTimer), this.prFetch.stop(), this.getSegmentsFetch.stop();
462
462
  } catch (s) {
463
463
  console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m", "color:#0097ff;", "------->pr-player: error", s);
464
464
  }
@@ -544,8 +544,8 @@ class et {
544
544
  switch (e) {
545
545
  case "audio":
546
546
  {
547
- const { codec: i, sampleRate: n, numberOfChannels: o } = s;
548
- this.decoderWorker?.initAudio({ codec: i, sampleRate: n, numberOfChannels: o });
547
+ const { codec: i, sampleRate: n, numberOfChannels: r } = s;
548
+ this.decoderWorker?.initAudio({ codec: i, sampleRate: n, numberOfChannels: r });
549
549
  }
550
550
  break;
551
551
  case "video":
@@ -561,14 +561,14 @@ class et {
561
561
  switch (e) {
562
562
  case "audio":
563
563
  {
564
- const { type: i, dts: n, data: o } = s, a = n * 1e3;
565
- this.decoderWorker.push({ kind: e, init: { type: i, timestamp: a, data: o } });
564
+ const { type: i, dts: n, data: r } = s, a = n * 1e3;
565
+ this.decoderWorker.push({ kind: e, init: { type: i, timestamp: a, data: r } });
566
566
  }
567
567
  break;
568
568
  case "video":
569
569
  {
570
- const { type: i, dts: n, data: o, nalus: a = [] } = s, r = n * 1e3;
571
- this.decoderWorker.push({ kind: e, init: { type: i, timestamp: r, data: o }, nalus: a });
570
+ const { type: i, dts: n, data: r, nalus: a = [] } = s, o = n * 1e3;
571
+ this.decoderWorker.push({ kind: e, init: { type: i, timestamp: o, data: r }, nalus: a });
572
572
  }
573
573
  break;
574
574
  }
@@ -595,8 +595,8 @@ class et {
595
595
  }, this.decoderWorker.on.nalus = async (e) => {
596
596
  for (const i of e) {
597
597
  if (i.byteLength <= 4) continue;
598
- const { header: n, data: o } = Y(i), { nal_unit_type: a } = n;
599
- a === 6 && this.on.decoder.sei && this.on.decoder.sei(o);
598
+ const { header: n, data: r } = Y(i), { nal_unit_type: a } = n;
599
+ a === 6 && this.on.decoder.sei && this.on.decoder.sei(r);
600
600
  }
601
601
  }, this.decoderWorker.on.analysis = (e) => {
602
602
  this.on.decoder.analysis && this.on.decoder.analysis(e);
@@ -618,7 +618,7 @@ class et {
618
618
  if (!s) throw new Error("reader is error.");
619
619
  for (; ; ) {
620
620
  const { done: e, value: i } = await s.read();
621
- if (i && this.demuxerWorker?.push(i), e) break;
621
+ if (i && this.demuxerWorker?.push(i), e || this.url === "") break;
622
622
  }
623
623
  } catch (t) {
624
624
  if (t?.name !== "AbortError") throw Error(t);
@@ -634,33 +634,32 @@ class et {
634
634
  parse: async (t) => {
635
635
  const i = new TextDecoder("utf-8").decode(t).split(`
636
636
  `).map((c) => c.replace("\r", "")), n = this.url.substring(0, this.url.lastIndexOf("/") + 1);
637
- let o = 4, a = 0, r = !1;
637
+ let r = 4, a = 0, o = !1;
638
638
  const d = [];
639
639
  for (const c of i)
640
- c.startsWith("#EXTINF:") ? o = parseFloat(c.split(":")[1].split(",")[0]) : c.startsWith("#EXT-X-TARGETDURATION:") ? a = parseInt(c.split(":")[1]) : c.startsWith("#EXT-X-ENDLIST") ? r = !1 : c.startsWith("#EXT-X-MEDIA-SEQUENCE:") ? r = !0 : c.includes(".ts") && !c.startsWith("#") && d.push({
640
+ c.startsWith("#EXTINF:") ? r = parseFloat(c.split(":")[1].split(",")[0]) : c.startsWith("#EXT-X-TARGETDURATION:") ? a = parseInt(c.split(":")[1]) : c.startsWith("#EXT-X-ENDLIST") ? o = !1 : c.startsWith("#EXT-X-MEDIA-SEQUENCE:") ? o = !0 : c.includes(".ts") && !c.startsWith("#") && d.push({
641
641
  url: c.startsWith("http") ? c : n + c,
642
- duration: o,
643
- isLive: r
642
+ duration: r,
643
+ isLive: o
644
644
  });
645
- return { baseUrl: n, targetDuration: a, isLive: r, segments: d };
645
+ return { baseUrl: n, targetDuration: a, isLive: o, segments: d };
646
646
  },
647
647
  getSegments: async () => {
648
648
  try {
649
- const t = new x();
650
- let s = await t.request(this.url);
651
- if (s.status !== 200 && (await new Promise((i) => setTimeout(() => i(!0), 500)), s = await t.request(this.url)), s.status !== 200 && (await new Promise((i) => setTimeout(() => i(!0), 500)), s = await t.request(this.url)), s.status !== 200) throw new Error("request is error.");
652
- const e = s.body?.getReader();
653
- if (!e) throw new Error("reader is error.");
649
+ let t = await this.getSegmentsFetch.request(this.url);
650
+ if (t.status !== 200 && (await new Promise((e) => setTimeout(() => e(!0), 500)), t = await this.getSegmentsFetch.request(this.url)), t.status !== 200 && (await new Promise((e) => setTimeout(() => e(!0), 500)), t = await this.getSegmentsFetch.request(this.url)), t.status !== 200) throw new Error("request is error.");
651
+ const s = t.body?.getReader();
652
+ if (!s) throw new Error("reader is error.");
654
653
  for (; ; ) {
655
- const { done: i, value: n } = await e.read();
656
- if (n) {
657
- const o = await this.hls.parse(n), { segments: a = [], isLive: r = !1 } = o;
658
- this.hls.isLive = r, r === !1 && (this.option.frameTrack = !1);
659
- let d = Array.from(a, (h) => h.url);
660
- const c = d.findIndex((h) => h === this.hls.url);
661
- c !== -1 && (d = d.slice(c + 1)), this.hls.urls = d;
654
+ const { done: e, value: i } = await s.read();
655
+ if (i) {
656
+ const n = await this.hls.parse(i), { segments: r = [], isLive: a = !1 } = n;
657
+ this.hls.isLive = a, a === !1 && (this.option.frameTrack = !1);
658
+ let o = Array.from(r, (c) => c.url);
659
+ const d = o.findIndex((c) => c === this.hls.url);
660
+ d !== -1 && (o = o.slice(d + 1)), this.hls.urls = o;
662
661
  }
663
- if (i) break;
662
+ if (e || this.url === "") break;
664
663
  }
665
664
  } catch (t) {
666
665
  this.on.error && this.on.error(t);
@@ -676,7 +675,7 @@ class et {
676
675
  if (!e) throw new Error("segment reader is error.");
677
676
  for (; ; ) {
678
677
  const { done: i, value: n } = await e.read();
679
- if (n && this.demuxerWorker?.push(n), i) break;
678
+ if (n && this.demuxerWorker?.push(n), i || this.url === "") break;
680
679
  }
681
680
  } else
682
681
  await new Promise((s) => setTimeout(() => s(!0), 300));
@@ -762,46 +761,46 @@ class Z {
762
761
  let e = s;
763
762
  const i = this.parseHeader(t, e);
764
763
  e += 4;
765
- const { transport_error_indicator: n, pid: o, payload_unit_start_indicator: a, adaptation_field_control: r } = i;
766
- if (n === 1 || o === void 0) return;
764
+ const { transport_error_indicator: n, pid: r, payload_unit_start_indicator: a, adaptation_field_control: o } = i;
765
+ if (n === 1 || r === void 0) return;
767
766
  let d = 184;
768
- if (r === 2 || r === 3) {
767
+ if (o === 2 || o === 3) {
769
768
  const c = t.getUint8(e);
770
769
  e += 1, this.parseAdaptationField(t, e), e += c, d -= c;
771
770
  }
772
- if (r === 3 && (d -= 1), r === 1 || r === 3) {
771
+ if (o === 3 && (d -= 1), o === 1 || o === 3) {
773
772
  const c = new Uint8Array(t.buffer.slice(e, e + d));
774
- if (o === 0) return this.parsePAT(t, e);
773
+ if (r === 0) return this.parsePAT(t, e);
775
774
  {
776
- const { programs: u = [] } = this.pat || {};
777
- if (u.find((f) => f.pmt_pid === o)) return this.parsePMT(t, e);
775
+ const { programs: h = [] } = this.pat || {};
776
+ if (h.find((f) => f.pmt_pid === r)) return this.parsePMT(t, e);
778
777
  }
779
- const { streams: h = [] } = this.pmt || {}, p = h.find((u) => u.elementary_pid === o);
778
+ const { streams: u = [] } = this.pmt || {}, p = u.find((h) => h.elementary_pid === r);
780
779
  if (p) {
781
780
  if (a === 1) {
782
- const u = this.payloadMap.get(o);
783
- if (u) {
781
+ const h = this.payloadMap.get(r);
782
+ if (h) {
784
783
  switch (p.kind) {
785
784
  case "audio":
786
785
  {
787
- const g = await this.parseAudio(u);
786
+ const g = await this.parseAudio(h);
788
787
  this.on.chunk && this.on.chunk(g);
789
788
  }
790
789
  break;
791
790
  case "video":
792
791
  {
793
- const g = await this.parseVideo(u);
792
+ const g = await this.parseVideo(h);
794
793
  this.on.chunk && this.on.chunk(g), await new Promise((f) => setTimeout(() => f(!0), 0));
795
794
  }
796
795
  break;
797
796
  }
798
- this.payloadMap.delete(o);
797
+ this.payloadMap.delete(r);
799
798
  }
800
799
  }
801
800
  {
802
- this.payloadMap.has(o) || this.payloadMap.set(o, new Uint8Array());
803
- const u = this.payloadMap.get(o), g = new Uint8Array(u.byteLength + c.byteLength);
804
- g.set(u, 0), g.set(c, u.byteLength), this.payloadMap.set(o, g);
801
+ this.payloadMap.has(r) || this.payloadMap.set(r, new Uint8Array());
802
+ const h = this.payloadMap.get(r), g = new Uint8Array(h.byteLength + c.byteLength);
803
+ g.set(h, 0), g.set(c, h.byteLength), this.payloadMap.set(r, g);
805
804
  }
806
805
  }
807
806
  }
@@ -809,10 +808,10 @@ class Z {
809
808
  // Header
810
809
  parseHeader = (t, s) => {
811
810
  let e = s;
812
- const i = t.getUint8(e), n = t.getUint8(e + 1), o = t.getUint8(e + 2), a = t.getUint8(e + 3), r = (n & 128) >> 7;
813
- if (r === 1) return { sync_byte: i, transport_error_indicator: r };
814
- const d = (n & 64) >> 6, c = (n & 32) >> 5, h = (n & 31) << 8 | o, p = (a & 192) >> 6, u = a >> 4 & 3, g = a & 15;
815
- return { sync_byte: i, transport_error_indicator: r, payload_unit_start_indicator: d, transport_priority: c, pid: h, transport_scrambling_control: p, adaptation_field_control: u, continuity_counter: g };
811
+ const i = t.getUint8(e), n = t.getUint8(e + 1), r = t.getUint8(e + 2), a = t.getUint8(e + 3), o = (n & 128) >> 7;
812
+ if (o === 1) return { sync_byte: i, transport_error_indicator: o };
813
+ const d = (n & 64) >> 6, c = (n & 32) >> 5, u = (n & 31) << 8 | r, p = (a & 192) >> 6, h = a >> 4 & 3, g = a & 15;
814
+ return { sync_byte: i, transport_error_indicator: o, payload_unit_start_indicator: d, transport_priority: c, pid: u, transport_scrambling_control: p, adaptation_field_control: h, continuity_counter: g };
816
815
  };
817
816
  // PAT表
818
817
  parsePAT = (t, s) => {
@@ -820,29 +819,29 @@ class Z {
820
819
  {
821
820
  const a = t.getUint8(e);
822
821
  e += 1;
823
- const r = t.getUint8(e);
824
- if (e += 1, r !== 0) throw new Error("Invalid PAT table_id");
822
+ const o = t.getUint8(e);
823
+ if (e += 1, o !== 0) throw new Error("Invalid PAT table_id");
825
824
  const d = t.getUint16(e) & 4095;
826
825
  e += 2;
827
826
  const c = t.getUint16(e);
828
827
  e += 2;
829
- const h = (t.getUint8(e) & 62) >> 1, p = t.getUint8(e) & 1;
828
+ const u = (t.getUint8(e) & 62) >> 1, p = t.getUint8(e) & 1;
830
829
  e += 1;
831
- const u = t.getUint8(e);
830
+ const h = t.getUint8(e);
832
831
  e += 1;
833
832
  const g = t.getUint8(e);
834
- e += 1, i = { pointer_field: a, table_id: r, section_length: d, transport_stream_id: c, version_number: h, current_next_indicator: p, section_number: u, last_section_number: g };
833
+ e += 1, i = { pointer_field: a, table_id: o, section_length: d, transport_stream_id: c, version_number: u, current_next_indicator: p, section_number: h, last_section_number: g };
835
834
  }
836
835
  const n = [];
837
836
  {
838
- const a = i.section_length - 5 - 4, r = e + a;
839
- for (; e < r; ) {
837
+ const a = i.section_length - 5 - 4, o = e + a;
838
+ for (; e < o; ) {
840
839
  const d = t.getUint16(e), c = t.getUint16(e + 2) & 8191;
841
840
  e += 4, d !== 0 && c >= 32 && c <= 8190 && n.push({ program_number: d, pmt_pid: c });
842
841
  }
843
842
  }
844
- const o = t.getUint32(e);
845
- this.pat = { header: i, programs: n, crc32: o }, this.on.debug && this.on.debug({ pat: this.pat });
843
+ const r = t.getUint32(e);
844
+ this.pat = { header: i, programs: n, crc32: r }, this.on.debug && this.on.debug({ pat: this.pat });
846
845
  };
847
846
  // PMT表
848
847
  parsePMT = (t, s) => {
@@ -850,42 +849,42 @@ class Z {
850
849
  {
851
850
  const a = t.getUint8(e);
852
851
  e += 1;
853
- const r = t.getUint8(e);
854
- if (e += 1, r !== 2) throw new Error("Invalid PMT table_id");
852
+ const o = t.getUint8(e);
853
+ if (e += 1, o !== 2) throw new Error("Invalid PMT table_id");
855
854
  const d = t.getUint16(e) & 4095;
856
855
  e += 2;
857
856
  const c = t.getUint16(e);
858
857
  e += 2;
859
- const h = (t.getUint8(e) & 62) >> 1, p = t.getUint8(e) & 1;
858
+ const u = (t.getUint8(e) & 62) >> 1, p = t.getUint8(e) & 1;
860
859
  e += 1;
861
- const u = t.getUint8(e);
860
+ const h = t.getUint8(e);
862
861
  e += 1;
863
862
  const g = t.getUint8(e);
864
863
  e += 1;
865
864
  const f = t.getUint16(e) & 8191;
866
865
  e += 2;
867
866
  const m = t.getUint16(e) & 4095;
868
- e += 2, i = { pointer_field: a, table_id: r, section_length: d, transport_stream_id: c, version_number: h, current_next_indicator: p, section_number: u, last_section_number: g, pcr_pid: f, program_info_length: m };
867
+ e += 2, i = { pointer_field: a, table_id: o, section_length: d, transport_stream_id: c, version_number: u, current_next_indicator: p, section_number: h, last_section_number: g, pcr_pid: f, program_info_length: m };
869
868
  }
870
869
  const n = [];
871
870
  {
872
- const a = i.section_length - 9 - 4, r = e + a;
873
- for (; e < r; ) {
874
- const d = t.getUint8(e), c = J(d), h = t.getUint16(e + 1) & 8191, p = t.getUint16(e + 3) & 4095;
875
- if (e += 5, h < 32 || h > 8190) {
876
- console.warn(`Invalid elementary_pid: 0x${h.toString(16)}`);
871
+ const a = i.section_length - 9 - 4, o = e + a;
872
+ for (; e < o; ) {
873
+ const d = t.getUint8(e), c = J(d), u = t.getUint16(e + 1) & 8191, p = t.getUint16(e + 3) & 4095;
874
+ if (e += 5, u < 32 || u > 8190) {
875
+ console.warn(`Invalid elementary_pid: 0x${u.toString(16)}`);
877
876
  continue;
878
877
  }
879
- n.push({ kind: c, stream_type: d, elementary_pid: h, es_info_length: p });
878
+ n.push({ kind: c, stream_type: d, elementary_pid: u, es_info_length: p });
880
879
  }
881
880
  }
882
- const o = t.getUint32(e);
883
- this.pmt = { header: i, streams: n, crc32: o }, this.on.debug && this.on.debug({ pmt: this.pmt });
881
+ const r = t.getUint32(e);
882
+ this.pmt = { header: i, streams: n, crc32: r }, this.on.debug && this.on.debug({ pmt: this.pmt });
884
883
  };
885
884
  // AdaptationField
886
885
  parseAdaptationField = (t, s) => {
887
- let e = s, i, n, o, a;
888
- const r = t.getUint8(e), d = !!(r & 128), c = !!(r & 64), h = !!(r & 32), p = !!(r & 16), u = !!(r & 8), g = !!(r & 4), f = !!(r & 2), m = !!(r & 1);
886
+ let e = s, i, n, r, a;
887
+ const o = t.getUint8(e), d = !!(o & 128), c = !!(o & 64), u = !!(o & 32), p = !!(o & 16), h = !!(o & 8), g = !!(o & 4), f = !!(o & 2), m = !!(o & 1);
889
888
  e += 1;
890
889
  const b = (k, w) => {
891
890
  let U = BigInt(0);
@@ -893,27 +892,27 @@ class Z {
893
892
  const I = (k.getUint16(w + 4) & 1) << 8 | k.getUint16(w + 5);
894
893
  return U = U * 300n + BigInt(I), U;
895
894
  };
896
- if (p && (i = b(t, e), e += 6), u && (n = b(t, e), e += 6), g && (o = t.getInt8(e), e += 1), f) {
895
+ if (p && (i = b(t, e), e += 6), h && (n = b(t, e), e += 6), g && (r = t.getInt8(e), e += 1), f) {
897
896
  const k = t.getUint8(e);
898
897
  e += 1, a = new Uint8Array(t.buffer, e, k), e += k;
899
898
  }
900
- return { discontinuity_indicator: d, random_access_indicator: c, elementary_stream_priority_indicator: h, pcr_flag: p, opcr_flag: u, splicing_point_flag: g, transport_private_data_flag: f, adaptation_field_extension_flag: m, pcr: i, opcr: n, splice_countdown: o, transport_private_data: a };
899
+ return { discontinuity_indicator: d, random_access_indicator: c, elementary_stream_priority_indicator: u, pcr_flag: p, opcr_flag: h, splicing_point_flag: g, transport_private_data_flag: f, adaptation_field_extension_flag: m, pcr: i, opcr: n, splice_countdown: r, transport_private_data: a };
901
900
  };
902
901
  parseAudio = async (t) => {
903
902
  const s = new DataView(t.buffer);
904
903
  let e = 0, i, n;
905
904
  {
906
- const o = s.getUint8(e) === 0 && s.getUint8(e + 1) === 0 && s.getUint8(e + 2) === 1;
907
- if (e += 3, !o)
905
+ const r = s.getUint8(e) === 0 && s.getUint8(e + 1) === 0 && s.getUint8(e + 2) === 1;
906
+ if (e += 3, !r)
908
907
  throw new Error("invalid ts audio payload.");
909
908
  const a = s.getUint8(e);
910
909
  e += 1;
911
- const r = s.getUint8(e) << 8 | s.getUint8(e + 1);
910
+ const o = s.getUint8(e) << 8 | s.getUint8(e + 1);
912
911
  e += 2;
913
- let d, c, h, p, u;
912
+ let d, c, u, p, h;
914
913
  {
915
914
  const m = s.getUint8(e);
916
- e += 1, d = m >> 4 & 3, c = (m >> 3 & 1) === 1, h = (m >> 2 & 1) === 1, p = (m >> 1 & 1) === 1, u = (m & 1) === 1;
915
+ e += 1, d = m >> 4 & 3, c = (m >> 3 & 1) === 1, u = (m >> 2 & 1) === 1, p = (m >> 1 & 1) === 1, h = (m & 1) === 1;
917
916
  }
918
917
  let g, f;
919
918
  {
@@ -922,36 +921,36 @@ class Z {
922
921
  const b = m >> 6, k = s.getUint8(e);
923
922
  e += 1, (b & 2) === 2 && (g = this.parsePtsDts(s, e)), (b & 1) === 1 ? f = this.parsePtsDts(s, e + 5) : f = g, e += k;
924
923
  }
925
- i = { stream_id: a, pes_packet_length: r, scrambling_control: d, priority: c, data_alignment: h, copyright: p, original_copy: u, pts: g, dts: f };
924
+ i = { stream_id: a, pes_packet_length: o, scrambling_control: d, priority: c, data_alignment: u, copyright: p, original_copy: h, pts: g, dts: f };
926
925
  }
927
926
  n = t.slice(e);
928
927
  {
929
928
  if (!this.audioConfig && s.getUint8(e) === 255) {
930
- const h = s.getUint8(e + 2), p = s.getUint8(e + 3);
931
- let u, g;
932
- g = h >> 2 & 15, u = (h & 1) << 2 | p >> 6;
933
- const f = `mp4a.40.${u}`, b = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350][g];
934
- this.audioConfig = { kind: "audio", codec: f, sampleRate: b, numberOfChannels: u }, this.on.config && this.on.config(this.audioConfig);
929
+ const u = s.getUint8(e + 2), p = s.getUint8(e + 3);
930
+ let h, g;
931
+ g = u >> 2 & 15, h = (u & 1) << 2 | p >> 6;
932
+ const f = `mp4a.40.${h}`, b = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350][g];
933
+ this.audioConfig = { kind: "audio", codec: f, sampleRate: b, numberOfChannels: h }, this.on.config && this.on.config(this.audioConfig);
935
934
  }
936
- const { dts: o = 0, pts: a = 0 } = i, r = a - o, d = n.slice(7);
937
- return { kind: "audio", type: "key", dts: o, pts: a, cts: r, data: d };
935
+ const { dts: r = 0, pts: a = 0 } = i, o = a - r, d = n.slice(7);
936
+ return { kind: "audio", type: "key", dts: r, pts: a, cts: o, data: d };
938
937
  }
939
938
  };
940
939
  parseVideo = async (t) => {
941
940
  const s = new DataView(t.buffer);
942
941
  let e = 0, i, n;
943
942
  {
944
- const o = s.getUint8(e) === 0 && s.getUint8(e + 1) === 0 && s.getUint8(e + 2) === 1;
945
- if (e += 3, !o)
943
+ const r = s.getUint8(e) === 0 && s.getUint8(e + 1) === 0 && s.getUint8(e + 2) === 1;
944
+ if (e += 3, !r)
946
945
  throw new Error("invalid ts video payload.");
947
946
  const a = s.getUint8(e);
948
947
  e += 1;
949
- const r = s.getUint8(e) << 8 | s.getUint8(e + 1);
948
+ const o = s.getUint8(e) << 8 | s.getUint8(e + 1);
950
949
  e += 2;
951
- let d, c, h, p, u;
950
+ let d, c, u, p, h;
952
951
  {
953
952
  const m = s.getUint8(e);
954
- e += 1, d = m >> 4 & 3, c = (m >> 3 & 1) === 1, h = (m >> 2 & 1) === 1, p = (m >> 1 & 1) === 1, u = (m & 1) === 1;
953
+ e += 1, d = m >> 4 & 3, c = (m >> 3 & 1) === 1, u = (m >> 2 & 1) === 1, p = (m >> 1 & 1) === 1, h = (m & 1) === 1;
955
954
  }
956
955
  let g, f;
957
956
  {
@@ -960,22 +959,22 @@ class Z {
960
959
  const b = m >> 6, k = s.getUint8(e);
961
960
  e += 1, (b & 2) === 2 && (g = this.parsePtsDts(s, e)), (b & 1) === 1 ? f = this.parsePtsDts(s, e + 5) : f = g, e += k;
962
961
  }
963
- i = { stream_id: a, pes_packet_length: r, scrambling_control: d, priority: c, data_alignment: h, copyright: p, original_copy: u, pts: g, dts: f };
962
+ i = { stream_id: a, pes_packet_length: o, scrambling_control: d, priority: c, data_alignment: u, copyright: p, original_copy: h, pts: g, dts: f };
964
963
  }
965
964
  n = t.slice(e);
966
965
  {
967
- const o = this.getNalus(n);
966
+ const r = this.getNalus(n);
968
967
  if (!this.videoConfig) {
969
- let u, g;
970
- if (u = o.find((m) => m.type === 7)?.nalu.slice(4), g = o.find((m) => m.type === 8)?.nalu.slice(4), u && g) {
971
- const f = H(u, g), { codec: m } = P(f);
972
- this.videoConfig = { kind: "video", codec: m, description: f, sps: u, pps: g }, this.on.config && this.on.config(this.videoConfig);
968
+ let h, g;
969
+ if (h = r.find((m) => m.type === 7)?.nalu.slice(4), g = r.find((m) => m.type === 8)?.nalu.slice(4), h && g) {
970
+ const f = H(h, g), { codec: m } = P(f);
971
+ this.videoConfig = { kind: "video", codec: m, description: f, sps: h, pps: g }, this.on.config && this.on.config(this.videoConfig);
973
972
  }
974
973
  }
975
974
  const a = [];
976
- let r = "delta";
977
- for (const u of o) {
978
- const { type: g, nalu: f } = u;
975
+ let o = "delta";
976
+ for (const h of r) {
977
+ const { type: g, nalu: f } = h;
979
978
  switch (g) {
980
979
  case 6:
981
980
  // sei
@@ -983,23 +982,23 @@ class Z {
983
982
  a.push(f);
984
983
  break;
985
984
  case 1:
986
- r = "delta", a.push(f);
985
+ o = "delta", a.push(f);
987
986
  break;
988
987
  case 5:
989
- r = "key", a.push(f);
988
+ o = "key", a.push(f);
990
989
  break;
991
990
  }
992
991
  }
993
- const d = X(a), { dts: c = 0, pts: h = 0 } = i, p = h - c;
994
- return { kind: "video", type: r, dts: c, pts: h, cts: p, data: d, nalus: a };
992
+ const d = X(a), { dts: c = 0, pts: u = 0 } = i, p = u - c;
993
+ return { kind: "video", type: o, dts: c, pts: u, cts: p, data: d, nalus: a };
995
994
  }
996
995
  };
997
996
  /**
998
997
  * 解析 PTS/DTS 时间戳(33-bit,单位:90kHz)
999
998
  */
1000
999
  parsePtsDts(t, s) {
1001
- const e = t.getUint8(s), i = t.getUint8(s + 1), n = t.getUint8(s + 2), o = t.getUint8(s + 3), a = t.getUint8(s + 4), r = (BigInt(e) & 0b00001110n) << 29n | (BigInt(i) & 0b11111111n) << 22n | (BigInt(n) & 0b11111110n) << 14n | (BigInt(o) & 0b11111111n) << 7n | (BigInt(a) & 0b11111110n) >> 1n;
1002
- return Number(r) / 90;
1000
+ const e = t.getUint8(s), i = t.getUint8(s + 1), n = t.getUint8(s + 2), r = t.getUint8(s + 3), a = t.getUint8(s + 4), o = (BigInt(e) & 0b00001110n) << 29n | (BigInt(i) & 0b11111111n) << 22n | (BigInt(n) & 0b11111110n) << 14n | (BigInt(r) & 0b11111111n) << 7n | (BigInt(a) & 0b11111110n) >> 1n;
1001
+ return Number(o) / 90;
1003
1002
  }
1004
1003
  getNalus = (t) => {
1005
1004
  const s = [];
@@ -1019,10 +1018,10 @@ class Z {
1019
1018
  }
1020
1019
  break;
1021
1020
  }
1022
- let o = e - i;
1023
- if (t[e - 1] === 0 && (o -= 1), o !== 0) {
1024
- const a = t.slice(i, i + o), r = K(a);
1025
- s.push({ type: n, nalu: r });
1021
+ let r = e - i;
1022
+ if (t[e - 1] === 0 && (r -= 1), r !== 0) {
1023
+ const a = t.slice(i, i + r), o = K(a);
1024
+ s.push({ type: n, nalu: o });
1026
1025
  }
1027
1026
  }
1028
1027
  return s;
@@ -1041,53 +1040,53 @@ class tt {
1041
1040
  parse = async (t) => {
1042
1041
  let s = 0;
1043
1042
  for (this.header || (this.parseHeader(t, s), s += 9); this.isSurplusTag(t, s) !== !1; ) {
1044
- const i = this.parseTagHeader(t, s + 4), { tagType: n, dataSize: o, timestamp: a } = i;
1043
+ const i = this.parseTagHeader(t, s + 4), { tagType: n, dataSize: r, timestamp: a } = i;
1045
1044
  if (n) {
1046
- const r = this.parseTagBody(n, t, s + 4 + 11, o);
1045
+ const o = this.parseTagBody(n, t, s + 4 + 11, r);
1047
1046
  switch (n) {
1048
1047
  case "script":
1049
- this.on.info && this.on.info(r);
1048
+ this.on.info && this.on.info(o);
1050
1049
  break;
1051
1050
  case "audio":
1052
1051
  {
1053
- const { accPacketType: d } = r;
1052
+ const { accPacketType: d } = o;
1054
1053
  if (d === 0) {
1055
- const { codec: c, sampleRate: h, channelConfiguration: p } = r;
1056
- this.audioConfig = { kind: "audio", codec: c, sampleRate: h, numberOfChannels: p }, this.on.config && this.on.config(this.audioConfig);
1054
+ const { codec: c, sampleRate: u, channelConfiguration: p } = o;
1055
+ this.audioConfig = { kind: "audio", codec: c, sampleRate: u, numberOfChannels: p }, this.on.config && this.on.config(this.audioConfig);
1057
1056
  } else {
1058
- const { cts: c, data: h } = r, p = "key", u = c === void 0 ? void 0 : c + a;
1059
- this.on.chunk && this.on.chunk({ kind: "audio", type: p, dts: a, pts: u, cts: c, data: h });
1057
+ const { cts: c, data: u } = o, p = "key", h = c === void 0 ? void 0 : c + a;
1058
+ this.on.chunk && this.on.chunk({ kind: "audio", type: p, dts: a, pts: h, cts: c, data: u });
1060
1059
  }
1061
1060
  }
1062
1061
  break;
1063
1062
  case "video":
1064
1063
  {
1065
- const { avcPacketType: d } = r;
1064
+ const { avcPacketType: d } = o;
1066
1065
  if (d === 0) {
1067
- const { codec: c, sps: h, pps: p, data: u } = r;
1068
- this.videoConfig = { kind: "video", codec: c, description: u, sps: h, pps: p }, this.on.config && this.on.config(this.videoConfig);
1066
+ const { codec: c, sps: u, pps: p, data: h } = o;
1067
+ this.videoConfig = { kind: "video", codec: c, description: h, sps: u, pps: p }, this.on.config && this.on.config(this.videoConfig);
1069
1068
  } else {
1070
- const { frameType: c, cts: h, data: p, nalus: u } = r, g = c === 1 ? "key" : "delta", f = h === void 0 ? void 0 : h + a;
1071
- this.on.chunk && this.on.chunk({ kind: "video", type: g, dts: a, pts: f, cts: h, data: p, nalus: u });
1069
+ const { frameType: c, cts: u, data: p, nalus: h } = o, g = c === 1 ? "key" : "delta", f = u === void 0 ? void 0 : u + a;
1070
+ this.on.chunk && this.on.chunk({ kind: "video", type: g, dts: a, pts: f, cts: u, data: p, nalus: h });
1072
1071
  }
1073
1072
  }
1074
1073
  break;
1075
1074
  }
1076
- s = s + 4 + 11 + o;
1075
+ s = s + 4 + 11 + r;
1077
1076
  }
1078
- await new Promise((r) => setTimeout(() => r(!0), 8));
1077
+ await new Promise((o) => setTimeout(() => o(!0), 8));
1079
1078
  }
1080
1079
  return s;
1081
1080
  };
1082
1081
  // Header
1083
1082
  parseHeader = (t, s) => {
1084
- let e, i, n, o;
1083
+ let e, i, n, r;
1085
1084
  e = t.getUint8(s) << 16 | t.getUint8(s + 1) << 8 | t.getUint8(s + 2), i = t.getUint8(3);
1086
1085
  {
1087
- const r = t.getUint8(0).toString(2).padStart(5, "0").split(""), [, , d, , c] = r;
1086
+ const o = t.getUint8(0).toString(2).padStart(5, "0").split(""), [, , d, , c] = o;
1088
1087
  n = { audio: c === "1", video: d === "1" };
1089
1088
  }
1090
- o = t.getUint32(5), this.header = { signature: e, version: i, flags: n, dataOffset: o };
1089
+ r = t.getUint32(5), this.header = { signature: e, version: i, flags: n, dataOffset: r };
1091
1090
  };
1092
1091
  // 是否是完整tag
1093
1092
  isSurplusTag = (t, s) => {
@@ -1104,11 +1103,11 @@ class tt {
1104
1103
  return e;
1105
1104
  };
1106
1105
  parseTagHeader = (t, s) => {
1107
- let e, i, n, o, a;
1106
+ let e, i, n, r, a;
1108
1107
  {
1109
- const r = t.getUint8(s);
1108
+ const o = t.getUint8(s);
1110
1109
  let d;
1111
- switch (r) {
1110
+ switch (o) {
1112
1111
  case 18:
1113
1112
  d = "script";
1114
1113
  break;
@@ -1121,7 +1120,7 @@ class tt {
1121
1120
  }
1122
1121
  e = d;
1123
1122
  }
1124
- return i = T(t, s + 1), n = T(t, s + 4), o = t.getUint8(s + 7), a = T(t, s + 8), { tagType: e, dataSize: i, timestamp: n, timestampExtended: o, streamID: a };
1123
+ return i = T(t, s + 1), n = T(t, s + 4), r = t.getUint8(s + 7), a = T(t, s + 8), { tagType: e, dataSize: i, timestamp: n, timestampExtended: r, streamID: a };
1125
1124
  };
1126
1125
  parseTagBody = (t, s, e, i) => {
1127
1126
  let n;
@@ -1156,44 +1155,44 @@ class tt {
1156
1155
  };
1157
1156
  parseAudio = (t, s, e) => {
1158
1157
  let i = s;
1159
- const n = t.getUint8(i), o = n >> 4 & 15, a = n >> 2 & 3, r = n >> 1 & 1, d = n & 1;
1158
+ const n = t.getUint8(i), r = n >> 4 & 15, a = n >> 2 & 3, o = n >> 1 & 1, d = n & 1;
1160
1159
  i = i + 1;
1161
1160
  const c = t.getUint8(i);
1162
1161
  i = i + 1;
1163
- const h = e, p = new Uint8Array(t.buffer.slice(i, i + h));
1164
- if (o === 10 && c === 0) {
1165
- const u = t.getUint8(i), g = t.getUint8(i + 1), f = u >> 3 & 31, m = (u & 7) << 1 | g >> 7, b = g >> 3 & 15, k = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350], w = `mp4a.40.${f}`, U = k[m];
1166
- return { soundFormat: o, soundRate: a, soundSize: r, soundType: d, accPacketType: c, data: p, samplingFrequencyIndex: m, channelConfiguration: b, codec: w, sampleRate: U };
1162
+ const u = e, p = new Uint8Array(t.buffer.slice(i, i + u));
1163
+ if (r === 10 && c === 0) {
1164
+ const h = t.getUint8(i), g = t.getUint8(i + 1), f = h >> 3 & 31, m = (h & 7) << 1 | g >> 7, b = g >> 3 & 15, k = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350], w = `mp4a.40.${f}`, U = k[m];
1165
+ return { soundFormat: r, soundRate: a, soundSize: o, soundType: d, accPacketType: c, data: p, samplingFrequencyIndex: m, channelConfiguration: b, codec: w, sampleRate: U };
1167
1166
  }
1168
- return { soundFormat: o, soundRate: a, soundSize: r, soundType: d, accPacketType: c, data: p };
1167
+ return { soundFormat: r, soundRate: a, soundSize: o, soundType: d, accPacketType: c, data: p };
1169
1168
  };
1170
1169
  parseVideo = (t, s, e) => {
1171
1170
  let i = s;
1172
- const n = t.getUint8(i), o = n >> 4 & 15, a = n & 15;
1171
+ const n = t.getUint8(i), r = n >> 4 & 15, a = n & 15;
1173
1172
  i = i + 1;
1174
- const r = t.getUint8(i);
1173
+ const o = t.getUint8(i);
1175
1174
  i = i + 1;
1176
1175
  const d = T(t, i);
1177
1176
  i = i + 3;
1178
- const c = e - 5, h = new Uint8Array(t.buffer.slice(i, i + c));
1177
+ const c = e - 5, u = new Uint8Array(t.buffer.slice(i, i + c));
1179
1178
  switch (a) {
1180
1179
  case 7:
1181
- if (r === 0) {
1182
- const p = P(h);
1183
- return { frameType: o, codecID: a, avcPacketType: r, cts: d, data: h, ...p };
1184
- } else if (r === 1) {
1185
- const p = [], u = i + e - 5;
1186
- for (; !(i + 4 > u); ) {
1180
+ if (o === 0) {
1181
+ const p = P(u);
1182
+ return { frameType: r, codecID: a, avcPacketType: o, cts: d, data: u, ...p };
1183
+ } else if (o === 1) {
1184
+ const p = [], h = i + e - 5;
1185
+ for (; !(i + 4 > h); ) {
1187
1186
  const g = t.getUint32(i, !1), f = new Uint8Array(t.buffer.slice(i, i + 4 + g));
1188
1187
  i += 4 + g, p.push(f);
1189
1188
  }
1190
- return { frameType: o, codecID: a, avcPacketType: r, cts: d, data: h, nalus: p };
1189
+ return { frameType: r, codecID: a, avcPacketType: o, cts: d, data: u, nalus: p };
1191
1190
  }
1192
1191
  break;
1193
1192
  default:
1194
1193
  throw new Error("Unsupported codecID");
1195
1194
  }
1196
- return { frameType: o, codecID: a, avcPacketType: r, cts: d, data: h };
1195
+ return { frameType: r, codecID: a, avcPacketType: o, cts: d, data: u };
1197
1196
  };
1198
1197
  getAmfType = (t, s) => t.getUint8(s);
1199
1198
  getAMFName = (t, s, e) => {
@@ -1201,69 +1200,69 @@ class tt {
1201
1200
  return this.textDecoder?.decode(i) || "";
1202
1201
  };
1203
1202
  getAMFValue = (t, s, e) => {
1204
- let i = s, n, o = 0;
1203
+ let i = s, n, r = 0;
1205
1204
  switch (e) {
1206
1205
  case 0:
1207
- n = t.getFloat64(i, !1), o = 8;
1206
+ n = t.getFloat64(i, !1), r = 8;
1208
1207
  break;
1209
1208
  case 1:
1210
- n = !!t.getUint8(i), o = 1;
1209
+ n = !!t.getUint8(i), r = 1;
1211
1210
  break;
1212
1211
  case 2:
1213
1212
  {
1214
1213
  n = "";
1215
- const r = t.getUint16(i, !1);
1214
+ const o = t.getUint16(i, !1);
1216
1215
  i = i + 2;
1217
- const d = new Int8Array(t.buffer, i, r).filter((h) => h !== 0);
1218
- n = (this.textDecoder?.decode(d) || "").trim(), o = 2 + r;
1216
+ const d = new Int8Array(t.buffer, i, o).filter((u) => u !== 0);
1217
+ n = (this.textDecoder?.decode(d) || "").trim(), r = 2 + o;
1219
1218
  }
1220
1219
  break;
1221
1220
  case 3:
1222
1221
  for (n = {}; i < t.byteLength; ) {
1223
- const r = t.getUint16(i, !1);
1224
- if (r === 0) break;
1222
+ const o = t.getUint16(i, !1);
1223
+ if (o === 0) break;
1225
1224
  i = i + 2;
1226
- const d = this.getAMFName(t, i, r);
1227
- i = i + r;
1225
+ const d = this.getAMFName(t, i, o);
1226
+ i = i + o;
1228
1227
  const c = this.getAmfType(t, i);
1229
1228
  if (c === 6) break;
1230
1229
  i = i + 1;
1231
- const h = this.getAMFValue(t, i, c);
1232
- i = i + h.length, n[d] = h.value, o = 2 + r + 1 + h.length;
1230
+ const u = this.getAMFValue(t, i, c);
1231
+ i = i + u.length, n[d] = u.value, r = 2 + o + 1 + u.length;
1233
1232
  }
1234
1233
  break;
1235
1234
  case 8:
1236
1235
  {
1237
1236
  n = {};
1238
- const r = t.getUint32(i, !1);
1237
+ const o = t.getUint32(i, !1);
1239
1238
  i = i + 4;
1240
- for (let d = 0; d < r; d++) {
1239
+ for (let d = 0; d < o; d++) {
1241
1240
  const c = t.getUint16(i, !1);
1242
1241
  i = i + 2;
1243
- const h = this.getAMFName(t, i, c);
1242
+ const u = this.getAMFName(t, i, c);
1244
1243
  i = i + c;
1245
1244
  const p = this.getAmfType(t, i);
1246
1245
  i = i + 1;
1247
- const u = this.getAMFValue(t, i, p);
1248
- i = i + u.length, n[h] = u.value, o = 2 + c + 1 + u.length;
1246
+ const h = this.getAMFValue(t, i, p);
1247
+ i = i + h.length, n[u] = h.value, r = 2 + c + 1 + h.length;
1249
1248
  }
1250
1249
  }
1251
1250
  break;
1252
1251
  case 10:
1253
1252
  {
1254
1253
  n = [];
1255
- const r = t.getUint32(i, !1);
1254
+ const o = t.getUint32(i, !1);
1256
1255
  i = i + 4;
1257
- for (let d = 0; d < r; d++) {
1256
+ for (let d = 0; d < o; d++) {
1258
1257
  const c = this.getAmfType(t, i);
1259
1258
  i = i + 1;
1260
- const h = this.getAMFValue(t, i, c);
1261
- i = i + h.length, n.push(h.value), o = 1 + h.length;
1259
+ const u = this.getAMFValue(t, i, c);
1260
+ i = i + u.length, n.push(u.value), r = 1 + u.length;
1262
1261
  }
1263
1262
  }
1264
1263
  break;
1265
1264
  }
1266
- return { amfType: e, length: o, value: n };
1265
+ return { amfType: e, length: r, value: n };
1267
1266
  };
1268
1267
  }
1269
1268
  class st {
@@ -1413,14 +1412,14 @@ class it {
1413
1412
  if (this.frameTrack) {
1414
1413
  const [i, n] = this.fameTrackOption[this.pattern];
1415
1414
  if (t <= i && (this.isFrameTrack = !1), t >= n && (this.isFrameTrack = !0), this.isFrameTrack) {
1416
- const o = Math.min(1 + (t - i) / 100, this.maxDecodingSpeedRatio);
1417
- this.decodingSpeedRatio = Number(o.toFixed(1));
1415
+ const r = Math.min(1 + (t - i) / 100, this.maxDecodingSpeedRatio);
1416
+ this.decodingSpeedRatio = Number(r.toFixed(1));
1418
1417
  } else
1419
1418
  this.decodingSpeedRatio = 1;
1420
1419
  }
1421
1420
  if (this.on.analysis) {
1422
- const { decodingSpeed: i, decodingSpeedRatio: n, fps: o } = this;
1423
- this.on.analysis({ decodingSpeed: i, decodingSpeedRatio: n, fps: o, cacheLength: t });
1421
+ const { decodingSpeed: i, decodingSpeedRatio: n, fps: r } = this;
1422
+ this.on.analysis({ decodingSpeed: i, decodingSpeedRatio: n, fps: r, cacheLength: t });
1424
1423
  }
1425
1424
  if (!this.currentChunk) break;
1426
1425
  const { kind: s, init: e } = this.currentChunk;
@@ -1480,8 +1479,8 @@ class nt {
1480
1479
  const { timestamp: s } = t;
1481
1480
  let { bitmap: e } = t;
1482
1481
  if (this.cutOption) {
1483
- const { sx: n = 0, sy: o = 0, sw: a = e.width, sh: r = e.height } = this.cutOption;
1484
- e = await createImageBitmap(e, n, o, a, r);
1482
+ const { sx: n = 0, sy: r = 0, sw: a = e.width, sh: o = e.height } = this.cutOption;
1483
+ e = await createImageBitmap(e, n, r, a, o);
1485
1484
  }
1486
1485
  const i = new VideoFrame(e, { timestamp: s });
1487
1486
  this.cutOption && e.close(), this.writer.write(i), i.close();
@@ -1,4 +1,4 @@
1
1
  (function(U,_){typeof exports=="object"&&typeof module<"u"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):(U=typeof globalThis<"u"?globalThis:U||self,_(U["pr-player"]={}))})(this,(function(U){"use strict";const _='(function(){"use strict";class P{pendingPayloads=[];payload=new Uint8Array(0);chunks=[];push=t=>{this.pendingPayloads.push(t)};next=(t=0)=>{this.payload=this.payload.slice(t);const s=this.pendingPayloads.shift();if(!s)return!1;const e=new Uint8Array(this.payload.byteLength+s.byteLength);return e.set(this.payload,0),e.set(s,this.payload.byteLength),this.payload=e,new DataView(this.payload.buffer)};pushChunk=t=>{this.chunks.push(t),this.chunks.length>1e3&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.chunks=[]}}const I=(y,t)=>{const s=new Uint8Array(y),e=new Uint8Array(t),n=new Uint8Array(11+s.length+e.length);let a=0;return n[a++]=1,n[a++]=s[1],n[a++]=s[2],n[a++]=s[3],n[a++]=255,n[a++]=225,n[a++]=s.length>>8&255,n[a++]=s.length&255,n.set(s,a),a+=s.length,n[a++]=1,n[a++]=e.length>>8&255,n[a++]=e.length&255,n.set(e,a),n},T=y=>{let t=0;const s=new DataView(y.buffer),e=s.getUint8(t);if(t=t+1,e!==1)throw new Error("Invalid AVC version");const n=s.getUint8(t)&255;t=t+1;const a=s.getUint8(t)&255;t=t+1;const o=s.getUint8(t)&255;t=t+1;const c=`avc1.${Array.from([n,a,o],U=>U.toString(16).padStart(2,"0")).join("")}`,r=(s.getUint8(t)&3)-1;t=t+1;const g=s.getUint8(t)&31;t=t+1;const p=s.getUint16(t,!1);t=t+2;const h=new Uint8Array(s.buffer.slice(t,t+p));t=t+p;const d=s.getUint8(t)&31;t=t+1;const u=s.getUint16(t,!1);t=t+2;const f=new Uint8Array(s.buffer.slice(t,t+u));return t=t+u,{version:e,codec:c,profile:n,compatibility:a,level:o,lengthSizeMinusOne:r,numOfSequenceParameterSets:g,sequenceParameterSetLength:p,sps:h,numOfPictureParameterSets:d,pictureParameterSetLength:u,pps:f}},M=y=>{const t=new Uint8Array(4+y.length);return new DataView(t.buffer).setUint32(0,y.length,!1),t.set(y,4),t},C=y=>{let t=0;for(const n of y)t+=n.length;const s=new Uint8Array(t);let e=0;for(const n of y){const a=n;s.set(a,e),e+=a.length}return s},D=y=>{let t="unknown";switch(y){case 1:case 2:case 27:case 36:t="video";break;case 3:case 4:case 15:t="audio";break;case 6:t="subtitle";break;case 134:t="ad";break}return t};class x{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async t=>{let s=0;for(;!(s+188>t.byteLength);){if(t.getInt8(s)!=71){s++;continue}await this.parsePacket(t,s),s+=188}return s};parsePacket=async(t,s)=>{if(s+188>t.byteLength)throw new Error("Invalid TS packet");if(t.getUint8(s)!==71)throw new Error("Invalid TS packet");let e=s;const n=this.parseHeader(t,e);e+=4;const{transport_error_indicator:a,pid:o,payload_unit_start_indicator:l,adaptation_field_control:i}=n;if(a===1||o===void 0)return;let c=184;if(i===2||i===3){const r=t.getUint8(e);e+=1,this.parseAdaptationField(t,e),e+=r,c-=r}if(i===3&&(c-=1),i===1||i===3){const r=new Uint8Array(t.buffer.slice(e,e+c));if(o===0)return this.parsePAT(t,e);{const{programs:h=[]}=this.pat||{};if(h.find(u=>u.pmt_pid===o))return this.parsePMT(t,e)}const{streams:g=[]}=this.pmt||{},p=g.find(h=>h.elementary_pid===o);if(p){if(l===1){const h=this.payloadMap.get(o);if(h){switch(p.kind){case"audio":{const d=await this.parseAudio(h);this.on.chunk&&this.on.chunk(d)}break;case"video":{const d=await this.parseVideo(h);this.on.chunk&&this.on.chunk(d),await new Promise(u=>setTimeout(()=>u(!0),0))}break}this.payloadMap.delete(o)}}{this.payloadMap.has(o)||this.payloadMap.set(o,new Uint8Array);const h=this.payloadMap.get(o),d=new Uint8Array(h.byteLength+r.byteLength);d.set(h,0),d.set(r,h.byteLength),this.payloadMap.set(o,d)}}}};parseHeader=(t,s)=>{let e=s;const n=t.getUint8(e),a=t.getUint8(e+1),o=t.getUint8(e+2),l=t.getUint8(e+3),i=(a&128)>>7;if(i===1)return{sync_byte:n,transport_error_indicator:i};const c=(a&64)>>6,r=(a&32)>>5,g=(a&31)<<8|o,p=(l&192)>>6,h=l>>4&3,d=l&15;return{sync_byte:n,transport_error_indicator:i,payload_unit_start_indicator:c,transport_priority:r,pid:g,transport_scrambling_control:p,adaptation_field_control:h,continuity_counter:d}};parsePAT=(t,s)=>{let e=s,n;{const l=t.getUint8(e);e+=1;const i=t.getUint8(e);if(e+=1,i!==0)throw new Error("Invalid PAT table_id");const c=t.getUint16(e)&4095;e+=2;const r=t.getUint16(e);e+=2;const g=(t.getUint8(e)&62)>>1,p=t.getUint8(e)&1;e+=1;const h=t.getUint8(e);e+=1;const d=t.getUint8(e);e+=1,n={pointer_field:l,table_id:i,section_length:c,transport_stream_id:r,version_number:g,current_next_indicator:p,section_number:h,last_section_number:d}}const a=[];{const l=n.section_length-5-4,i=e+l;for(;e<i;){const c=t.getUint16(e),r=t.getUint16(e+2)&8191;e+=4,c!==0&&r>=32&&r<=8190&&a.push({program_number:c,pmt_pid:r})}}const o=t.getUint32(e);this.pat={header:n,programs:a,crc32:o},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(t,s)=>{let e=s,n;{const l=t.getUint8(e);e+=1;const i=t.getUint8(e);if(e+=1,i!==2)throw new Error("Invalid PMT table_id");const c=t.getUint16(e)&4095;e+=2;const r=t.getUint16(e);e+=2;const g=(t.getUint8(e)&62)>>1,p=t.getUint8(e)&1;e+=1;const h=t.getUint8(e);e+=1;const d=t.getUint8(e);e+=1;const u=t.getUint16(e)&8191;e+=2;const f=t.getUint16(e)&4095;e+=2,n={pointer_field:l,table_id:i,section_length:c,transport_stream_id:r,version_number:g,current_next_indicator:p,section_number:h,last_section_number:d,pcr_pid:u,program_info_length:f}}const a=[];{const l=n.section_length-9-4,i=e+l;for(;e<i;){const c=t.getUint8(e),r=D(c),g=t.getUint16(e+1)&8191,p=t.getUint16(e+3)&4095;if(e+=5,g<32||g>8190){console.warn(`Invalid elementary_pid: 0x${g.toString(16)}`);continue}a.push({kind:r,stream_type:c,elementary_pid:g,es_info_length:p})}}const o=t.getUint32(e);this.pmt={header:n,streams:a,crc32:o},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(t,s)=>{let e=s,n,a,o,l;const i=t.getUint8(e),c=!!(i&128),r=!!(i&64),g=!!(i&32),p=!!(i&16),h=!!(i&8),d=!!(i&4),u=!!(i&2),f=!!(i&1);e+=1;const U=(_,b)=>{let m=BigInt(0);m|=BigInt(_.getUint16(b))<<25n,m|=BigInt(_.getUint16(b+1))<<17n,m|=BigInt(_.getUint16(b+2))<<9n,m|=BigInt(_.getUint16(b+3))<<1n,m|=BigInt(_.getUint16(b+4)>>7);const S=(_.getUint16(b+4)&1)<<8|_.getUint16(b+5);return m=m*300n+BigInt(S),m};if(p&&(n=U(t,e),e+=6),h&&(a=U(t,e),e+=6),d&&(o=t.getInt8(e),e+=1),u){const _=t.getUint8(e);e+=1,l=new Uint8Array(t.buffer,e,_),e+=_}return{discontinuity_indicator:c,random_access_indicator:r,elementary_stream_priority_indicator:g,pcr_flag:p,opcr_flag:h,splicing_point_flag:d,transport_private_data_flag:u,adaptation_field_extension_flag:f,pcr:n,opcr:a,splice_countdown:o,transport_private_data:l}};parseAudio=async t=>{const s=new DataView(t.buffer);let e=0,n,a;{const o=s.getUint8(e)===0&&s.getUint8(e+1)===0&&s.getUint8(e+2)===1;if(e+=3,!o)throw new Error("invalid ts audio payload.");const l=s.getUint8(e);e+=1;const i=s.getUint8(e)<<8|s.getUint8(e+1);e+=2;let c,r,g,p,h;{const f=s.getUint8(e);e+=1,c=f>>4&3,r=(f>>3&1)===1,g=(f>>2&1)===1,p=(f>>1&1)===1,h=(f&1)===1}let d,u;{const f=s.getUint8(e);e+=1;const U=f>>6,_=s.getUint8(e);e+=1,(U&2)===2&&(d=this.parsePtsDts(s,e)),(U&1)===1?u=this.parsePtsDts(s,e+5):u=d,e+=_}n={stream_id:l,pes_packet_length:i,scrambling_control:c,priority:r,data_alignment:g,copyright:p,original_copy:h,pts:d,dts:u}}a=t.slice(e);{if(!this.audioConfig&&s.getUint8(e)===255){const g=s.getUint8(e+2),p=s.getUint8(e+3);let h,d;d=g>>2&15,h=(g&1)<<2|p>>6;const u=`mp4a.40.${h}`,U=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][d];this.audioConfig={kind:"audio",codec:u,sampleRate:U,numberOfChannels:h},this.on.config&&this.on.config(this.audioConfig)}const{dts:o=0,pts:l=0}=n,i=l-o,c=a.slice(7);return{kind:"audio",type:"key",dts:o,pts:l,cts:i,data:c}}};parseVideo=async t=>{const s=new DataView(t.buffer);let e=0,n,a;{const o=s.getUint8(e)===0&&s.getUint8(e+1)===0&&s.getUint8(e+2)===1;if(e+=3,!o)throw new Error("invalid ts video payload.");const l=s.getUint8(e);e+=1;const i=s.getUint8(e)<<8|s.getUint8(e+1);e+=2;let c,r,g,p,h;{const f=s.getUint8(e);e+=1,c=f>>4&3,r=(f>>3&1)===1,g=(f>>2&1)===1,p=(f>>1&1)===1,h=(f&1)===1}let d,u;{const f=s.getUint8(e);e+=1;const U=f>>6,_=s.getUint8(e);e+=1,(U&2)===2&&(d=this.parsePtsDts(s,e)),(U&1)===1?u=this.parsePtsDts(s,e+5):u=d,e+=_}n={stream_id:l,pes_packet_length:i,scrambling_control:c,priority:r,data_alignment:g,copyright:p,original_copy:h,pts:d,dts:u}}a=t.slice(e);{const o=this.getNalus(a);if(!this.videoConfig){let h,d;if(h=o.find(f=>f.type===7)?.nalu.slice(4),d=o.find(f=>f.type===8)?.nalu.slice(4),h&&d){const u=I(h,d),{codec:f}=T(u);this.videoConfig={kind:"video",codec:f,description:u,sps:h,pps:d},this.on.config&&this.on.config(this.videoConfig)}}const l=[];let i="delta";for(const h of o){const{type:d,nalu:u}=h;switch(d){case 6:case 9:l.push(u);break;case 1:i="delta",l.push(u);break;case 5:i="key",l.push(u);break}}const c=C(l),{dts:r=0,pts:g=0}=n,p=g-r;return{kind:"video",type:i,dts:r,pts:g,cts:p,data:c,nalus:l}}};parsePtsDts(t,s){const e=t.getUint8(s),n=t.getUint8(s+1),a=t.getUint8(s+2),o=t.getUint8(s+3),l=t.getUint8(s+4),i=(BigInt(e)&0b00001110n)<<29n|(BigInt(n)&0b11111111n)<<22n|(BigInt(a)&0b11111110n)<<14n|(BigInt(o)&0b11111111n)<<7n|(BigInt(l)&0b11111110n)>>1n;return Number(i)/90}getNalus=t=>{const s=[];let e=0;for(;!(e+4>t.byteLength);){if(t[e]!==0||t[e+1]!==0||t[e+2]!==1){e+=1;continue}e+=3;let n=e;const a=t[e]&31;for(e+=1;!(e+1>t.byteLength);){if(t[e]!==0||t[e+1]!==0||t[e+2]!==1){e+=1;continue}break}let o=e-n;if(t[e-1]===0&&(o-=1),o!==0){const l=t.slice(n,n+o),i=M(l);s.push({type:a,nalu:i})}}return s}}const k=(y,t)=>y.getUint8(t)<<16|y.getUint8(t+1)<<8|y.getUint8(t+2);class L{audioConfig;videoConfig;header;textDecoder=new TextDecoder("utf-8");on={};constructor(){}parse=async t=>{let s=0;for(this.header||(this.parseHeader(t,s),s+=9);this.isSurplusTag(t,s)!==!1;){const n=this.parseTagHeader(t,s+4),{tagType:a,dataSize:o,timestamp:l}=n;if(a){const i=this.parseTagBody(a,t,s+4+11,o);switch(a){case"script":this.on.info&&this.on.info(i);break;case"audio":{const{accPacketType:c}=i;if(c===0){const{codec:r,sampleRate:g,channelConfiguration:p}=i;this.audioConfig={kind:"audio",codec:r,sampleRate:g,numberOfChannels:p},this.on.config&&this.on.config(this.audioConfig)}else{const{cts:r,data:g}=i,p="key",h=r===void 0?void 0:r+l;this.on.chunk&&this.on.chunk({kind:"audio",type:p,dts:l,pts:h,cts:r,data:g})}}break;case"video":{const{avcPacketType:c}=i;if(c===0){const{codec:r,sps:g,pps:p,data:h}=i;this.videoConfig={kind:"video",codec:r,description:h,sps:g,pps:p},this.on.config&&this.on.config(this.videoConfig)}else{const{frameType:r,cts:g,data:p,nalus:h}=i,d=r===1?"key":"delta",u=g===void 0?void 0:g+l;this.on.chunk&&this.on.chunk({kind:"video",type:d,dts:l,pts:u,cts:g,data:p,nalus:h})}}break}s=s+4+11+o}await new Promise(i=>setTimeout(()=>i(!0),8))}return s};parseHeader=(t,s)=>{let e,n,a,o;e=t.getUint8(s)<<16|t.getUint8(s+1)<<8|t.getUint8(s+2),n=t.getUint8(3);{const i=t.getUint8(0).toString(2).padStart(5,"0").split(""),[,,c,,r]=i;a={audio:r==="1",video:c==="1"}}o=t.getUint32(5),this.header={signature:e,version:n,flags:a,dataOffset:o}};isSurplusTag=(t,s)=>{let e=!0;const n=t.byteLength;if(s+4>n)e=!1;else if(s+4+11>n)e=!1;else{const a=k(t,s+4+1);s+4+11+a>n&&(e=!1)}return e};parseTagHeader=(t,s)=>{let e,n,a,o,l;{const i=t.getUint8(s);let c;switch(i){case 18:c="script";break;case 8:c="audio";break;case 9:c="video";break}e=c}return n=k(t,s+1),a=k(t,s+4),o=t.getUint8(s+7),l=k(t,s+8),{tagType:e,dataSize:n,timestamp:a,timestampExtended:o,streamID:l}};parseTagBody=(t,s,e,n)=>{let a;switch(t){case"script":a=this.parseMetaData(s,e);break;case"audio":a=this.parseAudio(s,e,n);break;case"video":a=this.parseVideo(s,e,n);break}return a};parseMetaData=(t,s)=>{let e=s;{if(t.getUint8(e)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");e=e+1}const n=t.getUint16(e,!1);e=e+2;{const l=new Int8Array(t.buffer.slice(e,e+n));if((this.textDecoder?.decode(l)||"")!=="onMetaData")throw new Error("Expected \'onMetaData\' string");e=e+n}const a=this.getAmfType(t,e);return e=e+1,this.getAMFValue(t,e,a).value};parseAudio=(t,s,e)=>{let n=s;const a=t.getUint8(n),o=a>>4&15,l=a>>2&3,i=a>>1&1,c=a&1;n=n+1;const r=t.getUint8(n);n=n+1;const g=e,p=new Uint8Array(t.buffer.slice(n,n+g));if(o===10&&r===0){const h=t.getUint8(n),d=t.getUint8(n+1),u=h>>3&31,f=(h&7)<<1|d>>7,U=d>>3&15,_=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],b=`mp4a.40.${u}`,m=_[f];return{soundFormat:o,soundRate:l,soundSize:i,soundType:c,accPacketType:r,data:p,samplingFrequencyIndex:f,channelConfiguration:U,codec:b,sampleRate:m}}return{soundFormat:o,soundRate:l,soundSize:i,soundType:c,accPacketType:r,data:p}};parseVideo=(t,s,e)=>{let n=s;const a=t.getUint8(n),o=a>>4&15,l=a&15;n=n+1;const i=t.getUint8(n);n=n+1;const c=k(t,n);n=n+3;const r=e-5,g=new Uint8Array(t.buffer.slice(n,n+r));switch(l){case 7:if(i===0){const p=T(g);return{frameType:o,codecID:l,avcPacketType:i,cts:c,data:g,...p}}else if(i===1){const p=[],h=n+e-5;for(;!(n+4>h);){const d=t.getUint32(n,!1),u=new Uint8Array(t.buffer.slice(n,n+4+d));n+=4+d,p.push(u)}return{frameType:o,codecID:l,avcPacketType:i,cts:c,data:g,nalus:p}}break;default:throw new Error("Unsupported codecID")}return{frameType:o,codecID:l,avcPacketType:i,cts:c,data:g}};getAmfType=(t,s)=>t.getUint8(s);getAMFName=(t,s,e)=>{const n=new Uint8Array(t.buffer.slice(s,s+e));return this.textDecoder?.decode(n)||""};getAMFValue=(t,s,e)=>{let n=s,a,o=0;switch(e){case 0:a=t.getFloat64(n,!1),o=8;break;case 1:a=!!t.getUint8(n),o=1;break;case 2:{a="";const i=t.getUint16(n,!1);n=n+2;const c=new Int8Array(t.buffer,n,i).filter(g=>g!==0);a=(this.textDecoder?.decode(c)||"").trim(),o=2+i}break;case 3:for(a={};n<t.byteLength;){const i=t.getUint16(n,!1);if(i===0)break;n=n+2;const c=this.getAMFName(t,n,i);n=n+i;const r=this.getAmfType(t,n);if(r===6)break;n=n+1;const g=this.getAMFValue(t,n,r);n=n+g.length,a[c]=g.value,o=2+i+1+g.length}break;case 8:{a={};const i=t.getUint32(n,!1);n=n+4;for(let c=0;c<i;c++){const r=t.getUint16(n,!1);n=n+2;const g=this.getAMFName(t,n,r);n=n+r;const p=this.getAmfType(t,n);n=n+1;const h=this.getAMFValue(t,n,p);n=n+h.length,a[g]=h.value,o=2+r+1+h.length}}break;case 10:{a=[];const i=t.getUint32(n,!1);n=n+4;for(let c=0;c<i;c++){const r=this.getAmfType(t,n);n=n+1;const g=this.getAMFValue(t,n,r);n=n+g.length,a.push(g.value),o=1+g.length}}break}return{amfType:e,length:o,value:a}}}class O{pattern;cacher=new P;isParseing=!1;offset=0;parser;on={};constructor(){}init=t=>{switch(this.destroy(),this.pattern=t,this.pattern){case"flv":this.parser=new L;break;case"hls":this.parser=new x;break;default:throw new Error("is error pattern.")}this.parser.on.debug=s=>this.on.debug&&this.on.debug(s),this.parser.on.info=s=>this.on.info&&this.on.info(s),this.parser.on.config=s=>this.on.config&&this.on.config(s),this.parser.on.chunk=s=>{this.cacher.pushChunk(s),this.on.chunk&&this.on.chunk(s)}};push=t=>{this.cacher.push(t),this.isParseing===!1&&this.parse()};destroy=()=>{this.cacher.destroy(),this.isParseing=!1,this.offset=0};parse=async()=>{try{if(this.isParseing=!0,!this.pattern)throw new Error("You need to set the pattern.");if(!this.parser)throw new Error("You need to init parser.");for(;;){const t=this.cacher.next(this.offset);if(this.offset=0,!t)break;this.offset=await this.parser.parse(t)}this.isParseing=!1}catch{this.destroy()}}}const A=new O;A.on.info=y=>postMessage({action:"on.info",data:y}),A.on.config=y=>postMessage({action:"on.config",data:y}),A.on.chunk=y=>postMessage({action:"on.chunk",data:y}),A.on.debug=y=>postMessage({action:"on.debug",data:y}),onmessage=y=>{const{action:t,data:s}=y.data,e=A[t];e&&e(s)}})();\n',v=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",_],{type:"text/javascript;charset=utf-8"});function N(l){let t;try{if(t=v&&(self.URL||self.webkitURL).createObjectURL(v),!t)throw"";const s=new Worker(t,{name:l?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(_),{name:l?.name})}}class A{worker=new N;on={};constructor(){this.worker.onmessage=t=>{const{action:s,data:e}=t.data;switch(s){case"on.info":this.on.info&&this.on.info(e);break;case"on.config":this.on.config&&this.on.config(e);break;case"on.chunk":this.on.chunk&&this.on.chunk(e);break;case"on.debug":this.on.debug&&this.on.debug(e);break}}}init=t=>this.worker.postMessage({action:"init",data:t});push=t=>this.worker.postMessage({action:"push",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}const x=`(function(){"use strict";class r{pattern="flv";audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;baseTime=0;pendingChunks=[];currentChunk;isProcessing=!1;decodeTimer=0;frameTrack=!1;isFrameTrack=!1;fameTrackOption={flv:[30,50],hls:[200,300],dash:[50,100],rtmp:[50,100]};decodingSpeedRatio=1;maxDecodingSpeedRatio=2;decodingSpeed=16;fps=0;firstVideoChunkTimestamp;secondVideoChunkTimestamp;frameStartTime;lastRenderTime;nextRenderTime;on={audio:{},video:{}};constructor(){}init=e=>{this.destroy(),this.pattern=e,this.baseTime=new Date().getTime()-performance.now(),this.initDecodeInterval()};initAudio=e=>{this.audio.destroy(),this.audioDecoderConfig={...e},this.audioDecoder=new AudioDecoder({output:i=>{const o=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:i,playbackRate:o})},error:i=>{this.on.audio.error&&this.on.audio.error(i)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:async i=>{this.frameStartTime||(this.frameStartTime=i.timestamp);const o=i.timestamp-this.frameStartTime+this.baseTime*1e3,s=await createImageBitmap(i);i.close(),s.width>0&&s.height>0?(this.on.video.decode&&this.on.video.decode({timestamp:o,bitmap:s}),this.currentChunk&&this.currentChunk.kind==="video"&&this.currentChunk.nalus&&this.on.nalus&&this.on.nalus(this.currentChunk.nalus)):s.close()},error:i=>{this.on.video.error&&this.on.video.error(i)}}),this.videoDecoder.configure(this.videoDecoderConfig)};setFrameTrack=e=>{this.frameTrack=e,this.frameTrack===!1&&(this.decodingSpeedRatio=1)};push=e=>{this.pendingChunks.push(e)};destroy=()=>{this.audio.destroy(),this.video.destroy(),this.pendingChunks=[],this.firstVideoChunkTimestamp=void 0,this.secondVideoChunkTimestamp=void 0,this.frameStartTime=void 0,this.lastRenderTime=void 0,this.nextRenderTime=void 0,clearInterval(this.decodeTimer)};initDecodeInterval=()=>{let e=this.decodingSpeed/this.decodingSpeedRatio;const i=this.baseTime+performance.now();if(this.lastRenderTime||(this.lastRenderTime=i),this.fps=Math.round(1e3/(i-this.lastRenderTime)),this.lastRenderTime=i,this.nextRenderTime){const o=this.lastRenderTime-this.nextRenderTime;e-=o}this.nextRenderTime=this.lastRenderTime+e,this.decodeTimer=setTimeout(()=>{this.decode(),this.initDecodeInterval()},e)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;;){this.currentChunk=this.pendingChunks.shift();const e=this.pendingChunks.length;if(this.frameTrack){const[s,n]=this.fameTrackOption[this.pattern];if(e<=s&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){const a=Math.min(1+(e-s)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(a.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){const{decodingSpeed:s,decodingSpeedRatio:n,fps:a}=this;this.on.analysis({decodingSpeed:s,decodingSpeedRatio:n,fps:a,cacheLength:e})}if(!this.currentChunk)break;const{kind:i,init:o}=this.currentChunk;switch(i){case"audio":this.decodeAudio(o);break;case"video":this.decodeVideo(o);break}if(i==="video")break}this.isProcessing=!1}};decodeAudio=e=>{if(!this.audioDecoder)return;const i=new EncodedAudioChunk(e);this.audioDecoder.decode(i)};decodeVideo=e=>{if(this.videoDecoder&&(e.type==="key"&&(this.hasKeyFrame=!0),this.firstVideoChunkTimestamp?this.secondVideoChunkTimestamp||(this.secondVideoChunkTimestamp=e.timestamp,this.decodingSpeed=(this.secondVideoChunkTimestamp-this.firstVideoChunkTimestamp)/1e3):this.firstVideoChunkTimestamp=e.timestamp,this.hasKeyFrame)){const i=new EncodedVideoChunk(e);this.videoDecoder.decode(i)}};audio={flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}}const d=new r;d.on.audio.decode=t=>postMessage({action:"on.audio.decode",data:t}),d.on.audio.error=t=>postMessage({action:"on.audio.error",data:t}),d.on.video.decode=t=>postMessage({action:"on.video.decode",data:t}),d.on.video.error=t=>postMessage({action:"on.video.error",data:t}),d.on.nalus=t=>postMessage({action:"on.nalus",data:t}),d.on.analysis=t=>postMessage({action:"on.analysis",data:t}),onmessage=t=>{const{action:e,data:i}=t.data,o=d[e];o&&o(i)}})();
2
- `,D=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",x],{type:"text/javascript;charset=utf-8"});function B(l){let t;try{if(t=D&&(self.URL||self.webkitURL).createObjectURL(D),!t)throw"";const s=new Worker(t,{name:l?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(x),{name:l?.name})}}class S{worker=new B;on={audio:{},video:{}};constructor(){this.worker.onmessage=t=>{const{action:s,data:e}=t.data;switch(s){case"on.audio.decode":this.on.audio.decode&&this.on.audio.decode(e);break;case"on.audio.error":this.on.audio.error&&this.on.audio.error(e);break;case"on.video.decode":this.on.video.decode&&this.on.video.decode(e);break;case"on.video.error":this.on.video.error&&this.on.video.error(e);break;case"on.nalus":this.on.nalus&&this.on.nalus(e);break;case"on.analysis":this.on.analysis&&this.on.analysis(e);break}}}init=t=>this.worker.postMessage({action:"init",data:t});initAudio=t=>this.worker.postMessage({action:"initAudio",data:t});initVideo=t=>this.worker.postMessage({action:"initVideo",data:t});push=t=>this.worker.postMessage({action:"push",data:t});setFrameTrack=t=>this.worker.postMessage({action:"setFrameTrack",data:t});destroy=()=>{this.worker.postMessage({action:"destroy"}),this.worker.terminate()}}var G=Object.defineProperty,O=(l,t,s)=>t in l?G(l,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):l[t]=s,m=(l,t,s)=>O(l,typeof t!="symbol"?t+"":t,s);class E{constructor(t,s){m(this,"inputStream",new MediaStream),m(this,"outputStream",new MediaStream),m(this,"inputGain",1),m(this,"enhanceGain",1),m(this,"bgsGain",1),m(this,"bgmGain",1),m(this,"outputGain",1),m(this,"mixAudioMap",new Map),m(this,"audioContext",new AudioContext),m(this,"sourceNode"),m(this,"inputGainNode"),m(this,"enhanceGainNode"),m(this,"bgsGainNode"),m(this,"bgmGainNode"),m(this,"analyserNode"),m(this,"analyserArrayData"),m(this,"outputGainNode"),m(this,"destinationNode"),m(this,"filterStream",e=>e),m(this,"stop",()=>{{const e=this.inputStream.getTracks();for(const i of e)i.stop(),this.inputStream.removeTrack(i)}}),m(this,"getStream",()=>this.filterStream(this.outputStream)),m(this,"setMute",(e=!0)=>{e?this.analyserNode.disconnect(this.outputGainNode):this.analyserNode.connect(this.outputGainNode)}),m(this,"setInputGain",e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),m(this,"setEnhanceGain",async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)}),m(this,"setBgsGain",e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),m(this,"setBgmGain",e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),m(this,"setOutputGain",e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)}),m(this,"getVolume",()=>{const{analyserNode:e,analyserArrayData:i}=this;e.getByteFrequencyData(i);let n=0;for(let o=0;o<i.length;o++)n+=i[o];return Math.ceil(n/i.length)}),m(this,"mixAudio",(e,i="bgm")=>new Promise(async(n,o)=>{try{{const d=this.mixAudioMap.get(i);d&&d.stop()}const a=i==="bgs"?this.bgsGainNode:this.bgmGainNode,r=this.audioContext.createBufferSource();this.mixAudioMap.set(i,r),r.buffer=e,r.connect(a),r.onended=()=>{r.disconnect(a),this.mixAudioMap.delete(i),n(!0)},r.start(0)}catch(a){o(a)}})),m(this,"mixAudioStop",e=>{const i=this.mixAudioMap.get(e);i?.stop()}),m(this,"changeMix",(e,i)=>{const n=e==="bgs"?this.bgsGainNode:this.bgmGainNode;i?n.connect(this.destinationNode):n.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:i,enhanceGainNode:n,bgsGainNode:o,bgmGainNode:a,analyserNode:r,outputGainNode:d,destinationNode:c}=this;e.connect(i),i.connect(n),n.connect(r),o.connect(r),a.connect(r),n.connect(c),o.connect(c),a.connect(c),r.connect(d),d.connect(this.audioContext.destination)}this.setMute(!0),this.audioContext.resume()}}const W=async(l,t)=>{try{const{format:s,numberOfChannels:e,numberOfFrames:i,sampleRate:n}=t,o=l.createBuffer(e,i,n);for(let a=0;a<e;a++){const r=t.allocationSize({planeIndex:a}),d=new Uint8Array(r);t.copyTo(d,{planeIndex:a});const c=new DataView(d.buffer),h=o.getChannelData(a);for(let p=0;p<i;p++){let u;switch(s){case"s16":case"s16-planar":u=c.getInt16(p*2,!0)/32768;break;case"f32":case"f32-planar":u=c.getFloat32(p*4,!0);break;case"u8":case"u8-planar":u=(c.getUint8(p)-128)/128;break;default:throw new Error(`Unsupported audio format: ${s}`)}h[p]=Math.max(-1,Math.min(1,u))}}return o}catch(s){throw console.error("Failed to convert AudioData to AudioBuffer:",s),s}};class j{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 E(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(t){const{audioData:s,playbackRate:e=1}=t;try{if(!this.audioContext||!this.destination)return;let i=await W(this.audioContext,s);if(!i)return;const n=this.audioContext.createBufferSource();n.buffer=i,n.playbackRate.value=e;const o=-1200*Math.log2(e);n.detune.value=o,n.connect(this.destination);const a=Math.max(this.nextStartTime,this.audioContext.currentTime),r=i.duration/e;this.nextStartTime=a+r,n.start(a),this.pendingSources.push(n),n.onended=()=>{this.pendingSources=this.pendingSources.filter(d=>d!==n)},this.audioContext.state==="suspended"&&await this.audioContext.resume()}finally{s.close()}}getStream=()=>this.prAudioStream?.getStream();destroy(){this.audioContext?.close(),this.audioContext=void 0,this.destination=void 0,this.nextStartTime=0,this.prAudioStream?.stop(),this.pendingSources.forEach(t=>t.stop()),this.pendingSources=[]}}const R=`(function(){"use strict";class o{writable;writer;cutOption;pause=!1;constructor(){}init=({writable:t})=>{this.destroy(),this.writable=t,this.writer=this.writable.getWriter()};push=async t=>{if(this.pause)return;const{timestamp:s}=t;let{bitmap:i}=t;if(this.cutOption){const{sx:n=0,sy:c=0,sw:h=i.width,sh:u=i.height}=this.cutOption;i=await createImageBitmap(i,n,c,h,u)}const r=new VideoFrame(i,{timestamp:s});this.cutOption&&i.close(),this.writer.write(r),r.close()};setCut=t=>{this.cutOption=t};setPause=t=>{this.pause=t};destroy=()=>{this.writable=void 0,this.writer=void 0,this.cutOption=void 0}}const a=new o;onmessage=e=>{const{action:t,data:s}=e.data,i=a[t];i&&i(s)}})();
3
- `,M=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",R],{type:"text/javascript;charset=utf-8"});function z(l){let t;try{if(t=M&&(self.URL||self.webkitURL).createObjectURL(M),!t)throw"";const s=new Worker(t,{name:l?.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:l?.name})}}class P{worker=new z;constructor(){}init=({writable:t})=>this.worker.postMessage({action:"init",data:{writable:t}},[t]);push=t=>this.worker.postMessage({action:"push",data:t});setCut=async t=>this.worker.postMessage({action:"setCut",data:t});setPause=t=>this.worker.postMessage({action:"setPause",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}const q=l=>{const t=l.toLowerCase();return t.includes(".m3u8")||t.includes("hls")||t.includes("master.m3u8")||t.match(/index\d*\.m3u8/)?"hls":t.includes(".mpd")||t.includes("dash")?"dash":t.startsWith("rtmp://")||t.startsWith("rtmps://")?"rtmp":t.includes(".flv")||t.includes("flv")&&!t.includes("flash")?"flv":"unknown"},I=l=>{const t=l?.getTracks()||[];for(const s of t)s.stop()},L=()=>{const l=new MediaStreamTrackGenerator({kind:"video"}),t=new MediaStream([l]),s=new P;return s.init({writable:l.writable}),{worker:s,stream:t,destroy:()=>{s.destroy(),I(t)}}};class ${resolvesMap=new Map;index=0;constructor(){}add=(t,s=()=>!1,e=0)=>new Promise(i=>{if(s())return i(!0);this.resolvesMap.has(t)||this.resolvesMap.set(t,new Map),this.index++;const a=`${this.index}`;if(e=Math.max(0,e),e===0){this.resolvesMap.get(t)?.set(a,{resolve:i,timer:0});return}const r=window.setTimeout(()=>{this.emit(t)},e);this.resolvesMap.get(t)?.set(a,{resolve:i,timer:r})});emit=async t=>{const s=this.resolvesMap.get(t);if(!s)return;const e=[...s.keys()];for(const i of e){const n=s.get(i);n&&(clearTimeout(n.timer),n.resolve(),s.delete(i))}}}const H=(l,t)=>{const s=new Uint8Array(l),e=new Uint8Array(t),i=new Uint8Array(11+s.length+e.length);let n=0;return i[n++]=1,i[n++]=s[1],i[n++]=s[2],i[n++]=s[3],i[n++]=255,i[n++]=225,i[n++]=s.length>>8&255,i[n++]=s.length&255,i.set(s,n),n+=s.length,i[n++]=1,i[n++]=e.length>>8&255,i[n++]=e.length&255,i.set(e,n),i},V=l=>{let t=0;const s=new DataView(l.buffer),e=s.getUint8(t);if(t=t+1,e!==1)throw new Error("Invalid AVC version");const i=s.getUint8(t)&255;t=t+1;const n=s.getUint8(t)&255;t=t+1;const o=s.getUint8(t)&255;t=t+1;const d=`avc1.${Array.from([i,n,o],b=>b.toString(16).padStart(2,"0")).join("")}`,c=(s.getUint8(t)&3)-1;t=t+1;const h=s.getUint8(t)&31;t=t+1;const p=s.getUint16(t,!1);t=t+2;const u=new Uint8Array(s.buffer.slice(t,t+p));t=t+p;const g=s.getUint8(t)&31;t=t+1;const f=s.getUint16(t,!1);t=t+2;const y=new Uint8Array(s.buffer.slice(t,t+f));return t=t+f,{version:e,codec:d,profile:i,compatibility:n,level:o,lengthSizeMinusOne:c,numOfSequenceParameterSets:h,sequenceParameterSetLength:p,sps:u,numOfPictureParameterSets:g,pictureParameterSetLength:f,pps:y}},K=l=>{const t=new Uint8Array(4+l.length);return new DataView(t.buffer).setUint32(0,l.length,!1),t.set(l,4),t},X=l=>{let t=0;for(const i of l)t+=i.length;const s=new Uint8Array(t);let e=0;for(const i of l){const n=i;s.set(n,e),e+=n.length}return s},Y=l=>{const t=new DataView(l.buffer);let s=0,e,i,n;e=t.getUint32(s,!1),s+=4;{const o=t.getUint8(s),a=o>>7&1,r=o>>5&3,d=o&31;i={forbidden_zero_bit:a,nal_ref_idc:r,nal_unit_type:d},s+=1}{const o=e-1;n=new Uint8Array(t.buffer.slice(s,s+o))}return{size:e,header:i,data:n}};class F{#e={timeout:5*1e3,check:!1};#t;constructor(t={}){this.#e={...this.#e,...t}}check=(t,s)=>new Promise(async(e,i)=>{this.stop(),this.#t=new AbortController;const n=window.setTimeout(()=>{this.#t?.abort("Timeout."),i({status:"timeout",reason:""})},this.#e.timeout);try{const o=await fetch(t,{...s,method:"HEAD",signal:this.#t?.signal});o.status===200?e({status:"successed",reason:""}):i({status:"failed",reason:`${o.status}`})}catch(o){i({status:"error",reason:o.message})}clearTimeout(n)});request=async(t,s)=>new Promise(async(e,i)=>{try{this.#e.check&&await this.check(t,s),this.#t=new AbortController;const n=await fetch(t,{...s,signal:this.#t?.signal});e(n)}catch(n){this.stop(),i(n)}});stop=()=>{this.#t?.signal.aborted===!1&&this.#t.abort("Actively stop.")}}class Q{option={debug:!1,frameTrack:!1};prFetch=new F;prResolves=new $;url="";demuxerWorker;decoderWorker;audioPlayer;renderWorker;stream;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(t={}){const{debug:s=!1}=t;this.option.debug=s}start=async t=>{this.stop(),this.url=t;const s=q(t);if(s==="unknown")throw new Error("This address cannot be parsed.");switch(this.init(s),s){case"flv":this.flv.start();break;case"hls":this.hls.start();break}};stop=async()=>{try{clearInterval(this.hls.getSegmentsTimer),this.prFetch.stop()}catch(s){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: error",s)}this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy();const t=[...this.cutRenders.keys()];for(const s of t)this.cutRenders.get(s)?.worker.destroy(),this.cutRenders.delete(s);I(this.stream),this.audioPlayer?.destroy()};getStream=()=>this.stream;setPause=t=>{this.renderWorker?.setPause(t)};setMute=t=>this.audioPlayer?.prAudioStream?.setMute(t);setFrameTrack=t=>{this.option.frameTrack=t,this.decoderWorker?.setFrameTrack(t)};isReady=()=>{const t=()=>this.stream?.active===!0;return this.prResolves.add("isReady",t)};cut={create:(t,s)=>{let e=this.cutRenders.get(t);return e?(e.worker.setCut(s),e.worker.setPause(!1),e):(e=L(),e.worker.setCut(s),this.cutRenders.set(t,e),e)},getStream:t=>this.cutRenders.get(t)?.stream,setPause:(t,s)=>{this.cutRenders.get(t)?.worker.setPause(s)},remove:t=>{this.cutRenders.get(t)?.destroy(),this.cutRenders.delete(t)}};init=t=>{this.initDecoder(t),this.initRender(),this.initDemuxer(t),this.audioPlayer=new j,this.audioPlayer.init()};initDemuxer=t=>{this.demuxerWorker=new A,this.demuxerWorker.init(t),this.demuxerWorker.on.debug=s=>{this.option.debug&&this.on.debug&&this.on.debug(s)},this.demuxerWorker.on.info=s=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: info",s),this.on.demuxer.info&&this.on.demuxer.info(s)},this.demuxerWorker.on.config=s=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: config",s),this.on.demuxer.config&&this.on.demuxer.config(s);const{kind:e}=s;switch(e){case"audio":{const{codec:i,sampleRate:n,numberOfChannels:o}=s;this.decoderWorker?.initAudio({codec:i,sampleRate:n,numberOfChannels:o})}break;case"video":{const{codec:i,description:n}=s;this.decoderWorker?.initVideo({codec:i,description:n})}break}},this.demuxerWorker.on.chunk=s=>{if(this.on.demuxer.chunk&&this.on.demuxer.chunk(s),!this.decoderWorker)return;const{kind:e}=s;switch(e){case"audio":{const{type:i,dts:n,data:o}=s,a=n*1e3;this.decoderWorker.push({kind:e,init:{type:i,timestamp:a,data:o}})}break;case"video":{const{type:i,dts:n,data:o,nalus:a=[]}=s,r=n*1e3;this.decoderWorker.push({kind:e,init:{type:i,timestamp:r,data:o},nalus:a})}break}}};initDecoder=t=>{this.decoderWorker=new S,this.decoderWorker.init(t);const{frameTrack:s=!1}=this.option;this.decoderWorker.setFrameTrack(s),this.decoderWorker.on.audio.decode=e=>{this.audioPlayer?.push(e),this.on.decoder.audio&&this.on.decoder.audio(e)},this.decoderWorker.on.audio.error=e=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: audio.error ",e),this.on.error&&this.on.error(e)},this.decoderWorker.on.video.decode=async e=>{this.renderWorker?.push(e);const i=[...this.cutRenders.keys()];for(const n of i)this.cutRenders.get(n)?.worker.push(e);this.on.decoder.video&&this.on.decoder.video(e),e.bitmap.close()},this.decoderWorker.on.video.error=e=>{this.on.error&&this.on.error(e)},this.decoderWorker.on.nalus=async e=>{for(const i of e){if(i.byteLength<=4)continue;const{header:n,data:o}=Y(i),{nal_unit_type:a}=n;a===6&&this.on.decoder.sei&&this.on.decoder.sei(o)}},this.decoderWorker.on.analysis=e=>{this.on.decoder.analysis&&this.on.decoder.analysis(e)}};initRender=()=>{const{worker:t,stream:s}=L();this.renderWorker=t,this.stream=s,this.renderWorker.setPause(!1)};flv={start:async()=>{try{let t=await this.prFetch.request(this.url);if(t.status!==200&&(await new Promise(e=>setTimeout(()=>e(!0),500)),t=await this.prFetch.request(this.url)),t.status!==200&&(await new Promise(e=>setTimeout(()=>e(!0),500)),t=await this.prFetch.request(this.url)),t.status!==200)throw new Error("request is error.");const s=t.body?.getReader();if(!s)throw new Error("reader is error.");for(;;){const{done:e,value:i}=await s.read();if(i&&this.demuxerWorker?.push(i),e)break}}catch(t){if(t?.name!=="AbortError")throw Error(t);this.on.error&&this.on.error(t)}}};hls={isLive:!1,urls:[],url:"",getSegmentsTimer:0,parse:async t=>{const i=new TextDecoder("utf-8").decode(t).split(`
4
- `).map(c=>c.replace("\r","")),n=this.url.substring(0,this.url.lastIndexOf("/")+1);let o=4,a=0,r=!1;const d=[];for(const c of i)c.startsWith("#EXTINF:")?o=parseFloat(c.split(":")[1].split(",")[0]):c.startsWith("#EXT-X-TARGETDURATION:")?a=parseInt(c.split(":")[1]):c.startsWith("#EXT-X-ENDLIST")?r=!1:c.startsWith("#EXT-X-MEDIA-SEQUENCE:")?r=!0:c.includes(".ts")&&!c.startsWith("#")&&d.push({url:c.startsWith("http")?c:n+c,duration:o,isLive:r});return{baseUrl:n,targetDuration:a,isLive:r,segments:d}},getSegments:async()=>{try{const t=new F;let s=await t.request(this.url);if(s.status!==200&&(await new Promise(i=>setTimeout(()=>i(!0),500)),s=await t.request(this.url)),s.status!==200&&(await new Promise(i=>setTimeout(()=>i(!0),500)),s=await t.request(this.url)),s.status!==200)throw new Error("request is error.");const e=s.body?.getReader();if(!e)throw new Error("reader is error.");for(;;){const{done:i,value:n}=await e.read();if(n){const o=await this.hls.parse(n),{segments:a=[],isLive:r=!1}=o;this.hls.isLive=r,r===!1&&(this.option.frameTrack=!1);let d=Array.from(a,h=>h.url);const c=d.findIndex(h=>h===this.hls.url);c!==-1&&(d=d.slice(c+1)),this.hls.urls=d}if(i)break}}catch(t){this.on.error&&this.on.error(t)}},start:async()=>{try{for(await this.hls.getSegments(),this.hls.getSegmentsTimer=window.setInterval(this.hls.getSegments,500),this.hls.isLive===!1&&(clearInterval(this.hls.getSegmentsTimer),this.decoderWorker?.setFrameTrack(!1));;){const t=this.hls.urls.shift();if(t){this.hls.url=t;const e=(await this.prFetch.request(t)).body?.getReader();if(!e)throw new Error("segment reader is error.");for(;;){const{done:i,value:n}=await e.read();if(n&&this.demuxerWorker?.push(n),i)break}}else await new Promise(s=>setTimeout(()=>s(!0),300))}}catch(t){if(t?.name!=="AbortError")throw Error(t)}}}}class J{pendingPayloads=[];payload=new Uint8Array(0);chunks=[];push=t=>{this.pendingPayloads.push(t)};next=(t=0)=>{this.payload=this.payload.slice(t);const s=this.pendingPayloads.shift();if(!s)return!1;const e=new Uint8Array(this.payload.byteLength+s.byteLength);return e.set(this.payload,0),e.set(s,this.payload.byteLength),this.payload=e,new DataView(this.payload.buffer)};pushChunk=t=>{this.chunks.push(t),this.chunks.length>1e3&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.chunks=[]}}const Z=l=>{let t="unknown";switch(l){case 1:case 2:case 27:case 36:t="video";break;case 3:case 4:case 15:t="audio";break;case 6:t="subtitle";break;case 134:t="ad";break}return t};class tt{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async t=>{let s=0;for(;!(s+188>t.byteLength);){if(t.getInt8(s)!=71){s++;continue}await this.parsePacket(t,s),s+=188}return s};parsePacket=async(t,s)=>{if(s+188>t.byteLength)throw new Error("Invalid TS packet");if(t.getUint8(s)!==71)throw new Error("Invalid TS packet");let e=s;const i=this.parseHeader(t,e);e+=4;const{transport_error_indicator:n,pid:o,payload_unit_start_indicator:a,adaptation_field_control:r}=i;if(n===1||o===void 0)return;let d=184;if(r===2||r===3){const c=t.getUint8(e);e+=1,this.parseAdaptationField(t,e),e+=c,d-=c}if(r===3&&(d-=1),r===1||r===3){const c=new Uint8Array(t.buffer.slice(e,e+d));if(o===0)return this.parsePAT(t,e);{const{programs:u=[]}=this.pat||{};if(u.find(f=>f.pmt_pid===o))return this.parsePMT(t,e)}const{streams:h=[]}=this.pmt||{},p=h.find(u=>u.elementary_pid===o);if(p){if(a===1){const u=this.payloadMap.get(o);if(u){switch(p.kind){case"audio":{const g=await this.parseAudio(u);this.on.chunk&&this.on.chunk(g)}break;case"video":{const g=await this.parseVideo(u);this.on.chunk&&this.on.chunk(g),await new Promise(f=>setTimeout(()=>f(!0),0))}break}this.payloadMap.delete(o)}}{this.payloadMap.has(o)||this.payloadMap.set(o,new Uint8Array);const u=this.payloadMap.get(o),g=new Uint8Array(u.byteLength+c.byteLength);g.set(u,0),g.set(c,u.byteLength),this.payloadMap.set(o,g)}}}};parseHeader=(t,s)=>{let e=s;const i=t.getUint8(e),n=t.getUint8(e+1),o=t.getUint8(e+2),a=t.getUint8(e+3),r=(n&128)>>7;if(r===1)return{sync_byte:i,transport_error_indicator:r};const d=(n&64)>>6,c=(n&32)>>5,h=(n&31)<<8|o,p=(a&192)>>6,u=a>>4&3,g=a&15;return{sync_byte:i,transport_error_indicator:r,payload_unit_start_indicator:d,transport_priority:c,pid:h,transport_scrambling_control:p,adaptation_field_control:u,continuity_counter:g}};parsePAT=(t,s)=>{let e=s,i;{const a=t.getUint8(e);e+=1;const r=t.getUint8(e);if(e+=1,r!==0)throw new Error("Invalid PAT table_id");const d=t.getUint16(e)&4095;e+=2;const c=t.getUint16(e);e+=2;const h=(t.getUint8(e)&62)>>1,p=t.getUint8(e)&1;e+=1;const u=t.getUint8(e);e+=1;const g=t.getUint8(e);e+=1,i={pointer_field:a,table_id:r,section_length:d,transport_stream_id:c,version_number:h,current_next_indicator:p,section_number:u,last_section_number:g}}const n=[];{const a=i.section_length-5-4,r=e+a;for(;e<r;){const d=t.getUint16(e),c=t.getUint16(e+2)&8191;e+=4,d!==0&&c>=32&&c<=8190&&n.push({program_number:d,pmt_pid:c})}}const o=t.getUint32(e);this.pat={header:i,programs:n,crc32:o},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(t,s)=>{let e=s,i;{const a=t.getUint8(e);e+=1;const r=t.getUint8(e);if(e+=1,r!==2)throw new Error("Invalid PMT table_id");const d=t.getUint16(e)&4095;e+=2;const c=t.getUint16(e);e+=2;const h=(t.getUint8(e)&62)>>1,p=t.getUint8(e)&1;e+=1;const u=t.getUint8(e);e+=1;const g=t.getUint8(e);e+=1;const f=t.getUint16(e)&8191;e+=2;const y=t.getUint16(e)&4095;e+=2,i={pointer_field:a,table_id:r,section_length:d,transport_stream_id:c,version_number:h,current_next_indicator:p,section_number:u,last_section_number:g,pcr_pid:f,program_info_length:y}}const n=[];{const a=i.section_length-9-4,r=e+a;for(;e<r;){const d=t.getUint8(e),c=Z(d),h=t.getUint16(e+1)&8191,p=t.getUint16(e+3)&4095;if(e+=5,h<32||h>8190){console.warn(`Invalid elementary_pid: 0x${h.toString(16)}`);continue}n.push({kind:c,stream_type:d,elementary_pid:h,es_info_length:p})}}const o=t.getUint32(e);this.pmt={header:i,streams:n,crc32:o},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(t,s)=>{let e=s,i,n,o,a;const r=t.getUint8(e),d=!!(r&128),c=!!(r&64),h=!!(r&32),p=!!(r&16),u=!!(r&8),g=!!(r&4),f=!!(r&2),y=!!(r&1);e+=1;const b=(k,T)=>{let w=BigInt(0);w|=BigInt(k.getUint16(T))<<25n,w|=BigInt(k.getUint16(T+1))<<17n,w|=BigInt(k.getUint16(T+2))<<9n,w|=BigInt(k.getUint16(T+3))<<1n,w|=BigInt(k.getUint16(T+4)>>7);const ot=(k.getUint16(T+4)&1)<<8|k.getUint16(T+5);return w=w*300n+BigInt(ot),w};if(p&&(i=b(t,e),e+=6),u&&(n=b(t,e),e+=6),g&&(o=t.getInt8(e),e+=1),f){const k=t.getUint8(e);e+=1,a=new Uint8Array(t.buffer,e,k),e+=k}return{discontinuity_indicator:d,random_access_indicator:c,elementary_stream_priority_indicator:h,pcr_flag:p,opcr_flag:u,splicing_point_flag:g,transport_private_data_flag:f,adaptation_field_extension_flag:y,pcr:i,opcr:n,splice_countdown:o,transport_private_data:a}};parseAudio=async t=>{const s=new DataView(t.buffer);let e=0,i,n;{const o=s.getUint8(e)===0&&s.getUint8(e+1)===0&&s.getUint8(e+2)===1;if(e+=3,!o)throw new Error("invalid ts audio payload.");const a=s.getUint8(e);e+=1;const r=s.getUint8(e)<<8|s.getUint8(e+1);e+=2;let d,c,h,p,u;{const y=s.getUint8(e);e+=1,d=y>>4&3,c=(y>>3&1)===1,h=(y>>2&1)===1,p=(y>>1&1)===1,u=(y&1)===1}let g,f;{const y=s.getUint8(e);e+=1;const b=y>>6,k=s.getUint8(e);e+=1,(b&2)===2&&(g=this.parsePtsDts(s,e)),(b&1)===1?f=this.parsePtsDts(s,e+5):f=g,e+=k}i={stream_id:a,pes_packet_length:r,scrambling_control:d,priority:c,data_alignment:h,copyright:p,original_copy:u,pts:g,dts:f}}n=t.slice(e);{if(!this.audioConfig&&s.getUint8(e)===255){const h=s.getUint8(e+2),p=s.getUint8(e+3);let u,g;g=h>>2&15,u=(h&1)<<2|p>>6;const f=`mp4a.40.${u}`,b=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][g];this.audioConfig={kind:"audio",codec:f,sampleRate:b,numberOfChannels:u},this.on.config&&this.on.config(this.audioConfig)}const{dts:o=0,pts:a=0}=i,r=a-o,d=n.slice(7);return{kind:"audio",type:"key",dts:o,pts:a,cts:r,data:d}}};parseVideo=async t=>{const s=new DataView(t.buffer);let e=0,i,n;{const o=s.getUint8(e)===0&&s.getUint8(e+1)===0&&s.getUint8(e+2)===1;if(e+=3,!o)throw new Error("invalid ts video payload.");const a=s.getUint8(e);e+=1;const r=s.getUint8(e)<<8|s.getUint8(e+1);e+=2;let d,c,h,p,u;{const y=s.getUint8(e);e+=1,d=y>>4&3,c=(y>>3&1)===1,h=(y>>2&1)===1,p=(y>>1&1)===1,u=(y&1)===1}let g,f;{const y=s.getUint8(e);e+=1;const b=y>>6,k=s.getUint8(e);e+=1,(b&2)===2&&(g=this.parsePtsDts(s,e)),(b&1)===1?f=this.parsePtsDts(s,e+5):f=g,e+=k}i={stream_id:a,pes_packet_length:r,scrambling_control:d,priority:c,data_alignment:h,copyright:p,original_copy:u,pts:g,dts:f}}n=t.slice(e);{const o=this.getNalus(n);if(!this.videoConfig){let u,g;if(u=o.find(y=>y.type===7)?.nalu.slice(4),g=o.find(y=>y.type===8)?.nalu.slice(4),u&&g){const f=H(u,g),{codec:y}=V(f);this.videoConfig={kind:"video",codec:y,description:f,sps:u,pps:g},this.on.config&&this.on.config(this.videoConfig)}}const a=[];let r="delta";for(const u of o){const{type:g,nalu:f}=u;switch(g){case 6:case 9:a.push(f);break;case 1:r="delta",a.push(f);break;case 5:r="key",a.push(f);break}}const d=X(a),{dts:c=0,pts:h=0}=i,p=h-c;return{kind:"video",type:r,dts:c,pts:h,cts:p,data:d,nalus:a}}};parsePtsDts(t,s){const e=t.getUint8(s),i=t.getUint8(s+1),n=t.getUint8(s+2),o=t.getUint8(s+3),a=t.getUint8(s+4),r=(BigInt(e)&0b00001110n)<<29n|(BigInt(i)&0b11111111n)<<22n|(BigInt(n)&0b11111110n)<<14n|(BigInt(o)&0b11111111n)<<7n|(BigInt(a)&0b11111110n)>>1n;return Number(r)/90}getNalus=t=>{const s=[];let e=0;for(;!(e+4>t.byteLength);){if(t[e]!==0||t[e+1]!==0||t[e+2]!==1){e+=1;continue}e+=3;let i=e;const n=t[e]&31;for(e+=1;!(e+1>t.byteLength);){if(t[e]!==0||t[e+1]!==0||t[e+2]!==1){e+=1;continue}break}let o=e-i;if(t[e-1]===0&&(o-=1),o!==0){const a=t.slice(i,i+o),r=K(a);s.push({type:n,nalu:r})}}return s}}const C=(l,t)=>l.getUint8(t)<<16|l.getUint8(t+1)<<8|l.getUint8(t+2);class et{audioConfig;videoConfig;header;textDecoder=new TextDecoder("utf-8");on={};constructor(){}parse=async t=>{let s=0;for(this.header||(this.parseHeader(t,s),s+=9);this.isSurplusTag(t,s)!==!1;){const i=this.parseTagHeader(t,s+4),{tagType:n,dataSize:o,timestamp:a}=i;if(n){const r=this.parseTagBody(n,t,s+4+11,o);switch(n){case"script":this.on.info&&this.on.info(r);break;case"audio":{const{accPacketType:d}=r;if(d===0){const{codec:c,sampleRate:h,channelConfiguration:p}=r;this.audioConfig={kind:"audio",codec:c,sampleRate:h,numberOfChannels:p},this.on.config&&this.on.config(this.audioConfig)}else{const{cts:c,data:h}=r,p="key",u=c===void 0?void 0:c+a;this.on.chunk&&this.on.chunk({kind:"audio",type:p,dts:a,pts:u,cts:c,data:h})}}break;case"video":{const{avcPacketType:d}=r;if(d===0){const{codec:c,sps:h,pps:p,data:u}=r;this.videoConfig={kind:"video",codec:c,description:u,sps:h,pps:p},this.on.config&&this.on.config(this.videoConfig)}else{const{frameType:c,cts:h,data:p,nalus:u}=r,g=c===1?"key":"delta",f=h===void 0?void 0:h+a;this.on.chunk&&this.on.chunk({kind:"video",type:g,dts:a,pts:f,cts:h,data:p,nalus:u})}}break}s=s+4+11+o}await new Promise(r=>setTimeout(()=>r(!0),8))}return s};parseHeader=(t,s)=>{let e,i,n,o;e=t.getUint8(s)<<16|t.getUint8(s+1)<<8|t.getUint8(s+2),i=t.getUint8(3);{const r=t.getUint8(0).toString(2).padStart(5,"0").split(""),[,,d,,c]=r;n={audio:c==="1",video:d==="1"}}o=t.getUint32(5),this.header={signature:e,version:i,flags:n,dataOffset:o}};isSurplusTag=(t,s)=>{let e=!0;const i=t.byteLength;if(s+4>i)e=!1;else if(s+4+11>i)e=!1;else{const n=C(t,s+4+1);s+4+11+n>i&&(e=!1)}return e};parseTagHeader=(t,s)=>{let e,i,n,o,a;{const r=t.getUint8(s);let d;switch(r){case 18:d="script";break;case 8:d="audio";break;case 9:d="video";break}e=d}return i=C(t,s+1),n=C(t,s+4),o=t.getUint8(s+7),a=C(t,s+8),{tagType:e,dataSize:i,timestamp:n,timestampExtended:o,streamID:a}};parseTagBody=(t,s,e,i)=>{let n;switch(t){case"script":n=this.parseMetaData(s,e);break;case"audio":n=this.parseAudio(s,e,i);break;case"video":n=this.parseVideo(s,e,i);break}return n};parseMetaData=(t,s)=>{let e=s;{if(t.getUint8(e)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");e=e+1}const i=t.getUint16(e,!1);e=e+2;{const a=new Int8Array(t.buffer.slice(e,e+i));if((this.textDecoder?.decode(a)||"")!=="onMetaData")throw new Error("Expected 'onMetaData' string");e=e+i}const n=this.getAmfType(t,e);return e=e+1,this.getAMFValue(t,e,n).value};parseAudio=(t,s,e)=>{let i=s;const n=t.getUint8(i),o=n>>4&15,a=n>>2&3,r=n>>1&1,d=n&1;i=i+1;const c=t.getUint8(i);i=i+1;const h=e,p=new Uint8Array(t.buffer.slice(i,i+h));if(o===10&&c===0){const u=t.getUint8(i),g=t.getUint8(i+1),f=u>>3&31,y=(u&7)<<1|g>>7,b=g>>3&15,k=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],T=`mp4a.40.${f}`,w=k[y];return{soundFormat:o,soundRate:a,soundSize:r,soundType:d,accPacketType:c,data:p,samplingFrequencyIndex:y,channelConfiguration:b,codec:T,sampleRate:w}}return{soundFormat:o,soundRate:a,soundSize:r,soundType:d,accPacketType:c,data:p}};parseVideo=(t,s,e)=>{let i=s;const n=t.getUint8(i),o=n>>4&15,a=n&15;i=i+1;const r=t.getUint8(i);i=i+1;const d=C(t,i);i=i+3;const c=e-5,h=new Uint8Array(t.buffer.slice(i,i+c));switch(a){case 7:if(r===0){const p=V(h);return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h,...p}}else if(r===1){const p=[],u=i+e-5;for(;!(i+4>u);){const g=t.getUint32(i,!1),f=new Uint8Array(t.buffer.slice(i,i+4+g));i+=4+g,p.push(f)}return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h,nalus:p}}break;default:throw new Error("Unsupported codecID")}return{frameType:o,codecID:a,avcPacketType:r,cts:d,data:h}};getAmfType=(t,s)=>t.getUint8(s);getAMFName=(t,s,e)=>{const i=new Uint8Array(t.buffer.slice(s,s+e));return this.textDecoder?.decode(i)||""};getAMFValue=(t,s,e)=>{let i=s,n,o=0;switch(e){case 0:n=t.getFloat64(i,!1),o=8;break;case 1:n=!!t.getUint8(i),o=1;break;case 2:{n="";const r=t.getUint16(i,!1);i=i+2;const d=new Int8Array(t.buffer,i,r).filter(h=>h!==0);n=(this.textDecoder?.decode(d)||"").trim(),o=2+r}break;case 3:for(n={};i<t.byteLength;){const r=t.getUint16(i,!1);if(r===0)break;i=i+2;const d=this.getAMFName(t,i,r);i=i+r;const c=this.getAmfType(t,i);if(c===6)break;i=i+1;const h=this.getAMFValue(t,i,c);i=i+h.length,n[d]=h.value,o=2+r+1+h.length}break;case 8:{n={};const r=t.getUint32(i,!1);i=i+4;for(let d=0;d<r;d++){const c=t.getUint16(i,!1);i=i+2;const h=this.getAMFName(t,i,c);i=i+c;const p=this.getAmfType(t,i);i=i+1;const u=this.getAMFValue(t,i,p);i=i+u.length,n[h]=u.value,o=2+c+1+u.length}}break;case 10:{n=[];const r=t.getUint32(i,!1);i=i+4;for(let d=0;d<r;d++){const c=this.getAmfType(t,i);i=i+1;const h=this.getAMFValue(t,i,c);i=i+h.length,n.push(h.value),o=1+h.length}}break}return{amfType:e,length:o,value:n}}}class st{pattern;cacher=new J;isParseing=!1;offset=0;parser;on={};constructor(){}init=t=>{switch(this.destroy(),this.pattern=t,this.pattern){case"flv":this.parser=new et;break;case"hls":this.parser=new tt;break;default:throw new Error("is error pattern.")}this.parser.on.debug=s=>this.on.debug&&this.on.debug(s),this.parser.on.info=s=>this.on.info&&this.on.info(s),this.parser.on.config=s=>this.on.config&&this.on.config(s),this.parser.on.chunk=s=>{this.cacher.pushChunk(s),this.on.chunk&&this.on.chunk(s)}};push=t=>{this.cacher.push(t),this.isParseing===!1&&this.parse()};destroy=()=>{this.cacher.destroy(),this.isParseing=!1,this.offset=0};parse=async()=>{try{if(this.isParseing=!0,!this.pattern)throw new Error("You need to set the pattern.");if(!this.parser)throw new Error("You need to init parser.");for(;;){const t=this.cacher.next(this.offset);if(this.offset=0,!t)break;this.offset=await this.parser.parse(t)}this.isParseing=!1}catch{this.destroy()}}}class it{pattern="flv";audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;baseTime=0;pendingChunks=[];currentChunk;isProcessing=!1;decodeTimer=0;frameTrack=!1;isFrameTrack=!1;fameTrackOption={flv:[30,50],hls:[200,300],dash:[50,100],rtmp:[50,100]};decodingSpeedRatio=1;maxDecodingSpeedRatio=2;decodingSpeed=16;fps=0;firstVideoChunkTimestamp;secondVideoChunkTimestamp;frameStartTime;lastRenderTime;nextRenderTime;on={audio:{},video:{}};constructor(){}init=t=>{this.destroy(),this.pattern=t,this.baseTime=new Date().getTime()-performance.now(),this.initDecodeInterval()};initAudio=t=>{this.audio.destroy(),this.audioDecoderConfig={...t},this.audioDecoder=new AudioDecoder({output:s=>{const e=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:s,playbackRate:e})},error:s=>{this.on.audio.error&&this.on.audio.error(s)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=t=>{this.video.destroy(),this.videoDecoderConfig={...t},this.videoDecoder=new VideoDecoder({output:async s=>{this.frameStartTime||(this.frameStartTime=s.timestamp);const e=s.timestamp-this.frameStartTime+this.baseTime*1e3,i=await createImageBitmap(s);s.close(),i.width>0&&i.height>0?(this.on.video.decode&&this.on.video.decode({timestamp:e,bitmap:i}),this.currentChunk&&this.currentChunk.kind==="video"&&this.currentChunk.nalus&&this.on.nalus&&this.on.nalus(this.currentChunk.nalus)):i.close()},error:s=>{this.on.video.error&&this.on.video.error(s)}}),this.videoDecoder.configure(this.videoDecoderConfig)};setFrameTrack=t=>{this.frameTrack=t,this.frameTrack===!1&&(this.decodingSpeedRatio=1)};push=t=>{this.pendingChunks.push(t)};destroy=()=>{this.audio.destroy(),this.video.destroy(),this.pendingChunks=[],this.firstVideoChunkTimestamp=void 0,this.secondVideoChunkTimestamp=void 0,this.frameStartTime=void 0,this.lastRenderTime=void 0,this.nextRenderTime=void 0,clearInterval(this.decodeTimer)};initDecodeInterval=()=>{let t=this.decodingSpeed/this.decodingSpeedRatio;const s=this.baseTime+performance.now();if(this.lastRenderTime||(this.lastRenderTime=s),this.fps=Math.round(1e3/(s-this.lastRenderTime)),this.lastRenderTime=s,this.nextRenderTime){const e=this.lastRenderTime-this.nextRenderTime;t-=e}this.nextRenderTime=this.lastRenderTime+t,this.decodeTimer=setTimeout(()=>{this.decode(),this.initDecodeInterval()},t)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;;){this.currentChunk=this.pendingChunks.shift();const t=this.pendingChunks.length;if(this.frameTrack){const[i,n]=this.fameTrackOption[this.pattern];if(t<=i&&(this.isFrameTrack=!1),t>=n&&(this.isFrameTrack=!0),this.isFrameTrack){const o=Math.min(1+(t-i)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(o.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){const{decodingSpeed:i,decodingSpeedRatio:n,fps:o}=this;this.on.analysis({decodingSpeed:i,decodingSpeedRatio:n,fps:o,cacheLength:t})}if(!this.currentChunk)break;const{kind:s,init:e}=this.currentChunk;switch(s){case"audio":this.decodeAudio(e);break;case"video":this.decodeVideo(e);break}if(s==="video")break}this.isProcessing=!1}};decodeAudio=t=>{if(!this.audioDecoder)return;const s=new EncodedAudioChunk(t);this.audioDecoder.decode(s)};decodeVideo=t=>{if(this.videoDecoder&&(t.type==="key"&&(this.hasKeyFrame=!0),this.firstVideoChunkTimestamp?this.secondVideoChunkTimestamp||(this.secondVideoChunkTimestamp=t.timestamp,this.decodingSpeed=(this.secondVideoChunkTimestamp-this.firstVideoChunkTimestamp)/1e3):this.firstVideoChunkTimestamp=t.timestamp,this.hasKeyFrame)){const s=new EncodedVideoChunk(t);this.videoDecoder.decode(s)}};audio={flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}}class nt{writable;writer;cutOption;pause=!1;constructor(){}init=({writable:t})=>{this.destroy(),this.writable=t,this.writer=this.writable.getWriter()};push=async t=>{if(this.pause)return;const{timestamp:s}=t;let{bitmap:e}=t;if(this.cutOption){const{sx:n=0,sy:o=0,sw:a=e.width,sh:r=e.height}=this.cutOption;e=await createImageBitmap(e,n,o,a,r)}const i=new VideoFrame(e,{timestamp:s});this.cutOption&&e.close(),this.writer.write(i),i.close()};setCut=t=>{this.cutOption=t};setPause=t=>{this.pause=t};destroy=()=>{this.writable=void 0,this.writer=void 0,this.cutOption=void 0}}U.Decoder=it,U.DecoderWorker=S,U.Demuxer=st,U.DemuxerWorker=A,U.PrPlayer=Q,U.Render=nt,U.RenderWorker=P,Object.defineProperty(U,Symbol.toStringTag,{value:"Module"})}));
2
+ `,D=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",x],{type:"text/javascript;charset=utf-8"});function B(l){let t;try{if(t=D&&(self.URL||self.webkitURL).createObjectURL(D),!t)throw"";const s=new Worker(t,{name:l?.name});return s.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),s}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(x),{name:l?.name})}}class S{worker=new B;on={audio:{},video:{}};constructor(){this.worker.onmessage=t=>{const{action:s,data:e}=t.data;switch(s){case"on.audio.decode":this.on.audio.decode&&this.on.audio.decode(e);break;case"on.audio.error":this.on.audio.error&&this.on.audio.error(e);break;case"on.video.decode":this.on.video.decode&&this.on.video.decode(e);break;case"on.video.error":this.on.video.error&&this.on.video.error(e);break;case"on.nalus":this.on.nalus&&this.on.nalus(e);break;case"on.analysis":this.on.analysis&&this.on.analysis(e);break}}}init=t=>this.worker.postMessage({action:"init",data:t});initAudio=t=>this.worker.postMessage({action:"initAudio",data:t});initVideo=t=>this.worker.postMessage({action:"initVideo",data:t});push=t=>this.worker.postMessage({action:"push",data:t});setFrameTrack=t=>this.worker.postMessage({action:"setFrameTrack",data:t});destroy=()=>{this.worker.postMessage({action:"destroy"}),this.worker.terminate()}}var G=Object.defineProperty,O=(l,t,s)=>t in l?G(l,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):l[t]=s,m=(l,t,s)=>O(l,typeof t!="symbol"?t+"":t,s);class E{constructor(t,s){m(this,"inputStream",new MediaStream),m(this,"outputStream",new MediaStream),m(this,"inputGain",1),m(this,"enhanceGain",1),m(this,"bgsGain",1),m(this,"bgmGain",1),m(this,"outputGain",1),m(this,"mixAudioMap",new Map),m(this,"audioContext",new AudioContext),m(this,"sourceNode"),m(this,"inputGainNode"),m(this,"enhanceGainNode"),m(this,"bgsGainNode"),m(this,"bgmGainNode"),m(this,"analyserNode"),m(this,"analyserArrayData"),m(this,"outputGainNode"),m(this,"destinationNode"),m(this,"filterStream",e=>e),m(this,"stop",()=>{{const e=this.inputStream.getTracks();for(const i of e)i.stop(),this.inputStream.removeTrack(i)}}),m(this,"getStream",()=>this.filterStream(this.outputStream)),m(this,"setMute",(e=!0)=>{e?this.analyserNode.disconnect(this.outputGainNode):this.analyserNode.connect(this.outputGainNode)}),m(this,"setInputGain",e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),m(this,"setEnhanceGain",async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)}),m(this,"setBgsGain",e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),m(this,"setBgmGain",e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)}),m(this,"setOutputGain",e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)}),m(this,"getVolume",()=>{const{analyserNode:e,analyserArrayData:i}=this;e.getByteFrequencyData(i);let n=0;for(let r=0;r<i.length;r++)n+=i[r];return Math.ceil(n/i.length)}),m(this,"mixAudio",(e,i="bgm")=>new Promise(async(n,r)=>{try{{const d=this.mixAudioMap.get(i);d&&d.stop()}const a=i==="bgs"?this.bgsGainNode:this.bgmGainNode,o=this.audioContext.createBufferSource();this.mixAudioMap.set(i,o),o.buffer=e,o.connect(a),o.onended=()=>{o.disconnect(a),this.mixAudioMap.delete(i),n(!0)},o.start(0)}catch(a){r(a)}})),m(this,"mixAudioStop",e=>{const i=this.mixAudioMap.get(e);i?.stop()}),m(this,"changeMix",(e,i)=>{const n=e==="bgs"?this.bgsGainNode:this.bgmGainNode;i?n.connect(this.destinationNode):n.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:i,enhanceGainNode:n,bgsGainNode:r,bgmGainNode:a,analyserNode:o,outputGainNode:d,destinationNode:c}=this;e.connect(i),i.connect(n),n.connect(o),r.connect(o),a.connect(o),n.connect(c),r.connect(c),a.connect(c),o.connect(d),d.connect(this.audioContext.destination)}this.setMute(!0),this.audioContext.resume()}}const W=async(l,t)=>{try{const{format:s,numberOfChannels:e,numberOfFrames:i,sampleRate:n}=t,r=l.createBuffer(e,i,n);for(let a=0;a<e;a++){const o=t.allocationSize({planeIndex:a}),d=new Uint8Array(o);t.copyTo(d,{planeIndex:a});const c=new DataView(d.buffer),u=r.getChannelData(a);for(let p=0;p<i;p++){let h;switch(s){case"s16":case"s16-planar":h=c.getInt16(p*2,!0)/32768;break;case"f32":case"f32-planar":h=c.getFloat32(p*4,!0);break;case"u8":case"u8-planar":h=(c.getUint8(p)-128)/128;break;default:throw new Error(`Unsupported audio format: ${s}`)}u[p]=Math.max(-1,Math.min(1,h))}}return r}catch(s){throw console.error("Failed to convert AudioData to AudioBuffer:",s),s}};class j{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 E(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(t){const{audioData:s,playbackRate:e=1}=t;try{if(!this.audioContext||!this.destination)return;let i=await W(this.audioContext,s);if(!i)return;const n=this.audioContext.createBufferSource();n.buffer=i,n.playbackRate.value=e;const r=-1200*Math.log2(e);n.detune.value=r,n.connect(this.destination);const a=Math.max(this.nextStartTime,this.audioContext.currentTime),o=i.duration/e;this.nextStartTime=a+o,n.start(a),this.pendingSources.push(n),n.onended=()=>{this.pendingSources=this.pendingSources.filter(d=>d!==n)},this.audioContext.state==="suspended"&&await this.audioContext.resume()}finally{s.close()}}getStream=()=>this.prAudioStream?.getStream();destroy(){this.audioContext?.close(),this.audioContext=void 0,this.destination=void 0,this.nextStartTime=0,this.prAudioStream?.stop(),this.pendingSources.forEach(t=>t.stop()),this.pendingSources=[]}}const R=`(function(){"use strict";class o{writable;writer;cutOption;pause=!1;constructor(){}init=({writable:t})=>{this.destroy(),this.writable=t,this.writer=this.writable.getWriter()};push=async t=>{if(this.pause)return;const{timestamp:s}=t;let{bitmap:i}=t;if(this.cutOption){const{sx:n=0,sy:c=0,sw:h=i.width,sh:u=i.height}=this.cutOption;i=await createImageBitmap(i,n,c,h,u)}const r=new VideoFrame(i,{timestamp:s});this.cutOption&&i.close(),this.writer.write(r),r.close()};setCut=t=>{this.cutOption=t};setPause=t=>{this.pause=t};destroy=()=>{this.writable=void 0,this.writer=void 0,this.cutOption=void 0}}const a=new o;onmessage=e=>{const{action:t,data:s}=e.data,i=a[t];i&&i(s)}})();
3
+ `,M=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",R],{type:"text/javascript;charset=utf-8"});function z(l){let t;try{if(t=M&&(self.URL||self.webkitURL).createObjectURL(M),!t)throw"";const s=new Worker(t,{name:l?.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:l?.name})}}class P{worker=new z;constructor(){}init=({writable:t})=>this.worker.postMessage({action:"init",data:{writable:t}},[t]);push=t=>this.worker.postMessage({action:"push",data:t});setCut=async t=>this.worker.postMessage({action:"setCut",data:t});setPause=t=>this.worker.postMessage({action:"setPause",data:t});destroy=()=>{this.worker.postMessage({action:"destroy",data:{}}),this.worker.terminate()}}const q=l=>{const t=l.toLowerCase();return t.includes(".m3u8")||t.includes("hls")||t.includes("master.m3u8")||t.match(/index\d*\.m3u8/)?"hls":t.includes(".mpd")||t.includes("dash")?"dash":t.startsWith("rtmp://")||t.startsWith("rtmps://")?"rtmp":t.includes(".flv")||t.includes("flv")&&!t.includes("flash")?"flv":"unknown"},I=l=>{const t=l?.getTracks()||[];for(const s of t)s.stop()},L=()=>{const l=new MediaStreamTrackGenerator({kind:"video"}),t=new MediaStream([l]),s=new P;return s.init({writable:l.writable}),{worker:s,stream:t,destroy:()=>{s.destroy(),I(t)}}};class ${resolvesMap=new Map;index=0;constructor(){}add=(t,s=()=>!1,e=0)=>new Promise(i=>{if(s())return i(!0);this.resolvesMap.has(t)||this.resolvesMap.set(t,new Map),this.index++;const a=`${this.index}`;if(e=Math.max(0,e),e===0){this.resolvesMap.get(t)?.set(a,{resolve:i,timer:0});return}const o=window.setTimeout(()=>{this.emit(t)},e);this.resolvesMap.get(t)?.set(a,{resolve:i,timer:o})});emit=async t=>{const s=this.resolvesMap.get(t);if(!s)return;const e=[...s.keys()];for(const i of e){const n=s.get(i);n&&(clearTimeout(n.timer),n.resolve(),s.delete(i))}}}const H=(l,t)=>{const s=new Uint8Array(l),e=new Uint8Array(t),i=new Uint8Array(11+s.length+e.length);let n=0;return i[n++]=1,i[n++]=s[1],i[n++]=s[2],i[n++]=s[3],i[n++]=255,i[n++]=225,i[n++]=s.length>>8&255,i[n++]=s.length&255,i.set(s,n),n+=s.length,i[n++]=1,i[n++]=e.length>>8&255,i[n++]=e.length&255,i.set(e,n),i},V=l=>{let t=0;const s=new DataView(l.buffer),e=s.getUint8(t);if(t=t+1,e!==1)throw new Error("Invalid AVC version");const i=s.getUint8(t)&255;t=t+1;const n=s.getUint8(t)&255;t=t+1;const r=s.getUint8(t)&255;t=t+1;const d=`avc1.${Array.from([i,n,r],b=>b.toString(16).padStart(2,"0")).join("")}`,c=(s.getUint8(t)&3)-1;t=t+1;const u=s.getUint8(t)&31;t=t+1;const p=s.getUint16(t,!1);t=t+2;const h=new Uint8Array(s.buffer.slice(t,t+p));t=t+p;const g=s.getUint8(t)&31;t=t+1;const f=s.getUint16(t,!1);t=t+2;const y=new Uint8Array(s.buffer.slice(t,t+f));return t=t+f,{version:e,codec:d,profile:i,compatibility:n,level:r,lengthSizeMinusOne:c,numOfSequenceParameterSets:u,sequenceParameterSetLength:p,sps:h,numOfPictureParameterSets:g,pictureParameterSetLength:f,pps:y}},K=l=>{const t=new Uint8Array(4+l.length);return new DataView(t.buffer).setUint32(0,l.length,!1),t.set(l,4),t},X=l=>{let t=0;for(const i of l)t+=i.length;const s=new Uint8Array(t);let e=0;for(const i of l){const n=i;s.set(n,e),e+=n.length}return s},Y=l=>{const t=new DataView(l.buffer);let s=0,e,i,n;e=t.getUint32(s,!1),s+=4;{const r=t.getUint8(s),a=r>>7&1,o=r>>5&3,d=r&31;i={forbidden_zero_bit:a,nal_ref_idc:o,nal_unit_type:d},s+=1}{const r=e-1;n=new Uint8Array(t.buffer.slice(s,s+r))}return{size:e,header:i,data:n}};class F{#e={timeout:5*1e3};#t;constructor(t={}){this.#e={...this.#e,...t}}check=(t,s)=>new Promise(async(e,i)=>{this.stop(),this.#t=new AbortController;const n=window.setTimeout(()=>{this.#t?.abort("Timeout."),i({status:"timeout",reason:""})},this.#e.timeout);try{const r=await fetch(t,{...s,method:"HEAD",signal:this.#t?.signal});r.status===200?e({status:"successed",reason:""}):i({status:"failed",reason:`${r.status}`})}catch(r){i({status:"error",reason:r.message})}clearTimeout(n)});request=async(t,s)=>new Promise(async(e,i)=>{try{await this.check(t,s),this.#t=new AbortController;const n=await fetch(t,{...s,signal:this.#t?.signal});e(n)}catch(n){this.stop(),i(n)}});stop=()=>{this.#t?.signal.aborted===!1&&this.#t.abort("Actively stop.")}}class Q{option={debug:!1,frameTrack:!1};prFetch=new F;getSegmentsFetch=new F;prResolves=new $;url="";demuxerWorker;decoderWorker;audioPlayer;renderWorker;stream;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(t={}){const{debug:s=!1}=t;this.option.debug=s}start=async t=>{await this.stop(),this.url=t;const s=q(t);if(s==="unknown")throw new Error("This address cannot be parsed.");switch(this.init(s),s){case"flv":this.flv.start();break;case"hls":this.hls.start();break}};stop=async()=>{try{this.url="",clearInterval(this.hls.getSegmentsTimer),this.prFetch.stop(),this.getSegmentsFetch.stop()}catch(s){console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: error",s)}this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy();const t=[...this.cutRenders.keys()];for(const s of t)this.cutRenders.get(s)?.worker.destroy(),this.cutRenders.delete(s);I(this.stream),this.audioPlayer?.destroy()};getStream=()=>this.stream;setPause=t=>{this.renderWorker?.setPause(t)};setMute=t=>this.audioPlayer?.prAudioStream?.setMute(t);setFrameTrack=t=>{this.option.frameTrack=t,this.decoderWorker?.setFrameTrack(t)};isReady=()=>{const t=()=>this.stream?.active===!0;return this.prResolves.add("isReady",t)};cut={create:(t,s)=>{let e=this.cutRenders.get(t);return e?(e.worker.setCut(s),e.worker.setPause(!1),e):(e=L(),e.worker.setCut(s),this.cutRenders.set(t,e),e)},getStream:t=>this.cutRenders.get(t)?.stream,setPause:(t,s)=>{this.cutRenders.get(t)?.worker.setPause(s)},remove:t=>{this.cutRenders.get(t)?.destroy(),this.cutRenders.delete(t)}};init=t=>{this.initDecoder(t),this.initRender(),this.initDemuxer(t),this.audioPlayer=new j,this.audioPlayer.init()};initDemuxer=t=>{this.demuxerWorker=new A,this.demuxerWorker.init(t),this.demuxerWorker.on.debug=s=>{this.option.debug&&this.on.debug&&this.on.debug(s)},this.demuxerWorker.on.info=s=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: info",s),this.on.demuxer.info&&this.on.demuxer.info(s)},this.demuxerWorker.on.config=s=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: config",s),this.on.demuxer.config&&this.on.demuxer.config(s);const{kind:e}=s;switch(e){case"audio":{const{codec:i,sampleRate:n,numberOfChannels:r}=s;this.decoderWorker?.initAudio({codec:i,sampleRate:n,numberOfChannels:r})}break;case"video":{const{codec:i,description:n}=s;this.decoderWorker?.initVideo({codec:i,description:n})}break}},this.demuxerWorker.on.chunk=s=>{if(this.on.demuxer.chunk&&this.on.demuxer.chunk(s),!this.decoderWorker)return;const{kind:e}=s;switch(e){case"audio":{const{type:i,dts:n,data:r}=s,a=n*1e3;this.decoderWorker.push({kind:e,init:{type:i,timestamp:a,data:r}})}break;case"video":{const{type:i,dts:n,data:r,nalus:a=[]}=s,o=n*1e3;this.decoderWorker.push({kind:e,init:{type:i,timestamp:o,data:r},nalus:a})}break}}};initDecoder=t=>{this.decoderWorker=new S,this.decoderWorker.init(t);const{frameTrack:s=!1}=this.option;this.decoderWorker.setFrameTrack(s),this.decoderWorker.on.audio.decode=e=>{this.audioPlayer?.push(e),this.on.decoder.audio&&this.on.decoder.audio(e)},this.decoderWorker.on.audio.error=e=>{this.option.debug&&console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m","color:#0097ff;","------->pr-player: audio.error ",e),this.on.error&&this.on.error(e)},this.decoderWorker.on.video.decode=async e=>{this.renderWorker?.push(e);const i=[...this.cutRenders.keys()];for(const n of i)this.cutRenders.get(n)?.worker.push(e);this.on.decoder.video&&this.on.decoder.video(e),e.bitmap.close()},this.decoderWorker.on.video.error=e=>{this.on.error&&this.on.error(e)},this.decoderWorker.on.nalus=async e=>{for(const i of e){if(i.byteLength<=4)continue;const{header:n,data:r}=Y(i),{nal_unit_type:a}=n;a===6&&this.on.decoder.sei&&this.on.decoder.sei(r)}},this.decoderWorker.on.analysis=e=>{this.on.decoder.analysis&&this.on.decoder.analysis(e)}};initRender=()=>{const{worker:t,stream:s}=L();this.renderWorker=t,this.stream=s,this.renderWorker.setPause(!1)};flv={start:async()=>{try{let t=await this.prFetch.request(this.url);if(t.status!==200&&(await new Promise(e=>setTimeout(()=>e(!0),500)),t=await this.prFetch.request(this.url)),t.status!==200&&(await new Promise(e=>setTimeout(()=>e(!0),500)),t=await this.prFetch.request(this.url)),t.status!==200)throw new Error("request is error.");const s=t.body?.getReader();if(!s)throw new Error("reader is error.");for(;;){const{done:e,value:i}=await s.read();if(i&&this.demuxerWorker?.push(i),e||this.url==="")break}}catch(t){if(t?.name!=="AbortError")throw Error(t);this.on.error&&this.on.error(t)}}};hls={isLive:!1,urls:[],url:"",getSegmentsTimer:0,parse:async t=>{const i=new TextDecoder("utf-8").decode(t).split(`
4
+ `).map(c=>c.replace("\r","")),n=this.url.substring(0,this.url.lastIndexOf("/")+1);let r=4,a=0,o=!1;const d=[];for(const c of i)c.startsWith("#EXTINF:")?r=parseFloat(c.split(":")[1].split(",")[0]):c.startsWith("#EXT-X-TARGETDURATION:")?a=parseInt(c.split(":")[1]):c.startsWith("#EXT-X-ENDLIST")?o=!1:c.startsWith("#EXT-X-MEDIA-SEQUENCE:")?o=!0:c.includes(".ts")&&!c.startsWith("#")&&d.push({url:c.startsWith("http")?c:n+c,duration:r,isLive:o});return{baseUrl:n,targetDuration:a,isLive:o,segments:d}},getSegments:async()=>{try{let t=await this.getSegmentsFetch.request(this.url);if(t.status!==200&&(await new Promise(e=>setTimeout(()=>e(!0),500)),t=await this.getSegmentsFetch.request(this.url)),t.status!==200&&(await new Promise(e=>setTimeout(()=>e(!0),500)),t=await this.getSegmentsFetch.request(this.url)),t.status!==200)throw new Error("request is error.");const s=t.body?.getReader();if(!s)throw new Error("reader is error.");for(;;){const{done:e,value:i}=await s.read();if(i){const n=await this.hls.parse(i),{segments:r=[],isLive:a=!1}=n;this.hls.isLive=a,a===!1&&(this.option.frameTrack=!1);let o=Array.from(r,c=>c.url);const d=o.findIndex(c=>c===this.hls.url);d!==-1&&(o=o.slice(d+1)),this.hls.urls=o}if(e||this.url==="")break}}catch(t){this.on.error&&this.on.error(t)}},start:async()=>{try{for(await this.hls.getSegments(),this.hls.getSegmentsTimer=window.setInterval(this.hls.getSegments,500),this.hls.isLive===!1&&(clearInterval(this.hls.getSegmentsTimer),this.decoderWorker?.setFrameTrack(!1));;){const t=this.hls.urls.shift();if(t){this.hls.url=t;const e=(await this.prFetch.request(t)).body?.getReader();if(!e)throw new Error("segment reader is error.");for(;;){const{done:i,value:n}=await e.read();if(n&&this.demuxerWorker?.push(n),i||this.url==="")break}}else await new Promise(s=>setTimeout(()=>s(!0),300))}}catch(t){if(t?.name!=="AbortError")throw Error(t)}}}}class J{pendingPayloads=[];payload=new Uint8Array(0);chunks=[];push=t=>{this.pendingPayloads.push(t)};next=(t=0)=>{this.payload=this.payload.slice(t);const s=this.pendingPayloads.shift();if(!s)return!1;const e=new Uint8Array(this.payload.byteLength+s.byteLength);return e.set(this.payload,0),e.set(s,this.payload.byteLength),this.payload=e,new DataView(this.payload.buffer)};pushChunk=t=>{this.chunks.push(t),this.chunks.length>1e3&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array(0),this.chunks=[]}}const Z=l=>{let t="unknown";switch(l){case 1:case 2:case 27:case 36:t="video";break;case 3:case 4:case 15:t="audio";break;case 6:t="subtitle";break;case 134:t="ad";break}return t};class tt{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async t=>{let s=0;for(;!(s+188>t.byteLength);){if(t.getInt8(s)!=71){s++;continue}await this.parsePacket(t,s),s+=188}return s};parsePacket=async(t,s)=>{if(s+188>t.byteLength)throw new Error("Invalid TS packet");if(t.getUint8(s)!==71)throw new Error("Invalid TS packet");let e=s;const i=this.parseHeader(t,e);e+=4;const{transport_error_indicator:n,pid:r,payload_unit_start_indicator:a,adaptation_field_control:o}=i;if(n===1||r===void 0)return;let d=184;if(o===2||o===3){const c=t.getUint8(e);e+=1,this.parseAdaptationField(t,e),e+=c,d-=c}if(o===3&&(d-=1),o===1||o===3){const c=new Uint8Array(t.buffer.slice(e,e+d));if(r===0)return this.parsePAT(t,e);{const{programs:h=[]}=this.pat||{};if(h.find(f=>f.pmt_pid===r))return this.parsePMT(t,e)}const{streams:u=[]}=this.pmt||{},p=u.find(h=>h.elementary_pid===r);if(p){if(a===1){const h=this.payloadMap.get(r);if(h){switch(p.kind){case"audio":{const g=await this.parseAudio(h);this.on.chunk&&this.on.chunk(g)}break;case"video":{const g=await this.parseVideo(h);this.on.chunk&&this.on.chunk(g),await new Promise(f=>setTimeout(()=>f(!0),0))}break}this.payloadMap.delete(r)}}{this.payloadMap.has(r)||this.payloadMap.set(r,new Uint8Array);const h=this.payloadMap.get(r),g=new Uint8Array(h.byteLength+c.byteLength);g.set(h,0),g.set(c,h.byteLength),this.payloadMap.set(r,g)}}}};parseHeader=(t,s)=>{let e=s;const i=t.getUint8(e),n=t.getUint8(e+1),r=t.getUint8(e+2),a=t.getUint8(e+3),o=(n&128)>>7;if(o===1)return{sync_byte:i,transport_error_indicator:o};const d=(n&64)>>6,c=(n&32)>>5,u=(n&31)<<8|r,p=(a&192)>>6,h=a>>4&3,g=a&15;return{sync_byte:i,transport_error_indicator:o,payload_unit_start_indicator:d,transport_priority:c,pid:u,transport_scrambling_control:p,adaptation_field_control:h,continuity_counter:g}};parsePAT=(t,s)=>{let e=s,i;{const a=t.getUint8(e);e+=1;const o=t.getUint8(e);if(e+=1,o!==0)throw new Error("Invalid PAT table_id");const d=t.getUint16(e)&4095;e+=2;const c=t.getUint16(e);e+=2;const u=(t.getUint8(e)&62)>>1,p=t.getUint8(e)&1;e+=1;const h=t.getUint8(e);e+=1;const g=t.getUint8(e);e+=1,i={pointer_field:a,table_id:o,section_length:d,transport_stream_id:c,version_number:u,current_next_indicator:p,section_number:h,last_section_number:g}}const n=[];{const a=i.section_length-5-4,o=e+a;for(;e<o;){const d=t.getUint16(e),c=t.getUint16(e+2)&8191;e+=4,d!==0&&c>=32&&c<=8190&&n.push({program_number:d,pmt_pid:c})}}const r=t.getUint32(e);this.pat={header:i,programs:n,crc32:r},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(t,s)=>{let e=s,i;{const a=t.getUint8(e);e+=1;const o=t.getUint8(e);if(e+=1,o!==2)throw new Error("Invalid PMT table_id");const d=t.getUint16(e)&4095;e+=2;const c=t.getUint16(e);e+=2;const u=(t.getUint8(e)&62)>>1,p=t.getUint8(e)&1;e+=1;const h=t.getUint8(e);e+=1;const g=t.getUint8(e);e+=1;const f=t.getUint16(e)&8191;e+=2;const y=t.getUint16(e)&4095;e+=2,i={pointer_field:a,table_id:o,section_length:d,transport_stream_id:c,version_number:u,current_next_indicator:p,section_number:h,last_section_number:g,pcr_pid:f,program_info_length:y}}const n=[];{const a=i.section_length-9-4,o=e+a;for(;e<o;){const d=t.getUint8(e),c=Z(d),u=t.getUint16(e+1)&8191,p=t.getUint16(e+3)&4095;if(e+=5,u<32||u>8190){console.warn(`Invalid elementary_pid: 0x${u.toString(16)}`);continue}n.push({kind:c,stream_type:d,elementary_pid:u,es_info_length:p})}}const r=t.getUint32(e);this.pmt={header:i,streams:n,crc32:r},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(t,s)=>{let e=s,i,n,r,a;const o=t.getUint8(e),d=!!(o&128),c=!!(o&64),u=!!(o&32),p=!!(o&16),h=!!(o&8),g=!!(o&4),f=!!(o&2),y=!!(o&1);e+=1;const b=(k,T)=>{let w=BigInt(0);w|=BigInt(k.getUint16(T))<<25n,w|=BigInt(k.getUint16(T+1))<<17n,w|=BigInt(k.getUint16(T+2))<<9n,w|=BigInt(k.getUint16(T+3))<<1n,w|=BigInt(k.getUint16(T+4)>>7);const ot=(k.getUint16(T+4)&1)<<8|k.getUint16(T+5);return w=w*300n+BigInt(ot),w};if(p&&(i=b(t,e),e+=6),h&&(n=b(t,e),e+=6),g&&(r=t.getInt8(e),e+=1),f){const k=t.getUint8(e);e+=1,a=new Uint8Array(t.buffer,e,k),e+=k}return{discontinuity_indicator:d,random_access_indicator:c,elementary_stream_priority_indicator:u,pcr_flag:p,opcr_flag:h,splicing_point_flag:g,transport_private_data_flag:f,adaptation_field_extension_flag:y,pcr:i,opcr:n,splice_countdown:r,transport_private_data:a}};parseAudio=async t=>{const s=new DataView(t.buffer);let e=0,i,n;{const r=s.getUint8(e)===0&&s.getUint8(e+1)===0&&s.getUint8(e+2)===1;if(e+=3,!r)throw new Error("invalid ts audio payload.");const a=s.getUint8(e);e+=1;const o=s.getUint8(e)<<8|s.getUint8(e+1);e+=2;let d,c,u,p,h;{const y=s.getUint8(e);e+=1,d=y>>4&3,c=(y>>3&1)===1,u=(y>>2&1)===1,p=(y>>1&1)===1,h=(y&1)===1}let g,f;{const y=s.getUint8(e);e+=1;const b=y>>6,k=s.getUint8(e);e+=1,(b&2)===2&&(g=this.parsePtsDts(s,e)),(b&1)===1?f=this.parsePtsDts(s,e+5):f=g,e+=k}i={stream_id:a,pes_packet_length:o,scrambling_control:d,priority:c,data_alignment:u,copyright:p,original_copy:h,pts:g,dts:f}}n=t.slice(e);{if(!this.audioConfig&&s.getUint8(e)===255){const u=s.getUint8(e+2),p=s.getUint8(e+3);let h,g;g=u>>2&15,h=(u&1)<<2|p>>6;const f=`mp4a.40.${h}`,b=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][g];this.audioConfig={kind:"audio",codec:f,sampleRate:b,numberOfChannels:h},this.on.config&&this.on.config(this.audioConfig)}const{dts:r=0,pts:a=0}=i,o=a-r,d=n.slice(7);return{kind:"audio",type:"key",dts:r,pts:a,cts:o,data:d}}};parseVideo=async t=>{const s=new DataView(t.buffer);let e=0,i,n;{const r=s.getUint8(e)===0&&s.getUint8(e+1)===0&&s.getUint8(e+2)===1;if(e+=3,!r)throw new Error("invalid ts video payload.");const a=s.getUint8(e);e+=1;const o=s.getUint8(e)<<8|s.getUint8(e+1);e+=2;let d,c,u,p,h;{const y=s.getUint8(e);e+=1,d=y>>4&3,c=(y>>3&1)===1,u=(y>>2&1)===1,p=(y>>1&1)===1,h=(y&1)===1}let g,f;{const y=s.getUint8(e);e+=1;const b=y>>6,k=s.getUint8(e);e+=1,(b&2)===2&&(g=this.parsePtsDts(s,e)),(b&1)===1?f=this.parsePtsDts(s,e+5):f=g,e+=k}i={stream_id:a,pes_packet_length:o,scrambling_control:d,priority:c,data_alignment:u,copyright:p,original_copy:h,pts:g,dts:f}}n=t.slice(e);{const r=this.getNalus(n);if(!this.videoConfig){let h,g;if(h=r.find(y=>y.type===7)?.nalu.slice(4),g=r.find(y=>y.type===8)?.nalu.slice(4),h&&g){const f=H(h,g),{codec:y}=V(f);this.videoConfig={kind:"video",codec:y,description:f,sps:h,pps:g},this.on.config&&this.on.config(this.videoConfig)}}const a=[];let o="delta";for(const h of r){const{type:g,nalu:f}=h;switch(g){case 6:case 9:a.push(f);break;case 1:o="delta",a.push(f);break;case 5:o="key",a.push(f);break}}const d=X(a),{dts:c=0,pts:u=0}=i,p=u-c;return{kind:"video",type:o,dts:c,pts:u,cts:p,data:d,nalus:a}}};parsePtsDts(t,s){const e=t.getUint8(s),i=t.getUint8(s+1),n=t.getUint8(s+2),r=t.getUint8(s+3),a=t.getUint8(s+4),o=(BigInt(e)&0b00001110n)<<29n|(BigInt(i)&0b11111111n)<<22n|(BigInt(n)&0b11111110n)<<14n|(BigInt(r)&0b11111111n)<<7n|(BigInt(a)&0b11111110n)>>1n;return Number(o)/90}getNalus=t=>{const s=[];let e=0;for(;!(e+4>t.byteLength);){if(t[e]!==0||t[e+1]!==0||t[e+2]!==1){e+=1;continue}e+=3;let i=e;const n=t[e]&31;for(e+=1;!(e+1>t.byteLength);){if(t[e]!==0||t[e+1]!==0||t[e+2]!==1){e+=1;continue}break}let r=e-i;if(t[e-1]===0&&(r-=1),r!==0){const a=t.slice(i,i+r),o=K(a);s.push({type:n,nalu:o})}}return s}}const C=(l,t)=>l.getUint8(t)<<16|l.getUint8(t+1)<<8|l.getUint8(t+2);class et{audioConfig;videoConfig;header;textDecoder=new TextDecoder("utf-8");on={};constructor(){}parse=async t=>{let s=0;for(this.header||(this.parseHeader(t,s),s+=9);this.isSurplusTag(t,s)!==!1;){const i=this.parseTagHeader(t,s+4),{tagType:n,dataSize:r,timestamp:a}=i;if(n){const o=this.parseTagBody(n,t,s+4+11,r);switch(n){case"script":this.on.info&&this.on.info(o);break;case"audio":{const{accPacketType:d}=o;if(d===0){const{codec:c,sampleRate:u,channelConfiguration:p}=o;this.audioConfig={kind:"audio",codec:c,sampleRate:u,numberOfChannels:p},this.on.config&&this.on.config(this.audioConfig)}else{const{cts:c,data:u}=o,p="key",h=c===void 0?void 0:c+a;this.on.chunk&&this.on.chunk({kind:"audio",type:p,dts:a,pts:h,cts:c,data:u})}}break;case"video":{const{avcPacketType:d}=o;if(d===0){const{codec:c,sps:u,pps:p,data:h}=o;this.videoConfig={kind:"video",codec:c,description:h,sps:u,pps:p},this.on.config&&this.on.config(this.videoConfig)}else{const{frameType:c,cts:u,data:p,nalus:h}=o,g=c===1?"key":"delta",f=u===void 0?void 0:u+a;this.on.chunk&&this.on.chunk({kind:"video",type:g,dts:a,pts:f,cts:u,data:p,nalus:h})}}break}s=s+4+11+r}await new Promise(o=>setTimeout(()=>o(!0),8))}return s};parseHeader=(t,s)=>{let e,i,n,r;e=t.getUint8(s)<<16|t.getUint8(s+1)<<8|t.getUint8(s+2),i=t.getUint8(3);{const o=t.getUint8(0).toString(2).padStart(5,"0").split(""),[,,d,,c]=o;n={audio:c==="1",video:d==="1"}}r=t.getUint32(5),this.header={signature:e,version:i,flags:n,dataOffset:r}};isSurplusTag=(t,s)=>{let e=!0;const i=t.byteLength;if(s+4>i)e=!1;else if(s+4+11>i)e=!1;else{const n=C(t,s+4+1);s+4+11+n>i&&(e=!1)}return e};parseTagHeader=(t,s)=>{let e,i,n,r,a;{const o=t.getUint8(s);let d;switch(o){case 18:d="script";break;case 8:d="audio";break;case 9:d="video";break}e=d}return i=C(t,s+1),n=C(t,s+4),r=t.getUint8(s+7),a=C(t,s+8),{tagType:e,dataSize:i,timestamp:n,timestampExtended:r,streamID:a}};parseTagBody=(t,s,e,i)=>{let n;switch(t){case"script":n=this.parseMetaData(s,e);break;case"audio":n=this.parseAudio(s,e,i);break;case"video":n=this.parseVideo(s,e,i);break}return n};parseMetaData=(t,s)=>{let e=s;{if(t.getUint8(e)!==2)throw new Error("Invalid AMF type for onMetaData (expected 0x02)");e=e+1}const i=t.getUint16(e,!1);e=e+2;{const a=new Int8Array(t.buffer.slice(e,e+i));if((this.textDecoder?.decode(a)||"")!=="onMetaData")throw new Error("Expected 'onMetaData' string");e=e+i}const n=this.getAmfType(t,e);return e=e+1,this.getAMFValue(t,e,n).value};parseAudio=(t,s,e)=>{let i=s;const n=t.getUint8(i),r=n>>4&15,a=n>>2&3,o=n>>1&1,d=n&1;i=i+1;const c=t.getUint8(i);i=i+1;const u=e,p=new Uint8Array(t.buffer.slice(i,i+u));if(r===10&&c===0){const h=t.getUint8(i),g=t.getUint8(i+1),f=h>>3&31,y=(h&7)<<1|g>>7,b=g>>3&15,k=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],T=`mp4a.40.${f}`,w=k[y];return{soundFormat:r,soundRate:a,soundSize:o,soundType:d,accPacketType:c,data:p,samplingFrequencyIndex:y,channelConfiguration:b,codec:T,sampleRate:w}}return{soundFormat:r,soundRate:a,soundSize:o,soundType:d,accPacketType:c,data:p}};parseVideo=(t,s,e)=>{let i=s;const n=t.getUint8(i),r=n>>4&15,a=n&15;i=i+1;const o=t.getUint8(i);i=i+1;const d=C(t,i);i=i+3;const c=e-5,u=new Uint8Array(t.buffer.slice(i,i+c));switch(a){case 7:if(o===0){const p=V(u);return{frameType:r,codecID:a,avcPacketType:o,cts:d,data:u,...p}}else if(o===1){const p=[],h=i+e-5;for(;!(i+4>h);){const g=t.getUint32(i,!1),f=new Uint8Array(t.buffer.slice(i,i+4+g));i+=4+g,p.push(f)}return{frameType:r,codecID:a,avcPacketType:o,cts:d,data:u,nalus:p}}break;default:throw new Error("Unsupported codecID")}return{frameType:r,codecID:a,avcPacketType:o,cts:d,data:u}};getAmfType=(t,s)=>t.getUint8(s);getAMFName=(t,s,e)=>{const i=new Uint8Array(t.buffer.slice(s,s+e));return this.textDecoder?.decode(i)||""};getAMFValue=(t,s,e)=>{let i=s,n,r=0;switch(e){case 0:n=t.getFloat64(i,!1),r=8;break;case 1:n=!!t.getUint8(i),r=1;break;case 2:{n="";const o=t.getUint16(i,!1);i=i+2;const d=new Int8Array(t.buffer,i,o).filter(u=>u!==0);n=(this.textDecoder?.decode(d)||"").trim(),r=2+o}break;case 3:for(n={};i<t.byteLength;){const o=t.getUint16(i,!1);if(o===0)break;i=i+2;const d=this.getAMFName(t,i,o);i=i+o;const c=this.getAmfType(t,i);if(c===6)break;i=i+1;const u=this.getAMFValue(t,i,c);i=i+u.length,n[d]=u.value,r=2+o+1+u.length}break;case 8:{n={};const o=t.getUint32(i,!1);i=i+4;for(let d=0;d<o;d++){const c=t.getUint16(i,!1);i=i+2;const u=this.getAMFName(t,i,c);i=i+c;const p=this.getAmfType(t,i);i=i+1;const h=this.getAMFValue(t,i,p);i=i+h.length,n[u]=h.value,r=2+c+1+h.length}}break;case 10:{n=[];const o=t.getUint32(i,!1);i=i+4;for(let d=0;d<o;d++){const c=this.getAmfType(t,i);i=i+1;const u=this.getAMFValue(t,i,c);i=i+u.length,n.push(u.value),r=1+u.length}}break}return{amfType:e,length:r,value:n}}}class st{pattern;cacher=new J;isParseing=!1;offset=0;parser;on={};constructor(){}init=t=>{switch(this.destroy(),this.pattern=t,this.pattern){case"flv":this.parser=new et;break;case"hls":this.parser=new tt;break;default:throw new Error("is error pattern.")}this.parser.on.debug=s=>this.on.debug&&this.on.debug(s),this.parser.on.info=s=>this.on.info&&this.on.info(s),this.parser.on.config=s=>this.on.config&&this.on.config(s),this.parser.on.chunk=s=>{this.cacher.pushChunk(s),this.on.chunk&&this.on.chunk(s)}};push=t=>{this.cacher.push(t),this.isParseing===!1&&this.parse()};destroy=()=>{this.cacher.destroy(),this.isParseing=!1,this.offset=0};parse=async()=>{try{if(this.isParseing=!0,!this.pattern)throw new Error("You need to set the pattern.");if(!this.parser)throw new Error("You need to init parser.");for(;;){const t=this.cacher.next(this.offset);if(this.offset=0,!t)break;this.offset=await this.parser.parse(t)}this.isParseing=!1}catch{this.destroy()}}}class it{pattern="flv";audioDecoderConfig;audioDecoder;videoDecoderConfig;videoDecoder;hasKeyFrame=!1;baseTime=0;pendingChunks=[];currentChunk;isProcessing=!1;decodeTimer=0;frameTrack=!1;isFrameTrack=!1;fameTrackOption={flv:[30,50],hls:[200,300],dash:[50,100],rtmp:[50,100]};decodingSpeedRatio=1;maxDecodingSpeedRatio=2;decodingSpeed=16;fps=0;firstVideoChunkTimestamp;secondVideoChunkTimestamp;frameStartTime;lastRenderTime;nextRenderTime;on={audio:{},video:{}};constructor(){}init=t=>{this.destroy(),this.pattern=t,this.baseTime=new Date().getTime()-performance.now(),this.initDecodeInterval()};initAudio=t=>{this.audio.destroy(),this.audioDecoderConfig={...t},this.audioDecoder=new AudioDecoder({output:s=>{const e=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:s,playbackRate:e})},error:s=>{this.on.audio.error&&this.on.audio.error(s)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=t=>{this.video.destroy(),this.videoDecoderConfig={...t},this.videoDecoder=new VideoDecoder({output:async s=>{this.frameStartTime||(this.frameStartTime=s.timestamp);const e=s.timestamp-this.frameStartTime+this.baseTime*1e3,i=await createImageBitmap(s);s.close(),i.width>0&&i.height>0?(this.on.video.decode&&this.on.video.decode({timestamp:e,bitmap:i}),this.currentChunk&&this.currentChunk.kind==="video"&&this.currentChunk.nalus&&this.on.nalus&&this.on.nalus(this.currentChunk.nalus)):i.close()},error:s=>{this.on.video.error&&this.on.video.error(s)}}),this.videoDecoder.configure(this.videoDecoderConfig)};setFrameTrack=t=>{this.frameTrack=t,this.frameTrack===!1&&(this.decodingSpeedRatio=1)};push=t=>{this.pendingChunks.push(t)};destroy=()=>{this.audio.destroy(),this.video.destroy(),this.pendingChunks=[],this.firstVideoChunkTimestamp=void 0,this.secondVideoChunkTimestamp=void 0,this.frameStartTime=void 0,this.lastRenderTime=void 0,this.nextRenderTime=void 0,clearInterval(this.decodeTimer)};initDecodeInterval=()=>{let t=this.decodingSpeed/this.decodingSpeedRatio;const s=this.baseTime+performance.now();if(this.lastRenderTime||(this.lastRenderTime=s),this.fps=Math.round(1e3/(s-this.lastRenderTime)),this.lastRenderTime=s,this.nextRenderTime){const e=this.lastRenderTime-this.nextRenderTime;t-=e}this.nextRenderTime=this.lastRenderTime+t,this.decodeTimer=setTimeout(()=>{this.decode(),this.initDecodeInterval()},t)};decode=()=>{if(this.isProcessing!==!0){for(this.isProcessing=!0;;){this.currentChunk=this.pendingChunks.shift();const t=this.pendingChunks.length;if(this.frameTrack){const[i,n]=this.fameTrackOption[this.pattern];if(t<=i&&(this.isFrameTrack=!1),t>=n&&(this.isFrameTrack=!0),this.isFrameTrack){const r=Math.min(1+(t-i)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(r.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){const{decodingSpeed:i,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:i,decodingSpeedRatio:n,fps:r,cacheLength:t})}if(!this.currentChunk)break;const{kind:s,init:e}=this.currentChunk;switch(s){case"audio":this.decodeAudio(e);break;case"video":this.decodeVideo(e);break}if(s==="video")break}this.isProcessing=!1}};decodeAudio=t=>{if(!this.audioDecoder)return;const s=new EncodedAudioChunk(t);this.audioDecoder.decode(s)};decodeVideo=t=>{if(this.videoDecoder&&(t.type==="key"&&(this.hasKeyFrame=!0),this.firstVideoChunkTimestamp?this.secondVideoChunkTimestamp||(this.secondVideoChunkTimestamp=t.timestamp,this.decodingSpeed=(this.secondVideoChunkTimestamp-this.firstVideoChunkTimestamp)/1e3):this.firstVideoChunkTimestamp=t.timestamp,this.hasKeyFrame)){const s=new EncodedVideoChunk(t);this.videoDecoder.decode(s)}};audio={flush:()=>{this.audioDecoder?.flush()},destroy:()=>{this.audioDecoderConfig=void 0,this.audioDecoder?.close(),this.audioDecoder=void 0}};video={flush:()=>{this.videoDecoder?.flush()},destroy:()=>{this.videoDecoderConfig=void 0,this.videoDecoder?.close(),this.videoDecoder=void 0,this.hasKeyFrame=!1}}}class nt{writable;writer;cutOption;pause=!1;constructor(){}init=({writable:t})=>{this.destroy(),this.writable=t,this.writer=this.writable.getWriter()};push=async t=>{if(this.pause)return;const{timestamp:s}=t;let{bitmap:e}=t;if(this.cutOption){const{sx:n=0,sy:r=0,sw:a=e.width,sh:o=e.height}=this.cutOption;e=await createImageBitmap(e,n,r,a,o)}const i=new VideoFrame(e,{timestamp:s});this.cutOption&&e.close(),this.writer.write(i),i.close()};setCut=t=>{this.cutOption=t};setPause=t=>{this.pause=t};destroy=()=>{this.writable=void 0,this.writer=void 0,this.cutOption=void 0}}U.Decoder=it,U.DecoderWorker=S,U.Demuxer=st,U.DemuxerWorker=A,U.PrPlayer=Q,U.Render=nt,U.RenderWorker=P,Object.defineProperty(U,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pr-player",
3
3
  "description": "对 flv hls 格式的地址进行解析 并输出 MediaStream,提供 demuxer 层(info、chunk)回调、 decoder 层(audio、video、sei)回调 ,提供 cut 等相关能力,以支持根据业务层 SEI 对视频进行剪切渲染。",
4
- "version": "0.2.12",
4
+ "version": "0.2.14",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist"