pr-player 0.3.7 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +56 -42
- package/dist/index.umd.cjs +2 -2
- package/package.json +7 -6
package/dist/index.js
CHANGED
|
@@ -166,7 +166,15 @@ var d = class {
|
|
|
166
166
|
data: {}
|
|
167
167
|
}), this.worker.terminate();
|
|
168
168
|
};
|
|
169
|
-
}, f = class {
|
|
169
|
+
}, f = "data:text/javascript;base64,LyoqDQogKiDpnZnpn7Pml7bvvJrlnKjpopHln5/ku4Xkv53nlZkgYmluIDDvvZ4077yI6ZqP5py677yJ77yM5YW25L2Z5Li6IDDvvIzlho3lkIjmiJDml7bln5/lhpnlhaXovpPlh7og4oCUIOWNs+S/ruaUueecn+WuniBQQ03vvIznu48gQW5hbHlzZXIoZmZ0U2l6ZT01MTIpIOaXtuWJjSA1IOS4qiBiaW4g5pyJ6IO96YeP44CB5YW25L2Z5o6l6L+RIDDjgIINCiAqIFBFUklPRCDpobvkuI4gUHJBdWRpb1N0cmVhbSDkuK0gYW5hbHlzZXJOb2RlLmZmdFNpemUg5LiA6Ie044CCDQogKi8NCmNsYXNzIG5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3NvciBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3NvciB7DQogIGlzRGVzdHJveSA9IGZhbHNlDQogIGRlYnVnID0gZmFsc2UNCg0KICBzdGF0aWMgU0lMRU5DRV9FUFMgPSAxZS0xNQ0KDQogIC8qKiDkuI4gc3JjL1ByQXVkaW9TdHJlYW0udHMg6YeMIGFuYWx5c2VyTm9kZS5mZnRTaXplIOS/neaMgeS4gOiHtCAqLw0KICBzdGF0aWMgUEVSSU9EID0gNTEyDQoNCiAgLyoqIGJpbiAw772eNCDpmo/mnLrlpI3mlbDvvIjlrp7pg6gv6Jma6YOo77yJ55qE5aSn6Ie05bmF5bqm5bC65bqm77yM5Y+v5oyJ5ZCs5oSfL+e8lueggeWGjeiwgyAqLw0KICBzdGF0aWMgQklOX1NDQUxFID0gMC4wMg0KDQogIGNvbnN0cnVjdG9yKCkgew0KICAgIHN1cGVyKCkNCiAgICB0aGlzLl9zaWxlbnRQY20gPSBuZXcgRmxvYXQzMkFycmF5KG5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5QRVJJT0QpDQogICAgdGhpcy5fc2lsZW50T2ZmID0gbm90RW1wdHlGaWx0ZXJXb3JrbGV0UHJvY2Vzc29yLlBFUklPRA0KICB9DQoNCiAgc3RhdGljIGFsbElucHV0c1NpbGVudChpbnB1dHMpIHsNCiAgICBjb25zdCBlcHMgPSBub3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuU0lMRU5DRV9FUFMNCiAgICBmb3IgKGxldCBuaSA9IDA7IG5pIDwgaW5wdXRzLmxlbmd0aDsgbmkrKykgew0KICAgICAgY29uc3QgaW5wdXQgPSBpbnB1dHNbbmldDQogICAgICBpZiAoIWlucHV0KSBjb250aW51ZQ0KICAgICAgZm9yIChsZXQgY2ggPSAwOyBjaCA8IGlucHV0Lmxlbmd0aDsgY2grKykgew0KICAgICAgICBjb25zdCBjaGFubmVsID0gaW5wdXRbY2hdDQogICAgICAgIGlmICghY2hhbm5lbCkgY29udGludWUNCiAgICAgICAgY29uc3QgbiA9IGNoYW5uZWwubGVuZ3RoDQogICAgICAgIGZvciAobGV0IGkgPSAwOyBpIDwgbjsgaSsrKSB7DQogICAgICAgICAgaWYgKE1hdGguYWJzKGNoYW5uZWxbaV0pID49IGVwcykgcmV0dXJuIGZhbHNlDQogICAgICAgIH0NCiAgICAgIH0NCiAgICB9DQogICAgcmV0dXJuIHRydWUNCiAgfQ0KDQogIC8qKg0KICAgKiDku4UgYmluIDAuLjQg6Z2e6Zu277yI6ZqP5py677yJ77yM5ruh6Laz5a6e5L+h5Y+3IElERlTvvIzlhpnlhaUgdGhpcy5fc2lsZW50UGNtDQogICAqLw0KICByZWZpbGxTaWxlbnRQY21Gcm9tRml2ZUJpbnMoKSB7DQogICAgY29uc3QgTiA9IG5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5QRVJJT0QNCiAgICBjb25zdCBzY2FsZSA9IG5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5CSU5fU0NBTEUNCiAgICBjb25zdCByZSA9IG5ldyBGbG9hdDY0QXJyYXkoNSkNCiAgICBjb25zdCBpbSA9IG5ldyBGbG9hdDY0QXJyYXkoNSkNCiAgICByZVswXSA9IChNYXRoLnJhbmRvbSgpICogMiAtIDEpICogc2NhbGUNCiAgICBpbVswXSA9IDANCiAgICBmb3IgKGxldCBrID0gMTsgayA8PSA0OyBrKyspIHsNCiAgICAgIHJlW2tdID0gKE1hdGgucmFuZG9tKCkgKiAyIC0gMSkgKiBzY2FsZQ0KICAgICAgaW1ba10gPSAoTWF0aC5yYW5kb20oKSAqIDIgLSAxKSAqIHNjYWxlDQogICAgfQ0KICAgIGNvbnN0IGludk4gPSAxIC8gTg0KICAgIGNvbnN0IHR3b1BpT3Zlck4gPSAoMiAqIE1hdGguUEkpIC8gTg0KICAgIGZvciAobGV0IG4gPSAwOyBuIDwgTjsgbisrKSB7DQogICAgICBsZXQgcyA9IHJlWzBdDQogICAgICBmb3IgKGxldCBrID0gMTsgayA8PSA0OyBrKyspIHsNCiAgICAgICAgY29uc3QgYW5nID0gdHdvUGlPdmVyTiAqIGsgKiBuDQogICAgICAgIHMgKz0gMiAqIChyZVtrXSAqIE1hdGguY29zKGFuZykgLSBpbVtrXSAqIE1hdGguc2luKGFuZykpDQogICAgICB9DQogICAgICB0aGlzLl9zaWxlbnRQY21bbl0gPSBzICogaW52Tg0KICAgIH0NCiAgICB0aGlzLl9zaWxlbnRPZmYgPSAwDQogIH0NCg0KICBmaWxsT3V0cHV0c1NwYXJzZUZpdmVCaW5zKG91dHB1dHMpIHsNCiAgICBjb25zdCBmaXJzdCA9IG91dHB1dHNbMF0NCiAgICBpZiAoIWZpcnN0IHx8ICFmaXJzdFswXSkgcmV0dXJuDQogICAgY29uc3QgZnJhbWVMZW4gPSBmaXJzdFswXS5sZW5ndGgNCg0KICAgIGZvciAobGV0IGkgPSAwOyBpIDwgZnJhbWVMZW47IGkrKykgew0KICAgICAgaWYgKHRoaXMuX3NpbGVudE9mZiA+PSBub3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuUEVSSU9EKSB7DQogICAgICAgIHRoaXMucmVmaWxsU2lsZW50UGNtRnJvbUZpdmVCaW5zKCkNCiAgICAgIH0NCiAgICAgIGNvbnN0IHYgPSB0aGlzLl9zaWxlbnRQY21bdGhpcy5fc2lsZW50T2ZmKytdDQogICAgICBmb3IgKGxldCBubyA9IDA7IG5vIDwgb3V0cHV0cy5sZW5ndGg7IG5vKyspIHsNCiAgICAgICAgY29uc3Qgb3V0UG9ydHMgPSBvdXRwdXRzW25vXQ0KICAgICAgICBpZiAoIW91dFBvcnRzKSBjb250aW51ZQ0KICAgICAgICBmb3IgKGxldCBjaCA9IDA7IGNoIDwgb3V0UG9ydHMubGVuZ3RoOyBjaCsrKSB7DQogICAgICAgICAgY29uc3QgY2hhbm5lbCA9IG91dFBvcnRzW2NoXQ0KICAgICAgICAgIGlmIChjaGFubmVsKSBjaGFubmVsW2ldID0gdg0KICAgICAgICB9DQogICAgICB9DQogICAgfQ0KICB9DQoNCiAgc3RhdGljIGNvcHlJbnB1dHNUb091dHB1dHMoaW5wdXRzLCBvdXRwdXRzKSB7DQogICAgZm9yIChsZXQgbm8gPSAwOyBubyA8IG91dHB1dHMubGVuZ3RoOyBubysrKSB7DQogICAgICBjb25zdCBvdXRQb3J0cyA9IG91dHB1dHNbbm9dDQogICAgICBjb25zdCBpblBvcnRzID0gaW5wdXRzW25vXQ0KICAgICAgaWYgKCFvdXRQb3J0cykgY29udGludWUNCiAgICAgIGZvciAobGV0IGNoID0gMDsgY2ggPCBvdXRQb3J0cy5sZW5ndGg7IGNoKyspIHsNCiAgICAgICAgY29uc3Qgb3V0Q2ggPSBvdXRQb3J0c1tjaF0NCiAgICAgICAgaWYgKCFvdXRDaCkgY29udGludWUNCiAgICAgICAgY29uc3QgaW5DaCA9IGluUG9ydHMgJiYgaW5Qb3J0c1tjaF0NCiAgICAgICAgaWYgKGluQ2ggJiYgaW5DaC5sZW5ndGggPT09IG91dENoLmxlbmd0aCkgew0KICAgICAgICAgIG91dENoLnNldChpbkNoKQ0KICAgICAgICB9IGVsc2UgaWYgKGluQ2gpIHsNCiAgICAgICAgICBjb25zdCBuID0gTWF0aC5taW4oaW5DaC5sZW5ndGgsIG91dENoLmxlbmd0aCkNCiAgICAgICAgICBmb3IgKGxldCBpID0gMDsgaSA8IG47IGkrKykgb3V0Q2hbaV0gPSBpbkNoW2ldDQogICAgICAgICAgZm9yIChsZXQgaSA9IG47IGkgPCBvdXRDaC5sZW5ndGg7IGkrKykgb3V0Q2hbaV0gPSAwDQogICAgICAgIH0gZWxzZSB7DQogICAgICAgICAgb3V0Q2guZmlsbCgwKQ0KICAgICAgICB9DQogICAgICB9DQogICAgfQ0KICB9DQoNCiAgcHJvY2VzcyhpbnB1dHMsIG91dHB1dHMpIHsNCiAgICBpZiAodGhpcy5pc0Rlc3Ryb3kpIHJldHVybiBmYWxzZQ0KDQogICAgaWYgKHRoaXMuZGVidWcpIHsNCiAgICAgIGNvbnNvbGUubG9nKCdceDFiWzM4OzI7MDsxNTE7MjU1bSVjJXNceDFiWzBtJywgJ2NvbG9yOiMwMDk3ZmY7JywgJy0tLS0tLS0+QnJlYXRoZTogaW5wdXRzJywgaW5wdXRzKQ0KICAgIH0NCg0KICAgIGlmIChub3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuYWxsSW5wdXRzU2lsZW50KGlucHV0cykpIHsNCiAgICAgIHRoaXMuZmlsbE91dHB1dHNTcGFyc2VGaXZlQmlucyhvdXRwdXRzKQ0KICAgIH0gZWxzZSB7DQogICAgICB0aGlzLl9zaWxlbnRPZmYgPSBub3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuUEVSSU9EDQogICAgICBub3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuY29weUlucHV0c1RvT3V0cHV0cyhpbnB1dHMsIG91dHB1dHMpDQogICAgfQ0KDQogICAgcmV0dXJuIHRydWUNCiAgfQ0KDQogIGRlc3Ryb3koKSB7DQogICAgdGhpcy5pc0Rlc3Ryb3kgPSB0cnVlDQogIH0NCn0NCg0KcmVnaXN0ZXJQcm9jZXNzb3IoJ25vdC1lbXB0eS1maWx0ZXItcHJvY2Vzc29yJywgbm90RW1wdHlGaWx0ZXJXb3JrbGV0UHJvY2Vzc29yKQ0K", p = class {
|
|
170
|
+
audioContext = new AudioContext();
|
|
171
|
+
notEmptyFilterWorkletNode;
|
|
172
|
+
constructor() {}
|
|
173
|
+
createNotEmptyFilterWorkletNode = async (e) => (this.destroy(), this.audioContext = e, await this.audioContext.audioWorklet.addModule(f), this.notEmptyFilterWorkletNode = new AudioWorkletNode(this.audioContext, "not-empty-filter-processor"), this.notEmptyFilterWorkletNode);
|
|
174
|
+
destroy = () => {
|
|
175
|
+
this.notEmptyFilterWorkletNode?.disconnect(), this.notEmptyFilterWorkletNode?.port.postMessage({ type: "destroy" }), this.notEmptyFilterWorkletNode = void 0;
|
|
176
|
+
};
|
|
177
|
+
}, m = class {
|
|
170
178
|
inputStream = new MediaStream();
|
|
171
179
|
outputStream = new MediaStream();
|
|
172
180
|
inputGain = 1;
|
|
@@ -188,8 +196,11 @@ var d = class {
|
|
|
188
196
|
destinationNode;
|
|
189
197
|
denoise = !1;
|
|
190
198
|
mute = !0;
|
|
199
|
+
notEmpty = !1;
|
|
191
200
|
rnnoiseWorklet;
|
|
192
201
|
rnnoiseWorkletNode;
|
|
202
|
+
notEmptyFilterWorklet = new p();
|
|
203
|
+
notEmptyFilterWorkletNode;
|
|
193
204
|
filterStream = (e) => e;
|
|
194
205
|
constructor(e, t) {
|
|
195
206
|
this.inputStream = e, t && (this.audioContext = 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;
|
|
@@ -225,7 +236,10 @@ var d = class {
|
|
|
225
236
|
this.mute = e, this.analyserNode.disconnect(), e === !1 && this.analyserNode.connect(this.outputGainNode);
|
|
226
237
|
};
|
|
227
238
|
setDenoise = async (e = !0) => {
|
|
228
|
-
this.rnnoiseWorklet && (this.inputGainNode.disconnect(),
|
|
239
|
+
this.rnnoiseWorklet && (this.inputGainNode.disconnect(), e ? (this.rnnoiseWorkletNode = await this.rnnoiseWorklet.createRnnoiseWorkletNode(this.audioContext), this.inputGainNode.connect(this.rnnoiseWorkletNode), this.rnnoiseWorkletNode.connect(this.enhanceGainNode)) : (this.inputGainNode.connect(this.enhanceGainNode), this.rnnoiseWorklet.destroy()), this.denoise = e);
|
|
240
|
+
};
|
|
241
|
+
setNotEmpty = async (e = !0) => {
|
|
242
|
+
this.notEmptyFilterWorklet && (e ? (this.notEmptyFilterWorkletNode = await this.notEmptyFilterWorklet.createNotEmptyFilterWorkletNode(this.audioContext), this.notEmptyFilterWorkletNode.connect(this.analyserNode), this.notEmptyFilterWorkletNode.connect(this.destinationNode)) : (this.notEmptyFilterWorkletNode?.disconnect(), this.notEmptyFilterWorklet.destroy()), this.notEmpty = e);
|
|
229
243
|
};
|
|
230
244
|
setInputGain = (e) => {
|
|
231
245
|
this.inputGain = e, this.inputGainNode.gain.setValueAtTime(e, this.audioContext.currentTime);
|
|
@@ -270,7 +284,7 @@ var d = class {
|
|
|
270
284
|
let n = e === "bgs" ? this.bgsGainNode : this.bgmGainNode;
|
|
271
285
|
t ? n.connect(this.destinationNode) : n.disconnect(this.destinationNode);
|
|
272
286
|
};
|
|
273
|
-
},
|
|
287
|
+
}, h = async (e, t) => {
|
|
274
288
|
try {
|
|
275
289
|
let { format: n, numberOfChannels: r, numberOfFrames: i, sampleRate: a } = t, o = e.createBuffer(r, i, a);
|
|
276
290
|
for (let e = 0; e < r; e++) {
|
|
@@ -301,7 +315,7 @@ var d = class {
|
|
|
301
315
|
} catch (e) {
|
|
302
316
|
throw console.error("Failed to convert AudioData to AudioBuffer:", e), e;
|
|
303
317
|
}
|
|
304
|
-
},
|
|
318
|
+
}, g = class {
|
|
305
319
|
prAudioStream;
|
|
306
320
|
audioContext;
|
|
307
321
|
destination;
|
|
@@ -310,12 +324,12 @@ var d = class {
|
|
|
310
324
|
pendingSources = [];
|
|
311
325
|
constructor() {}
|
|
312
326
|
init = (e) => {
|
|
313
|
-
e ||= new (window.AudioContext || window.webkitAudioContext)(), this.audioContext = e, this.destination = this.audioContext.createMediaStreamDestination(), this.stream = new MediaStream(), this.stream.addTrack(this.destination.stream.getAudioTracks()[0]), this.prAudioStream = new
|
|
327
|
+
e ||= new (window.AudioContext || window.webkitAudioContext)(), this.audioContext = e, this.destination = this.audioContext.createMediaStreamDestination(), this.stream = new MediaStream(), this.stream.addTrack(this.destination.stream.getAudioTracks()[0]), this.prAudioStream = new m(this.stream, this.audioContext), this.nextStartTime = 0, this.pendingSources = [];
|
|
314
328
|
};
|
|
315
329
|
async push(e) {
|
|
316
330
|
let { audioData: t, playbackRate: n = 1 } = e;
|
|
317
331
|
if (!this.audioContext || !this.destination) return;
|
|
318
|
-
let r = await
|
|
332
|
+
let r = await h(this.audioContext, t);
|
|
319
333
|
if (t.close(), !r) return;
|
|
320
334
|
let i = this.audioContext.createBufferSource();
|
|
321
335
|
i.buffer = r, i.playbackRate.value = n;
|
|
@@ -330,13 +344,13 @@ var d = class {
|
|
|
330
344
|
destroy() {
|
|
331
345
|
this.audioContext?.close(), this.audioContext = void 0, this.destination = void 0, this.nextStartTime = 0, this.prAudioStream?.stop(), this.pendingSources.forEach((e) => e.stop()), this.pendingSources = [];
|
|
332
346
|
}
|
|
333
|
-
},
|
|
347
|
+
}, _ = (e) => {
|
|
334
348
|
let t = e.toLowerCase();
|
|
335
349
|
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";
|
|
336
|
-
},
|
|
350
|
+
}, v = (e) => {
|
|
337
351
|
let t = e?.getTracks() || [];
|
|
338
352
|
for (let e of t) e.stop();
|
|
339
|
-
},
|
|
353
|
+
}, y = class {
|
|
340
354
|
resolvesMap = /* @__PURE__ */ new Map();
|
|
341
355
|
index = 0;
|
|
342
356
|
constructor() {}
|
|
@@ -368,10 +382,10 @@ var d = class {
|
|
|
368
382
|
n && (clearTimeout(n.timer), n.resolve(), t.delete(e));
|
|
369
383
|
}
|
|
370
384
|
};
|
|
371
|
-
},
|
|
385
|
+
}, b = (e, t) => {
|
|
372
386
|
let n = new Uint8Array(e), r = new Uint8Array(t), i = new Uint8Array(11 + n.length + r.length), a = 0;
|
|
373
387
|
return i[a++] = 1, i[a++] = n[1], i[a++] = n[2], i[a++] = n[3], i[a++] = 255, i[a++] = 225, i[a++] = n.length >> 8 & 255, i[a++] = n.length & 255, i.set(n, a), a += n.length, i[a++] = 1, i[a++] = r.length >> 8 & 255, i[a++] = r.length & 255, i.set(r, a), i;
|
|
374
|
-
},
|
|
388
|
+
}, x = (e) => {
|
|
375
389
|
let t = 0, n = new DataView(e.buffer), r = n.getUint8(t);
|
|
376
390
|
if (t += 1, r !== 1) throw Error("Invalid AVC version");
|
|
377
391
|
let i = n.getUint8(t) & 255;
|
|
@@ -411,10 +425,10 @@ var d = class {
|
|
|
411
425
|
pictureParameterSetLength: p,
|
|
412
426
|
pps: m
|
|
413
427
|
};
|
|
414
|
-
},
|
|
428
|
+
}, S = (e) => {
|
|
415
429
|
let t = new Uint8Array(4 + e.length);
|
|
416
430
|
return new DataView(t.buffer).setUint32(0, e.length, !1), t.set(e, 4), t;
|
|
417
|
-
},
|
|
431
|
+
}, C = (e) => {
|
|
418
432
|
let t = 0;
|
|
419
433
|
for (let n of e) t += n.length;
|
|
420
434
|
let n = new Uint8Array(t), r = 0;
|
|
@@ -423,7 +437,7 @@ var d = class {
|
|
|
423
437
|
n.set(e, r), r += e.length;
|
|
424
438
|
}
|
|
425
439
|
return n;
|
|
426
|
-
},
|
|
440
|
+
}, w = (e) => {
|
|
427
441
|
let t = new DataView(e.buffer), n = 0, r, i, a;
|
|
428
442
|
r = t.getUint32(n, !1), n += 4;
|
|
429
443
|
{
|
|
@@ -443,7 +457,7 @@ var d = class {
|
|
|
443
457
|
header: i,
|
|
444
458
|
data: a
|
|
445
459
|
};
|
|
446
|
-
},
|
|
460
|
+
}, T = class {
|
|
447
461
|
#e = {
|
|
448
462
|
timeout: 5 * 1e3,
|
|
449
463
|
check: !1
|
|
@@ -502,15 +516,15 @@ var d = class {
|
|
|
502
516
|
e.name = "AbortError", this.#t.abort(e);
|
|
503
517
|
}
|
|
504
518
|
};
|
|
505
|
-
},
|
|
519
|
+
}, E = class {
|
|
506
520
|
option = {
|
|
507
521
|
debug: !1,
|
|
508
522
|
frameTrack: !1
|
|
509
523
|
};
|
|
510
524
|
converter = "MediaStreamTrackGenerator" in window ? "generator" : "canvas";
|
|
511
|
-
prFetch = new
|
|
512
|
-
getSegmentsFetch = new
|
|
513
|
-
prResolves = new
|
|
525
|
+
prFetch = new T();
|
|
526
|
+
getSegmentsFetch = new T();
|
|
527
|
+
prResolves = new y();
|
|
514
528
|
url = "";
|
|
515
529
|
start_resolve;
|
|
516
530
|
demuxerWorker;
|
|
@@ -530,7 +544,7 @@ var d = class {
|
|
|
530
544
|
}
|
|
531
545
|
start = async (e) => {
|
|
532
546
|
await this.stop(), this.url = e;
|
|
533
|
-
let t =
|
|
547
|
+
let t = _(e);
|
|
534
548
|
if (t === "unknown") throw Error("This address cannot be parsed.");
|
|
535
549
|
switch (this.init(t), t) {
|
|
536
550
|
case "flv":
|
|
@@ -543,7 +557,7 @@ var d = class {
|
|
|
543
557
|
};
|
|
544
558
|
stop = async () => {
|
|
545
559
|
try {
|
|
546
|
-
this.url = "", clearInterval(this.hls.getSegmentsTimer), this.prFetch.stop(), this.getSegmentsFetch.stop(), this.demuxerWorker?.destroy(), this.decoderWorker?.destroy(), this.renderWorker?.destroy(), this.cutRenders = /* @__PURE__ */ new Map(),
|
|
560
|
+
this.url = "", clearInterval(this.hls.getSegmentsTimer), this.prFetch.stop(), this.getSegmentsFetch.stop(), this.demuxerWorker?.destroy(), this.decoderWorker?.destroy(), this.renderWorker?.destroy(), this.cutRenders = /* @__PURE__ */ new Map(), v(this.stream), this.audioPlayer?.destroy();
|
|
547
561
|
} catch (e) {
|
|
548
562
|
console.log("\x1B[38;2;0;151;255m%c%s\x1B[0m", "color:#0097ff;", "------->pr-player: error", e);
|
|
549
563
|
}
|
|
@@ -595,7 +609,7 @@ var d = class {
|
|
|
595
609
|
}
|
|
596
610
|
};
|
|
597
611
|
init = (e) => {
|
|
598
|
-
this.initRender(), this.initDecoder(e), this.initDemuxer(e), this.audioPlayer = new
|
|
612
|
+
this.initRender(), this.initDecoder(e), this.initDemuxer(e), this.audioPlayer = new g(), this.audioPlayer.init();
|
|
599
613
|
};
|
|
600
614
|
initDemuxer = (e) => {
|
|
601
615
|
this.demuxerWorker = new r(), this.demuxerWorker.init(e), this.demuxerWorker.on.debug = (e) => {
|
|
@@ -674,7 +688,7 @@ var d = class {
|
|
|
674
688
|
}, this.decoderWorker.on.nalus = async (e) => {
|
|
675
689
|
for (let t of e) {
|
|
676
690
|
if (t.byteLength <= 4) continue;
|
|
677
|
-
let { header: e, data: n } =
|
|
691
|
+
let { header: e, data: n } = w(t), { nal_unit_type: r } = e;
|
|
678
692
|
r === 6 && this.on.decoder.sei && this.on.decoder.sei(n);
|
|
679
693
|
}
|
|
680
694
|
}, this.decoderWorker.on.analysis = (e) => {
|
|
@@ -784,7 +798,7 @@ var d = class {
|
|
|
784
798
|
}
|
|
785
799
|
})
|
|
786
800
|
};
|
|
787
|
-
},
|
|
801
|
+
}, D = class {
|
|
788
802
|
pendingPayloads = [];
|
|
789
803
|
payload = new Uint8Array();
|
|
790
804
|
chunks = [];
|
|
@@ -804,7 +818,7 @@ var d = class {
|
|
|
804
818
|
destroy = () => {
|
|
805
819
|
this.pendingPayloads = [], this.payload = new Uint8Array(), this.chunks = [];
|
|
806
820
|
};
|
|
807
|
-
},
|
|
821
|
+
}, O = (e) => {
|
|
808
822
|
let t = "unknown";
|
|
809
823
|
switch (e) {
|
|
810
824
|
case 1:
|
|
@@ -826,7 +840,7 @@ var d = class {
|
|
|
826
840
|
break;
|
|
827
841
|
}
|
|
828
842
|
return t;
|
|
829
|
-
},
|
|
843
|
+
}, k = class {
|
|
830
844
|
pat;
|
|
831
845
|
pmt;
|
|
832
846
|
audioConfig;
|
|
@@ -991,7 +1005,7 @@ var d = class {
|
|
|
991
1005
|
{
|
|
992
1006
|
let t = r.section_length - 9 - 4, a = n + t;
|
|
993
1007
|
for (; n < a;) {
|
|
994
|
-
let t = e.getUint8(n), r =
|
|
1008
|
+
let t = e.getUint8(n), r = O(t), a = e.getUint16(n + 1) & 8191, o = e.getUint16(n + 3) & 4095;
|
|
995
1009
|
if (n += 5, a < 32 || a > 8190) {
|
|
996
1010
|
console.warn(`Invalid elementary_pid: 0x${a.toString(16)}`);
|
|
997
1011
|
continue;
|
|
@@ -1147,7 +1161,7 @@ var d = class {
|
|
|
1147
1161
|
if (!this.videoConfig) {
|
|
1148
1162
|
let t, n;
|
|
1149
1163
|
if (t = e.find((e) => e.type === 7)?.nalu.slice(4), n = e.find((e) => e.type === 8)?.nalu.slice(4), t && n) {
|
|
1150
|
-
let e =
|
|
1164
|
+
let e = b(t, n), { codec: r } = x(e);
|
|
1151
1165
|
this.videoConfig = {
|
|
1152
1166
|
kind: "video",
|
|
1153
1167
|
codec: r,
|
|
@@ -1173,7 +1187,7 @@ var d = class {
|
|
|
1173
1187
|
break;
|
|
1174
1188
|
}
|
|
1175
1189
|
}
|
|
1176
|
-
let a =
|
|
1190
|
+
let a = C(t), { dts: o = 0, pts: s = 0 } = r, c = s - o;
|
|
1177
1191
|
return {
|
|
1178
1192
|
kind: "video",
|
|
1179
1193
|
type: n,
|
|
@@ -1207,7 +1221,7 @@ var d = class {
|
|
|
1207
1221
|
}
|
|
1208
1222
|
let a = n - r;
|
|
1209
1223
|
if (e[n - 1] === 0 && --a, a !== 0) {
|
|
1210
|
-
let n =
|
|
1224
|
+
let n = S(e.slice(r, r + a));
|
|
1211
1225
|
t.push({
|
|
1212
1226
|
type: i,
|
|
1213
1227
|
nalu: n
|
|
@@ -1216,7 +1230,7 @@ var d = class {
|
|
|
1216
1230
|
}
|
|
1217
1231
|
return t;
|
|
1218
1232
|
};
|
|
1219
|
-
},
|
|
1233
|
+
}, A = (e, t) => e.getUint8(t) << 16 | e.getUint8(t + 1) << 8 | e.getUint8(t + 2), j = class {
|
|
1220
1234
|
audioConfig;
|
|
1221
1235
|
videoConfig;
|
|
1222
1236
|
header;
|
|
@@ -1312,7 +1326,7 @@ var d = class {
|
|
|
1312
1326
|
if (t + 4 > r) n = !1;
|
|
1313
1327
|
else if (t + 4 + 11 > r) n = !1;
|
|
1314
1328
|
else {
|
|
1315
|
-
let i =
|
|
1329
|
+
let i = A(e, t + 4 + 1);
|
|
1316
1330
|
t + 4 + 11 + i > r && (n = !1);
|
|
1317
1331
|
}
|
|
1318
1332
|
return n;
|
|
@@ -1334,7 +1348,7 @@ var d = class {
|
|
|
1334
1348
|
}
|
|
1335
1349
|
n = i;
|
|
1336
1350
|
}
|
|
1337
|
-
return r =
|
|
1351
|
+
return r = A(e, t + 1), i = A(e, t + 4), a = e.getUint8(t + 7), o = A(e, t + 8), {
|
|
1338
1352
|
tagType: n,
|
|
1339
1353
|
dataSize: r,
|
|
1340
1354
|
timestamp: i,
|
|
@@ -1420,7 +1434,7 @@ var d = class {
|
|
|
1420
1434
|
r += 1;
|
|
1421
1435
|
let s = e.getUint8(r);
|
|
1422
1436
|
r += 1;
|
|
1423
|
-
let c =
|
|
1437
|
+
let c = A(e, r);
|
|
1424
1438
|
r += 3;
|
|
1425
1439
|
let l = n - 5, u = new Uint8Array(e.buffer.slice(r, r + l));
|
|
1426
1440
|
switch (o) {
|
|
@@ -1431,7 +1445,7 @@ var d = class {
|
|
|
1431
1445
|
avcPacketType: s,
|
|
1432
1446
|
cts: c,
|
|
1433
1447
|
data: u,
|
|
1434
|
-
...
|
|
1448
|
+
...x(u)
|
|
1435
1449
|
};
|
|
1436
1450
|
if (s === 1) {
|
|
1437
1451
|
let t = [], i = r + n - 5;
|
|
@@ -1533,9 +1547,9 @@ var d = class {
|
|
|
1533
1547
|
value: i
|
|
1534
1548
|
};
|
|
1535
1549
|
};
|
|
1536
|
-
},
|
|
1550
|
+
}, M = class {
|
|
1537
1551
|
pattern;
|
|
1538
|
-
cacher = new
|
|
1552
|
+
cacher = new D();
|
|
1539
1553
|
isParseing = !1;
|
|
1540
1554
|
offset = 0;
|
|
1541
1555
|
parser;
|
|
@@ -1544,10 +1558,10 @@ var d = class {
|
|
|
1544
1558
|
init = (e) => {
|
|
1545
1559
|
switch (this.destroy(), this.pattern = e, this.pattern) {
|
|
1546
1560
|
case "flv":
|
|
1547
|
-
this.parser = new
|
|
1561
|
+
this.parser = new j();
|
|
1548
1562
|
break;
|
|
1549
1563
|
case "hls":
|
|
1550
|
-
this.parser = new
|
|
1564
|
+
this.parser = new k();
|
|
1551
1565
|
break;
|
|
1552
1566
|
default: throw Error("is error pattern.");
|
|
1553
1567
|
}
|
|
@@ -1575,7 +1589,7 @@ var d = class {
|
|
|
1575
1589
|
this.destroy();
|
|
1576
1590
|
}
|
|
1577
1591
|
};
|
|
1578
|
-
},
|
|
1592
|
+
}, N = class {
|
|
1579
1593
|
pattern = "flv";
|
|
1580
1594
|
audioDecoderConfig;
|
|
1581
1595
|
audioDecoder;
|
|
@@ -1726,7 +1740,7 @@ var d = class {
|
|
|
1726
1740
|
this.videoDecoderConfig = void 0, this.videoDecoder?.close(), this.videoDecoder = void 0, this.hasKeyFrame = !1;
|
|
1727
1741
|
}
|
|
1728
1742
|
};
|
|
1729
|
-
},
|
|
1743
|
+
}, P = class {
|
|
1730
1744
|
renderMap = /* @__PURE__ */ new Map();
|
|
1731
1745
|
constructor() {}
|
|
1732
1746
|
push = async (e) => {
|
|
@@ -1802,4 +1816,4 @@ var d = class {
|
|
|
1802
1816
|
};
|
|
1803
1817
|
};
|
|
1804
1818
|
//#endregion
|
|
1805
|
-
export {
|
|
1819
|
+
export { N as Decoder, s as DecoderWorker, M as Demuxer, r as DemuxerWorker, E as PrPlayer, P as Render, d as RenderWorker };
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`pr-player`]={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t="(function(){var e=class{pendingPayloads=[];payload=new Uint8Array;chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);let t=this.pendingPayloads.shift();if(!t)return!1;let n=new Uint8Array(this.payload.byteLength+t.byteLength);return n.set(this.payload,0),n.set(t,this.payload.byteLength),this.payload=n,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array,this.chunks=[]}};let t=(e,t)=>{let n=new Uint8Array(e),r=new Uint8Array(t),i=new Uint8Array(11+n.length+r.length),a=0;return i[a++]=1,i[a++]=n[1],i[a++]=n[2],i[a++]=n[3],i[a++]=255,i[a++]=225,i[a++]=n.length>>8&255,i[a++]=n.length&255,i.set(n,a),a+=n.length,i[a++]=1,i[a++]=r.length>>8&255,i[a++]=r.length&255,i.set(r,a),i},n=e=>{let t=0,n=new DataView(e.buffer),r=n.getUint8(t);if(t+=1,r!==1)throw Error(`Invalid AVC version`);let i=n.getUint8(t)&255;t+=1;let a=n.getUint8(t)&255;t+=1;let o=n.getUint8(t)&255;t+=1;let s=`avc1.${Array.from([i,a,o],e=>e.toString(16).padStart(2,`0`)).join(``)}`,c=(n.getUint8(t)&3)-1;t+=1;let l=n.getUint8(t)&31;t+=1;let u=n.getUint16(t,!1);t+=2;let d=new Uint8Array(n.buffer.slice(t,t+u));t+=u;let f=n.getUint8(t)&31;t+=1;let p=n.getUint16(t,!1);t+=2;let m=new Uint8Array(n.buffer.slice(t,t+p));return t+=p,{version:r,codec:s,profile:i,compatibility:a,level:o,lengthSizeMinusOne:c,numOfSequenceParameterSets:l,sequenceParameterSetLength:u,sps:d,numOfPictureParameterSets:f,pictureParameterSetLength:p,pps:m}},r=e=>{let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t},i=e=>{let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e){let e=t;n.set(e,r),r+=e.length}return n},a=e=>{let t=`unknown`;switch(e){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};var o=class{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let t=0;for(;!(t+188>e.byteLength);){if(e.getInt8(t)!=71){t++;continue}await this.parsePacket(e,t),t+=188}return t};parsePacket=async(e,t)=>{if(t+188>e.byteLength||e.getUint8(t)!==71)throw Error(`Invalid TS packet`);let n=t,r=this.parseHeader(e,n);n+=4;let{transport_error_indicator:i,pid:a,payload_unit_start_indicator:o,adaptation_field_control:s}=r;if(i===1||a===void 0)return;let c=184;if(s===2||s===3){let t=e.getUint8(n);n+=1,this.parseAdaptationField(e,n),n+=t,c-=t}if(s===3&&--c,s===1||s===3){let t=new Uint8Array(e.buffer.slice(n,n+c));if(a===0)return this.parsePAT(e,n);{let{programs:t=[]}=this.pat||{};if(t.find(e=>e.pmt_pid===a))return this.parsePMT(e,n)}let{streams:r=[]}=this.pmt||{},i=r.find(e=>e.elementary_pid===a);if(i){if(o===1){let e=this.payloadMap.get(a);if(e){switch(i.kind){case`audio`:{let t=await this.parseAudio(e);this.on.chunk&&this.on.chunk(t)}break;case`video`:{let t=await this.parseVideo(e);this.on.chunk&&this.on.chunk(t),await new Promise(e=>setTimeout(()=>e(!0),0))}break}this.payloadMap.delete(a)}}{this.payloadMap.has(a)||this.payloadMap.set(a,new Uint8Array);let e=this.payloadMap.get(a),n=new Uint8Array(e.byteLength+t.byteLength);n.set(e,0),n.set(t,e.byteLength),this.payloadMap.set(a,n)}}}};parseHeader=(e,t)=>{let n=t,r=e.getUint8(n),i=e.getUint8(n+1),a=e.getUint8(n+2),o=e.getUint8(n+3),s=(i&128)>>7;return s===1?{sync_byte:r,transport_error_indicator:s}:{sync_byte:r,transport_error_indicator:s,payload_unit_start_indicator:(i&64)>>6,transport_priority:(i&32)>>5,pid:(i&31)<<8|a,transport_scrambling_control:(o&192)>>6,adaptation_field_control:o>>4&3,continuity_counter:o&15}};parsePAT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==0)throw Error(`Invalid PAT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u}}let i=[];{let t=r.section_length-5-4,a=n+t;for(;n<a;){let t=e.getUint16(n),r=e.getUint16(n+2)&8191;n+=4,t!==0&&r>=32&&r<=8190&&i.push({program_number:t,pmt_pid:r})}}let a=e.getUint32(n);this.pat={header:r,programs:i,crc32:a},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==2)throw Error(`Invalid PMT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1;let d=e.getUint16(n)&8191;n+=2;let f=e.getUint16(n)&4095;n+=2,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u,pcr_pid:d,program_info_length:f}}let i=[];{let t=r.section_length-9-4,o=n+t;for(;n<o;){let t=e.getUint8(n),r=a(t),o=e.getUint16(n+1)&8191,s=e.getUint16(n+3)&4095;if(n+=5,o<32||o>8190){console.warn(`Invalid elementary_pid: 0x${o.toString(16)}`);continue}i.push({kind:r,stream_type:t,elementary_pid:o,es_info_length:s})}}let o=e.getUint32(n);this.pmt={header:r,streams:i,crc32:o},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(e,t)=>{let n=t,r,i,a,o,s=e.getUint8(n),c=!!(s&128),l=!!(s&64),u=!!(s&32),d=!!(s&16),f=!!(s&8),p=!!(s&4),m=!!(s&2),h=!!(s&1);n+=1;let g=(e,t)=>{let n=BigInt(0);n|=BigInt(e.getUint16(t))<<25n,n|=BigInt(e.getUint16(t+1))<<17n,n|=BigInt(e.getUint16(t+2))<<9n,n|=BigInt(e.getUint16(t+3))<<1n,n|=BigInt(e.getUint16(t+4)>>7);let r=(e.getUint16(t+4)&1)<<8|e.getUint16(t+5);return n=n*300n+BigInt(r),n};if(d&&(r=g(e,n),n+=6),f&&(i=g(e,n),n+=6),p&&(a=e.getInt8(n),n+=1),m){let t=e.getUint8(n);n+=1,o=new Uint8Array(e.buffer,n,t),n+=t}return{discontinuity_indicator:c,random_access_indicator:l,elementary_stream_priority_indicator:u,pcr_flag:d,opcr_flag:f,splicing_point_flag:p,transport_private_data_flag:m,adaptation_field_extension_flag:h,pcr:r,opcr:i,splice_countdown:a,transport_private_data:o}};parseAudio=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts audio payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{if(!this.audioConfig&&t.getUint8(n)===255){let e=t.getUint8(n+2),r=t.getUint8(n+3),i,a;a=e>>2&15,i=(e&1)<<2|r>>6,this.audioConfig={kind:`audio`,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],numberOfChannels:i},this.on.config&&this.on.config(this.audioConfig)}let{dts:e=0,pts:a=0}=r;return{kind:`audio`,type:`key`,dts:e,pts:a,cts:a-e,data:i.slice(7)}}};parseVideo=async e=>{let r=new DataView(e.buffer),a=0,o,s;{let e=r.getUint8(a)===0&&r.getUint8(a+1)===0&&r.getUint8(a+2)===1;if(a+=3,!e)throw Error(`invalid ts video payload.`);let t=r.getUint8(a);a+=1;let n=r.getUint8(a)<<8|r.getUint8(a+1);a+=2;let i,s,c,l,u;{let e=r.getUint8(a);a+=1,i=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=r.getUint8(a);a+=1;let t=e>>6,n=r.getUint8(a);a+=1,(t&2)==2&&(d=this.parsePtsDts(r,a)),f=(t&1)==1?this.parsePtsDts(r,a+5):d,a+=n}o={stream_id:t,pes_packet_length:n,scrambling_control:i,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}s=e.slice(a);{let e=this.getNalus(s);if(!this.videoConfig){let r,i;if(r=e.find(e=>e.type===7)?.nalu.slice(4),i=e.find(e=>e.type===8)?.nalu.slice(4),r&&i){let e=t(r,i),{codec:a}=n(e);this.videoConfig={kind:`video`,codec:a,description:e,sps:r,pps:i},this.on.config&&this.on.config(this.videoConfig)}}let r=[],a=`delta`;for(let t of e){let{type:e,nalu:n}=t;switch(e){case 6:case 9:r.push(n);break;case 1:a=`delta`,r.push(n);break;case 5:a=`key`,r.push(n);break}}let c=i(r),{dts:l=0,pts:u=0}=o,d=u-l;return{kind:`video`,type:a,dts:l,pts:u,cts:d,data:c,nalus:r}}};parsePtsDts(e,t){let n=e.getUint8(t),r=e.getUint8(t+1),i=e.getUint8(t+2),a=e.getUint8(t+3),o=e.getUint8(t+4),s=(BigInt(n)&14n)<<29n|(BigInt(r)&255n)<<22n|(BigInt(i)&254n)<<14n|(BigInt(a)&255n)<<7n|(BigInt(o)&254n)>>1n;return Number(s)/90}getNalus=e=>{let t=[],n=0;for(;!(n+4>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}n+=3;let i=n,a=e[n]&31;for(n+=1;!(n+1>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}break}let o=n-i;if(e[n-1]===0&&--o,o!==0){let n=r(e.slice(i,i+o));t.push({type:a,nalu:n})}}return t}};let s=(e,t)=>e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2);var c=class{audioConfig;videoConfig;header;textDecoder=new TextDecoder(`utf-8`);on={};constructor(){}parse=async e=>{let t=0;for(this.header||(this.parseHeader(e,t),t+=9);this.isSurplusTag(e,t)!==!1;){let{tagType:n,dataSize:r,timestamp:i}=this.parseTagHeader(e,t+4);if(n){let a=this.parseTagBody(n,e,t+4+11,r);switch(n){case`script`:this.on.info&&this.on.info(a);break;case`audio`:{let{accPacketType:e}=a;if(e===0){let{codec:e,sampleRate:t,channelConfiguration:n}=a;this.audioConfig={kind:`audio`,codec:e,sampleRate:t,numberOfChannels:n},this.on.config&&this.on.config(this.audioConfig)}else{let{cts:e,data:t}=a,n=e===void 0?void 0:e+i;this.on.chunk&&this.on.chunk({kind:`audio`,type:`key`,dts:i,pts:n,cts:e,data:t})}}break;case`video`:{let{avcPacketType:e}=a;if(e===0){let{codec:e,sps:t,pps:n,data:r}=a;this.videoConfig={kind:`video`,codec:e,description:r,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}else{let{frameType:e,cts:t,data:n,nalus:r}=a,o=e===1?`key`:`delta`,s=t===void 0?void 0:t+i;this.on.chunk&&this.on.chunk({kind:`video`,type:o,dts:i,pts:s,cts:t,data:n,nalus:r})}}break}t=t+4+11+r}await new Promise(e=>setTimeout(()=>e(!0),8))}return t};parseHeader=(e,t)=>{let n,r,i,a;n=e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),r=e.getUint8(3);{let[,,t,,n]=e.getUint8(0).toString(2).padStart(5,`0`).split(``);i={audio:n===`1`,video:t===`1`}}a=e.getUint32(5),this.header={signature:n,version:r,flags:i,dataOffset:a}};isSurplusTag=(e,t)=>{let n=!0,r=e.byteLength;if(t+4>r)n=!1;else if(t+4+11>r)n=!1;else{let i=s(e,t+4+1);t+4+11+i>r&&(n=!1)}return n};parseTagHeader=(e,t)=>{let n,r,i,a,o;{let r=e.getUint8(t),i;switch(r){case 18:i=`script`;break;case 8:i=`audio`;break;case 9:i=`video`;break}n=i}return r=s(e,t+1),i=s(e,t+4),a=e.getUint8(t+7),o=s(e,t+8),{tagType:n,dataSize:r,timestamp:i,timestampExtended:a,streamID:o}};parseTagBody=(e,t,n,r)=>{let i;switch(e){case`script`:i=this.parseMetaData(t,n);break;case`audio`:i=this.parseAudio(t,n,r);break;case`video`:i=this.parseVideo(t,n,r);break}return i};parseMetaData=(e,t)=>{let n=t;if(e.getUint8(n)!==2)throw Error(`Invalid AMF type for onMetaData (expected 0x02)`);n+=1;let r=e.getUint16(n,!1);n+=2;{let t=new Int8Array(e.buffer.slice(n,n+r));if((this.textDecoder?.decode(t)||``)!==`onMetaData`)throw Error(`Expected 'onMetaData' string`);n+=r}let i=this.getAmfType(e,n);return n+=1,this.getAMFValue(e,n,i).value};parseAudio=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i>>2&3,s=i>>1&1,c=i&1;r+=1;let l=e.getUint8(r);r+=1;let u=n,d=new Uint8Array(e.buffer.slice(r,r+u));if(a===10&&l===0){let t=e.getUint8(r),n=e.getUint8(r+1),i=t>>3&31,u=(t&7)<<1|n>>7;return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d,samplingFrequencyIndex:u,channelConfiguration:n>>3&15,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][u]}}return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d}};parseVideo=(e,t,r)=>{let i=t,a=e.getUint8(i),o=a>>4&15,c=a&15;i+=1;let l=e.getUint8(i);i+=1;let u=s(e,i);i+=3;let d=r-5,f=new Uint8Array(e.buffer.slice(i,i+d));switch(c){case 7:if(l===0)return{frameType:o,codecID:c,avcPacketType:l,cts:u,data:f,...n(f)};if(l===1){let t=[],n=i+r-5;for(;!(i+4>n);){let n=e.getUint32(i,!1),r=new Uint8Array(e.buffer.slice(i,i+4+n));i+=4+n,t.push(r)}return{frameType:o,codecID:c,avcPacketType:l,cts:u,data:f,nalus:t}}break;default:throw Error(`Unsupported codecID`)}return{frameType:o,codecID:c,avcPacketType:l,cts:u,data:f}};getAmfType=(e,t)=>e.getUint8(t);getAMFName=(e,t,n)=>{let r=new Uint8Array(e.buffer.slice(t,t+n));return this.textDecoder?.decode(r)||``};getAMFValue=(e,t,n)=>{let r=t,i,a=0;switch(n){case 0:i=e.getFloat64(r,!1),a=8;break;case 1:i=!!e.getUint8(r),a=1;break;case 2:{i=``;let t=e.getUint16(r,!1);r+=2;let n=new Int8Array(e.buffer,r,t).filter(e=>e!==0);i=(this.textDecoder?.decode(n)||``).trim(),a=2+t}break;case 3:for(i={};r<e.byteLength;){let t=e.getUint16(r,!1);if(t===0)break;r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);if(o===6)break;r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}break;case 8:{i={};let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=e.getUint16(r,!1);r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}}break;case 10:{i=[];let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=this.getAmfType(e,r);r+=1;let n=this.getAMFValue(e,r,t);r+=n.length,i.push(n.value),a=1+n.length}}break}return{amfType:n,length:a,value:i}}};let l=new class{pattern;cacher=new e;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case`flv`:this.parser=new c;break;case`hls`:this.parser=new o;break;default:throw Error(`is error pattern.`)}this.parser.on.debug=e=>this.on.debug&&this.on.debug(e),this.parser.on.info=e=>this.on.info&&this.on.info(e),this.parser.on.config=e=>this.on.config&&this.on.config(e),this.parser.on.chunk=e=>{this.cacher.pushChunk(e),this.on.chunk&&this.on.chunk(e)}};push=e=>{this.cacher.push(e),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 Error(`You need to set the pattern.`);if(!this.parser)throw Error(`You need to init parser.`);for(;;){let e=this.cacher.next(this.offset);if(this.offset=0,!e)break;this.offset=await this.parser.parse(e)}this.isParseing=!1}catch{this.destroy()}}};l.on.info=e=>postMessage({action:`on.info`,data:e}),l.on.config=e=>postMessage({action:`on.config`,data:e}),l.on.chunk=e=>postMessage({action:`on.chunk`,data:e}),l.on.debug=e=>postMessage({action:`on.debug`,data:e}),onmessage=e=>{let{action:t,data:n}=e.data,r=l[t];r&&r(n)}})();",n=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,t],{type:`text/javascript;charset=utf-8`});function r(e){let r;try{if(r=n&&(self.URL||self.webkitURL).createObjectURL(n),!r)throw``;let t=new Worker(r,{name:e?.name});return t.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(r)}),t}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(t),{name:e?.name})}}var i=class{worker=new r;on={};constructor(){this.worker.onmessage=e=>{let{action:t,data:n}=e.data;switch(t){case`on.info`:this.on.info&&this.on.info(n);break;case`on.config`:this.on.config&&this.on.config(n);break;case`on.chunk`:this.on.chunk&&this.on.chunk(n);break;case`on.debug`:this.on.debug&&this.on.debug(n);break}}}init=e=>this.worker.postMessage({action:`init`,data:e});push=e=>this.worker.postMessage({action:`push`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`,data:{}}),this.worker.terminate()}},a="(function(){let e=new class{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:e=>{let t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:e,playbackRate:t})},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:async e=>{this.frameStartTime||=e.timestamp;try{let t=e.timestamp-this.frameStartTime+this.baseTime*1e3,n=await createImageBitmap(e);if(e.close(),!n.width||!n.height)return n.close();this.on.video.decode&&this.on.video.decode({timestamp:t,bitmap:n}),this.currentChunk&&this.currentChunk.kind===`video`&&this.currentChunk.nalus&&this.on.nalus&&this.on.nalus(this.currentChunk.nalus)}catch{e.close()}},error:e=>{this.on.video.error&&this.on.video.error(e)}}),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,t=this.baseTime+performance.now();if(this.lastRenderTime||=t,this.fps=Math.round(1e3/(t-this.lastRenderTime)),this.lastRenderTime=t,this.nextRenderTime){let t=this.lastRenderTime-this.nextRenderTime;e-=t}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(),this.currentChunk;){let e=this.pendingChunks.length;if(this.frameTrack){let[t,n]=this.fameTrackOption[this.pattern];if(e<=t&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){let n=Math.min(1+(e-t)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(n.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){let{decodingSpeed:t,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:t,decodingSpeedRatio:n,fps:r,cacheLength:e})}let{kind:t,init:n}=this.currentChunk;switch(t){case`audio`:this.decodeAudio(n);break;case`video`:this.decodeVideo(n);break}if(t===`video`)break}this.isProcessing=!1}};decodeAudio=e=>{if(!this.audioDecoder)return;let t=new EncodedAudioChunk(e);this.audioDecoder.decode(t)};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)){let t=new EncodedVideoChunk(e);this.videoDecoder.decode(t)}};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}}};e.on.audio.decode=e=>postMessage({action:`on.audio.decode`,data:e},[e.audioData]),e.on.audio.error=e=>postMessage({action:`on.audio.error`,data:e}),e.on.video.decode=e=>postMessage({action:`on.video.decode`,data:e},[e.bitmap]),e.on.video.error=e=>postMessage({action:`on.video.error`,data:e}),e.on.nalus=e=>postMessage({action:`on.nalus`,data:e}),e.on.analysis=e=>postMessage({action:`on.analysis`,data:e}),onmessage=t=>{let{action:n,data:r}=t.data,i=e[n];i&&i(r)}})();",o=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,a],{type:`text/javascript;charset=utf-8`});function s(e){let t;try{if(t=o&&(self.URL||self.webkitURL).createObjectURL(o),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(a),{name:e?.name})}}var c=class{worker=new s;on={audio:{},video:{}};constructor(){this.worker.onmessage=e=>{let{action:t,data:n}=e.data;switch(t){case`on.audio.decode`:this.on.audio.decode&&this.on.audio.decode(n);break;case`on.audio.error`:this.on.audio.error&&this.on.audio.error(n);break;case`on.video.decode`:this.on.video.decode&&this.on.video.decode(n);break;case`on.video.error`:this.on.video.error&&this.on.video.error(n);break;case`on.nalus`:this.on.nalus&&this.on.nalus(n);break;case`on.analysis`:this.on.analysis&&this.on.analysis(n);break}}}init=e=>this.worker.postMessage({action:`init`,data:e});initAudio=e=>this.worker.postMessage({action:`initAudio`,data:e});initVideo=e=>this.worker.postMessage({action:`initVideo`,data:e});push=e=>this.worker.postMessage({action:`push`,data:e});setFrameTrack=e=>this.worker.postMessage({action:`setFrameTrack`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`}),this.worker.terminate()}},l="(function(){let e=new class{renderMap=new Map;constructor(){}push=async e=>{let{timestamp:t}=e,{bitmap:n}=e;try{let e=[...this.renderMap.keys()];for(let r of e){let e=this.renderMap.get(r);if(!e)continue;let{pause:i=!1,writer:a,offscreen:o,option:s}=e;if(i===!0)continue;let c=async e=>{if(a){let n=new VideoFrame(e,{timestamp:t});try{await a.write(n)}catch{}n.close()}else o&&(o.width=e.width,o.height=e.height,o?.getContext(`2d`)?.drawImage(e,0,0))};if(r===`default`)await c(n);else if(s){let{sx:e=0,sy:t=0,sw:r=n.width,sh:i=n.height}=s;await c(await createImageBitmap(n,e,t,r,i))}}}catch{}n.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,option:i}={key:`default`,...e};if(n){let e=n.getWriter();this.renderMap.set(t,{writer:e,option:i,pause:!1})}else this.renderMap.set(t,{offscreen:r,option:i,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{let{key:t,cutOption:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,option:n})};setPause=e=>{let{key:t,pause:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,pause:n})};destroy=()=>{this.renderMap=new Map}};onmessage=t=>{let{action:n,data:r}=t.data,i=e[n];i&&i(r)}})();",u=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,l],{type:`text/javascript;charset=utf-8`});function d(e){let t;try{if(t=u&&(self.URL||self.webkitURL).createObjectURL(u),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(l),{name:e?.name})}}var f=class{worker=new d;constructor(){}push=e=>this.worker.postMessage({action:`push`,data:e},[e.bitmap]);addCut=e=>{let t=[];e.writable&&t.push(e.writable),e.offscreen&&t.push(e.offscreen),this.worker.postMessage({action:`addCut`,data:e},t)};delCut=e=>this.worker.postMessage({action:`delCut`,data:e});setCut=e=>this.worker.postMessage({action:`setCut`,data:e});setPause=e=>this.worker.postMessage({action:`setPause`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`,data:{}}),this.worker.terminate()}},p=class{inputStream=new MediaStream;outputStream=new MediaStream;inputGain=1;enhanceGain=1;bgsGain=1;bgmGain=1;outputGain=1;mixAudioMap=new Map;audioContext=new AudioContext;sourceNode;inputGainNode;enhanceGainNode;bgsGainNode;bgmGainNode;rnnoiseNode;analyserNode;analyserArrayData;outputGainNode;destinationNode;denoise=!1;mute=!0;rnnoiseWorklet;rnnoiseWorkletNode;filterStream=e=>e;constructor(e,t){this.inputStream=e,t&&(this.audioContext=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;{let{sourceNode:e,inputGainNode:t,enhanceGainNode:n,bgsGainNode:r,bgmGainNode:i,analyserNode:a,outputGainNode:o,destinationNode:s}=this;e.connect(t),t.connect(n),n.connect(a),r.connect(a),i.connect(a),n.connect(s),r.connect(s),i.connect(s),o.connect(this.audioContext.destination)}this.audioContext.resume()}use=({rnnoise:e})=>{this.rnnoiseWorklet=new e.RnnoiseWorklet};_changeSource=()=>{this.sourceNode.disconnect(),this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.sourceNode.connect(this.inputGainNode)};replaceTrack=e=>{let t=this.inputStream.getTracks();for(let e of t)this.inputStream.removeTrack(e);this.inputStream.addTrack(e),this._changeSource()};stop=()=>{{let e=this.inputStream.getTracks();for(let t of e)t.stop(),this.inputStream.removeTrack(t)}};pause=async e=>{let t=this.inputStream.getTracks();for(let n of t)n.enabled=!e};getStream=()=>this.filterStream(this.outputStream);setMute=(e=!0)=>{this.mute=e,this.analyserNode.disconnect(),e===!1&&this.analyserNode.connect(this.outputGainNode)};setDenoise=async(e=!0)=>{this.rnnoiseWorklet&&(this.inputGainNode.disconnect(),this.rnnoiseWorklet.destroy(),e?(this.rnnoiseWorkletNode=await this.rnnoiseWorklet.createRnnoiseWorkletNode(this.audioContext),this.inputGainNode.connect(this.rnnoiseWorkletNode),this.rnnoiseWorkletNode.connect(this.enhanceGainNode)):this.inputGainNode.connect(this.enhanceGainNode),this.denoise=e)};setInputGain=e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setEnhanceGain=async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)};setBgsGain=e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setBgmGain=e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setOutputGain=e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)};getVolume=()=>{let{analyserNode:e,analyserArrayData:t}=this;e.getByteFrequencyData(t);let n=0;for(let e=0;e<t.length;e++)n+=t[e];return Math.ceil(n/t.length)};mixAudio=(e,t=`bgm`)=>new Promise(async(n,r)=>{try{{let e=this.mixAudioMap.get(t);e&&e.stop()}let r=t===`bgs`?this.bgsGainNode:this.bgmGainNode,i=this.audioContext.createBufferSource();this.mixAudioMap.set(t,i),i.buffer=e,i.connect(r),i.onended=()=>{i.disconnect(r),this.mixAudioMap.delete(t),n(!0)},i.start(0)}catch(e){r(e)}});mixAudioStop=e=>{this.mixAudioMap.get(e)?.stop()};changeMix=(e,t)=>{let n=e===`bgs`?this.bgsGainNode:this.bgmGainNode;t?n.connect(this.destinationNode):n.disconnect(this.destinationNode)}},m=async(e,t)=>{try{let{format:n,numberOfChannels:r,numberOfFrames:i,sampleRate:a}=t,o=e.createBuffer(r,i,a);for(let e=0;e<r;e++){let r=t.allocationSize({planeIndex:e}),a=new Uint8Array(r);t.copyTo(a,{planeIndex:e});let s=new DataView(a.buffer),c=o.getChannelData(e);for(let e=0;e<i;e++){let t;switch(n){case`s16`:case`s16-planar`:t=s.getInt16(e*2,!0)/32768;break;case`f32`:case`f32-planar`:t=s.getFloat32(e*4,!0);break;case`u8`:case`u8-planar`:t=(s.getUint8(e)-128)/128;break;default:throw Error(`Unsupported audio format: ${n}`)}c[e]=Math.max(-1,Math.min(1,t))}}return o}catch(e){throw console.error(`Failed to convert AudioData to AudioBuffer:`,e),e}},h=class{prAudioStream;audioContext;destination;stream=new MediaStream;nextStartTime=0;pendingSources=[];constructor(){}init=e=>{e||=new(window.AudioContext||window.webkitAudioContext),this.audioContext=e,this.destination=this.audioContext.createMediaStreamDestination(),this.stream=new MediaStream,this.stream.addTrack(this.destination.stream.getAudioTracks()[0]),this.prAudioStream=new p(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(e){let{audioData:t,playbackRate:n=1}=e;if(!this.audioContext||!this.destination)return;let r=await m(this.audioContext,t);if(t.close(),!r)return;let i=this.audioContext.createBufferSource();i.buffer=r,i.playbackRate.value=n;let a=-1200*Math.log2(n);i.detune.value=a,i.connect(this.destination);let o=Math.max(this.nextStartTime,this.audioContext.currentTime);this.nextStartTime=o+r.duration/n,i.start(o),this.pendingSources.push(i),i.onended=()=>{this.pendingSources=this.pendingSources.filter(e=>e!==i)},this.audioContext.state===`suspended`&&await this.audioContext.resume()}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(e=>e.stop()),this.pendingSources=[]}},g=e=>{let t=e.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`},_=e=>{let t=e?.getTracks()||[];for(let e of t)e.stop()},v=class{resolvesMap=new Map;index=0;constructor(){}add=(e,t=()=>!1,n=0)=>new Promise(r=>{if(t())return r(!0);this.resolvesMap.has(e)||this.resolvesMap.set(e,new Map),this.index++;let i=`${this.index}`;if(n=Math.max(0,n),n===0){this.resolvesMap.get(e)?.set(i,{resolve:r,timer:0});return}let a=window.setTimeout(()=>{this.emit(e)},n);this.resolvesMap.get(e)?.set(i,{resolve:r,timer:a})});emit=async e=>{let t=this.resolvesMap.get(e);if(!t)return;let n=[...t.keys()];for(let e of n){let n=t.get(e);n&&(clearTimeout(n.timer),n.resolve(),t.delete(e))}}},y=(e,t)=>{let n=new Uint8Array(e),r=new Uint8Array(t),i=new Uint8Array(11+n.length+r.length),a=0;return i[a++]=1,i[a++]=n[1],i[a++]=n[2],i[a++]=n[3],i[a++]=255,i[a++]=225,i[a++]=n.length>>8&255,i[a++]=n.length&255,i.set(n,a),a+=n.length,i[a++]=1,i[a++]=r.length>>8&255,i[a++]=r.length&255,i.set(r,a),i},b=e=>{let t=0,n=new DataView(e.buffer),r=n.getUint8(t);if(t+=1,r!==1)throw Error(`Invalid AVC version`);let i=n.getUint8(t)&255;t+=1;let a=n.getUint8(t)&255;t+=1;let o=n.getUint8(t)&255;t+=1;let s=`avc1.${Array.from([i,a,o],e=>e.toString(16).padStart(2,`0`)).join(``)}`,c=(n.getUint8(t)&3)-1;t+=1;let l=n.getUint8(t)&31;t+=1;let u=n.getUint16(t,!1);t+=2;let d=new Uint8Array(n.buffer.slice(t,t+u));t+=u;let f=n.getUint8(t)&31;t+=1;let p=n.getUint16(t,!1);t+=2;let m=new Uint8Array(n.buffer.slice(t,t+p));return t+=p,{version:r,codec:s,profile:i,compatibility:a,level:o,lengthSizeMinusOne:c,numOfSequenceParameterSets:l,sequenceParameterSetLength:u,sps:d,numOfPictureParameterSets:f,pictureParameterSetLength:p,pps:m}},x=e=>{let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t},S=e=>{let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e){let e=t;n.set(e,r),r+=e.length}return n},C=e=>{let t=new DataView(e.buffer),n=0,r,i,a;r=t.getUint32(n,!1),n+=4;{let e=t.getUint8(n);i={forbidden_zero_bit:e>>7&1,nal_ref_idc:e>>5&3,nal_unit_type:e&31},n+=1}{let e=r-1;a=new Uint8Array(t.buffer.slice(n,n+e))}return{size:r,header:i,data:a}},w=class{#e={timeout:5*1e3,check:!1};#t=null;constructor(e={}){this.#e={...this.#e,...e}}#n=(e,t)=>new Promise(async n=>{this.#t=new AbortController;let{signal:r}=this.#t,i=this.#e.timeout,a=setTimeout(()=>{this.#t?.abort(`Timeout (${i}ms)`)},i);await fetch(e,{cache:`no-store`,...t,method:`HEAD`,signal:r}).then(e=>{clearTimeout(a),n({status:e.status===200?`successed`:`failed`,reason:e.status===200?``:`HTTP ${e.status}`})}).catch(e=>{if(clearTimeout(a),e.name===`AbortError`){let e=r.reason||`Actively stopped`;n({status:e.includes(`Timeout`)?`timeout`:`stopped`,reason:e})}else n({status:`error`,reason:e.message})})});request=(e,t)=>new Promise(async(n,r)=>{try{this.stop(),this.#e.check&&await this.#n(e),this.#t=new AbortController;let{signal:r}=this.#t;n(await fetch(e,{cache:`no-store`,...t,signal:r}))}catch(e){r(e)}});stop=()=>{if(this.#t?.signal.aborted===!1){let e=Error(`Actively stopped.`);e.name=`AbortError`,this.#t.abort(e)}}},T=class{option={debug:!1,frameTrack:!1};converter=`MediaStreamTrackGenerator`in window?`generator`:`canvas`;prFetch=new w;getSegmentsFetch=new w;prResolves=new v;url=``;start_resolve;demuxerWorker;decoderWorker;audioPlayer;renderWorker;stream;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(e={}){let{debug:t=!1}=e;this.option.debug=t}start=async e=>{await this.stop(),this.url=e;let t=g(e);if(t===`unknown`)throw Error(`This address cannot be parsed.`);switch(this.init(t),t){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(),this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy(),this.cutRenders=new Map,_(this.stream),this.audioPlayer?.destroy()}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: error`,e)}};getStream=()=>this.stream;setPause=e=>{this.renderWorker?.setPause({pause:e})};setMute=e=>this.audioPlayer?.prAudioStream?.setMute(e);setOutputGain=e=>{this.audioPlayer?.prAudioStream?.setOutputGain(e)};setFrameTrack=e=>{this.option.frameTrack=e,this.decoderWorker?.setFrameTrack(e)};isReady=()=>this.prResolves.add(`isReady`,()=>this.stream?.active===!0);cut={create:(e,t)=>{if(this.converter===`generator`){let n=new MediaStreamTrackGenerator({kind:`video`}),r=new MediaStream([n]);return this.renderWorker?.addCut({key:e,writable:n.writable,option:t}),this.cutRenders.set(e,{stream:r}),r}let n=document.createElement(`canvas`),r=n.captureStream(),i=n.transferControlToOffscreen();return this.renderWorker?.addCut({key:e,offscreen:i,option:t}),this.cutRenders.set(e,{stream:r}),r},setCut:(e,t)=>{this.renderWorker?.setCut({key:e,cutOption:t})},getStream:e=>this.cutRenders.get(e)?.stream,remove:e=>{this.renderWorker?.delCut(e),this.cutRenders.delete(e)},setPause:(e,t)=>{this.renderWorker?.setPause({key:e,pause:t})}};init=e=>{this.initRender(),this.initDecoder(e),this.initDemuxer(e),this.audioPlayer=new h,this.audioPlayer.init()};initDemuxer=e=>{this.demuxerWorker=new i,this.demuxerWorker.init(e),this.demuxerWorker.on.debug=e=>{this.option.debug&&this.on.debug&&this.on.debug(e)},this.demuxerWorker.on.info=e=>{this.option.debug&&console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: info`,e),this.on.demuxer.info&&this.on.demuxer.info(e)},this.demuxerWorker.on.config=e=>{this.option.debug&&console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: config`,e),this.on.demuxer.config&&this.on.demuxer.config(e);let{kind:t}=e;switch(t){case`audio`:{let{codec:t,sampleRate:n,numberOfChannels:r}=e;this.decoderWorker?.initAudio({codec:t,sampleRate:n,numberOfChannels:r})}break;case`video`:{let{codec:t,description:n}=e;this.decoderWorker?.initVideo({codec:t,description:n})}break}},this.demuxerWorker.on.chunk=e=>{if(this.on.demuxer.chunk&&this.on.demuxer.chunk(e),!this.decoderWorker)return;let{kind:t}=e;switch(t){case`audio`:{let{type:n,dts:r,data:i}=e,a=r*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:a,data:i}})}break;case`video`:{let{type:n,dts:r,data:i,nalus:a=[]}=e,o=r*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:o,data:i},nalus:a})}break}}};initDecoder=e=>{this.decoderWorker=new c,this.decoderWorker.init(e);let{frameTrack:t=!1}=this.option;this.decoderWorker.setFrameTrack(t),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.start_resolve&&=(this.start_resolve(!0),void 0),this.renderWorker?.push(e),this.on.decoder.video&&this.on.decoder.video(e)},this.decoderWorker.on.video.error=e=>{this.on.error&&this.on.error(e)},this.decoderWorker.on.nalus=async e=>{for(let t of e){if(t.byteLength<=4)continue;let{header:e,data:n}=C(t),{nal_unit_type:r}=e;r===6&&this.on.decoder.sei&&this.on.decoder.sei(n)}},this.decoderWorker.on.analysis=e=>{this.on.decoder.analysis&&this.on.decoder.analysis(e)}};initRender=()=>{if(this.renderWorker=new f,this.converter===`generator`){let e=new MediaStreamTrackGenerator({kind:`video`}),t=new MediaStream([e]);this.renderWorker?.addCut({writable:e.writable}),this.stream=t}else{let e=document.createElement(`canvas`),t=e.captureStream(),n=e.transferControlToOffscreen();this.renderWorker?.addCut({offscreen:n}),this.stream=t}this.renderWorker?.setPause({pause:!1})};flv={start:()=>new Promise(async(e,t)=>{try{this.start_resolve=e;let n,r=0;for(;;){r+=1;try{n=await this.prFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(n?.status===200||r===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!n||n.status!==200)return t(`request is error.`);let i=n.body?.getReader();if(!i)return t(`reader is error.`);for(;;){let{done:e,value:t}=await i.read();if(t&&this.demuxerWorker?.push(t),e||this.url===``)break}}catch(e){e.name!==`AbortError`&&t(e)}})};hls={isLive:!1,urls:[],url:``,getSegmentsTimer:0,parse:async e=>{let t=new TextDecoder(`utf-8`).decode(e).split(`
|
|
2
|
-
`).map(e=>e.replace(`\r`,``)),n=this.url.substring(0,this.url.lastIndexOf(`/`)+1),r=4,i=0,a=!1,o=[];for(let e of t)e.startsWith(`#EXTINF:`)?r=parseFloat(e.split(`:`)[1].split(`,`)[0]):e.startsWith(`#EXT-X-TARGETDURATION:`)?i=parseInt(e.split(`:`)[1]):e.startsWith(`#EXT-X-ENDLIST`)?a=!1:e.startsWith(`#EXT-X-MEDIA-SEQUENCE:`)?a=!0:e.includes(`.ts`)&&!e.startsWith(`#`)&&o.push({url:e.startsWith(`http`)?e:n+e,duration:r,isLive:a});return{baseUrl:n,targetDuration:i,isLive:a,segments:o}},getSegments:async()=>{try{let e,t=0;for(;;){t+=1;try{e=await this.getSegmentsFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(e?.status===200||t===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!e||e.status!==200)throw Error(`request is error.`);let n=e.body?.getReader();if(!n)throw Error(`reader is error.`);for(;;){let{done:e,value:t}=await n.read();if(t){let{segments:e=[],isLive:n=!1}=await this.hls.parse(t);this.hls.isLive=n,n===!1&&(this.option.frameTrack=!1);let r=Array.from(e,e=>e.url),i=r.findIndex(e=>e===this.hls.url);i!==-1&&(r=r.slice(i+1)),this.hls.urls=r}if(e||this.url===``)break}}catch(e){e.name!==`AbortError`&&this.on.error&&this.on.error(e)}},start:()=>new Promise(async(e,t)=>{try{for(this.start_resolve=e,this.hls.url=``,this.hls.urls=[],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));;){let e=this.hls.urls.shift();if(e){this.hls.url=e;let t=(await this.prFetch.request(e)).body?.getReader();if(!t)throw Error(`segment reader is error.`);for(;;){let{done:e,value:n}=await t.read();if(n&&this.demuxerWorker?.push(n),e||this.url===``)break}}else await new Promise(e=>setTimeout(()=>e(!0),300))}}catch(e){e.name!==`AbortError`&&t(e)}})}},E=class{pendingPayloads=[];payload=new Uint8Array;chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);let t=this.pendingPayloads.shift();if(!t)return!1;let n=new Uint8Array(this.payload.byteLength+t.byteLength);return n.set(this.payload,0),n.set(t,this.payload.byteLength),this.payload=n,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array,this.chunks=[]}},D=e=>{let t=`unknown`;switch(e){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},O=class{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let t=0;for(;!(t+188>e.byteLength);){if(e.getInt8(t)!=71){t++;continue}await this.parsePacket(e,t),t+=188}return t};parsePacket=async(e,t)=>{if(t+188>e.byteLength||e.getUint8(t)!==71)throw Error(`Invalid TS packet`);let n=t,r=this.parseHeader(e,n);n+=4;let{transport_error_indicator:i,pid:a,payload_unit_start_indicator:o,adaptation_field_control:s}=r;if(i===1||a===void 0)return;let c=184;if(s===2||s===3){let t=e.getUint8(n);n+=1,this.parseAdaptationField(e,n),n+=t,c-=t}if(s===3&&--c,s===1||s===3){let t=new Uint8Array(e.buffer.slice(n,n+c));if(a===0)return this.parsePAT(e,n);{let{programs:t=[]}=this.pat||{};if(t.find(e=>e.pmt_pid===a))return this.parsePMT(e,n)}let{streams:r=[]}=this.pmt||{},i=r.find(e=>e.elementary_pid===a);if(i){if(o===1){let e=this.payloadMap.get(a);if(e){switch(i.kind){case`audio`:{let t=await this.parseAudio(e);this.on.chunk&&this.on.chunk(t)}break;case`video`:{let t=await this.parseVideo(e);this.on.chunk&&this.on.chunk(t),await new Promise(e=>setTimeout(()=>e(!0),0))}break}this.payloadMap.delete(a)}}{this.payloadMap.has(a)||this.payloadMap.set(a,new Uint8Array);let e=this.payloadMap.get(a),n=new Uint8Array(e.byteLength+t.byteLength);n.set(e,0),n.set(t,e.byteLength),this.payloadMap.set(a,n)}}}};parseHeader=(e,t)=>{let n=t,r=e.getUint8(n),i=e.getUint8(n+1),a=e.getUint8(n+2),o=e.getUint8(n+3),s=(i&128)>>7;return s===1?{sync_byte:r,transport_error_indicator:s}:{sync_byte:r,transport_error_indicator:s,payload_unit_start_indicator:(i&64)>>6,transport_priority:(i&32)>>5,pid:(i&31)<<8|a,transport_scrambling_control:(o&192)>>6,adaptation_field_control:o>>4&3,continuity_counter:o&15}};parsePAT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==0)throw Error(`Invalid PAT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u}}let i=[];{let t=r.section_length-5-4,a=n+t;for(;n<a;){let t=e.getUint16(n),r=e.getUint16(n+2)&8191;n+=4,t!==0&&r>=32&&r<=8190&&i.push({program_number:t,pmt_pid:r})}}let a=e.getUint32(n);this.pat={header:r,programs:i,crc32:a},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==2)throw Error(`Invalid PMT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1;let d=e.getUint16(n)&8191;n+=2;let f=e.getUint16(n)&4095;n+=2,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u,pcr_pid:d,program_info_length:f}}let i=[];{let t=r.section_length-9-4,a=n+t;for(;n<a;){let t=e.getUint8(n),r=D(t),a=e.getUint16(n+1)&8191,o=e.getUint16(n+3)&4095;if(n+=5,a<32||a>8190){console.warn(`Invalid elementary_pid: 0x${a.toString(16)}`);continue}i.push({kind:r,stream_type:t,elementary_pid:a,es_info_length:o})}}let a=e.getUint32(n);this.pmt={header:r,streams:i,crc32:a},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(e,t)=>{let n=t,r,i,a,o,s=e.getUint8(n),c=!!(s&128),l=!!(s&64),u=!!(s&32),d=!!(s&16),f=!!(s&8),p=!!(s&4),m=!!(s&2),h=!!(s&1);n+=1;let g=(e,t)=>{let n=BigInt(0);n|=BigInt(e.getUint16(t))<<25n,n|=BigInt(e.getUint16(t+1))<<17n,n|=BigInt(e.getUint16(t+2))<<9n,n|=BigInt(e.getUint16(t+3))<<1n,n|=BigInt(e.getUint16(t+4)>>7);let r=(e.getUint16(t+4)&1)<<8|e.getUint16(t+5);return n=n*300n+BigInt(r),n};if(d&&(r=g(e,n),n+=6),f&&(i=g(e,n),n+=6),p&&(a=e.getInt8(n),n+=1),m){let t=e.getUint8(n);n+=1,o=new Uint8Array(e.buffer,n,t),n+=t}return{discontinuity_indicator:c,random_access_indicator:l,elementary_stream_priority_indicator:u,pcr_flag:d,opcr_flag:f,splicing_point_flag:p,transport_private_data_flag:m,adaptation_field_extension_flag:h,pcr:r,opcr:i,splice_countdown:a,transport_private_data:o}};parseAudio=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts audio payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{if(!this.audioConfig&&t.getUint8(n)===255){let e=t.getUint8(n+2),r=t.getUint8(n+3),i,a;a=e>>2&15,i=(e&1)<<2|r>>6,this.audioConfig={kind:`audio`,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],numberOfChannels:i},this.on.config&&this.on.config(this.audioConfig)}let{dts:e=0,pts:a=0}=r;return{kind:`audio`,type:`key`,dts:e,pts:a,cts:a-e,data:i.slice(7)}}};parseVideo=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts video payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{let e=this.getNalus(i);if(!this.videoConfig){let t,n;if(t=e.find(e=>e.type===7)?.nalu.slice(4),n=e.find(e=>e.type===8)?.nalu.slice(4),t&&n){let e=y(t,n),{codec:r}=b(e);this.videoConfig={kind:`video`,codec:r,description:e,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}}let t=[],n=`delta`;for(let r of e){let{type:e,nalu:i}=r;switch(e){case 6:case 9:t.push(i);break;case 1:n=`delta`,t.push(i);break;case 5:n=`key`,t.push(i);break}}let a=S(t),{dts:o=0,pts:s=0}=r,c=s-o;return{kind:`video`,type:n,dts:o,pts:s,cts:c,data:a,nalus:t}}};parsePtsDts(e,t){let n=e.getUint8(t),r=e.getUint8(t+1),i=e.getUint8(t+2),a=e.getUint8(t+3),o=e.getUint8(t+4),s=(BigInt(n)&14n)<<29n|(BigInt(r)&255n)<<22n|(BigInt(i)&254n)<<14n|(BigInt(a)&255n)<<7n|(BigInt(o)&254n)>>1n;return Number(s)/90}getNalus=e=>{let t=[],n=0;for(;!(n+4>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}n+=3;let r=n,i=e[n]&31;for(n+=1;!(n+1>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}break}let a=n-r;if(e[n-1]===0&&--a,a!==0){let n=x(e.slice(r,r+a));t.push({type:i,nalu:n})}}return t}},k=(e,t)=>e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),A=class{audioConfig;videoConfig;header;textDecoder=new TextDecoder(`utf-8`);on={};constructor(){}parse=async e=>{let t=0;for(this.header||(this.parseHeader(e,t),t+=9);this.isSurplusTag(e,t)!==!1;){let{tagType:n,dataSize:r,timestamp:i}=this.parseTagHeader(e,t+4);if(n){let a=this.parseTagBody(n,e,t+4+11,r);switch(n){case`script`:this.on.info&&this.on.info(a);break;case`audio`:{let{accPacketType:e}=a;if(e===0){let{codec:e,sampleRate:t,channelConfiguration:n}=a;this.audioConfig={kind:`audio`,codec:e,sampleRate:t,numberOfChannels:n},this.on.config&&this.on.config(this.audioConfig)}else{let{cts:e,data:t}=a,n=e===void 0?void 0:e+i;this.on.chunk&&this.on.chunk({kind:`audio`,type:`key`,dts:i,pts:n,cts:e,data:t})}}break;case`video`:{let{avcPacketType:e}=a;if(e===0){let{codec:e,sps:t,pps:n,data:r}=a;this.videoConfig={kind:`video`,codec:e,description:r,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}else{let{frameType:e,cts:t,data:n,nalus:r}=a,o=e===1?`key`:`delta`,s=t===void 0?void 0:t+i;this.on.chunk&&this.on.chunk({kind:`video`,type:o,dts:i,pts:s,cts:t,data:n,nalus:r})}}break}t=t+4+11+r}await new Promise(e=>setTimeout(()=>e(!0),8))}return t};parseHeader=(e,t)=>{let n,r,i,a;n=e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),r=e.getUint8(3);{let[,,t,,n]=e.getUint8(0).toString(2).padStart(5,`0`).split(``);i={audio:n===`1`,video:t===`1`}}a=e.getUint32(5),this.header={signature:n,version:r,flags:i,dataOffset:a}};isSurplusTag=(e,t)=>{let n=!0,r=e.byteLength;if(t+4>r)n=!1;else if(t+4+11>r)n=!1;else{let i=k(e,t+4+1);t+4+11+i>r&&(n=!1)}return n};parseTagHeader=(e,t)=>{let n,r,i,a,o;{let r=e.getUint8(t),i;switch(r){case 18:i=`script`;break;case 8:i=`audio`;break;case 9:i=`video`;break}n=i}return r=k(e,t+1),i=k(e,t+4),a=e.getUint8(t+7),o=k(e,t+8),{tagType:n,dataSize:r,timestamp:i,timestampExtended:a,streamID:o}};parseTagBody=(e,t,n,r)=>{let i;switch(e){case`script`:i=this.parseMetaData(t,n);break;case`audio`:i=this.parseAudio(t,n,r);break;case`video`:i=this.parseVideo(t,n,r);break}return i};parseMetaData=(e,t)=>{let n=t;if(e.getUint8(n)!==2)throw Error(`Invalid AMF type for onMetaData (expected 0x02)`);n+=1;let r=e.getUint16(n,!1);n+=2;{let t=new Int8Array(e.buffer.slice(n,n+r));if((this.textDecoder?.decode(t)||``)!==`onMetaData`)throw Error(`Expected 'onMetaData' string`);n+=r}let i=this.getAmfType(e,n);return n+=1,this.getAMFValue(e,n,i).value};parseAudio=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i>>2&3,s=i>>1&1,c=i&1;r+=1;let l=e.getUint8(r);r+=1;let u=n,d=new Uint8Array(e.buffer.slice(r,r+u));if(a===10&&l===0){let t=e.getUint8(r),n=e.getUint8(r+1),i=t>>3&31,u=(t&7)<<1|n>>7;return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d,samplingFrequencyIndex:u,channelConfiguration:n>>3&15,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][u]}}return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d}};parseVideo=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i&15;r+=1;let s=e.getUint8(r);r+=1;let c=k(e,r);r+=3;let l=n-5,u=new Uint8Array(e.buffer.slice(r,r+l));switch(o){case 7:if(s===0)return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u,...b(u)};if(s===1){let t=[],i=r+n-5;for(;!(r+4>i);){let n=e.getUint32(r,!1),i=new Uint8Array(e.buffer.slice(r,r+4+n));r+=4+n,t.push(i)}return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u,nalus:t}}break;default:throw Error(`Unsupported codecID`)}return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u}};getAmfType=(e,t)=>e.getUint8(t);getAMFName=(e,t,n)=>{let r=new Uint8Array(e.buffer.slice(t,t+n));return this.textDecoder?.decode(r)||``};getAMFValue=(e,t,n)=>{let r=t,i,a=0;switch(n){case 0:i=e.getFloat64(r,!1),a=8;break;case 1:i=!!e.getUint8(r),a=1;break;case 2:{i=``;let t=e.getUint16(r,!1);r+=2;let n=new Int8Array(e.buffer,r,t).filter(e=>e!==0);i=(this.textDecoder?.decode(n)||``).trim(),a=2+t}break;case 3:for(i={};r<e.byteLength;){let t=e.getUint16(r,!1);if(t===0)break;r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);if(o===6)break;r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}break;case 8:{i={};let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=e.getUint16(r,!1);r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}}break;case 10:{i=[];let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=this.getAmfType(e,r);r+=1;let n=this.getAMFValue(e,r,t);r+=n.length,i.push(n.value),a=1+n.length}}break}return{amfType:n,length:a,value:i}}},j=class{pattern;cacher=new E;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case`flv`:this.parser=new A;break;case`hls`:this.parser=new O;break;default:throw Error(`is error pattern.`)}this.parser.on.debug=e=>this.on.debug&&this.on.debug(e),this.parser.on.info=e=>this.on.info&&this.on.info(e),this.parser.on.config=e=>this.on.config&&this.on.config(e),this.parser.on.chunk=e=>{this.cacher.pushChunk(e),this.on.chunk&&this.on.chunk(e)}};push=e=>{this.cacher.push(e),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 Error(`You need to set the pattern.`);if(!this.parser)throw Error(`You need to init parser.`);for(;;){let e=this.cacher.next(this.offset);if(this.offset=0,!e)break;this.offset=await this.parser.parse(e)}this.isParseing=!1}catch{this.destroy()}}},M=class{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:e=>{let t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:e,playbackRate:t})},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:async e=>{this.frameStartTime||=e.timestamp;try{let t=e.timestamp-this.frameStartTime+this.baseTime*1e3,n=await createImageBitmap(e);if(e.close(),!n.width||!n.height)return n.close();this.on.video.decode&&this.on.video.decode({timestamp:t,bitmap:n}),this.currentChunk&&this.currentChunk.kind===`video`&&this.currentChunk.nalus&&this.on.nalus&&this.on.nalus(this.currentChunk.nalus)}catch{e.close()}},error:e=>{this.on.video.error&&this.on.video.error(e)}}),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,t=this.baseTime+performance.now();if(this.lastRenderTime||=t,this.fps=Math.round(1e3/(t-this.lastRenderTime)),this.lastRenderTime=t,this.nextRenderTime){let t=this.lastRenderTime-this.nextRenderTime;e-=t}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(),this.currentChunk;){let e=this.pendingChunks.length;if(this.frameTrack){let[t,n]=this.fameTrackOption[this.pattern];if(e<=t&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){let n=Math.min(1+(e-t)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(n.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){let{decodingSpeed:t,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:t,decodingSpeedRatio:n,fps:r,cacheLength:e})}let{kind:t,init:n}=this.currentChunk;switch(t){case`audio`:this.decodeAudio(n);break;case`video`:this.decodeVideo(n);break}if(t===`video`)break}this.isProcessing=!1}};decodeAudio=e=>{if(!this.audioDecoder)return;let t=new EncodedAudioChunk(e);this.audioDecoder.decode(t)};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)){let t=new EncodedVideoChunk(e);this.videoDecoder.decode(t)}};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}}},N=class{renderMap=new Map;constructor(){}push=async e=>{let{timestamp:t}=e,{bitmap:n}=e;try{let e=[...this.renderMap.keys()];for(let r of e){let e=this.renderMap.get(r);if(!e)continue;let{pause:i=!1,writer:a,offscreen:o,option:s}=e;if(i===!0)continue;let c=async e=>{if(a){let n=new VideoFrame(e,{timestamp:t});try{await a.write(n)}catch{}n.close()}else o&&(o.width=e.width,o.height=e.height,o?.getContext(`2d`)?.drawImage(e,0,0))};if(r===`default`)await c(n);else if(s){let{sx:e=0,sy:t=0,sw:r=n.width,sh:i=n.height}=s;await c(await createImageBitmap(n,e,t,r,i))}}}catch{}n.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,option:i}={key:`default`,...e};if(n){let e=n.getWriter();this.renderMap.set(t,{writer:e,option:i,pause:!1})}else this.renderMap.set(t,{offscreen:r,option:i,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{let{key:t,cutOption:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,option:n})};setPause=e=>{let{key:t,pause:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,pause:n})};destroy=()=>{this.renderMap=new Map}};e.Decoder=M,e.DecoderWorker=c,e.Demuxer=j,e.DemuxerWorker=i,e.PrPlayer=T,e.Render=N,e.RenderWorker=f});
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`pr-player`]={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t="(function(){var e=class{pendingPayloads=[];payload=new Uint8Array;chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);let t=this.pendingPayloads.shift();if(!t)return!1;let n=new Uint8Array(this.payload.byteLength+t.byteLength);return n.set(this.payload,0),n.set(t,this.payload.byteLength),this.payload=n,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array,this.chunks=[]}};let t=(e,t)=>{let n=new Uint8Array(e),r=new Uint8Array(t),i=new Uint8Array(11+n.length+r.length),a=0;return i[a++]=1,i[a++]=n[1],i[a++]=n[2],i[a++]=n[3],i[a++]=255,i[a++]=225,i[a++]=n.length>>8&255,i[a++]=n.length&255,i.set(n,a),a+=n.length,i[a++]=1,i[a++]=r.length>>8&255,i[a++]=r.length&255,i.set(r,a),i},n=e=>{let t=0,n=new DataView(e.buffer),r=n.getUint8(t);if(t+=1,r!==1)throw Error(`Invalid AVC version`);let i=n.getUint8(t)&255;t+=1;let a=n.getUint8(t)&255;t+=1;let o=n.getUint8(t)&255;t+=1;let s=`avc1.${Array.from([i,a,o],e=>e.toString(16).padStart(2,`0`)).join(``)}`,c=(n.getUint8(t)&3)-1;t+=1;let l=n.getUint8(t)&31;t+=1;let u=n.getUint16(t,!1);t+=2;let d=new Uint8Array(n.buffer.slice(t,t+u));t+=u;let f=n.getUint8(t)&31;t+=1;let p=n.getUint16(t,!1);t+=2;let m=new Uint8Array(n.buffer.slice(t,t+p));return t+=p,{version:r,codec:s,profile:i,compatibility:a,level:o,lengthSizeMinusOne:c,numOfSequenceParameterSets:l,sequenceParameterSetLength:u,sps:d,numOfPictureParameterSets:f,pictureParameterSetLength:p,pps:m}},r=e=>{let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t},i=e=>{let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e){let e=t;n.set(e,r),r+=e.length}return n},a=e=>{let t=`unknown`;switch(e){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};var o=class{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let t=0;for(;!(t+188>e.byteLength);){if(e.getInt8(t)!=71){t++;continue}await this.parsePacket(e,t),t+=188}return t};parsePacket=async(e,t)=>{if(t+188>e.byteLength||e.getUint8(t)!==71)throw Error(`Invalid TS packet`);let n=t,r=this.parseHeader(e,n);n+=4;let{transport_error_indicator:i,pid:a,payload_unit_start_indicator:o,adaptation_field_control:s}=r;if(i===1||a===void 0)return;let c=184;if(s===2||s===3){let t=e.getUint8(n);n+=1,this.parseAdaptationField(e,n),n+=t,c-=t}if(s===3&&--c,s===1||s===3){let t=new Uint8Array(e.buffer.slice(n,n+c));if(a===0)return this.parsePAT(e,n);{let{programs:t=[]}=this.pat||{};if(t.find(e=>e.pmt_pid===a))return this.parsePMT(e,n)}let{streams:r=[]}=this.pmt||{},i=r.find(e=>e.elementary_pid===a);if(i){if(o===1){let e=this.payloadMap.get(a);if(e){switch(i.kind){case`audio`:{let t=await this.parseAudio(e);this.on.chunk&&this.on.chunk(t)}break;case`video`:{let t=await this.parseVideo(e);this.on.chunk&&this.on.chunk(t),await new Promise(e=>setTimeout(()=>e(!0),0))}break}this.payloadMap.delete(a)}}{this.payloadMap.has(a)||this.payloadMap.set(a,new Uint8Array);let e=this.payloadMap.get(a),n=new Uint8Array(e.byteLength+t.byteLength);n.set(e,0),n.set(t,e.byteLength),this.payloadMap.set(a,n)}}}};parseHeader=(e,t)=>{let n=t,r=e.getUint8(n),i=e.getUint8(n+1),a=e.getUint8(n+2),o=e.getUint8(n+3),s=(i&128)>>7;return s===1?{sync_byte:r,transport_error_indicator:s}:{sync_byte:r,transport_error_indicator:s,payload_unit_start_indicator:(i&64)>>6,transport_priority:(i&32)>>5,pid:(i&31)<<8|a,transport_scrambling_control:(o&192)>>6,adaptation_field_control:o>>4&3,continuity_counter:o&15}};parsePAT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==0)throw Error(`Invalid PAT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u}}let i=[];{let t=r.section_length-5-4,a=n+t;for(;n<a;){let t=e.getUint16(n),r=e.getUint16(n+2)&8191;n+=4,t!==0&&r>=32&&r<=8190&&i.push({program_number:t,pmt_pid:r})}}let a=e.getUint32(n);this.pat={header:r,programs:i,crc32:a},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==2)throw Error(`Invalid PMT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1;let d=e.getUint16(n)&8191;n+=2;let f=e.getUint16(n)&4095;n+=2,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u,pcr_pid:d,program_info_length:f}}let i=[];{let t=r.section_length-9-4,o=n+t;for(;n<o;){let t=e.getUint8(n),r=a(t),o=e.getUint16(n+1)&8191,s=e.getUint16(n+3)&4095;if(n+=5,o<32||o>8190){console.warn(`Invalid elementary_pid: 0x${o.toString(16)}`);continue}i.push({kind:r,stream_type:t,elementary_pid:o,es_info_length:s})}}let o=e.getUint32(n);this.pmt={header:r,streams:i,crc32:o},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(e,t)=>{let n=t,r,i,a,o,s=e.getUint8(n),c=!!(s&128),l=!!(s&64),u=!!(s&32),d=!!(s&16),f=!!(s&8),p=!!(s&4),m=!!(s&2),h=!!(s&1);n+=1;let g=(e,t)=>{let n=BigInt(0);n|=BigInt(e.getUint16(t))<<25n,n|=BigInt(e.getUint16(t+1))<<17n,n|=BigInt(e.getUint16(t+2))<<9n,n|=BigInt(e.getUint16(t+3))<<1n,n|=BigInt(e.getUint16(t+4)>>7);let r=(e.getUint16(t+4)&1)<<8|e.getUint16(t+5);return n=n*300n+BigInt(r),n};if(d&&(r=g(e,n),n+=6),f&&(i=g(e,n),n+=6),p&&(a=e.getInt8(n),n+=1),m){let t=e.getUint8(n);n+=1,o=new Uint8Array(e.buffer,n,t),n+=t}return{discontinuity_indicator:c,random_access_indicator:l,elementary_stream_priority_indicator:u,pcr_flag:d,opcr_flag:f,splicing_point_flag:p,transport_private_data_flag:m,adaptation_field_extension_flag:h,pcr:r,opcr:i,splice_countdown:a,transport_private_data:o}};parseAudio=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts audio payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{if(!this.audioConfig&&t.getUint8(n)===255){let e=t.getUint8(n+2),r=t.getUint8(n+3),i,a;a=e>>2&15,i=(e&1)<<2|r>>6,this.audioConfig={kind:`audio`,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],numberOfChannels:i},this.on.config&&this.on.config(this.audioConfig)}let{dts:e=0,pts:a=0}=r;return{kind:`audio`,type:`key`,dts:e,pts:a,cts:a-e,data:i.slice(7)}}};parseVideo=async e=>{let r=new DataView(e.buffer),a=0,o,s;{let e=r.getUint8(a)===0&&r.getUint8(a+1)===0&&r.getUint8(a+2)===1;if(a+=3,!e)throw Error(`invalid ts video payload.`);let t=r.getUint8(a);a+=1;let n=r.getUint8(a)<<8|r.getUint8(a+1);a+=2;let i,s,c,l,u;{let e=r.getUint8(a);a+=1,i=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=r.getUint8(a);a+=1;let t=e>>6,n=r.getUint8(a);a+=1,(t&2)==2&&(d=this.parsePtsDts(r,a)),f=(t&1)==1?this.parsePtsDts(r,a+5):d,a+=n}o={stream_id:t,pes_packet_length:n,scrambling_control:i,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}s=e.slice(a);{let e=this.getNalus(s);if(!this.videoConfig){let r,i;if(r=e.find(e=>e.type===7)?.nalu.slice(4),i=e.find(e=>e.type===8)?.nalu.slice(4),r&&i){let e=t(r,i),{codec:a}=n(e);this.videoConfig={kind:`video`,codec:a,description:e,sps:r,pps:i},this.on.config&&this.on.config(this.videoConfig)}}let r=[],a=`delta`;for(let t of e){let{type:e,nalu:n}=t;switch(e){case 6:case 9:r.push(n);break;case 1:a=`delta`,r.push(n);break;case 5:a=`key`,r.push(n);break}}let c=i(r),{dts:l=0,pts:u=0}=o,d=u-l;return{kind:`video`,type:a,dts:l,pts:u,cts:d,data:c,nalus:r}}};parsePtsDts(e,t){let n=e.getUint8(t),r=e.getUint8(t+1),i=e.getUint8(t+2),a=e.getUint8(t+3),o=e.getUint8(t+4),s=(BigInt(n)&14n)<<29n|(BigInt(r)&255n)<<22n|(BigInt(i)&254n)<<14n|(BigInt(a)&255n)<<7n|(BigInt(o)&254n)>>1n;return Number(s)/90}getNalus=e=>{let t=[],n=0;for(;!(n+4>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}n+=3;let i=n,a=e[n]&31;for(n+=1;!(n+1>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}break}let o=n-i;if(e[n-1]===0&&--o,o!==0){let n=r(e.slice(i,i+o));t.push({type:a,nalu:n})}}return t}};let s=(e,t)=>e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2);var c=class{audioConfig;videoConfig;header;textDecoder=new TextDecoder(`utf-8`);on={};constructor(){}parse=async e=>{let t=0;for(this.header||(this.parseHeader(e,t),t+=9);this.isSurplusTag(e,t)!==!1;){let{tagType:n,dataSize:r,timestamp:i}=this.parseTagHeader(e,t+4);if(n){let a=this.parseTagBody(n,e,t+4+11,r);switch(n){case`script`:this.on.info&&this.on.info(a);break;case`audio`:{let{accPacketType:e}=a;if(e===0){let{codec:e,sampleRate:t,channelConfiguration:n}=a;this.audioConfig={kind:`audio`,codec:e,sampleRate:t,numberOfChannels:n},this.on.config&&this.on.config(this.audioConfig)}else{let{cts:e,data:t}=a,n=e===void 0?void 0:e+i;this.on.chunk&&this.on.chunk({kind:`audio`,type:`key`,dts:i,pts:n,cts:e,data:t})}}break;case`video`:{let{avcPacketType:e}=a;if(e===0){let{codec:e,sps:t,pps:n,data:r}=a;this.videoConfig={kind:`video`,codec:e,description:r,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}else{let{frameType:e,cts:t,data:n,nalus:r}=a,o=e===1?`key`:`delta`,s=t===void 0?void 0:t+i;this.on.chunk&&this.on.chunk({kind:`video`,type:o,dts:i,pts:s,cts:t,data:n,nalus:r})}}break}t=t+4+11+r}await new Promise(e=>setTimeout(()=>e(!0),8))}return t};parseHeader=(e,t)=>{let n,r,i,a;n=e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),r=e.getUint8(3);{let[,,t,,n]=e.getUint8(0).toString(2).padStart(5,`0`).split(``);i={audio:n===`1`,video:t===`1`}}a=e.getUint32(5),this.header={signature:n,version:r,flags:i,dataOffset:a}};isSurplusTag=(e,t)=>{let n=!0,r=e.byteLength;if(t+4>r)n=!1;else if(t+4+11>r)n=!1;else{let i=s(e,t+4+1);t+4+11+i>r&&(n=!1)}return n};parseTagHeader=(e,t)=>{let n,r,i,a,o;{let r=e.getUint8(t),i;switch(r){case 18:i=`script`;break;case 8:i=`audio`;break;case 9:i=`video`;break}n=i}return r=s(e,t+1),i=s(e,t+4),a=e.getUint8(t+7),o=s(e,t+8),{tagType:n,dataSize:r,timestamp:i,timestampExtended:a,streamID:o}};parseTagBody=(e,t,n,r)=>{let i;switch(e){case`script`:i=this.parseMetaData(t,n);break;case`audio`:i=this.parseAudio(t,n,r);break;case`video`:i=this.parseVideo(t,n,r);break}return i};parseMetaData=(e,t)=>{let n=t;if(e.getUint8(n)!==2)throw Error(`Invalid AMF type for onMetaData (expected 0x02)`);n+=1;let r=e.getUint16(n,!1);n+=2;{let t=new Int8Array(e.buffer.slice(n,n+r));if((this.textDecoder?.decode(t)||``)!==`onMetaData`)throw Error(`Expected 'onMetaData' string`);n+=r}let i=this.getAmfType(e,n);return n+=1,this.getAMFValue(e,n,i).value};parseAudio=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i>>2&3,s=i>>1&1,c=i&1;r+=1;let l=e.getUint8(r);r+=1;let u=n,d=new Uint8Array(e.buffer.slice(r,r+u));if(a===10&&l===0){let t=e.getUint8(r),n=e.getUint8(r+1),i=t>>3&31,u=(t&7)<<1|n>>7;return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d,samplingFrequencyIndex:u,channelConfiguration:n>>3&15,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][u]}}return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d}};parseVideo=(e,t,r)=>{let i=t,a=e.getUint8(i),o=a>>4&15,c=a&15;i+=1;let l=e.getUint8(i);i+=1;let u=s(e,i);i+=3;let d=r-5,f=new Uint8Array(e.buffer.slice(i,i+d));switch(c){case 7:if(l===0)return{frameType:o,codecID:c,avcPacketType:l,cts:u,data:f,...n(f)};if(l===1){let t=[],n=i+r-5;for(;!(i+4>n);){let n=e.getUint32(i,!1),r=new Uint8Array(e.buffer.slice(i,i+4+n));i+=4+n,t.push(r)}return{frameType:o,codecID:c,avcPacketType:l,cts:u,data:f,nalus:t}}break;default:throw Error(`Unsupported codecID`)}return{frameType:o,codecID:c,avcPacketType:l,cts:u,data:f}};getAmfType=(e,t)=>e.getUint8(t);getAMFName=(e,t,n)=>{let r=new Uint8Array(e.buffer.slice(t,t+n));return this.textDecoder?.decode(r)||``};getAMFValue=(e,t,n)=>{let r=t,i,a=0;switch(n){case 0:i=e.getFloat64(r,!1),a=8;break;case 1:i=!!e.getUint8(r),a=1;break;case 2:{i=``;let t=e.getUint16(r,!1);r+=2;let n=new Int8Array(e.buffer,r,t).filter(e=>e!==0);i=(this.textDecoder?.decode(n)||``).trim(),a=2+t}break;case 3:for(i={};r<e.byteLength;){let t=e.getUint16(r,!1);if(t===0)break;r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);if(o===6)break;r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}break;case 8:{i={};let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=e.getUint16(r,!1);r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}}break;case 10:{i=[];let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=this.getAmfType(e,r);r+=1;let n=this.getAMFValue(e,r,t);r+=n.length,i.push(n.value),a=1+n.length}}break}return{amfType:n,length:a,value:i}}};let l=new class{pattern;cacher=new e;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case`flv`:this.parser=new c;break;case`hls`:this.parser=new o;break;default:throw Error(`is error pattern.`)}this.parser.on.debug=e=>this.on.debug&&this.on.debug(e),this.parser.on.info=e=>this.on.info&&this.on.info(e),this.parser.on.config=e=>this.on.config&&this.on.config(e),this.parser.on.chunk=e=>{this.cacher.pushChunk(e),this.on.chunk&&this.on.chunk(e)}};push=e=>{this.cacher.push(e),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 Error(`You need to set the pattern.`);if(!this.parser)throw Error(`You need to init parser.`);for(;;){let e=this.cacher.next(this.offset);if(this.offset=0,!e)break;this.offset=await this.parser.parse(e)}this.isParseing=!1}catch{this.destroy()}}};l.on.info=e=>postMessage({action:`on.info`,data:e}),l.on.config=e=>postMessage({action:`on.config`,data:e}),l.on.chunk=e=>postMessage({action:`on.chunk`,data:e}),l.on.debug=e=>postMessage({action:`on.debug`,data:e}),onmessage=e=>{let{action:t,data:n}=e.data,r=l[t];r&&r(n)}})();",n=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,t],{type:`text/javascript;charset=utf-8`});function r(e){let r;try{if(r=n&&(self.URL||self.webkitURL).createObjectURL(n),!r)throw``;let t=new Worker(r,{name:e?.name});return t.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(r)}),t}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(t),{name:e?.name})}}var i=class{worker=new r;on={};constructor(){this.worker.onmessage=e=>{let{action:t,data:n}=e.data;switch(t){case`on.info`:this.on.info&&this.on.info(n);break;case`on.config`:this.on.config&&this.on.config(n);break;case`on.chunk`:this.on.chunk&&this.on.chunk(n);break;case`on.debug`:this.on.debug&&this.on.debug(n);break}}}init=e=>this.worker.postMessage({action:`init`,data:e});push=e=>this.worker.postMessage({action:`push`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`,data:{}}),this.worker.terminate()}},a="(function(){let e=new class{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:e=>{let t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:e,playbackRate:t})},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:async e=>{this.frameStartTime||=e.timestamp;try{let t=e.timestamp-this.frameStartTime+this.baseTime*1e3,n=await createImageBitmap(e);if(e.close(),!n.width||!n.height)return n.close();this.on.video.decode&&this.on.video.decode({timestamp:t,bitmap:n}),this.currentChunk&&this.currentChunk.kind===`video`&&this.currentChunk.nalus&&this.on.nalus&&this.on.nalus(this.currentChunk.nalus)}catch{e.close()}},error:e=>{this.on.video.error&&this.on.video.error(e)}}),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,t=this.baseTime+performance.now();if(this.lastRenderTime||=t,this.fps=Math.round(1e3/(t-this.lastRenderTime)),this.lastRenderTime=t,this.nextRenderTime){let t=this.lastRenderTime-this.nextRenderTime;e-=t}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(),this.currentChunk;){let e=this.pendingChunks.length;if(this.frameTrack){let[t,n]=this.fameTrackOption[this.pattern];if(e<=t&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){let n=Math.min(1+(e-t)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(n.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){let{decodingSpeed:t,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:t,decodingSpeedRatio:n,fps:r,cacheLength:e})}let{kind:t,init:n}=this.currentChunk;switch(t){case`audio`:this.decodeAudio(n);break;case`video`:this.decodeVideo(n);break}if(t===`video`)break}this.isProcessing=!1}};decodeAudio=e=>{if(!this.audioDecoder)return;let t=new EncodedAudioChunk(e);this.audioDecoder.decode(t)};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)){let t=new EncodedVideoChunk(e);this.videoDecoder.decode(t)}};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}}};e.on.audio.decode=e=>postMessage({action:`on.audio.decode`,data:e},[e.audioData]),e.on.audio.error=e=>postMessage({action:`on.audio.error`,data:e}),e.on.video.decode=e=>postMessage({action:`on.video.decode`,data:e},[e.bitmap]),e.on.video.error=e=>postMessage({action:`on.video.error`,data:e}),e.on.nalus=e=>postMessage({action:`on.nalus`,data:e}),e.on.analysis=e=>postMessage({action:`on.analysis`,data:e}),onmessage=t=>{let{action:n,data:r}=t.data,i=e[n];i&&i(r)}})();",o=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,a],{type:`text/javascript;charset=utf-8`});function s(e){let t;try{if(t=o&&(self.URL||self.webkitURL).createObjectURL(o),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(a),{name:e?.name})}}var c=class{worker=new s;on={audio:{},video:{}};constructor(){this.worker.onmessage=e=>{let{action:t,data:n}=e.data;switch(t){case`on.audio.decode`:this.on.audio.decode&&this.on.audio.decode(n);break;case`on.audio.error`:this.on.audio.error&&this.on.audio.error(n);break;case`on.video.decode`:this.on.video.decode&&this.on.video.decode(n);break;case`on.video.error`:this.on.video.error&&this.on.video.error(n);break;case`on.nalus`:this.on.nalus&&this.on.nalus(n);break;case`on.analysis`:this.on.analysis&&this.on.analysis(n);break}}}init=e=>this.worker.postMessage({action:`init`,data:e});initAudio=e=>this.worker.postMessage({action:`initAudio`,data:e});initVideo=e=>this.worker.postMessage({action:`initVideo`,data:e});push=e=>this.worker.postMessage({action:`push`,data:e});setFrameTrack=e=>this.worker.postMessage({action:`setFrameTrack`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`}),this.worker.terminate()}},l="(function(){let e=new class{renderMap=new Map;constructor(){}push=async e=>{let{timestamp:t}=e,{bitmap:n}=e;try{let e=[...this.renderMap.keys()];for(let r of e){let e=this.renderMap.get(r);if(!e)continue;let{pause:i=!1,writer:a,offscreen:o,option:s}=e;if(i===!0)continue;let c=async e=>{if(a){let n=new VideoFrame(e,{timestamp:t});try{await a.write(n)}catch{}n.close()}else o&&(o.width=e.width,o.height=e.height,o?.getContext(`2d`)?.drawImage(e,0,0))};if(r===`default`)await c(n);else if(s){let{sx:e=0,sy:t=0,sw:r=n.width,sh:i=n.height}=s;await c(await createImageBitmap(n,e,t,r,i))}}}catch{}n.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,option:i}={key:`default`,...e};if(n){let e=n.getWriter();this.renderMap.set(t,{writer:e,option:i,pause:!1})}else this.renderMap.set(t,{offscreen:r,option:i,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{let{key:t,cutOption:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,option:n})};setPause=e=>{let{key:t,pause:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,pause:n})};destroy=()=>{this.renderMap=new Map}};onmessage=t=>{let{action:n,data:r}=t.data,i=e[n];i&&i(r)}})();",u=typeof self<`u`&&self.Blob&&new Blob([`(self.URL || self.webkitURL).revokeObjectURL(self.location.href);`,l],{type:`text/javascript;charset=utf-8`});function d(e){let t;try{if(t=u&&(self.URL||self.webkitURL).createObjectURL(u),!t)throw``;let n=new Worker(t,{name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(l),{name:e?.name})}}var f=class{worker=new d;constructor(){}push=e=>this.worker.postMessage({action:`push`,data:e},[e.bitmap]);addCut=e=>{let t=[];e.writable&&t.push(e.writable),e.offscreen&&t.push(e.offscreen),this.worker.postMessage({action:`addCut`,data:e},t)};delCut=e=>this.worker.postMessage({action:`delCut`,data:e});setCut=e=>this.worker.postMessage({action:`setCut`,data:e});setPause=e=>this.worker.postMessage({action:`setPause`,data:e});destroy=()=>{this.worker.postMessage({action:`destroy`,data:{}}),this.worker.terminate()}},p=`data:text/javascript;base64,LyoqDQogKiDpnZnpn7Pml7bvvJrlnKjpopHln5/ku4Xkv53nlZkgYmluIDDvvZ4077yI6ZqP5py677yJ77yM5YW25L2Z5Li6IDDvvIzlho3lkIjmiJDml7bln5/lhpnlhaXovpPlh7og4oCUIOWNs+S/ruaUueecn+WuniBQQ03vvIznu48gQW5hbHlzZXIoZmZ0U2l6ZT01MTIpIOaXtuWJjSA1IOS4qiBiaW4g5pyJ6IO96YeP44CB5YW25L2Z5o6l6L+RIDDjgIINCiAqIFBFUklPRCDpobvkuI4gUHJBdWRpb1N0cmVhbSDkuK0gYW5hbHlzZXJOb2RlLmZmdFNpemUg5LiA6Ie044CCDQogKi8NCmNsYXNzIG5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3NvciBleHRlbmRzIEF1ZGlvV29ya2xldFByb2Nlc3NvciB7DQogIGlzRGVzdHJveSA9IGZhbHNlDQogIGRlYnVnID0gZmFsc2UNCg0KICBzdGF0aWMgU0lMRU5DRV9FUFMgPSAxZS0xNQ0KDQogIC8qKiDkuI4gc3JjL1ByQXVkaW9TdHJlYW0udHMg6YeMIGFuYWx5c2VyTm9kZS5mZnRTaXplIOS/neaMgeS4gOiHtCAqLw0KICBzdGF0aWMgUEVSSU9EID0gNTEyDQoNCiAgLyoqIGJpbiAw772eNCDpmo/mnLrlpI3mlbDvvIjlrp7pg6gv6Jma6YOo77yJ55qE5aSn6Ie05bmF5bqm5bC65bqm77yM5Y+v5oyJ5ZCs5oSfL+e8lueggeWGjeiwgyAqLw0KICBzdGF0aWMgQklOX1NDQUxFID0gMC4wMg0KDQogIGNvbnN0cnVjdG9yKCkgew0KICAgIHN1cGVyKCkNCiAgICB0aGlzLl9zaWxlbnRQY20gPSBuZXcgRmxvYXQzMkFycmF5KG5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5QRVJJT0QpDQogICAgdGhpcy5fc2lsZW50T2ZmID0gbm90RW1wdHlGaWx0ZXJXb3JrbGV0UHJvY2Vzc29yLlBFUklPRA0KICB9DQoNCiAgc3RhdGljIGFsbElucHV0c1NpbGVudChpbnB1dHMpIHsNCiAgICBjb25zdCBlcHMgPSBub3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuU0lMRU5DRV9FUFMNCiAgICBmb3IgKGxldCBuaSA9IDA7IG5pIDwgaW5wdXRzLmxlbmd0aDsgbmkrKykgew0KICAgICAgY29uc3QgaW5wdXQgPSBpbnB1dHNbbmldDQogICAgICBpZiAoIWlucHV0KSBjb250aW51ZQ0KICAgICAgZm9yIChsZXQgY2ggPSAwOyBjaCA8IGlucHV0Lmxlbmd0aDsgY2grKykgew0KICAgICAgICBjb25zdCBjaGFubmVsID0gaW5wdXRbY2hdDQogICAgICAgIGlmICghY2hhbm5lbCkgY29udGludWUNCiAgICAgICAgY29uc3QgbiA9IGNoYW5uZWwubGVuZ3RoDQogICAgICAgIGZvciAobGV0IGkgPSAwOyBpIDwgbjsgaSsrKSB7DQogICAgICAgICAgaWYgKE1hdGguYWJzKGNoYW5uZWxbaV0pID49IGVwcykgcmV0dXJuIGZhbHNlDQogICAgICAgIH0NCiAgICAgIH0NCiAgICB9DQogICAgcmV0dXJuIHRydWUNCiAgfQ0KDQogIC8qKg0KICAgKiDku4UgYmluIDAuLjQg6Z2e6Zu277yI6ZqP5py677yJ77yM5ruh6Laz5a6e5L+h5Y+3IElERlTvvIzlhpnlhaUgdGhpcy5fc2lsZW50UGNtDQogICAqLw0KICByZWZpbGxTaWxlbnRQY21Gcm9tRml2ZUJpbnMoKSB7DQogICAgY29uc3QgTiA9IG5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5QRVJJT0QNCiAgICBjb25zdCBzY2FsZSA9IG5vdEVtcHR5RmlsdGVyV29ya2xldFByb2Nlc3Nvci5CSU5fU0NBTEUNCiAgICBjb25zdCByZSA9IG5ldyBGbG9hdDY0QXJyYXkoNSkNCiAgICBjb25zdCBpbSA9IG5ldyBGbG9hdDY0QXJyYXkoNSkNCiAgICByZVswXSA9IChNYXRoLnJhbmRvbSgpICogMiAtIDEpICogc2NhbGUNCiAgICBpbVswXSA9IDANCiAgICBmb3IgKGxldCBrID0gMTsgayA8PSA0OyBrKyspIHsNCiAgICAgIHJlW2tdID0gKE1hdGgucmFuZG9tKCkgKiAyIC0gMSkgKiBzY2FsZQ0KICAgICAgaW1ba10gPSAoTWF0aC5yYW5kb20oKSAqIDIgLSAxKSAqIHNjYWxlDQogICAgfQ0KICAgIGNvbnN0IGludk4gPSAxIC8gTg0KICAgIGNvbnN0IHR3b1BpT3Zlck4gPSAoMiAqIE1hdGguUEkpIC8gTg0KICAgIGZvciAobGV0IG4gPSAwOyBuIDwgTjsgbisrKSB7DQogICAgICBsZXQgcyA9IHJlWzBdDQogICAgICBmb3IgKGxldCBrID0gMTsgayA8PSA0OyBrKyspIHsNCiAgICAgICAgY29uc3QgYW5nID0gdHdvUGlPdmVyTiAqIGsgKiBuDQogICAgICAgIHMgKz0gMiAqIChyZVtrXSAqIE1hdGguY29zKGFuZykgLSBpbVtrXSAqIE1hdGguc2luKGFuZykpDQogICAgICB9DQogICAgICB0aGlzLl9zaWxlbnRQY21bbl0gPSBzICogaW52Tg0KICAgIH0NCiAgICB0aGlzLl9zaWxlbnRPZmYgPSAwDQogIH0NCg0KICBmaWxsT3V0cHV0c1NwYXJzZUZpdmVCaW5zKG91dHB1dHMpIHsNCiAgICBjb25zdCBmaXJzdCA9IG91dHB1dHNbMF0NCiAgICBpZiAoIWZpcnN0IHx8ICFmaXJzdFswXSkgcmV0dXJuDQogICAgY29uc3QgZnJhbWVMZW4gPSBmaXJzdFswXS5sZW5ndGgNCg0KICAgIGZvciAobGV0IGkgPSAwOyBpIDwgZnJhbWVMZW47IGkrKykgew0KICAgICAgaWYgKHRoaXMuX3NpbGVudE9mZiA+PSBub3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuUEVSSU9EKSB7DQogICAgICAgIHRoaXMucmVmaWxsU2lsZW50UGNtRnJvbUZpdmVCaW5zKCkNCiAgICAgIH0NCiAgICAgIGNvbnN0IHYgPSB0aGlzLl9zaWxlbnRQY21bdGhpcy5fc2lsZW50T2ZmKytdDQogICAgICBmb3IgKGxldCBubyA9IDA7IG5vIDwgb3V0cHV0cy5sZW5ndGg7IG5vKyspIHsNCiAgICAgICAgY29uc3Qgb3V0UG9ydHMgPSBvdXRwdXRzW25vXQ0KICAgICAgICBpZiAoIW91dFBvcnRzKSBjb250aW51ZQ0KICAgICAgICBmb3IgKGxldCBjaCA9IDA7IGNoIDwgb3V0UG9ydHMubGVuZ3RoOyBjaCsrKSB7DQogICAgICAgICAgY29uc3QgY2hhbm5lbCA9IG91dFBvcnRzW2NoXQ0KICAgICAgICAgIGlmIChjaGFubmVsKSBjaGFubmVsW2ldID0gdg0KICAgICAgICB9DQogICAgICB9DQogICAgfQ0KICB9DQoNCiAgc3RhdGljIGNvcHlJbnB1dHNUb091dHB1dHMoaW5wdXRzLCBvdXRwdXRzKSB7DQogICAgZm9yIChsZXQgbm8gPSAwOyBubyA8IG91dHB1dHMubGVuZ3RoOyBubysrKSB7DQogICAgICBjb25zdCBvdXRQb3J0cyA9IG91dHB1dHNbbm9dDQogICAgICBjb25zdCBpblBvcnRzID0gaW5wdXRzW25vXQ0KICAgICAgaWYgKCFvdXRQb3J0cykgY29udGludWUNCiAgICAgIGZvciAobGV0IGNoID0gMDsgY2ggPCBvdXRQb3J0cy5sZW5ndGg7IGNoKyspIHsNCiAgICAgICAgY29uc3Qgb3V0Q2ggPSBvdXRQb3J0c1tjaF0NCiAgICAgICAgaWYgKCFvdXRDaCkgY29udGludWUNCiAgICAgICAgY29uc3QgaW5DaCA9IGluUG9ydHMgJiYgaW5Qb3J0c1tjaF0NCiAgICAgICAgaWYgKGluQ2ggJiYgaW5DaC5sZW5ndGggPT09IG91dENoLmxlbmd0aCkgew0KICAgICAgICAgIG91dENoLnNldChpbkNoKQ0KICAgICAgICB9IGVsc2UgaWYgKGluQ2gpIHsNCiAgICAgICAgICBjb25zdCBuID0gTWF0aC5taW4oaW5DaC5sZW5ndGgsIG91dENoLmxlbmd0aCkNCiAgICAgICAgICBmb3IgKGxldCBpID0gMDsgaSA8IG47IGkrKykgb3V0Q2hbaV0gPSBpbkNoW2ldDQogICAgICAgICAgZm9yIChsZXQgaSA9IG47IGkgPCBvdXRDaC5sZW5ndGg7IGkrKykgb3V0Q2hbaV0gPSAwDQogICAgICAgIH0gZWxzZSB7DQogICAgICAgICAgb3V0Q2guZmlsbCgwKQ0KICAgICAgICB9DQogICAgICB9DQogICAgfQ0KICB9DQoNCiAgcHJvY2VzcyhpbnB1dHMsIG91dHB1dHMpIHsNCiAgICBpZiAodGhpcy5pc0Rlc3Ryb3kpIHJldHVybiBmYWxzZQ0KDQogICAgaWYgKHRoaXMuZGVidWcpIHsNCiAgICAgIGNvbnNvbGUubG9nKCdceDFiWzM4OzI7MDsxNTE7MjU1bSVjJXNceDFiWzBtJywgJ2NvbG9yOiMwMDk3ZmY7JywgJy0tLS0tLS0+QnJlYXRoZTogaW5wdXRzJywgaW5wdXRzKQ0KICAgIH0NCg0KICAgIGlmIChub3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuYWxsSW5wdXRzU2lsZW50KGlucHV0cykpIHsNCiAgICAgIHRoaXMuZmlsbE91dHB1dHNTcGFyc2VGaXZlQmlucyhvdXRwdXRzKQ0KICAgIH0gZWxzZSB7DQogICAgICB0aGlzLl9zaWxlbnRPZmYgPSBub3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuUEVSSU9EDQogICAgICBub3RFbXB0eUZpbHRlcldvcmtsZXRQcm9jZXNzb3IuY29weUlucHV0c1RvT3V0cHV0cyhpbnB1dHMsIG91dHB1dHMpDQogICAgfQ0KDQogICAgcmV0dXJuIHRydWUNCiAgfQ0KDQogIGRlc3Ryb3koKSB7DQogICAgdGhpcy5pc0Rlc3Ryb3kgPSB0cnVlDQogIH0NCn0NCg0KcmVnaXN0ZXJQcm9jZXNzb3IoJ25vdC1lbXB0eS1maWx0ZXItcHJvY2Vzc29yJywgbm90RW1wdHlGaWx0ZXJXb3JrbGV0UHJvY2Vzc29yKQ0K`,m=class{audioContext=new AudioContext;notEmptyFilterWorkletNode;constructor(){}createNotEmptyFilterWorkletNode=async e=>(this.destroy(),this.audioContext=e,await this.audioContext.audioWorklet.addModule(p),this.notEmptyFilterWorkletNode=new AudioWorkletNode(this.audioContext,`not-empty-filter-processor`),this.notEmptyFilterWorkletNode);destroy=()=>{this.notEmptyFilterWorkletNode?.disconnect(),this.notEmptyFilterWorkletNode?.port.postMessage({type:`destroy`}),this.notEmptyFilterWorkletNode=void 0}},h=class{inputStream=new MediaStream;outputStream=new MediaStream;inputGain=1;enhanceGain=1;bgsGain=1;bgmGain=1;outputGain=1;mixAudioMap=new Map;audioContext=new AudioContext;sourceNode;inputGainNode;enhanceGainNode;bgsGainNode;bgmGainNode;rnnoiseNode;analyserNode;analyserArrayData;outputGainNode;destinationNode;denoise=!1;mute=!0;notEmpty=!1;rnnoiseWorklet;rnnoiseWorkletNode;notEmptyFilterWorklet=new m;notEmptyFilterWorkletNode;filterStream=e=>e;constructor(e,t){this.inputStream=e,t&&(this.audioContext=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;{let{sourceNode:e,inputGainNode:t,enhanceGainNode:n,bgsGainNode:r,bgmGainNode:i,analyserNode:a,outputGainNode:o,destinationNode:s}=this;e.connect(t),t.connect(n),n.connect(a),r.connect(a),i.connect(a),n.connect(s),r.connect(s),i.connect(s),o.connect(this.audioContext.destination)}this.audioContext.resume()}use=({rnnoise:e})=>{this.rnnoiseWorklet=new e.RnnoiseWorklet};_changeSource=()=>{this.sourceNode.disconnect(),this.sourceNode=this.audioContext.createMediaStreamSource(this.inputStream),this.sourceNode.connect(this.inputGainNode)};replaceTrack=e=>{let t=this.inputStream.getTracks();for(let e of t)this.inputStream.removeTrack(e);this.inputStream.addTrack(e),this._changeSource()};stop=()=>{{let e=this.inputStream.getTracks();for(let t of e)t.stop(),this.inputStream.removeTrack(t)}};pause=async e=>{let t=this.inputStream.getTracks();for(let n of t)n.enabled=!e};getStream=()=>this.filterStream(this.outputStream);setMute=(e=!0)=>{this.mute=e,this.analyserNode.disconnect(),e===!1&&this.analyserNode.connect(this.outputGainNode)};setDenoise=async(e=!0)=>{this.rnnoiseWorklet&&(this.inputGainNode.disconnect(),e?(this.rnnoiseWorkletNode=await this.rnnoiseWorklet.createRnnoiseWorkletNode(this.audioContext),this.inputGainNode.connect(this.rnnoiseWorkletNode),this.rnnoiseWorkletNode.connect(this.enhanceGainNode)):(this.inputGainNode.connect(this.enhanceGainNode),this.rnnoiseWorklet.destroy()),this.denoise=e)};setNotEmpty=async(e=!0)=>{this.notEmptyFilterWorklet&&(e?(this.notEmptyFilterWorkletNode=await this.notEmptyFilterWorklet.createNotEmptyFilterWorkletNode(this.audioContext),this.notEmptyFilterWorkletNode.connect(this.analyserNode),this.notEmptyFilterWorkletNode.connect(this.destinationNode)):(this.notEmptyFilterWorkletNode?.disconnect(),this.notEmptyFilterWorklet.destroy()),this.notEmpty=e)};setInputGain=e=>{this.inputGain=e,this.inputGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setEnhanceGain=async e=>{this.enhanceGain=e+1,this.enhanceGainNode.gain.setValueAtTime(this.enhanceGain,this.audioContext.currentTime)};setBgsGain=e=>{this.bgsGain=e,this.bgsGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setBgmGain=e=>{this.bgmGain=e,this.bgmGainNode.gain.setValueAtTime(e,this.audioContext.currentTime)};setOutputGain=e=>{this.outputGain=e,this.outputGainNode.gain.setValueAtTime(this.outputGain,this.audioContext.currentTime)};getVolume=()=>{let{analyserNode:e,analyserArrayData:t}=this;e.getByteFrequencyData(t);let n=0;for(let e=0;e<t.length;e++)n+=t[e];return Math.ceil(n/t.length)};mixAudio=(e,t=`bgm`)=>new Promise(async(n,r)=>{try{{let e=this.mixAudioMap.get(t);e&&e.stop()}let r=t===`bgs`?this.bgsGainNode:this.bgmGainNode,i=this.audioContext.createBufferSource();this.mixAudioMap.set(t,i),i.buffer=e,i.connect(r),i.onended=()=>{i.disconnect(r),this.mixAudioMap.delete(t),n(!0)},i.start(0)}catch(e){r(e)}});mixAudioStop=e=>{this.mixAudioMap.get(e)?.stop()};changeMix=(e,t)=>{let n=e===`bgs`?this.bgsGainNode:this.bgmGainNode;t?n.connect(this.destinationNode):n.disconnect(this.destinationNode)}},g=async(e,t)=>{try{let{format:n,numberOfChannels:r,numberOfFrames:i,sampleRate:a}=t,o=e.createBuffer(r,i,a);for(let e=0;e<r;e++){let r=t.allocationSize({planeIndex:e}),a=new Uint8Array(r);t.copyTo(a,{planeIndex:e});let s=new DataView(a.buffer),c=o.getChannelData(e);for(let e=0;e<i;e++){let t;switch(n){case`s16`:case`s16-planar`:t=s.getInt16(e*2,!0)/32768;break;case`f32`:case`f32-planar`:t=s.getFloat32(e*4,!0);break;case`u8`:case`u8-planar`:t=(s.getUint8(e)-128)/128;break;default:throw Error(`Unsupported audio format: ${n}`)}c[e]=Math.max(-1,Math.min(1,t))}}return o}catch(e){throw console.error(`Failed to convert AudioData to AudioBuffer:`,e),e}},_=class{prAudioStream;audioContext;destination;stream=new MediaStream;nextStartTime=0;pendingSources=[];constructor(){}init=e=>{e||=new(window.AudioContext||window.webkitAudioContext),this.audioContext=e,this.destination=this.audioContext.createMediaStreamDestination(),this.stream=new MediaStream,this.stream.addTrack(this.destination.stream.getAudioTracks()[0]),this.prAudioStream=new h(this.stream,this.audioContext),this.nextStartTime=0,this.pendingSources=[]};async push(e){let{audioData:t,playbackRate:n=1}=e;if(!this.audioContext||!this.destination)return;let r=await g(this.audioContext,t);if(t.close(),!r)return;let i=this.audioContext.createBufferSource();i.buffer=r,i.playbackRate.value=n;let a=-1200*Math.log2(n);i.detune.value=a,i.connect(this.destination);let o=Math.max(this.nextStartTime,this.audioContext.currentTime);this.nextStartTime=o+r.duration/n,i.start(o),this.pendingSources.push(i),i.onended=()=>{this.pendingSources=this.pendingSources.filter(e=>e!==i)},this.audioContext.state===`suspended`&&await this.audioContext.resume()}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(e=>e.stop()),this.pendingSources=[]}},v=e=>{let t=e.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`},y=e=>{let t=e?.getTracks()||[];for(let e of t)e.stop()},b=class{resolvesMap=new Map;index=0;constructor(){}add=(e,t=()=>!1,n=0)=>new Promise(r=>{if(t())return r(!0);this.resolvesMap.has(e)||this.resolvesMap.set(e,new Map),this.index++;let i=`${this.index}`;if(n=Math.max(0,n),n===0){this.resolvesMap.get(e)?.set(i,{resolve:r,timer:0});return}let a=window.setTimeout(()=>{this.emit(e)},n);this.resolvesMap.get(e)?.set(i,{resolve:r,timer:a})});emit=async e=>{let t=this.resolvesMap.get(e);if(!t)return;let n=[...t.keys()];for(let e of n){let n=t.get(e);n&&(clearTimeout(n.timer),n.resolve(),t.delete(e))}}},x=(e,t)=>{let n=new Uint8Array(e),r=new Uint8Array(t),i=new Uint8Array(11+n.length+r.length),a=0;return i[a++]=1,i[a++]=n[1],i[a++]=n[2],i[a++]=n[3],i[a++]=255,i[a++]=225,i[a++]=n.length>>8&255,i[a++]=n.length&255,i.set(n,a),a+=n.length,i[a++]=1,i[a++]=r.length>>8&255,i[a++]=r.length&255,i.set(r,a),i},S=e=>{let t=0,n=new DataView(e.buffer),r=n.getUint8(t);if(t+=1,r!==1)throw Error(`Invalid AVC version`);let i=n.getUint8(t)&255;t+=1;let a=n.getUint8(t)&255;t+=1;let o=n.getUint8(t)&255;t+=1;let s=`avc1.${Array.from([i,a,o],e=>e.toString(16).padStart(2,`0`)).join(``)}`,c=(n.getUint8(t)&3)-1;t+=1;let l=n.getUint8(t)&31;t+=1;let u=n.getUint16(t,!1);t+=2;let d=new Uint8Array(n.buffer.slice(t,t+u));t+=u;let f=n.getUint8(t)&31;t+=1;let p=n.getUint16(t,!1);t+=2;let m=new Uint8Array(n.buffer.slice(t,t+p));return t+=p,{version:r,codec:s,profile:i,compatibility:a,level:o,lengthSizeMinusOne:c,numOfSequenceParameterSets:l,sequenceParameterSetLength:u,sps:d,numOfPictureParameterSets:f,pictureParameterSetLength:p,pps:m}},C=e=>{let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t},w=e=>{let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e){let e=t;n.set(e,r),r+=e.length}return n},T=e=>{let t=new DataView(e.buffer),n=0,r,i,a;r=t.getUint32(n,!1),n+=4;{let e=t.getUint8(n);i={forbidden_zero_bit:e>>7&1,nal_ref_idc:e>>5&3,nal_unit_type:e&31},n+=1}{let e=r-1;a=new Uint8Array(t.buffer.slice(n,n+e))}return{size:r,header:i,data:a}},E=class{#e={timeout:5*1e3,check:!1};#t=null;constructor(e={}){this.#e={...this.#e,...e}}#n=(e,t)=>new Promise(async n=>{this.#t=new AbortController;let{signal:r}=this.#t,i=this.#e.timeout,a=setTimeout(()=>{this.#t?.abort(`Timeout (${i}ms)`)},i);await fetch(e,{cache:`no-store`,...t,method:`HEAD`,signal:r}).then(e=>{clearTimeout(a),n({status:e.status===200?`successed`:`failed`,reason:e.status===200?``:`HTTP ${e.status}`})}).catch(e=>{if(clearTimeout(a),e.name===`AbortError`){let e=r.reason||`Actively stopped`;n({status:e.includes(`Timeout`)?`timeout`:`stopped`,reason:e})}else n({status:`error`,reason:e.message})})});request=(e,t)=>new Promise(async(n,r)=>{try{this.stop(),this.#e.check&&await this.#n(e),this.#t=new AbortController;let{signal:r}=this.#t;n(await fetch(e,{cache:`no-store`,...t,signal:r}))}catch(e){r(e)}});stop=()=>{if(this.#t?.signal.aborted===!1){let e=Error(`Actively stopped.`);e.name=`AbortError`,this.#t.abort(e)}}},D=class{option={debug:!1,frameTrack:!1};converter=`MediaStreamTrackGenerator`in window?`generator`:`canvas`;prFetch=new E;getSegmentsFetch=new E;prResolves=new b;url=``;start_resolve;demuxerWorker;decoderWorker;audioPlayer;renderWorker;stream;on={demuxer:{},decoder:{}};cutRenders=new Map;trackGenerator;constructor(e={}){let{debug:t=!1}=e;this.option.debug=t}start=async e=>{await this.stop(),this.url=e;let t=v(e);if(t===`unknown`)throw Error(`This address cannot be parsed.`);switch(this.init(t),t){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(),this.demuxerWorker?.destroy(),this.decoderWorker?.destroy(),this.renderWorker?.destroy(),this.cutRenders=new Map,y(this.stream),this.audioPlayer?.destroy()}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: error`,e)}};getStream=()=>this.stream;setPause=e=>{this.renderWorker?.setPause({pause:e})};setMute=e=>this.audioPlayer?.prAudioStream?.setMute(e);setOutputGain=e=>{this.audioPlayer?.prAudioStream?.setOutputGain(e)};setFrameTrack=e=>{this.option.frameTrack=e,this.decoderWorker?.setFrameTrack(e)};isReady=()=>this.prResolves.add(`isReady`,()=>this.stream?.active===!0);cut={create:(e,t)=>{if(this.converter===`generator`){let n=new MediaStreamTrackGenerator({kind:`video`}),r=new MediaStream([n]);return this.renderWorker?.addCut({key:e,writable:n.writable,option:t}),this.cutRenders.set(e,{stream:r}),r}let n=document.createElement(`canvas`),r=n.captureStream(),i=n.transferControlToOffscreen();return this.renderWorker?.addCut({key:e,offscreen:i,option:t}),this.cutRenders.set(e,{stream:r}),r},setCut:(e,t)=>{this.renderWorker?.setCut({key:e,cutOption:t})},getStream:e=>this.cutRenders.get(e)?.stream,remove:e=>{this.renderWorker?.delCut(e),this.cutRenders.delete(e)},setPause:(e,t)=>{this.renderWorker?.setPause({key:e,pause:t})}};init=e=>{this.initRender(),this.initDecoder(e),this.initDemuxer(e),this.audioPlayer=new _,this.audioPlayer.init()};initDemuxer=e=>{this.demuxerWorker=new i,this.demuxerWorker.init(e),this.demuxerWorker.on.debug=e=>{this.option.debug&&this.on.debug&&this.on.debug(e)},this.demuxerWorker.on.info=e=>{this.option.debug&&console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: info`,e),this.on.demuxer.info&&this.on.demuxer.info(e)},this.demuxerWorker.on.config=e=>{this.option.debug&&console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->pr-player: config`,e),this.on.demuxer.config&&this.on.demuxer.config(e);let{kind:t}=e;switch(t){case`audio`:{let{codec:t,sampleRate:n,numberOfChannels:r}=e;this.decoderWorker?.initAudio({codec:t,sampleRate:n,numberOfChannels:r})}break;case`video`:{let{codec:t,description:n}=e;this.decoderWorker?.initVideo({codec:t,description:n})}break}},this.demuxerWorker.on.chunk=e=>{if(this.on.demuxer.chunk&&this.on.demuxer.chunk(e),!this.decoderWorker)return;let{kind:t}=e;switch(t){case`audio`:{let{type:n,dts:r,data:i}=e,a=r*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:a,data:i}})}break;case`video`:{let{type:n,dts:r,data:i,nalus:a=[]}=e,o=r*1e3;this.decoderWorker.push({kind:t,init:{type:n,timestamp:o,data:i},nalus:a})}break}}};initDecoder=e=>{this.decoderWorker=new c,this.decoderWorker.init(e);let{frameTrack:t=!1}=this.option;this.decoderWorker.setFrameTrack(t),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.start_resolve&&=(this.start_resolve(!0),void 0),this.renderWorker?.push(e),this.on.decoder.video&&this.on.decoder.video(e)},this.decoderWorker.on.video.error=e=>{this.on.error&&this.on.error(e)},this.decoderWorker.on.nalus=async e=>{for(let t of e){if(t.byteLength<=4)continue;let{header:e,data:n}=T(t),{nal_unit_type:r}=e;r===6&&this.on.decoder.sei&&this.on.decoder.sei(n)}},this.decoderWorker.on.analysis=e=>{this.on.decoder.analysis&&this.on.decoder.analysis(e)}};initRender=()=>{if(this.renderWorker=new f,this.converter===`generator`){let e=new MediaStreamTrackGenerator({kind:`video`}),t=new MediaStream([e]);this.renderWorker?.addCut({writable:e.writable}),this.stream=t}else{let e=document.createElement(`canvas`),t=e.captureStream(),n=e.transferControlToOffscreen();this.renderWorker?.addCut({offscreen:n}),this.stream=t}this.renderWorker?.setPause({pause:!1})};flv={start:()=>new Promise(async(e,t)=>{try{this.start_resolve=e;let n,r=0;for(;;){r+=1;try{n=await this.prFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(n?.status===200||r===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!n||n.status!==200)return t(`request is error.`);let i=n.body?.getReader();if(!i)return t(`reader is error.`);for(;;){let{done:e,value:t}=await i.read();if(t&&this.demuxerWorker?.push(t),e||this.url===``)break}}catch(e){e.name!==`AbortError`&&t(e)}})};hls={isLive:!1,urls:[],url:``,getSegmentsTimer:0,parse:async e=>{let t=new TextDecoder(`utf-8`).decode(e).split(`
|
|
2
|
+
`).map(e=>e.replace(`\r`,``)),n=this.url.substring(0,this.url.lastIndexOf(`/`)+1),r=4,i=0,a=!1,o=[];for(let e of t)e.startsWith(`#EXTINF:`)?r=parseFloat(e.split(`:`)[1].split(`,`)[0]):e.startsWith(`#EXT-X-TARGETDURATION:`)?i=parseInt(e.split(`:`)[1]):e.startsWith(`#EXT-X-ENDLIST`)?a=!1:e.startsWith(`#EXT-X-MEDIA-SEQUENCE:`)?a=!0:e.includes(`.ts`)&&!e.startsWith(`#`)&&o.push({url:e.startsWith(`http`)?e:n+e,duration:r,isLive:a});return{baseUrl:n,targetDuration:i,isLive:a,segments:o}},getSegments:async()=>{try{let e,t=0;for(;;){t+=1;try{e=await this.getSegmentsFetch.request(this.url)}catch(e){console.log(`\x1B[38;2;0;151;255m%c%s\x1B[0m`,`color:#0097ff;`,`------->Breathe: error`,e)}if(e?.status===200||t===3)break;await new Promise(e=>setTimeout(()=>e(!0),500))}if(!e||e.status!==200)throw Error(`request is error.`);let n=e.body?.getReader();if(!n)throw Error(`reader is error.`);for(;;){let{done:e,value:t}=await n.read();if(t){let{segments:e=[],isLive:n=!1}=await this.hls.parse(t);this.hls.isLive=n,n===!1&&(this.option.frameTrack=!1);let r=Array.from(e,e=>e.url),i=r.findIndex(e=>e===this.hls.url);i!==-1&&(r=r.slice(i+1)),this.hls.urls=r}if(e||this.url===``)break}}catch(e){e.name!==`AbortError`&&this.on.error&&this.on.error(e)}},start:()=>new Promise(async(e,t)=>{try{for(this.start_resolve=e,this.hls.url=``,this.hls.urls=[],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));;){let e=this.hls.urls.shift();if(e){this.hls.url=e;let t=(await this.prFetch.request(e)).body?.getReader();if(!t)throw Error(`segment reader is error.`);for(;;){let{done:e,value:n}=await t.read();if(n&&this.demuxerWorker?.push(n),e||this.url===``)break}}else await new Promise(e=>setTimeout(()=>e(!0),300))}}catch(e){e.name!==`AbortError`&&t(e)}})}},O=class{pendingPayloads=[];payload=new Uint8Array;chunks=[];push=e=>{this.pendingPayloads.push(e)};next=(e=0)=>{this.payload=this.payload.slice(e);let t=this.pendingPayloads.shift();if(!t)return!1;let n=new Uint8Array(this.payload.byteLength+t.byteLength);return n.set(this.payload,0),n.set(t,this.payload.byteLength),this.payload=n,new DataView(this.payload.buffer)};pushChunk=e=>{this.chunks.push(e),this.chunks.length>100&&this.chunks.shift()};destroy=()=>{this.pendingPayloads=[],this.payload=new Uint8Array,this.chunks=[]}},k=e=>{let t=`unknown`;switch(e){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},A=class{pat;pmt;audioConfig;videoConfig;payloadMap=new Map;on={};constructor(){}parse=async e=>{let t=0;for(;!(t+188>e.byteLength);){if(e.getInt8(t)!=71){t++;continue}await this.parsePacket(e,t),t+=188}return t};parsePacket=async(e,t)=>{if(t+188>e.byteLength||e.getUint8(t)!==71)throw Error(`Invalid TS packet`);let n=t,r=this.parseHeader(e,n);n+=4;let{transport_error_indicator:i,pid:a,payload_unit_start_indicator:o,adaptation_field_control:s}=r;if(i===1||a===void 0)return;let c=184;if(s===2||s===3){let t=e.getUint8(n);n+=1,this.parseAdaptationField(e,n),n+=t,c-=t}if(s===3&&--c,s===1||s===3){let t=new Uint8Array(e.buffer.slice(n,n+c));if(a===0)return this.parsePAT(e,n);{let{programs:t=[]}=this.pat||{};if(t.find(e=>e.pmt_pid===a))return this.parsePMT(e,n)}let{streams:r=[]}=this.pmt||{},i=r.find(e=>e.elementary_pid===a);if(i){if(o===1){let e=this.payloadMap.get(a);if(e){switch(i.kind){case`audio`:{let t=await this.parseAudio(e);this.on.chunk&&this.on.chunk(t)}break;case`video`:{let t=await this.parseVideo(e);this.on.chunk&&this.on.chunk(t),await new Promise(e=>setTimeout(()=>e(!0),0))}break}this.payloadMap.delete(a)}}{this.payloadMap.has(a)||this.payloadMap.set(a,new Uint8Array);let e=this.payloadMap.get(a),n=new Uint8Array(e.byteLength+t.byteLength);n.set(e,0),n.set(t,e.byteLength),this.payloadMap.set(a,n)}}}};parseHeader=(e,t)=>{let n=t,r=e.getUint8(n),i=e.getUint8(n+1),a=e.getUint8(n+2),o=e.getUint8(n+3),s=(i&128)>>7;return s===1?{sync_byte:r,transport_error_indicator:s}:{sync_byte:r,transport_error_indicator:s,payload_unit_start_indicator:(i&64)>>6,transport_priority:(i&32)>>5,pid:(i&31)<<8|a,transport_scrambling_control:(o&192)>>6,adaptation_field_control:o>>4&3,continuity_counter:o&15}};parsePAT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==0)throw Error(`Invalid PAT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u}}let i=[];{let t=r.section_length-5-4,a=n+t;for(;n<a;){let t=e.getUint16(n),r=e.getUint16(n+2)&8191;n+=4,t!==0&&r>=32&&r<=8190&&i.push({program_number:t,pmt_pid:r})}}let a=e.getUint32(n);this.pat={header:r,programs:i,crc32:a},this.on.debug&&this.on.debug({pat:this.pat})};parsePMT=(e,t)=>{let n=t,r;{let t=e.getUint8(n);n+=1;let i=e.getUint8(n);if(n+=1,i!==2)throw Error(`Invalid PMT table_id`);let a=e.getUint16(n)&4095;n+=2;let o=e.getUint16(n);n+=2;let s=(e.getUint8(n)&62)>>1,c=e.getUint8(n)&1;n+=1;let l=e.getUint8(n);n+=1;let u=e.getUint8(n);n+=1;let d=e.getUint16(n)&8191;n+=2;let f=e.getUint16(n)&4095;n+=2,r={pointer_field:t,table_id:i,section_length:a,transport_stream_id:o,version_number:s,current_next_indicator:c,section_number:l,last_section_number:u,pcr_pid:d,program_info_length:f}}let i=[];{let t=r.section_length-9-4,a=n+t;for(;n<a;){let t=e.getUint8(n),r=k(t),a=e.getUint16(n+1)&8191,o=e.getUint16(n+3)&4095;if(n+=5,a<32||a>8190){console.warn(`Invalid elementary_pid: 0x${a.toString(16)}`);continue}i.push({kind:r,stream_type:t,elementary_pid:a,es_info_length:o})}}let a=e.getUint32(n);this.pmt={header:r,streams:i,crc32:a},this.on.debug&&this.on.debug({pmt:this.pmt})};parseAdaptationField=(e,t)=>{let n=t,r,i,a,o,s=e.getUint8(n),c=!!(s&128),l=!!(s&64),u=!!(s&32),d=!!(s&16),f=!!(s&8),p=!!(s&4),m=!!(s&2),h=!!(s&1);n+=1;let g=(e,t)=>{let n=BigInt(0);n|=BigInt(e.getUint16(t))<<25n,n|=BigInt(e.getUint16(t+1))<<17n,n|=BigInt(e.getUint16(t+2))<<9n,n|=BigInt(e.getUint16(t+3))<<1n,n|=BigInt(e.getUint16(t+4)>>7);let r=(e.getUint16(t+4)&1)<<8|e.getUint16(t+5);return n=n*300n+BigInt(r),n};if(d&&(r=g(e,n),n+=6),f&&(i=g(e,n),n+=6),p&&(a=e.getInt8(n),n+=1),m){let t=e.getUint8(n);n+=1,o=new Uint8Array(e.buffer,n,t),n+=t}return{discontinuity_indicator:c,random_access_indicator:l,elementary_stream_priority_indicator:u,pcr_flag:d,opcr_flag:f,splicing_point_flag:p,transport_private_data_flag:m,adaptation_field_extension_flag:h,pcr:r,opcr:i,splice_countdown:a,transport_private_data:o}};parseAudio=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts audio payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{if(!this.audioConfig&&t.getUint8(n)===255){let e=t.getUint8(n+2),r=t.getUint8(n+3),i,a;a=e>>2&15,i=(e&1)<<2|r>>6,this.audioConfig={kind:`audio`,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],numberOfChannels:i},this.on.config&&this.on.config(this.audioConfig)}let{dts:e=0,pts:a=0}=r;return{kind:`audio`,type:`key`,dts:e,pts:a,cts:a-e,data:i.slice(7)}}};parseVideo=async e=>{let t=new DataView(e.buffer),n=0,r,i;{let e=t.getUint8(n)===0&&t.getUint8(n+1)===0&&t.getUint8(n+2)===1;if(n+=3,!e)throw Error(`invalid ts video payload.`);let i=t.getUint8(n);n+=1;let a=t.getUint8(n)<<8|t.getUint8(n+1);n+=2;let o,s,c,l,u;{let e=t.getUint8(n);n+=1,o=e>>4&3,s=(e>>3&1)==1,c=(e>>2&1)==1,l=(e>>1&1)==1,u=(e&1)==1}let d,f;{let e=t.getUint8(n);n+=1;let r=e>>6,i=t.getUint8(n);n+=1,(r&2)==2&&(d=this.parsePtsDts(t,n)),f=(r&1)==1?this.parsePtsDts(t,n+5):d,n+=i}r={stream_id:i,pes_packet_length:a,scrambling_control:o,priority:s,data_alignment:c,copyright:l,original_copy:u,pts:d,dts:f}}i=e.slice(n);{let e=this.getNalus(i);if(!this.videoConfig){let t,n;if(t=e.find(e=>e.type===7)?.nalu.slice(4),n=e.find(e=>e.type===8)?.nalu.slice(4),t&&n){let e=x(t,n),{codec:r}=S(e);this.videoConfig={kind:`video`,codec:r,description:e,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}}let t=[],n=`delta`;for(let r of e){let{type:e,nalu:i}=r;switch(e){case 6:case 9:t.push(i);break;case 1:n=`delta`,t.push(i);break;case 5:n=`key`,t.push(i);break}}let a=w(t),{dts:o=0,pts:s=0}=r,c=s-o;return{kind:`video`,type:n,dts:o,pts:s,cts:c,data:a,nalus:t}}};parsePtsDts(e,t){let n=e.getUint8(t),r=e.getUint8(t+1),i=e.getUint8(t+2),a=e.getUint8(t+3),o=e.getUint8(t+4),s=(BigInt(n)&14n)<<29n|(BigInt(r)&255n)<<22n|(BigInt(i)&254n)<<14n|(BigInt(a)&255n)<<7n|(BigInt(o)&254n)>>1n;return Number(s)/90}getNalus=e=>{let t=[],n=0;for(;!(n+4>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}n+=3;let r=n,i=e[n]&31;for(n+=1;!(n+1>e.byteLength);){if(e[n]!==0||e[n+1]!==0||e[n+2]!==1){n+=1;continue}break}let a=n-r;if(e[n-1]===0&&--a,a!==0){let n=C(e.slice(r,r+a));t.push({type:i,nalu:n})}}return t}},j=(e,t)=>e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),M=class{audioConfig;videoConfig;header;textDecoder=new TextDecoder(`utf-8`);on={};constructor(){}parse=async e=>{let t=0;for(this.header||(this.parseHeader(e,t),t+=9);this.isSurplusTag(e,t)!==!1;){let{tagType:n,dataSize:r,timestamp:i}=this.parseTagHeader(e,t+4);if(n){let a=this.parseTagBody(n,e,t+4+11,r);switch(n){case`script`:this.on.info&&this.on.info(a);break;case`audio`:{let{accPacketType:e}=a;if(e===0){let{codec:e,sampleRate:t,channelConfiguration:n}=a;this.audioConfig={kind:`audio`,codec:e,sampleRate:t,numberOfChannels:n},this.on.config&&this.on.config(this.audioConfig)}else{let{cts:e,data:t}=a,n=e===void 0?void 0:e+i;this.on.chunk&&this.on.chunk({kind:`audio`,type:`key`,dts:i,pts:n,cts:e,data:t})}}break;case`video`:{let{avcPacketType:e}=a;if(e===0){let{codec:e,sps:t,pps:n,data:r}=a;this.videoConfig={kind:`video`,codec:e,description:r,sps:t,pps:n},this.on.config&&this.on.config(this.videoConfig)}else{let{frameType:e,cts:t,data:n,nalus:r}=a,o=e===1?`key`:`delta`,s=t===void 0?void 0:t+i;this.on.chunk&&this.on.chunk({kind:`video`,type:o,dts:i,pts:s,cts:t,data:n,nalus:r})}}break}t=t+4+11+r}await new Promise(e=>setTimeout(()=>e(!0),8))}return t};parseHeader=(e,t)=>{let n,r,i,a;n=e.getUint8(t)<<16|e.getUint8(t+1)<<8|e.getUint8(t+2),r=e.getUint8(3);{let[,,t,,n]=e.getUint8(0).toString(2).padStart(5,`0`).split(``);i={audio:n===`1`,video:t===`1`}}a=e.getUint32(5),this.header={signature:n,version:r,flags:i,dataOffset:a}};isSurplusTag=(e,t)=>{let n=!0,r=e.byteLength;if(t+4>r)n=!1;else if(t+4+11>r)n=!1;else{let i=j(e,t+4+1);t+4+11+i>r&&(n=!1)}return n};parseTagHeader=(e,t)=>{let n,r,i,a,o;{let r=e.getUint8(t),i;switch(r){case 18:i=`script`;break;case 8:i=`audio`;break;case 9:i=`video`;break}n=i}return r=j(e,t+1),i=j(e,t+4),a=e.getUint8(t+7),o=j(e,t+8),{tagType:n,dataSize:r,timestamp:i,timestampExtended:a,streamID:o}};parseTagBody=(e,t,n,r)=>{let i;switch(e){case`script`:i=this.parseMetaData(t,n);break;case`audio`:i=this.parseAudio(t,n,r);break;case`video`:i=this.parseVideo(t,n,r);break}return i};parseMetaData=(e,t)=>{let n=t;if(e.getUint8(n)!==2)throw Error(`Invalid AMF type for onMetaData (expected 0x02)`);n+=1;let r=e.getUint16(n,!1);n+=2;{let t=new Int8Array(e.buffer.slice(n,n+r));if((this.textDecoder?.decode(t)||``)!==`onMetaData`)throw Error(`Expected 'onMetaData' string`);n+=r}let i=this.getAmfType(e,n);return n+=1,this.getAMFValue(e,n,i).value};parseAudio=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i>>2&3,s=i>>1&1,c=i&1;r+=1;let l=e.getUint8(r);r+=1;let u=n,d=new Uint8Array(e.buffer.slice(r,r+u));if(a===10&&l===0){let t=e.getUint8(r),n=e.getUint8(r+1),i=t>>3&31,u=(t&7)<<1|n>>7;return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d,samplingFrequencyIndex:u,channelConfiguration:n>>3&15,codec:`mp4a.40.${i}`,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][u]}}return{soundFormat:a,soundRate:o,soundSize:s,soundType:c,accPacketType:l,data:d}};parseVideo=(e,t,n)=>{let r=t,i=e.getUint8(r),a=i>>4&15,o=i&15;r+=1;let s=e.getUint8(r);r+=1;let c=j(e,r);r+=3;let l=n-5,u=new Uint8Array(e.buffer.slice(r,r+l));switch(o){case 7:if(s===0)return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u,...S(u)};if(s===1){let t=[],i=r+n-5;for(;!(r+4>i);){let n=e.getUint32(r,!1),i=new Uint8Array(e.buffer.slice(r,r+4+n));r+=4+n,t.push(i)}return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u,nalus:t}}break;default:throw Error(`Unsupported codecID`)}return{frameType:a,codecID:o,avcPacketType:s,cts:c,data:u}};getAmfType=(e,t)=>e.getUint8(t);getAMFName=(e,t,n)=>{let r=new Uint8Array(e.buffer.slice(t,t+n));return this.textDecoder?.decode(r)||``};getAMFValue=(e,t,n)=>{let r=t,i,a=0;switch(n){case 0:i=e.getFloat64(r,!1),a=8;break;case 1:i=!!e.getUint8(r),a=1;break;case 2:{i=``;let t=e.getUint16(r,!1);r+=2;let n=new Int8Array(e.buffer,r,t).filter(e=>e!==0);i=(this.textDecoder?.decode(n)||``).trim(),a=2+t}break;case 3:for(i={};r<e.byteLength;){let t=e.getUint16(r,!1);if(t===0)break;r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);if(o===6)break;r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}break;case 8:{i={};let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=e.getUint16(r,!1);r+=2;let n=this.getAMFName(e,r,t);r+=t;let o=this.getAmfType(e,r);r+=1;let s=this.getAMFValue(e,r,o);r+=s.length,i[n]=s.value,a=2+t+1+s.length}}break;case 10:{i=[];let t=e.getUint32(r,!1);r+=4;for(let n=0;n<t;n++){let t=this.getAmfType(e,r);r+=1;let n=this.getAMFValue(e,r,t);r+=n.length,i.push(n.value),a=1+n.length}}break}return{amfType:n,length:a,value:i}}},N=class{pattern;cacher=new O;isParseing=!1;offset=0;parser;on={};constructor(){}init=e=>{switch(this.destroy(),this.pattern=e,this.pattern){case`flv`:this.parser=new M;break;case`hls`:this.parser=new A;break;default:throw Error(`is error pattern.`)}this.parser.on.debug=e=>this.on.debug&&this.on.debug(e),this.parser.on.info=e=>this.on.info&&this.on.info(e),this.parser.on.config=e=>this.on.config&&this.on.config(e),this.parser.on.chunk=e=>{this.cacher.pushChunk(e),this.on.chunk&&this.on.chunk(e)}};push=e=>{this.cacher.push(e),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 Error(`You need to set the pattern.`);if(!this.parser)throw Error(`You need to init parser.`);for(;;){let e=this.cacher.next(this.offset);if(this.offset=0,!e)break;this.offset=await this.parser.parse(e)}this.isParseing=!1}catch{this.destroy()}}},P=class{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:e=>{let t=this.decodingSpeedRatio;this.on.audio.decode&&this.on.audio.decode({audioData:e,playbackRate:t})},error:e=>{this.on.audio.error&&this.on.audio.error(e)}}),this.audioDecoder.configure(this.audioDecoderConfig)};initVideo=e=>{this.video.destroy(),this.videoDecoderConfig={...e},this.videoDecoder=new VideoDecoder({output:async e=>{this.frameStartTime||=e.timestamp;try{let t=e.timestamp-this.frameStartTime+this.baseTime*1e3,n=await createImageBitmap(e);if(e.close(),!n.width||!n.height)return n.close();this.on.video.decode&&this.on.video.decode({timestamp:t,bitmap:n}),this.currentChunk&&this.currentChunk.kind===`video`&&this.currentChunk.nalus&&this.on.nalus&&this.on.nalus(this.currentChunk.nalus)}catch{e.close()}},error:e=>{this.on.video.error&&this.on.video.error(e)}}),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,t=this.baseTime+performance.now();if(this.lastRenderTime||=t,this.fps=Math.round(1e3/(t-this.lastRenderTime)),this.lastRenderTime=t,this.nextRenderTime){let t=this.lastRenderTime-this.nextRenderTime;e-=t}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(),this.currentChunk;){let e=this.pendingChunks.length;if(this.frameTrack){let[t,n]=this.fameTrackOption[this.pattern];if(e<=t&&(this.isFrameTrack=!1),e>=n&&(this.isFrameTrack=!0),this.isFrameTrack){let n=Math.min(1+(e-t)/100,this.maxDecodingSpeedRatio);this.decodingSpeedRatio=Number(n.toFixed(1))}else this.decodingSpeedRatio=1}if(this.on.analysis){let{decodingSpeed:t,decodingSpeedRatio:n,fps:r}=this;this.on.analysis({decodingSpeed:t,decodingSpeedRatio:n,fps:r,cacheLength:e})}let{kind:t,init:n}=this.currentChunk;switch(t){case`audio`:this.decodeAudio(n);break;case`video`:this.decodeVideo(n);break}if(t===`video`)break}this.isProcessing=!1}};decodeAudio=e=>{if(!this.audioDecoder)return;let t=new EncodedAudioChunk(e);this.audioDecoder.decode(t)};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)){let t=new EncodedVideoChunk(e);this.videoDecoder.decode(t)}};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}}},F=class{renderMap=new Map;constructor(){}push=async e=>{let{timestamp:t}=e,{bitmap:n}=e;try{let e=[...this.renderMap.keys()];for(let r of e){let e=this.renderMap.get(r);if(!e)continue;let{pause:i=!1,writer:a,offscreen:o,option:s}=e;if(i===!0)continue;let c=async e=>{if(a){let n=new VideoFrame(e,{timestamp:t});try{await a.write(n)}catch{}n.close()}else o&&(o.width=e.width,o.height=e.height,o?.getContext(`2d`)?.drawImage(e,0,0))};if(r===`default`)await c(n);else if(s){let{sx:e=0,sy:t=0,sw:r=n.width,sh:i=n.height}=s;await c(await createImageBitmap(n,e,t,r,i))}}}catch{}n.close()};addCut=e=>{let{key:t,writable:n,offscreen:r,option:i}={key:`default`,...e};if(n){let e=n.getWriter();this.renderMap.set(t,{writer:e,option:i,pause:!1})}else this.renderMap.set(t,{offscreen:r,option:i,pause:!1})};delCut=e=>{this.renderMap.delete(e)};setCut=e=>{let{key:t,cutOption:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,option:n})};setPause=e=>{let{key:t,pause:n}={key:`default`,...e},r=this.renderMap.get(t);r&&this.renderMap.set(t,{...r,pause:n})};destroy=()=>{this.renderMap=new Map}};e.Decoder=P,e.DecoderWorker=c,e.Demuxer=N,e.DemuxerWorker=i,e.PrPlayer=D,e.Render=F,e.RenderWorker=f});
|
package/package.json
CHANGED
|
@@ -1,31 +1,32 @@
|
|
|
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.
|
|
4
|
+
"version": "0.4.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
7
7
|
"dist"
|
|
8
8
|
],
|
|
9
9
|
"main": "./dist/index.umd.cjs",
|
|
10
10
|
"module": "./dist/index.js",
|
|
11
|
-
"types": "./dist/index.d.ts",
|
|
11
|
+
"types": "./dist/src/index.d.ts",
|
|
12
12
|
"exports": {
|
|
13
13
|
".": {
|
|
14
14
|
"import": "./dist/index.js",
|
|
15
|
-
"require": "./dist/index.umd.cjs"
|
|
15
|
+
"require": "./dist/index.umd.cjs",
|
|
16
|
+
"types": "./dist/src/index.d.ts"
|
|
16
17
|
}
|
|
17
18
|
},
|
|
18
19
|
"scripts": {
|
|
19
20
|
"build": "tsc && vite build"
|
|
20
21
|
},
|
|
21
22
|
"dependencies": {
|
|
22
|
-
"pr-audio-stream": "^0.2.
|
|
23
|
+
"pr-audio-stream": "^0.2.11",
|
|
23
24
|
"pr-fetch": "^0.0.4"
|
|
24
25
|
},
|
|
25
26
|
"devDependencies": {
|
|
26
27
|
"typescript": "^6.0.2",
|
|
27
|
-
"vite": "^8.0.
|
|
28
|
-
"vite-plugin-dts": "^4.5.
|
|
28
|
+
"vite": "^8.0.5",
|
|
29
|
+
"vite-plugin-dts": "^4.5.2"
|
|
29
30
|
},
|
|
30
31
|
"private": false,
|
|
31
32
|
"author": "Breathe",
|