fluxkit-player 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +88 -9
  2. package/README.en.md +224 -0
  3. package/README.md +207 -98
  4. package/THIRD-PARTY-NOTICES.md +30 -0
  5. package/dist/fluxkit.js +2052 -479
  6. package/dist/fluxkit.js.map +1 -1
  7. package/dist/fluxkit.umd.cjs +75 -3
  8. package/dist/fluxkit.umd.cjs.map +1 -1
  9. package/dist/types/config.d.ts +21 -1
  10. package/dist/types/crypto/hls-aes.d.ts +13 -0
  11. package/dist/types/demux/flv.d.ts +2 -0
  12. package/dist/types/demux/hls.d.ts +25 -0
  13. package/dist/types/index.d.ts +3 -2
  14. package/dist/types/pipeline/timeline.d.ts +4 -0
  15. package/dist/types/player.d.ts +60 -1
  16. package/dist/types/render/audio.d.ts +13 -0
  17. package/dist/types/render/backlog.d.ts +27 -0
  18. package/dist/types/render/mse.d.ts +7 -0
  19. package/dist/types/render/software.d.ts +34 -1
  20. package/dist/types/render/subtitles.d.ts +36 -0
  21. package/dist/types/render/webcodecs.d.ts +4 -0
  22. package/dist/types/soft/index.d.ts +5 -0
  23. package/dist/types/soft/openh264.d.ts +21 -0
  24. package/dist/types/soft/soft-worker.d.ts +2 -0
  25. package/dist/types/soft/types.d.ts +2 -2
  26. package/dist/types/soft/worker-protocol.d.ts +52 -0
  27. package/dist/types/source/abr.d.ts +22 -0
  28. package/dist/types/source/hls.d.ts +39 -2
  29. package/dist/types/source/stream.d.ts +2 -1
  30. package/dist/types/types.d.ts +108 -0
  31. package/dist/types/ui/controls.d.ts +68 -0
  32. package/docs/PUBLISHING.md +142 -0
  33. package/docs/README.md +42 -0
  34. package/docs/TEST-REPORT.md +370 -0
  35. package/docs/USAGE.md +513 -0
  36. package/docs/architecture.md +213 -0
  37. package/docs/test-logs/build.txt +19 -0
  38. package/docs/test-logs/coverage.txt +64 -0
  39. package/docs/test-logs/e2e-firefox.txt +1667 -0
  40. package/docs/test-logs/e2e.txt +1667 -0
  41. package/docs/test-logs/environment.json +62 -0
  42. package/docs/test-logs/typecheck.txt +1 -0
  43. package/docs/test-logs/unit.txt +81 -0
  44. package/examples/README.md +53 -0
  45. package/examples/minimal.html +49 -0
  46. package/examples/react/FluxPlayer.tsx +48 -0
  47. package/examples/soft-worker.js +6 -0
  48. package/examples/vue/FluxPlayer.vue +47 -0
  49. package/package.json +22 -3
package/dist/fluxkit.js CHANGED
@@ -61,6 +61,8 @@ function o(e = {}) {
61
61
  return {
62
62
  decoder: e.decoder ?? a.decoder,
63
63
  protocol: e.protocol ?? "auto",
64
+ autoReconnect: e.autoReconnect ?? !0,
65
+ live: e.live,
64
66
  autoplay: e.autoplay ?? a.autoplay,
65
67
  muted: e.muted ?? a.muted,
66
68
  loop: e.loop ?? a.loop,
@@ -78,17 +80,30 @@ function o(e = {}) {
78
80
  hls: {
79
81
  mode: e.hls?.mode ?? "demux",
80
82
  maxBandwidth: e.hls?.maxBandwidth,
81
- liveReloadFactor: e.hls?.liveReloadFactor ?? 1.5
83
+ liveReloadFactor: e.hls?.liveReloadFactor ?? 1.5,
84
+ abr: e.hls?.abr ?? !0,
85
+ abrLowBuffer: e.hls?.abrLowBuffer ?? 2,
86
+ abrHighBuffer: e.hls?.abrHighBuffer ?? 8
82
87
  },
83
88
  webcodecs: {
84
89
  fit: e.webcodecs?.fit ?? "contain",
85
90
  audioBuffer: e.webcodecs?.audioBuffer ?? .15
86
91
  },
92
+ controls: {
93
+ enabled: typeof e.controls == "object" || !!e.controls,
94
+ autoHide: (typeof e.controls == "object" ? e.controls.autoHide : void 0) ?? 2500,
95
+ screenshot: (typeof e.controls == "object" ? e.controls.screenshot : void 0) ?? !0,
96
+ record: (typeof e.controls == "object" ? e.controls.record : void 0) ?? !0,
97
+ fullscreen: (typeof e.controls == "object" ? e.controls.fullscreen : void 0) ?? !0,
98
+ downloadName: (typeof e.controls == "object" ? e.controls.downloadName : void 0) ?? "fluxkit"
99
+ },
87
100
  softDecode: {
88
101
  enabled: e.softDecode?.enabled ?? !0,
89
102
  maxDecodeAhead: e.softDecode?.maxDecodeAhead ?? 4,
90
103
  dropLateFrames: e.softDecode?.dropLateFrames ?? !0,
91
- loaders: e.softDecode?.loaders
104
+ loaders: e.softDecode?.loaders,
105
+ worker: e.softDecode?.worker,
106
+ modules: e.softDecode?.modules
92
107
  }
93
108
  };
94
109
  }
@@ -201,25 +216,36 @@ function p(e, t, n) {
201
216
  // src/pipeline/timeline.ts
202
217
  var m = class {
203
218
  constructor(e) {
204
- r(this, "tracks", void 0), r(this, "baseMs", null), r(this, "startMs", 0), r(this, "lastDts", /* @__PURE__ */ new Map()), this.tracks = e;
219
+ r(this, "tracks", void 0), r(this, "baseMs", null), r(this, "startMs", 0), r(this, "lastDts", /* @__PURE__ */ new Map()), r(this, "offsets", /* @__PURE__ */ new Map()), r(this, "pendingDiscontinuity", /* @__PURE__ */ new Set()), this.tracks = e;
205
220
  }
206
221
  setStart(e) {
207
- this.startMs = e, this.baseMs = null, this.lastDts.clear();
222
+ this.startMs = e, this.baseMs = null, this.lastDts.clear(), this.offsets.clear(), this.pendingDiscontinuity.clear();
223
+ }
224
+ markDiscontinuity() {
225
+ for (let e of this.tracks.keys()) this.pendingDiscontinuity.add(e);
208
226
  }
209
227
  normalize(e) {
210
228
  let t = this.tracks.get(e.trackId);
211
229
  if (!t) return e;
212
230
  let n = e.dts * 1e3 / t.timescale;
213
231
  this.baseMs === null && (this.baseMs = n - this.startMs);
214
- let r = t.timescale / 1e3, i = Math.round((n - this.baseMs) * r), a = Math.round((e.pts * 1e3 / t.timescale - this.baseMs) * r), o = this.lastDts.get(t.id);
215
- if (o !== void 0 && i <= o) {
216
- let e = o + 1 - i;
217
- i += e, a += e;
232
+ let r = t.timescale / 1e3, i = this.offsets.get(t.id) ?? 0, a = Math.round((n - this.baseMs) * r) + i, o = Math.round((e.pts * 1e3 / t.timescale - this.baseMs) * r) + i;
233
+ if (this.pendingDiscontinuity.delete(t.id)) {
234
+ let n = this.lastDts.get(t.id);
235
+ if (n !== void 0) {
236
+ let r = n + (e.duration > 0 ? e.duration : 1) - a;
237
+ a += r, o += r, this.offsets.set(t.id, i + r);
238
+ }
239
+ }
240
+ let s = this.lastDts.get(t.id);
241
+ if (s !== void 0 && a <= s) {
242
+ let e = s + 1 - a;
243
+ a += e, o += e;
218
244
  }
219
- return a < i && (a = i), this.lastDts.set(t.id, i), {
245
+ return o < a && (o = a), this.lastDts.set(t.id, a), {
220
246
  ...e,
221
- dts: i,
222
- pts: a
247
+ dts: a,
248
+ pts: o
223
249
  };
224
250
  }
225
251
  }, h = class {
@@ -562,9 +588,9 @@ function te(e, t) {
562
588
  }
563
589
  function ne(e) {
564
590
  let t = new x(64);
565
- return O(t, e), t.toUint8Array();
591
+ return re(t, e), t.toUint8Array();
566
592
  }
567
- function O(e, t) {
593
+ function re(e, t) {
568
594
  if (t === null) e.u8(5);
569
595
  else if (t === void 0) e.u8(6);
570
596
  else switch (typeof t) {
@@ -580,24 +606,24 @@ function O(e, t) {
580
606
  case "object":
581
607
  if (Array.isArray(t)) {
582
608
  e.u8(10).u32(t.length);
583
- for (let n of t) O(e, n);
609
+ for (let n of t) re(e, n);
584
610
  return;
585
611
  }
586
612
  e.u8(3);
587
613
  for (let [n, r] of Object.entries(t)) {
588
614
  let t = new TextEncoder().encode(n);
589
- e.u16(t.length).raw(t), O(e, r);
615
+ e.u16(t.length).raw(t), re(e, r);
590
616
  }
591
617
  e.u16(0).u8(9);
592
618
  return;
593
619
  default: e.u8(6);
594
620
  }
595
621
  }
596
- function re(...e) {
622
+ function ie(...e) {
597
623
  return _(...e.map(ne));
598
624
  }
599
625
  // src/codec/bit.ts
600
- var ie = class {
626
+ var ae = class {
601
627
  constructor(e, t = 0) {
602
628
  r(this, "data", void 0), r(this, "bitPos", 0), this.data = e, this.bitPos = t;
603
629
  }
@@ -628,7 +654,7 @@ var ie = class {
628
654
  return e & 1 ? (e + 1) / 2 : -(e / 2);
629
655
  }
630
656
  };
631
- function ae(e) {
657
+ function oe(e) {
632
658
  let t = !1;
633
659
  for (let n = 2; n < e.length; n++) if (e[n] === 3 && e[n - 1] === 0 && e[n - 2] === 0) {
634
660
  t = !0;
@@ -643,7 +669,7 @@ function ae(e) {
643
669
  return n.subarray(0, r);
644
670
  }
645
671
  // src/codec/h264.ts
646
- var k = {
672
+ var se = {
647
673
  SLICE: 1,
648
674
  IDR: 5,
649
675
  SEI: 6,
@@ -651,7 +677,7 @@ var k = {
651
677
  PPS: 8,
652
678
  AUD: 9
653
679
  };
654
- function A(e) {
680
+ function ce(e) {
655
681
  let t = [], n = -1, r = 0;
656
682
  for (; r + 2 < e.length;) if (e[r] === 0 && e[r + 1] === 0 && e[r + 2] === 1) {
657
683
  if (n >= 0) {
@@ -668,7 +694,7 @@ function A(e) {
668
694
  }
669
695
  return t;
670
696
  }
671
- function oe(e, t = 4) {
697
+ function le(e, t = 4) {
672
698
  let n = [];
673
699
  for (let r of e) {
674
700
  let e = new Uint8Array(t), i = new DataView(e.buffer);
@@ -676,12 +702,12 @@ function oe(e, t = 4) {
676
702
  }
677
703
  return _(...n);
678
704
  }
679
- function se(e, t) {
705
+ function ue(e, t) {
680
706
  let n = 8, r = 8;
681
707
  for (let i = 0; i < t; i++) r !== 0 && (r = (n + e.se() + 256) % 256), n = r === 0 ? n : r;
682
708
  }
683
- function ce(e) {
684
- let t = new ie(ae(e.subarray(1))), n = t.u(8), r = t.u(8), i = t.u(8);
709
+ function de(e) {
710
+ let t = new ae(oe(e.subarray(1))), n = t.u(8), r = t.u(8), i = t.u(8);
685
711
  t.ue();
686
712
  let a = 1, o = 8, s = 8;
687
713
  if ([
@@ -700,7 +726,7 @@ function ce(e) {
700
726
  135
701
727
  ].includes(n) && (a = t.ue(), a === 3 && t.u(1), o = t.ue() + 8, s = t.ue() + 8, t.u(1), t.u(1))) {
702
728
  let e = a === 3 ? 12 : 8;
703
- for (let n = 0; n < e; n++) t.u(1) && se(t, n < 6 ? 16 : 64);
729
+ for (let n = 0; n < e; n++) t.u(1) && ue(t, n < 6 ? 16 : 64);
704
730
  }
705
731
  t.ue();
706
732
  let c = t.ue();
@@ -734,7 +760,7 @@ function ce(e) {
734
760
  bitDepthChroma: s
735
761
  };
736
762
  }
737
- function le(e, t, n, r = 4) {
763
+ function fe(e, t, n, r = 4) {
738
764
  let i = new x();
739
765
  i.u8(1), i.u8(n.profile), i.u8(n.compat), i.u8(n.level), i.u8(252 | r - 1 & 3), i.u8(224 | e.length & 31);
740
766
  for (let t of e) i.u16(t.length), i.raw(t);
@@ -742,17 +768,17 @@ function le(e, t, n, r = 4) {
742
768
  for (let e of t) i.u16(e.length), i.raw(e);
743
769
  return i.toUint8Array();
744
770
  }
745
- function ue(e) {
771
+ function pe(e) {
746
772
  return e.length < 4 ? "avc1.42E01E" : `avc1.${y(e[1])}${y(e[2])}${y(e[3])}`;
747
773
  }
748
- function de(e) {
774
+ function me(e) {
749
775
  return {
750
776
  profile: e[1] ?? 0,
751
777
  compat: e[2] ?? 0,
752
778
  level: e[3] ?? 0
753
779
  };
754
780
  }
755
- function fe(e, t = 4) {
781
+ function he(e, t = 4) {
756
782
  let n = [], r = 0;
757
783
  for (; r + t <= e.length;) {
758
784
  let i = 0;
@@ -762,21 +788,21 @@ function fe(e, t = 4) {
762
788
  }
763
789
  return _(...n);
764
790
  }
765
- function pe(e, t = 4) {
791
+ function ge(e, t = 4) {
766
792
  let n = 0;
767
793
  for (; n + t <= e.length;) {
768
794
  let r = 0;
769
795
  for (let i = 0; i < t; i++) r = r * 256 + e[n + i];
770
796
  if (n += t, r <= 0 || n >= e.length) return !1;
771
797
  let i = e[n] & 31;
772
- if (i === k.IDR || i === k.SPS) return !0;
773
- if (i === k.SEI || i === k.AUD) n += r;
798
+ if (i === se.IDR || i === se.SPS) return !0;
799
+ if (i === se.SEI || i === se.AUD) n += r;
774
800
  else return !1;
775
801
  }
776
802
  return !1;
777
803
  }
778
804
  // src/codec/h265.ts
779
- var me = {
805
+ var _e = {
780
806
  VPS: 32,
781
807
  SPS: 33,
782
808
  PPS: 34,
@@ -784,10 +810,10 @@ var me = {
784
810
  PREFIX_SEI: 39,
785
811
  SUFFIX_SEI: 40
786
812
  };
787
- function he(e) {
813
+ function ve(e) {
788
814
  return e[0] >> 1 & 63;
789
815
  }
790
- function ge(e, t) {
816
+ function ye(e, t) {
791
817
  let n = e.u(2), r = e.u(1), i = e.u(5), a = e.u(32), o = /* @__PURE__ */ new Uint8Array(6);
792
818
  for (let t = 0; t < 48; t++) e.u(1) && (o[t >> 3] |= 128 >> (t & 7));
793
819
  let s = e.u(8), c = [], l = [];
@@ -803,12 +829,12 @@ function ge(e, t) {
803
829
  levelIdc: s
804
830
  };
805
831
  }
806
- function _e(e) {
807
- let t = new ie(ae(e.subarray(2)));
832
+ function be(e) {
833
+ let t = new ae(oe(e.subarray(2)));
808
834
  t.u(4);
809
835
  let n = t.u(3) + 1;
810
836
  t.u(1);
811
- let r = ge(t, n - 1);
837
+ let r = ye(t, n - 1);
812
838
  t.ue();
813
839
  let i = t.ue();
814
840
  i === 3 && t.u(1);
@@ -825,18 +851,18 @@ function _e(e) {
825
851
  maxSubLayers: n
826
852
  };
827
853
  }
828
- function ve(e, t, n, r, i = 4) {
854
+ function xe(e, t, n, r, i = 4) {
829
855
  let a = new x();
830
856
  a.u8(1), a.u8(e.profileSpace << 6 | e.tier << 5 | e.profileIdc & 31), a.u32(e.compatFlags >>> 0), a.raw(e.constraintFlags.subarray(0, 6)), a.u8(e.levelIdc), a.u16(61440), a.u8(252), a.u8(252 | e.chromaFormat & 3), a.u8(248 | e.bitDepthLuma - 8 & 7), a.u8(248 | e.bitDepthChroma - 8 & 7), a.u16(0), a.u8(e.maxSubLayers - 1 << 3 | 4 | i - 1 & 3), a.u8(3);
831
857
  let o = [
832
- [me.VPS, t],
833
- [me.SPS, n],
834
- [me.PPS, r]
858
+ [_e.VPS, t],
859
+ [_e.SPS, n],
860
+ [_e.PPS, r]
835
861
  ];
836
862
  for (let [e, t] of o) a.u8(128 | e & 63), a.u16(1), a.u16(t.length), a.raw(t);
837
863
  return a.toUint8Array();
838
864
  }
839
- function j(e) {
865
+ function O(e) {
840
866
  if (e.length < 13) return "hvc1.1.6.L93.B0";
841
867
  let t = e[1] >> 6 & 3, n = e[1] >> 5 & 1, r = e[1] & 31, i = (e[2] << 24 | e[3] << 16 | e[4] << 8 | e[5]) >>> 0, a = 0;
842
868
  for (let e = 0; e < 32; e++) i & 1 << e && (a |= 1 << 31 - e);
@@ -852,20 +878,20 @@ function j(e) {
852
878
  for (let e of s) c += `.${y(e)}`;
853
879
  return c;
854
880
  }
855
- function ye(e, t = 4) {
881
+ function Se(e, t = 4) {
856
882
  let n = 0;
857
883
  for (; n + t <= e.length;) {
858
884
  let r = 0;
859
885
  for (let i = 0; i < t; i++) r = r * 256 + e[n + i];
860
886
  if (n += t, r <= 0 || n >= e.length) return !1;
861
- let i = he(e.subarray(n, n + Math.min(r, 2)));
887
+ let i = ve(e.subarray(n, n + Math.min(r, 2)));
862
888
  if (i <= 31) return i >= 16 && i <= 23;
863
889
  n += r;
864
890
  }
865
891
  return !1;
866
892
  }
867
893
  // src/codec/config.ts
868
- function M(e) {
894
+ function k(e) {
869
895
  let t = [], n = [], r = 4, i = null;
870
896
  if (e.length < 7) return {
871
897
  nalLengthSize: r,
@@ -886,7 +912,7 @@ function M(e) {
886
912
  let t = a.u16();
887
913
  n.push(e.subarray(a.offset, a.offset + t)), a.skip(t);
888
914
  }
889
- t.length > 0 && (i = ce(t[0]));
915
+ t.length > 0 && (i = de(t[0]));
890
916
  } catch {}
891
917
  return {
892
918
  nalLengthSize: r,
@@ -895,7 +921,7 @@ function M(e) {
895
921
  info: i
896
922
  };
897
923
  }
898
- function N(e) {
924
+ function A(e) {
899
925
  let t = [], n = [], r = [], i = 4, a = null;
900
926
  if (e.length < 23) return {
901
927
  nalLengthSize: i,
@@ -917,7 +943,7 @@ function N(e) {
917
943
  s += a, i === 32 ? t.push(o) : i === 33 ? n.push(o) : i === 34 && r.push(o);
918
944
  }
919
945
  }
920
- n.length > 0 && (a = _e(n[0]));
946
+ n.length > 0 && (a = be(n[0]));
921
947
  } catch {}
922
948
  return {
923
949
  nalLengthSize: i,
@@ -927,12 +953,12 @@ function N(e) {
927
953
  info: a
928
954
  };
929
955
  }
930
- function be(e, t) {
956
+ function Ce(e, t) {
931
957
  let n = e[t] << 16 | e[t + 1] << 8 | e[t + 2];
932
958
  return n & 8388608 ? n - 16777216 : n;
933
959
  }
934
960
  // src/codec/aac.ts
935
- var xe = [
961
+ var we = [
936
962
  96e3,
937
963
  88200,
938
964
  64e3,
@@ -950,25 +976,25 @@ var xe = [
950
976
  0,
951
977
  0
952
978
  ];
953
- function Se(e, t = 0) {
979
+ function Te(e, t = 0) {
954
980
  if (t + 7 > e.length || e[t] !== 255 || (e[t + 1] & 240) != 240) return null;
955
981
  let n = e[t + 1] & 1, r = e[t + 2] >> 6 & 3, i = e[t + 2] >> 2 & 15, a = (e[t + 2] & 1) << 2 | e[t + 3] >> 6 & 3, o = (e[t + 3] & 3) << 11 | e[t + 4] << 3 | e[t + 5] >> 5 & 7;
956
982
  return o < 7 ? null : {
957
983
  objectType: r + 1,
958
- sampleRate: xe[i] || 44100,
984
+ sampleRate: we[i] || 44100,
959
985
  sampleRateIndex: i,
960
986
  channels: a || 2,
961
987
  frameLength: o,
962
988
  headerLength: n ? 7 : 9
963
989
  };
964
990
  }
965
- function P(e, t, n) {
966
- let r = xe.indexOf(t);
991
+ function Ee(e, t, n) {
992
+ let r = we.indexOf(t);
967
993
  (r < 0 || r > 12) && (r = 4);
968
994
  let i = e << 11 | r << 7 | (n & 15) << 3;
969
995
  return Uint8Array.of(i >> 8 & 255, i & 255);
970
996
  }
971
- function F(e) {
997
+ function j(e) {
972
998
  let t = 0, n = (n) => {
973
999
  let r = 0;
974
1000
  for (let i = 0; i < n; i++) {
@@ -978,20 +1004,20 @@ function F(e) {
978
1004
  return r;
979
1005
  }, r = n(5);
980
1006
  r === 31 && (r = 32 + n(6));
981
- let i = n(4), a = i === 15 ? n(24) : xe[i] || 44100, o = n(4);
1007
+ let i = n(4), a = i === 15 ? n(24) : we[i] || 44100, o = n(4);
982
1008
  return {
983
1009
  objectType: r,
984
1010
  sampleRate: a,
985
1011
  channels: o || 2
986
1012
  };
987
1013
  }
988
- function I(e) {
1014
+ function De(e) {
989
1015
  if (!e || e.length < 2) return "mp4a.40.2";
990
- let { objectType: t } = F(e);
1016
+ let { objectType: t } = j(e);
991
1017
  return `mp4a.40.${t}`;
992
1018
  }
993
1019
  // src/demux/flv.ts
994
- var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1020
+ var Oe = 8, ke = 9, Ae = 18, M = 1e3, je = class {
995
1021
  constructor(e) {
996
1022
  r(this, "onTag", void 0), r(this, "buf", new g()), r(this, "headerParsed", !1), this.onTag = e;
997
1023
  }
@@ -1016,7 +1042,7 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1016
1042
  let e = this.buf.peek(11);
1017
1043
  if (!e) return;
1018
1044
  let t = e[0];
1019
- if (t !== Ce && t !== we && t !== Te) {
1045
+ if (t !== Oe && t !== ke && t !== Ae) {
1020
1046
  this.buf.skip(1);
1021
1047
  continue;
1022
1048
  }
@@ -1030,9 +1056,9 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1030
1056
  }
1031
1057
  }
1032
1058
  }
1033
- }, De = class {
1059
+ }, Me = class {
1034
1060
  constructor(e) {
1035
- r(this, "sink", void 0), r(this, "format", "flv"), r(this, "parser", void 0), r(this, "videoTrack", null), r(this, "audioTrack", null), r(this, "meta", {}), r(this, "warnedUnsupported", /* @__PURE__ */ new Set()), this.sink = e, this.parser = new Ee((e, t, n) => this.handleTag(e, t, n));
1061
+ r(this, "sink", void 0), r(this, "format", "flv"), r(this, "parser", void 0), r(this, "videoTrack", null), r(this, "audioTrack", null), r(this, "meta", {}), r(this, "warnedUnsupported", /* @__PURE__ */ new Set()), this.sink = e, this.parser = new je((e, t, n) => this.handleTag(e, t, n));
1036
1062
  }
1037
1063
  push(e) {
1038
1064
  this.parser.push(e);
@@ -1040,6 +1066,10 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1040
1066
  pushTag(e, t, n) {
1041
1067
  this.handleTag(e, t, n);
1042
1068
  }
1069
+ get duration() {
1070
+ let e = this.meta.duration;
1071
+ return typeof e == "number" && e > 0 ? e : void 0;
1072
+ }
1043
1073
  flush() {
1044
1074
  this.parser.flush();
1045
1075
  }
@@ -1051,7 +1081,7 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1051
1081
  return this.videoTrack && e.push(this.videoTrack), this.audioTrack && e.push(this.audioTrack), e;
1052
1082
  }
1053
1083
  handleTag(e, t, n) {
1054
- e === we ? this.handleVideo(t, n) : e === Ce ? this.handleAudio(t, n) : e === Te && this.handleScript(n);
1084
+ e === ke ? this.handleVideo(t, n) : e === Oe ? this.handleAudio(t, n) : e === Ae && this.handleScript(n);
1055
1085
  }
1056
1086
  handleScript(e) {
1057
1087
  try {
@@ -1075,12 +1105,12 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1075
1105
  if (a === 0) c = !0, s = t.subarray(5);
1076
1106
  else if (a === 1) {
1077
1107
  if (t.length < 8) return;
1078
- o = be(t, 5), s = t.subarray(8);
1108
+ o = Ce(t, 5), s = t.subarray(8);
1079
1109
  } else if (a === 3) s = t.subarray(5);
1080
1110
  else return;
1081
1111
  } else if (i = n & 15, a = t[1], i === 7 || i === 12) {
1082
1112
  if (a === 0) c = !0, s = t.subarray(5);
1083
- else if (a === 1) o = be(t, 2), s = t.subarray(5);
1113
+ else if (a === 1) o = Ce(t, 2), s = t.subarray(5);
1084
1114
  else return;
1085
1115
  } else if (i === 2) {
1086
1116
  this.warnOnce(2, "Sorenson H.263 video is not supported");
@@ -1094,7 +1124,7 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1094
1124
  return;
1095
1125
  }
1096
1126
  if (!s || s.length === 0 || !this.videoTrack) return;
1097
- let l = r === 1 || (this.videoTrack.codec === "avc" ? pe(s) : ye(s));
1127
+ let l = r === 1 || (this.videoTrack.codec === "avc" ? ge(s) : Se(s));
1098
1128
  this.sink.onSample({
1099
1129
  trackId: this.videoTrack.id,
1100
1130
  kind: "video",
@@ -1106,11 +1136,11 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1106
1136
  });
1107
1137
  }
1108
1138
  configureAvc(e) {
1109
- let t = M(e).info, n = {
1139
+ let t = k(e).info, n = {
1110
1140
  kind: "video",
1111
1141
  id: 1,
1112
1142
  codec: "avc",
1113
- timescale: L,
1143
+ timescale: M,
1114
1144
  width: t?.width ?? 0,
1115
1145
  height: t?.height ?? 0,
1116
1146
  fps: t?.fps,
@@ -1121,11 +1151,11 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1121
1151
  this.applyMetaSize(n), this.videoTrack = n, this.sink.onTracks(this.tracks());
1122
1152
  }
1123
1153
  configureHevc(e) {
1124
- let t = N(e).info, n = {
1154
+ let t = A(e).info, n = {
1125
1155
  kind: "video",
1126
1156
  id: 1,
1127
1157
  codec: "hevc",
1128
- timescale: L,
1158
+ timescale: M,
1129
1159
  width: t?.width ?? 0,
1130
1160
  height: t?.height ?? 0,
1131
1161
  codecPrivate: e.slice(),
@@ -1158,7 +1188,7 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1158
1188
  kind: "audio",
1159
1189
  id: 2,
1160
1190
  codec: n,
1161
- timescale: L,
1191
+ timescale: M,
1162
1192
  sampleRate: 8e3,
1163
1193
  channels: a + 1
1164
1194
  }, this.sink.onTracks(this.tracks())), this.sink.onSample({
@@ -1174,7 +1204,7 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1174
1204
  kind: "audio",
1175
1205
  id: 2,
1176
1206
  codec: "mp3",
1177
- timescale: L,
1207
+ timescale: M,
1178
1208
  sampleRate: [
1179
1209
  5512,
1180
1210
  11025,
@@ -1193,11 +1223,11 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1193
1223
  })) : (r === 0 || r === 3) && this.warnOnce(20 + r, "uncompressed FLV audio is not supported");
1194
1224
  }
1195
1225
  configureAac(e) {
1196
- let t = F(e), n = {
1226
+ let t = j(e), n = {
1197
1227
  kind: "audio",
1198
1228
  id: 2,
1199
1229
  codec: "aac",
1200
- timescale: L,
1230
+ timescale: M,
1201
1231
  sampleRate: t.sampleRate,
1202
1232
  channels: t.channels,
1203
1233
  codecPrivate: e.slice()
@@ -1209,7 +1239,7 @@ var Ce = 8, we = 9, Te = 18, L = 1e3, Ee = class {
1209
1239
  }
1210
1240
  };
1211
1241
  // src/demux/mp4.ts
1212
- function R(e) {
1242
+ function N(e) {
1213
1243
  let t = [], n = new DataView(e.buffer, e.byteOffset, e.byteLength), r = 0;
1214
1244
  for (; r + 8 <= e.length;) {
1215
1245
  let i = n.getUint32(r), a = v(e, r + 4, r + 8), o = 8, s = i;
@@ -1228,13 +1258,13 @@ function R(e) {
1228
1258
  }
1229
1259
  return t;
1230
1260
  }
1231
- function z(e, t) {
1261
+ function P(e, t) {
1232
1262
  return e.find((e) => e.type === t);
1233
1263
  }
1234
- function B(e, t) {
1264
+ function Ne(e, t) {
1235
1265
  return e.filter((e) => e.type === t);
1236
1266
  }
1237
- var V = class {
1267
+ var F = class {
1238
1268
  constructor(e) {
1239
1269
  r(this, "sink", void 0), r(this, "format", "mp4"), r(this, "buf", new g(65536)), r(this, "bufStart", 0), r(this, "skipBytes", 0), r(this, "state", "boxes"), r(this, "mdatEnd", 0), r(this, "pending", []), r(this, "pendingIndex", 0), r(this, "moovDone", !1), r(this, "sawMdatFirst", !1), r(this, "mediaDuration", 0), r(this, "tracks", /* @__PURE__ */ new Map()), r(this, "sawMoof", !1), this.sink = e;
1240
1270
  }
@@ -1343,25 +1373,25 @@ var V = class {
1343
1373
  }
1344
1374
  }
1345
1375
  parseMoov(e) {
1346
- let t = R(e), n = z(t, "mvhd");
1376
+ let t = N(e), n = P(t, "mvhd");
1347
1377
  if (n) try {
1348
1378
  let e = new b(n.payload), t = e.u8();
1349
1379
  e.u24(), e.skip(t === 1 ? 16 : 8);
1350
1380
  let r = e.u32(), i = t === 1 ? e.u64() : e.u32();
1351
1381
  r > 0 && i > 0 && (this.mediaDuration = i / r);
1352
1382
  } catch {}
1353
- for (let e of B(t, "trak")) this.parseTrak(e.payload);
1383
+ for (let e of Ne(t, "trak")) this.parseTrak(e.payload);
1354
1384
  this.moovDone = !0, this.tracks.size > 0 && this.sink.onTracks([...this.tracks.values()]);
1355
1385
  }
1356
1386
  parseTrak(e) {
1357
- let t = R(e), n = z(t, "tkhd"), r = z(t, "mdia");
1387
+ let t = N(e), n = P(t, "tkhd"), r = P(t, "mdia");
1358
1388
  if (!n || !r) return;
1359
1389
  let a = 0, o = 0, s = 0;
1360
1390
  {
1361
1391
  let e = new b(n.payload), t = e.u8();
1362
1392
  e.u24(), t === 1 ? e.skip(16) : e.skip(8), a = e.u32(), e.skip(4), t === 1 ? e.skip(8) : e.skip(4), e.skip(8), e.skip(8), e.skip(36), o = e.u32() / 65536, s = e.u32() / 65536;
1363
1393
  }
1364
- let c = R(r.payload), l = z(c, "mdhd"), u = z(c, "hdlr"), d = z(c, "minf");
1394
+ let c = N(r.payload), l = P(c, "mdhd"), u = P(c, "hdlr"), d = P(c, "minf");
1365
1395
  if (!l || !u || !d) return;
1366
1396
  let f = 1e3;
1367
1397
  {
@@ -1374,12 +1404,12 @@ var V = class {
1374
1404
  e.skip(8), p = e.fourcc();
1375
1405
  }
1376
1406
  if (p !== "vide" && p !== "soun") return;
1377
- let m = z(R(d.payload), "stbl");
1407
+ let m = P(N(d.payload), "stbl");
1378
1408
  if (!m) return;
1379
- let h = R(m.payload), g = z(h, "stsd");
1409
+ let h = N(m.payload), g = P(h, "stsd");
1380
1410
  if (!g) return;
1381
1411
  let _ = p === "vide" ? this.parseVideoTrack(g.payload, a, f, o, s) : this.parseAudioTrack(g.payload, a, f);
1382
- if (!_ || (this.tracks.set(a, _), !z(h, "stsz") || !this.hasSampleTable(h))) return;
1412
+ if (!_ || (this.tracks.set(a, _), !P(h, "stsz") || !this.hasSampleTable(h))) return;
1383
1413
  let v = this.buildSampleTable(h, _, a);
1384
1414
  if (v.length > 0) {
1385
1415
  if (this.sawMdatFirst && v[0].offset < this.bufStart) throw new i("MP4_MOOV_AT_END", "this MP4 has its index (moov) at the end of the file; re-mux it with faststart, or use native playback");
@@ -1387,11 +1417,11 @@ var V = class {
1387
1417
  }
1388
1418
  }
1389
1419
  hasSampleTable(e) {
1390
- let t = z(e, "stsz");
1420
+ let t = P(e, "stsz");
1391
1421
  return t ? new DataView(t.payload.buffer, t.payload.byteOffset, t.payload.byteLength).getUint32(8) > 0 : !1;
1392
1422
  }
1393
1423
  buildSampleTable(e, t, n) {
1394
- let r = z(e, "stsz"), i = z(e, "stts"), a = z(e, "ctts"), o = z(e, "stsc"), s = z(e, "stss"), c = z(e, "stco"), l = z(e, "co64"), u = new b(r.payload);
1424
+ let r = P(e, "stsz"), i = P(e, "stts"), a = P(e, "ctts"), o = P(e, "stsc"), s = P(e, "stss"), c = P(e, "stco"), l = P(e, "co64"), u = new b(r.payload);
1395
1425
  u.skip(4);
1396
1426
  let d = u.u32(), f = u.u32(), p = [];
1397
1427
  if (d === 0) for (let e = 0; e < f; e++) p.push(u.u32());
@@ -1475,11 +1505,11 @@ var V = class {
1475
1505
  a.skip(6), a.u16(), a.skip(16);
1476
1506
  let l = a.u16(), u = a.u16();
1477
1507
  a.skip(50);
1478
- let d = c + 78, f = c - 8 + o, p = R(e.subarray(d, f));
1508
+ let d = c + 78, f = c - 8 + o, p = N(e.subarray(d, f));
1479
1509
  if (s === "avc1" || s === "avc3") {
1480
1510
  let e = p.find((e) => e.type === "avcC");
1481
1511
  if (!e) return null;
1482
- let a = e.payload.slice(), o = M(a);
1512
+ let a = e.payload.slice(), o = k(a);
1483
1513
  return {
1484
1514
  kind: "video",
1485
1515
  id: t,
@@ -1495,7 +1525,7 @@ var V = class {
1495
1525
  }
1496
1526
  let m = p.find((e) => e.type === "hvcC");
1497
1527
  if (!m) return null;
1498
- let h = m.payload.slice(), g = N(h);
1528
+ let h = m.payload.slice(), g = A(h);
1499
1529
  return {
1500
1530
  kind: "video",
1501
1531
  id: t,
@@ -1526,14 +1556,14 @@ var V = class {
1526
1556
  };
1527
1557
  if (o === "ec-3" || o === "ac-3") return this.sink.onError?.(new i("UNSUPPORTED_AUDIO", `Dolby ${o} audio is not supported`)), null;
1528
1558
  if (o !== "mp4a") return null;
1529
- let u = s + 28, d = R(e.subarray(u, s + (a - 8))).find((e) => e.type === "esds"), f;
1559
+ let u = s + 28, d = N(e.subarray(u, s + (a - 8))).find((e) => e.type === "esds"), f;
1530
1560
  if (d) {
1531
- let e = Oe(d.payload);
1561
+ let e = Pe(d.payload);
1532
1562
  e && (f = e);
1533
1563
  }
1534
1564
  let p = l || 44100, m = c || 2;
1535
1565
  if (f) try {
1536
- let e = F(f);
1566
+ let e = j(f);
1537
1567
  p = e.sampleRate || p, m = e.channels || m;
1538
1568
  } catch {}
1539
1569
  return {
@@ -1543,25 +1573,25 @@ var V = class {
1543
1573
  timescale: n,
1544
1574
  sampleRate: p,
1545
1575
  channels: m,
1546
- codecPrivate: f ?? P(2, p, m)
1576
+ codecPrivate: f ?? Ee(2, p, m)
1547
1577
  };
1548
1578
  }
1549
1579
  parseMoof(e, t, n = 8) {
1550
- let r = R(e);
1551
- for (let i of B(r, "traf")) {
1552
- let r = R(i.payload), a = z(r, "tfhd");
1580
+ let r = N(e);
1581
+ for (let i of Ne(r, "traf")) {
1582
+ let r = N(i.payload), a = P(r, "tfhd");
1553
1583
  if (!a) continue;
1554
1584
  let o = new b(a.payload);
1555
1585
  o.u8();
1556
1586
  let s = o.u24(), c = o.u32(), l = t;
1557
1587
  s & 1 && (l = o.u64()), s & 2 && o.u32();
1558
- let u = s & 8 ? o.u32() : 0, d = s & 16 ? o.u32() : 0, f = s & 32 ? o.u32() : 0, p = z(r, "tfdt"), m = 0;
1588
+ let u = s & 8 ? o.u32() : 0, d = s & 16 ? o.u32() : 0, f = s & 32 ? o.u32() : 0, p = P(r, "tfdt"), m = 0;
1559
1589
  if (p) {
1560
1590
  let e = new b(p.payload), t = e.u8();
1561
1591
  e.u24(), m = t === 1 ? e.u64() : e.u32();
1562
1592
  }
1563
1593
  let h = 0, g = !0;
1564
- for (let i of B(r, "trun")) {
1594
+ for (let i of Ne(r, "trun")) {
1565
1595
  let r = new b(i.payload), a = r.u8(), o = r.u24(), s = r.u32(), p = 0;
1566
1596
  o & 1 && (p = r.i32());
1567
1597
  let _ = null;
@@ -1585,7 +1615,7 @@ var V = class {
1585
1615
  this.pending.sort((e, t) => e.offset - t.offset);
1586
1616
  }
1587
1617
  };
1588
- function Oe(e) {
1618
+ function Pe(e) {
1589
1619
  let t = 4, n = () => {
1590
1620
  let n = 0;
1591
1621
  for (let r = 0; r < 4; r++) {
@@ -1611,7 +1641,7 @@ function Oe(e) {
1611
1641
  return null;
1612
1642
  }
1613
1643
  // src/io/http.ts
1614
- var ke = class {
1644
+ var Fe = class {
1615
1645
  constructor() {
1616
1646
  r(this, "controller", null), r(this, "paused", !1), r(this, "resumeWaiters", []);
1617
1647
  }
@@ -1694,7 +1724,7 @@ var ke = class {
1694
1724
  this.controller?.abort(), this.controller = null, this.resume();
1695
1725
  }
1696
1726
  };
1697
- async function H(e, t = {}) {
1727
+ async function I(e, t = {}) {
1698
1728
  let n = new AbortController(), r = t.timeout ? setTimeout(() => n.abort(), t.timeout) : null;
1699
1729
  try {
1700
1730
  let r = await fetch(e, {
@@ -1710,7 +1740,7 @@ async function H(e, t = {}) {
1710
1740
  r && clearTimeout(r);
1711
1741
  }
1712
1742
  }
1713
- async function U(e, t = {}) {
1743
+ async function L(e, t = {}) {
1714
1744
  let n = new AbortController(), r = t.timeout ? setTimeout(() => n.abort(), t.timeout) : null;
1715
1745
  try {
1716
1746
  let r = await fetch(e, {
@@ -1727,7 +1757,7 @@ async function U(e, t = {}) {
1727
1757
  }
1728
1758
  }
1729
1759
  // src/io/websocket.ts
1730
- var Ae = class {
1760
+ var Ie = class {
1731
1761
  constructor() {
1732
1762
  r(this, "socket", null), r(this, "closedByUs", !1), r(this, "onData", void 0), r(this, "onText", void 0), r(this, "onClose", void 0), r(this, "onError", void 0);
1733
1763
  }
@@ -1764,36 +1794,36 @@ var Ae = class {
1764
1794
  e?.close();
1765
1795
  } catch {}
1766
1796
  }
1767
- }, je = class {
1797
+ }, Le = class {
1768
1798
  constructor() {
1769
1799
  r(this, "transport", null);
1770
1800
  }
1771
1801
  async start(e, t, n = {}) {
1772
- let r = new Ae();
1802
+ let r = new Ie();
1773
1803
  this.transport = r, r.onData = t.onData, r.onError = t.onError, r.onClose = () => t.onEnd(), await r.connect(e, n);
1774
1804
  }
1775
1805
  stop() {
1776
1806
  this.transport?.close(), this.transport = null;
1777
1807
  }
1778
- }, Me = class {
1808
+ }, Re = class {
1779
1809
  constructor(e, t, n, i, a) {
1780
- r(this, "url", void 0), r(this, "options", void 0), r(this, "ctx", void 0), r(this, "protocol", void 0), r(this, "demuxer", void 0), r(this, "http", new ke()), r(this, "ws", null), r(this, "_live", void 0), this.url = t, this.options = n, this.ctx = i, this.protocol = e, this._live = a ?? (e === "flv" || e === "ws-flv");
1810
+ r(this, "url", void 0), r(this, "options", void 0), r(this, "ctx", void 0), r(this, "protocol", void 0), r(this, "demuxer", void 0), r(this, "http", new Fe()), r(this, "ws", null), r(this, "_live", void 0), r(this, "liveOverride", void 0), this.url = t, this.options = n, this.ctx = i, this.protocol = e, this.liveOverride = a, this._live = a ?? (e === "flv" || e === "ws-flv");
1781
1811
  let o = {
1782
1812
  onTracks: (e) => i.onTracks(e),
1783
1813
  onSample: (e) => i.onSample(e),
1784
1814
  onError: (e) => i.onError(e)
1785
1815
  };
1786
- this.demuxer = e === "mp4" || e === "fmp4" ? new V(o) : new De(o);
1816
+ this.demuxer = e === "mp4" || e === "fmp4" ? new F(o) : new Me(o);
1787
1817
  }
1788
1818
  get live() {
1789
1819
  return this._live;
1790
1820
  }
1791
1821
  get duration() {
1792
- return this.demuxer instanceof V ? this.demuxer.duration : void 0;
1822
+ if (this.demuxer instanceof Me || this.demuxer instanceof F) return this.demuxer.duration;
1793
1823
  }
1794
1824
  async start() {
1795
1825
  if (this.protocol === "ws-flv") {
1796
- let e = new je();
1826
+ let e = new Le();
1797
1827
  this.ws = e, await e.start(this.url, {
1798
1828
  onData: (e) => {
1799
1829
  this.ctx.onBytes?.(e.byteLength), this.demuxer.push(e);
@@ -1809,7 +1839,9 @@ var Ae = class {
1809
1839
  this.demuxer.flush(), this.ctx.onEnd();
1810
1840
  },
1811
1841
  onError: (e) => this.ctx.onError(e),
1812
- onResponse: (e) => this.sniff(e.contentType)
1842
+ onResponse: (e) => {
1843
+ this.sniff(e.contentType), this.liveOverride === void 0 && e.contentLength !== null && e.contentLength > 0 && this._live && (this._live = !1, this.ctx.onLive?.(!1));
1844
+ }
1813
1845
  }, {
1814
1846
  headers: this.options.headers,
1815
1847
  timeout: this.options.timeout,
@@ -1833,14 +1865,14 @@ var Ae = class {
1833
1865
  }
1834
1866
  };
1835
1867
  // src/demux/hls.ts
1836
- function W(e, t) {
1868
+ function R(e, t) {
1837
1869
  try {
1838
1870
  return new URL(e, t).href;
1839
1871
  } catch {
1840
1872
  return e;
1841
1873
  }
1842
1874
  }
1843
- function G(e) {
1875
+ function z(e) {
1844
1876
  let t = {}, n = "", r = !1, i = [];
1845
1877
  for (let t = 0; t < e.length; t++) {
1846
1878
  let a = e[t];
@@ -1855,40 +1887,41 @@ function G(e) {
1855
1887
  }
1856
1888
  return t;
1857
1889
  }
1858
- function Ne(e) {
1890
+ function ze(e) {
1859
1891
  return e.split(/\r?\n/).map((e) => e.trim()).filter((e) => e.length > 0);
1860
1892
  }
1861
- function Pe(e, t) {
1862
- let n = [], r = Ne(e);
1893
+ function Be(e, t) {
1894
+ let n = [], r = ze(e);
1863
1895
  for (let e = 0; e < r.length; e++) {
1864
1896
  let i = r[e];
1865
1897
  if (!i.startsWith("#EXT-X-STREAM-INF:")) continue;
1866
- let a = G(i.slice(18)), o = "";
1898
+ let a = z(i.slice(18)), o = "";
1867
1899
  for (let t = e + 1; t < r.length; t++) if (!r[t].startsWith("#")) {
1868
1900
  o = r[t];
1869
1901
  break;
1870
1902
  }
1871
1903
  o && n.push({
1872
- uri: W(o, t),
1904
+ uri: R(o, t),
1873
1905
  bandwidth: Number(a.BANDWIDTH ?? 0),
1874
1906
  resolution: a.RESOLUTION,
1875
1907
  codecs: a.CODECS,
1876
1908
  frameRate: a["FRAME-RATE"] ? Number(a["FRAME-RATE"]) : void 0,
1877
- audioGroup: a.AUDIO
1909
+ audioGroup: a.AUDIO,
1910
+ subtitleGroup: a.SUBTITLES
1878
1911
  });
1879
1912
  }
1880
1913
  return n;
1881
1914
  }
1882
- function Fe(e, t) {
1915
+ function Ve(e, t) {
1883
1916
  let n = [];
1884
- for (let r of Ne(e)) {
1917
+ for (let r of ze(e)) {
1885
1918
  if (!r.startsWith("#EXT-X-MEDIA:")) continue;
1886
- let e = G(r.slice(13));
1919
+ let e = z(r.slice(13));
1887
1920
  e.TYPE && e["GROUP-ID"] && n.push({
1888
1921
  type: e.TYPE,
1889
1922
  groupId: e["GROUP-ID"],
1890
1923
  name: e.NAME ?? "",
1891
- uri: e.URI ? W(e.URI, t) : void 0,
1924
+ uri: e.URI ? R(e.URI, t) : void 0,
1892
1925
  default: e.DEFAULT === "YES",
1893
1926
  autoselect: e.AUTOSELECT === "YES",
1894
1927
  language: e.LANGUAGE
@@ -1896,87 +1929,145 @@ function Fe(e, t) {
1896
1929
  }
1897
1930
  return n;
1898
1931
  }
1899
- function Ie(e, t) {
1932
+ function He(e, t) {
1900
1933
  let [n, r] = e.split("@"), i = Number(n), a = r === void 0 ? t : Number(r);
1901
1934
  return {
1902
1935
  offset: Number.isFinite(a) ? a : 0,
1903
1936
  length: Number.isFinite(i) ? i : 0
1904
1937
  };
1905
1938
  }
1906
- function Le(e, t) {
1907
- let n = Ne(e), r = {
1939
+ function B(e, t) {
1940
+ let n = ze(e), r = {
1908
1941
  targetDuration: 4,
1909
1942
  mediaSequence: 0,
1943
+ discontinuitySequence: 0,
1944
+ partTarget: 1,
1945
+ canBlockReload: !1,
1910
1946
  segments: [],
1911
1947
  endList: !1,
1912
1948
  encrypted: !1
1913
- }, i = 0, a = !1, o, s, c, l, u = /* @__PURE__ */ new Map();
1949
+ }, i = 0, a = !1, o, s = [], c, l, u, d = /* @__PURE__ */ new Map();
1914
1950
  for (let e = 0; e < n.length; e++) {
1915
- let d = n[e];
1916
- if (d.startsWith("#EXT-X-TARGETDURATION:")) {
1917
- r.targetDuration = Number(d.slice(22)) || 4;
1951
+ let f = n[e];
1952
+ if (f.startsWith("#EXT-X-TARGETDURATION:")) {
1953
+ r.targetDuration = Number(f.slice(22)) || 4;
1918
1954
  continue;
1919
1955
  }
1920
- if (d.startsWith("#EXT-X-MEDIA-SEQUENCE:")) {
1921
- r.mediaSequence = Number(d.slice(22)) || 0;
1956
+ if (f.startsWith("#EXT-X-MEDIA-SEQUENCE:")) {
1957
+ r.mediaSequence = Number(f.slice(22)) || 0;
1922
1958
  continue;
1923
1959
  }
1924
- if (d === "#EXT-X-ENDLIST") {
1960
+ if (f.startsWith("#EXT-X-DISCONTINUITY-SEQUENCE:")) {
1961
+ r.discontinuitySequence = Number(f.slice(30)) || 0;
1962
+ continue;
1963
+ }
1964
+ if (f.startsWith("#EXT-X-PART-INF:")) {
1965
+ let e = z(f.slice(16)), t = Number(e["PART-TARGET"]);
1966
+ Number.isFinite(t) && t > 0 && (r.partTarget = t);
1967
+ continue;
1968
+ }
1969
+ if (f.startsWith("#EXT-X-SERVER-CONTROL:")) {
1970
+ let e = z(f.slice(22));
1971
+ r.canBlockReload = e["CAN-BLOCK-RELOAD"] === "YES";
1972
+ let t = Number(e["PART-HOLD-BACK"]);
1973
+ Number.isFinite(t) && t > 0 && (r.partHoldBack = t);
1974
+ continue;
1975
+ }
1976
+ if (f.startsWith("#EXT-X-PART:")) {
1977
+ let e = z(f.slice(12)), n = e.GAP === "YES";
1978
+ if (e.URI) {
1979
+ let r = R(e.URI, t), i;
1980
+ e.BYTERANGE && (i = He(e.BYTERANGE, d.get(r) ?? 0), d.set(r, i.offset + i.length)), s.push({
1981
+ uri: r,
1982
+ duration: Number(e.DURATION) || 0,
1983
+ independent: e.INDEPENDENT === "YES",
1984
+ gap: n,
1985
+ byterange: i
1986
+ });
1987
+ } else n && s.push({
1988
+ uri: "",
1989
+ duration: Number(e.DURATION) || 0,
1990
+ independent: !1,
1991
+ gap: !0
1992
+ });
1993
+ continue;
1994
+ }
1995
+ if (f === "#EXT-X-ENDLIST") {
1925
1996
  r.endList = !0;
1926
1997
  continue;
1927
1998
  }
1928
- if (d === "#EXT-X-DISCONTINUITY") {
1999
+ if (f === "#EXT-X-DISCONTINUITY") {
1929
2000
  a = !0;
1930
2001
  continue;
1931
2002
  }
1932
- if (d.startsWith("#EXTINF:")) {
1933
- i = Number(d.slice(8).split(",")[0]) || 0;
2003
+ if (f.startsWith("#EXTINF:")) {
2004
+ i = Number(f.slice(8).split(",")[0]) || 0;
1934
2005
  continue;
1935
2006
  }
1936
- if (d.startsWith("#EXT-X-BYTERANGE:")) {
1937
- let r = n[e + 1], i = r && !r.startsWith("#") ? u.get(W(r, t)) ?? 0 : 0;
1938
- o = Ie(d.slice(17), i);
2007
+ if (f.startsWith("#EXT-X-BYTERANGE:")) {
2008
+ let r = n[e + 1], i = r && !r.startsWith("#") ? d.get(R(r, t)) ?? 0 : 0;
2009
+ o = He(f.slice(17), i);
1939
2010
  continue;
1940
2011
  }
1941
- if (d.startsWith("#EXT-X-MAP:")) {
1942
- let e = G(d.slice(11));
1943
- e.URI && (s = W(e.URI, t), c = e.BYTERANGE ? Ie(e.BYTERANGE, 0) : void 0, r.map || (r.map = s, r.mapByterange = c));
2012
+ if (f.startsWith("#EXT-X-MAP:")) {
2013
+ let e = z(f.slice(11));
2014
+ e.URI && (c = R(e.URI, t), l = e.BYTERANGE ? He(e.BYTERANGE, 0) : void 0, r.map || (r.map = c, r.mapByterange = l));
1944
2015
  continue;
1945
2016
  }
1946
- if (d.startsWith("#EXT-X-KEY:")) {
1947
- let e = G(d.slice(11));
1948
- e.METHOD && e.METHOD !== "NONE" ? (r.encrypted = !0, l = {
2017
+ if (f.startsWith("#EXT-X-KEY:")) {
2018
+ let e = z(f.slice(11));
2019
+ e.METHOD && e.METHOD !== "NONE" ? (r.encrypted = !0, u = {
1949
2020
  method: e.METHOD,
1950
- uri: e.URI ? W(e.URI, t) : void 0
1951
- }) : l = void 0;
2021
+ uri: e.URI ? R(e.URI, t) : void 0,
2022
+ iv: e.IV,
2023
+ keyformat: e.KEYFORMAT
2024
+ }) : u = void 0;
1952
2025
  continue;
1953
2026
  }
1954
- if (d.startsWith("#")) continue;
1955
- let f = W(d, t), p = {
1956
- uri: f,
2027
+ if (f.startsWith("#")) continue;
2028
+ let p = R(f, t), m = {
2029
+ uri: p,
1957
2030
  duration: i,
1958
2031
  sequence: r.mediaSequence + r.segments.length,
1959
2032
  discontinuity: a,
1960
- map: s ?? r.map,
1961
- mapByterange: c ?? r.mapByterange,
1962
- key: l
2033
+ complete: !0,
2034
+ parts: s,
2035
+ map: c ?? r.map,
2036
+ mapByterange: l ?? r.mapByterange,
2037
+ key: u
1963
2038
  };
1964
- o ? (p.byterange = o, u.set(f, o.offset + o.length)) : u.delete(f), r.segments.push(p), i = 0, a = !1, o = void 0;
1965
- }
1966
- return r;
2039
+ o ? (m.byterange = o, d.set(p, o.offset + o.length)) : d.delete(p), r.segments.push(m), i = 0, a = !1, o = void 0, s = [];
2040
+ }
2041
+ return s.length > 0 && r.segments.push({
2042
+ uri: "",
2043
+ duration: s.reduce((e, t) => e + t.duration, 0),
2044
+ sequence: r.mediaSequence + r.segments.length,
2045
+ discontinuity: a,
2046
+ complete: !1,
2047
+ parts: s,
2048
+ map: c ?? r.map,
2049
+ mapByterange: l ?? r.mapByterange,
2050
+ key: u
2051
+ }), r;
1967
2052
  }
1968
- function Re(e, t) {
2053
+ function Ue(e, t) {
1969
2054
  if (e.length === 0) return null;
1970
2055
  let n = t ? e.filter((e) => !e.bandwidth || e.bandwidth <= t) : e;
1971
2056
  return [...n.length > 0 ? n : e].sort((e, t) => t.bandwidth - e.bandwidth)[0] ?? null;
1972
2057
  }
1973
2058
  // src/demux/ts.ts
1974
- var K = 9e4, ze = 188;
1975
- function Be(e, t) {
2059
+ var V = 9e4, We = 188;
2060
+ function Ge(e, t) {
2061
+ if (e === t) return !0;
2062
+ if (!e || !t || e.byteLength !== t.byteLength) return !1;
2063
+ for (let n = 0; n < e.length; n++) if (e[n] !== t[n]) return !1;
2064
+ return !0;
2065
+ }
2066
+ function Ke(e, t) {
1976
2067
  let n = e[t], r = e[t + 1], i = e[t + 2], a = e[t + 3], o = e[t + 4];
1977
2068
  return (n >> 1 & 7) * 1073741824 + (r << 22) + ((i >> 1 & 127) << 15) + (a << 7) + (o >> 1 & 127);
1978
2069
  }
1979
- var Ve = class {
2070
+ var qe = class {
1980
2071
  constructor() {
1981
2072
  r(this, "buf", new g(8192)), r(this, "parsed", !1), r(this, "invalid", !1), r(this, "payloadOffset", 9), r(this, "declaredLength", 0), r(this, "pts", -1), r(this, "dts", -1);
1982
2073
  }
@@ -2007,10 +2098,10 @@ var Ve = class {
2007
2098
  if (this.payloadOffset = 9 + n, t & 128) {
2008
2099
  if (this.buf.length < 14) return;
2009
2100
  let e = this.buf.peek(14);
2010
- if (this.pts = Be(e, 9), t & 64) {
2101
+ if (this.pts = Ke(e, 9), t & 64) {
2011
2102
  if (this.buf.length < 19) return;
2012
2103
  let e = this.buf.peek(19);
2013
- this.dts = Be(e, 14);
2104
+ this.dts = Ke(e, 14);
2014
2105
  } else this.dts = this.pts;
2015
2106
  } else this.dts = -1;
2016
2107
  this.parsed = !0;
@@ -2019,9 +2110,9 @@ var Ve = class {
2019
2110
  let e = this.buf.peek(this.buf.length), t = this.declaredLength > 0 ? Math.min(e.length, 6 + this.declaredLength) : e.length, n = e.slice(Math.min(this.payloadOffset, t), t);
2020
2111
  return this.reset(), n;
2021
2112
  }
2022
- }, He = class {
2113
+ }, Je = class {
2023
2114
  constructor(e) {
2024
- r(this, "sink", void 0), r(this, "format", "ts"), r(this, "buf", new g(65536)), r(this, "packetSize", ze), r(this, "syncOffset", 0), r(this, "synced", !1), r(this, "pmtPid", -1), r(this, "streams", /* @__PURE__ */ new Map()), r(this, "tracks", /* @__PURE__ */ new Map()), r(this, "videoPid", -1), r(this, "audioPid", -1), r(this, "warned", /* @__PURE__ */ new Set()), this.sink = e;
2115
+ r(this, "sink", void 0), r(this, "format", "ts"), r(this, "buf", new g(65536)), r(this, "packetSize", We), r(this, "syncOffset", 0), r(this, "synced", !1), r(this, "pmtPid", -1), r(this, "streams", /* @__PURE__ */ new Map()), r(this, "tracks", /* @__PURE__ */ new Map()), r(this, "videoPid", -1), r(this, "audioPid", -1), r(this, "warned", /* @__PURE__ */ new Set()), this.sink = e;
2025
2116
  }
2026
2117
  push(e) {
2027
2118
  this.buf.append(e), this.parse();
@@ -2115,7 +2206,7 @@ var Ve = class {
2115
2206
  pid: e,
2116
2207
  kind: t,
2117
2208
  codec: n,
2118
- acc: new Ve(),
2209
+ acc: new qe(),
2119
2210
  lastRawDts: -1,
2120
2211
  wrapOffset: 0,
2121
2212
  auNals: [],
@@ -2141,7 +2232,7 @@ var Ve = class {
2141
2232
  }
2142
2233
  handleVideoPes(e, t, n, r) {
2143
2234
  e.curPesPts = n, e.curPesDts = r, e.auIndex = 0;
2144
- let i = A(t);
2235
+ let i = ce(t);
2145
2236
  for (let t of i) {
2146
2237
  if (t.length === 0) continue;
2147
2238
  let n = e.codec === "avc" ? t[0] & 31 : t[0] >> 1 & 63;
@@ -2172,45 +2263,46 @@ var Ve = class {
2172
2263
  }
2173
2264
  }
2174
2265
  maybeBuildVideoTrack(e) {
2175
- if (!e.sps || !e.pps || this.tracks.has(1)) return;
2266
+ if (!e.sps || !e.pps) return;
2176
2267
  let t = null;
2177
2268
  if (e.codec === "avc") {
2178
- let n = ce(e.sps), r = le([e.sps], [e.pps], n);
2269
+ let n = de(e.sps), r = fe([e.sps], [e.pps], n);
2179
2270
  t = {
2180
2271
  kind: "video",
2181
2272
  id: 1,
2182
2273
  codec: "avc",
2183
- timescale: K,
2274
+ timescale: V,
2184
2275
  width: n.width,
2185
2276
  height: n.height,
2186
2277
  fps: n.fps,
2187
2278
  codecPrivate: r,
2188
2279
  profile: n.profile,
2189
2280
  level: n.level
2190
- }, e.frameDuration = Math.round(K / (n.fps && n.fps > 1 ? n.fps : 25));
2281
+ }, e.frameDuration = Math.round(V / (n.fps && n.fps > 1 ? n.fps : 25));
2191
2282
  } else {
2192
2283
  if (!e.vps) return;
2193
- let n = _e(e.sps), r = ve(n, e.vps, e.sps, e.pps);
2284
+ let n = be(e.sps), r = xe(n, e.vps, e.sps, e.pps);
2194
2285
  t = {
2195
2286
  kind: "video",
2196
2287
  id: 1,
2197
2288
  codec: "hevc",
2198
- timescale: K,
2289
+ timescale: V,
2199
2290
  width: n.width,
2200
2291
  height: n.height,
2201
2292
  codecPrivate: r,
2202
2293
  profile: n.profileIdc,
2203
2294
  level: n.levelIdc
2204
- }, e.frameDuration = Math.round(K / 25);
2295
+ }, e.frameDuration = Math.round(V / 25);
2205
2296
  }
2206
- this.tracks.set(1, t), this.sink.onTracks([...this.tracks.values()]);
2297
+ let n = this.tracks.get(1);
2298
+ n?.kind === "video" && n.codec === t.codec && n.width === t.width && n.height === t.height && Ge(n.codecPrivate, t.codecPrivate) || (this.tracks.set(1, t), this.sink.onTracks([...this.tracks.values()]));
2207
2299
  }
2208
2300
  flushAu(e) {
2209
2301
  if (!e.auHasVcl || e.auNals.length === 0) {
2210
2302
  e.auNals = [], e.auHasVcl = !1;
2211
2303
  return;
2212
2304
  }
2213
- let t = oe(e.auNals), n = e.auIndex === 0 ? e.curPesPts : e.curPesPts + e.auIndex * e.frameDuration, r = e.auIndex === 0 ? e.curPesDts : e.curPesDts + e.auIndex * e.frameDuration, i = e.auNals.find((t) => {
2305
+ let t = le(e.auNals), n = e.auIndex === 0 ? e.curPesPts : e.curPesPts + e.auIndex * e.frameDuration, r = e.auIndex === 0 ? e.curPesDts : e.curPesDts + e.auIndex * e.frameDuration, i = e.auNals.find((t) => {
2214
2306
  let n = e.codec === "avc" ? t[0] & 31 : t[0] >> 1 & 63;
2215
2307
  return e.codec === "avc" ? n >= 1 && n <= 5 : n <= 31;
2216
2308
  }), a = !1;
@@ -2231,10 +2323,10 @@ var Ve = class {
2231
2323
  handleAudioPes(e, t, n) {
2232
2324
  let r = 0, i = 0;
2233
2325
  for (; r + 7 <= t.length;) {
2234
- let e = Se(t, r);
2326
+ let e = Te(t, r);
2235
2327
  if (!e || r + e.frameLength > t.length) break;
2236
2328
  this.tracks.has(2) || this.buildAudioTrack(e.sampleRate, e.channels, e.objectType);
2237
- let a = Math.max(1, Math.round(1024 * K / e.sampleRate));
2329
+ let a = Math.max(1, Math.round(1024 * V / e.sampleRate));
2238
2330
  this.sink.onSample({
2239
2331
  trackId: 2,
2240
2332
  kind: "audio",
@@ -2252,19 +2344,107 @@ var Ve = class {
2252
2344
  kind: "audio",
2253
2345
  id: 2,
2254
2346
  codec: "aac",
2255
- timescale: K,
2347
+ timescale: V,
2256
2348
  sampleRate: e,
2257
2349
  channels: t,
2258
- codecPrivate: P(n, e, t)
2350
+ codecPrivate: Ee(n, e, t)
2259
2351
  };
2260
2352
  this.tracks.set(2, r), this.sink.onTracks([...this.tracks.values()]);
2261
2353
  }
2262
2354
  warnOnce(e, t) {
2263
2355
  this.warned.has(e) || (this.warned.add(e), this.sink.onError?.(Error(t)));
2264
2356
  }
2265
- }, Ue = class {
2266
- constructor(e, t, n, i = 0) {
2267
- r(this, "url", void 0), r(this, "options", void 0), r(this, "ctx", void 0), r(this, "startMs", void 0), r(this, "protocol", "hls"), r(this, "tracks", []), r(this, "stopped", !1), r(this, "_live", !1), r(this, "mediaDuration", 0), r(this, "audioOnly", !1), this.url = e, this.options = t, this.ctx = n, this.startMs = i;
2357
+ }, H = 16;
2358
+ function Ye(e) {
2359
+ let t = new Uint8Array(H), n = Number.isFinite(e) ? Math.max(0, Math.floor(e)) : 0;
2360
+ for (let e = 15; e >= 0 && n > 0; e--) t[e] = n % 256, n = Math.floor(n / 256);
2361
+ return t;
2362
+ }
2363
+ function Xe(e) {
2364
+ if (!e) return null;
2365
+ let t = e.trim();
2366
+ if ((t.startsWith("0x") || t.startsWith("0X")) && (t = t.slice(2)), t.length === 0 || t.length > 32 || !/^[0-9a-fA-F]+$/.test(t)) return null;
2367
+ t = t.padStart(32, "0");
2368
+ let n = new Uint8Array(H);
2369
+ for (let e = 0; e < H; e++) n[e] = Number.parseInt(t.slice(e * 2, e * 2 + 2), 16);
2370
+ return n;
2371
+ }
2372
+ function Ze(e, t) {
2373
+ return Xe(e) ?? Ye(t);
2374
+ }
2375
+ async function Qe(e) {
2376
+ if (e.byteLength !== H) throw new i("HLS_KEY_INVALID", `AES-128 key must be 16 bytes, got ${e.byteLength}`);
2377
+ let t = globalThis.crypto?.subtle;
2378
+ if (!t) throw new i("HLS_DECRYPT_UNSUPPORTED", "WebCrypto AES-CBC is unavailable (HLS AES-128 requires a secure context)");
2379
+ try {
2380
+ return await t.importKey("raw", e, { name: "AES-CBC" }, !1, ["decrypt"]);
2381
+ } catch (e) {
2382
+ throw new i("HLS_KEY_INVALID", "could not import the AES-128 key", e);
2383
+ }
2384
+ }
2385
+ async function $e(e) {
2386
+ if (e.byteLength !== 32) throw new i("HLS_KEY_INVALID", `AES-256-GCM key must be 32 bytes, got ${e.byteLength}`);
2387
+ let t = globalThis.crypto?.subtle;
2388
+ if (!t) throw new i("HLS_DECRYPT_UNSUPPORTED", "WebCrypto AES-GCM is unavailable (HLS AES-256-GCM requires a secure context)");
2389
+ try {
2390
+ return await t.importKey("raw", e, { name: "AES-GCM" }, !1, ["decrypt"]);
2391
+ } catch (e) {
2392
+ throw new i("HLS_KEY_INVALID", "could not import the AES-256-GCM key", e);
2393
+ }
2394
+ }
2395
+ async function et(e, t) {
2396
+ if (t.byteLength < 32) throw new i("HLS_DECRYPT_FAILED", "AES-256-GCM segment is shorter than IV + tag");
2397
+ let n = globalThis.crypto?.subtle;
2398
+ if (!n) throw new i("HLS_DECRYPT_UNSUPPORTED", "WebCrypto AES-GCM is unavailable (HLS AES-256-GCM requires a secure context)");
2399
+ try {
2400
+ let r = await n.decrypt({
2401
+ name: "AES-GCM",
2402
+ iv: t.subarray(0, 16),
2403
+ tagLength: 128
2404
+ }, e, t.subarray(16));
2405
+ return new Uint8Array(r);
2406
+ } catch (e) {
2407
+ throw new i("HLS_DECRYPT_FAILED", "AES-256-GCM decryption failed (wrong key, corrupt segment, or authentication tag)", e);
2408
+ }
2409
+ }
2410
+ async function tt(e, t, n) {
2411
+ let r = globalThis.crypto?.subtle;
2412
+ if (!r) throw new i("HLS_DECRYPT_UNSUPPORTED", "WebCrypto AES-CBC is unavailable (HLS AES-128 requires a secure context)");
2413
+ try {
2414
+ let i = await r.decrypt({
2415
+ name: "AES-CBC",
2416
+ iv: t
2417
+ }, e, n);
2418
+ return new Uint8Array(i);
2419
+ } catch (e) {
2420
+ throw new i("HLS_DECRYPT_FAILED", "AES-128 decryption failed (wrong key/IV or corrupt segment)", e);
2421
+ }
2422
+ }
2423
+ // src/source/abr.ts
2424
+ function nt(e) {
2425
+ let { variants: t, currentUri: n } = e;
2426
+ if (t.length < 2) return null;
2427
+ let r = t.findIndex((e) => e.uri === n);
2428
+ if (r < 0) return null;
2429
+ let i = e.live ? Math.min(e.highBuffer, Math.max(4, e.liveBufferTarget * 2)) : e.highBuffer;
2430
+ if (e.buffer < e.lowBuffer && r > 0) {
2431
+ let n = t[r];
2432
+ if (!e.throughput || e.throughput < n.bandwidth * 1.1) return t[r - 1];
2433
+ }
2434
+ if (e.buffer > i && r < t.length - 1) {
2435
+ let n = t[r + 1];
2436
+ if (!e.throughput || e.throughput > n.bandwidth * 1.25) return n;
2437
+ }
2438
+ return null;
2439
+ }
2440
+ function U(e) {
2441
+ let t = e?.split(",")[0]?.trim().toLowerCase();
2442
+ return t ? t.startsWith("avc1") || t.startsWith("avc3") ? "avc" : t.startsWith("hvc1") || t.startsWith("hev1") ? "hevc" : t.split(".")[0] : null;
2443
+ }
2444
+ // src/source/hls.ts
2445
+ var W = class {
2446
+ constructor(e, t, n, i = 0, a, o) {
2447
+ r(this, "url", void 0), r(this, "options", void 0), r(this, "ctx", void 0), r(this, "startMs", void 0), r(this, "preferredBandwidth", void 0), r(this, "protocol", "hls"), r(this, "tracks", []), r(this, "stopped", !1), r(this, "_live", !1), r(this, "mediaDuration", 0), r(this, "audioOnly", !1), r(this, "audioRenditions", []), r(this, "subtitleRenditions", []), r(this, "activeAudioId", null), r(this, "preferredAudioId", void 0), r(this, "variants", []), r(this, "manualBandwidth", null), r(this, "switchTarget", null), r(this, "lastSwitchAt", 0), r(this, "throughputBps", 0), r(this, "keyCache", /* @__PURE__ */ new Map()), this.url = e, this.options = t, this.ctx = n, this.startMs = i, this.preferredBandwidth = o, this.preferredAudioId = a;
2268
2448
  }
2269
2449
  get duration() {
2270
2450
  return this.mediaDuration;
@@ -2272,98 +2452,184 @@ var Ve = class {
2272
2452
  get live() {
2273
2453
  return this._live;
2274
2454
  }
2455
+ get variantBandwidth() {
2456
+ return this.tracks.find((e) => !e.isAudio)?.variant?.bandwidth ?? 0;
2457
+ }
2458
+ get audioTracks() {
2459
+ return this.audioRenditions.map((e) => ({
2460
+ id: e.id,
2461
+ label: e.label,
2462
+ language: e.language,
2463
+ default: e.default,
2464
+ active: e.id === this.activeAudioId
2465
+ }));
2466
+ }
2467
+ get subtitleTracks() {
2468
+ return this.subtitleRenditions.map((e) => ({
2469
+ id: e.id,
2470
+ label: e.label,
2471
+ language: e.language,
2472
+ default: e.default,
2473
+ active: !1,
2474
+ uri: e.uri
2475
+ }));
2476
+ }
2275
2477
  async start() {
2276
- let e = await H(this.url, {
2478
+ let e = await I(this.url, {
2277
2479
  headers: this.options.headers,
2278
2480
  timeout: this.options.timeout
2279
- }), t = this.url, n = null, r = [];
2280
- if (e.includes("#EXT-X-STREAM-INF")) {
2281
- if (n = Re(Pe(e, this.url), this.options.hls.maxBandwidth), !n) throw new i("HLS_NO_VARIANTS", "master playlist has no playable variant");
2481
+ }), t = this.url, n = null, r = Ve(e, this.url);
2482
+ this.audioRenditions = r.filter((e) => e.type === "AUDIO" && e.uri).map((e, t) => ({
2483
+ id: `audio-${t}`,
2484
+ label: e.name || e.language || `Audio ${t + 1}`,
2485
+ language: e.language,
2486
+ default: e.default || e.autoselect,
2487
+ uri: e.uri,
2488
+ groupId: e.groupId
2489
+ }));
2490
+ let a = /* @__PURE__ */ new Set(["SUBTITLES", "SUBTITLE"]);
2491
+ if (this.subtitleRenditions = r.filter((e) => a.has(e.type) && e.uri).map((e, t) => ({
2492
+ id: `subtitle-${t}`,
2493
+ label: e.name || e.language || `Subtitles ${t + 1}`,
2494
+ language: e.language,
2495
+ default: e.default,
2496
+ uri: e.uri,
2497
+ groupId: e.groupId
2498
+ })), e.includes("#EXT-X-STREAM-INF")) {
2499
+ let r = Be(e, this.url);
2500
+ if (this.variants = r, n = Ue(r, this.options.hls.maxBandwidth), !n) throw new i("HLS_NO_VARIANTS", "master playlist has no playable variant");
2501
+ if (this.preferredBandwidth) {
2502
+ let e = this.options.hls.maxBandwidth, t = r.filter((t) => t.bandwidth > 0 && (!e || t.bandwidth <= e)).sort((e, t) => e.bandwidth - t.bandwidth);
2503
+ n = t.filter((e) => e.bandwidth <= this.preferredBandwidth).pop() ?? t[0] ?? n, this.manualBandwidth = this.preferredBandwidth;
2504
+ }
2282
2505
  t = n.uri;
2283
- let a = Fe(e, this.url).filter((e) => e.type === "AUDIO" && e.uri);
2284
- if (n.audioGroup) {
2285
- let e = a.filter((e) => e.groupId === n.audioGroup), t = a.filter((e) => e.groupId !== n.audioGroup);
2286
- r = [...e, ...t].map((e) => e.uri);
2287
- }
2288
- } else e.includes("#EXT-X-MEDIA:") && (r = Fe(e, this.url).filter((e) => e.type === "AUDIO" && e.uri).map((e) => e.uri));
2289
- r = [...new Set(r)];
2290
- let a = !!n && !n.resolution && /mp4a/i.test(n.codecs ?? "") && !/avc1|hvc1|hev1/i.test(n.codecs ?? "");
2291
- this.audioOnly = a;
2292
- let o = await this.createTrack(t, "main", !1);
2293
- if (this.tracks.push(o), r.length > 0 && !a) {
2506
+ }
2507
+ let o = n?.audioGroup, s = [...this.audioRenditions].sort((e, t) => {
2508
+ let n = (e) => e.id === this.preferredAudioId ? 0 : e.groupId === o ? 1 : 2;
2509
+ return n(e) - n(t) || (e.default ? -1 : 0) || +!!t.default;
2510
+ }), c = !!n && !n.resolution && /mp4a/i.test(n.codecs ?? "") && !/avc1|hvc1|hev1/i.test(n.codecs ?? "");
2511
+ this.audioOnly = c;
2512
+ let l = await this.createTrack(t, "main", !1, n ?? void 0);
2513
+ if (this.tracks.push(l), this.lastSwitchAt = performance.now(), s.length > 0 && !c) {
2294
2514
  let e = null;
2295
- for (let t of r) try {
2296
- let n = await this.createTrack(t, "audio", !0);
2297
- this.tracks.push(n), e = null;
2515
+ for (let t of s) try {
2516
+ let n = await this.createTrack(t.uri, "audio", !0);
2517
+ this.tracks.push(n), this.activeAudioId = t.id, e = null;
2298
2518
  break;
2299
2519
  } catch (t) {
2300
2520
  e = t;
2301
2521
  }
2302
2522
  e && this.ctx.onError(new i("HLS_AUDIO_FAILED", "no playable alternate audio rendition", e));
2303
2523
  }
2304
- this._live = this.tracks.some((e) => !e.playlist.endList), this.mediaDuration = Math.max(0, ...this.tracks.map((e) => e.playlist.segments.reduce((e, t) => e + t.duration, 0)));
2524
+ this._live = this.tracks.some((e) => !e.playlist.endList), this.ctx.onLive?.(this._live), this.mediaDuration = Math.max(0, ...this.tracks.map((e) => e.playlist.segments.reduce((e, t) => e + t.duration, 0)));
2305
2525
  for (let e of this.tracks) this.runLoop(e);
2306
2526
  }
2307
- async createTrack(e, t, n) {
2308
- let r = Le(await H(e, {
2309
- headers: this.options.headers,
2310
- timeout: this.options.timeout
2311
- }), e);
2312
- if (r.segments.length === 0) throw new i("HLS_EMPTY", `HLS playlist ${e} has no segments`);
2313
- let a = !!r.map || r.segments.some((e) => /\.(m4s|mp4|cmfv|cmfa)$/i.test(Ge(e.uri))), o = !1, s = {
2314
- onTracks: (e) => {
2315
- e.length > 0 && (o = !0), this.ctx.onTracks(n ? e.map(We) : e);
2527
+ createSink(e, t) {
2528
+ return {
2529
+ onTracks: (n) => {
2530
+ n.length > 0 && t?.(), this.ctx.onTracks(e ? n.map(rt) : n);
2316
2531
  },
2317
- onSample: (e) => this.ctx.onSample(n ? {
2318
- ...e,
2532
+ onSample: (t) => this.ctx.onSample(e ? {
2533
+ ...t,
2319
2534
  kind: "audio",
2320
2535
  trackId: 2
2321
- } : e),
2322
- onError: (e) => {
2323
- n && e instanceof i && e.code === "UNSUPPORTED_AUDIO" || this.ctx.onError(e);
2536
+ } : t),
2537
+ onError: (t) => {
2538
+ e && t instanceof i && t.code === "UNSUPPORTED_AUDIO" || this.ctx.onError(t);
2324
2539
  }
2325
- }, c = a ? new V(s) : new He(s);
2326
- if (a && r.map) {
2327
- let t = { ...this.options.headers };
2328
- if (r.mapByterange) {
2329
- let { offset: e, length: n } = r.mapByterange;
2330
- t.Range = `bytes=${e}-${e + n - 1}`;
2331
- }
2332
- let n = await U(r.map, {
2333
- headers: t,
2334
- timeout: this.options.timeout
2335
- });
2336
- if (c.push(n), !o) throw new i("HLS_UNSUPPORTED_TRACK", `the init segment of ${e} contains no supported track`);
2540
+ };
2541
+ }
2542
+ createDemuxer(e, t) {
2543
+ return e ? new F(t) : new Je(t);
2544
+ }
2545
+ async pushInit(e, t) {
2546
+ if (!t.map) return;
2547
+ let n = { ...this.options.headers };
2548
+ if (t.mapByterange) {
2549
+ let { offset: e, length: r } = t.mapByterange;
2550
+ n.Range = `bytes=${e}-${e + r - 1}`;
2337
2551
  }
2338
- let l = 0;
2552
+ let r = await L(t.map, {
2553
+ headers: n,
2554
+ timeout: this.options.timeout
2555
+ });
2556
+ e.push(r);
2557
+ }
2558
+ async createTrack(e, t, n, r) {
2559
+ let a = B(await I(e, {
2560
+ headers: this.options.headers,
2561
+ timeout: this.options.timeout
2562
+ }), e);
2563
+ if (a.segments.length === 0) throw new i("HLS_EMPTY", `HLS playlist ${e} has no segments`);
2564
+ let o = !!a.map || a.segments.some((e) => /\.(m4s|mp4|cmfv|cmfa)$/i.test(it(e.uri))), s = !1, c = this.createSink(n, () => {
2565
+ s = !0;
2566
+ }), l = this.createDemuxer(o, c);
2567
+ if (o && a.map && (await this.pushInit(l, a), !s)) throw new i("HLS_UNSUPPORTED_TRACK", `the init segment of ${e} contains no supported track`);
2568
+ let u = 0;
2339
2569
  if (this.startMs > 0) {
2340
- let e = 0;
2341
- for (; l < r.segments.length - 1 && e * 1e3 < this.startMs;) e += r.segments[l].duration, l++;
2342
- }
2570
+ let e = this.startMs / 1e3, t = 0;
2571
+ for (; u < a.segments.length - 1 && t + a.segments[u].duration <= e;) t += a.segments[u].duration, u++;
2572
+ } else a.endList || (u = Math.max(0, a.segments.length - 1));
2343
2573
  return {
2344
2574
  label: t,
2345
2575
  url: e,
2346
- playlist: r,
2347
- demuxer: c,
2348
- index: l,
2576
+ playlist: a,
2577
+ demuxer: l,
2578
+ index: u,
2579
+ partIndex: 0,
2349
2580
  ended: !1,
2350
- isAudio: n
2581
+ isAudio: n,
2582
+ currentMap: a.map,
2583
+ currentMapByterange: a.mapByterange,
2584
+ pendingDiscontinuity: !1,
2585
+ variant: r,
2586
+ isFmp4: o
2351
2587
  };
2352
2588
  }
2353
2589
  async runLoop(e) {
2354
2590
  try {
2355
2591
  for (; !this.stopped;) {
2592
+ if (!e.isAudio && this.switchTarget && e.partIndex === 0) {
2593
+ let t = this.switchTarget;
2594
+ this.switchTarget = null, await this.switchVariant(e, t);
2595
+ }
2356
2596
  if (e.index >= e.playlist.segments.length) {
2357
2597
  if (e.playlist.endList) break;
2358
- await f(Math.max(300, e.playlist.targetDuration * 500)), await this.reload(e);
2598
+ await f(Math.max(300, e.playlist.targetDuration * 500));
2599
+ let t = e.playlist.segments[e.playlist.segments.length - 1], n = t ? t.sequence + 1 : e.playlist.mediaSequence;
2600
+ await this.reload(e, {
2601
+ msn: n,
2602
+ part: 0
2603
+ });
2359
2604
  continue;
2360
2605
  }
2361
- let t = e.playlist.segments[e.index++];
2362
- if (t.key && t.key.method !== "NONE") throw new i("HLS_ENCRYPTED", "AES-128 encrypted HLS is not supported yet");
2363
- t.discontinuity && e.demuxer.flush();
2364
- let n = await this.fetchSegment(t);
2365
- if (this.stopped) return;
2366
- this.ctx.onBytes?.(n.byteLength), e.demuxer.push(n), e.playlist.endList ? await this.waitForDemand() : await this.paceLive();
2606
+ let t = e.playlist.segments[e.index];
2607
+ if (this.assertKeySupported(t.key), !t.complete || e.partIndex > 0) {
2608
+ if (e.partIndex < t.parts.length) {
2609
+ e.partIndex === 0 && (t.discontinuity && (e.demuxer.flush(), this.ctx.onDiscontinuity?.()), await this.refreshMap(e, t));
2610
+ let n = t.parts[e.partIndex++];
2611
+ if (!n.gap) {
2612
+ let r = performance.now(), i = await this.fetchPart(n);
2613
+ if (this.recordDownload(i.byteLength, performance.now() - r), t.key && (i = await this.decrypt(i, t.key, t.sequence)), this.stopped) return;
2614
+ this.ctx.onBytes?.(i.byteLength), e.demuxer.push(i);
2615
+ }
2616
+ this.maybeAdapt(e), e.playlist.endList ? await this.waitForDemand() : await this.paceLive();
2617
+ continue;
2618
+ }
2619
+ if (t.complete) {
2620
+ e.index++, e.partIndex = 0, this.prunePlaylist(e), this.maybeAdapt(e);
2621
+ continue;
2622
+ }
2623
+ e.playlist.canBlockReload || await f(Math.max(200, e.playlist.partTarget * 250)), await this.reload(e, {
2624
+ msn: t.sequence,
2625
+ part: e.partIndex
2626
+ });
2627
+ continue;
2628
+ }
2629
+ e.index++, e.partIndex = 0, this.prunePlaylist(e), t.discontinuity && (e.demuxer.flush(), this.ctx.onDiscontinuity?.()), await this.refreshMap(e, t);
2630
+ let n = performance.now(), r = await this.fetchSegment(t);
2631
+ if (this.recordDownload(r.byteLength, performance.now() - n), t.key && (r = await this.decrypt(r, t.key, t.sequence)), this.stopped) return;
2632
+ this.ctx.onBytes?.(r.byteLength), e.demuxer.push(r), this.maybeAdapt(e), e.playlist.endList ? await this.waitForDemand() : await this.paceLive();
2367
2633
  }
2368
2634
  if (this.stopped) return;
2369
2635
  e.ended = !0, e.demuxer.flush(), this.tracks.every((e) => e.ended) && this.ctx.onEnd();
@@ -2371,25 +2637,185 @@ var Ve = class {
2371
2637
  this.stopped || this.ctx.onError(e instanceof Error ? e : Error(String(e)));
2372
2638
  }
2373
2639
  }
2374
- async fetchSegment(e) {
2375
- let t = { ...this.options.headers };
2376
- return e.byterange && (t.Range = `bytes=${e.byterange.offset}-${e.byterange.offset + e.byterange.length - 1}`), U(e.uri, {
2377
- headers: t,
2640
+ prunePlaylist(e) {
2641
+ if (e.index <= 60) return;
2642
+ let t = e.index - 30;
2643
+ t <= 0 || (e.playlist.segments.splice(0, t), e.index -= t);
2644
+ }
2645
+ async refreshMap(e, t) {
2646
+ let n = t.map;
2647
+ if (!n) return;
2648
+ let r = t.mapByterange, i = e.currentMapByterange;
2649
+ if (n === e.currentMap && (r?.offset ?? 0) === (i?.offset ?? 0) && (r?.length ?? 0) === (i?.length ?? 0)) return;
2650
+ let a = { ...this.options.headers };
2651
+ r && (a.Range = `bytes=${r.offset}-${r.offset + r.length - 1}`);
2652
+ let o = await L(n, {
2653
+ headers: a,
2378
2654
  timeout: this.options.timeout
2379
2655
  });
2656
+ this.stopped || (this.ctx.onBytes?.(o.byteLength), e.demuxer.push(o), e.currentMap = n, e.currentMapByterange = r);
2380
2657
  }
2381
- async reload(e) {
2382
- let t = Le(await H(e.url, {
2383
- headers: this.options.headers,
2384
- timeout: this.options.timeout
2385
- }), e.url), n = new Set(e.playlist.segments.map((e) => e.sequence));
2386
- e.playlist.endList = t.endList, e.playlist.targetDuration = t.targetDuration || e.playlist.targetDuration;
2387
- for (let r of t.segments) n.has(r.sequence) || e.playlist.segments.push(r);
2388
- this._live = this.tracks.some((e) => !e.playlist.endList);
2658
+ setQuality(e) {
2659
+ if (e === "auto") {
2660
+ this.manualBandwidth = null, this.switchTarget = null;
2661
+ return;
2662
+ }
2663
+ if (!Number.isFinite(e) || e <= 0) return;
2664
+ this.manualBandwidth = e;
2665
+ let t = this.tracks.find((e) => !e.isAudio), n = this.abrPool(t);
2666
+ if (n.length === 0) return;
2667
+ let r = n[0];
2668
+ for (let t of n) t.bandwidth <= e && t.bandwidth >= r.bandwidth && (r = t);
2669
+ this.switchTarget = t?.variant?.uri === r.uri ? null : r;
2670
+ }
2671
+ abrPool(e) {
2672
+ let t = this.options.hls.maxBandwidth, n = U(e?.variant?.codecs);
2673
+ return this.variants.filter((e) => e.bandwidth > 0 && (!t || e.bandwidth <= t)).filter((e) => !n || !e.codecs || U(e.codecs) === n).sort((e, t) => e.bandwidth - t.bandwidth);
2674
+ }
2675
+ recordDownload(e, t) {
2676
+ if (!(e > 0) || !(t > 0)) return;
2677
+ let n = e * 8e3 / t;
2678
+ this.throughputBps = this.throughputBps > 0 ? this.throughputBps * .6 + n * .4 : n;
2679
+ }
2680
+ maybeAdapt(e) {
2681
+ if (e.isAudio || !this.options.hls.abr || this.manualBandwidth !== null || this.switchTarget || this.variants.length < 2) return;
2682
+ let t = this.ctx.getRendererMode?.();
2683
+ if (t && t !== "mse") return;
2684
+ let n = this.abrPool(e);
2685
+ if (n.length < 2 || !e.variant || performance.now() - this.lastSwitchAt < 6e3) return;
2686
+ let r = this._live ? Math.min(this.options.hls.abrLowBuffer, Math.max(1, this.options.liveBufferTarget)) : this.options.hls.abrLowBuffer, i = nt({
2687
+ variants: n,
2688
+ currentUri: e.variant.uri,
2689
+ buffer: this.ctx.getBufferAhead?.() ?? 0,
2690
+ throughput: this.throughputBps || e.variant.bandwidth,
2691
+ live: this._live,
2692
+ liveBufferTarget: this.options.liveBufferTarget,
2693
+ lowBuffer: r,
2694
+ highBuffer: this.options.hls.abrHighBuffer
2695
+ });
2696
+ i && (this.switchTarget = i);
2697
+ }
2698
+ async switchVariant(e, t) {
2699
+ if (this.stopped || e.isAudio || e.variant?.uri === t.uri) return;
2700
+ let n = this.ctx.getRendererMode?.();
2701
+ if (n && n !== "mse") return;
2702
+ let r = U(e.variant?.codecs), i = U(t.codecs);
2703
+ if (!(r && i && r !== i)) try {
2704
+ let n = B(await I(t.uri, {
2705
+ headers: this.options.headers,
2706
+ timeout: this.options.timeout
2707
+ }), t.uri);
2708
+ if (n.segments.length === 0) return;
2709
+ let r = !!n.map || n.segments.some((e) => /\.(m4s|mp4|cmfv|cmfa)$/i.test(it(e.uri)));
2710
+ if (r !== e.isFmp4) return;
2711
+ let i = e.playlist.segments[e.index], a = i ? i.sequence : (e.playlist.segments[e.playlist.segments.length - 1]?.sequence ?? 0) + 1;
2712
+ i && !i.complete && e.partIndex > 0 && (a = i.sequence + 1);
2713
+ let o = n.segments.findIndex((e) => e.sequence >= a);
2714
+ if (o < 0) {
2715
+ if (n.endList) return;
2716
+ o = Math.max(0, n.segments.length - 1);
2717
+ }
2718
+ let s = n.segments[o], c = s?.map ?? n.map, l = s?.mapByterange ?? n.mapByterange;
2719
+ e.demuxer.flush();
2720
+ let u = !1, d = this.createSink(!1, () => {
2721
+ u = !0;
2722
+ }), f = this.createDemuxer(r, d);
2723
+ if (r && c && (await this.pushInit(f, {
2724
+ ...n,
2725
+ map: c,
2726
+ mapByterange: l
2727
+ }), !u)) return;
2728
+ e.url = t.uri, e.playlist = n, e.demuxer = f, e.index = o, e.partIndex = 0, e.currentMap = c, e.currentMapByterange = l, e.pendingDiscontinuity = !1, e.variant = t, e.isFmp4 = r, this.lastSwitchAt = performance.now(), this._live = this.tracks.some((e) => !e.playlist.endList), this.ctx.onLive?.(this._live), this.ctx.onVariantChange?.(t.bandwidth);
2729
+ } catch {}
2730
+ }
2731
+ assertKeySupported(e) {
2732
+ if (e && e.method !== "NONE") {
2733
+ if (e.method !== "AES-128" && e.method !== "AES-256-GCM") throw new i("HLS_ENCRYPTED", `unsupported HLS encryption method ${e.method} (AES-128 and AES-256-GCM are supported)`);
2734
+ if (e.keyformat && e.keyformat !== "identity") throw new i("HLS_ENCRYPTED", `unsupported HLS KEYFORMAT ${e.keyformat} (only identity is supported)`);
2735
+ if (!e.uri) throw new i("HLS_KEY_FAILED", "AES-128 EXT-X-KEY is missing its URI");
2736
+ }
2737
+ }
2738
+ async decrypt(e, t, n) {
2739
+ let r = await this.getKey(t);
2740
+ return t.method === "AES-256-GCM" ? et(r, e) : tt(r, Ze(t.iv, n), e);
2741
+ }
2742
+ async getKey(e) {
2743
+ let t = e.uri;
2744
+ if (!t) throw new i("HLS_KEY_FAILED", "HLS key URI is missing");
2745
+ let n = `${e.method}:${t}`, r = this.keyCache.get(n);
2746
+ if (r) return r;
2747
+ let a = (async () => {
2748
+ let n = null;
2749
+ for (let r = 0; r < 3; r++) try {
2750
+ let n = await L(t, {
2751
+ headers: this.options.headers,
2752
+ timeout: this.options.timeout
2753
+ });
2754
+ return e.method === "AES-256-GCM" ? await $e(n) : await Qe(n);
2755
+ } catch (e) {
2756
+ n = e, r < 2 && await f(300 * (r + 1));
2757
+ }
2758
+ throw n instanceof Error ? n : Error(String(n));
2759
+ })();
2760
+ return this.keyCache.set(n, a), a.catch(() => {
2761
+ this.keyCache.get(n) === a && this.keyCache.delete(n);
2762
+ }), a;
2763
+ }
2764
+ async fetchSegment(e) {
2765
+ return this.fetchUri(e.uri, e.byterange);
2766
+ }
2767
+ async fetchPart(e) {
2768
+ return this.fetchUri(e.uri, e.byterange);
2769
+ }
2770
+ async fetchUri(e, t) {
2771
+ let n = { ...this.options.headers };
2772
+ t && (n.Range = `bytes=${t.offset}-${t.offset + t.length - 1}`);
2773
+ let r = null;
2774
+ for (let t = 0; t < 3; t++) try {
2775
+ return await L(e, {
2776
+ headers: n,
2777
+ timeout: this.options.timeout
2778
+ });
2779
+ } catch (e) {
2780
+ r = e, t < 2 && await f(300 * (t + 1));
2781
+ }
2782
+ throw r instanceof Error ? r : Error(String(r));
2783
+ }
2784
+ async reload(e, t) {
2785
+ let n = !!t && e.playlist.canBlockReload, r = n ? this.blockingUrl(e.url, t) : e.url;
2786
+ for (let t = 0; t < 3; t++) try {
2787
+ let t = B(await I(r, {
2788
+ headers: this.options.headers,
2789
+ timeout: this.options.timeout
2790
+ }), e.url), { added: i, updated: a } = this.mergePlaylist(e, t);
2791
+ t.discontinuitySequence !== e.playlist.discontinuitySequence && (e.pendingDiscontinuity = !0), e.pendingDiscontinuity && i.length > 0 && (i[0].discontinuity = !0, e.pendingDiscontinuity = !1), e.playlist.endList = t.endList, e.playlist.targetDuration = t.targetDuration || e.playlist.targetDuration, e.playlist.partTarget = t.partTarget || e.playlist.partTarget, e.playlist.partHoldBack = t.partHoldBack ?? e.playlist.partHoldBack, e.playlist.canBlockReload = t.canBlockReload, e.playlist.discontinuitySequence = t.discontinuitySequence, this._live = this.tracks.some((e) => !e.playlist.endList), this.ctx.onLive?.(this._live), n && i.length === 0 && a === 0 && await f(150);
2792
+ return;
2793
+ } catch {
2794
+ t < 2 && await f(300 * (t + 1));
2795
+ }
2796
+ }
2797
+ blockingUrl(e, t) {
2798
+ try {
2799
+ let n = new URL(e);
2800
+ return n.searchParams.set("_HLS_msn", String(t.msn)), n.searchParams.set("_HLS_part", String(Math.max(0, t.part))), n.href;
2801
+ } catch {
2802
+ return e;
2803
+ }
2804
+ }
2805
+ mergePlaylist(e, t) {
2806
+ let n = new Map(e.playlist.segments.map((e) => [e.sequence, e])), r = [], i = 0;
2807
+ for (let a of t.segments) {
2808
+ let t = n.get(a.sequence);
2809
+ t ? ((t.parts.length !== a.parts.length || t.complete !== a.complete) && i++, t.parts = a.parts, t.complete = a.complete, a.uri && (t.uri = a.uri), a.duration > 0 && (t.duration = a.duration), a.map && (t.map = a.map, t.mapByterange = a.mapByterange), t.key = a.key, t.byterange = a.byterange, t.discontinuity = t.discontinuity || a.discontinuity) : (e.playlist.segments.push(a), n.set(a.sequence, a), r.push(a));
2810
+ }
2811
+ return {
2812
+ added: r,
2813
+ updated: i
2814
+ };
2389
2815
  }
2390
2816
  async waitForDemand() {
2391
2817
  for (;;) {
2392
- if (this.stopped || (this.ctx.getBufferAhead?.() ?? 0) < 30) return;
2818
+ if (this.stopped || this.switchTarget || (this.ctx.getBufferAhead?.() ?? 0) < 30) return;
2393
2819
  await f(250);
2394
2820
  }
2395
2821
  }
@@ -2403,13 +2829,13 @@ var Ve = class {
2403
2829
  this.stopped = !0;
2404
2830
  }
2405
2831
  };
2406
- function We(e) {
2832
+ function rt(e) {
2407
2833
  return e.kind === "audio" ? {
2408
2834
  ...e,
2409
2835
  id: 2
2410
2836
  } : e;
2411
2837
  }
2412
- function Ge(e) {
2838
+ function it(e) {
2413
2839
  try {
2414
2840
  return new URL(e).pathname;
2415
2841
  } catch {
@@ -2417,7 +2843,7 @@ function Ge(e) {
2417
2843
  }
2418
2844
  }
2419
2845
  // src/remux/fmp4.ts
2420
- var Ke = [
2846
+ var at = [
2421
2847
  65536,
2422
2848
  0,
2423
2849
  0,
@@ -2427,11 +2853,11 @@ var Ke = [
2427
2853
  0,
2428
2854
  0,
2429
2855
  1073741824
2430
- ], qe = 1e3;
2431
- function Je(e) {
2432
- for (let t of Ke) e.u32(t);
2856
+ ], ot = 1e3;
2857
+ function st(e) {
2858
+ for (let t of at) e.u32(t);
2433
2859
  }
2434
- function Ye() {
2860
+ function ct() {
2435
2861
  let e = new x();
2436
2862
  e.fourcc("iso5"), e.u32(512);
2437
2863
  for (let t of [
@@ -2443,48 +2869,48 @@ function Ye() {
2443
2869
  ]) e.fourcc(t);
2444
2870
  return S("ftyp", e.toUint8Array());
2445
2871
  }
2446
- function Xe() {
2872
+ function lt() {
2447
2873
  let e = new x();
2448
- e.u32(0).u32(0), e.u32(qe).u32(0), e.u32(65536), e.u16(256), e.u16(0), e.u32(0).u32(0), Je(e);
2874
+ e.u32(0).u32(0), e.u32(ot).u32(0), e.u32(65536), e.u16(256), e.u16(0), e.u32(0).u32(0), st(e);
2449
2875
  for (let t = 0; t < 6; t++) e.u32(0);
2450
2876
  return e.u32(3), C("mvhd", 0, 0, e.toUint8Array());
2451
2877
  }
2452
- function Ze(e, t) {
2878
+ function ut(e, t) {
2453
2879
  let n = new x();
2454
- return n.u32(0).u32(0), n.u32(t), n.u32(0), n.u32(0), n.u32(0).u32(0), n.u16(0), n.u16(0), n.u16(e.kind === "audio" ? 256 : 0), n.u16(0), Je(n), n.u32(e.kind === "video" ? w(e.width) : 0), n.u32(e.kind === "video" ? w(e.height) : 0), C("tkhd", 0, 3, n.toUint8Array());
2880
+ return n.u32(0).u32(0), n.u32(t), n.u32(0), n.u32(0), n.u32(0).u32(0), n.u16(0), n.u16(0), n.u16(e.kind === "audio" ? 256 : 0), n.u16(0), st(n), n.u32(e.kind === "video" ? w(e.width) : 0), n.u32(e.kind === "video" ? w(e.height) : 0), C("tkhd", 0, 3, n.toUint8Array());
2455
2881
  }
2456
- function Qe(e) {
2882
+ function dt(e) {
2457
2883
  let t = new x();
2458
2884
  return t.u32(0).u32(0), t.u32(e.timescale), t.u32(0), t.u16(21956), t.u16(0), C("mdhd", 0, 0, t.toUint8Array());
2459
2885
  }
2460
- function $e(e) {
2886
+ function ft(e) {
2461
2887
  let t = new x();
2462
2888
  return t.u32(0), t.fourcc(e.kind === "video" ? "vide" : "soun"), t.u32(0).u32(0).u32(0), t.cstring(e.kind === "video" ? "VideoHandler" : "SoundHandler"), C("hdlr", 0, 0, t.toUint8Array());
2463
2889
  }
2464
- function et() {
2890
+ function pt() {
2465
2891
  let e = new x();
2466
2892
  return e.u16(0), e.u16(0).u16(0).u16(0), C("vmhd", 0, 1, e.toUint8Array());
2467
2893
  }
2468
- function tt() {
2894
+ function mt() {
2469
2895
  let e = new x();
2470
2896
  return e.u16(0), e.u16(0), C("smhd", 0, 0, e.toUint8Array());
2471
2897
  }
2472
- function nt() {
2473
- return S("dinf", C("dref", 0, 0, rt(1), C("url ", 0, 1)));
2898
+ function ht() {
2899
+ return S("dinf", C("dref", 0, 0, gt(1), C("url ", 0, 1)));
2474
2900
  }
2475
- function rt(e) {
2901
+ function gt(e) {
2476
2902
  let t = new x(4);
2477
2903
  return t.u32(e), t.toUint8Array();
2478
2904
  }
2479
- function it(e, t, n) {
2905
+ function _t(e, t, n) {
2480
2906
  let r = new x();
2481
2907
  return r.raw(/* @__PURE__ */ new Uint8Array(6)), r.u16(1), r.u16(0), r.u16(0), r.u32(0).u32(0).u32(0), r.u16(t.width || 1920), r.u16(t.height || 1080), r.u32(4718592), r.u32(4718592), r.u32(0), r.u16(1), r.raw(/* @__PURE__ */ new Uint8Array(32)), r.u16(24), r.i16(-1), S(e, r.toUint8Array(), n);
2482
2908
  }
2483
- function at(e, t) {
2909
+ function vt(e, t) {
2484
2910
  let n = new x();
2485
2911
  return n.raw(/* @__PURE__ */ new Uint8Array(6)), n.u16(1), n.u32(0).u32(0), n.u16(e.channels || 2), n.u16(16), n.u16(0), n.u16(0), n.u32((e.sampleRate || 44100) << 16), S("mp4a", n.toUint8Array(), t);
2486
2912
  }
2487
- function q(e, t) {
2913
+ function G(e, t) {
2488
2914
  let n = [], r = t.length;
2489
2915
  do
2490
2916
  n.unshift(r & 127), r >>= 7;
@@ -2492,59 +2918,59 @@ function q(e, t) {
2492
2918
  for (let e = 0; e < n.length - 1; e++) n[e] |= 128;
2493
2919
  return _(Uint8Array.of(e, ...n), t);
2494
2920
  }
2495
- function ot(e) {
2921
+ function yt(e) {
2496
2922
  let t = new x();
2497
- t.u8(64), t.u8(21), t.u24(0), t.u32(e.sampleRate * e.channels * 2), t.u32(e.sampleRate * e.channels * 2);
2498
- let n = q(5, e.codecPrivate ?? Uint8Array.of(17, 144)), r = q(4, _(t.toUint8Array(), n)), i = new x();
2499
- return i.u16(1), i.u8(0), C("esds", 0, 0, q(3, _(i.toUint8Array(), r, q(6, Uint8Array.of(2)))));
2923
+ e.codec === "mp3" ? t.u8(107) : t.u8(64), t.u8(21), t.u24(0), t.u32(e.sampleRate * e.channels * 2), t.u32(e.sampleRate * e.channels * 2);
2924
+ let n = e.codec === "mp3" ? void 0 : G(5, e.codecPrivate ?? Uint8Array.of(17, 144)), r = G(4, _(t.toUint8Array(), n)), i = new x();
2925
+ return i.u16(1), i.u8(0), C("esds", 0, 0, G(3, _(i.toUint8Array(), r, G(6, Uint8Array.of(2)))));
2500
2926
  }
2501
- function st(e) {
2927
+ function bt(e) {
2502
2928
  let t;
2503
- return t = e.kind === "video" ? it(e.codec === "hevc" ? "hvc1" : "avc1", e, S(e.codec === "hevc" ? "hvcC" : "avcC", e.codecPrivate)) : at(e, ot(e)), C("stsd", 0, 0, rt(1), t);
2929
+ return t = e.kind === "video" ? _t(e.codec === "hevc" ? "hvc1" : "avc1", e, S(e.codec === "hevc" ? "hvcC" : "avcC", e.codecPrivate)) : vt(e, yt(e)), C("stsd", 0, 0, gt(1), t);
2504
2930
  }
2505
- function ct(e) {
2506
- let t = (e) => C(e, 0, 0, rt(0)), n = (() => {
2931
+ function xt(e) {
2932
+ let t = (e) => C(e, 0, 0, gt(0)), n = (() => {
2507
2933
  let e = new x();
2508
2934
  return e.u32(0), e.u32(0), C("stsz", 0, 0, e.toUint8Array());
2509
2935
  })();
2510
- return S("stbl", st(e), t("stts"), t("stsc"), n, t("stco"));
2936
+ return S("stbl", bt(e), t("stts"), t("stsc"), n, t("stco"));
2511
2937
  }
2512
- function lt(e) {
2513
- return S("minf", e.kind === "video" ? et() : tt(), nt(), ct(e));
2938
+ function St(e) {
2939
+ return S("minf", e.kind === "video" ? pt() : mt(), ht(), xt(e));
2514
2940
  }
2515
- function ut(e) {
2941
+ function Ct(e) {
2516
2942
  let t = new x();
2517
2943
  return t.u32(e), t.u32(1), t.u32(0), t.u32(0), t.u32(0), S("mvex", C("trex", 0, 0, t.toUint8Array()));
2518
2944
  }
2519
- function dt(e) {
2520
- let t = e.id || 1, n = S("moov", Xe(), S("trak", Ze(e, t), S("mdia", Qe(e), $e(e), lt(e))), ut(t));
2521
- return _(Ye(), n);
2945
+ function wt(e) {
2946
+ let t = e.id || 1, n = S("moov", lt(), S("trak", ut(e, t), S("mdia", dt(e), ft(e), St(e))), Ct(t));
2947
+ return _(ct(), n);
2522
2948
  }
2523
- function ft(e) {
2524
- return `video/mp4; codecs="${e.codec === "hevc" ? j(e.codecPrivate) : ue(e.codecPrivate)}"`;
2949
+ function Tt(e) {
2950
+ return `video/mp4; codecs="${e.codec === "hevc" ? O(e.codecPrivate) : pe(e.codecPrivate)}"`;
2525
2951
  }
2526
- function pt(e) {
2527
- return e.codec === "g711a" ? "audio/mp4; codecs=\"alaw\"" : e.codec === "g711u" ? "audio/mp4; codecs=\"ulaw\"" : e.codec === "opus" ? "audio/mp4; codecs=\"opus\"" : `audio/mp4; codecs="${e.codec === "aac" ? I(e.codecPrivate) : "mp4a.40.34"}"`;
2952
+ function Et(e) {
2953
+ return e.codec === "g711a" ? "audio/mp4; codecs=\"alaw\"" : e.codec === "g711u" ? "audio/mp4; codecs=\"ulaw\"" : e.codec === "opus" ? "audio/mp4; codecs=\"opus\"" : e.codec === "mp3" ? "audio/mp4; codecs=\"mp4a.6B\"" : `audio/mp4; codecs="${e.codec === "aac" ? De(e.codecPrivate) : "mp4a.40.34"}"`;
2528
2954
  }
2529
- function J(e) {
2530
- return e.kind === "video" ? ft(e) : pt(e);
2955
+ function K(e) {
2956
+ return e.kind === "video" ? Tt(e) : Et(e);
2531
2957
  }
2532
- function mt(e) {
2958
+ function Dt(e) {
2533
2959
  if (e.kind === "video") {
2534
- if (e.codec === "hevc") return `HEVC (${j(e.codecPrivate)})`;
2535
- let { profile: t, level: n } = de(e.codecPrivate);
2960
+ if (e.codec === "hevc") return `HEVC (${O(e.codecPrivate)})`;
2961
+ let { profile: t, level: n } = me(e.codecPrivate);
2536
2962
  return `H.264 (avc1.${t.toString(16).padStart(2, "0")}${n.toString(16).padStart(2, "0")})`;
2537
2963
  }
2538
2964
  return e.codec === "aac" ? "AAC" : e.codec === "g711a" ? "G.711 A-law" : e.codec === "g711u" ? "G.711 μ-law" : e.codec.toUpperCase();
2539
2965
  }
2540
- function ht(e) {
2966
+ function Ot(e) {
2541
2967
  if (e.kind === "video") {
2542
2968
  let t = e.fps && e.fps > 1 ? e.fps : 25;
2543
2969
  return Math.max(1, Math.round(e.timescale / t));
2544
2970
  }
2545
2971
  return Math.max(1, Math.round(1024 * e.timescale / (e.sampleRate || 48e3)));
2546
2972
  }
2547
- function gt(e, t, n, r, i) {
2973
+ function kt(e, t, n, r, i) {
2548
2974
  return S("moof", (() => {
2549
2975
  let t = new x();
2550
2976
  return t.u32(e), C("mfhd", 0, 0, t.toUint8Array());
@@ -2561,12 +2987,12 @@ function gt(e, t, n, r, i) {
2561
2987
  return C("trun", 1, 3841, e.toUint8Array());
2562
2988
  })()));
2563
2989
  }
2564
- var _t = class {
2990
+ var At = class {
2565
2991
  constructor(e) {
2566
- r(this, "track", void 0), r(this, "sequence", 1), r(this, "fallbackDuration", void 0), this.track = e, this.fallbackDuration = ht(e);
2992
+ r(this, "track", void 0), r(this, "sequence", 1), r(this, "fallbackDuration", void 0), this.track = e, this.fallbackDuration = Ot(e);
2567
2993
  }
2568
2994
  initSegment() {
2569
- return dt(this.track);
2995
+ return wt(this.track);
2570
2996
  }
2571
2997
  reset() {
2572
2998
  this.sequence = 1;
@@ -2578,8 +3004,8 @@ var _t = class {
2578
3004
  size: e.data.length,
2579
3005
  flags: e.keyframe ? 33554432 : 16842752,
2580
3006
  cts: Math.round(e.pts - e.dts)
2581
- })), i = this.sequence++, a = gt(i, this.track, n, r, 0).length + 8;
2582
- return _(gt(i, this.track, n, r, a), S("mdat", ...t.map((e) => e.data)));
3007
+ })), i = this.sequence++, a = kt(i, this.track, n, r, 0).length + 8;
3008
+ return _(kt(i, this.track, n, r, a), S("mdat", ...t.map((e) => e.data)));
2583
3009
  }
2584
3010
  normalize(e) {
2585
3011
  if (e.length <= 1) return e;
@@ -2590,56 +3016,75 @@ var _t = class {
2590
3016
  }), n = t[e].dts;
2591
3017
  return t;
2592
3018
  }
2593
- }, vt = /* @__PURE__ */ St(), yt = /* @__PURE__ */ Ct();
2594
- function bt(e) {
3019
+ }, jt = /* @__PURE__ */ Ft(), Mt = /* @__PURE__ */ It();
3020
+ function Nt(e) {
2595
3021
  let t = e ^ 85, n = (t & 15) << 4, r = (t & 112) >> 4;
2596
3022
  return r === 0 ? n += 8 : r === 1 ? n += 264 : (n += 264, n <<= r - 1), t & 128 ? n : -n;
2597
3023
  }
2598
- function xt(e) {
3024
+ function Pt(e) {
2599
3025
  let t = ~e & 255, n = ((t & 15) << 3) + 132;
2600
3026
  return n <<= (t & 112) >> 4, t & 128 ? 132 - n : n - 132;
2601
3027
  }
2602
- function St() {
3028
+ function Ft() {
2603
3029
  let e = /* @__PURE__ */ new Int16Array(256);
2604
- for (let t = 0; t < 256; t++) e[t] = bt(t);
3030
+ for (let t = 0; t < 256; t++) e[t] = Nt(t);
2605
3031
  return e;
2606
3032
  }
2607
- function Ct() {
3033
+ function It() {
2608
3034
  let e = /* @__PURE__ */ new Int16Array(256);
2609
- for (let t = 0; t < 256; t++) e[t] = xt(t);
3035
+ for (let t = 0; t < 256; t++) e[t] = Pt(t);
2610
3036
  return e;
2611
3037
  }
2612
- function wt(e, t) {
2613
- let n = t === "alaw" ? vt : yt, r = new Float32Array(e.length);
3038
+ function Lt(e, t) {
3039
+ let n = t === "alaw" ? jt : Mt, r = new Int16Array(e.length);
3040
+ for (let t = 0; t < e.length; t++) r[t] = n[e[t]];
3041
+ return r;
3042
+ }
3043
+ function Rt(e, t) {
3044
+ let n = t === "alaw" ? jt : Mt, r = new Float32Array(e.length);
2614
3045
  for (let t = 0; t < e.length; t++) r[t] = n[e[t]] / 32768;
2615
3046
  return r;
2616
3047
  }
2617
3048
  // src/render/audio.ts
2618
- var Y = globalThis, Tt = class {
3049
+ var q = globalThis, zt = class {
2619
3050
  constructor(e) {
2620
- r(this, "options", void 0), r(this, "decoder", null), r(this, "track", null), r(this, "manualLaw", null), r(this, "ctx", null), r(this, "gain", null), r(this, "anchorMedia", 0), r(this, "anchorCtx", 0), r(this, "anchored", !1), r(this, "volume", void 0), r(this, "destroyed", !1), r(this, "clockSource", null), r(this, "decodedFrames", 0), this.options = e, this.volume = e.volume;
3051
+ r(this, "options", void 0), r(this, "decoder", null), r(this, "track", null), r(this, "manualLaw", null), r(this, "ctx", null), r(this, "gain", null), r(this, "destination", null), r(this, "anchorMedia", 0), r(this, "anchorCtx", 0), r(this, "anchored", !1), r(this, "volume", void 0), r(this, "destroyed", !1), r(this, "clockSource", null), r(this, "rate", 1), r(this, "decodedFrames", 0), r(this, "peakValue", 0), r(this, "peakAt", 0), this.options = e, this.volume = e.volume;
2621
3052
  }
2622
3053
  get configured() {
2623
3054
  return this.decoder !== null || this.manualLaw !== null;
2624
3055
  }
3056
+ get peak() {
3057
+ return this.peakValue === 0 || performance.now() - this.peakAt > 3e3 ? 0 : this.peakValue;
3058
+ }
3059
+ get state() {
3060
+ return this.ctx?.state ?? "none";
3061
+ }
3062
+ get volumeLevel() {
3063
+ return this.gain?.gain.value ?? this.volume;
3064
+ }
3065
+ captureStream() {
3066
+ let e = this.ensureAudioContext();
3067
+ return !e || !this.gain ? null : (this.destination || (this.destination = e.createMediaStreamDestination(), this.gain.connect(this.destination)), this.destination.stream);
3068
+ }
2625
3069
  configure(e) {
2626
3070
  if (this.track = e, e.codec === "g711a" || e.codec === "g711u") {
2627
3071
  this.manualLaw = e.codec === "g711a" ? "alaw" : "ulaw", this.decoder = null;
2628
3072
  return;
2629
3073
  }
2630
- let t = Y.AudioDecoder;
2631
- if (t && e.codecPrivate) try {
3074
+ let t = q.AudioDecoder;
3075
+ if (t && (e.codec !== "aac" || e.codecPrivate)) try {
2632
3076
  this.decoder = new t({
2633
3077
  output: (e) => this.onData(e),
2634
3078
  error: (e) => {
2635
3079
  this.options.onError?.(/* @__PURE__ */ Error(`audio decoder: ${e?.message ?? e}`));
2636
3080
  }
2637
- }), this.decoder.configure({
2638
- codec: I(e.codecPrivate),
2639
- sampleRate: e.sampleRate,
2640
- numberOfChannels: e.channels,
2641
- description: e.codecPrivate
2642
3081
  });
3082
+ let n = {
3083
+ codec: e.codec === "mp3" ? "mp3" : De(e.codecPrivate),
3084
+ sampleRate: e.sampleRate,
3085
+ numberOfChannels: e.channels
3086
+ };
3087
+ e.codec === "aac" && e.codecPrivate && (n.description = e.codecPrivate), this.decoder.configure(n);
2643
3088
  } catch (e) {
2644
3089
  this.decoder = null, this.options.onError?.(e instanceof Error ? e : Error(String(e)));
2645
3090
  }
@@ -2650,7 +3095,7 @@ var Y = globalThis, Tt = class {
2650
3095
  this.writeManual(e, this.manualLaw);
2651
3096
  return;
2652
3097
  }
2653
- let t = this.decoder, n = Y.EncodedAudioChunk, r = this.track;
3098
+ let t = this.decoder, n = q.EncodedAudioChunk, r = this.track;
2654
3099
  if (t && n && r) for (let i of e) {
2655
3100
  if (t.decodeQueueSize > 60) return;
2656
3101
  try {
@@ -2666,30 +3111,43 @@ var Y = globalThis, Tt = class {
2666
3111
  }
2667
3112
  }
2668
3113
  writeManual(e, t) {
2669
- let n = this.ensureAudioContext(), r = this.track;
2670
- if (n && r && n.state === "running") for (let n of e) {
2671
- if (n.data.length === 0) continue;
2672
- let e = wt(n.data, t);
2673
- this.schedule([e], r.sampleRate, n.pts / r.timescale), this.decodedFrames++;
3114
+ let n = this.track;
3115
+ if (n) {
3116
+ this.ensureAudioContext();
3117
+ for (let r of e) {
3118
+ if (r.data.length === 0) continue;
3119
+ let e = Rt(r.data, t);
3120
+ this.updatePeak([e]), this.schedule([e], n.sampleRate, r.pts / n.timescale), this.decodedFrames++;
3121
+ }
3122
+ }
3123
+ }
3124
+ updatePeak(e) {
3125
+ let t = 0;
3126
+ for (let n of e) for (let e = 0; e < n.length; e++) {
3127
+ let r = Math.abs(n[e]);
3128
+ r > t && (t = r);
2674
3129
  }
3130
+ let n = performance.now();
3131
+ n - this.peakAt > 1e3 ? (this.peakValue = t, this.peakAt = n) : t > this.peakValue && (this.peakValue = t);
2675
3132
  }
2676
3133
  get clock() {
2677
- return this.clockSource ? this.clockSource() : !this.anchored || !this.ctx ? null : this.anchorMedia + (this.ctx.currentTime - this.anchorCtx);
3134
+ return this.clockSource ? this.clockSource() : !this.anchored || !this.ctx ? null : this.anchorMedia + (this.ctx.currentTime - this.anchorCtx) * this.rate;
2678
3135
  }
2679
3136
  setClockSource(e) {
2680
3137
  this.clockSource = e;
2681
3138
  }
3139
+ setRate(e) {
3140
+ if (!Number.isFinite(e) || e <= 0) return;
3141
+ let t = this.clock;
3142
+ this.rate = Math.min(4, Math.max(.25, e)), this.ctx && t !== null && (this.anchored = !0, this.anchorMedia = t, this.anchorCtx = this.ctx.currentTime);
3143
+ }
2682
3144
  ensureAudioContext() {
2683
3145
  if (this.ctx) return this.ctx;
2684
- let e = Y.AudioContext || Y.webkitAudioContext;
3146
+ let e = q.AudioContext || q.webkitAudioContext;
2685
3147
  return e ? (this.ctx = new e(), this.gain = this.ctx.createGain(), this.gain.gain.value = this.volume, this.gain.connect(this.ctx.destination), this.ctx) : null;
2686
3148
  }
2687
3149
  onData(e) {
2688
- let t = this.ensureAudioContext();
2689
- if (!t || !this.gain || t.state !== "running") try {
2690
- e.close();
2691
- } catch {}
2692
- else try {
3150
+ try {
2693
3151
  let t = e.numberOfChannels, n = e.numberOfFrames, r = [];
2694
3152
  for (let i = 0; i < t; i++) {
2695
3153
  let t = new Float32Array(n);
@@ -2703,6 +3161,9 @@ var Y = globalThis, Tt = class {
2703
3161
  }
2704
3162
  r.push(t);
2705
3163
  }
3164
+ this.updatePeak(r);
3165
+ let i = this.ensureAudioContext();
3166
+ if (!i || !this.gain || i.state !== "running") return;
2706
3167
  this.schedule(r, e.sampleRate, e.timestamp / 1e6), this.decodedFrames++;
2707
3168
  } finally {
2708
3169
  try {
@@ -2712,17 +3173,17 @@ var Y = globalThis, Tt = class {
2712
3173
  }
2713
3174
  schedule(e, t, n) {
2714
3175
  let r = this.ensureAudioContext();
2715
- if (!r || !this.gain) return;
3176
+ if (!r || !this.gain || r.state !== "running") return;
2716
3177
  let i = r.currentTime, a, o = this.clockSource?.();
2717
3178
  if (o != null) {
2718
- let e = n - o;
3179
+ let e = (n - o) / this.rate;
2719
3180
  if (e < -.3 || e > 2) return;
2720
3181
  a = i + Math.max(0, e) + .02;
2721
- } else if (this.anchored || (this.anchored = !0, this.anchorMedia = n, this.anchorCtx = i + .06), a = this.anchorCtx + (n - this.anchorMedia), a < i + .01 && (a = i + .04, this.anchorCtx = a, this.anchorMedia = n), a > i + 1.5) return;
3182
+ } else if (this.anchored || (this.anchored = !0, this.anchorMedia = n, this.anchorCtx = i + .06), a = this.anchorCtx + (n - this.anchorMedia) / this.rate, a < i + .01 && (a = i + .04, this.anchorCtx = a, this.anchorMedia = n), a > i + 1.5) return;
2722
3183
  let s = r.createBuffer(e.length, e[0].length, t);
2723
3184
  for (let t = 0; t < e.length; t++) s.copyToChannel(e[t], t);
2724
3185
  let c = r.createBufferSource();
2725
- c.buffer = s, c.connect(this.gain), c.onended = () => {
3186
+ c.buffer = s, c.playbackRate.value = this.rate, c.connect(this.gain), c.onended = () => {
2726
3187
  try {
2727
3188
  c.disconnect();
2728
3189
  } catch {}
@@ -2748,38 +3209,85 @@ var Y = globalThis, Tt = class {
2748
3209
  try {
2749
3210
  this.decoder?.close();
2750
3211
  } catch {}
2751
- this.decoder = null, this.manualLaw = null, this.ctx && (this.ctx.close(), this.ctx = null), this.gain = null;
3212
+ this.decoder = null, this.manualLaw = null, this.ctx && (this.ctx.close(), this.ctx = null), this.gain = null, this.destination = null;
2752
3213
  }
2753
- }, X = class {
3214
+ };
3215
+ // src/render/mse.ts
3216
+ function Bt(e, t) {
3217
+ if (e === t) return !0;
3218
+ if (e.byteLength !== t.byteLength) return !1;
3219
+ for (let n = 0; n < e.length; n++) if (e[n] !== t[n]) return !1;
3220
+ return !0;
3221
+ }
3222
+ function Vt(e, t) {
3223
+ return e.kind !== t.kind || e.codec !== t.codec || e.timescale !== t.timescale || !!e.codecPrivate != !!t.codecPrivate || e.codecPrivate && t.codecPrivate && !Bt(e.codecPrivate, t.codecPrivate) ? !1 : e.kind === "video" && t.kind === "video" ? e.width === t.width && e.height === t.height && (e.profile ?? 0) === (t.profile ?? 0) && (e.level ?? 0) === (t.level ?? 0) : e.kind === "audio" && t.kind === "audio" && e.sampleRate === t.sampleRate && e.channels === t.channels;
3224
+ }
3225
+ function Ht(e, t) {
3226
+ return e.kind === t.kind && e.codec === t.codec;
3227
+ }
3228
+ var J = class {
2754
3229
  constructor(e, t) {
2755
- r(this, "video", void 0), r(this, "options", void 0), r(this, "mode", "mse"), r(this, "mediaSource", null), r(this, "objectUrl", null), r(this, "sourceOpen", !1), r(this, "buffers", /* @__PURE__ */ new Map()), r(this, "queues", /* @__PURE__ */ new Map()), r(this, "muxers", /* @__PURE__ */ new Map()), r(this, "attached", /* @__PURE__ */ new Set()), r(this, "trackList", /* @__PURE__ */ new Map()), r(this, "fallbackTracks", /* @__PURE__ */ new Set()), r(this, "fallbackAudio", null), r(this, "endPending", !1), r(this, "destroyed", !1), this.video = e, this.options = t;
3230
+ r(this, "video", void 0), r(this, "options", void 0), r(this, "mode", "mse"), r(this, "mediaSource", null), r(this, "objectUrl", null), r(this, "sourceOpen", !1), r(this, "buffers", /* @__PURE__ */ new Map()), r(this, "queues", /* @__PURE__ */ new Map()), r(this, "muxers", /* @__PURE__ */ new Map()), r(this, "mimeTypes", /* @__PURE__ */ new Map()), r(this, "attached", /* @__PURE__ */ new Set()), r(this, "trackList", /* @__PURE__ */ new Map()), r(this, "fallbackTracks", /* @__PURE__ */ new Set()), r(this, "fallbackAudio", null), r(this, "hasMseAudio", !1), r(this, "endPending", !1), r(this, "destroyed", !1), this.video = e, this.options = t;
2756
3231
  }
2757
3232
  get stats() {
2758
3233
  let e = this.video.getVideoPlaybackQuality?.();
2759
3234
  return {
2760
3235
  decodedVideoFrames: e?.totalVideoFrames ?? 0,
2761
3236
  droppedVideoFrames: e?.droppedVideoFrames ?? 0,
2762
- decodedAudioFrames: this.fallbackAudio?.decodedFrames ?? 0
3237
+ decodedAudioFrames: this.fallbackAudio?.decodedFrames ?? 0,
3238
+ audioPeak: this.fallbackAudio?.peak ?? 0,
3239
+ audioState: this.fallbackAudio?.state ?? "none",
3240
+ audioVolume: this.fallbackAudio?.volumeLevel ?? (this.video.muted ? 0 : this.video.volume),
3241
+ audioPath: this.fallbackAudio ? "webaudio" : this.hasMseAudio ? "mse" : "none"
2763
3242
  };
2764
3243
  }
2765
3244
  async attach(e) {
2766
- let t = e.filter((e) => !this.attached.has(e.id));
3245
+ let t = e.filter((e) => {
3246
+ let t = this.trackList.get(e.id);
3247
+ return !t || !Vt(t, e);
3248
+ });
2767
3249
  if (t.length === 0) return;
2768
3250
  let n = (e) => {
2769
3251
  try {
2770
- return MediaSource.isTypeSupported(J(e));
3252
+ return MediaSource.isTypeSupported(K(e));
2771
3253
  } catch {
2772
3254
  return !1;
2773
3255
  }
2774
3256
  };
2775
3257
  t.some(n) && !this.mediaSource && await this.initMediaSource();
2776
- for (let e of t) if (this.attached.add(e.id), this.trackList.set(e.id, e), !n(e)) {
2777
- if (e.kind !== "audio") throw new i("MSE_UNSUPPORTED_CODEC", `MediaSource does not support ${J(e)}`);
2778
- this.ensureFallbackAudio().configure(e), this.fallbackTracks.add(e.id);
2779
- } else this.addTrack(e);
3258
+ for (let e of t) {
3259
+ let t = this.trackList.get(e.id);
3260
+ if (t) this.reconfigure(e, t);
3261
+ else if (this.attached.add(e.id), this.trackList.set(e.id, e), !n(e)) {
3262
+ if (e.kind !== "audio") throw new i("MSE_UNSUPPORTED_CODEC", `MediaSource does not support ${K(e)}`);
3263
+ this.ensureFallbackAudio().configure(e), this.fallbackTracks.add(e.id);
3264
+ } else this.addTrack(e);
3265
+ }
3266
+ }
3267
+ reconfigure(e, t) {
3268
+ if (this.fallbackTracks.has(e.id)) {
3269
+ this.trackList.set(e.id, e), e.kind === "audio" && this.ensureFallbackAudio().configure(e);
3270
+ return;
3271
+ }
3272
+ if (!Ht(t, e)) {
3273
+ this.options.onError?.(new i("MSE_TRACK_CHANGE", `cannot switch from ${t.codec} to ${e.codec} in the same MSE buffer`));
3274
+ return;
3275
+ }
3276
+ this.trackList.set(e.id, e);
3277
+ let n = this.buffers.get(e.id);
3278
+ if (!n) {
3279
+ this.addTrack(e);
3280
+ return;
3281
+ }
3282
+ let r = K(e);
3283
+ if (this.mimeTypes.get(e.id) !== r && typeof n.changeType == "function") try {
3284
+ n.changeType(r), this.mimeTypes.set(e.id, r);
3285
+ } catch {}
3286
+ let a = new At(e);
3287
+ this.muxers.set(e.id, a), this.enqueue(e.id, a.initSegment());
2780
3288
  }
2781
3289
  ensureFallbackAudio() {
2782
- return this.fallbackAudio || (this.fallbackAudio = new Tt({
3290
+ return this.fallbackAudio || (this.fallbackAudio = new zt({
2783
3291
  volume: this.video.muted ? 0 : this.video.volume,
2784
3292
  onError: this.options.onError
2785
3293
  }), this.fallbackAudio.setClockSource(() => Number.isFinite(this.video.currentTime) ? this.video.currentTime : 0)), this.fallbackAudio;
@@ -2794,11 +3302,12 @@ var Y = globalThis, Tt = class {
2794
3302
  });
2795
3303
  }
2796
3304
  addTrack(e) {
2797
- let t = this.mediaSource, n = J(e);
3305
+ let t = this.mediaSource, n = K(e);
2798
3306
  if (!MediaSource.isTypeSupported(n)) throw new i("MSE_UNSUPPORTED_CODEC", `MediaSource does not support ${n}. Try decoder: 'webcodecs'.`);
3307
+ e.kind === "audio" && (this.hasMseAudio = !0);
2799
3308
  let r = t.addSourceBuffer(n);
2800
- r.mode = "segments", this.buffers.set(e.id, r), this.queues.set(e.id, []);
2801
- let a = new _t(e);
3309
+ r.mode = "segments", this.buffers.set(e.id, r), this.mimeTypes.set(e.id, n), this.queues.set(e.id, []);
3310
+ let a = new At(e);
2802
3311
  this.muxers.set(e.id, a), r.addEventListener("updateend", () => this.pump(e.id)), r.addEventListener("error", () => {
2803
3312
  this.options.onError?.(new i("MSE_APPEND_ERROR", `SourceBuffer error for track ${e.id}`));
2804
3313
  }), this.enqueue(e.id, a.initSegment());
@@ -2875,6 +3384,9 @@ var Y = globalThis, Tt = class {
2875
3384
  setPaused(e) {
2876
3385
  this.fallbackAudio?.setPaused(e);
2877
3386
  }
3387
+ setPlaybackRate(e) {
3388
+ this.fallbackAudio?.setRate(e);
3389
+ }
2878
3390
  destroy() {
2879
3391
  this.destroyed = !0;
2880
3392
  for (let e of this.buffers.values()) try {
@@ -2885,6 +3397,13 @@ var Y = globalThis, Tt = class {
2885
3397
  this.video.removeAttribute("src"), this.video.load();
2886
3398
  } catch {}
2887
3399
  }
3400
+ captureStream() {
3401
+ let e = this.video;
3402
+ return typeof e.captureStream == "function" ? e.captureStream() : typeof e.mozCaptureStream == "function" ? e.mozCaptureStream() : null;
3403
+ }
3404
+ captureAudioStream() {
3405
+ return this.fallbackAudio?.captureStream() ?? null;
3406
+ }
2888
3407
  get bufferAhead() {
2889
3408
  try {
2890
3409
  let e = this.video.buffered;
@@ -2895,13 +3414,13 @@ var Y = globalThis, Tt = class {
2895
3414
  return 0;
2896
3415
  }
2897
3416
  }
2898
- }, Z = globalThis;
2899
- function Et() {
2900
- return Z.VideoDecoder !== void 0 && Z.EncodedVideoChunk !== void 0;
3417
+ }, Y = globalThis;
3418
+ function Ut() {
3419
+ return Y.VideoDecoder !== void 0 && Y.EncodedVideoChunk !== void 0;
2901
3420
  }
2902
- var Q = class {
3421
+ var X = class {
2903
3422
  constructor(e, t) {
2904
- r(this, "options", void 0), r(this, "mode", "webcodecs"), r(this, "videoDecoder", null), r(this, "audio", void 0), r(this, "canvas", void 0), r(this, "ctx", null), r(this, "frames", []), r(this, "videoBacklog", []), r(this, "rafId", 0), r(this, "paused", !1), r(this, "anchored", !1), r(this, "anchorWall", 0), r(this, "anchorMedia", 0), r(this, "decodedVideo", 0), r(this, "droppedVideo", 0), r(this, "hardware", "unknown"), r(this, "firstFrameReported", !1), r(this, "destroyed", !1), r(this, "tick", () => {
3423
+ r(this, "options", void 0), r(this, "mode", "webcodecs"), r(this, "videoDecoder", null), r(this, "audio", void 0), r(this, "canvas", void 0), r(this, "ctx", null), r(this, "frames", []), r(this, "videoBacklog", []), r(this, "rafId", 0), r(this, "paused", !1), r(this, "anchored", !1), r(this, "anchorWall", 0), r(this, "anchorMedia", 0), r(this, "rate", 1), r(this, "decodedVideo", 0), r(this, "droppedVideo", 0), r(this, "hardware", "unknown"), r(this, "firstFrameReported", !1), r(this, "destroyed", !1), r(this, "tick", () => {
2905
3424
  if (this.rafId = 0, this.paused || !this.anchored || this.destroyed) return;
2906
3425
  let e = this.mediaTime(), t = null;
2907
3426
  for (; this.frames.length > 0 && this.frames[0].timestamp / 1e6 <= e + .002;) t && (t.close(), this.droppedVideo++), t = this.frames.shift();
@@ -2909,7 +3428,7 @@ var Q = class {
2909
3428
  }), this.options = e, this.canvas = t ?? document.createElement("canvas"), this.canvas.style.width = "100%", this.canvas.style.height = "100%", this.canvas.style.display = "block", this.ctx = this.canvas.getContext("2d", {
2910
3429
  alpha: !1,
2911
3430
  desynchronized: !0
2912
- }), this.audio = new Tt({
3431
+ }), this.audio = new zt({
2913
3432
  volume: e.volume,
2914
3433
  onError: e.onError
2915
3434
  });
@@ -2918,7 +3437,11 @@ var Q = class {
2918
3437
  return {
2919
3438
  decodedVideoFrames: this.decodedVideo,
2920
3439
  droppedVideoFrames: this.droppedVideo,
2921
- decodedAudioFrames: this.audio.decodedFrames
3440
+ decodedAudioFrames: this.audio.decodedFrames,
3441
+ audioPeak: this.audio.peak,
3442
+ audioState: this.audio.state,
3443
+ audioVolume: this.audio.volumeLevel,
3444
+ audioPath: this.audio.configured ? "webaudio" : "none"
2922
3445
  };
2923
3446
  }
2924
3447
  get currentTime() {
@@ -2933,6 +3456,13 @@ var Q = class {
2933
3456
  get element() {
2934
3457
  return this.canvas;
2935
3458
  }
3459
+ captureStream() {
3460
+ let e = this.canvas;
3461
+ return typeof e.captureStream == "function" ? e.captureStream(30) : null;
3462
+ }
3463
+ captureAudioStream() {
3464
+ return this.audio.captureStream();
3465
+ }
2936
3466
  async attach(e) {
2937
3467
  let t = e.find((e) => e.kind === "video");
2938
3468
  t && !this.videoDecoder && await this.configureVideo(t);
@@ -2940,9 +3470,9 @@ var Q = class {
2940
3470
  n && !this.audio.configured && this.audio.configure(n);
2941
3471
  }
2942
3472
  async configureVideo(e) {
2943
- let t = Z.VideoDecoder;
3473
+ let t = Y.VideoDecoder;
2944
3474
  if (!t) throw new i("WEBCODECS_UNAVAILABLE", "WebCodecs VideoDecoder is not available");
2945
- let n = e.codec === "hevc" ? j(e.codecPrivate) : ue(e.codecPrivate), r = {
3475
+ let n = e.codec === "hevc" ? O(e.codecPrivate) : pe(e.codecPrivate), r = {
2946
3476
  codec: n,
2947
3477
  description: e.codecPrivate,
2948
3478
  optimizeForLatency: !0
@@ -2987,7 +3517,7 @@ var Q = class {
2987
3517
  this.pumpVideo();
2988
3518
  }
2989
3519
  pumpVideo() {
2990
- let e = this.videoDecoder, t = Z.EncodedVideoChunk;
3520
+ let e = this.videoDecoder, t = Y.EncodedVideoChunk;
2991
3521
  if (e && t && !this.destroyed) for (; this.videoBacklog.length > 0 && !(this.frames.length + e.decodeQueueSize >= 8);) {
2992
3522
  let { track: n, sample: r } = this.videoBacklog.shift(), i = new t({
2993
3523
  type: r.keyframe ? "key" : "delta",
@@ -3014,7 +3544,7 @@ var Q = class {
3014
3544
  }
3015
3545
  mediaTime() {
3016
3546
  let e = this.audio.clock;
3017
- return e === null ? this.anchorMedia + (performance.now() - this.anchorWall) / 1e3 : e;
3547
+ return e === null ? this.anchorMedia + (performance.now() - this.anchorWall) / 1e3 * this.rate : e;
3018
3548
  }
3019
3549
  startRaf() {
3020
3550
  this.rafId !== 0 || this.paused || this.destroyed || (this.rafId = requestAnimationFrame(this.tick));
@@ -3052,6 +3582,11 @@ var Q = class {
3052
3582
  setVolume(e) {
3053
3583
  this.audio.setVolume(e);
3054
3584
  }
3585
+ setPlaybackRate(e) {
3586
+ if (!Number.isFinite(e) || e <= 0) return;
3587
+ let t = this.anchored ? this.mediaTime() : 0;
3588
+ this.rate = Math.min(4, Math.max(.25, e)), this.audio.setRate(this.rate), this.anchored && (this.anchorMedia = t, this.anchorWall = performance.now());
3589
+ }
3055
3590
  flush() {}
3056
3591
  endOfStream() {}
3057
3592
  reset() {
@@ -3075,7 +3610,7 @@ var Q = class {
3075
3610
  }
3076
3611
  };
3077
3612
  // src/soft/libde265.ts
3078
- function Dt(e) {
3613
+ function Wt(e) {
3079
3614
  return {
3080
3615
  width: e.width,
3081
3616
  height: e.height,
@@ -3083,12 +3618,12 @@ function Dt(e) {
3083
3618
  bytes: e.bytes.slice(0, e.stride * e.height)
3084
3619
  };
3085
3620
  }
3086
- var Ot = class {
3621
+ var Gt = class {
3087
3622
  constructor() {
3088
3623
  r(this, "name", "libde265"), r(this, "module", null), r(this, "decoder", null), r(this, "parameterSets", []);
3089
3624
  }
3090
3625
  async configure(e) {
3091
- let t = N(e.codecPrivate);
3626
+ let t = A(e.codecPrivate);
3092
3627
  if (this.parameterSets = [
3093
3628
  ...t.vps,
3094
3629
  ...t.sps,
@@ -3104,7 +3639,7 @@ var Ot = class {
3104
3639
  if (!this.decoder) return [];
3105
3640
  let r = BigInt(Math.round(t));
3106
3641
  if (n) for (let e of this.parameterSets) this.decoder.pushNal(e, r);
3107
- for (let t of A(e)) t.length > 0 && this.decoder.pushNal(t, r);
3642
+ for (let t of ce(e)) t.length > 0 && this.decoder.pushNal(t, r);
3108
3643
  return this.decoder.pushEndOfFrame(), this.drain();
3109
3644
  }
3110
3645
  flush() {
@@ -3132,9 +3667,9 @@ var Ot = class {
3132
3667
  width: t,
3133
3668
  height: r
3134
3669
  },
3135
- y: Dt(i),
3136
- u: Dt(a),
3137
- v: Dt(o)
3670
+ y: Wt(i),
3671
+ u: Wt(a),
3672
+ v: Wt(o)
3138
3673
  }), n.delete();
3139
3674
  }
3140
3675
  if (!t.more) break;
@@ -3149,15 +3684,15 @@ var Ot = class {
3149
3684
  }
3150
3685
  };
3151
3686
  // src/soft/h264bsd.ts
3152
- function kt(e) {
3687
+ function Kt(e) {
3153
3688
  return _(Uint8Array.of(0, 0, 0, 1), e);
3154
3689
  }
3155
- var At = class {
3690
+ var qt = class {
3156
3691
  constructor() {
3157
3692
  r(this, "name", "h264bsd"), r(this, "module", null), r(this, "decoder", null), r(this, "parameterSets", []), r(this, "picId", 0), r(this, "ptsById", /* @__PURE__ */ new Map());
3158
3693
  }
3159
3694
  async configure(e) {
3160
- let t = M(e.codecPrivate), n = e.codecPrivate[1] ?? 0;
3695
+ let t = k(e.codecPrivate), n = e.codecPrivate[1] ?? 0;
3161
3696
  if (n !== 66 && n !== 88) throw new i("SOFT_PROFILE_UNSUPPORTED", `h264bsd only decodes Baseline H.264 (profile ${n}); use MSE/WebCodecs or transcode on the server`);
3162
3697
  if (this.parameterSets = [...t.sps, ...t.pps].filter((e) => e.length > 0), this.parameterSets.length === 0) throw new i("SOFT_DECODER_NO_CONFIG", "avcC has no SPS/PPS; cannot start the software decoder");
3163
3698
  }
@@ -3169,7 +3704,7 @@ var At = class {
3169
3704
  decode(e, t, n) {
3170
3705
  if (!this.decoder) return [];
3171
3706
  let r = [];
3172
- if (n) for (let e of this.parameterSets) r.push(kt(e));
3707
+ if (n) for (let e of this.parameterSets) r.push(Kt(e));
3173
3708
  r.push(e);
3174
3709
  let i = this.picId++;
3175
3710
  this.ptsById.set(i, t);
@@ -3229,49 +3764,254 @@ var At = class {
3229
3764
  } catch {}
3230
3765
  this.decoder = null, this.module = null, this.ptsById.clear();
3231
3766
  }
3232
- }, jt = () => import(
3767
+ };
3768
+ // src/soft/openh264.ts
3769
+ function Jt(e) {
3770
+ return _(Uint8Array.of(0, 0, 0, 1), e);
3771
+ }
3772
+ function Yt(e) {
3773
+ let t = globalThis.Buffer;
3774
+ if (t) return t.from(e).toString("base64");
3775
+ let n = "", r = 32768;
3776
+ for (let t = 0; t < e.length; t += r) n += String.fromCharCode(...e.subarray(t, t + r));
3777
+ return btoa(n);
3778
+ }
3779
+ function Xt(e) {
3780
+ let t = globalThis.Buffer;
3781
+ if (t) return new Uint8Array(t.from(e, "base64"));
3782
+ let n = atob(e), r = new Uint8Array(n.length);
3783
+ for (let e = 0; e < n.length; e++) r[e] = n.charCodeAt(e);
3784
+ return r;
3785
+ }
3786
+ var Zt = 64, Qt = 827019080, $t = 1, en = 1, tn = class {
3787
+ constructor() {
3788
+ r(this, "name", "OpenH264"), r(this, "shim", null), r(this, "handle", 0), r(this, "parameterSets", []);
3789
+ }
3790
+ async configure(e) {
3791
+ let t = k(e.codecPrivate);
3792
+ if (this.parameterSets = [...t.sps, ...t.pps].filter((e) => e.length > 0), this.parameterSets.length === 0) throw new i("SOFT_DECODER_NO_CONFIG", "avcC has no SPS/PPS; cannot start the software decoder");
3793
+ }
3794
+ async init(e) {
3795
+ let t = await e(), n = t.initOpenH264Kmp ?? (typeof t.default == "function" ? t.default : t.default?.initOpenH264Kmp);
3796
+ if (typeof n != "function") throw new i("SOFT_DECODER_MISSING", "OpenH264 module does not export an initializer");
3797
+ let r = await n();
3798
+ if (this.shim = r, this.handle = r.decoderCreate(), !this.handle) throw new i("SOFT_DECODER_FAILED", "OpenH264 decoderCreate failed");
3799
+ }
3800
+ decode(e, t, n) {
3801
+ let r = this.shim;
3802
+ if (!r || !this.handle) return [];
3803
+ let a = [];
3804
+ if (n) for (let e of this.parameterSets) a.push(Jt(e));
3805
+ a.push(e);
3806
+ let o = r.decode(this.handle, Yt(_(...a)), t);
3807
+ if (o < 0) throw new i("SOFT_DECODE_FAILED", `OpenH264 decode failed (${o})`);
3808
+ return o === en ? this.takeFrame(t) : [];
3809
+ }
3810
+ flush() {
3811
+ let e = this.shim;
3812
+ return !e || !this.handle || e.flush(this.handle) !== en ? [] : this.takeFrame(0);
3813
+ }
3814
+ takeFrame(e) {
3815
+ let t = this.shim;
3816
+ if (!t || !this.handle) return [];
3817
+ let n = t.frameBlob(this.handle), r = n.indexOf(":");
3818
+ if (r < 0 || Number(n.slice(0, r)) !== en) return [];
3819
+ let a = Xt(n.slice(r + 1));
3820
+ if (a.byteLength < Zt) return [];
3821
+ let o = new DataView(a.buffer, a.byteOffset, a.byteLength);
3822
+ if (o.getUint32(0, !0) !== Qt || o.getInt32(4, !0) !== $t) throw new i("SOFT_FRAME_BAD_LAYOUT", "OpenH264 returned an unknown frame blob");
3823
+ let s = o.getInt32(8, !0), c = o.getInt32(12, !0), l = o.getInt32(40, !0), u = o.getInt32(44, !0), d = o.getInt32(48, !0), f = Number(o.getBigInt64(32, !0)), p = Math.ceil(s / 2), m = Math.ceil(c / 2);
3824
+ if (a.byteLength < Zt + l + u + d) return [];
3825
+ let h = a.subarray(Zt);
3826
+ return [{
3827
+ ptsUs: Number.isFinite(f) && f > 0 ? f : e,
3828
+ width: s,
3829
+ height: c,
3830
+ crop: {
3831
+ left: 0,
3832
+ top: 0,
3833
+ width: s,
3834
+ height: c
3835
+ },
3836
+ y: {
3837
+ bytes: h.subarray(0, l),
3838
+ width: s,
3839
+ height: c,
3840
+ stride: s
3841
+ },
3842
+ u: {
3843
+ bytes: h.subarray(l, l + u),
3844
+ width: p,
3845
+ height: m,
3846
+ stride: p
3847
+ },
3848
+ v: {
3849
+ bytes: h.subarray(l + u),
3850
+ width: p,
3851
+ height: m,
3852
+ stride: p
3853
+ }
3854
+ }];
3855
+ }
3856
+ close() {
3857
+ try {
3858
+ this.shim?.decoderDestroy(this.handle);
3859
+ } catch {}
3860
+ this.shim = null, this.handle = 0;
3861
+ }
3862
+ }, nn = class {
3863
+ constructor() {
3864
+ r(this, "canvas", null), r(this, "ctx", null), r(this, "image", null), r(this, "width", 0), r(this, "height", 0), r(this, "luma", /* @__PURE__ */ new Int32Array(256)), r(this, "cbBlue", /* @__PURE__ */ new Int32Array(256)), r(this, "cbGreen", /* @__PURE__ */ new Int32Array(256)), r(this, "crGreen", /* @__PURE__ */ new Int32Array(256)), r(this, "crRed", /* @__PURE__ */ new Int32Array(256));
3865
+ for (let e = 0; e < 256; e++) {
3866
+ this.luma[e] = 298 * (e - 16) + 128 >> 8;
3867
+ let t = e - 128;
3868
+ this.crRed[e] = 409 * t >> 8, this.cbGreen[e] = -100 * t >> 8, this.crGreen[e] = -208 * t >> 8, this.cbBlue[e] = 516 * t >> 8;
3869
+ }
3870
+ }
3871
+ convert(e) {
3872
+ let t = e.crop.width, n = e.crop.height;
3873
+ this.canvas && this.canvas.width === t && this.canvas.height === n || (this.canvas = new OffscreenCanvas(t, n), this.ctx = this.canvas.getContext("2d"), this.image = null);
3874
+ let r = this.ctx;
3875
+ if (!r) throw Error("OffscreenCanvas 2D context is unavailable");
3876
+ this.image && this.width === t && this.height === n || (this.image = r.createImageData(t, n), this.width = t, this.height = n);
3877
+ let i = this.image.data, { y: a, u: o, v: s } = e, c = 0;
3878
+ for (let r = 0; r < n; r++) {
3879
+ let n = (e.crop.top + r) * a.stride + e.crop.left, l = (e.crop.top + r >> 1) * o.stride + (e.crop.left >> 1);
3880
+ for (let e = 0; e < t; e++) {
3881
+ let t = this.luma[a.bytes[n + e]], r = o.bytes[l + (e >> 1)], u = s.bytes[l + (e >> 1)];
3882
+ i[c++] = t + this.crRed[u], i[c++] = t + this.cbGreen[r] + this.crGreen[u], i[c++] = t + this.cbBlue[r], i[c++] = 255;
3883
+ }
3884
+ }
3885
+ return r.putImageData(this.image, 0, 0), this.canvas.transferToImageBitmap();
3886
+ }
3887
+ };
3888
+ function rn(e) {
3889
+ let t = null, n = Promise.resolve(), r = new nn(), i = (t, n = []) => {
3890
+ e.postMessage(t, n);
3891
+ }, a = (e, t) => {
3892
+ let n = t.map((e) => ({
3893
+ ptsUs: e.ptsUs,
3894
+ bitmap: r.convert(e)
3895
+ }));
3896
+ i({
3897
+ type: "frames",
3898
+ id: e,
3899
+ frames: n
3900
+ }, n.map((e) => e.bitmap));
3901
+ }, o = async (n) => {
3902
+ if (n.type === "init") {
3903
+ let e = n.track, r = e.codec === "avc" ? e.codecPrivate[1] ?? 0 : 0, a = e.codec === "avc" && (r === 66 || r === 88), o = e.codec === "hevc" ? new Gt() : a ? new qt() : new tn();
3904
+ await o.configure(e);
3905
+ let s = n.modules, c = e.codec === "hevc" ? s?.hevc : a ? s?.avc : s?.openh264, l = c ? () => import(
3906
+ /* @vite-ignore */
3907
+ c
3908
+ ) : void 0;
3909
+ await o.init(l ?? (e.codec === "hevc" ? () => import("@yume-chan/libde265") : a ? () => import("@yume-chan/h264bsd") : () => import("@enaium/openh264-kmp"))), t = o, i({
3910
+ type: "ready",
3911
+ name: o.name
3912
+ });
3913
+ } else if (n.type === "close") try {
3914
+ t?.close();
3915
+ } finally {
3916
+ t = null, e.close();
3917
+ }
3918
+ else {
3919
+ if (!t) throw Error("soft worker is not initialized");
3920
+ n.type === "decode" ? a(n.id, await t.decode(n.data, n.ptsUs, n.keyframe)) : n.type === "flush" && a(n.id, await t.flush());
3921
+ }
3922
+ };
3923
+ e.onmessage = (e) => {
3924
+ let t = e.data;
3925
+ n = n.then(() => o(t)).catch((e) => {
3926
+ i({
3927
+ type: "error",
3928
+ id: t.id,
3929
+ message: e instanceof Error ? e.message : String(e)
3930
+ });
3931
+ });
3932
+ };
3933
+ }
3934
+ // src/soft/index.ts
3935
+ var an = () => import(
3233
3936
  /* @vite-ignore */
3234
3937
  "@yume-chan/libde265"
3235
- ), Mt = () => import(
3938
+ ), on = () => import(
3236
3939
  /* @vite-ignore */
3237
3940
  "@yume-chan/h264bsd"
3941
+ ), sn = () => import(
3942
+ /* @vite-ignore */
3943
+ "@enaium/openh264-kmp"
3238
3944
  );
3239
- async function Nt(e, t = {}) {
3240
- let n = e.codec === "hevc", r = n ? new Ot() : new At();
3241
- await r.configure(e);
3242
- let a = n ? t.hevc ?? jt : t.avc ?? Mt;
3945
+ async function cn(e, t = {}) {
3946
+ let n = e.codec === "hevc", r = e.codec === "avc" ? e.codecPrivate[1] ?? 0 : 0, a = e.codec === "avc" && (r === 66 || r === 88), o = n ? new Gt() : a ? new qt() : new tn();
3947
+ await o.configure(e);
3948
+ let s = n ? t.hevc ?? an : a ? t.avc ?? on : t.openh264 ?? sn;
3243
3949
  try {
3244
- await r.init(a);
3950
+ await o.init(s);
3245
3951
  } catch (e) {
3246
- throw e instanceof i ? e : new i("SOFT_DECODER_MISSING", `failed to load the WASM ${n ? "HEVC" : "H.264"} decoder. Install @yume-chan/${n ? "libde265" : "h264bsd"} or provide softDecode.loaders.`, e);
3952
+ if (e instanceof i) throw e;
3953
+ let t = n ? "@yume-chan/libde265" : a ? "@yume-chan/h264bsd" : "@enaium/openh264-kmp", r = e instanceof Error ? `: ${e.message}` : "";
3954
+ throw new i("SOFT_DECODER_MISSING", `failed to load the WASM ${n ? "HEVC" : a ? "Baseline H.264" : "H.264 Main/High"} decoder. Install ${t} or provide softDecode.loaders${r}`, e);
3247
3955
  }
3248
- return r;
3956
+ return o;
3957
+ }
3958
+ // src/render/backlog.ts
3959
+ function ln(e, t, n = .2) {
3960
+ if (e.length === 0) return {
3961
+ cut: 0,
3962
+ awaitingKeyframe: !1
3963
+ };
3964
+ let r = t - n;
3965
+ if (e[0].ptsUs / 1e6 >= r) return {
3966
+ cut: 0,
3967
+ awaitingKeyframe: !1
3968
+ };
3969
+ for (let t = 0; t < e.length; t++) if (e[t].keyframe && e[t].ptsUs / 1e6 >= r) return {
3970
+ cut: t,
3971
+ awaitingKeyframe: !1
3972
+ };
3973
+ return {
3974
+ cut: e.length,
3975
+ awaitingKeyframe: !0
3976
+ };
3249
3977
  }
3250
3978
  // src/render/software.ts
3251
- var Pt = "\nattribute vec2 aPos;\nuniform vec4 uTexRange;\nvarying vec2 vTex;\nvoid main() {\n vTex = mix(uTexRange.xy, uTexRange.zw, aPos * 0.5 + 0.5);\n gl_Position = vec4(aPos, 0.0, 1.0);\n}", Ft = "\nprecision mediump float;\nvarying vec2 vTex;\nuniform sampler2D uY;\nuniform sampler2D uU;\nuniform sampler2D uV;\nvoid main() {\n vec2 uv = vec2(vTex.x, 1.0 - vTex.y);\n float y = texture2D(uY, uv).r;\n float u = texture2D(uU, uv).r - 0.5;\n float v = texture2D(uV, uv).r - 0.5;\n y = 1.164 * (y - 0.0625);\n gl_FragColor = vec4(y + 1.596 * v, y - 0.813 * v - 0.391 * u, y + 2.018 * u, 1.0);\n}", $ = class {
3979
+ var un = 1, dn = "\nattribute vec2 aPos;\nuniform vec4 uTexRange;\nvarying vec2 vTex;\nvoid main() {\n vTex = mix(uTexRange.xy, uTexRange.zw, aPos * 0.5 + 0.5);\n gl_Position = vec4(aPos, 0.0, 1.0);\n}", fn = "\nprecision mediump float;\nvarying vec2 vTex;\nuniform sampler2D uY;\nuniform sampler2D uU;\nuniform sampler2D uV;\nvoid main() {\n vec2 uv = vec2(vTex.x, 1.0 - vTex.y);\n float y = texture2D(uY, uv).r;\n float u = texture2D(uU, uv).r - 0.5;\n float v = texture2D(uV, uv).r - 0.5;\n y = 1.164 * (y - 0.0625);\n gl_FragColor = vec4(y + 1.596 * v, y - 0.813 * v - 0.391 * u, y + 2.018 * u, 1.0);\n}", Z = class {
3252
3980
  constructor(e, t) {
3253
- r(this, "options", void 0), r(this, "mode", "software"), r(this, "decoder", null), r(this, "videoTrack", null), r(this, "audio", void 0), r(this, "canvas", void 0), r(this, "backlog", []), r(this, "present", []), r(this, "decoding", !1), r(this, "rafId", 0), r(this, "timer", null), r(this, "paused", !1), r(this, "anchored", !1), r(this, "anchorMedia", 0), r(this, "anchorWall", 0), r(this, "decoded", 0), r(this, "dropped", 0), r(this, "firstFrameReported", !1), r(this, "destroyed", !1), r(this, "ended", !1), r(this, "gl", null), r(this, "glFailed", !1), r(this, "ctx2d", null), r(this, "tmpCanvas", null), r(this, "tmpCtx", null), r(this, "imageData", null), r(this, "resizeObserver", null), r(this, "decodeStep", () => {
3254
- if (this.timer = null, this.decoding = !1, this.destroyed || this.paused || !this.decoder || this.present.length >= this.options.maxDecodeAhead) return;
3981
+ r(this, "options", void 0), r(this, "mode", "software"), r(this, "decoder", null), r(this, "videoTrack", null), r(this, "audio", void 0), r(this, "canvas", void 0), r(this, "backlog", []), r(this, "present", []), r(this, "decoding", !1), r(this, "rafId", 0), r(this, "timer", null), r(this, "paused", !1), r(this, "anchored", !1), r(this, "anchorMedia", 0), r(this, "rate", 1), r(this, "anchorWall", 0), r(this, "decoded", 0), r(this, "dropped", 0), r(this, "firstFrameReported", !1), r(this, "destroyed", !1), r(this, "ended", !1), r(this, "gl", null), r(this, "glFailed", !1), r(this, "ctx2d", null), r(this, "tmpCanvas", null), r(this, "tmpCtx", null), r(this, "imageData", null), r(this, "resizeObserver", null), r(this, "worker", null), r(this, "workerReady", !1), r(this, "workerName", ""), r(this, "workerInFlight", 0), r(this, "workerMaxInFlight", 4), r(this, "workerId", 0), r(this, "workerFlushPending", !1), r(this, "workerFlushId", 0), r(this, "lastDecodedPtsUs", -1), r(this, "dropBeforeUs", 0), r(this, "awaitingKeyframe", !1), r(this, "decodeStep", async () => {
3982
+ if (this.timer = null, this.destroyed || this.paused || !this.decoder || this.present.length >= this.options.maxDecodeAhead) {
3983
+ this.decoding = !1;
3984
+ return;
3985
+ }
3255
3986
  let e = this.backlog.shift();
3256
- if (!e) return;
3987
+ if (!e) {
3988
+ this.decoding = !1;
3989
+ return;
3990
+ }
3257
3991
  let t = [];
3258
3992
  try {
3259
- t = this.decoder.decode(e.annexB, e.ptsUs, e.keyframe);
3993
+ t = await this.decoder.decode(e.annexB, e.ptsUs, e.keyframe);
3260
3994
  } catch (e) {
3261
3995
  this.options.onError?.(e instanceof Error ? e : Error(String(e)));
3262
3996
  }
3263
- for (let e of t) this.decoded++, this.present.push(e);
3264
- this.present.length > 1 && this.present.sort((e, t) => e.ptsUs - t.ptsUs), !this.anchored && this.present.length > 0 && (this.anchored = !0, this.anchorMedia = this.present[0].ptsUs / 1e6, this.anchorWall = performance.now()), this.present.length < this.options.maxDecodeAhead && this.scheduleDecode(), this.startRaf();
3997
+ if (this.decoding = !1, !this.destroyed) {
3998
+ for (let e of t) e.ptsUs < this.dropBeforeUs ? this.dropped++ : (this.decoded++, this.present.push({
3999
+ ptsUs: e.ptsUs,
4000
+ frame: e
4001
+ }), e.ptsUs > this.lastDecodedPtsUs && (this.lastDecodedPtsUs = e.ptsUs));
4002
+ this.present.length > 1 && this.present.sort((e, t) => e.ptsUs - t.ptsUs), !this.anchored && this.present.length > 0 && (this.anchored = !0, this.anchorMedia = this.present[0].ptsUs / 1e6, this.anchorWall = performance.now()), this.present.length < this.options.maxDecodeAhead && this.scheduleDecode(), this.startRaf();
4003
+ }
3265
4004
  }), r(this, "tick", () => {
3266
4005
  if (this.rafId = 0, this.paused || this.destroyed) return;
3267
4006
  if (!this.anchored) {
3268
4007
  this.startRaf();
3269
4008
  return;
3270
4009
  }
4010
+ this.options.live && this.maybeResync();
3271
4011
  let e = this.mediaTime(), t = null;
3272
- for (; this.present.length > 0 && this.present[0].ptsUs / 1e6 <= e + .005;) t && this.options.dropLateFrames && this.dropped++, t = this.present.shift();
3273
- t && this.render(t), this.scheduleDecode(), (this.present.length > 0 || this.backlog.length > 0) && (this.rafId = requestAnimationFrame(this.tick));
3274
- }), this.options = e, this.canvas = t, this.audio = new Tt({
4012
+ for (; this.present.length > 0 && this.present[0].ptsUs / 1e6 <= e + .005;) t && (t.bitmap?.close(), this.options.dropLateFrames && this.dropped++), t = this.present.shift();
4013
+ t && (t.bitmap ? this.renderBitmap(t.bitmap) : t.frame && this.render(t.frame)), this.worker ? this.pumpWorker() : this.scheduleDecode(), (this.present.length > 0 || this.backlog.length > 0) && (this.rafId = requestAnimationFrame(this.tick));
4014
+ }), this.options = e, this.canvas = t, this.audio = new zt({
3275
4015
  volume: e.volume,
3276
4016
  onError: e.onError
3277
4017
  });
@@ -3280,47 +4020,135 @@ var Pt = "\nattribute vec2 aPos;\nuniform vec4 uTexRange;\nvarying vec2 vTex;\nv
3280
4020
  return {
3281
4021
  decodedVideoFrames: this.decoded,
3282
4022
  droppedVideoFrames: this.dropped,
3283
- decodedAudioFrames: this.audio.decodedFrames
4023
+ decodedAudioFrames: this.audio.decodedFrames,
4024
+ audioPeak: this.audio.peak,
4025
+ audioState: this.audio.state,
4026
+ audioVolume: this.audio.volumeLevel,
4027
+ audioPath: this.audio.configured ? "webaudio" : "none"
3284
4028
  };
3285
4029
  }
3286
4030
  get currentTime() {
3287
4031
  return this.anchored ? this.mediaTime() : 0;
3288
4032
  }
3289
4033
  get framesPending() {
3290
- return this.present.length + this.backlog.length + +!!this.decoding;
4034
+ return this.present.length + this.backlog.length + +!!this.decoding + this.workerInFlight + +!!this.workerFlushPending;
4035
+ }
4036
+ get usingWorker() {
4037
+ return this.worker !== null;
3291
4038
  }
3292
4039
  get backlogSeconds() {
3293
4040
  let e = this.backlog.length > 0 ? this.backlog[this.backlog.length - 1].ptsUs : this.present.length > 0 ? this.present[this.present.length - 1].ptsUs : 0;
3294
4041
  return e > 0 ? Math.max(0, e / 1e6 - this.mediaTime()) : 0;
3295
4042
  }
3296
4043
  get decoderName() {
3297
- return this.decoder?.name ?? "none";
4044
+ return this.workerName || this.decoder?.name || "none";
4045
+ }
4046
+ captureStream() {
4047
+ let e = this.canvas;
4048
+ return typeof e.captureStream == "function" ? e.captureStream(30) : null;
4049
+ }
4050
+ captureAudioStream() {
4051
+ return this.audio.captureStream();
3298
4052
  }
3299
4053
  async attach(e) {
3300
4054
  let t = e.find((e) => e.kind === "video");
3301
- t && !this.decoder && (this.decoder = await Nt(t, this.options.loaders), this.videoTrack = t, this.resize(), this.observeResize());
4055
+ if (t && !this.decoder && !this.worker) {
4056
+ this.videoTrack = t;
4057
+ let e = !1;
4058
+ this.options.worker && (e = await this.initWorker(t)), e || (this.decoder = await cn(t, this.options.loaders)), this.resize(), this.observeResize();
4059
+ }
3302
4060
  let n = e.find((e) => e.kind === "audio");
3303
4061
  n && !this.audio.configured && this.audio.configure(n);
3304
4062
  }
4063
+ async initWorker(e) {
4064
+ let t = null;
4065
+ try {
4066
+ let n = this.options.worker;
4067
+ t = typeof n == "function" ? n() : new Worker(n, { type: "module" });
4068
+ let r = await new Promise((n, r) => {
4069
+ let i = window.setTimeout(() => r(/* @__PURE__ */ Error("soft worker init timeout")), 8e3);
4070
+ t.onerror = (e) => {
4071
+ window.clearTimeout(i), r(Error(e.message || "soft worker error"));
4072
+ }, t.onmessage = (e) => {
4073
+ let t = e.data;
4074
+ t.type === "ready" ? (window.clearTimeout(i), n(t.name)) : t.type === "error" && (window.clearTimeout(i), r(Error(t.message)));
4075
+ };
4076
+ let a = e.codecPrivate.slice();
4077
+ t.postMessage({
4078
+ type: "init",
4079
+ track: {
4080
+ ...e,
4081
+ codecPrivate: a
4082
+ },
4083
+ modules: this.options.modules
4084
+ }, [a.buffer]);
4085
+ });
4086
+ return t.onmessage = (e) => this.onWorkerMessage(e.data), t.onerror = (e) => {
4087
+ this.options.onError?.(Error(e.message || "soft worker error"));
4088
+ }, this.worker = t, this.workerReady = !0, this.workerName = r, console.info(`[fluxkit] software decode worker: ${r}`), !0;
4089
+ } catch (e) {
4090
+ return t?.terminate(), console.warn("[fluxkit] software worker unavailable, falling back to the main thread", e), !1;
4091
+ }
4092
+ }
4093
+ onWorkerMessage(e) {
4094
+ if (e.type === "frames") {
4095
+ this.workerFlushPending && e.id === this.workerFlushId ? this.workerFlushPending = !1 : this.workerInFlight = Math.max(0, this.workerInFlight - 1);
4096
+ for (let t of e.frames) t.ptsUs < this.dropBeforeUs ? (t.bitmap.close(), this.dropped++) : (this.decoded++, this.present.push({
4097
+ ptsUs: t.ptsUs,
4098
+ bitmap: t.bitmap
4099
+ }), t.ptsUs > this.lastDecodedPtsUs && (this.lastDecodedPtsUs = t.ptsUs));
4100
+ this.present.length > 1 && this.present.sort((e, t) => e.ptsUs - t.ptsUs), !this.anchored && this.present.length > 0 && (this.anchored = !0, this.anchorMedia = this.present[0].ptsUs / 1e6, this.anchorWall = performance.now()), this.startRaf(), this.pumpWorker();
4101
+ } else e.type === "error" && (this.workerFlushPending && e.id === this.workerFlushId ? this.workerFlushPending = !1 : this.workerInFlight = Math.max(0, this.workerInFlight - 1), this.options.onError?.(Error(e.message)));
4102
+ }
4103
+ pumpWorker() {
4104
+ let e = this.worker;
4105
+ if (e && this.workerReady && !this.paused && !this.destroyed && !(this.present.length >= this.options.maxDecodeAhead)) for (; this.workerInFlight < this.workerMaxInFlight && this.backlog.length > 0;) {
4106
+ let t = this.backlog.shift(), n = ++this.workerId;
4107
+ this.workerInFlight++, e.postMessage({
4108
+ type: "decode",
4109
+ id: n,
4110
+ data: t.annexB,
4111
+ ptsUs: t.ptsUs,
4112
+ keyframe: t.keyframe
4113
+ }, [t.annexB.buffer]);
4114
+ }
4115
+ }
3305
4116
  write(e, t) {
3306
4117
  if (!(this.destroyed || t.length === 0)) {
3307
4118
  if (e.kind === "video") {
3308
- if (!this.decoder) return;
3309
- for (let n of t) this.backlog.push({
3310
- annexB: fe(n.data),
3311
- ptsUs: Math.round(n.pts * 1e6 / e.timescale),
3312
- keyframe: n.keyframe
3313
- });
3314
- this.scheduleDecode();
4119
+ if (!this.decoder && !this.worker) return;
4120
+ for (let n of t) {
4121
+ if (this.awaitingKeyframe) {
4122
+ if (!n.keyframe) continue;
4123
+ this.awaitingKeyframe = !1;
4124
+ }
4125
+ this.backlog.push({
4126
+ annexB: he(n.data),
4127
+ ptsUs: Math.round(n.pts * 1e6 / e.timescale),
4128
+ keyframe: n.keyframe
4129
+ });
4130
+ }
4131
+ this.maybeResync(), this.worker ? this.pumpWorker() : this.scheduleDecode();
3315
4132
  } else this.audio.write(t);
3316
4133
  }
3317
4134
  }
3318
4135
  scheduleDecode() {
3319
- this.decoding || this.destroyed || this.paused || !this.decoder || this.present.length >= this.options.maxDecodeAhead || this.backlog.length !== 0 && (this.decoding = !0, this.timer = setTimeout(this.decodeStep, 0));
4136
+ this.worker || this.decoding || this.destroyed || this.paused || !this.decoder || this.present.length >= this.options.maxDecodeAhead || this.backlog.length !== 0 && (this.decoding = !0, this.timer = setTimeout(this.decodeStep, 0));
4137
+ }
4138
+ maybeResync() {
4139
+ if (!this.options.live || !this.anchored || this.destroyed || this.lastDecodedPtsUs < 0) return;
4140
+ let e = this.mediaTime();
4141
+ if (e - this.lastDecodedPtsUs / 1e6 <= un) return;
4142
+ let t = ln(this.backlog, e);
4143
+ if (t.cut === 0 && !t.awaitingKeyframe) return;
4144
+ t.cut > 0 && this.backlog.splice(0, t.cut), this.awaitingKeyframe = t.awaitingKeyframe, this.dropBeforeUs = Math.round((e - .2) * 1e6);
4145
+ let n = [];
4146
+ for (let e of this.present) e.ptsUs >= this.dropBeforeUs ? n.push(e) : (e.bitmap?.close(), this.dropped++);
4147
+ this.present = n;
3320
4148
  }
3321
4149
  mediaTime() {
3322
4150
  let e = this.audio.clock;
3323
- return e === null ? this.anchorMedia + (performance.now() - this.anchorWall) / 1e3 : e;
4151
+ return e === null ? this.anchorMedia + (performance.now() - this.anchorWall) / 1e3 * this.rate : e;
3324
4152
  }
3325
4153
  startRaf() {
3326
4154
  this.rafId !== 0 || this.paused || this.destroyed || (this.rafId = requestAnimationFrame(this.tick));
@@ -3334,6 +4162,26 @@ var Pt = "\nattribute vec2 aPos;\nuniform vec4 uTexRange;\nvarying vec2 vTex;\nv
3334
4162
  let e = this.canvas.parentElement;
3335
4163
  e && (this.resizeObserver = new ResizeObserver(() => this.resize()), this.resizeObserver.observe(e));
3336
4164
  }
4165
+ renderBitmap(e) {
4166
+ let t = e.width, n = e.height;
4167
+ !this.firstFrameReported && t > 0 && n > 0 && (this.firstFrameReported = !0, this.options.onFirstFrame?.(t, n)), this.resize(), this.ctx2d || (this.ctx2d = this.canvas.getContext("2d"));
4168
+ let r = this.ctx2d;
4169
+ if (!r) {
4170
+ e.close();
4171
+ return;
4172
+ }
4173
+ let i = this.canvas.width, a = this.canvas.height;
4174
+ r.fillStyle = "#000", r.fillRect(0, 0, i, a);
4175
+ let o = i, s = a;
4176
+ if (this.options.fit === "contain") {
4177
+ let e = Math.min(i / t, a / n);
4178
+ o = t * e, s = n * e;
4179
+ } else if (this.options.fit === "cover") {
4180
+ let e = Math.max(i / t, a / n);
4181
+ o = t * e, s = n * e;
4182
+ }
4183
+ r.drawImage(e, (i - o) / 2, (a - s) / 2, o, s), e.close();
4184
+ }
3337
4185
  render(e) {
3338
4186
  this.firstFrameReported || (this.firstFrameReported = !0, this.options.onFirstFrame?.(e.crop.width, e.crop.height)), this.resize(), !this.gl && !this.glFailed && this.initGl(), this.gl ? this.renderGl(e) : this.render2d(e);
3339
4187
  }
@@ -3344,7 +4192,7 @@ var Pt = "\nattribute vec2 aPos;\nuniform vec4 uTexRange;\nvarying vec2 vTex;\nv
3344
4192
  antialias: !1,
3345
4193
  depth: !1,
3346
4194
  stencil: !1,
3347
- preserveDrawingBuffer: !1,
4195
+ preserveDrawingBuffer: !0,
3348
4196
  desynchronized: !0
3349
4197
  });
3350
4198
  if (!e) {
@@ -3356,7 +4204,7 @@ var Pt = "\nattribute vec2 aPos;\nuniform vec4 uTexRange;\nvarying vec2 vTex;\nv
3356
4204
  if (e.shaderSource(r, n), e.compileShader(r), !e.getShaderParameter(r, e.COMPILE_STATUS)) throw Error(`shader compile failed: ${e.getShaderInfoLog(r)}`);
3357
4205
  return r;
3358
4206
  }, n = e.createProgram();
3359
- if (e.attachShader(n, t(e.VERTEX_SHADER, Pt)), e.attachShader(n, t(e.FRAGMENT_SHADER, Ft)), e.linkProgram(n), !e.getProgramParameter(n, e.LINK_STATUS)) throw Error(`program link failed: ${e.getProgramInfoLog(n)}`);
4207
+ if (e.attachShader(n, t(e.VERTEX_SHADER, dn)), e.attachShader(n, t(e.FRAGMENT_SHADER, fn)), e.linkProgram(n), !e.getProgramParameter(n, e.LINK_STATUS)) throw Error(`program link failed: ${e.getProgramInfoLog(n)}`);
3360
4208
  e.useProgram(n);
3361
4209
  let r = e.getUniformLocation(n, "uTexRange"), i = e.getUniformLocation(n, "uY"), a = e.getUniformLocation(n, "uU"), o = e.getUniformLocation(n, "uV");
3362
4210
  if (!r || !i || !a || !o) throw Error("missing uniforms");
@@ -3448,7 +4296,7 @@ var Pt = "\nattribute vec2 aPos;\nuniform vec4 uTexRange;\nvarying vec2 vTex;\nv
3448
4296
  l.drawImage(this.tmpCanvas, (u - f) / 2, (d - p) / 2, f, p);
3449
4297
  }
3450
4298
  setPaused(e) {
3451
- e !== this.paused && (this.paused = e, this.audio.setPaused(e), e ? (this.rafId && cancelAnimationFrame(this.rafId), this.rafId = 0) : (this.anchored = !1, this.present.length > 0 && (this.anchored = !0, this.anchorMedia = this.present[0].ptsUs / 1e6, this.anchorWall = performance.now()), this.scheduleDecode(), this.startRaf()));
4299
+ e !== this.paused && (this.paused = e, this.audio.setPaused(e), e ? (this.rafId && cancelAnimationFrame(this.rafId), this.rafId = 0) : (this.anchored = !1, this.present.length > 0 && (this.anchored = !0, this.anchorMedia = this.present[0].ptsUs / 1e6, this.anchorWall = performance.now()), this.worker ? this.pumpWorker() : this.scheduleDecode(), this.startRaf()));
3452
4300
  }
3453
4301
  resumeAudio() {
3454
4302
  return this.audio.resume();
@@ -3456,31 +4304,435 @@ var Pt = "\nattribute vec2 aPos;\nuniform vec4 uTexRange;\nvarying vec2 vTex;\nv
3456
4304
  setVolume(e) {
3457
4305
  this.audio.setVolume(e);
3458
4306
  }
4307
+ setPlaybackRate(e) {
4308
+ if (!Number.isFinite(e) || e <= 0) return;
4309
+ let t = this.anchored ? this.mediaTime() : 0;
4310
+ this.rate = Math.min(4, Math.max(.25, e)), this.audio.setRate(this.rate), this.anchored && (this.anchorMedia = t, this.anchorWall = performance.now());
4311
+ }
3459
4312
  flush() {}
3460
4313
  endOfStream() {
3461
- if (!this.ended && this.decoder) {
3462
- this.ended = !0;
3463
- try {
3464
- for (let e of this.decoder.flush()) this.decoded++, this.present.push(e);
3465
- } catch {}
3466
- this.startRaf();
4314
+ if (this.ended) return;
4315
+ if (this.worker) {
4316
+ if (!this.workerReady) return;
4317
+ this.ended = !0, this.workerFlushPending = !0, this.workerFlushId = ++this.workerId, this.worker.postMessage({
4318
+ type: "flush",
4319
+ id: this.workerFlushId
4320
+ });
4321
+ return;
3467
4322
  }
4323
+ if (!this.decoder) return;
4324
+ this.ended = !0;
4325
+ let e = this.decoder;
4326
+ Promise.resolve(e.flush()).then((e) => {
4327
+ if (!this.destroyed) {
4328
+ for (let t of e) this.decoded++, this.present.push({
4329
+ ptsUs: t.ptsUs,
4330
+ frame: t
4331
+ });
4332
+ this.startRaf();
4333
+ }
4334
+ }).catch(() => {});
3468
4335
  }
3469
4336
  reset() {
3470
- this.backlog = [], this.present = [], this.anchored = !1, this.ended = !1, this.audio.reset();
4337
+ this.backlog = [];
4338
+ for (let e of this.present) e.bitmap?.close();
4339
+ this.present = [], this.anchored = !1, this.ended = !1, this.lastDecodedPtsUs = -1, this.dropBeforeUs = 0, this.awaitingKeyframe = !1, this.audio.reset();
3471
4340
  }
3472
4341
  destroy() {
3473
4342
  this.destroyed = !0, this.timer !== null && clearTimeout(this.timer), this.rafId && cancelAnimationFrame(this.rafId), this.resizeObserver?.disconnect(), this.resizeObserver = null;
3474
4343
  try {
3475
4344
  this.decoder?.close();
3476
4345
  } catch {}
3477
- if (this.decoder = null, this.audio.destroy(), this.gl) {
4346
+ if (this.decoder = null, this.worker) {
4347
+ try {
4348
+ this.worker.postMessage({ type: "close" });
4349
+ } catch {}
4350
+ this.worker.terminate(), this.worker = null, this.workerReady = !1;
4351
+ }
4352
+ for (let e of this.present) e.bitmap?.close();
4353
+ if (this.present = [], this.audio.destroy(), this.gl) {
3478
4354
  let { gl: e } = this.gl;
3479
4355
  for (let t of this.gl.textures) e.deleteTexture(t);
3480
4356
  e.deleteBuffer(this.gl.quad), e.deleteProgram(this.gl.program), this.gl = null;
3481
4357
  }
3482
4358
  }
3483
- }, It = "0.1.0", Lt = {
4359
+ }, Q = {
4360
+ play: "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M8 5.14v13.72c0 .8.86 1.3 1.55.9l11.02-6.86a1.05 1.05 0 0 0 0-1.8L9.55 4.24A1.05 1.05 0 0 0 8 5.14Z\"/></svg>",
4361
+ pause: "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect x=\"6\" y=\"4.5\" width=\"4\" height=\"15\" rx=\"1\"/><rect x=\"14\" y=\"4.5\" width=\"4\" height=\"15\" rx=\"1\"/></svg>",
4362
+ stop: "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\"/></svg>",
4363
+ volume: "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M4 9.5v5h3.2l4.3 3.4V6.1L7.2 9.5H4Zm11.1-2.1a1 1 0 0 1 1.4 1.4 4.4 4.4 0 0 1 0 6.4 1 1 0 1 1-1.4-1.4 2.4 2.4 0 0 0 0-3.6 1 1 0 0 1 0-2.8Z\"/></svg>",
4364
+ muted: "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M4 9.5v5h3.2l4.3 3.4V6.1L7.2 9.5H4Zm11.3 1 1.8-1.8 1.4 1.4-1.8 1.8 1.8 1.8-1.4 1.4-1.8-1.8-1.8 1.8-1.4-1.4 1.8-1.8-1.8-1.8 1.4-1.4 1.8 1.8Z\"/></svg>",
4365
+ camera: "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M9 4 7.7 6H5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-2.7L15 4H9Zm3 4.5a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9Zm0 2a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z\"/></svg>",
4366
+ record: "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"6\"/></svg>",
4367
+ recordStop: "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect x=\"7\" y=\"7\" width=\"10\" height=\"10\" rx=\"2\"/></svg>",
4368
+ fullscreen: "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M4 4h6v2H6v4H4V4Zm10 0h6v6h-2V6h-4V4ZM4 14h2v4h4v2H4v-6Zm14 0h2v6h-6v-2h4v-4Z\"/></svg>",
4369
+ pip: "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M3 5h18a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm1 2v10h16V7H4Zm9 4h5v5h-5v-5Z\"/></svg>",
4370
+ exitFullscreen: "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M9 4h2v5H6V7h3V4Zm4 0h2v3h3v2h-5V4ZM6 15h5v5H9v-3H6v-2Zm8 0h5v2h-3v3h-2v-5Z\"/></svg>"
4371
+ }, pn = "fluxkit-controls-style";
4372
+ function mn() {
4373
+ if (typeof document > "u" || document.getElementById(pn)) return;
4374
+ let e = document.createElement("style");
4375
+ e.id = pn, e.textContent = "\n.fk-controls{position:absolute;left:0;right:0;bottom:0;z-index:30;box-sizing:border-box;padding:34px 12px 10px;background:linear-gradient(to top,rgba(4,7,12,.82),rgba(4,7,12,.4) 55%,rgba(4,7,12,0));color:#fff;font:12px/1.4 ui-sans-serif,system-ui,-apple-system,\"Segoe UI\",sans-serif;user-select:none;transition:opacity .2s ease;outline:none}\n.fk-controls[data-visible=\"false\"]{opacity:0;pointer-events:none}\n.fk-controls:focus-visible{box-shadow:inset 0 0 0 2px rgba(91,140,255,.7)}\n.fk-progress{position:relative;height:4px;border-radius:999px;background:rgba(255,255,255,.22);cursor:pointer;touch-action:none}\n.fk-controls.fk-is-live .fk-progress{cursor:default}\n.fk-buffer,.fk-played{position:absolute;top:0;bottom:0;left:0;height:100%;border-radius:999px}\n.fk-buffer{background:rgba(255,255,255,.3)}\n.fk-played{background:#5b8cff}\n.fk-thumb{position:absolute;top:50%;left:0;width:11px;height:11px;border-radius:50%;background:#fff;transform:translate(-50%,-50%);box-shadow:0 0 0 2px rgba(91,140,255,.65);pointer-events:none}\n.fk-controls.fk-is-live .fk-thumb{display:none}\n.fk-row{display:flex;align-items:center;gap:6px;margin-top:8px}\n.fk-btn{width:30px;height:30px;display:grid;place-items:center;padding:0;border:0;border-radius:8px;background:transparent;color:#fff;cursor:pointer;flex:none}\n.fk-btn:hover{background:rgba(255,255,255,.13)}\n.fk-btn:focus-visible{outline:2px solid #5b8cff;outline-offset:1px}\n.fk-btn svg{width:18px;height:18px;fill:currentColor;display:block}\n.fk-btn.fk-rec{color:#ff5c7a}\n.fk-controls.fk-recording .fk-rec{background:rgba(255,92,122,.16)}\n.fk-time{white-space:nowrap;font-variant-numeric:tabular-nums;color:rgba(255,255,255,.88);margin:0 4px}\n.fk-live{display:none;align-items:center;gap:5px;font-size:10px;font-weight:700;letter-spacing:.7px;color:#ff5c7a;margin-left:2px;padding:2px 4px;border:0;background:transparent;border-radius:4px;cursor:pointer;font-family:inherit}\n.fk-live:hover{background:rgba(255,92,122,.14)}\n.fk-controls.fk-is-live .fk-live{display:inline-flex}\n.fk-live::before{content:\"\";width:6px;height:6px;border-radius:50%;background:#ff5c7a}\n.fk-rec-time{display:none;color:#ff5c7a;font-variant-numeric:tabular-nums;font-size:11px}\n.fk-controls.fk-recording .fk-rec-time{display:inline}\n.fk-volume{display:flex;align-items:center;gap:3px}\n.fk-volume input{width:70px;accent-color:#5b8cff;height:14px;cursor:pointer}\n.fk-spacer{flex:1}\n.fk-rate{background:rgba(0,0,0,.3);border:1px solid rgba(255,255,255,.18);color:#fff;border-radius:6px;font:11px/1.4 inherit;padding:2px 4px;cursor:pointer;outline:none}\n.fk-rate option{background:#121722;color:#fff}\n.fk-spinner{position:absolute;inset:0;display:none;place-items:center;z-index:26;pointer-events:none}\n.fk-spinner[data-show=\"true\"]{display:grid}\n.fk-spinner::after{content:\"\";width:34px;height:34px;border-radius:50%;border:3px solid rgba(255,255,255,.22);border-top-color:#fff;animation:fk-spin .8s linear infinite}\n@keyframes fk-spin{to{transform:rotate(360deg)}}\n.fk-toast{position:absolute;left:50%;bottom:78px;transform:translateX(-50%);max-width:82%;display:none;z-index:40;padding:8px 12px;border-radius:8px;background:rgba(18,23,34,.94);color:#ffd7de;font-size:12px;line-height:1.45;box-shadow:0 8px 24px rgba(0,0,0,.35);white-space:pre-wrap;word-break:break-word}\n.fk-toast[data-show=\"true\"]{display:block}\n@media (max-width:560px){.fk-rate,.fk-pip{display:none!important}}\n@media (max-width:560px){.fk-volume input{width:46px}.fk-time{font-size:11px}.fk-controls{padding-left:8px;padding-right:8px}}\n@media (prefers-reduced-motion:reduce){.fk-controls{transition:none}}\n", document.head.appendChild(e);
4376
+ }
4377
+ function $(e) {
4378
+ if (!Number.isFinite(e) || e < 0) return "--:--";
4379
+ let t = Math.floor(e / 1e3), n = Math.floor(t / 3600), r = Math.floor(t % 3600 / 60), i = t % 60;
4380
+ return n > 0 ? `${n}:${String(r).padStart(2, "0")}:${String(i).padStart(2, "0")}` : `${String(r).padStart(2, "0")}:${String(i).padStart(2, "0")}`;
4381
+ }
4382
+ function hn(e, t) {
4383
+ let n = URL.createObjectURL(e), r = document.createElement("a");
4384
+ r.href = n, r.download = t, r.style.display = "none", document.body.appendChild(r), r.click(), r.remove(), setTimeout(() => URL.revokeObjectURL(n), 1500);
4385
+ }
4386
+ function gn() {
4387
+ let e = /* @__PURE__ */ new Date(), t = (e) => String(e).padStart(2, "0");
4388
+ return `${e.getFullYear()}${t(e.getMonth() + 1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`;
4389
+ }
4390
+ var _n = class {
4391
+ constructor(e, t, n) {
4392
+ r(this, "player", void 0), r(this, "container", void 0), r(this, "options", void 0), r(this, "root", void 0), r(this, "progress", void 0), r(this, "bufferBar", void 0), r(this, "playedBar", void 0), r(this, "thumb", void 0), r(this, "playButton", void 0), r(this, "stopButton", void 0), r(this, "muteButton", void 0), r(this, "volumeInput", void 0), r(this, "timeLabel", void 0), r(this, "recTime", void 0), r(this, "shotButton", null), r(this, "recordButton", null), r(this, "fullscreenButton", null), r(this, "pipButton", null), r(this, "rateSelect", null), r(this, "spinner", void 0), r(this, "toast", void 0), r(this, "toastTimer", 0), r(this, "cleanups", []), r(this, "timer", 0), r(this, "hideTimer", 0), r(this, "dragging", !1), r(this, "recordStartedAt", 0), r(this, "destroyed", !1), this.player = e, this.container = t, this.options = n, mn(), getComputedStyle(t).position === "static" && (t.style.position = "relative"), t.hasAttribute("tabindex") || (t.tabIndex = 0), this.root = document.createElement("div"), this.root.className = "fk-controls", this.root.dataset.visible = "true", this.root.innerHTML = `
4393
+ <div class="fk-progress" role="slider" tabindex="0" aria-label="播放进度" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
4394
+ <div class="fk-buffer"></div>
4395
+ <div class="fk-played"></div>
4396
+ <div class="fk-thumb"></div>
4397
+ </div>
4398
+ <div class="fk-row">
4399
+ <button class="fk-btn" data-action="play" aria-label="播放"></button>
4400
+ <button class="fk-btn" data-action="stop" aria-label="停止">${Q.stop}</button>
4401
+ <div class="fk-volume">
4402
+ <button class="fk-btn" data-action="mute" aria-label="静音"></button>
4403
+ <input type="range" min="0" max="1" step="0.01" value="1" aria-label="音量" />
4404
+ </div>
4405
+ <span class="fk-time">00:00 / --:--</span>
4406
+ <button class="fk-live" type="button" aria-label="跳到直播最新">LIVE</button>
4407
+ <span class="fk-spacer"></span>
4408
+ <span class="fk-rec-time"></span>
4409
+ <select class="fk-rate" aria-label="播放速度">
4410
+ <option value="0.5">0.5x</option>
4411
+ <option value="0.75">0.75x</option>
4412
+ <option value="1" selected>1x</option>
4413
+ <option value="1.25">1.25x</option>
4414
+ <option value="1.5">1.5x</option>
4415
+ <option value="2">2x</option>
4416
+ </select>
4417
+ ${document.pictureInPictureEnabled ? `<button class="fk-btn fk-pip" data-action="pip" aria-label="画中画">${Q.pip}</button>` : ""}
4418
+ ${this.options.screenshot ? `<button class="fk-btn" data-action="shot" aria-label="截图">${Q.camera}</button>` : ""}
4419
+ ${this.options.record ? `<button class="fk-btn fk-rec" data-action="record" aria-label="录制">${Q.record}</button>` : ""}
4420
+ ${this.options.fullscreen ? `<button class="fk-btn" data-action="fullscreen" aria-label="全屏">${Q.fullscreen}</button>` : ""}
4421
+ </div>`, t.appendChild(this.root), this.progress = this.query(".fk-progress"), this.bufferBar = this.query(".fk-buffer"), this.playedBar = this.query(".fk-played"), this.thumb = this.query(".fk-thumb"), this.playButton = this.query("[data-action=\"play\"]"), this.stopButton = this.query("[data-action=\"stop\"]"), this.muteButton = this.query("[data-action=\"mute\"]"), this.volumeInput = this.query(".fk-volume input"), this.timeLabel = this.query(".fk-time"), this.recTime = this.query(".fk-rec-time"), this.shotButton = this.root.querySelector("[data-action=\"shot\"]"), this.recordButton = this.root.querySelector("[data-action=\"record\"]"), this.fullscreenButton = this.root.querySelector("[data-action=\"fullscreen\"]"), this.pipButton = this.root.querySelector("[data-action=\"pip\"]"), this.rateSelect = this.root.querySelector(".fk-rate"), this.spinner = document.createElement("div"), this.spinner.className = "fk-spinner", this.spinner.dataset.show = "false", t.appendChild(this.spinner), this.toast = document.createElement("div"), this.toast.className = "fk-toast", this.toast.dataset.show = "false", t.appendChild(this.toast), this.bind(), this.updatePlayButton(), this.updateVolume(), this.updateProgress();
4422
+ }
4423
+ query(e) {
4424
+ let t = this.root.querySelector(e);
4425
+ if (!t) throw Error(`FluxKit controls: missing ${e}`);
4426
+ return t;
4427
+ }
4428
+ bind() {
4429
+ let e = (e, t, n, r) => {
4430
+ e.addEventListener(t, n, r), this.cleanups.push(() => e.removeEventListener(t, n, r));
4431
+ };
4432
+ e(this.playButton, "click", () => this.togglePlay()), e(this.stopButton, "click", () => {
4433
+ this.player.stop(), this.updatePlayButton(), this.updateProgress();
4434
+ }), e(this.muteButton, "click", () => {
4435
+ this.player.setMuted(!this.player.muted), this.updateVolume();
4436
+ }), e(this.volumeInput, "input", () => {
4437
+ let e = Number(this.volumeInput.value);
4438
+ this.player.setVolume(e), e > 0 && this.player.muted && this.player.setMuted(!1), this.updateVolume();
4439
+ }), e(this.progress, "pointerdown", (e) => this.onPointerDown(e)), e(this.progress, "pointermove", (e) => {
4440
+ this.dragging && this.onPointerMove(e);
4441
+ }), e(this.progress, "pointerup", (e) => this.onPointerUp(e)), e(this.progress, "pointercancel", (e) => this.onPointerUp(e)), e(this.progress, "keydown", (e) => {
4442
+ if (this.player.isLive) return;
4443
+ let t = e.key;
4444
+ if (t === "ArrowLeft") this.player.seek(Math.max(0, this.player.currentTime - 5e3));
4445
+ else if (t === "ArrowRight") this.player.seek(this.player.currentTime + 5e3);
4446
+ else if (t === "Home") this.player.seek(0);
4447
+ else if (t === "End") this.player.seek(Math.max(0, this.player.duration - 1e3));
4448
+ else return;
4449
+ e.preventDefault();
4450
+ }), this.shotButton && e(this.shotButton, "click", () => void this.takeSnapshot()), this.recordButton && e(this.recordButton, "click", () => void this.toggleRecording()), this.fullscreenButton && e(this.fullscreenButton, "click", () => void this.player.toggleFullscreen()), this.pipButton && e(this.pipButton, "click", () => void this.player.togglePictureInPicture()), this.rateSelect && e(this.rateSelect, "change", () => {
4451
+ this.player.setPlaybackRate(Number(this.rateSelect.value));
4452
+ });
4453
+ let t = this.root.querySelector(".fk-live");
4454
+ t && e(t, "click", () => void this.player.seekToLive());
4455
+ let n = () => this.updatePipButton(), r = this.player.videoElement;
4456
+ r.addEventListener("enterpictureinpicture", n), r.addEventListener("leavepictureinpicture", n), this.cleanups.push(() => {
4457
+ r.removeEventListener("enterpictureinpicture", n), r.removeEventListener("leavepictureinpicture", n);
4458
+ }), this.cleanups.push(this.player.on("play", () => {
4459
+ this.updatePlayButton(), this.scheduleHide();
4460
+ }), this.player.on("pause", () => {
4461
+ this.updatePlayButton(), this.show(!1);
4462
+ }), this.player.on("ready", () => this.updateProgress()), this.player.on("metadata", () => this.updateProgress()), this.player.on("ended", () => {
4463
+ this.updatePlayButton(), this.show(!1);
4464
+ }), this.player.on("stats", () => this.updateProgress()), this.player.on("loading", ({ loading: e }) => {
4465
+ this.spinner.dataset.show = String(e);
4466
+ }), this.player.on("error", (e) => this.showToast(e instanceof Error ? e.message : String(e))), this.player.on("reconnecting", ({ attempt: e, max: t }) => this.showToast(`连接中断,正在重连 (${e}/${t})…`)), this.player.on("reconnected", () => this.showToast("已重新连接")), this.player.on("ready", () => {
4467
+ this.updateRateVisibility(), this.updatePipButton();
4468
+ }));
4469
+ let i = () => this.show(!0);
4470
+ e(this.container, "pointermove", i), e(this.container, "pointerdown", i), e(this.container, "touchstart", i, { passive: !0 }), e(this.container, "keydown", (e) => this.onKeyDown(e)), e(document, "fullscreenchange", () => this.updateFullscreenButton()), this.timer = window.setInterval(() => {
4471
+ this.destroyed || (this.updateProgress(), this.updateRecordTimer());
4472
+ }, 250), this.updateFullscreenButton();
4473
+ }
4474
+ onKeyDown(e) {
4475
+ let t = e.target;
4476
+ if (!(t && /^(INPUT|TEXTAREA|SELECT|BUTTON)$/.test(t.tagName))) {
4477
+ switch (e.key) {
4478
+ case " ":
4479
+ case "k":
4480
+ case "K":
4481
+ this.togglePlay();
4482
+ break;
4483
+ case "ArrowLeft":
4484
+ this.player.seek(Math.max(0, this.player.currentTime - 5e3));
4485
+ break;
4486
+ case "ArrowRight":
4487
+ this.player.seek(this.player.currentTime + 5e3);
4488
+ break;
4489
+ case "m":
4490
+ case "M":
4491
+ this.player.setMuted(!this.player.muted), this.updateVolume();
4492
+ break;
4493
+ case "f":
4494
+ case "F":
4495
+ this.player.toggleFullscreen();
4496
+ break;
4497
+ default: return;
4498
+ }
4499
+ e.preventDefault();
4500
+ }
4501
+ }
4502
+ togglePlay() {
4503
+ this.player.paused ? this.player.play() : this.player.pause();
4504
+ }
4505
+ updatePlayButton() {
4506
+ let e = this.player.paused;
4507
+ this.playButton.innerHTML = e ? Q.play : Q.pause, this.playButton.setAttribute("aria-label", e ? "播放" : "暂停");
4508
+ }
4509
+ updateVolume() {
4510
+ let e = this.player.muted, t = e ? 0 : this.player.volume;
4511
+ this.volumeInput.value = String(t), this.muteButton.innerHTML = e || t === 0 ? Q.muted : Q.volume, this.muteButton.setAttribute("aria-label", e ? "取消静音" : "静音");
4512
+ }
4513
+ onPointerDown(e) {
4514
+ this.player.isLive || (this.dragging = !0, this.progress.setPointerCapture?.(e.pointerId), this.seekToPointer(e));
4515
+ }
4516
+ onPointerMove(e) {
4517
+ this.dragging && this.seekToPointer(e);
4518
+ }
4519
+ onPointerUp(e) {
4520
+ if (this.dragging) {
4521
+ this.dragging = !1;
4522
+ try {
4523
+ this.progress.releasePointerCapture?.(e.pointerId);
4524
+ } catch {}
4525
+ }
4526
+ }
4527
+ seekToPointer(e) {
4528
+ let t = this.player.duration;
4529
+ if (!Number.isFinite(t) || t <= 0) return;
4530
+ let n = this.progress.getBoundingClientRect(), r = Math.min(1, Math.max(0, (e.clientX - n.left) / Math.max(1, n.width)));
4531
+ this.player.seek(r * t);
4532
+ }
4533
+ bufferedEndMs() {
4534
+ try {
4535
+ let e = this.player.videoElement.buffered, t = 0;
4536
+ for (let n = 0; n < e.length; n++) t = Math.max(t, e.end(n));
4537
+ return t * 1e3;
4538
+ } catch {
4539
+ return 0;
4540
+ }
4541
+ }
4542
+ updateProgress() {
4543
+ let e = this.player.duration, t = this.player.isLive || !Number.isFinite(e) || e <= 0;
4544
+ if (this.root.classList.toggle("fk-is-live", t), t) {
4545
+ this.playedBar.style.width = "100%", this.bufferBar.style.width = "100%", this.thumb.style.left = "100%", this.timeLabel.textContent = $(this.player.currentTime), this.progress.setAttribute("aria-disabled", "true"), this.progress.setAttribute("aria-valuenow", "100");
4546
+ return;
4547
+ }
4548
+ let n = Math.min(1, Math.max(0, this.player.currentTime / e));
4549
+ this.playedBar.style.width = `${n * 100}%`, this.thumb.style.left = `${n * 100}%`;
4550
+ let r = Math.min(1, Math.max(0, this.bufferedEndMs() / e));
4551
+ this.bufferBar.style.width = `${r * 100}%`, this.timeLabel.textContent = `${$(this.player.currentTime)} / ${$(e)}`, this.progress.setAttribute("aria-disabled", "false"), this.progress.setAttribute("aria-valuenow", String(Math.round(n * 100)));
4552
+ }
4553
+ async takeSnapshot() {
4554
+ try {
4555
+ hn(await this.player.snapshot(), `${this.options.downloadName}-${gn()}.png`);
4556
+ } catch (e) {
4557
+ console.error("[fluxkit] snapshot failed", e);
4558
+ }
4559
+ }
4560
+ async toggleRecording() {
4561
+ try {
4562
+ if (this.player.isRecording) {
4563
+ let e = await this.player.stopRecording();
4564
+ if (e) {
4565
+ let t = e.type.includes("mp4") ? "mp4" : "webm";
4566
+ hn(e, `${this.options.downloadName}-${gn()}.${t}`);
4567
+ }
4568
+ this.updateRecordButton();
4569
+ return;
4570
+ }
4571
+ this.player.startRecording(), this.recordStartedAt = Date.now(), this.updateRecordButton();
4572
+ } catch (e) {
4573
+ console.error("[fluxkit] recording failed", e);
4574
+ }
4575
+ }
4576
+ updateRecordButton() {
4577
+ let e = this.player.isRecording;
4578
+ this.root.classList.toggle("fk-recording", e), this.recordButton && (this.recordButton.innerHTML = e ? Q.recordStop : Q.record, this.recordButton.setAttribute("aria-label", e ? "停止录制" : "录制")), this.updateRecordTimer();
4579
+ }
4580
+ updateRecordTimer() {
4581
+ if (!this.player.isRecording) {
4582
+ this.recTime.textContent = "";
4583
+ return;
4584
+ }
4585
+ let e = Math.floor((Date.now() - this.recordStartedAt) / 1e3);
4586
+ this.recTime.textContent = `REC ${$(e * 1e3)}`;
4587
+ }
4588
+ updateRateVisibility() {
4589
+ if (!this.rateSelect) return;
4590
+ let e = this.player.decoderMode !== "none";
4591
+ this.rateSelect.style.display = e ? "" : "none", this.pipButton && (this.pipButton.style.display = e ? "" : "none"), this.rateSelect.value = String(this.player.playbackRate);
4592
+ }
4593
+ updatePipButton() {
4594
+ if (!this.pipButton) return;
4595
+ let e = !!document.pictureInPictureElement;
4596
+ this.pipButton.innerHTML = Q.pip, this.pipButton.setAttribute("aria-label", e ? "退出画中画" : "画中画"), this.pipButton.style.opacity = e ? "0.65" : "";
4597
+ }
4598
+ showToast(e) {
4599
+ this.toast.textContent = e, this.toast.dataset.show = "true", this.toastTimer && window.clearTimeout(this.toastTimer), this.toastTimer = window.setTimeout(() => {
4600
+ this.toast.dataset.show = "false";
4601
+ }, 5e3);
4602
+ }
4603
+ updateFullscreenButton() {
4604
+ if (!this.fullscreenButton) return;
4605
+ let e = document.fullscreenElement === this.container;
4606
+ this.fullscreenButton.innerHTML = e ? Q.exitFullscreen : Q.fullscreen, this.fullscreenButton.setAttribute("aria-label", e ? "退出全屏" : "全屏");
4607
+ }
4608
+ show(e) {
4609
+ this.root.dataset.visible = "true", this.hideTimer && window.clearTimeout(this.hideTimer), this.hideTimer = 0, e && this.scheduleHide();
4610
+ }
4611
+ scheduleHide() {
4612
+ this.hideTimer && window.clearTimeout(this.hideTimer), this.player.paused || (this.hideTimer = window.setTimeout(() => {
4613
+ this.dragging || this.player.paused || (this.root.dataset.visible = "false");
4614
+ }, this.options.autoHide));
4615
+ }
4616
+ destroy() {
4617
+ this.destroyed = !0, this.timer && window.clearInterval(this.timer), this.hideTimer && window.clearTimeout(this.hideTimer);
4618
+ for (let e of this.cleanups) e();
4619
+ this.cleanups.length = 0, this.spinner.remove(), this.toast.remove(), this.root.remove();
4620
+ }
4621
+ };
4622
+ // src/render/subtitles.ts
4623
+ function vn(e) {
4624
+ let t = e.trim().replace(",", ".").split(":"), n = 0;
4625
+ for (let e of t) n = n * 60 + Number(e);
4626
+ return Math.round((Number.isFinite(n) ? n : 0) * 1e3);
4627
+ }
4628
+ function yn(e) {
4629
+ return e.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, "\"").replace(/&#39;/gi, "'");
4630
+ }
4631
+ function bn(e) {
4632
+ return yn(e.join("\n").replace(/<[^>]*>/g, "")).trim();
4633
+ }
4634
+ function xn(e, t = 0) {
4635
+ let n = e.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").split("\n"), r = t, i = n.findIndex((e) => e.trim() === "");
4636
+ i < 0 && (i = n.length);
4637
+ for (let e = 0; e < i; e++) {
4638
+ let t = /X-TIMESTAMP-MAP\s*=\s*LOCAL:([^,]+),\s*MPEGTS:(\d+)/i.exec(n[e]);
4639
+ if (t) {
4640
+ r = Number(t[2]) / 9e4 * 1e3 - vn(t[1]);
4641
+ break;
4642
+ }
4643
+ }
4644
+ let a = [], o = [], s = () => {
4645
+ if (o.length === 0) return;
4646
+ let e = o[0].trim().toUpperCase();
4647
+ if (e.startsWith("NOTE") || e.startsWith("STYLE") || e.startsWith("REGION")) {
4648
+ o = [];
4649
+ return;
4650
+ }
4651
+ let t = o.findIndex((e) => e.includes("-->"));
4652
+ if (t < 0) {
4653
+ o = [];
4654
+ return;
4655
+ }
4656
+ let [n, i] = o[t].split("-->"), s = i.trim().split(/\s+/)[0], c = vn(n) + r, l = vn(s) + r, u = bn(o.slice(t + 1));
4657
+ u && Number.isFinite(c) && Number.isFinite(l) && l > c && a.push({
4658
+ startMs: c,
4659
+ endMs: l,
4660
+ text: u
4661
+ }), o = [];
4662
+ };
4663
+ for (let e = i + 1; e < n.length; e++) {
4664
+ let t = n[e];
4665
+ t.trim() === "" ? s() : o.push(t);
4666
+ }
4667
+ return s(), a;
4668
+ }
4669
+ var Sn = class {
4670
+ constructor(e, t) {
4671
+ r(this, "options", void 0), r(this, "host", void 0), r(this, "label", void 0), r(this, "cues", []), r(this, "seen", /* @__PURE__ */ new Set()), r(this, "timer", 0), r(this, "generation", 0), r(this, "destroyed", !1), r(this, "current", ""), r(this, "lastPrune", 0), r(this, "tick", () => {
4672
+ if (this.destroyed) return;
4673
+ let e = this.options.getTime();
4674
+ this.options.live && e - this.lastPrune > 5e3 && (this.lastPrune = e, this.cues = this.cues.filter((t) => t.endMs >= e - 6e4));
4675
+ let t = this.cues.filter((t) => e >= t.startMs && e < t.endMs).map((e) => e.text).join("\n");
4676
+ t !== this.current && (this.current = t, this.label.textContent = t, this.host.style.display = t ? "flex" : "none");
4677
+ }), this.options = t, this.host = document.createElement("div"), this.host.className = "fk-subtitles", this.host.style.cssText = "position:absolute;left:0;right:0;bottom:9%;display:none;justify-content:center;pointer-events:none;z-index:4;padding:0 6%;", this.label = document.createElement("span"), this.label.style.cssText = "max-width:90%;padding:4px 10px;border-radius:4px;background:rgba(0,0,0,.72);color:#fff;font:500 clamp(14px,2.2vw,22px)/1.35 system-ui,-apple-system,Segoe UI,sans-serif;text-align:center;white-space:pre-line;text-shadow:0 1px 2px rgba(0,0,0,.9);", this.host.appendChild(this.label), e.appendChild(this.host), this.timer = window.setInterval(this.tick, 100);
4678
+ }
4679
+ get activeText() {
4680
+ return this.current;
4681
+ }
4682
+ async load(e, t) {
4683
+ let n = ++this.generation;
4684
+ this.cues = [], this.seen.clear(), this.current = "", this.label.textContent = "", this.host.style.display = "none", this.lastPrune = 0;
4685
+ let r = !1, i = 500;
4686
+ for (;;) try {
4687
+ if (this.destroyed || n !== this.generation) return;
4688
+ let r = B(await this.fetchWithRetry(e, t), e);
4689
+ if (await this.loadSegments(r, n, t), this.cues.sort((e, t) => e.startMs - t.startMs || e.endMs - t.endMs), r.endList) return;
4690
+ i = 500, await f(Math.max(500, r.targetDuration * 500));
4691
+ } catch (e) {
4692
+ if (this.destroyed || n !== this.generation || (r || (r = !0, this.options.onError?.(e instanceof Error ? e : Error(String(e)))), !this.options.live)) return;
4693
+ await f(i), i = Math.min(i * 2, 5e3);
4694
+ }
4695
+ }
4696
+ async fetchWithRetry(e, t) {
4697
+ let n = null;
4698
+ for (let r = 0; r < 3; r++) try {
4699
+ return await I(e, {
4700
+ headers: t,
4701
+ timeout: this.options.timeout
4702
+ });
4703
+ } catch (e) {
4704
+ n = e, r < 2 && await f(300 * (r + 1));
4705
+ }
4706
+ throw n instanceof Error ? n : Error(String(n));
4707
+ }
4708
+ async loadSegments(e, t, n) {
4709
+ for (let r of e.segments) {
4710
+ if (this.destroyed || t !== this.generation) return;
4711
+ if (this.seen.has(r.sequence)) continue;
4712
+ let e = { ...n };
4713
+ if (r.byterange) {
4714
+ let { offset: t, length: n } = r.byterange;
4715
+ e.Range = `bytes=${t}-${t + n - 1}`;
4716
+ }
4717
+ let i = await this.fetchWithRetry(r.uri, e);
4718
+ if (this.destroyed || t !== this.generation) return;
4719
+ this.seen.add(r.sequence), this.cues.push(...xn(i));
4720
+ }
4721
+ }
4722
+ destroy() {
4723
+ this.destroyed = !0, this.generation++, this.timer && window.clearInterval(this.timer), this.timer = 0, this.host.remove();
4724
+ }
4725
+ }, Cn = "0.1.0";
4726
+ function wn(e, t) {
4727
+ if (e === t) return !0;
4728
+ if (!e || !t || e.byteLength !== t.byteLength) return !1;
4729
+ for (let n = 0; n < e.length; n++) if (e[n] !== t[n]) return !1;
4730
+ return !0;
4731
+ }
4732
+ function Tn(e, t) {
4733
+ return e.kind !== t.kind || e.codec !== t.codec || e.timescale !== t.timescale || !wn(e.codecPrivate, t.codecPrivate) ? !1 : e.kind === "video" && t.kind === "video" ? e.width === t.width && e.height === t.height : e.kind === "audio" && t.kind === "audio" && e.sampleRate === t.sampleRate && e.channels === t.channels;
4734
+ }
4735
+ var En = {
3484
4736
  bytesReceived: 0,
3485
4737
  kbps: 0,
3486
4738
  protocol: "flv",
@@ -3490,12 +4742,18 @@ var Pt = "\nattribute vec2 aPos;\nuniform vec4 uTexRange;\nvarying vec2 vTex;\nv
3490
4742
  decodedVideoFrames: 0,
3491
4743
  droppedVideoFrames: 0,
3492
4744
  decodedAudioFrames: 0,
4745
+ audioPeak: 0,
4746
+ audioState: "none",
4747
+ audioVolume: 1,
4748
+ audioPath: "none",
4749
+ decodeWorker: !1,
3493
4750
  bufferAhead: 0,
3494
4751
  latency: 0,
4752
+ variantBandwidth: 0,
3495
4753
  live: !1,
3496
4754
  droppedAudioFrames: 0
3497
4755
  };
3498
- function Rt(e) {
4756
+ function Dn(e) {
3499
4757
  let t = typeof e == "string" ? document.querySelector(e) : e;
3500
4758
  if (!t) throw new i("ELEMENT_NOT_FOUND", `element not found: ${String(e)}`);
3501
4759
  let n = t instanceof HTMLVideoElement ? t : null, r = t instanceof HTMLCanvasElement ? t : null, a = n || r ? t.parentElement ?? t : t, o = [];
@@ -3510,23 +4768,23 @@ function Rt(e) {
3510
4768
  created: o
3511
4769
  };
3512
4770
  }
3513
- function zt(e, t, n = .25) {
4771
+ function On(e, t, n = .25) {
3514
4772
  for (let r = 0; r < e.length; r++) if (t >= e.start(r) - n && t <= e.end(r) + n) return !0;
3515
4773
  return !1;
3516
4774
  }
3517
- var Bt = class {
4775
+ var kn = class {
3518
4776
  static isSupported() {
3519
- return typeof window > "u" ? !1 : typeof MediaSource < "u" || Et();
4777
+ return typeof window > "u" ? !1 : typeof MediaSource < "u" || Ut();
3520
4778
  }
3521
4779
  constructor(e, t = {}) {
3522
- r(this, "options", void 0), r(this, "logger", void 0), r(this, "emitter", new c()), r(this, "stage", void 0), r(this, "video", void 0), r(this, "canvas", void 0), r(this, "tracks", /* @__PURE__ */ new Map()), r(this, "timeline", void 0), r(this, "segmenter", void 0), r(this, "source", null), r(this, "renderer", null), r(this, "rendererPromise", null), r(this, "lastRendererError", null), r(this, "url", ""), r(this, "protocol", "flv"), r(this, "live", !1), r(this, "startMs", 0), r(this, "nativeMode", !1), r(this, "loadId", 0), r(this, "destroyed", !1), r(this, "preBuffer", []), r(this, "readyDeferred", null), r(this, "switchAttempts", /* @__PURE__ */ new Set()), r(this, "pendingSeek", null), r(this, "statsTimer", 0), r(this, "lastStats", Lt), r(this, "bytes", 0), r(this, "lastBytes", 0), r(this, "lastStatsAt", 0), r(this, "lastFrames", 0), r(this, "lastFpsAt", 0), r(this, "lastWidth", 0), r(this, "lastHeight", 0), r(this, "audioOnlyTimer", 0), r(this, "wcPaused", !1), r(this, "sourcePaused", !1), this.options = o(t), this.logger = new u(this.options.logLevel, this.options.logger, (e, t) => this.emitter.emit("log", {
4780
+ r(this, "options", void 0), r(this, "logger", void 0), r(this, "emitter", new c()), r(this, "stage", void 0), r(this, "video", void 0), r(this, "canvas", void 0), r(this, "tracks", /* @__PURE__ */ new Map()), r(this, "timeline", void 0), r(this, "segmenter", void 0), r(this, "source", null), r(this, "renderer", null), r(this, "rendererPromise", null), r(this, "lastRendererError", null), r(this, "url", ""), r(this, "protocol", "flv"), r(this, "live", !1), r(this, "startMs", 0), r(this, "nativeMode", !1), r(this, "loadId", 0), r(this, "destroyed", !1), r(this, "preBuffer", []), r(this, "readyDeferred", null), r(this, "switchAttempts", /* @__PURE__ */ new Set()), r(this, "pendingSeek", null), r(this, "statsTimer", 0), r(this, "lastStats", En), r(this, "bytes", 0), r(this, "lastBytes", 0), r(this, "lastStatsAt", 0), r(this, "lastFrames", 0), r(this, "lastFpsAt", 0), r(this, "lastWidth", 0), r(this, "lastHeight", 0), r(this, "audioOnlyTimer", 0), r(this, "wcPaused", !1), r(this, "sourcePaused", !1), r(this, "controlsUI", null), r(this, "stopped", !1), r(this, "lastUrl", ""), r(this, "lastDuration", 0), r(this, "loading", !1), r(this, "playbackRateValue", 1), r(this, "hasStarted", !1), r(this, "preferredAudioId", void 0), r(this, "preferredBandwidth", null), r(this, "activeSubtitleId", null), r(this, "subtitleRenderer", null), r(this, "pipVideo", null), r(this, "pipStream", null), r(this, "reconnectAttempts", 0), r(this, "reconnectTimer", 0), r(this, "reconnectResetTimer", 0), r(this, "recorder", null), r(this, "recordedChunks", []), r(this, "recordingDone", null), this.options = o(t), this.logger = new u(this.options.logLevel, this.options.logger, (e, t) => this.emitter.emit("log", {
3523
4781
  level: e,
3524
4782
  message: t
3525
- })), this.stage = Rt(e), this.video = this.stage.video, this.canvas = this.stage.canvas, this.video.muted = this.options.muted, this.video.loop = this.options.loop, this.video.volume = this.options.volume, this.video.playsInline = !0, this.timeline = new m(this.tracks), this.segmenter = new h({
4783
+ })), this.stage = Dn(e), this.video = this.stage.video, this.canvas = this.stage.canvas, this.video.muted = this.options.muted, this.video.loop = this.options.loop, this.video.volume = this.options.volume, this.video.playsInline = !0, this.timeline = new m(this.tracks), this.segmenter = new h({
3526
4784
  durationMs: this.options.segmentDuration,
3527
4785
  onSegment: (e, t) => this.renderer?.write(e, t),
3528
4786
  getTrack: (e) => this.tracks.get(e)
3529
- }), this.bindVideoEvents();
4787
+ }), this.bindVideoEvents(), this.options.controls.enabled && (this.video.controls = !1, this.controlsUI = new _n(this, this.stage.container, this.options.controls));
3530
4788
  }
3531
4789
  on(e, t) {
3532
4790
  return this.emitter.on(e, t);
@@ -3559,9 +4817,11 @@ var Bt = class {
3559
4817
  return this.lastStats;
3560
4818
  }
3561
4819
  get currentTime() {
3562
- return this.nativeMode || this.renderer?.mode === "mse" ? (Number.isFinite(this.video.currentTime) ? this.video.currentTime : 0) * 1e3 : this.renderer instanceof Q || this.renderer instanceof $ ? this.renderer.currentTime * 1e3 : 0;
4820
+ return this.nativeMode || this.renderer?.mode === "mse" ? (Number.isFinite(this.video.currentTime) ? this.video.currentTime : 0) * 1e3 : this.renderer instanceof X || this.renderer instanceof Z ? this.renderer.currentTime * 1e3 : 0;
3563
4821
  }
3564
4822
  get duration() {
4823
+ if (this.stopped) return this.lastDuration;
4824
+ if (this.live) return Infinity;
3565
4825
  if (this.nativeMode || this.renderer?.mode === "mse") {
3566
4826
  let e = this.video.duration;
3567
4827
  if (Number.isFinite(e)) return e * 1e3;
@@ -3569,11 +4829,26 @@ var Bt = class {
3569
4829
  return !this.live && this.source && typeof this.source.duration == "number" ? this.source.duration * 1e3 : Infinity;
3570
4830
  }
3571
4831
  get paused() {
3572
- return this.nativeMode || this.renderer?.mode === "mse" ? this.video.paused : this.renderer?.mode === "webcodecs" || this.renderer?.mode === "software" ? this.wcPaused : !0;
4832
+ return this.stopped ? !0 : this.nativeMode || this.renderer?.mode === "mse" ? this.video.paused : this.renderer?.mode === "webcodecs" || this.renderer?.mode === "software" ? this.wcPaused : !0;
3573
4833
  }
3574
4834
  get volume() {
3575
4835
  return this.video.volume;
3576
4836
  }
4837
+ get muted() {
4838
+ return this.video.muted;
4839
+ }
4840
+ get isRecording() {
4841
+ return this.recorder !== null;
4842
+ }
4843
+ get isStopped() {
4844
+ return this.stopped;
4845
+ }
4846
+ get isLoading() {
4847
+ return this.loading;
4848
+ }
4849
+ get playbackRate() {
4850
+ return this.playbackRateValue;
4851
+ }
3577
4852
  setVolume(e) {
3578
4853
  let t = Math.min(1, Math.max(0, e));
3579
4854
  this.video.volume = t, this.renderer?.setVolume?.(this.video.muted ? 0 : t);
@@ -3592,13 +4867,19 @@ var Bt = class {
3592
4867
  }
3593
4868
  async load(e, t = {}) {
3594
4869
  if (this.destroyed) throw new i("DESTROYED", "this player has been destroyed");
4870
+ this.cleanupPip();
3595
4871
  let n = ++this.loadId;
3596
- if (this.stopInternal(), this.url = e, this.startMs = t.startTime ?? 0, this.live = !1, this.nativeMode = !1, this.wcPaused = !1, this.sourcePaused = !1, this.pendingSeek = this.startMs > 0 ? this.startMs : null, this.switchAttempts.clear(), this.tracks.clear(), this.preBuffer = [], this.timeline.setStart(this.startMs), this.readyDeferred = d(), this.lastStats = {
3597
- ...Lt,
4872
+ if (e === this.url ? this.clearReconnectTimer() : (this.cancelReconnect(), this.reconnectAttempts = 0, this.hasStarted = !1, this.preferredAudioId = void 0, this.preferredBandwidth = null, this.activeSubtitleId = null, this.subtitleRenderer?.destroy(), this.subtitleRenderer = null), this.stopInternal(), this.stopped = !1, this.lastUrl = e, this.video.playbackRate = this.playbackRateValue, this.setLoading(!0, e), this.url = e, this.startMs = t.startTime ?? 0, this.live = !1, this.nativeMode = !1, this.wcPaused = !1, this.sourcePaused = !1, this.pendingSeek = this.startMs > 0 ? this.startMs : null, this.switchAttempts.clear(), this.tracks.clear(), this.preBuffer = [], this.timeline.setStart(this.startMs), this.readyDeferred = d(), this.lastStats = {
4873
+ ...En,
3598
4874
  protocol: this.protocol
3599
- }, this.bytes = 0, this.lastBytes = 0, this.protocol = this.options.protocol === "auto" ? s(e) : this.options.protocol, this.logger.info(`loading ${this.protocol} ${e}`), this.shouldUseNative()) await this.startNative(n);
4875
+ }, this.bytes = 0, this.lastBytes = 0, this.protocol = this.options.protocol === "auto" ? s(e) : this.options.protocol, this.logger.info(`loading ${this.protocol} ${e}`), this.shouldUseNative()) try {
4876
+ await this.startNative(n);
4877
+ } catch (e) {
4878
+ let t = e instanceof Error ? e : Error(String(e));
4879
+ throw this.setLoading(!1), this.emitter.emit("error", t), this.readyDeferred?.reject(t), t;
4880
+ }
3600
4881
  else {
3601
- this.source = this.createSource(this.protocol, this.startMs), this.live = this.source.live, this.lastStats.live = this.live;
4882
+ this.source = this.createSource(this.protocol, this.startMs, n), this.live = this.source.live, this.lastStats.live = this.live;
3602
4883
  try {
3603
4884
  await this.source.start();
3604
4885
  } catch (e) {
@@ -3614,7 +4895,8 @@ var Bt = class {
3614
4895
  }
3615
4896
  async play() {
3616
4897
  if (!this.destroyed) {
3617
- if (this.nativeMode || this.renderer?.mode === "mse") {
4898
+ if (this.stopped) this.lastUrl && await this.load(this.lastUrl);
4899
+ else if (this.nativeMode || this.renderer?.mode === "mse") {
3618
4900
  this.renderer?.setPaused?.(!1), this.renderer?.resumeAudio?.();
3619
4901
  try {
3620
4902
  await this.video.play();
@@ -3625,7 +4907,186 @@ var Bt = class {
3625
4907
  }
3626
4908
  }
3627
4909
  pause() {
3628
- this.nativeMode || this.renderer?.mode === "mse" ? (this.video.pause(), this.renderer?.setPaused?.(!0)) : (this.renderer?.mode === "webcodecs" || this.renderer?.mode === "software") && (this.wcPaused = !0, this.renderer.setPaused?.(!0), this.emitter.emit("pause", void 0));
4910
+ this.stopped || (this.nativeMode || this.renderer?.mode === "mse" ? (this.video.pause(), this.renderer?.setPaused?.(!0)) : (this.renderer?.mode === "webcodecs" || this.renderer?.mode === "software") && (this.wcPaused = !0, this.renderer.setPaused?.(!0), this.emitter.emit("pause", void 0)));
4911
+ }
4912
+ async snapshot(e = "image/png", t = .95) {
4913
+ let n = this.renderer;
4914
+ if (n && (n.mode === "webcodecs" || n.mode === "software")) {
4915
+ if (this.canvas.width < 2 || this.canvas.height < 2) throw new i("SNAPSHOT_NOT_READY", "no frame has been rendered yet");
4916
+ return An(this.canvas, e, t);
4917
+ }
4918
+ let r = this.video;
4919
+ if (!r.videoWidth || !r.videoHeight) throw new i("SNAPSHOT_NOT_READY", "no frame has been rendered yet");
4920
+ let a = document.createElement("canvas");
4921
+ a.width = r.videoWidth, a.height = r.videoHeight;
4922
+ let o = a.getContext("2d");
4923
+ if (!o) throw new i("SNAPSHOT_FAILED", "2d canvas is not available");
4924
+ try {
4925
+ o.drawImage(r, 0, 0, a.width, a.height);
4926
+ } catch (e) {
4927
+ throw new i("SNAPSHOT_BLOCKED", "the video is tainted by a cross-origin source", e);
4928
+ }
4929
+ return An(a, e, t);
4930
+ }
4931
+ startRecording(e = {}) {
4932
+ if (this.recorder) return;
4933
+ if (typeof MediaRecorder > "u") throw new i("RECORD_UNSUPPORTED", "MediaRecorder is not available");
4934
+ let t = this.buildRecordingStream();
4935
+ if (!t) throw new i("RECORD_UNSUPPORTED", "no capturable video/audio stream");
4936
+ let n = e.mimeType ?? jn(), r;
4937
+ try {
4938
+ r = new MediaRecorder(t, {
4939
+ ...n ? { mimeType: n } : {},
4940
+ ...e.videoBitsPerSecond ? { videoBitsPerSecond: e.videoBitsPerSecond } : {}
4941
+ });
4942
+ } catch (e) {
4943
+ throw new i("RECORD_UNSUPPORTED", "MediaRecorder rejected the stream", e);
4944
+ }
4945
+ this.recordedChunks = [];
4946
+ let a = d();
4947
+ this.recordingDone = a, r.ondataavailable = (e) => {
4948
+ e.data && e.data.size > 0 && this.recordedChunks.push(e.data);
4949
+ }, r.onstop = () => {
4950
+ let e = new Blob(this.recordedChunks, { type: r.mimeType || n || "video/webm" });
4951
+ this.recordedChunks = [], this.recorder = null, a.resolve(e);
4952
+ }, r.onerror = () => {
4953
+ this.recorder = null, a.resolve(null);
4954
+ }, r.start(1e3), this.recorder = r;
4955
+ }
4956
+ async stopRecording() {
4957
+ let e = this.recorder;
4958
+ if (!e) return null;
4959
+ if (e.state === "inactive") return this.recorder = null, null;
4960
+ let t = this.recordingDone;
4961
+ try {
4962
+ e.stop();
4963
+ } catch {
4964
+ return this.recorder = null, null;
4965
+ }
4966
+ return t ? t.promise : null;
4967
+ }
4968
+ buildRecordingStream() {
4969
+ let e = this.renderer, t = [], n = e?.captureStream?.();
4970
+ if (n) t.push(n);
4971
+ else if (this.nativeMode) {
4972
+ let e = this.video, n = e.captureStream?.() ?? e.mozCaptureStream?.();
4973
+ n && t.push(n);
4974
+ }
4975
+ let r = e?.captureAudioStream?.();
4976
+ r && t.push(r);
4977
+ let i = [], a = !1;
4978
+ for (let e of t) for (let t of e.getTracks()) {
4979
+ if (t.kind === "audio") {
4980
+ if (a) continue;
4981
+ a = !0;
4982
+ }
4983
+ i.push(t);
4984
+ }
4985
+ return i.length > 0 ? new MediaStream(i) : null;
4986
+ }
4987
+ async seekToLive() {
4988
+ if (this.live) {
4989
+ if (this.nativeMode || this.renderer?.mode === "mse") {
4990
+ let e = this.video.buffered;
4991
+ if (e.length > 0) {
4992
+ let t = Math.max(0, e.end(e.length - 1) - .1);
4993
+ this.video.currentTime = t, this.emitter.emit("seeked", { time: t * 1e3 });
4994
+ return;
4995
+ }
4996
+ }
4997
+ await this.load(this.lastUrl || this.url, { autoplay: !0 });
4998
+ }
4999
+ }
5000
+ setPlaybackRate(e) {
5001
+ let t = Math.min(4, Math.max(.25, Number.isFinite(e) ? e : 1));
5002
+ this.playbackRateValue = t, (this.nativeMode || this.renderer?.mode === "mse") && (this.video.playbackRate = t), this.renderer?.setPlaybackRate?.(t);
5003
+ }
5004
+ get audioTracks() {
5005
+ return this.source instanceof W ? this.source.audioTracks : [];
5006
+ }
5007
+ get subtitleTracks() {
5008
+ return (this.source instanceof W ? this.source.subtitleTracks : []).map((e) => ({
5009
+ ...e,
5010
+ active: e.id === this.activeSubtitleId
5011
+ }));
5012
+ }
5013
+ async selectAudioTrack(e) {
5014
+ if (!(this.source instanceof W)) throw new i("AUDIO_TRACKS_UNSUPPORTED", "audio track selection is only available for HLS");
5015
+ let t = this.source.audioTracks.find((t) => t.id === e);
5016
+ if (!t || t.active) return;
5017
+ this.preferredAudioId = e, await this.restartAt(this.live ? 0 : this.currentTime, !this.live);
5018
+ let n = this.audioTracks.find((e) => e.active)?.id ?? null;
5019
+ this.logger.info(`audio track: ${n ?? "none"}`), this.emitter.emit("audiochange", { id: n });
5020
+ }
5021
+ selectSubtitleTrack(e) {
5022
+ if (!(this.source instanceof W)) throw new i("SUBTITLES_UNSUPPORTED", "subtitle selection is only available for HLS");
5023
+ let t = e ? this.source.subtitleTracks.find((t) => t.id === e) : null;
5024
+ if (!e || t) {
5025
+ if (this.activeSubtitleId = t?.id ?? null, this.subtitleRenderer?.destroy(), this.subtitleRenderer = null, t?.uri) {
5026
+ let e = new Sn(this.stage.container, {
5027
+ getTime: () => this.currentTime,
5028
+ live: this.live,
5029
+ timeout: this.options.timeout,
5030
+ onError: (e) => this.emitter.emit("error", new i("SUBTITLES_FAILED", "subtitle playlist failed", e))
5031
+ });
5032
+ this.subtitleRenderer = e, e.load(t.uri, this.options.headers);
5033
+ }
5034
+ this.logger.info(`subtitles: ${t?.label ?? "off"}`), this.emitter.emit("subtitlechange", { id: this.activeSubtitleId });
5035
+ }
5036
+ }
5037
+ setQuality(e) {
5038
+ this.preferredBandwidth = e === "auto" ? null : e, this.source?.setQuality ? this.source.setQuality(e) : this.emitter.emit("error", new i("QUALITY_UNSUPPORTED", "quality selection is only available for HLS"));
5039
+ }
5040
+ async togglePictureInPicture() {
5041
+ let e = this.video;
5042
+ try {
5043
+ if (document.pictureInPictureElement) {
5044
+ await document.exitPictureInPicture(), this.cleanupPip();
5045
+ return;
5046
+ }
5047
+ if (this.renderer?.mode === "webcodecs" || this.renderer?.mode === "software") {
5048
+ let e = this.buildRecordingStream();
5049
+ if (!e) throw new i("PIP_UNSUPPORTED", "canvas capture is not available");
5050
+ let t = document.createElement("video");
5051
+ t.muted = !0, t.playsInline = !0, t.srcObject = e, t.style.cssText = "position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none;", document.body.appendChild(t), this.pipVideo = t, this.pipStream = e, t.addEventListener("leavepictureinpicture", () => this.cleanupPip(), { once: !0 }), await new Promise((e, n) => {
5052
+ if (t.readyState >= 1) return e();
5053
+ let r = window.setTimeout(() => n(/* @__PURE__ */ Error("PiP video metadata timeout")), 5e3);
5054
+ t.addEventListener("loadedmetadata", () => {
5055
+ window.clearTimeout(r), e();
5056
+ }, { once: !0 });
5057
+ }), await t.play();
5058
+ let n = t.requestPictureInPicture;
5059
+ if (!n) throw new i("PIP_UNSUPPORTED", "Picture-in-Picture is not available");
5060
+ await n.call(t);
5061
+ } else if (e.requestPictureInPicture) await e.requestPictureInPicture();
5062
+ else throw new i("PIP_UNSUPPORTED", "Picture-in-Picture is not available");
5063
+ } catch (e) {
5064
+ this.cleanupPip(), this.emitter.emit("error", new i("PIP_FAILED", "Picture-in-Picture failed", e));
5065
+ }
5066
+ }
5067
+ cleanupPip() {
5068
+ let e = this.pipVideo, t = this.pipStream;
5069
+ if (this.pipVideo = null, this.pipStream = null, e) {
5070
+ try {
5071
+ e.pause();
5072
+ } catch {}
5073
+ e.srcObject = null, e.remove();
5074
+ }
5075
+ if (t) for (let e of t.getTracks()) e.stop();
5076
+ }
5077
+ setLoading(e, t) {
5078
+ this.loading !== e && (this.loading = e, this.emitter.emit("loading", {
5079
+ loading: e,
5080
+ url: t
5081
+ }));
5082
+ }
5083
+ async toggleFullscreen() {
5084
+ let e = this.stage.container;
5085
+ try {
5086
+ document.fullscreenElement ? await document.exitFullscreen() : await e.requestFullscreen?.();
5087
+ } catch (e) {
5088
+ this.emitter.emit("error", new i("FULLSCREEN_FAILED", "fullscreen request failed", e));
5089
+ }
3629
5090
  }
3630
5091
  async seek(e) {
3631
5092
  if (!(!Number.isFinite(e) || e < 0)) {
@@ -3633,7 +5094,7 @@ var Bt = class {
3633
5094
  else {
3634
5095
  if (this.renderer?.mode === "mse") {
3635
5096
  let t = e / 1e3;
3636
- if (zt(this.video.buffered, t)) {
5097
+ if (On(this.video.buffered, t)) {
3637
5098
  this.video.currentTime = t, this.emitter.emit("seeked", { time: e });
3638
5099
  return;
3639
5100
  }
@@ -3641,35 +5102,40 @@ var Bt = class {
3641
5102
  this.pendingSeek = e, await this.restartAt(e);
3642
5103
  return;
3643
5104
  }
5105
+ } else if (!this.live && this.protocol === "hls") {
5106
+ this.pendingSeek = e, await this.restartAt(e), this.emitter.emit("seeked", { time: e });
5107
+ return;
3644
5108
  }
3645
5109
  this.emitter.emit("error", new i("SEEK_UNSUPPORTED", "this stream cannot be seeked outside the buffered range"));
3646
5110
  }
3647
5111
  }
3648
5112
  }
3649
5113
  stop() {
3650
- this.loadId++, this.stopInternal(), this.readyDeferred?.reject(new i("STOPPED", "playback stopped")), this.readyDeferred = null;
5114
+ this.cancelReconnect(), this.cleanupPip(), this.subtitleRenderer?.destroy(), this.subtitleRenderer = null, this.activeSubtitleId = null;
5115
+ let e = this.duration;
5116
+ this.lastDuration = Number.isFinite(e) ? e : 0, this.stopped = !0, this.setLoading(!1), this.loadId++, this.stopInternal(), this.readyDeferred?.reject(new i("STOPPED", "playback stopped")), this.readyDeferred = null;
3651
5117
  }
3652
5118
  destroy() {
3653
5119
  if (!this.destroyed) {
3654
- this.destroyed = !0, this.stopInternal(), this.emitter.removeAll();
5120
+ this.destroyed = !0, this.cancelReconnect(), this.cleanupPip(), this.subtitleRenderer?.destroy(), this.subtitleRenderer = null, this.stopInternal(), this.readyDeferred?.reject(new i("DESTROYED", "this player has been destroyed")), this.readyDeferred = null, this.controlsUI?.destroy(), this.controlsUI = null, this.emitter.removeAll();
3655
5121
  for (let e of this.stage.created) e.remove();
3656
5122
  }
3657
5123
  }
3658
5124
  shouldUseNative() {
3659
5125
  return this.options.decoder === "native" || this.protocol === "hls" && this.options.hls.mode === "native";
3660
5126
  }
3661
- createSource(e, t) {
3662
- let n = this.buildSourceContext();
5127
+ createSource(e, t, n = this.loadId) {
5128
+ let r = this.buildSourceContext(n);
3663
5129
  switch (e) {
3664
- case "hls": return new Ue(this.url, this.options, n, t);
3665
- default: return new Me(e, this.url, this.options, n);
5130
+ case "hls": return new W(this.url, this.options, r, t, this.preferredAudioId, this.preferredBandwidth ?? void 0);
5131
+ default: return new Re(e, this.url, this.options, r, this.options.live);
3666
5132
  }
3667
5133
  }
3668
5134
  onTracks(e) {
3669
5135
  let t = !1;
3670
5136
  for (let n of e) {
3671
5137
  let e = this.tracks.get(n.id);
3672
- e ? e.kind === "video" && n.kind === "video" && (e.width !== n.width || e.height !== n.height || e.codec !== n.codec) && (this.tracks.set(n.id, n), t = !0) : (this.tracks.set(n.id, n), t = !0);
5138
+ e && Tn(e, n) || (this.tracks.set(n.id, n), t = !0);
3673
5139
  }
3674
5140
  if (!t) return;
3675
5141
  let n = [...this.tracks.values()];
@@ -3698,13 +5164,13 @@ var Bt = class {
3698
5164
  if (t.length === 0) return;
3699
5165
  let n = null, r = this.options.decoder, a = (e) => {
3700
5166
  try {
3701
- return MediaSource.isTypeSupported(J(e));
5167
+ return MediaSource.isTypeSupported(K(e));
3702
5168
  } catch {
3703
5169
  return !1;
3704
5170
  }
3705
5171
  }, o = t.find((e) => e.kind === "video");
3706
5172
  if (typeof MediaSource < "u" && r !== "webcodecs" && r !== "software" && r !== "native" && (o ? a(o) : t.some(a))) try {
3707
- let e = new X(this.video, {
5173
+ let e = new J(this.video, {
3708
5174
  live: this.live,
3709
5175
  liveBufferTarget: this.options.liveBufferTarget,
3710
5176
  onError: (e) => this.emitter.emit("error", e)
@@ -3713,8 +5179,8 @@ var Bt = class {
3713
5179
  } catch (e) {
3714
5180
  this.lastRendererError = e instanceof Error ? e : Error(String(e)), this.logger.warn(`MSE unavailable: ${this.lastRendererError.message}`);
3715
5181
  }
3716
- if (!n && (r === "auto" || r === "webcodecs") && Et()) try {
3717
- let e = new Q({
5182
+ if (!n && (r === "auto" || r === "webcodecs") && Ut()) try {
5183
+ let e = new X({
3718
5184
  hardwareAcceleration: this.options.hardwareAcceleration,
3719
5185
  fit: this.options.webcodecs.fit,
3720
5186
  volume: this.options.volume,
@@ -3729,12 +5195,15 @@ var Bt = class {
3729
5195
  this.lastRendererError = e instanceof Error ? e : Error(String(e)), this.logger.warn(`WebCodecs unavailable: ${this.lastRendererError.message}`);
3730
5196
  }
3731
5197
  if (!n && (r === "auto" || r === "software") && this.options.softDecode.enabled && t.some((e) => e.kind === "video")) try {
3732
- let e = new $({
5198
+ let e = new Z({
3733
5199
  fit: this.options.webcodecs.fit,
5200
+ live: this.live,
3734
5201
  volume: this.options.volume,
3735
5202
  maxDecodeAhead: this.options.softDecode.maxDecodeAhead,
3736
5203
  dropLateFrames: this.options.softDecode.dropLateFrames,
3737
5204
  loaders: this.options.softDecode.loaders,
5205
+ worker: this.options.softDecode.worker,
5206
+ modules: this.options.softDecode.modules,
3738
5207
  onError: (e) => this.emitter.emit("error", e),
3739
5208
  onFirstFrame: (e, t) => this.emitter.emit("loaded", {
3740
5209
  width: e,
@@ -3756,9 +5225,9 @@ var Bt = class {
3756
5225
  n.destroy();
3757
5226
  return;
3758
5227
  }
3759
- this.renderer = n, this.showRenderer(n.mode);
5228
+ this.renderer = n, n.mode === "mse" && (this.video.playbackRate = this.playbackRateValue), n.setPlaybackRate?.(this.playbackRateValue), this.showRenderer(n.mode);
3760
5229
  let s = [...this.tracks.values()];
3761
- await n.attach(s), this.emitter.emit("ready", {
5230
+ await n.attach(s), this.setLoading(!1), this.hasStarted = !0, this.onReconnected(), this.emitter.emit("ready", {
3762
5231
  tracks: s,
3763
5232
  protocol: this.protocol,
3764
5233
  decoder: n.mode
@@ -3781,8 +5250,8 @@ var Bt = class {
3781
5250
  }
3782
5251
  onSourceEnd() {
3783
5252
  if (this.segmenter.flush(), this.renderer?.endOfStream?.(), (this.renderer?.mode === "webcodecs" || this.renderer?.mode === "software") && !this.live) {
3784
- let e = window.setInterval(() => {
3785
- (this.renderer instanceof Q || this.renderer instanceof $ ? this.renderer.framesPending : 0) > 0 || (window.clearInterval(e), this.destroyed || this.emitter.emit("ended", void 0));
5253
+ let e = this.loadId, t = this.renderer, n = Date.now(), r = window.setInterval(() => {
5254
+ this.destroyed || this.stopped || this.loadId !== e || this.renderer !== t ? window.clearInterval(r) : (t instanceof X || t instanceof Z ? t.framesPending : 0) > 0 && Date.now() - n < 1e4 || (window.clearInterval(r), this.emitter.emit("ended", void 0));
3786
5255
  }, 200);
3787
5256
  }
3788
5257
  }
@@ -3795,8 +5264,46 @@ var Bt = class {
3795
5264
  return;
3796
5265
  }
3797
5266
  }
3798
- this.tryNativeFallback(e) || (this.logger.error(e.message), this.emitter.emit("error", e), this.readyDeferred?.reject(e));
5267
+ this.tryNativeFallback(e) || (this.shouldReconnect(e) ? (this.logger.warn(`live stream interrupted: ${e.message}`), this.scheduleReconnect()) : (this.setLoading(!1), this.logger.error(e.message), this.emitter.emit("error", e), this.readyDeferred?.reject(e)));
5268
+ }
5269
+ }
5270
+ shouldReconnect(e) {
5271
+ if (!this.options.autoReconnect || !this.live || !this.hasStarted || this.stopped || this.destroyed || this.reconnectAttempts >= this.options.retry.maxRetries) return !1;
5272
+ if (e instanceof i) {
5273
+ if (e.code === "HTTP_STATUS") {
5274
+ let t = e.detail?.status ?? 0;
5275
+ if (t >= 400 && t < 500 && t !== 408 && t !== 429) return !1;
5276
+ }
5277
+ if (e.code.startsWith("MSE_") || e.code.startsWith("WEBCODECS_") || e.code === "NO_DECODER" || e.code === "MP4_MOOV_AT_END" || e.code === "HLS_ENCRYPTED" || e.code === "HLS_KEY_FAILED" || e.code === "HLS_KEY_INVALID" || e.code === "HLS_DECRYPT_FAILED" || e.code === "HLS_DECRYPT_UNSUPPORTED" || e.code === "HLS_AUDIO_FAILED" || e.code === "UNSUPPORTED_AUDIO" || e.code === "SOFT_PROFILE_UNSUPPORTED") return !1;
5278
+ }
5279
+ return !0;
5280
+ }
5281
+ scheduleReconnect() {
5282
+ if (this.reconnectTimer || this.stopped || this.destroyed) return;
5283
+ let e = this.options.retry.maxRetries;
5284
+ if (this.reconnectAttempts >= e) {
5285
+ this.setLoading(!1), this.emitter.emit("error", new i("RECONNECT_FAILED", "live stream lost and reconnect attempts were exhausted"));
5286
+ return;
3799
5287
  }
5288
+ let t = ++this.reconnectAttempts, n = Math.min(this.options.retry.delay * 2 ** (t - 1), this.options.retry.maxDelay);
5289
+ this.emitter.emit("reconnecting", {
5290
+ attempt: t,
5291
+ max: e,
5292
+ delay: n
5293
+ }), this.setLoading(!0, this.url), this.reconnectTimer = window.setTimeout(() => {
5294
+ this.reconnectTimer = 0, this.stopped || this.destroyed || this.load(this.url).catch(() => {});
5295
+ }, n);
5296
+ }
5297
+ onReconnected() {
5298
+ this.reconnectAttempts !== 0 && (this.emitter.emit("reconnected", void 0), window.clearTimeout(this.reconnectResetTimer), this.reconnectResetTimer = window.setTimeout(() => {
5299
+ this.reconnectAttempts = 0;
5300
+ }, 5e3));
5301
+ }
5302
+ clearReconnectTimer() {
5303
+ this.reconnectTimer && (window.clearTimeout(this.reconnectTimer), this.reconnectTimer = 0);
5304
+ }
5305
+ cancelReconnect() {
5306
+ this.clearReconnectTimer(), this.reconnectResetTimer && (window.clearTimeout(this.reconnectResetTimer), this.reconnectResetTimer = 0);
3800
5307
  }
3801
5308
  tryNativeFallback(e) {
3802
5309
  if (!this.options.allowNativeFallback || this.nativeMode || this.protocol !== "mp4" && this.protocol !== "hls") return !1;
@@ -3812,46 +5319,67 @@ var Bt = class {
3812
5319
  "SOFT_PROFILE_UNSUPPORTED",
3813
5320
  "SOFT_DECODE_FAILED",
3814
5321
  "NO_DECODER"
3815
- ].includes(t) ? (this.logger.warn(`decoder failed (${t}); falling back to native playback`), this.startNative(this.loadId), !0) : !1;
5322
+ ].includes(t) ? (this.logger.warn(`decoder failed (${t}); falling back to native playback`), this.startNative(this.loadId).catch((e) => {
5323
+ this.onSourceError(e instanceof Error ? e : Error(String(e)));
5324
+ }), !0) : !1;
3816
5325
  }
3817
5326
  async switchProtocol(e) {
3818
5327
  let t = this.loadId;
3819
- this.stopPipeline(), this.tracks.clear(), this.preBuffer = [], this.timeline.setStart(this.startMs), this.readyDeferred = d(), this.protocol = e, this.source = this.createSource(e, this.startMs), this.live = this.source.live;
5328
+ this.stopPipeline(), this.tracks.clear(), this.preBuffer = [], this.timeline.setStart(this.startMs), this.readyDeferred = d(), this.protocol = e, this.source = this.createSource(e, this.startMs, t), this.live = this.source.live;
3820
5329
  try {
3821
5330
  await this.source.start(), await this.readyDeferred.promise;
3822
5331
  } catch (e) {
3823
5332
  t === this.loadId && this.onSourceError(e instanceof Error ? e : Error(String(e)));
3824
5333
  }
3825
5334
  }
3826
- async restartAt(e) {
3827
- let t = this.loadId;
3828
- this.stopPipeline(), this.tracks.clear(), this.preBuffer = [], this.startMs = e, this.timeline.setStart(e), this.readyDeferred = d(), this.lastWidth = 0, this.lastHeight = 0, this.source = new Ue(this.url, this.options, this.buildSourceContext(), e), this.live = this.source.live;
5335
+ async restartAt(e, t = !0) {
5336
+ let n = this.loadId;
5337
+ this.cleanupPip(), this.stopPipeline(), this.tracks.clear(), this.preBuffer = [], this.startMs = e, this.timeline.setStart(e), this.readyDeferred = d(), this.lastWidth = 0, this.lastHeight = 0, this.source = new W(this.url, this.options, this.buildSourceContext(n), e, this.preferredAudioId, this.preferredBandwidth ?? void 0), this.live = this.source.live;
3829
5338
  try {
3830
- await this.source.start(), await this.readyDeferred.promise, t === this.loadId && (this.pendingSeek = e);
5339
+ await this.source.start(), await this.readyDeferred.promise, t && n === this.loadId && (this.pendingSeek = this.renderer?.mode === "mse" ? e : null);
3831
5340
  } catch (e) {
3832
5341
  this.onSourceError(e instanceof Error ? e : Error(String(e)));
3833
5342
  }
3834
5343
  }
3835
- buildSourceContext() {
5344
+ buildSourceContext(e = this.loadId) {
5345
+ let t = () => e === this.loadId && !this.destroyed;
3836
5346
  return {
3837
- onTracks: (e) => this.onTracks(e),
3838
- onSample: (e) => this.onSample(e),
3839
- onEnd: () => this.onSourceEnd(),
3840
- onError: (e) => this.onSourceError(e),
5347
+ onTracks: (e) => {
5348
+ t() && this.onTracks(e);
5349
+ },
5350
+ onSample: (e) => {
5351
+ t() && this.onSample(e);
5352
+ },
5353
+ onEnd: () => {
5354
+ t() && this.onSourceEnd();
5355
+ },
5356
+ onError: (e) => {
5357
+ t() && this.onSourceError(e);
5358
+ },
5359
+ onDiscontinuity: () => {
5360
+ t() && this.timeline.markDiscontinuity();
5361
+ },
5362
+ getRendererMode: () => this.renderer?.mode ?? "none",
5363
+ onVariantChange: (e) => {
5364
+ t() && (this.logger.info(`HLS variant: ${Math.round(e / 1e3)} kbps`), this.emitter.emit("qualitychange", { bandwidth: e }));
5365
+ },
3841
5366
  getBufferAhead: () => this.bufferAhead,
3842
5367
  getCurrentTime: () => this.currentTime / 1e3,
3843
5368
  onBytes: (e) => {
3844
- this.bytes += e;
5369
+ t() && (this.bytes += e);
5370
+ },
5371
+ onLive: (e) => {
5372
+ t() && (this.live = e, this.lastStats.live = e);
3845
5373
  }
3846
5374
  };
3847
5375
  }
3848
5376
  async startNative(e) {
3849
- this.stopPipeline(), this.nativeMode = !0, this.showRenderer("native"), this.video.src = this.url, this.video.load(), await new Promise((e, t) => {
5377
+ this.stopPipeline(), this.nativeMode = !0, this.showRenderer("native"), this.video.src = this.url, this.video.playbackRate = this.playbackRateValue, this.video.load(), await new Promise((e, t) => {
3850
5378
  let n = window.setTimeout(() => o(new i("NATIVE_TIMEOUT", "native playback did not start")), Math.max(15e3, this.options.timeout)), r = () => o(), a = () => o(new i("NATIVE_FAILED", "native playback failed")), o = (i) => {
3851
5379
  window.clearTimeout(n), this.video.removeEventListener("loadedmetadata", r), this.video.removeEventListener("error", a), i ? t(i) : e();
3852
5380
  };
3853
5381
  this.video.addEventListener("loadedmetadata", r), this.video.addEventListener("error", a);
3854
- }), e === this.loadId && (this.emitter.emit("ready", {
5382
+ }), e === this.loadId && (this.setLoading(!1), this.hasStarted = !0, this.onReconnected(), this.emitter.emit("ready", {
3855
5383
  tracks: [],
3856
5384
  protocol: this.protocol,
3857
5385
  decoder: "native"
@@ -3869,7 +5397,7 @@ var Bt = class {
3869
5397
  }
3870
5398
  startStats() {
3871
5399
  this.statsTimer || (this.lastStatsAt = performance.now(), this.lastFpsAt = performance.now(), this.lastFrames = this.renderer?.stats.decodedVideoFrames ?? 0, this.lastStats = {
3872
- ...Lt,
5400
+ ...En,
3873
5401
  protocol: this.protocol
3874
5402
  }, this.statsTimer = window.setInterval(() => this.updateStats(), 1e3));
3875
5403
  }
@@ -3879,14 +5407,18 @@ var Bt = class {
3879
5407
  for (let t = 0; t < e.length; t++) if (e.start(t) <= this.video.currentTime && e.end(t) >= this.video.currentTime) return e.end(t) - this.video.currentTime;
3880
5408
  return 0;
3881
5409
  }
3882
- return this.renderer instanceof X ? this.renderer.bufferAhead : this.renderer instanceof Q || this.renderer instanceof $ ? this.renderer.backlogSeconds : 0;
5410
+ return this.renderer instanceof J ? this.renderer.bufferAhead : this.renderer instanceof X || this.renderer instanceof Z ? this.renderer.backlogSeconds : 0;
3883
5411
  }
3884
5412
  updateStats() {
3885
5413
  if (this.destroyed) return;
3886
5414
  let e = performance.now(), t = this.renderer?.stats ?? {
3887
5415
  decodedVideoFrames: 0,
3888
5416
  droppedVideoFrames: 0,
3889
- decodedAudioFrames: 0
5417
+ decodedAudioFrames: 0,
5418
+ audioPeak: 0,
5419
+ audioState: "none",
5420
+ audioVolume: 0,
5421
+ audioPath: "none"
3890
5422
  }, n = Math.max(.001, (e - this.lastFpsAt) / 1e3), r = Math.max(0, (t.decodedVideoFrames - this.lastFrames) / n);
3891
5423
  this.lastFrames = t.decodedVideoFrames, this.lastFpsAt = e;
3892
5424
  let i = Math.max(.001, (e - this.lastStatsAt) / 1e3), a = (this.bytes - this.lastBytes) * 8 / 1e3 / i;
@@ -3897,7 +5429,7 @@ var Bt = class {
3897
5429
  kbps: Math.round(a),
3898
5430
  protocol: this.protocol,
3899
5431
  decoder: this.decoderMode,
3900
- hardwareAcceleration: this.renderer instanceof Q ? this.renderer.acceleration : this.renderer?.mode === "software" ? "software" : this.renderer?.mode === "mse" ? "preferred" : "unknown",
5432
+ hardwareAcceleration: this.renderer instanceof X ? this.renderer.acceleration : this.renderer?.mode === "software" ? "software" : this.renderer?.mode === "mse" ? "preferred" : "unknown",
3901
5433
  videoCodec: this.findCodec("video"),
3902
5434
  audioCodec: this.findCodec("audio"),
3903
5435
  width: this.lastWidth || this.video.videoWidth || void 0,
@@ -3906,11 +5438,17 @@ var Bt = class {
3906
5438
  decodedVideoFrames: t.decodedVideoFrames,
3907
5439
  droppedVideoFrames: t.droppedVideoFrames,
3908
5440
  decodedAudioFrames: t.decodedAudioFrames,
5441
+ audioPeak: t.audioPeak,
5442
+ audioState: t.audioState,
5443
+ audioVolume: t.audioVolume,
5444
+ audioPath: t.audioPath,
5445
+ decodeWorker: this.renderer instanceof Z && this.renderer.usingWorker,
3909
5446
  bufferAhead: o,
3910
5447
  latency: this.live ? o : 0,
5448
+ variantBandwidth: this.source?.variantBandwidth ?? 0,
3911
5449
  live: this.live,
3912
5450
  droppedAudioFrames: 0
3913
- }, this.emitter.emit("stats", this.lastStats), this.renderer instanceof X && !this.live && this.renderer.trimOld(60), (this.renderer instanceof Q || this.renderer instanceof $) && !this.live) {
5451
+ }, this.emitter.emit("stats", this.lastStats), this.renderer instanceof J && this.renderer.trimOld(this.live ? 30 : 60), (this.renderer instanceof X || this.renderer instanceof Z) && !this.live) {
3914
5452
  let e = this.renderer.backlogSeconds;
3915
5453
  e > 10 && !this.sourcePaused ? (this.source?.pause?.(), this.sourcePaused = !0) : e < 4 && this.sourcePaused && (this.source?.resume?.(), this.sourcePaused = !1);
3916
5454
  }
@@ -3920,7 +5458,16 @@ var Bt = class {
3920
5458
  }
3921
5459
  if (this.pendingSeek !== null && !this.nativeMode) {
3922
5460
  let e = this.pendingSeek / 1e3;
3923
- this.renderer?.mode === "mse" && zt(this.video.buffered, e, .5) && (this.video.currentTime = e, this.emitter.emit("seeked", { time: this.pendingSeek }), this.pendingSeek = null);
5461
+ if (this.renderer?.mode === "mse") {
5462
+ let t = this.video.buffered;
5463
+ for (let n = 0; n < t.length; n++) {
5464
+ let r = t.start(n), i = t.end(n);
5465
+ if (e >= r - .5 && e <= i + .5) {
5466
+ this.video.currentTime = Math.max(r + .01, Math.min(e, i - .02)), this.emitter.emit("seeked", { time: this.pendingSeek }), this.pendingSeek = null;
5467
+ break;
5468
+ }
5469
+ }
5470
+ }
3924
5471
  }
3925
5472
  }
3926
5473
  findCodec(e) {
@@ -3947,6 +5494,12 @@ var Bt = class {
3947
5494
  this.audioOnlyTimer && (window.clearTimeout(this.audioOnlyTimer), this.audioOnlyTimer = 0);
3948
5495
  }
3949
5496
  stopPipeline() {
5497
+ if (this.recorder) {
5498
+ try {
5499
+ this.recorder.stop();
5500
+ } catch {}
5501
+ this.recorder = null;
5502
+ }
3950
5503
  this.sourcePaused = !1, this.source?.stop(), this.source = null, this.renderer?.destroy(), this.renderer = null, this.rendererPromise = null, this.clearAudioOnlyTimer(), this.statsTimer && (window.clearInterval(this.statsTimer), this.statsTimer = 0);
3951
5504
  try {
3952
5505
  this.video.pause(), this.video.removeAttribute("src"), this.video.load();
@@ -3957,7 +5510,27 @@ var Bt = class {
3957
5510
  this.stopPipeline(), this.segmenter.flush();
3958
5511
  }
3959
5512
  };
3960
- r(Bt, "version", It);
3961
- export { a as DEFAULTS, L as FLV_TIMESCALE, Bt as FluxKit, Bt as default, i as FluxKitError, De as FlvDemuxer, Ee as FlvTagParser, _t as Fmp4Muxer, At as H264BsdDecoder, Ue as HlsSource, ke as HttpStream, Ot as Libde265Decoder, V as Mp4Demuxer, X as MseRenderer, h as Segmenter, $ as SoftwareRenderer, Me as StreamSource, K as TS_TIMESCALE, m as Timeline, He as TsDemuxer, It as VERSION, Q as WebCodecsRenderer, je as WsStream, Ae as WsTransport, I as aacCodecString, pt as audioMimeType, ue as avcCodecString, fe as avccToAnnexB, P as buildAudioSpecificConfig, le as buildAvcC, ve as buildHvcC, dt as buildInitSegment, mt as codecLabel, Nt as createSoftwareDecoder, D as decodeAmf0, ee as decodeAmf0All, s as detectProtocol, ne as encodeAmf0, re as encodeAmf0Values, U as fetchBytes, H as fetchText, j as hevcCodecString, pe as isAvcKeyframe, ye as isHevcKeyframe, Et as isWebCodecsSupported, J as mimeTypeFor, oe as nalsToAvcc, Se as parseAdts, G as parseAttributes, F as parseAudioSpecificConfig, M as parseAvcC, ce as parseAvcSps, _e as parseHevcSps, N as parseHvcC, Pe as parseMasterPlaylist, Le as parseMediaPlaylist, Fe as parseMediaRenditions, o as resolveOptions, W as resolveUrl, Re as selectVariant, A as splitAnnexB, ft as videoMimeType };
5513
+ r(kn, "version", Cn);
5514
+ function An(e, t, n) {
5515
+ return new Promise((r, a) => {
5516
+ try {
5517
+ e.toBlob((e) => e ? r(e) : a(new i("SNAPSHOT_FAILED", "canvas.toBlob returned null")), t, n);
5518
+ } catch (e) {
5519
+ a(new i("SNAPSHOT_FAILED", "could not export the canvas", e));
5520
+ }
5521
+ });
5522
+ }
5523
+ function jn() {
5524
+ return typeof MediaRecorder > "u" || typeof MediaRecorder.isTypeSupported != "function" ? "video/webm" : [
5525
+ "video/webm;codecs=vp9,opus",
5526
+ "video/webm;codecs=vp8,opus",
5527
+ "video/webm;codecs=vp9",
5528
+ "video/webm;codecs=vp8",
5529
+ "video/webm",
5530
+ "video/mp4;codecs=avc1",
5531
+ "video/mp4"
5532
+ ].find((e) => MediaRecorder.isTypeSupported(e)) ?? "";
5533
+ }
5534
+ export { a as DEFAULTS, M as FLV_TIMESCALE, kn as FluxKit, kn as default, i as FluxKitError, Me as FlvDemuxer, je as FlvTagParser, At as Fmp4Muxer, qt as H264BsdDecoder, W as HlsSource, Fe as HttpStream, Gt as Libde265Decoder, F as Mp4Demuxer, J as MseRenderer, h as Segmenter, Z as SoftwareRenderer, Re as StreamSource, V as TS_TIMESCALE, m as Timeline, Je as TsDemuxer, Cn as VERSION, X as WebCodecsRenderer, Le as WsStream, Ie as WsTransport, De as aacCodecString, Et as audioMimeType, pe as avcCodecString, he as avccToAnnexB, Ee as buildAudioSpecificConfig, fe as buildAvcC, xe as buildHvcC, wt as buildInitSegment, Dt as codecLabel, cn as createSoftwareDecoder, D as decodeAmf0, ee as decodeAmf0All, Lt as decodeG711, Rt as decodeG711Float, s as detectProtocol, ne as encodeAmf0, ie as encodeAmf0Values, L as fetchBytes, I as fetchText, O as hevcCodecString, rn as installSoftWorker, ge as isAvcKeyframe, Se as isHevcKeyframe, Ut as isWebCodecsSupported, K as mimeTypeFor, le as nalsToAvcc, Te as parseAdts, z as parseAttributes, j as parseAudioSpecificConfig, k as parseAvcC, de as parseAvcSps, be as parseHevcSps, A as parseHvcC, Be as parseMasterPlaylist, B as parseMediaPlaylist, Ve as parseMediaRenditions, o as resolveOptions, R as resolveUrl, Ue as selectVariant, ce as splitAnnexB, Tt as videoMimeType };
3962
5535
 
3963
5536
  //# sourceMappingURL=fluxkit.js.map