@wix/video 1.72.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +126 -0
  3. package/dist/cjs/Video.js +121 -0
  4. package/dist/cjs/Video.js.map +1 -0
  5. package/dist/cjs/Video.module.scss +27 -0
  6. package/dist/cjs/Video.stories.js +68 -0
  7. package/dist/cjs/Video.stories.js.map +1 -0
  8. package/dist/cjs/custom-element/WowVideo.js +88 -0
  9. package/dist/cjs/custom-element/WowVideo.js.map +1 -0
  10. package/dist/cjs/custom-element/registry.js +34 -0
  11. package/dist/cjs/custom-element/registry.js.map +1 -0
  12. package/dist/cjs/custom-element/utils.js +138 -0
  13. package/dist/cjs/custom-element/utils.js.map +1 -0
  14. package/dist/cjs/custom-element/videoLayout.js +120 -0
  15. package/dist/cjs/custom-element/videoLayout.js.map +1 -0
  16. package/dist/cjs/customElementInit.js +10 -0
  17. package/dist/cjs/customElementInit.js.map +1 -0
  18. package/dist/cjs/dataManifest.js +53 -0
  19. package/dist/cjs/dataManifest.js.map +1 -0
  20. package/dist/cjs/external-types.d.js +2 -0
  21. package/dist/cjs/external-types.d.js.map +1 -0
  22. package/dist/cjs/index.js +23 -0
  23. package/dist/cjs/index.js.map +1 -0
  24. package/dist/cjs/storybook/Container.js +33 -0
  25. package/dist/cjs/storybook/Container.js.map +1 -0
  26. package/dist/cjs/storybook/args.js +178 -0
  27. package/dist/cjs/storybook/args.js.map +1 -0
  28. package/dist/cjs/test-types.d.js +2 -0
  29. package/dist/cjs/test-types.d.js.map +1 -0
  30. package/dist/cjs/types.js +4 -0
  31. package/dist/cjs/types.js.map +1 -0
  32. package/dist/esm/Video.js +95 -0
  33. package/dist/esm/Video.js.map +1 -0
  34. package/dist/esm/Video.module.scss +27 -0
  35. package/dist/esm/Video.stories.js +47 -0
  36. package/dist/esm/Video.stories.js.map +1 -0
  37. package/dist/esm/custom-element/WowVideo.js +83 -0
  38. package/dist/esm/custom-element/WowVideo.js.map +1 -0
  39. package/dist/esm/custom-element/registry.js +29 -0
  40. package/dist/esm/custom-element/registry.js.map +1 -0
  41. package/dist/esm/custom-element/utils.js +131 -0
  42. package/dist/esm/custom-element/utils.js.map +1 -0
  43. package/dist/esm/custom-element/videoLayout.js +117 -0
  44. package/dist/esm/custom-element/videoLayout.js.map +1 -0
  45. package/dist/esm/customElementInit.js +13 -0
  46. package/dist/esm/customElementInit.js.map +1 -0
  47. package/dist/esm/dataManifest.js +49 -0
  48. package/dist/esm/dataManifest.js.map +1 -0
  49. package/dist/esm/external-types.d.js +2 -0
  50. package/dist/esm/external-types.d.js.map +1 -0
  51. package/dist/esm/index.js +6 -0
  52. package/dist/esm/index.js.map +1 -0
  53. package/dist/esm/storybook/Container.js +21 -0
  54. package/dist/esm/storybook/Container.js.map +1 -0
  55. package/dist/esm/storybook/args.js +174 -0
  56. package/dist/esm/storybook/args.js.map +1 -0
  57. package/dist/esm/test-types.d.js +2 -0
  58. package/dist/esm/test-types.d.js.map +1 -0
  59. package/dist/esm/types.js +2 -0
  60. package/dist/esm/types.js.map +1 -0
  61. package/dist/statics/189.chunk.js +35383 -0
  62. package/dist/statics/189.chunk.js.map +1 -0
  63. package/dist/statics/189.chunk.min.js +2 -0
  64. package/dist/statics/189.chunk.min.js.map +1 -0
  65. package/dist/statics/janet/110.8a580c2d.iframe.bundle.js +10826 -0
  66. package/dist/statics/janet/110.8a580c2d.iframe.bundle.js.map +1 -0
  67. package/dist/statics/janet/134.6007b391.iframe.bundle.js +484 -0
  68. package/dist/statics/janet/134.6007b391.iframe.bundle.js.map +1 -0
  69. package/dist/statics/janet/134.d48c36bc94ecd2280c0a.manager.bundle.js +1 -0
  70. package/dist/statics/janet/317.2df397a1e1f34d5a30fd.manager.bundle.js +1 -0
  71. package/dist/statics/janet/326.e8fcdb36.iframe.bundle.js +1998 -0
  72. package/dist/statics/janet/326.e8fcdb36.iframe.bundle.js.map +1 -0
  73. package/dist/statics/janet/326.ff40cdf1778fd94969c8.manager.bundle.js +2 -0
  74. package/dist/statics/janet/326.ff40cdf1778fd94969c8.manager.bundle.js.LICENSE.txt +31 -0
  75. package/dist/statics/janet/470.aab6696c.iframe.bundle.js +35380 -0
  76. package/dist/statics/janet/470.aab6696c.iframe.bundle.js.map +1 -0
  77. package/dist/statics/janet/599.37d4aa34.iframe.bundle.js +3294 -0
  78. package/dist/statics/janet/599.37d4aa34.iframe.bundle.js.map +1 -0
  79. package/dist/statics/janet/599.47c7dacc8997e4d71eac.manager.bundle.js +1 -0
  80. package/dist/statics/janet/61.5cb88eb5.iframe.bundle.js +2652 -0
  81. package/dist/statics/janet/61.5cb88eb5.iframe.bundle.js.map +1 -0
  82. package/dist/statics/janet/61.a575d4776ab0d42da5c8.manager.bundle.js +1 -0
  83. package/dist/statics/janet/673.59f2a23a.iframe.bundle.js +173 -0
  84. package/dist/statics/janet/673.59f2a23a.iframe.bundle.js.map +1 -0
  85. package/dist/statics/janet/725.0db49c6347dfe44ace2d.manager.bundle.js +2 -0
  86. package/dist/statics/janet/725.0db49c6347dfe44ace2d.manager.bundle.js.LICENSE.txt +8 -0
  87. package/dist/statics/janet/725.cbba2e4b.iframe.bundle.js +10451 -0
  88. package/dist/statics/janet/725.cbba2e4b.iframe.bundle.js.map +1 -0
  89. package/dist/statics/janet/734.428ea23e9773cd26fb57.manager.bundle.js +2 -0
  90. package/dist/statics/janet/734.428ea23e9773cd26fb57.manager.bundle.js.LICENSE.txt +94 -0
  91. package/dist/statics/janet/833.75275036.iframe.bundle.js +6777 -0
  92. package/dist/statics/janet/833.75275036.iframe.bundle.js.map +1 -0
  93. package/dist/statics/janet/833.ef639b005d7b76723595.manager.bundle.js +2 -0
  94. package/dist/statics/janet/833.ef639b005d7b76723595.manager.bundle.js.LICENSE.txt +12 -0
  95. package/dist/statics/janet/W-06.svg +1 -0
  96. package/dist/statics/janet/favicon.ico +0 -0
  97. package/dist/statics/janet/iframe.html +364 -0
  98. package/dist/statics/janet/index.html +59 -0
  99. package/dist/statics/janet/janet.json +10 -0
  100. package/dist/statics/janet/main.666d4853f3d62ab20aa1.manager.bundle.js +1 -0
  101. package/dist/statics/janet/main.d8a321d6.iframe.bundle.js +73260 -0
  102. package/dist/statics/janet/main.d8a321d6.iframe.bundle.js.map +1 -0
  103. package/dist/statics/janet/project.json +1 -0
  104. package/dist/statics/janet/runtime~main.2195d24e465f19ad9c9a.manager.bundle.js +1 -0
  105. package/dist/statics/janet/w-06.ico +0 -0
  106. package/dist/statics/manifest.json +4 -0
  107. package/dist/statics/manifest.min.json +4 -0
  108. package/dist/statics/video.css +10 -0
  109. package/dist/statics/video.css.map +1 -0
  110. package/dist/statics/video.min.css +1 -0
  111. package/dist/statics/video.rtl.css +8 -0
  112. package/dist/statics/video.rtl.min.css +1 -0
  113. package/dist/statics/video.umd.js +5990 -0
  114. package/dist/statics/video.umd.js.map +1 -0
  115. package/dist/statics/video.umd.min.js +2 -0
  116. package/dist/statics/video.umd.min.js.map +1 -0
  117. package/dist/tsconfig.tsbuildinfo +1 -0
  118. package/dist/types/Video.d.ts +5 -0
  119. package/dist/types/Video.d.ts.map +1 -0
  120. package/dist/types/Video.stories.d.ts +20 -0
  121. package/dist/types/Video.stories.d.ts.map +1 -0
  122. package/dist/types/custom-element/WowVideo.d.ts +4 -0
  123. package/dist/types/custom-element/WowVideo.d.ts.map +1 -0
  124. package/dist/types/custom-element/registry.d.ts +3 -0
  125. package/dist/types/custom-element/registry.d.ts.map +1 -0
  126. package/dist/types/custom-element/utils.d.ts +11 -0
  127. package/dist/types/custom-element/utils.d.ts.map +1 -0
  128. package/dist/types/custom-element/videoLayout.d.ts +35 -0
  129. package/dist/types/custom-element/videoLayout.d.ts.map +1 -0
  130. package/dist/types/customElementInit.d.ts +4 -0
  131. package/dist/types/customElementInit.d.ts.map +1 -0
  132. package/dist/types/dataManifest.d.ts +2 -0
  133. package/dist/types/dataManifest.d.ts.map +1 -0
  134. package/dist/types/index.d.ts +6 -0
  135. package/dist/types/index.d.ts.map +1 -0
  136. package/dist/types/storybook/Container.d.ts +5 -0
  137. package/dist/types/storybook/Container.d.ts.map +1 -0
  138. package/dist/types/storybook/args.d.ts +174 -0
  139. package/dist/types/storybook/args.d.ts.map +1 -0
  140. package/dist/types/types.d.ts +62 -0
  141. package/dist/types/types.d.ts.map +1 -0
  142. package/package.json +121 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"189.chunk.js","mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC,GAAG;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD,+BAA+B;AACnF;AACA,sDAAsD,+BAA+B;AACrF;AACA,uDAAuD;AACvD;AACA,6EAA6E;AAC7E;AACA,kEAAkE;AAClE;AACA,iDAAiD,+BAA+B;AAChF;AACA,mDAAmD,+BAA+B;AAClF;AACA,kDAAkD;AAClD;AACA,mDAAmD;AACnD;AACA,wDAAwD,+BAA+B;AACvF;AACA,0DAA0D,+BAA+B;AACzF;AACA,0DAA0D,+BAA+B;AACzF;AACA,4DAA4D,+BAA+B;AAC3F;AACA,kDAAkD,qCAAqC;AACvF;AACA,0DAA0D;AAC1D;AACA,+DAA+D;AAC/D;AACA,6DAA6D;AAC7D;AACA;AACA;AACA;AACA,wDAAwD;AACxD;AACA,qDAAqD,qCAAqC;AAC1F;AACA,6DAA6D;AAC7D;AACA,8FAA8F;AAC9F;AACA,kJAAkJ;AAClJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mEAAmE,6BAA6B;AAChG;AACA,qEAAqE,6BAA6B;AAClG;AACA,sEAAsE,sDAAsD;AAC5H;AACA,sEAAsE,sDAAsD;AAC5H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC,GAAG;;AAEJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wFAAwF,WAAW;AACnG;AACA,0DAA0D;AAC1D;AACA,4DAA4D;AAC5D;AACA,oFAAoF;AACpF;AACA;AACA;AACA;AACA;AACA,4DAA4D;AAC5D;AACA;AACA;AACA,8DAA8D;AAC9D;AACA,oDAAoD;AACpD;AACA,oDAAoD;AACpD;AACA,sDAAsD;AACtD;AACA,sDAAsD;AACtD;AACA,0DAA0D;AAC1D;AACA,4DAA4D;AAC5D;AACA,kHAAkH;AAClH;AACA,8FAA8F;AAC9F;AACA,+EAA+E;AAC/E;AACA,uEAAuE;AACvE;AACA,gEAAgE;AAChE;AACA,gEAAgE;AAChE;AACA,wDAAwD;AACxD;AACA,0DAA0D;AAC1D;AACA,0HAA0H;AAC1H;AACA,0EAA0E;AAC1E;AACA;AACA;AACA,0DAA0D;AAC1D;AACA,0DAA0D;AAC1D;AACA,4DAA4D;AAC5D;AACA,4HAA4H;AAC5H;AACA,iEAAiE;AACjE;AACA,oFAAoF;AACpF;AACA,yEAAyE,YAAY,gDAAgD;AACrI;AACA,uDAAuD;AACvD;AACA,oDAAoD;AACpD;AACA,4DAA4D,0BAA0B;AACtF;AACA,+EAA+E;AAC/E;AACA,0DAA0D;AAC1D;AACA,6DAA6D,8EAA8E;AAC3I;AACA,wEAAwE;AACxE;AACA,wDAAwD;AACxD;AACA,mDAAmD;AACnD;AACA,iEAAiE;AACjE;AACA,wDAAwD;AACxD;AACA,8FAA8F;AAC9F;AACA,qFAAqF;AACrF;AACA,+CAA+C;AAC/C;AACA,mEAAmE;AACnE;AACA,kDAAkD;AAClD;AACA,6CAA6C;AAC7C;AACA;AACA;AACA,uDAAuD;AACvD;AACA,6DAA6D;AAC7D;AACA,iBAAiB,0CAA0C;AAC3D;AACA,uGAAuG;AACvG;AACA,6DAA6D;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC,GAAG;;AAEJ;AACA,+DAA+D,8BAA8B;AAC7F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA,oBAAoB,sBAAsB;AAC1C;AACA,0BAA0B;AAC1B;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,kBAAkB,sBAAsB;AACxC;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,MAAM;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,2CAA2C,0BAA0B,GAAG,KAAK;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,+CAA+C,QAAQ,sBAAsB,QAAQ;AACrF,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,oBAAoB,kBAAkB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,kBAAkB;;AAElB;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,wFAAwF,iBAAiB;AACzG;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yBAAyB;AACzB;AACA;AACA;AACA;AACA,2BAA2B;AAC3B;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;;AAEA;AACA,GAAG;AACH,GAAG;AACH;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,kEAAkE,oCAAoC;AACtG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,0EAA0E,mCAAmC;AAC7G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,kBAAkB,QAAQ;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,QAAQ;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,kBAAkB,qBAAqB;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,kBAAkB,kBAAkB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA,oBAAoB;AACpB;AACA;AACA,+BAA+B;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,IAAI;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D;AAC1D,8FAA8F;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wDAAwD,oBAAoB,oBAAoB,wBAAwB,KAAK,mBAAmB;AAChJ;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,kBAAkB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,kBAAkB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,kBAAkB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,aAAa;AACb,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,iBAAiB;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;;AAEhC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B,kBAAkB;AAC/C;AACA;AACA;AACA,gBAAgB;AAChB;AACA;AACA;AACA;AACA;AACA,gBAAgB;AAChB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;;AAEN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN;AACA,6CAA6C,aAAa,qBAAqB,UAAU;AACzF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,gBAAgB;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,wBAAwB,QAAQ;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,YAAY;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc,eAAe;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,SAAS;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,wBAAwB;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,KAAK,KAAK,SAAS,MAAM;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D;AAC9D;AACA,GAAG;AACH,kBAAkB,0BAA0B;AAC5C;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,sBAAsB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,IAAI;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,mBAAmB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC,iBAAiB;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD;AACjD,iDAAiD;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,mDAAmD,SAAS;AAC5D;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA,SAAS;AACT;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oJAAoJ,GAAG;AACvJ;AACA;AACA;AACA,6CAA6C,6BAA6B;AAC1E;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA,iBAAiB,aAAa,GAAG,YAAY,GAAG,2BAA2B,EAAE,+BAA+B,GAAG,MAAM,GAAG,+BAA+B;AACvJ;AACA;AACA,iBAAiB,eAAe,EAAE,mCAAmC,GAAG,MAAM;AAC9E;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B,kCAAkC;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,SAAS,0CAA0C;AACnD;AACA;AACA;AACA,SAAS,iFAAiF;AAC1F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ,iCAAiC,IAAI;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mEAAmE,0BAA0B,wBAAwB,UAAU;AAC/H;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4EAA4E,qBAAqB;AACjG;AACA;AACA;AACA;AACA,yEAAyE,oBAAoB,yCAAyC,oCAAoC;AAC1K;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,sEAAsE,yBAAyB,eAAe,UAAU;AACxH;AACA;AACA;AACA,qEAAqE,4BAA4B,eAAe,aAAa;AAC7H;AACA;AACA;AACA,oFAAoF,wBAAwB;AAC5G;AACA;AACA;AACA,4EAA4E,qBAAqB;AACjG;AACA;AACA;AACA,iEAAiE,wBAAwB,oBAAoB,cAAc;AAC3H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,QAAQ,oBAAoB,OAAO;AAChF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA,GAAG,IAAI;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,mBAAmB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,IAAI;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA,4BAA4B,QAAQ;AACpC;AACA;AACA;AACA;AACA,gCAAgC,gBAAgB;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD,8BAA8B;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,QAAQ,EAAE,mCAAmC,WAAW,qBAAqB;AACzG,2BAA2B;AAC3B,6BAA6B,kCAAkC;AAC/D,kDAAkD,4BAA4B;AAC9E,sDAAsD,qCAAqC;AAC3F,uBAAuB,UAAU;AACjC,6BAA6B,yDAAyD;AACtF,yBAAyB,0BAA0B;AACnD,2BAA2B,eAAe,IAAI,0BAA0B;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD;AACjD,2BAA2B,0BAA0B;AACrD,6BAA6B,kCAAkC;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,uBAAuB;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0FAA0F,YAAY,aAAa,QAAQ;AAC3H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc,qBAAqB,GAAG,qCAAqC;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,oCAAoC,8CAA8C,uCAAuC;AAChK;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mEAAmE,0BAA0B,UAAU;AAC1H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gEAAgE;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA,oCAAoC,qBAAqB;AACzD,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,mBAAmB;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kEAAkE,mBAAmB,cAAc,OAAO,EAAE,wBAAwB;AACpI,cAAc;AACd,uFAAuF,OAAO,EAAE,wBAAwB;AACxH;AACA,uDAAuD,MAAM;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,yBAAyB,KAAK,cAAc,mCAAmC,gCAAgC,IAAI,sCAAsC,uBAAuB,gBAAgB,IAAI,kBAAkB;AACjQ;AACA,wCAAwC,mBAAmB,IAAI,GAAG,aAAa,uBAAuB,YAAY,kCAAkC,OAAO,4BAA4B,cAAc,wBAAwB,mBAAmB,6BAA6B,gBAAgB,0BAA0B,iBAAiB,gBAAgB,WAAW,oBAAoB,aAAa,sBAAsB,gBAAgB,UAAU;AACpb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,wBAAwB;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,8DAA8D;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,MAAM,GAAG,aAAa,GAAG,gBAAgB,GAAG,qCAAqC,GAAG,UAAU;AAC3I;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,MAAM;AACN;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,UAAU;AACV;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,gCAAgC;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC;AACzC;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,QAAQ;AACR,kCAAkC,IAAI;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV,gDAAgD,sBAAsB;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,iBAAiB;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,YAAY,QAAQ,aAAa;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,IAAI;AACxC,2BAA2B,sBAAsB;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,IAAI;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,8BAA8B,IAAI;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,sBAAsB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,sBAAsB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,8BAA8B,IAAI;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,cAAc,GAAG,eAAe,GAAG,YAAY;AAC3D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,wDAAwD,aAAa;AACrE;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,SAAS;AACzB;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,gBAAgB,SAAS;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,gBAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA,uBAAuB,mBAAmB;AAC1C;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,aAAa;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,QAAQ;AAC/D;AACA;;AAEA,uBAAuB;;AAEvB;AACA;AACA;AACA,IAAI,IAAI;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,0EAA0E,SAAS,IAAI,YAAY;AACnG;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,IAAI;AACnC;AACA;AACA;;AAEA,wCAAwC;;AAExC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qDAAqD,0BAA0B;AAC/E;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,2CAA2C,eAAe,EAAE,cAAc;AAC1E;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,qBAAqB;AACnE;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,2CAA2C,eAAe,EAAE,cAAc;AAC1E;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,qBAAqB;AACnE;AACA;AACA,WAAW;AACX;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,gCAAgC;AACjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,IAAI;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,uBAAuB;AAC3C;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,qBAAqB;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,oBAAoB,sBAAsB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;;AAEA,sCAAsC,oBAAoB;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+IAA+I,aAAa;AAC5J;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,4BAA4B,KAAK,gDAAgD,UAAU;AAC3F;AACA,MAAM;AACN,0GAA0G,cAAc;AACxH;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA,mIAAmI,KAAK;AACxI,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ,kJAAkJ,OAAO;AACzJ;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,4BAA4B;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,MAAM,cAAc,MAAM;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,IAAI,sCAAsC,iBAAiB;AAC9G;AACA;AACA;AACA;AACA;AACA,8CAA8C;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,6EAA6E,QAAQ,KAAK,UAAU;AACpG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,yEAAyE,2BAA2B;AACpG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,IAAI;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qDAAqD,OAAO;AAC5D;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yBAAyB,kBAAkB;AAC3C;AACA;AACA;AACA,iDAAiD;AACjD;AACA;AACA;AACA;AACA;AACA,sCAAsC;AACtC;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,UAAU;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,SAAS,MAAM;AAC9C;AACA;AACA,KAAK;AACL;AACA,+BAA+B,SAAS,MAAM;AAC9C;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0EAA0E,YAAY;;AAEtF;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,sDAAsD;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,QAAQ;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,8DAA8D;;AAE9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,mBAAmB;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB;AAChB,+EAA+E,WAAW;AAC1F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA,oBAAoB,mBAAmB;AACvC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,KAAK;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB;AAChB,gEAAgE,OAAO;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC;AACzC;AACA;AACA,gBAAgB;AAChB,uEAAuE,OAAO;AAC9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB;AAChB;AACA;AACA;AACA;AACA;AACA,qCAAqC,YAAY,GAAG,MAAM;AAC1D,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wDAAwD,OAAO;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,IAAI;AACxC;AACA;AACA;AACA,uCAAuC,IAAI;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,gBAAgB;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C;AAC3C;AACA;AACA,gCAAgC,YAAY;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,IAAI;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA,mDAAmD,KAAK,kCAAkC,UAAU;AACpG;AACA;AACA,mDAAmD,KAAK,8CAA8C,UAAU;AAChH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,OAAO;AAC3B;AACA;;AAEA;AACA,oBAAoB,0BAA0B;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,QAAQ;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,yBAAyB;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,+CAA+C,IAAI;AACnD;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,6BAA6B;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ,gCAAgC;AAChC;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,8EAA8E,oCAAoC;AAClH;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,UAAU;AACrD;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,UAAU;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sFAAsF,WAAW;AACjG;AACA,QAAQ;AACR,+FAA+F,WAAW,IAAI,WAAW;AACzH;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,SAAS,EAAE;AACjC,qBAAqB;AACrB,EAAE;;AAEF,qBAAqB;AACrB,EAAE,gBAAgB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA,IAAI;AACJ;AACA;AACA,IAAI;AACJ;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,sBAAsB;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC,IAAI;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,GAAG;AACH;;AAEA;AACA,0CAA0C,SAAS;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,SAAS;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oEAAoE,SAAS;AAC7E;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oBAAoB,SAAS;AAC7B,iBAAiB,sBAAsB,GAAG,oBAAoB;AAC9D;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,mCAAmC,mEAAmE,WAAW,MAAM;AACvH;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,wBAAwB,eAAe,qBAAqB;AACxH;AACA;AACA;AACA;;AAEA;AACA;AACA,6CAA6C,aAAa;AAC1D;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,WAAW,MAAM,QAAQ,EAAE,8CAA8C,KAAK,sCAAsC;AACzI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,WAAW,MAAM,SAAS,KAAK,sBAAsB,EAAE,WAAW;AAC7F;AACA;;AAEA,yCAAyC;AACzC;AACA,KAAK;AACL;AACA;AACA;AACA,+BAA+B,qDAAqD;AACpF;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,QAAQ;AACR;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA,SAAS;AACT;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,yBAAyB,WAAW,MAAM,QAAQ,EAAE,oCAAoC,KAAK,kCAAkC,WAAW,4EAA4E;AACtN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,qBAAqB;AACjF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,yBAAyB;AAClF;AACA;AACA;AACA,kCAAkC,SAAS,MAAM,gBAAgB,GAAG,cAAc,KAAK,sBAAsB,EAAE,WAAW;AAC1H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,gCAAgC,aAAa,gDAAgD,IAAI,QAAQ;AAC7I;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,WAAW,MAAM,SAAS,QAAQ,YAAY,GAAG,UAAU,GAAG,oBAAoB,OAAO,iCAAiC,QAAQ,SAAS,GAAG,gBAAgB,GAAG,cAAc,aAAa,wCAAwC;AAClQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,4BAA4B;AACxF;AACA,MAAM;AACN;AACA;AACA;AACA,wBAAwB,WAAW,MAAM,SAAS,KAAK,2BAA2B,QAAQ,SAAS,EAAE,iEAAiE,YAAY,wCAAwC;AAC1N;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,SAAS;AACT;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC,gCAAgC,gCAAgC,oBAAoB;AACtH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,oEAAoE,IAAI,KAAK,sBAAsB,EAAE,WAAW;AAChH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,cAAc;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,mEAAmE,QAAQ,UAAU,wBAAwB;AAC7G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,eAAe,+CAA+C,WAAW,oBAAoB,kBAAkB,cAAc,8CAA8C;AACxN;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,aAAa,6BAA6B,GAAG;AAChG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,IAAI;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,SAAS;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gFAAgF,6BAA6B;AAC7G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mFAAmF,QAAQ;AAC3F;AACA;AACA,4EAA4E;AAC5E;AACA;AACA;AACA;AACA,mFAAmF,QAAQ;AAC3F;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,gCAAgC,YAAY,iDAAiD,IAAI,iBAAiB,aAAa,OAAO;AAC/K;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,eAAe,wBAAwB,iBAAiB,WAAW,yDAAyD;AACzK;AACA,QAAQ;AACR;AACA;AACA;AACA,sEAAsE,cAAc;AACpF;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,QAAQ,EAAE,mCAAmC,KAAK,sBAAsB,EAAE,YAAY;AAClH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oEAAoE,UAAU,IAAI,gFAAgF;AAClK;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,4BAA4B,SAAS,KAAK,YAAY,EAAE,YAAY,eAAe,aAAa,qBAAqB,eAAe,GAAG,yBAAyB,KAAK,MAAM;AAC3K;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,qBAAqB,cAAc,iCAAiC,WAAW;AAC/E;AACA;AACA,MAAM;AACN;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sFAAsF,cAAc;AACpG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA,sEAAsE,cAAc,KAAK,sBAAsB,EAAE,gBAAgB;AACjI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gDAAgD,SAAS,EAAE,MAAM,qBAAqB,eAAe;AACrG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,SAAS,KAAK,sBAAsB,EAAE,YAAY;AAChH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,SAAS,KAAK,sBAAsB,GAAG,UAAU;AAC5F,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,WAAW,MAAM,QAAQ,EAAE,oCAAoC,KAAK,iCAAiC;AAC5H;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,cAAc,sBAAsB,EAAE,YAAY,GAAG,uBAAuB,IAAI,+FAA+F,GAAG,6FAA6F,GAAG,uFAAuF;AACzW;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,cAAc,IAAI,UAAU;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,mBAAmB;AACrC;AACA;AACA;AACA;AACA;AACA;;AAEA,qBAAqB;;AAErB;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,aAAa,UAAU;AACvB,aAAa,GAAG;AAChB,aAAa,SAAS;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,aAAa,cAAc;AAC3B,aAAa,iBAAiB;AAC9B,aAAa,UAAU;AACvB,aAAa,GAAG;AAChB,aAAa,SAAS;AACtB,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,aAAa,cAAc;AAC3B,aAAa,iBAAiB;AAC9B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,aAAa,iBAAiB;AAC9B,eAAe,OAAO;AACtB;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,4DAA4D,OAAO;AACnE;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,aAAa,iBAAiB;AAC9B,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,aAAa,iBAAiB;AAC9B,eAAe,SAAS;AACxB;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,4CAA4C,SAAS;AACrD;AACA;;AAEA;AACA,MAAM;AACN;AACA;;AAEA,kBAAkB,YAAY;AAC9B;;AAEA;AACA,8DAA8D;AAC9D,kEAAkE;AAClE,sEAAsE;AACtE,0EAA0E;AAC1E;AACA,6DAA6D,SAAS;AACtE;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,aAAa,iBAAiB;AAC9B,aAAa,UAAU;AACvB,aAAa,GAAG;AAChB,eAAe,cAAc;AAC7B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,aAAa,iBAAiB;AAC9B,aAAa,UAAU;AACvB,aAAa,GAAG;AAChB,eAAe,cAAc;AAC7B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,aAAa,iBAAiB;AAC9B,aAAa,UAAU;AACvB,aAAa,GAAG;AAChB,aAAa,SAAS;AACtB,eAAe,cAAc;AAC7B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,8DAA8D,YAAY;AAC1E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,aAAa,iBAAiB;AAC9B,eAAe,cAAc;AAC7B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,YAAY,iBAAiB,mBAAmB,KAAK,gBAAgB,GAAG,iCAAiC,QAAQ;AAC/J;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,2DAA2D,kBAAkB;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,cAAc,iBAAiB,MAAM,aAAa,aAAa,SAAS,YAAY,oBAAoB,gBAAgB,iBAAiB,kBAAkB;AAC1L;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,oBAAoB,GAAG,YAAY,GAAG,gBAAgB;AAChH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,+BAA+B,WAAW,QAAQ,OAAO,uBAAuB,YAAY,GAAG,oBAAoB,GAAG,iBAAiB,WAAW,QAAQ;AAC1J;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,aAAa,YAAY,GAAG;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,aAAa,YAAY,GAAG;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA,IAAI;AACJ;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,mBAAmB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC,GAAG;;AAEJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,KAAK;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC,iBAAiB;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mCAAmC;AACnC,mCAAmC;AACnC,kCAAkC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA,eAAe;AACf;;AAEA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC,iBAAiB;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wGAAwG;AACxG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,4BAA4B,oCAAoC;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B,qCAAqC;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB;AACnB;AACA,4BAA4B;AAC5B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAmB;AACnB;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mDAAmD;AACnD,0CAA0C;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA,0BAA0B;AAC1B,+BAA+B,uCAAuC;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,+BAA+B;AAC/B;AACA;;AAEA;AACA;AACA,iCAAiC;AACjC;AACA;AACA,6BAA6B;AAC7B,MAAM;AACN,gCAAgC;AAChC;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,OAAO;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,WAAW;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC;AACpC,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AACjB,eAAe;AACf;AACA;AACA;AACA;AACA;AACA,QAAQ;;AAER,iBAAiB;AACjB,iBAAiB;AACjB,mBAAmB;AACnB;AACA;AACA;AACA,oBAAoB,sBAAsB;AAC1C;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA,iBAAiB;AACjB,MAAM;AACN,mBAAmB;AACnB,gBAAgB;AAChB,gBAAgB;AAChB;AACA,kBAAkB,oCAAoC;AACtD;AACA,QAAQ;AACR;AACA,eAAe;AACf,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,MAAM;;AAEN,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,oBAAoB;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB;AACpB;AACA,oBAAoB;AACpB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB;AACpB;AACA,sBAAsB;;AAEtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,2BAA2B;AAC/C;AACA;AACA;AACA;AACA,0CAA0C,OAAO;AACjD;AACA;AACA;AACA,oBAAoB,2BAA2B;AAC/C;AACA,wBAAwB;AACxB;AACA;AACA;AACA,wBAAwB;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mFAAmF,4BAA4B;AAC/G,oBAAoB;AACpB,oBAAoB;AACpB,oBAAoB;AACpB;AACA,kBAAkB;AAClB,kBAAkB;AAClB,kBAAkB;AAClB,kBAAkB;AAClB,kBAAkB;AAClB,kBAAkB;AAClB;AACA;AACA;AACA;AACA,6BAA6B,YAAY;AACzC,iCAAiC,mCAAmC;AACpE;AACA;AACA,4BAA4B;AAC5B,cAAc;AACd;AACA;AACA;AACA;AACA,8BAA8B,aAAa;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB,sBAAsB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,iCAAiC;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,qBAAqB;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,wBAAwB,uBAAuB;AAC/C;AACA;AACA;AACA,wBAAwB,uBAAuB;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,gCAAgC;AACtD,wBAAwB,2CAA2C;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB,sBAAsB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB;AACxB,wBAAwB;AACxB,wBAAwB;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B,4BAA4B;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,4BAA4B;AACtD,0CAA0C;AAC1C;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA,8BAA8B,aAAa;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,aAAa;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B;AAC1B,0BAA0B;AAC1B,0BAA0B;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,QAAQ;AAC5B,sHAAsH;AACtH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,qBAAqB,EAAE,oBAAoB,GAAG,mCAAmC,GAAG,iBAAiB,EAAE,kBAAkB;AACpJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,kBAAkB;AAClB,oBAAoB;AACpB,oBAAoB;AACpB,oBAAoB;AACpB;AACA;AACA,iBAAiB;AACjB,oBAAoB;AACpB;AACA;AACA;AACA;AACA,iBAAiB;AACjB,iBAAiB;AACjB,oBAAoB;AACpB;AACA;AACA,6BAA6B;AAC7B;AACA,2BAA2B;AAC3B,MAAM;AACN,2BAA2B;AAC3B,MAAM;AACN,2BAA2B;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0EAA0E,WAAW;AACrF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iCAAiC,aAAa;AAC9C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,OAAO,qBAAqB,WAAW,gCAAgC,YAAY;AAC5I;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,yDAAyD,gBAAgB;AACzE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,YAAY;AACZ;AACA;AACA,SAAS;AACT,QAAQ;AACR;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,cAAc;AAC7D;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kDAAkD,kBAAkB;AACpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kEAAkE,OAAO;AACzE,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,kBAAkB;AACjC;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC;AACjC;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,cAAc;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA,gBAAgB,MAAM;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yBAAyB,sCAAsC;AAC/D;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,aAAa;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,UAAU;AACV;AACA,UAAU;AACV;AACA,UAAU;AACV;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B;;AAE9B,6DAA6D;AAC7D,yDAAyD;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,SAAS;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,oBAAoB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,gBAAgB,sBAAsB;AACtC;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,gBAAgB,sBAAsB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,uDAAuD;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,mCAAmC,YAAY,iBAAiB,aAAa,GAAG,YAAY;AAC5F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,SAAS;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,oBAAoB,kBAAkB;AACtC;AACA,sBAAsB,qBAAqB;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,kBAAkB;AACtC;AACA;AACA,sBAAsB,qBAAqB;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iDAAiD;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,6CAA6C;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,oBAAoB,SAAS,QAAQ;AAC5F;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ,wEAAwE,QAAQ;AAChF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,oBAAoB,eAAe;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,yCAAyC,IAAI,kCAAkC,MAAM,MAAM,0CAA0C,sBAAsB;AACzL,UAAU;AACV,8BAA8B,yCAAyC,IAAI,mCAAmC,MAAM,MAAM,iDAAiD,sBAAsB;AACjM;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA,4BAA4B,yBAAyB;AACrD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,oCAAoC,GAAG,oCAAoC,WAAW,kCAAkC;AACtL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,eAAe;AACnC;AACA;AACA;AACA;AACA;AACA,sBAAsB,aAAa;AACnC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,SAAS;AACvD,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,eAAe;AACnC;AACA;AACA;AACA;AACA,yDAAyD,aAAa;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,kEAAkE,sBAAsB,wBAAwB,iBAAiB,wBAAwB;AACzJ,YAAY;AACZ;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA,sDAAsD,SAAS;AAC/D;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,gDAAgD;AAChD;;AAEA;AACA;AACA,8CAA8C,yBAAyB;AACvE;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,8CAA8C,kCAAkC,6BAA6B,2CAA2C;AACxJ;AACA;AACA,UAAU;;AAEV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,SAAS,gBAAgB,sCAAsC,WAAW,2CAA2C;AAC5K,0BAA0B,aAAa;AACvC;AACA;AACA;AACA,gGAAgG;AAChG;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sDAAsD,gBAAgB;AACtE;AACA;AACA;AACA;AACA,mGAAmG;AACnG;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD,SAAS;AAC7D,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,mHAAmH;AACnH;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,oBAAoB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,gBAAgB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,gBAAgB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,qDAAqD;AACrD;AACA;AACA;AACA;;AAEA;AACA,iCAAiC;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,YAAY,OAAO,sCAAsC,KAAK,oBAAoB;AACjI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,YAAY;AACtD;AACA;AACA;AACA;AACA,wCAAwC,YAAY;AACpD;AACA;;AAEA;AACA;AACA;AACA;AACA,EAAE;AACF;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA;AACA,CAAC;AACD;AACA;AACA,CAAC;AACD;AACA;AACA,CAAC;AACD;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEA,6CAA6C;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,6CAA6C;AAC7C;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,cAAc;AACvD;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN,gDAAgD,SAAS,MAAM,aAAa,EAAE,uDAAuD,KAAK,wDAAwD,EAAE,gBAAgB;AACpN;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,4CAA4C,SAAS;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,gBAAgB,GAAG,eAAe,GAAG,aAAa;AACnF;AACA,wCAAwC,QAAQ;AAChD;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,mBAAmB,OAAO,GAAG;AAC1E;AACA,YAAY;AACZ,oDAAoD,GAAG;AACvD;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,UAAU;AACV,2CAA2C,GAAG;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uFAAuF,WAAW,MAAM,aAAa,EAAE,uDAAuD,EAAE,uDAAuD,IAAI,iBAAiB,MAAM;AAClQ,yBAAyB;AACzB,uBAAuB;AACvB,sBAAsB;AACtB,8BAA8B;AAC9B,sBAAsB;AACtB,6BAA6B,kBAAkB;AAC/C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,MAAM;AACN;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,SAAS;AACT,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,MAAM;AACN;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,SAAS;AACT,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,6BAA6B;;AAE7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC,IAAI,mBAAmB,QAAQ,GAAG,UAAU;AAC9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+DAA+D,2BAA2B;AAC1F;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA,+CAA+C,QAAQ,qCAAqC,cAAc;AAC1G;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,0DAA0D,SAAS,GAAG,WAAW,QAAQ,QAAQ;AACjG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,SAAS,GAAG,WAAW,QAAQ,QAAQ,YAAY,mBAAmB,GAAG,iBAAiB,GAAG,iCAAiC,sBAAsB,GAAG,yBAAyB,QAAQ,YAAY,yBAAyB;AACzP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,yFAAyF,SAAS,WAAW,YAAY;AACzH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,iCAAiC,IAAI,MAAM,iBAAiB,GAAG,cAAc,UAAU,QAAQ;AAC/F;AACA,wCAAwC;AACxC;AACA;AACA;AACA;AACA,MAAM;AACN,2CAA2C,QAAQ,qDAAqD,SAAS,MAAM,iBAAiB,GAAG,cAAc,UAAU,QAAQ;AAC3K;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0EAA0E;AAC1E,4BAA4B,QAAQ,EAAE,iCAAiC,WAAW,YAAY,8CAA8C,WAAW,iBAAiB,yDAAyD;AACjO;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uEAAuE;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,MAAM;;AAEN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,gBAAgB,0BAA0B,mBAAmB,GAAG,YAAY;AACzH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,gEAAgE,SAAS,+CAA+C,SAAS,WAAW,aAAa;AACzJ;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,8DAA8D;AAC9D;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,6BAA6B;AACnD;AACA;AACA;AACA;AACA,UAAU;AACV,yEAAyE,MAAM;AAC/E;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,+EAA+E,MAAM;AACrF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;;AAEN;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,gCAAgC,OAAO,EAAE,4HAA4H;AACrK;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,wBAAwB;AACvE;AACA;AACA,YAAY;AACZ;AACA;AACA,0DAA0D,4BAA4B,MAAM,aAAa,qBAAqB,YAAY;AAC1I;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,kBAAkB,kBAAkB,wBAAwB,UAAU,aAAa,UAAU,UAAU,UAAU,KAAK;AAC/J;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC,mDAAmD,KAAK,sCAAsC;AACnI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,eAAe,GAAG,yBAAyB,SAAS,aAAa;AAChH;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,+CAA+C,eAAe,GAAG,yBAAyB,SAAS,aAAa,OAAO,MAAM;AAC7H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,kBAAkB,uBAAuB;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,uCAAuC,IAAI,YAAY,SAAS,4BAA4B,iEAAiE;AAC7J;AACA;AACA;AACA;AACA,4BAA4B,IAAI,GAAG,wBAAwB,SAAS,yBAAyB,QAAQ,SAAS,UAAU,gBAAgB,GAAG,cAAc;AACzJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,QAAQ;AACR;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,yCAAyC,oBAAoB,8BAA8B,qDAAqD;AAChJ;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,0FAA0F,8EAA8E,eAAe,mBAAmB;AAC1M;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,2CAA2C,MAAM;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,OAAO,GAAG,WAAW,SAAS,YAAY,QAAQ,eAAe,WAAW,eAAe;AACpI;AACA;AACA,oEAAoE;AACpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,wBAAwB;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,sBAAsB,wBAAwB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,sBAAsB,wBAAwB;AAC9C;AACA;AACA;AACA;AACA;AACA,sBAAsB,wBAAwB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,IAAI,GAAG,gBAAgB,SAAS,iBAAiB,QAAQ,QAAQ,EAAE,oJAAoJ,EAAE,uFAAuF,CAAE,aAAa,EAAE,IAAI;AACzW;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yBAAyB;AACzB,4BAA4B;AAC5B;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B;AAC3B,8BAA8B;AAC9B;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,EAAE;AACF,EAAE;AACF,EAAE,yBAAyB;AAC3B;AACA;AACA;AACA,2IAA2I,KAAK,KAAK,sBAAsB,IAAI,mBAAmB;AAClM;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,+BAA+B,EAAE,4BAA4B,EAAE,8BAA8B;AACvH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,6EAA6E,YAAY,IAAI,SAAS;AACtG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,qCAAqC,EAAE,6CAA6C,EAAE,oBAAoB;AAC3J;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,oCAAoC;AACpC;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,aAAa;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,mIAAmI,gBAAgB,2EAA2E;AAC9O;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6DAA6D,4BAA4B;AACzF,mBAAmB;AACnB,mBAAmB,yFAAyF;AAC5G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6FAA6F,aAAa,KAAK,UAAU;AACzH;AACA;AACA,wFAAwF,+BAA+B,MAAM,4BAA4B,iBAAiB,WAAW,eAAe,YAAY;AAChN,wDAAwD;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,+BAA+B,iDAAiD;AAChF;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,+CAA+C,IAAI;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ,2CAA2C,aAAa;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,mCAAmC,KAAK;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,WAAW,sBAAsB,uBAAuB;AACxF;AACA;AACA;AACA,mDAAmD,oBAAoB,SAAS,WAAW;AAC3F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,SAAS,KAAK,WAAW;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK,IAAI;AACT;AACA;AACA,wBAAwB,WAAW,SAAS,MAAM;AAClD;AACA,4BAA4B,SAAS;AACrC;AACA;AACA;AACA;AACA;AACA,iCAAiC,MAAM,uBAAuB,SAAS;AACvE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,uBAAuB;AACvB,0BAA0B;AAC1B;AACA,sCAAsC,MAAM;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,uBAAuB;AACvB,0BAA0B;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,KAAK;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2EAA2E,WAAW,UAAU,MAAM,QAAQ,GAAG;AACjH;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA,gDAAgD,MAAM;AACtD,OAAO;AACP;AACA,gDAAgD,MAAM;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA,UAAU;AACV;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,8BAA8B,iBAAiB,GAAG,qCAAqC,8BAA8B,KAAK,kBAAkB,2CAA2C;AACvL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yBAAyB,KAAK,WAAW,MAAM,GAAG,IAAI;AACtD;AACA;AACA;AACA;AACA,OAAO;AACP;AACA,iEAAiE,kBAAkB,KAAK,gBAAgB,MAAM,MAAM;AACpH,OAAO;AACP;AACA,kEAAkE,kBAAkB,KAAK,gBAAgB,MAAM,MAAM;AACrH;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA,sCAAsC,MAAM,GAAG,KAAK,QAAQ,KAAK;AACjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,oFAAoF,WAAW,SAAS,YAAY,MAAM,QAAQ;AAClI;AACA;AACA,8CAA8C,MAAM;AACpD;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,MAAM;AAC9B;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA,4FAA4F,uBAAuB;AACnH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;;AAEX;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,YAAY;AACZ,qCAAqC,MAAM;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,qDAAqD,oBAAoB;AACzE;AACA;AACA;AACA;AACA,iDAAiD,qBAAqB,8BAA8B,MAAM,GAAG,IAAI;AACjH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,6CAA6C,mBAAmB,yBAAyB,uBAAuB,IAAI,kBAAkB;AACtI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,OAAO;AACP,wDAAwD,oBAAoB;AAC5E;AACA;AACA,OAAO;AACP,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,iBAAiB,SAAS,MAAM;AAC5D;AACA,0CAA0C,SAAS,GAAG,uCAAuC,EAAE,iBAAiB;AAChH;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,gEAAgE,cAAc;AAC9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,MAAM,8CAA8C,yFAAyF;AAC5K,kBAAkB,MAAM;AACxB;AACA,sDAAsD;AACtD;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;;AAEA,oDAAoD;AACpD;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,iDAAiD,MAAM;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,YAAY,GAAG,UAAU,aAAa,MAAM;AACxE;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEA,oDAAoD;AACpD;AACA;AACA;AACA;AACA,sEAAsE,MAAM;AAC5E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,MAAM;AACzD;AACA,OAAO;AACP,MAAM;AACN;AACA;AACA,QAAQ;AACR,mDAAmD,qBAAqB,EAAE,MAAM;AAChF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;;AAEN,qDAAqD,SAAS;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yEAAyE,aAAa,SAAS;AAC/F;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,wDAAwD;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wDAAwD,SAAS,IAAI,wBAAwB,IAAI,0BAA0B,YAAY,gBAAgB,GAAG,iBAAiB;AAC3K;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,oBAAoB,mBAAmB;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,QAAQ,GAAG,YAAY,OAAO,KAAK;AACnE;AACA,GAAG;AACH;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,oBAAoB;AACjC;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,yCAAyC;AACtD;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C;AAC9C;AACA;AACA;AACA;AACA,sDAAsD,YAAY;AAClE;;AAEA;;AAEA,yCAAyC;;AAEzC;AACA;AACA;AACA;AACA;AACA,iEAAiE;AACjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,kDAAkD;AAC/D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,8DAA8D;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,EAAE,kBAAkB,GAAG;AACtC;AACA,aAAa,EAAE,kBAAkB,GAAG,yBAAyB;AAC7D,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc,+BAA+B,EAAE,8BAA8B;AAC7E,IAAI;AACJ;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,yCAAyC,GAAG,8BAA8B;AACvF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,GAAG,WAAW,mBAAmB;AACjC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC;AACtC;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC;AACzC;AACA;AACA;AACA;AACA;AACA,yJAAyJ;AACzJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,IAAI;AACP;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC;AACvC;AACA;AACA;AACA;AACA,YAAY,WAAW,GAAG,2BAA2B;AACrD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,IAAI,EAAE,UAAU,EAAE,MAAM;AACpC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,0BAA0B;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,OAAO,IAAI;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,QAAQ;AACR,wCAAwC,QAAQ;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,cAAc,IAAI,mBAAmB,wCAAwC,cAAc,UAAU,iCAAiC,cAAc,4BAA4B,aAAa,kCAAkC;AACtQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,eAAe,gCAAgC,UAAU;AACtG;AACA;AACA;AACA;AACA,wBAAwB,qBAAqB,GAAG,eAAe,qBAAqB,eAAe;AACnG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,oBAAoB,4BAA4B;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,UAAU;AAClD;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,8DAA8D,uBAAuB,KAAK,yBAAyB;AACnH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,mBAAmB;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,iBAAiB,SAAS,QAAQ;AAC5F,iEAAiE,qBAAqB,SAAS,QAAQ;AACvG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,0BAA0B,kCAAkC;AAC5D,+CAA+C,yBAAyB,SAAS,QAAQ;AACzF;AACA;AACA;AACA,0BAA0B,qCAAqC;AAC/D,8CAA8C,4BAA4B,SAAS,QAAQ;AAC3F;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,yDAAyD,IAAI;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,IAAI;AACnD;AACA;AACA,uCAAuC,sBAAsB;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,YAAY;AACZ;AACA,sEAAsE,UAAU;AAChF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA,qDAAqD,YAAY,EAAE,YAAY,GAAG,YAAY;AAC9F;AACA;AACA;AACA,wCAAwC,aAAa;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,aAAa;AACrD;AACA;AACA;AACA,OAAO;AACP;AACA,uDAAuD,YAAY;AACnE;AACA;AACA;AACA,8CAA8C,IAAI;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC;AACrC;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,6BAA6B,WAAW,4BAA4B,aAAa;AACjF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,WAAW,gCAAgC,aAAa,4BAA4B,UAAU;AAC5I;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ,yBAAyB,YAAY,wBAAwB,MAAM;AACnE;AACA;AACA,UAAU;AACV;AACA,8CAA8C,WAAW,gCAAgC,aAAa,4BAA4B,UAAU;AAC5I;AACA;AACA;AACA;AACA;AACA;AACA,yBAAyB,YAAY,iBAAiB,kBAAkB,qCAAqC,UAAU;AACvH;AACA;AACA;AACA;AACA,2BAA2B,YAAY;AACvC,cAAc;AACd,mCAAmC,YAAY,MAAM,gFAAgF;AACrI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,wBAAwB,6BAA6B;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC,WAAW,eAAe,iBAAiB,oCAAoC,UAAU;AAC3H;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA,aAAa;AACb,WAAW;AACX;AACA;AACA,OAAO;AACP;AACA;AACA,mBAAmB,WAAW;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0EAA0E,UAAU;AACpF;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN,8DAA8D,UAAU;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,YAAY;AACZ;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,SAAS;AACT;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,mFAAmF,gCAAgC;AACnH;AACA,sGAAsG,kBAAkB;AACxH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,UAAU,mCAAmC,iCAAiC;AAC5H;AACA;AACA;AACA;AACA;AACA,2DAA2D,UAAU,KAAK,MAAM;AAChF,OAAO;AACP;AACA,2CAA2C,+BAA+B;AAC1E;AACA,2CAA2C,UAAU;AACrD;AACA,8CAA8C,UAAU;AACxD;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA,yDAAyD,UAAU,EAAE,IAAI,MAAM;AAC/E,SAAS;AACT;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH,6CAA6C,UAAU,WAAW,qCAAqC;AACvG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,qBAAqB,cAAc;AACzE,QAAQ,gBAAgB,8BAA8B;AACtD;AACA;AACA;AACA,uDAAuD;AACvD;AACA,0DAA0D,SAAS,EAAE,UAAU,IAAI,WAAW,gBAAgB,sBAAsB;AACpI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,UAAU;AACV,oEAAoE,UAAU;AAC9E;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA,kCAAkC,OAAO,WAAW,sBAAsB,YAAY,oBAAoB,OAAO,gBAAgB;AACjI,yCAAyC,WAAW;AACpD;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA,+CAA+C,cAAc,EAAE,eAAe,IAAI,iBAAiB,YAAY,WAAW;AAC1H;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT,OAAO;AACP;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,sDAAsD;AAC7D;AACA,OAAO,EAAE;AACT;AACA;AACA;AACA;AACA;AACA,wCAAwC,UAAU;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,sCAAsC,UAAU;AAChD;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD,OAAO;AAC3D;AACA;AACA;AACA,oDAAoD,OAAO,KAAK,OAAO,mBAAmB,cAAc,UAAU,sCAAsC;AACxJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,mBAAmB,YAAY,+BAA+B,qBAAqB,kBAAkB,mBAAmB;AACxH;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA,SAAS;AACT,QAAQ;AACR;AACA;AACA;AACA;AACA,QAAQ;AACR,uDAAuD,YAAY;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,mBAAmB,kBAAkB,MAAM;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,WAAW;AACX,UAAU;AACV;AACA;AACA;AACA;AACA,WAAW,4BAA4B,UAAU;AACjD,UAAU;AACV;AACA,UAAU;AACV,oDAAoD,UAAU;AAC9D;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA,qDAAqD,sGAAsG,WAAW,MAAM;AAC5K,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,OAAO,2CAA2C,MAAM;AACxD,KAAK;AACL;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC,OAAO,2BAA2B,2HAA2H,iBAAiB,6EAA6E,OAAO,uCAAuC;AAC9U;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,UAAU;AAC3D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,WAAW,MAAM,UAAU,gCAAgC,IAAI,aAAa,eAAe,GAAG,cAAc;AAC5G,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,MAAM,UAAU,mCAAmC,IAAI;AAClE,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,yCAAyC,8CAA8C,GAAG,wCAAwC,QAAQ,UAAU;AACpJ;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sDAAsD;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,SAAS;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,kDAAkD,IAAI;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,qDAAqD;AAC9F;AACA;AACA;AACA;AACA,gBAAgB;AAChB;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,iCAAiC,IAAI,aAAa,YAAY,GAAG,eAAe;AAC/F,cAAc;AACd;AACA,qDAAqD,cAAc;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,8CAA8C,MAAM;AACpD;AACA;AACA;AACA;AACA,wDAAwD,MAAM;AAC9D,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,iEAAiE,MAAM;AACvE;AACA;AACA;AACA;AACA,2EAA2E,MAAM;AACjF,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,yDAAyD,sBAAsB;AAC/E;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,6DAA6D,2BAA2B;AACxF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,8CAA8C,MAAM;AACpD;AACA;AACA;AACA;AACA,wDAAwD,MAAM;AAC9D,SAAS;AACT,OAAO;AACP;AACA,OAAO;AACP;AACA,6CAA6C,MAAM;AACnD;AACA;AACA;AACA;AACA,uDAAuD,MAAM;AAC7D,SAAS;AACT,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,IAAI;AACrD;AACA,MAAM;AACN,yCAAyC,IAAI;AAC7C;AACA;AACA;AACA;AACA,QAAQ;AACR,gFAAgF,KAAK;AACrF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,IAAI;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,iBAAiB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qDAAqD,SAAS;AAC9D;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,0BAA0B;AAC5C;AACA,0CAA0C;AAC1C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,mBAAmB;AACzC;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,0CAA0C,IAAI,YAAY,SAAS,4BAA4B,iEAAiE;AAChK;AACA;AACA;AACA;AACA,+BAA+B,IAAI,GAAG,wBAAwB,SAAS,yBAAyB,QAAQ,SAAS,UAAU,gBAAgB,GAAG,cAAc;AAC5J;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,QAAQ;AACR;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4CAA4C,uBAAuB,qBAAqB,2DAA2D;AACnJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,mBAAmB;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,mBAAmB;AACzC;AACA;AACA;AACA;AACA;AACA,sBAAsB,mBAAmB;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,mBAAmB;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,IAAI,GAAG,kBAAkB,SAAS,mBAAmB,QAAQ,QAAQ,EAAE,oJAAoJ,EAAE,uFAAuF,CAAE,aAAa,EAAE,IAAI;AAC1W;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kEAAkE,kBAAkB,kBAAkB,kBAAkB;AACxH;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,8CAA8C,MAAM;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,MAAM,kBAAkB,WAAW,SAAS,YAAY,QAAQ,cAAc;AAC1H;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,CAAC,GAAG;AACJ;AACA,YAAY,wBAAwB,GAAG,mBAAmB,GAAG,UAAU;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc,wBAAwB,IAAI,uEAAuE,EAAE,sCAAsC,GAAG,mCAAmC;AAC/L;AACA;AACA;AACA;AACA,cAAc,iBAAiB,IAAI,iBAAiB,GAAG,8BAA8B;AACrF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,oCAAoC,EAAE,iEAAiE,EAAE,8GAA8G;AACrP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,kBAAkB;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,eAAe;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,IAAI;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,YAAY;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,gBAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,WAAW;AACX,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,WAAW;AACX,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6EAA6E,aAAa;AAC1F;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,mBAAmB,wBAAwB,eAAe,YAAY,0CAA0C,iBAAiB;AACjI;AACA;AACA;AACA,mBAAmB,wBAAwB,eAAe,YAAY;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,wBAAwB,eAAe,YAAY,OAAO,cAAc,eAAe,YAAY;AACxH;AACA;AACA;AACA;AACA;AACA,qBAAqB,wBAAwB,eAAe,YAAY,uCAAuC,cAAc,YAAY,kBAAkB,GAAG,oBAAoB;AAClL;AACA;AACA;AACA;AACA;AACA,qBAAqB,wBAAwB,eAAe,YAAY,mBAAmB,cAAc,mBAAmB,oBAAoB,GAAG,mBAAmB,MAAM,kBAAkB,MAAM,iBAAiB;AACrN;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,iEAAiE,IAAI,yBAAyB,GAAG,uBAAuB;AACrI;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA,2JAA2J,YAAY,EAAE,YAAY,GAAG,YAAY;AACpM;AACA,OAAO;AACP;AACA,mJAAmJ,YAAY;AAC/J;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D;AAC5D;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,0BAA0B,KAAK;AAC1E,YAAY,+CAA+C;AAC3D;AACA;AACA,mCAAmC,WAAW;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA,6BAA6B,GAAG,IAAI,eAAe,IAAI,sBAAsB,IAAI,cAAc;AAC/F;AACA;AACA;AACA;AACA,OAAO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,qCAAqC,6BAA6B;AAClE;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yBAAyB,MAAM,GAAG,aAAa;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA,+CAA+C,IAAI;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,SAAS;AACT;AACA;AACA,SAAS;AACT;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,SAAS;AACT;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA,WAAW;AACX;AACA;AACA,WAAW;AACX;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,WAAW;AACX;AACA;AACA,WAAW;AACX;AACA;AACA,WAAW;AACX;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,QAAQ,EAAE,iCAAiC;AACvF;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,2BAA2B,gBAAgB;AAC3C,QAAQ;AACR;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,oDAAoD,iCAAiC;AACrF,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gFAAgF,aAAa;AAC7F;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,8DAA8D,KAAK,oCAAoC,OAAO,cAAc;AAC5I;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,MAAM,IAAI,eAAe;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,oBAAoB,GAAG,+BAA+B,EAAE,iCAAiC;AACtI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,cAAc,EAAE,6BAA6B;AACpF;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,gCAAgC,EAAE,oDAAoD;AAC/H;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,+DAA+D,aAAa;AAC5E;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kEAAkE,aAAa;AAC/E;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,mBAAmB,GAAG,iBAAiB,mBAAmB,aAAa;AAClG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yBAAyB,+BAA+B;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,+BAA+B;AACvD;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6DAA6D,+CAA+C;AAC5G;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,wBAAwB;AAClF;AACA,OAAO;AACP;AACA;AACA,6DAA6D,wBAAwB;AACrF;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,wBAAwB;AAClF;AACA,OAAO;AACP;AACA;AACA,6DAA6D,wBAAwB;AACrF;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,+BAA+B;AACrD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,sBAAsB,0BAA0B,0BAA0B;AACnH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,mBAAmB,GAAG,2BAA2B,EAAE,aAAa,EAAE,iCAAiC,mBAAmB,gBAAgB,eAAe,OAAO;AACtM;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,mCAAmC,qBAAqB;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kDAAkD,YAAY;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;;AAEA;AACA;AACA;AACA,oBAAoB,wBAAwB;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,sBAAsB,wBAAwB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,8BAA8B;AACxE;AACA;AACA;AACA;AACA;AACA,mCAAmC;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,iBAAiB;AAC1E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC;AACrC;AACA,OAAO;AACP;AACA;AACA,mDAAmD,cAAc,YAAY,QAAQ;AACrF;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oEAAoE,aAAa;AACjF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,QAAQ,oBAAoB,sBAAsB,IAAI,SAAS;AACvG;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,aAAa;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2DAA2D,SAAS,EAAE,cAAc,KAAK,+BAA+B;AACxH;AACA,YAAY;AACZ,oCAAoC,kBAAkB,KAAK,oCAAoC,WAAW,SAAS,EAAE,aAAa;AAClI;AACA;AACA;AACA;AACA;AACA;AACA,iJAAiJ,YAAY,EAAE,aAAa;AAC5K,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,qEAAqE,QAAQ;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,eAAe,mDAAmD;AAC9G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6CAA6C,mBAAmB,GAAG,iBAAiB,EAAE,OAAO;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,QAAQ,0BAA0B,2BAA2B,sDAAsD,0BAA0B;AACvL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,mCAAmC,WAAW;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kDAAkD,wBAAwB,WAAW,YAAY,OAAO,kBAAkB,WAAW,uDAAuD,SAAS,mBAAmB;AACxN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,iDAAiD,aAAa,QAAQ,iBAAiB,IAAI,aAAa;AACxG;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2FAA2F,kBAAkB,EAAE,aAAa;AAC5H;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,6BAA6B;;AAE7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oBAAoB,qBAAqB;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,oBAAoB;AAC5C;AACA;AACA;AACA,YAAY;AACZ;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN;AACA,kEAAkE,QAAQ;AAC1E;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,SAAS,UAAU,mBAAmB,GAAG,iBAAiB,GAAG,iCAAiC,sBAAsB,GAAG,yBAAyB,QAAQ,YAAY,yBAAyB;AAC5N;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT,OAAO;AACP,qBAAqB,SAAS,IAAI,YAAY;AAC9C;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qDAAqD,KAAK,yCAAyC,MAAM,uCAAuC,OAAO;AACvJ;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iEAAiE;AACjE,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,WAAW,GAAG,SAAS,IAAI,EAAE;AACjD;AACA;AACA;AACA;AACA;AACA,kBAAkB,qBAAqB;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,oBAAoB;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,aAAa;AACjC;AACA;AACA;AACA;AACA;AACA,oBAAoB,aAAa;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,aAAa;AACjC;AACA;AACA;AACA;AACA;AACA,oBAAoB,aAAa;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,gBAAgB;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,aAAa;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,aAAa;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,aAAa;AACjC;AACA;AACA;AACA;AACA;AACA,oBAAoB,aAAa;AACjC;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,aAAa;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,aAAa;AACjC;AACA;AACA;AACA;AACA;AACA,oBAAoB,aAAa;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,sBAAsB,aAAa;AACnC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,uBAAuB;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,aAAa;AACjC;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,kBAAkB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,oBAAoB,qBAAqB;AACzC;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA;AACA,oBAAoB;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oBAAoB,uCAAuC;AAC3D;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oBAAoB,0BAA0B;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,sBAAsB;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C;AAC9C;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,KAAK;AACL,uDAAuD;AACvD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,KAAK;AACL,qDAAqD;AACrD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,mDAAmD;AACnD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,gDAAgD;AAChD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA,kDAAkD;AAClD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,KAAK;AACL,oDAAoD;AACpD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,uDAAuD;AACvD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,KAAK;AACL,gDAAgD;AAChD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,qDAAqD;AACrD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,oDAAoD;AACpD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,yDAAyD;AACzD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,gDAAgD;AAChD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,iDAAiD;AACjD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,yCAAyC,EAAE,MAAM,EAAE;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kDAAkD;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,cAAc;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,IAAI;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,QAAQ;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,sCAAsC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC;;AAEpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD,WAAW;AAC/D;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B;AAC1B;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;;AAEA;AACA,yBAAyB,GAAG,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE;;AAEpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,IAAI;AAC7C;AACA,GAAG,IAAI;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,IAAI;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG,IAAI;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qDAAqD,KAAK;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC,IAAI;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA,6CAA6C;AAC7C;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,sBAAsB,6BAA6B;AACnD;AACA;AACA;AACA;AACA,iFAAiF;AACjF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,sBAAsB,uBAAuB;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,wBAAwB;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,mFAAmF,4BAA4B;AAC/G;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,mBAAmB;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL,+CAA+C,MAAM;AACrD;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,iDAAiD,MAAM;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,oBAAoB,oBAAoB;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,WAAW;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,+BAA+B;AACnD;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,gCAAgC,GAAG;AACnC;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,OAAO;AACP,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,0BAA0B,QAAQ,gBAAgB,YAAY;AAC9D;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,2CAA2C,oEAAoE;AAC/G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,mBAAmB,8CAA8C,gBAAgB,uCAAuC,aAAa,YAAY,GAAG,yBAAyB,KAAK,gBAAgB;AAClM;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,KAAK;AAC3C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB;AAChB;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC,uBAAuB;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,0BAA0B,qCAAqC;AAC/D;AACA;AACA;AACA,mCAAmC,KAAK,SAAS,QAAQ;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,qCAAqC,oBAAoB,oCAAoC,WAAW,KAAK,kCAAkC;AAC/I;AACA,GAAG;AACH,yCAAyC;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK,IAAI;AACT;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gDAAgD,YAAY,UAAU,4BAA4B;AAClG;AACA;AACA,kDAAkD;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yGAAyG,aAAa,QAAQ,WAAW,KAAK,SAAS,kBAAkB,cAAc;AACvL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,uDAAuD,mBAAmB,qBAAqB,sBAAsB;AACrH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+DAA+D,aAAa,KAAK,WAAW;AAC5F;AACA;AACA;AACA,qFAAqF,aAAa,KAAK,WAAW;AAClH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,aAAa,KAAK,WAAW;AACzF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,MAAM;AACN,uFAAuF,aAAa,QAAQ,sBAAsB;AAClI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA,CAAC;AACD;AACA,qEAAqE,EAAE;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,uBAAuB;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,MAAM;;AAEN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,oBAAoB;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,mBAAmB;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,IAAI;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,IAAI;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,WAAW;AACX;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,gBAAgB;AACpC;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,sBAAsB,uBAAuB;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wGAAwG,wBAAwB,kBAAkB,6FAA6F,wBAAwB,oCAAoC,iCAAiC,oBAAoB,KAAK,aAAa;AAClX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,mDAAmD,IAAI;AACvD;AACA;AACA,kEAAkE,WAAW,GAAG,aAAa;AAC7F;AACA;AACA,YAAY;AACZ,kEAAkE,WAAW,GAAG,aAAa;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sDAAsD,kBAAkB;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,uCAAuC,eAAe;AACtD,0BAA0B,sBAAsB,EAAE,oBAAoB,GAAG,WAAW,GAAG,UAAU,GAAG,OAAO,GAAG,YAAY,GAAG,KAAK;AAClI;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,oEAAoE,wBAAwB;AAC5F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qEAAqE,wHAAwH;AAC7L;AACA,4BAA4B,OAAO;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,wBAAwB,2BAA2B;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,oBAAoB,mBAAmB;AACvC;AACA;AACA;AACA;AACA;AACA,qCAAqC,eAAe,iCAAiC,kBAAkB;AACvG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC,UAAU,GAAG,wCAAwC,EAAE,+CAA+C,EAAE,2CAA2C,GAAG,cAAc,GAAG,+CAA+C,aAAa,eAAe,EAAE,sDAAsD;AAC7U;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA,qCAAqC,iBAAiB,iDAAiD,aAAa;AACpH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,iBAAiB;AACpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,uCAAuC,MAAM;AAC7C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,kBAAkB,EAAE,oJAAoJ,EAAE,yCAAyC,EAAE,uFAAuF,CAAE,aAAa,EAAE,IAAI;AACrW;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,2BAA2B;;AAE3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC,uBAAuB;;AAEzD;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,aAAa,oBAAoB,sCAAsC;AAC1H;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iEAAiE,2BAA2B;AAC5F;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;;AAEN;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,oCAAoC,OAAO,aAAa,WAAW;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,6BAA6B,SAAS,WAAW,YAAY;AAC7D;AACA,QAAQ;AACR;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,uDAAuD;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,yDAAyD,WAAW;AACpE;AACA;AACA,sBAAsB,YAAY,UAAU,mBAAmB,GAAG,iBAAiB,GAAG,iCAAiC,sBAAsB,GAAG,yBAAyB,QAAQ,QAAQ,mBAAmB,IAAI,iBAAiB,aAAa,SAAS;AACvP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,wBAAwB,4DAA4D,IAAI,2BAA2B,4BAA4B;AAChL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA,mFAAmF,SAAS,WAAW,YAAY;AACnH;AACA;AACA;AACA;AACA,yBAAyB,YAAY;AACrC;AACA;AACA;AACA;AACA,qCAAqC,SAAS,WAAW,YAAY;AACrE;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,+BAA+B,SAAS,MAAM,iBAAiB,GAAG,cAAc,UAAU,WAAW,OAAO,QAAQ;AACpH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,6CAA6C,KAAK;AAClD;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,8BAA8B,QAAQ,EAAE,iCAAiC,WAAW,YAAY,8CAA8C,WAAW;AACzJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,cAAc,uBAAuB,YAAY;AACvF;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gDAAgD,OAAO;AACvD;AACA;AACA;AACA;AACA,kDAAkD,eAAe,oBAAoB,aAAa,eAAe,YAAY;AAC7H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB,0CAA0C,2DAA2D,SAAS;AAC/H;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kDAAkD,WAAW;AAC7D;AACA;AACA,mDAAmD,wBAAwB,SAAS,WAAW;AAC/F;AACA;AACA;AACA,+CAA+C,gBAAgB,mCAAmC,iBAAiB,GAAG,8BAA8B,GAAG,YAAY;AACnK;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,gBAAgB,0BAA0B,8BAA8B,GAAG,iBAAiB,GAAG,2EAA2E,EAAE,gEAAgE;AAC3R;AACA;AACA;AACA,oDAAoD,qBAAqB,0BAA0B,oBAAoB,GAAG,iBAAiB;AAC3I;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR,sBAAsB,+BAA+B;AACrD;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gHAAgH,gBAAgB;AAChI;AACA;AACA;AACA;AACA,sHAAsH,IAAI;AAC1H;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6IAA6I,mBAAmB;AAChK;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA,oGAAoG,eAAe,cAAc,cAAc;AAC/I;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,mEAAmE,aAAa,WAAW,cAAc,QAAQ,WAAW;;AAE5H;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kDAAkD,aAAa;AAC/D,UAAU;AACV,kDAAkD,aAAa,cAAc,kBAAkB;AAC/F;AACA;AACA;AACA,0EAA0E,aAAa;AACvF;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,8BAA8B;AAC9B;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC;AAClC;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA,OAAO;AACP;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;;AAEA,oFAAoF,YAAY;;AAEhG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA,MAAM;AACN;AACA,6BAA6B,kCAAkC,0CAA0C,cAAc;AACvH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,+BAA+B,qFAAqF,yBAAyB,aAAa;AAC1J;AACA,sBAAsB,eAAe,MAAM,WAAW;AACtD,MAAM;AACN,yBAAyB,YAAY,aAAa,gBAAgB;AAClE;AACA;AACA,+CAA+C,QAAQ;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,uEAAuE,KAAK;AAC5E;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,2CAA2C;AAC3C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,kCAAkC,cAAc;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC,0EAA0E;AAC3G;AACA;AACA,oBAAoB,oCAAoC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,oCAAoC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,wCAAwC,SAAS;AACjD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC,SAAS;AAC9C;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC,SAAS;AAC9C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,sCAAsC,SAAS;AAC/C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,SAAS;AAC/C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gDAAgD;AAChD,QAAQ;AACR;AACA;AACA,iDAAiD;AACjD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,8CAA8C,SAAS;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,oBAAoB,SAAS;AAC7B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,iCAAiC,IAAI;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEmuB;AACnuB","sources":["webpack://_wix_video/../../../node_modules/hls.js/dist/hls.mjs"],"sourcesContent":["// https://caniuse.com/mdn-javascript_builtins_number_isfinite\nconst isFiniteNumber = Number.isFinite || function (value) {\n return typeof value === 'number' && isFinite(value);\n};\n\n// https://caniuse.com/mdn-javascript_builtins_number_issafeinteger\nconst isSafeInteger = Number.isSafeInteger || function (value) {\n return typeof value === 'number' && Math.abs(value) <= MAX_SAFE_INTEGER;\n};\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;\n\nlet ErrorTypes = /*#__PURE__*/function (ErrorTypes) {\n // Identifier for a network error (loading error / timeout ...)\n ErrorTypes[\"NETWORK_ERROR\"] = \"networkError\";\n // Identifier for a media Error (video/parsing/mediasource error)\n ErrorTypes[\"MEDIA_ERROR\"] = \"mediaError\";\n // EME (encrypted media extensions) errors\n ErrorTypes[\"KEY_SYSTEM_ERROR\"] = \"keySystemError\";\n // Identifier for a mux Error (demuxing/remuxing)\n ErrorTypes[\"MUX_ERROR\"] = \"muxError\";\n // Identifier for all other errors\n ErrorTypes[\"OTHER_ERROR\"] = \"otherError\";\n return ErrorTypes;\n}({});\nlet ErrorDetails = /*#__PURE__*/function (ErrorDetails) {\n ErrorDetails[\"KEY_SYSTEM_NO_KEYS\"] = \"keySystemNoKeys\";\n ErrorDetails[\"KEY_SYSTEM_NO_ACCESS\"] = \"keySystemNoAccess\";\n ErrorDetails[\"KEY_SYSTEM_NO_SESSION\"] = \"keySystemNoSession\";\n ErrorDetails[\"KEY_SYSTEM_NO_CONFIGURED_LICENSE\"] = \"keySystemNoConfiguredLicense\";\n ErrorDetails[\"KEY_SYSTEM_LICENSE_REQUEST_FAILED\"] = \"keySystemLicenseRequestFailed\";\n ErrorDetails[\"KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED\"] = \"keySystemServerCertificateRequestFailed\";\n ErrorDetails[\"KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED\"] = \"keySystemServerCertificateUpdateFailed\";\n ErrorDetails[\"KEY_SYSTEM_SESSION_UPDATE_FAILED\"] = \"keySystemSessionUpdateFailed\";\n ErrorDetails[\"KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED\"] = \"keySystemStatusOutputRestricted\";\n ErrorDetails[\"KEY_SYSTEM_STATUS_INTERNAL_ERROR\"] = \"keySystemStatusInternalError\";\n ErrorDetails[\"KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR\"] = \"keySystemDestroyMediaKeysError\";\n ErrorDetails[\"KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR\"] = \"keySystemDestroyCloseSessionError\";\n ErrorDetails[\"KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR\"] = \"keySystemDestroyRemoveSessionError\";\n // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n ErrorDetails[\"MANIFEST_LOAD_ERROR\"] = \"manifestLoadError\";\n // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n ErrorDetails[\"MANIFEST_LOAD_TIMEOUT\"] = \"manifestLoadTimeOut\";\n // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}\n ErrorDetails[\"MANIFEST_PARSING_ERROR\"] = \"manifestParsingError\";\n // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}\n ErrorDetails[\"MANIFEST_INCOMPATIBLE_CODECS_ERROR\"] = \"manifestIncompatibleCodecsError\";\n // Identifier for a level which contains no fragments - data: { url: faulty URL, reason: \"no fragments found in level\", level: index of the bad level }\n ErrorDetails[\"LEVEL_EMPTY_ERROR\"] = \"levelEmptyError\";\n // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n ErrorDetails[\"LEVEL_LOAD_ERROR\"] = \"levelLoadError\";\n // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n ErrorDetails[\"LEVEL_LOAD_TIMEOUT\"] = \"levelLoadTimeOut\";\n // Identifier for a level parse error - data: { url : faulty URL, error: Error, reason: error message }\n ErrorDetails[\"LEVEL_PARSING_ERROR\"] = \"levelParsingError\";\n // Identifier for a level switch error - data: { level : faulty level Id, event : error description}\n ErrorDetails[\"LEVEL_SWITCH_ERROR\"] = \"levelSwitchError\";\n // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n ErrorDetails[\"AUDIO_TRACK_LOAD_ERROR\"] = \"audioTrackLoadError\";\n // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n ErrorDetails[\"AUDIO_TRACK_LOAD_TIMEOUT\"] = \"audioTrackLoadTimeOut\";\n // Identifier for a subtitle track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n ErrorDetails[\"SUBTITLE_LOAD_ERROR\"] = \"subtitleTrackLoadError\";\n // Identifier for a subtitle track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n ErrorDetails[\"SUBTITLE_TRACK_LOAD_TIMEOUT\"] = \"subtitleTrackLoadTimeOut\";\n // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n ErrorDetails[\"FRAG_LOAD_ERROR\"] = \"fragLoadError\";\n // Identifier for fragment load timeout error - data: { frag : fragment object}\n ErrorDetails[\"FRAG_LOAD_TIMEOUT\"] = \"fragLoadTimeOut\";\n // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }\n ErrorDetails[\"FRAG_DECRYPT_ERROR\"] = \"fragDecryptError\";\n // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }\n // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release\n ErrorDetails[\"FRAG_PARSING_ERROR\"] = \"fragParsingError\";\n // Identifier for a fragment or part load skipped because of a GAP tag or attribute\n ErrorDetails[\"FRAG_GAP\"] = \"fragGap\";\n // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }\n ErrorDetails[\"REMUX_ALLOC_ERROR\"] = \"remuxAllocError\";\n // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n ErrorDetails[\"KEY_LOAD_ERROR\"] = \"keyLoadError\";\n // Identifier for decrypt key load timeout error - data: { frag : fragment object}\n ErrorDetails[\"KEY_LOAD_TIMEOUT\"] = \"keyLoadTimeOut\";\n // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { error : exception , mimeType : mimeType }\n ErrorDetails[\"BUFFER_ADD_CODEC_ERROR\"] = \"bufferAddCodecError\";\n // Triggered when source buffer(s) could not be created using level (manifest CODECS attribute), parsed media, or best guess codec(s) - data: { reason : error reason }\n ErrorDetails[\"BUFFER_INCOMPATIBLE_CODECS_ERROR\"] = \"bufferIncompatibleCodecsError\";\n // Identifier for a buffer append error - data: append error description\n ErrorDetails[\"BUFFER_APPEND_ERROR\"] = \"bufferAppendError\";\n // Identifier for a buffer appending error event - data: appending error description\n ErrorDetails[\"BUFFER_APPENDING_ERROR\"] = \"bufferAppendingError\";\n // Identifier for a buffer stalled error event\n ErrorDetails[\"BUFFER_STALLED_ERROR\"] = \"bufferStalledError\";\n // Identifier for a buffer full event\n ErrorDetails[\"BUFFER_FULL_ERROR\"] = \"bufferFullError\";\n // Identifier for a buffer seek over hole event\n ErrorDetails[\"BUFFER_SEEK_OVER_HOLE\"] = \"bufferSeekOverHole\";\n // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)\n ErrorDetails[\"BUFFER_NUDGE_ON_STALL\"] = \"bufferNudgeOnStall\";\n // Identifier for a Interstitial Asset List load error - data: { url: faulty URL, response: { code: error code, text: error text } }\n ErrorDetails[\"ASSET_LIST_LOAD_ERROR\"] = \"assetListLoadError\";\n // Identifier for a Interstitial Asset List load timeout - data: { url: faulty URL, response: { code: error code, text: error text } }\n ErrorDetails[\"ASSET_LIST_LOAD_TIMEOUT\"] = \"assetListLoadTimeout\";\n // Identifier for a Interstitial Asset List parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}\n ErrorDetails[\"ASSET_LIST_PARSING_ERROR\"] = \"assetListParsingError\";\n // Identifier for a Interstitial Asset List parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}\n ErrorDetails[\"INTERSTITIAL_ASSET_ITEM_ERROR\"] = \"interstitialAssetItemError\";\n // Identifier for an internal exception happening inside hls.js while handling an event\n ErrorDetails[\"INTERNAL_EXCEPTION\"] = \"internalException\";\n // Identifier for an internal call to abort a loader\n ErrorDetails[\"INTERNAL_ABORTED\"] = \"aborted\";\n // Triggered when attachMedia fails\n ErrorDetails[\"ATTACH_MEDIA_ERROR\"] = \"attachMediaError\";\n // Uncategorized error\n ErrorDetails[\"UNKNOWN\"] = \"unknown\";\n return ErrorDetails;\n}({});\n\nlet Events = /*#__PURE__*/function (Events) {\n // Fired before MediaSource is attaching to media element\n Events[\"MEDIA_ATTACHING\"] = \"hlsMediaAttaching\";\n // Fired when MediaSource has been successfully attached to media element\n Events[\"MEDIA_ATTACHED\"] = \"hlsMediaAttached\";\n // Fired before detaching MediaSource from media element\n Events[\"MEDIA_DETACHING\"] = \"hlsMediaDetaching\";\n // Fired when MediaSource has been detached from media element\n Events[\"MEDIA_DETACHED\"] = \"hlsMediaDetached\";\n // Fired when HTMLMediaElement dispatches \"ended\" event, or stalls at end of VOD program\n Events[\"MEDIA_ENDED\"] = \"hlsMediaEnded\";\n // Fired after playback stall is resolved with playing, seeked, or ended event following BUFFER_STALLED_ERROR\n Events[\"STALL_RESOLVED\"] = \"hlsStallResolved\";\n // Fired when the buffer is going to be reset\n Events[\"BUFFER_RESET\"] = \"hlsBufferReset\";\n // Fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}\n Events[\"BUFFER_CODECS\"] = \"hlsBufferCodecs\";\n // fired when sourcebuffers have been created - data: { tracks : tracks }\n Events[\"BUFFER_CREATED\"] = \"hlsBufferCreated\";\n // fired when we append a segment to the buffer - data: { segment: segment object }\n Events[\"BUFFER_APPENDING\"] = \"hlsBufferAppending\";\n // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}\n Events[\"BUFFER_APPENDED\"] = \"hlsBufferAppended\";\n // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }\n Events[\"BUFFER_EOS\"] = \"hlsBufferEos\";\n // fired when all buffers are full to the end of the program, after calling MediaSource.endOfStream() (unless restricted)\n Events[\"BUFFERED_TO_END\"] = \"hlsBufferedToEnd\";\n // fired when the media buffer should be flushed - data { startOffset, endOffset }\n Events[\"BUFFER_FLUSHING\"] = \"hlsBufferFlushing\";\n // fired when the media buffer has been flushed - data: { }\n Events[\"BUFFER_FLUSHED\"] = \"hlsBufferFlushed\";\n // fired to signal that a manifest loading starts - data: { url : manifestURL}\n Events[\"MANIFEST_LOADING\"] = \"hlsManifestLoading\";\n // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks ], url : manifestURL, stats : LoaderStats }\n Events[\"MANIFEST_LOADED\"] = \"hlsManifestLoaded\";\n // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}\n Events[\"MANIFEST_PARSED\"] = \"hlsManifestParsed\";\n // fired when a level switch is requested - data: { level : id of new level }\n Events[\"LEVEL_SWITCHING\"] = \"hlsLevelSwitching\";\n // fired when a level switch is effective - data: { level : id of new level }\n Events[\"LEVEL_SWITCHED\"] = \"hlsLevelSwitched\";\n // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}\n Events[\"LEVEL_LOADING\"] = \"hlsLevelLoading\";\n // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : LoaderStats }\n Events[\"LEVEL_LOADED\"] = \"hlsLevelLoaded\";\n // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }\n Events[\"LEVEL_UPDATED\"] = \"hlsLevelUpdated\";\n // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }\n Events[\"LEVEL_PTS_UPDATED\"] = \"hlsLevelPtsUpdated\";\n // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }\n Events[\"LEVELS_UPDATED\"] = \"hlsLevelsUpdated\";\n // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }\n Events[\"AUDIO_TRACKS_UPDATED\"] = \"hlsAudioTracksUpdated\";\n // fired when an audio track switching is requested - data: { id : audio track id }\n Events[\"AUDIO_TRACK_SWITCHING\"] = \"hlsAudioTrackSwitching\";\n // fired when an audio track switch actually occurs - data: { id : audio track id }\n Events[\"AUDIO_TRACK_SWITCHED\"] = \"hlsAudioTrackSwitched\";\n // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }\n Events[\"AUDIO_TRACK_LOADING\"] = \"hlsAudioTrackLoading\";\n // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : LoaderStats }\n Events[\"AUDIO_TRACK_LOADED\"] = \"hlsAudioTrackLoaded\";\n // fired when an audio tracks's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, id : track id }\n Events[\"AUDIO_TRACK_UPDATED\"] = \"hlsAudioTrackUpdated\";\n // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n Events[\"SUBTITLE_TRACKS_UPDATED\"] = \"hlsSubtitleTracksUpdated\";\n // fired to notify that subtitle tracks were cleared as a result of stopping the media\n Events[\"SUBTITLE_TRACKS_CLEARED\"] = \"hlsSubtitleTracksCleared\";\n // fired when an subtitle track switch occurs - data: { id : subtitle track id }\n Events[\"SUBTITLE_TRACK_SWITCH\"] = \"hlsSubtitleTrackSwitch\";\n // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }\n Events[\"SUBTITLE_TRACK_LOADING\"] = \"hlsSubtitleTrackLoading\";\n // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : LoaderStats }\n Events[\"SUBTITLE_TRACK_LOADED\"] = \"hlsSubtitleTrackLoaded\";\n // fired when a subtitle racks's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, id : track id }\n Events[\"SUBTITLE_TRACK_UPDATED\"] = \"hlsSubtitleTrackUpdated\";\n // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }\n Events[\"SUBTITLE_FRAG_PROCESSED\"] = \"hlsSubtitleFragProcessed\";\n // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }\n Events[\"CUES_PARSED\"] = \"hlsCuesParsed\";\n // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }\n Events[\"NON_NATIVE_TEXT_TRACKS_FOUND\"] = \"hlsNonNativeTextTracksFound\";\n // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, timescale: timescale, frag : fragment object }\n Events[\"INIT_PTS_FOUND\"] = \"hlsInitPtsFound\";\n // fired when a fragment loading starts - data: { frag : fragment object }\n Events[\"FRAG_LOADING\"] = \"hlsFragLoading\";\n // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }\n // FRAG_LOAD_PROGRESS = 'hlsFragLoadProgress',\n // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }\n Events[\"FRAG_LOAD_EMERGENCY_ABORTED\"] = \"hlsFragLoadEmergencyAborted\";\n // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : LoaderStats }\n Events[\"FRAG_LOADED\"] = \"hlsFragLoaded\";\n // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }\n Events[\"FRAG_DECRYPTED\"] = \"hlsFragDecrypted\";\n // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }\n Events[\"FRAG_PARSING_INIT_SEGMENT\"] = \"hlsFragParsingInitSegment\";\n // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }\n Events[\"FRAG_PARSING_USERDATA\"] = \"hlsFragParsingUserdata\";\n // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }\n Events[\"FRAG_PARSING_METADATA\"] = \"hlsFragParsingMetadata\";\n // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}\n // FRAG_PARSING_DATA = 'hlsFragParsingData',\n // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }\n Events[\"FRAG_PARSED\"] = \"hlsFragParsed\";\n // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : LoaderStats }\n Events[\"FRAG_BUFFERED\"] = \"hlsFragBuffered\";\n // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }\n Events[\"FRAG_CHANGED\"] = \"hlsFragChanged\";\n // Identifier for a FPS drop event - data: { currentDropped, currentDecoded, totalDroppedFrames }\n Events[\"FPS_DROP\"] = \"hlsFpsDrop\";\n // triggered when FPS drop triggers auto level capping - data: { level, droppedLevel }\n Events[\"FPS_DROP_LEVEL_CAPPING\"] = \"hlsFpsDropLevelCapping\";\n // triggered when maxAutoLevel changes - data { autoLevelCapping, levels, maxAutoLevel, minAutoLevel, maxHdcpLevel }\n Events[\"MAX_AUTO_LEVEL_UPDATED\"] = \"hlsMaxAutoLevelUpdated\";\n // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }\n Events[\"ERROR\"] = \"hlsError\";\n // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }\n Events[\"DESTROYING\"] = \"hlsDestroying\";\n // fired when a decrypt key loading starts - data: { frag : fragment object }\n Events[\"KEY_LOADING\"] = \"hlsKeyLoading\";\n // fired when a decrypt key loading is completed - data: { frag : fragment object, keyInfo : KeyLoaderInfo }\n Events[\"KEY_LOADED\"] = \"hlsKeyLoaded\";\n // deprecated; please use BACK_BUFFER_REACHED - data : { bufferEnd: number }\n Events[\"LIVE_BACK_BUFFER_REACHED\"] = \"hlsLiveBackBufferReached\";\n // fired when the back buffer is reached as defined by the backBufferLength config option - data : { bufferEnd: number }\n Events[\"BACK_BUFFER_REACHED\"] = \"hlsBackBufferReached\";\n // fired after steering manifest has been loaded - data: { steeringManifest: SteeringManifest object, url: steering manifest URL }\n Events[\"STEERING_MANIFEST_LOADED\"] = \"hlsSteeringManifestLoaded\";\n // fired when asset list has begun loading\n Events[\"ASSET_LIST_LOADING\"] = \"hlsAssetListLoading\";\n // fired when a valid asset list is loaded\n Events[\"ASSET_LIST_LOADED\"] = \"hlsAssetListLoaded\";\n // fired when the list of Interstitial Events and Interstitial Schedule is updated\n Events[\"INTERSTITIALS_UPDATED\"] = \"hlsInterstitialsUpdated\";\n // fired when the buffer reaches an Interstitial Schedule boundary (both Primary segments and Interstitial Assets)\n Events[\"INTERSTITIALS_BUFFERED_TO_BOUNDARY\"] = \"hlsInterstitialsBufferedToBoundary\";\n // fired when a player instance for an Interstitial Asset has been created\n Events[\"INTERSTITIAL_ASSET_PLAYER_CREATED\"] = \"hlsInterstitialAssetPlayerCreated\";\n // Interstitial playback started\n Events[\"INTERSTITIAL_STARTED\"] = \"hlsInterstitialStarted\";\n // InterstitialAsset playback started\n Events[\"INTERSTITIAL_ASSET_STARTED\"] = \"hlsInterstitialAssetStarted\";\n // InterstitialAsset playback ended\n Events[\"INTERSTITIAL_ASSET_ENDED\"] = \"hlsInterstitialAssetEnded\";\n // InterstitialAsset playback errored\n Events[\"INTERSTITIAL_ASSET_ERROR\"] = \"hlsInterstitialAssetError\";\n // Interstitial playback ended\n Events[\"INTERSTITIAL_ENDED\"] = \"hlsInterstitialEnded\";\n // Interstitial schedule resumed primary playback\n Events[\"INTERSTITIALS_PRIMARY_RESUMED\"] = \"hlsInterstitialsPrimaryResumed\";\n // Interstitial players dispatch this event when playout limit is reached\n Events[\"PLAYOUT_LIMIT_REACHED\"] = \"hlsPlayoutLimitReached\";\n // Event DateRange cue \"enter\" event dispatched\n Events[\"EVENT_CUE_ENTER\"] = \"hlsEventCueEnter\";\n return Events;\n}({});\n\n/**\n * Defines each Event type and payload by Event name. Used in {@link hls.js#HlsEventEmitter} to strongly type the event listener API.\n */\n\nvar PlaylistContextType = {\n MANIFEST: \"manifest\",\n LEVEL: \"level\",\n AUDIO_TRACK: \"audioTrack\",\n SUBTITLE_TRACK: \"subtitleTrack\"\n};\nvar PlaylistLevelType = {\n MAIN: \"main\",\n AUDIO: \"audio\",\n SUBTITLE: \"subtitle\"\n};\n\n/*\n * compute an Exponential Weighted moving average\n * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * - heavily inspired from shaka-player\n */\n\nclass EWMA {\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n constructor(halfLife, estimate = 0, weight = 0) {\n this.halfLife = void 0;\n this.alpha_ = void 0;\n this.estimate_ = void 0;\n this.totalWeight_ = void 0;\n this.halfLife = halfLife;\n // Larger values of alpha expire historical data more slowly.\n this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n this.estimate_ = estimate;\n this.totalWeight_ = weight;\n }\n sample(weight, value) {\n const adjAlpha = Math.pow(this.alpha_, weight);\n this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;\n this.totalWeight_ += weight;\n }\n getTotalWeight() {\n return this.totalWeight_;\n }\n getEstimate() {\n if (this.alpha_) {\n const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);\n if (zeroFactor) {\n return this.estimate_ / zeroFactor;\n }\n }\n return this.estimate_;\n }\n}\n\n/*\n * EWMA Bandwidth Estimator\n * - heavily inspired from shaka-player\n * Tracks bandwidth samples and estimates available bandwidth.\n * Based on the minimum of two exponentially-weighted moving averages with\n * different half-lives.\n */\n\nclass EwmaBandWidthEstimator {\n constructor(slow, fast, defaultEstimate, defaultTTFB = 100) {\n this.defaultEstimate_ = void 0;\n this.minWeight_ = void 0;\n this.minDelayMs_ = void 0;\n this.slow_ = void 0;\n this.fast_ = void 0;\n this.defaultTTFB_ = void 0;\n this.ttfb_ = void 0;\n this.defaultEstimate_ = defaultEstimate;\n this.minWeight_ = 0.001;\n this.minDelayMs_ = 50;\n this.slow_ = new EWMA(slow);\n this.fast_ = new EWMA(fast);\n this.defaultTTFB_ = defaultTTFB;\n this.ttfb_ = new EWMA(slow);\n }\n update(slow, fast) {\n const {\n slow_,\n fast_,\n ttfb_\n } = this;\n if (slow_.halfLife !== slow) {\n this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());\n }\n if (fast_.halfLife !== fast) {\n this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());\n }\n if (ttfb_.halfLife !== slow) {\n this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());\n }\n }\n sample(durationMs, numBytes) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n const numBits = 8 * numBytes;\n // weight is duration in seconds\n const durationS = durationMs / 1000;\n // value is bandwidth in bits/s\n const bandwidthInBps = numBits / durationS;\n this.fast_.sample(durationS, bandwidthInBps);\n this.slow_.sample(durationS, bandwidthInBps);\n }\n sampleTTFB(ttfb) {\n // weight is frequency curve applied to TTFB in seconds\n // (longer times have less weight with expected input under 1 second)\n const seconds = ttfb / 1000;\n const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);\n this.ttfb_.sample(weight, Math.max(ttfb, 5));\n }\n canEstimate() {\n return this.fast_.getTotalWeight() >= this.minWeight_;\n }\n getEstimate() {\n if (this.canEstimate()) {\n // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));\n // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));\n // Take the minimum of these two estimates. This should have the effect of\n // adapting down quickly, but up more slowly.\n return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());\n } else {\n return this.defaultEstimate_;\n }\n }\n getEstimateTTFB() {\n if (this.ttfb_.getTotalWeight() >= this.minWeight_) {\n return this.ttfb_.getEstimate();\n } else {\n return this.defaultTTFB_;\n }\n }\n get defaultEstimate() {\n return this.defaultEstimate_;\n }\n destroy() {}\n}\n\nfunction _defineProperty(e, r, t) {\n return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: true,\n configurable: true,\n writable: true\n }) : e[r] = t, e;\n}\nfunction _extends() {\n return _extends = Object.assign ? Object.assign.bind() : function (n) {\n for (var e = 1; e < arguments.length; e++) {\n var t = arguments[e];\n for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n }\n return n;\n }, _extends.apply(null, arguments);\n}\nfunction ownKeys(e, r) {\n var t = Object.keys(e);\n if (Object.getOwnPropertySymbols) {\n var o = Object.getOwnPropertySymbols(e);\n r && (o = o.filter(function (r) {\n return Object.getOwnPropertyDescriptor(e, r).enumerable;\n })), t.push.apply(t, o);\n }\n return t;\n}\nfunction _objectSpread2(e) {\n for (var r = 1; r < arguments.length; r++) {\n var t = null != arguments[r] ? arguments[r] : {};\n r % 2 ? ownKeys(Object(t), true).forEach(function (r) {\n _defineProperty(e, r, t[r]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {\n Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n });\n }\n return e;\n}\nfunction _toPrimitive(t, r) {\n if (\"object\" != typeof t || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r);\n if (\"object\" != typeof i) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nfunction _toPropertyKey(t) {\n var i = _toPrimitive(t, \"string\");\n return \"symbol\" == typeof i ? i : i + \"\";\n}\n\nclass Logger {\n constructor(label, logger) {\n this.trace = void 0;\n this.debug = void 0;\n this.log = void 0;\n this.warn = void 0;\n this.info = void 0;\n this.error = void 0;\n const lb = `[${label}]:`;\n this.trace = noop;\n this.debug = logger.debug.bind(null, lb);\n this.log = logger.log.bind(null, lb);\n this.warn = logger.warn.bind(null, lb);\n this.info = logger.info.bind(null, lb);\n this.error = logger.error.bind(null, lb);\n }\n}\nconst noop = function noop() {};\nconst fakeLogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop\n};\nfunction createLogger() {\n return _extends({}, fakeLogger);\n}\n\n// let lastCallTime;\n// function formatMsgWithTimeInfo(type, msg) {\n// const now = Date.now();\n// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';\n// lastCallTime = now;\n// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';\n// return msg;\n// }\n\nfunction consolePrintFn(type, id) {\n const func = self.console[type];\n return func ? func.bind(self.console, `${id ? '[' + id + '] ' : ''}[${type}] >`) : noop;\n}\nfunction getLoggerFn(key, debugConfig, id) {\n return debugConfig[key] ? debugConfig[key].bind(debugConfig) : consolePrintFn(key, id);\n}\nconst exportedLogger = createLogger();\nfunction enableLogs(debugConfig, context, id) {\n // check that console is available\n const newLogger = createLogger();\n if (typeof console === 'object' && debugConfig === true || typeof debugConfig === 'object') {\n const keys = [\n // Remove out from list here to hard-disable a log-level\n // 'trace',\n 'debug', 'log', 'info', 'warn', 'error'];\n keys.forEach(key => {\n newLogger[key] = getLoggerFn(key, debugConfig, id);\n });\n // Some browsers don't allow to use bind on console object anyway\n // fallback to default if needed\n try {\n newLogger.log(`Debug logs enabled for \"${context}\" in hls.js version ${\"1.6.2\"}`);\n } catch (e) {\n /* log fn threw an exception. All logger methods are no-ops. */\n return createLogger();\n }\n // global exported logger uses the same functions as new logger without `id`\n keys.forEach(key => {\n exportedLogger[key] = getLoggerFn(key, debugConfig);\n });\n } else {\n // Reset global exported logger\n _extends(exportedLogger, newLogger);\n }\n return newLogger;\n}\nconst logger = exportedLogger;\n\nfunction getMediaSource(preferManagedMediaSource = true) {\n if (typeof self === 'undefined') return undefined;\n const mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;\n return mms || self.MediaSource || self.WebKitMediaSource;\n}\nfunction isManagedMediaSource(source) {\n return typeof self !== 'undefined' && source === self.ManagedMediaSource;\n}\nfunction isCompatibleTrackChange(currentTracks, requiredTracks) {\n const trackNames = Object.keys(currentTracks);\n const requiredTrackNames = Object.keys(requiredTracks);\n const trackCount = trackNames.length;\n const requiredTrackCount = requiredTrackNames.length;\n return !trackCount || !requiredTrackCount || trackCount === requiredTrackCount && !trackNames.some(name => requiredTrackNames.indexOf(name) === -1);\n}\n\n// http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n/* utf.js - UTF-8 <=> UTF-16 convertion\n *\n * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n * Version: 1.0\n * LastModified: Dec 25 1999\n * This library is free. You can redistribute it and/or modify it.\n */\n/**\n * Converts a UTF-8 array to a string.\n *\n * @param array - The UTF-8 array to convert\n *\n * @returns The string\n *\n * @group Utils\n *\n * @beta\n */\nfunction utf8ArrayToStr(array, exitOnNull = false) {\n if (typeof TextDecoder !== 'undefined') {\n const decoder = new TextDecoder('utf-8');\n const decoded = decoder.decode(array);\n if (exitOnNull) {\n // grab up to the first null\n const idx = decoded.indexOf('\\0');\n return idx !== -1 ? decoded.substring(0, idx) : decoded;\n }\n // remove any null characters\n return decoded.replace(/\\0/g, '');\n }\n const len = array.length;\n let c;\n let char2;\n let char3;\n let out = '';\n let i = 0;\n while (i < len) {\n c = array[i++];\n if (c === 0x00 && exitOnNull) {\n return out;\n } else if (c === 0x00 || c === 0x03) {\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\n continue;\n }\n switch (c >> 4) {\n case 0:\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n // 0xxxxxxx\n out += String.fromCharCode(c);\n break;\n case 12:\n case 13:\n // 110x xxxx 10xx xxxx\n char2 = array[i++];\n out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);\n break;\n case 14:\n // 1110 xxxx 10xx xxxx 10xx xxxx\n char2 = array[i++];\n char3 = array[i++];\n out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);\n break;\n }\n }\n return out;\n}\n\n/**\n * hex dump helper class\n */\n\nconst Hex = {\n hexDump: function (array) {\n let str = '';\n for (let i = 0; i < array.length; i++) {\n let h = array[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n str += h;\n }\n return str;\n }\n};\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nvar urlToolkit = {exports: {}};\n\nvar hasRequiredUrlToolkit;\n\nfunction requireUrlToolkit () {\n\tif (hasRequiredUrlToolkit) return urlToolkit.exports;\n\thasRequiredUrlToolkit = 1;\n\t(function (module, exports) {\n\t\t// see https://tools.ietf.org/html/rfc1808\n\n\t\t(function (root) {\n\t\t var URL_REGEX =\n\t\t /^(?=((?:[a-zA-Z0-9+\\-.]+:)?))\\1(?=((?:\\/\\/[^\\/?#]*)?))\\2(?=((?:(?:[^?#\\/]*\\/)*[^;?#\\/]*)?))\\3((?:;[^?#]*)?)(\\?[^#]*)?(#[^]*)?$/;\n\t\t var FIRST_SEGMENT_REGEX = /^(?=([^\\/?#]*))\\1([^]*)$/;\n\t\t var SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\n\t\t var SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/)[^\\/]*(?=\\/)/g;\n\n\t\t var URLToolkit = {\n\t\t // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\n\t\t // E.g\n\t\t // With opts.alwaysNormalize = false (default, spec compliant)\n\t\t // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\n\t\t // With opts.alwaysNormalize = true (not spec compliant)\n\t\t // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\n\t\t buildAbsoluteURL: function (baseURL, relativeURL, opts) {\n\t\t opts = opts || {};\n\t\t // remove any remaining space and CRLF\n\t\t baseURL = baseURL.trim();\n\t\t relativeURL = relativeURL.trim();\n\t\t if (!relativeURL) {\n\t\t // 2a) If the embedded URL is entirely empty, it inherits the\n\t\t // entire base URL (i.e., is set equal to the base URL)\n\t\t // and we are done.\n\t\t if (!opts.alwaysNormalize) {\n\t\t return baseURL;\n\t\t }\n\t\t var basePartsForNormalise = URLToolkit.parseURL(baseURL);\n\t\t if (!basePartsForNormalise) {\n\t\t throw new Error('Error trying to parse base URL.');\n\t\t }\n\t\t basePartsForNormalise.path = URLToolkit.normalizePath(\n\t\t basePartsForNormalise.path\n\t\t );\n\t\t return URLToolkit.buildURLFromParts(basePartsForNormalise);\n\t\t }\n\t\t var relativeParts = URLToolkit.parseURL(relativeURL);\n\t\t if (!relativeParts) {\n\t\t throw new Error('Error trying to parse relative URL.');\n\t\t }\n\t\t if (relativeParts.scheme) {\n\t\t // 2b) If the embedded URL starts with a scheme name, it is\n\t\t // interpreted as an absolute URL and we are done.\n\t\t if (!opts.alwaysNormalize) {\n\t\t return relativeURL;\n\t\t }\n\t\t relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\n\t\t return URLToolkit.buildURLFromParts(relativeParts);\n\t\t }\n\t\t var baseParts = URLToolkit.parseURL(baseURL);\n\t\t if (!baseParts) {\n\t\t throw new Error('Error trying to parse base URL.');\n\t\t }\n\t\t if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {\n\t\t // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\n\t\t // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\n\t\t var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\n\t\t baseParts.netLoc = pathParts[1];\n\t\t baseParts.path = pathParts[2];\n\t\t }\n\t\t if (baseParts.netLoc && !baseParts.path) {\n\t\t baseParts.path = '/';\n\t\t }\n\t\t var builtParts = {\n\t\t // 2c) Otherwise, the embedded URL inherits the scheme of\n\t\t // the base URL.\n\t\t scheme: baseParts.scheme,\n\t\t netLoc: relativeParts.netLoc,\n\t\t path: null,\n\t\t params: relativeParts.params,\n\t\t query: relativeParts.query,\n\t\t fragment: relativeParts.fragment,\n\t\t };\n\t\t if (!relativeParts.netLoc) {\n\t\t // 3) If the embedded URL's <net_loc> is non-empty, we skip to\n\t\t // Step 7. Otherwise, the embedded URL inherits the <net_loc>\n\t\t // (if any) of the base URL.\n\t\t builtParts.netLoc = baseParts.netLoc;\n\t\t // 4) If the embedded URL path is preceded by a slash \"/\", the\n\t\t // path is not relative and we skip to Step 7.\n\t\t if (relativeParts.path[0] !== '/') {\n\t\t if (!relativeParts.path) {\n\t\t // 5) If the embedded URL path is empty (and not preceded by a\n\t\t // slash), then the embedded URL inherits the base URL path\n\t\t builtParts.path = baseParts.path;\n\t\t // 5a) if the embedded URL's <params> is non-empty, we skip to\n\t\t // step 7; otherwise, it inherits the <params> of the base\n\t\t // URL (if any) and\n\t\t if (!relativeParts.params) {\n\t\t builtParts.params = baseParts.params;\n\t\t // 5b) if the embedded URL's <query> is non-empty, we skip to\n\t\t // step 7; otherwise, it inherits the <query> of the base\n\t\t // URL (if any) and we skip to step 7.\n\t\t if (!relativeParts.query) {\n\t\t builtParts.query = baseParts.query;\n\t\t }\n\t\t }\n\t\t } else {\n\t\t // 6) The last segment of the base URL's path (anything\n\t\t // following the rightmost slash \"/\", or the entire path if no\n\t\t // slash is present) is removed and the embedded URL's path is\n\t\t // appended in its place.\n\t\t var baseURLPath = baseParts.path;\n\t\t var newPath =\n\t\t baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +\n\t\t relativeParts.path;\n\t\t builtParts.path = URLToolkit.normalizePath(newPath);\n\t\t }\n\t\t }\n\t\t }\n\t\t if (builtParts.path === null) {\n\t\t builtParts.path = opts.alwaysNormalize\n\t\t ? URLToolkit.normalizePath(relativeParts.path)\n\t\t : relativeParts.path;\n\t\t }\n\t\t return URLToolkit.buildURLFromParts(builtParts);\n\t\t },\n\t\t parseURL: function (url) {\n\t\t var parts = URL_REGEX.exec(url);\n\t\t if (!parts) {\n\t\t return null;\n\t\t }\n\t\t return {\n\t\t scheme: parts[1] || '',\n\t\t netLoc: parts[2] || '',\n\t\t path: parts[3] || '',\n\t\t params: parts[4] || '',\n\t\t query: parts[5] || '',\n\t\t fragment: parts[6] || '',\n\t\t };\n\t\t },\n\t\t normalizePath: function (path) {\n\t\t // The following operations are\n\t\t // then applied, in order, to the new path:\n\t\t // 6a) All occurrences of \"./\", where \".\" is a complete path\n\t\t // segment, are removed.\n\t\t // 6b) If the path ends with \".\" as a complete path segment,\n\t\t // that \".\" is removed.\n\t\t path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');\n\t\t // 6c) All occurrences of \"<segment>/../\", where <segment> is a\n\t\t // complete path segment not equal to \"..\", are removed.\n\t\t // Removal of these path segments is performed iteratively,\n\t\t // removing the leftmost matching pattern on each iteration,\n\t\t // until no matching pattern remains.\n\t\t // 6d) If the path ends with \"<segment>/..\", where <segment> is a\n\t\t // complete path segment not equal to \"..\", that\n\t\t // \"<segment>/..\" is removed.\n\t\t while (\n\t\t path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length\n\t\t ) {}\n\t\t return path.split('').reverse().join('');\n\t\t },\n\t\t buildURLFromParts: function (parts) {\n\t\t return (\n\t\t parts.scheme +\n\t\t parts.netLoc +\n\t\t parts.path +\n\t\t parts.params +\n\t\t parts.query +\n\t\t parts.fragment\n\t\t );\n\t\t },\n\t\t };\n\n\t\t module.exports = URLToolkit;\n\t\t})(); \n\t} (urlToolkit));\n\treturn urlToolkit.exports;\n}\n\nvar urlToolkitExports = requireUrlToolkit();\n\nclass LoadStats {\n constructor() {\n this.aborted = false;\n this.loaded = 0;\n this.retry = 0;\n this.total = 0;\n this.chunkCount = 0;\n this.bwEstimate = 0;\n this.loading = {\n start: 0,\n first: 0,\n end: 0\n };\n this.parsing = {\n start: 0,\n end: 0\n };\n this.buffering = {\n start: 0,\n first: 0,\n end: 0\n };\n }\n}\n\nvar ElementaryStreamTypes = {\n AUDIO: \"audio\",\n VIDEO: \"video\",\n AUDIOVIDEO: \"audiovideo\"\n};\nclass BaseSegment {\n constructor(base) {\n this._byteRange = null;\n this._url = null;\n this._stats = null;\n this._streams = null;\n // baseurl is the URL to the playlist\n this.base = void 0;\n // relurl is the portion of the URL that comes from inside the playlist.\n this.relurl = void 0;\n if (typeof base === 'string') {\n base = {\n url: base\n };\n }\n this.base = base;\n makeEnumerable(this, 'stats');\n }\n\n // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array\n setByteRange(value, previous) {\n const params = value.split('@', 2);\n let start;\n if (params.length === 1) {\n start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;\n } else {\n start = parseInt(params[1]);\n }\n this._byteRange = [start, parseInt(params[0]) + start];\n }\n get baseurl() {\n return this.base.url;\n }\n get byteRange() {\n if (this._byteRange === null) {\n return [];\n }\n return this._byteRange;\n }\n get byteRangeStartOffset() {\n return this.byteRange[0];\n }\n get byteRangeEndOffset() {\n return this.byteRange[1];\n }\n get elementaryStreams() {\n if (this._streams === null) {\n this._streams = {\n [ElementaryStreamTypes.AUDIO]: null,\n [ElementaryStreamTypes.VIDEO]: null,\n [ElementaryStreamTypes.AUDIOVIDEO]: null\n };\n }\n return this._streams;\n }\n set elementaryStreams(value) {\n this._streams = value;\n }\n get hasStats() {\n return this._stats !== null;\n }\n get hasStreams() {\n return this._streams !== null;\n }\n get stats() {\n if (this._stats === null) {\n this._stats = new LoadStats();\n }\n return this._stats;\n }\n set stats(value) {\n this._stats = value;\n }\n get url() {\n if (!this._url && this.baseurl && this.relurl) {\n this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {\n alwaysNormalize: true\n });\n }\n return this._url || '';\n }\n set url(value) {\n this._url = value;\n }\n clearElementaryStreamInfo() {\n const {\n elementaryStreams\n } = this;\n elementaryStreams[ElementaryStreamTypes.AUDIO] = null;\n elementaryStreams[ElementaryStreamTypes.VIDEO] = null;\n elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;\n }\n}\nfunction isMediaFragment(frag) {\n return frag.sn !== 'initSegment';\n}\n\n/**\n * Object representing parsed data from an HLS Segment. Found in {@link hls.js#LevelDetails.fragments}.\n */\nclass Fragment extends BaseSegment {\n constructor(type, base) {\n super(base);\n this._decryptdata = null;\n this._programDateTime = null;\n this._ref = null;\n // Approximate bit rate of the fragment expressed in bits per second (bps) as indicated by the last EXT-X-BITRATE (kbps) tag\n this._bitrate = void 0;\n this.rawProgramDateTime = null;\n this.tagList = [];\n // EXTINF has to be present for a m3u8 to be considered valid\n this.duration = 0;\n // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'\n this.sn = 0;\n // levelkeys are the EXT-X-KEY tags that apply to this segment for decryption\n // core difference from the private field _decryptdata is the lack of the initialized IV\n // _decryptdata will set the IV for this segment based on the segment number in the fragment\n this.levelkeys = void 0;\n // A string representing the fragment type\n this.type = void 0;\n // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading\n this.loader = null;\n // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading\n this.keyLoader = null;\n // The level/track index to which the fragment belongs\n this.level = -1;\n // The continuity counter of the fragment\n this.cc = 0;\n // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.\n this.startPTS = void 0;\n // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.\n this.endPTS = void 0;\n // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n this.startDTS = void 0;\n // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n this.endDTS = void 0;\n // The start time of the fragment, as listed in the manifest. Updated after transmux complete.\n this.start = 0;\n // The offset time (seconds) of the fragment from the start of the Playlist\n this.playlistOffset = 0;\n // Set by `updateFragPTSDTS` in level-helper\n this.deltaPTS = void 0;\n // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n this.maxStartPTS = void 0;\n // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n this.minEndPTS = void 0;\n // Init Segment bytes (unset for media segments)\n this.data = void 0;\n // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered\n this.bitrateTest = false;\n // #EXTINF segment title\n this.title = null;\n // The Media Initialization Section for this segment\n this.initSegment = null;\n // Fragment is the last fragment in the media playlist\n this.endList = void 0;\n // Fragment is marked by an EXT-X-GAP tag indicating that it does not contain media data and should not be loaded\n this.gap = void 0;\n // Deprecated\n this.urlId = 0;\n this.type = type;\n }\n get byteLength() {\n if (this.hasStats) {\n const total = this.stats.total;\n if (total) {\n return total;\n }\n }\n if (this.byteRange) {\n const start = this.byteRange[0];\n const end = this.byteRange[1];\n if (isFiniteNumber(start) && isFiniteNumber(end)) {\n return end - start;\n }\n }\n return null;\n }\n get bitrate() {\n if (this.byteLength) {\n return this.byteLength * 8 / this.duration;\n }\n if (this._bitrate) {\n return this._bitrate;\n }\n return null;\n }\n set bitrate(value) {\n this._bitrate = value;\n }\n get decryptdata() {\n const {\n levelkeys\n } = this;\n if (!levelkeys && !this._decryptdata) {\n return null;\n }\n if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {\n const key = this.levelkeys.identity;\n if (key) {\n this._decryptdata = key.getDecryptData(this.sn);\n } else {\n const keyFormats = Object.keys(this.levelkeys);\n if (keyFormats.length === 1) {\n return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);\n }\n }\n }\n return this._decryptdata;\n }\n get end() {\n return this.start + this.duration;\n }\n get endProgramDateTime() {\n if (this.programDateTime === null) {\n return null;\n }\n const duration = !isFiniteNumber(this.duration) ? 0 : this.duration;\n return this.programDateTime + duration * 1000;\n }\n get encrypted() {\n var _this$_decryptdata;\n // At the m3u8-parser level we need to add support for manifest signalled keyformats\n // when we want the fragment to start reporting that it is encrypted.\n // Currently, keyFormat will only be set for identity keys\n if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {\n return true;\n } else if (this.levelkeys) {\n const keyFormats = Object.keys(this.levelkeys);\n const len = keyFormats.length;\n if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {\n return true;\n }\n }\n return false;\n }\n get programDateTime() {\n if (this._programDateTime === null && this.rawProgramDateTime) {\n this.programDateTime = Date.parse(this.rawProgramDateTime);\n }\n return this._programDateTime;\n }\n set programDateTime(value) {\n if (!isFiniteNumber(value)) {\n this._programDateTime = this.rawProgramDateTime = null;\n return;\n }\n this._programDateTime = value;\n }\n get ref() {\n if (!isMediaFragment(this)) {\n return null;\n }\n if (!this._ref) {\n this._ref = {\n base: this.base,\n start: this.start,\n duration: this.duration,\n sn: this.sn,\n programDateTime: this.programDateTime\n };\n }\n return this._ref;\n }\n addStart(value) {\n this.setStart(this.start + value);\n }\n setStart(value) {\n this.start = value;\n if (this._ref) {\n this._ref.start = value;\n }\n }\n setDuration(value) {\n this.duration = value;\n if (this._ref) {\n this._ref.duration = value;\n }\n }\n setKeyFormat(keyFormat) {\n if (this.levelkeys) {\n const key = this.levelkeys[keyFormat];\n if (key && !this._decryptdata) {\n this._decryptdata = key.getDecryptData(this.sn);\n }\n }\n }\n abortRequests() {\n var _this$loader, _this$keyLoader;\n (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();\n (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();\n }\n setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial = false) {\n const {\n elementaryStreams\n } = this;\n const info = elementaryStreams[type];\n if (!info) {\n elementaryStreams[type] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n partial\n };\n return;\n }\n info.startPTS = Math.min(info.startPTS, startPTS);\n info.endPTS = Math.max(info.endPTS, endPTS);\n info.startDTS = Math.min(info.startDTS, startDTS);\n info.endDTS = Math.max(info.endDTS, endDTS);\n }\n}\n\n/**\n * Object representing parsed data from an HLS Partial Segment. Found in {@link hls.js#LevelDetails.partList}.\n */\nclass Part extends BaseSegment {\n constructor(partAttrs, frag, base, index, previous) {\n super(base);\n this.fragOffset = 0;\n this.duration = 0;\n this.gap = false;\n this.independent = false;\n this.relurl = void 0;\n this.fragment = void 0;\n this.index = void 0;\n this.duration = partAttrs.decimalFloatingPoint('DURATION');\n this.gap = partAttrs.bool('GAP');\n this.independent = partAttrs.bool('INDEPENDENT');\n this.relurl = partAttrs.enumeratedString('URI');\n this.fragment = frag;\n this.index = index;\n const byteRange = partAttrs.enumeratedString('BYTERANGE');\n if (byteRange) {\n this.setByteRange(byteRange, previous);\n }\n if (previous) {\n this.fragOffset = previous.fragOffset + previous.duration;\n }\n }\n get start() {\n return this.fragment.start + this.fragOffset;\n }\n get end() {\n return this.start + this.duration;\n }\n get loaded() {\n const {\n elementaryStreams\n } = this;\n return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);\n }\n}\nfunction getOwnPropertyDescriptorFromPrototypeChain(object, property) {\n const prototype = Object.getPrototypeOf(object);\n if (prototype) {\n const propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, property);\n if (propertyDescriptor) {\n return propertyDescriptor;\n }\n return getOwnPropertyDescriptorFromPrototypeChain(prototype, property);\n }\n}\nfunction makeEnumerable(object, property) {\n const d = getOwnPropertyDescriptorFromPrototypeChain(object, property);\n if (d) {\n d.enumerable = true;\n Object.defineProperty(object, property, d);\n }\n}\n\nconst UINT32_MAX$1 = Math.pow(2, 32) - 1;\nconst push = [].push;\n\n// We are using fixed track IDs for driving the MP4 remuxer\n// instead of following the TS PIDs.\n// There is no reason not to do this and some browsers/SourceBuffer-demuxers\n// may not like if there are TrackID \"switches\"\n// See https://github.com/video-dev/hls.js/issues/1331\n// Here we are mapping our internal track types to constant MP4 track IDs\n// With MSE currently one can only have one track of each, and we are muxing\n// whatever video/audio rendition in them.\nconst RemuxerTrackIdConfig = {\n video: 1,\n audio: 2,\n id3: 3,\n text: 4\n};\nfunction bin2str(data) {\n return String.fromCharCode.apply(null, data);\n}\nfunction readUint16(buffer, offset) {\n const val = buffer[offset] << 8 | buffer[offset + 1];\n return val < 0 ? 65536 + val : val;\n}\nfunction readUint32(buffer, offset) {\n const val = readSint32(buffer, offset);\n return val < 0 ? 4294967296 + val : val;\n}\nfunction readUint64(buffer, offset) {\n let result = readUint32(buffer, offset);\n result *= Math.pow(2, 32);\n result += readUint32(buffer, offset + 4);\n return result;\n}\nfunction readSint32(buffer, offset) {\n return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];\n}\nfunction writeUint32(buffer, offset, value) {\n buffer[offset] = value >> 24;\n buffer[offset + 1] = value >> 16 & 0xff;\n buffer[offset + 2] = value >> 8 & 0xff;\n buffer[offset + 3] = value & 0xff;\n}\n\n// Find \"moof\" box\nfunction hasMoofData(data) {\n const end = data.byteLength;\n for (let i = 0; i < end;) {\n const size = readUint32(data, i);\n if (size > 8 && data[i + 4] === 0x6d && data[i + 5] === 0x6f && data[i + 6] === 0x6f && data[i + 7] === 0x66) {\n return true;\n }\n i = size > 1 ? i + size : end;\n }\n return false;\n}\n\n// Find the data for a box specified by its path\nfunction findBox(data, path) {\n const results = [];\n if (!path.length) {\n // short-circuit the search for empty paths\n return results;\n }\n const end = data.byteLength;\n for (let i = 0; i < end;) {\n const size = readUint32(data, i);\n const type = bin2str(data.subarray(i + 4, i + 8));\n const endbox = size > 1 ? i + size : end;\n if (type === path[0]) {\n if (path.length === 1) {\n // this is the end of the path and we've found the box we were\n // looking for\n results.push(data.subarray(i + 8, endbox));\n } else {\n // recursively search for the next box along the path\n const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));\n if (subresults.length) {\n push.apply(results, subresults);\n }\n }\n }\n i = endbox;\n }\n\n // we've finished searching all of data\n return results;\n}\nfunction parseSegmentIndex(sidx) {\n const references = [];\n const version = sidx[0];\n\n // set initial offset, we skip the reference ID (not needed)\n let index = 8;\n const timescale = readUint32(sidx, index);\n index += 4;\n let earliestPresentationTime = 0;\n let firstOffset = 0;\n if (version === 0) {\n earliestPresentationTime = readUint32(sidx, index);\n firstOffset = readUint32(sidx, index + 4);\n index += 8;\n } else {\n earliestPresentationTime = readUint64(sidx, index);\n firstOffset = readUint64(sidx, index + 8);\n index += 16;\n }\n\n // skip reserved\n index += 2;\n let startByte = sidx.length + firstOffset;\n const referencesCount = readUint16(sidx, index);\n index += 2;\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n const referenceInfo = readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n const referenceSize = referenceInfo & 0x7fffffff;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n if (referenceType === 1) {\n logger.warn('SIDX has hierarchical references (not supported)');\n return null;\n }\n const subsegmentDuration = readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n references.push({\n referenceSize,\n subsegmentDuration,\n // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1\n }\n });\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n return {\n earliestPresentationTime,\n timescale,\n version,\n referencesCount,\n references\n };\n}\n\n/**\n * Parses an MP4 initialization segment and extracts stream type and\n * timescale values for any declared tracks. Timescale values indicate the\n * number of clock ticks per second to assume for time-based values\n * elsewhere in the MP4.\n *\n * To determine the start time of an MP4, you need two pieces of\n * information: the timescale unit and the earliest base media decode\n * time. Multiple timescales can be specified within an MP4 but the\n * base media decode time is always expressed in the timescale from\n * the media header box for the track:\n * ```\n * moov > trak > mdia > mdhd.timescale\n * moov > trak > mdia > hdlr\n * ```\n * @param initSegment the bytes of the init segment\n * @returns a hash of track type to timescale values or null if\n * the init segment is malformed.\n */\n\nfunction parseInitSegment(initSegment) {\n const result = [];\n const traks = findBox(initSegment, ['moov', 'trak']);\n for (let i = 0; i < traks.length; i++) {\n const trak = traks[i];\n const tkhd = findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n let version = tkhd[0];\n const trackId = readUint32(tkhd, version === 0 ? 12 : 20);\n const mdhd = findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd[0];\n const timescale = readUint32(mdhd, version === 0 ? 12 : 20);\n const hdlr = findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n const hdlrType = bin2str(hdlr.subarray(8, 12));\n const type = {\n soun: ElementaryStreamTypes.AUDIO,\n vide: ElementaryStreamTypes.VIDEO\n }[hdlrType];\n // Parse codec details\n const stsdBox = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];\n const stsd = parseStsd(stsdBox);\n if (type) {\n // Add 'audio', 'video', and 'audiovideo' track records that will map to SourceBuffers\n result[trackId] = {\n timescale,\n type,\n stsd\n };\n result[type] = _objectSpread2({\n timescale,\n id: trackId\n }, stsd);\n } else {\n // Add 'meta' and other track records required by `offsetStartDTS`\n result[trackId] = {\n timescale,\n type: hdlrType,\n stsd\n };\n }\n }\n }\n }\n }\n const trex = findBox(initSegment, ['moov', 'mvex', 'trex']);\n trex.forEach(trex => {\n const trackId = readUint32(trex, 4);\n const track = result[trackId];\n if (track) {\n track.default = {\n duration: readUint32(trex, 12),\n flags: readUint32(trex, 20)\n };\n }\n });\n return result;\n}\nfunction parseStsd(stsd) {\n const sampleEntries = stsd.subarray(8);\n const sampleEntriesEnd = sampleEntries.subarray(8 + 78);\n const fourCC = bin2str(sampleEntries.subarray(4, 8));\n let codec = fourCC;\n let supplemental;\n const encrypted = fourCC === 'enca' || fourCC === 'encv';\n if (encrypted) {\n const encBox = findBox(sampleEntries, [fourCC])[0];\n const encBoxChildren = encBox.subarray(fourCC === 'enca' ? 28 : 78);\n const sinfs = findBox(encBoxChildren, ['sinf']);\n sinfs.forEach(sinf => {\n const schm = findBox(sinf, ['schm'])[0];\n if (schm) {\n const scheme = bin2str(schm.subarray(4, 8));\n if (scheme === 'cbcs' || scheme === 'cenc') {\n const frma = findBox(sinf, ['frma'])[0];\n if (frma) {\n // for encrypted content codec fourCC will be in frma\n codec = bin2str(frma);\n }\n }\n }\n });\n }\n const codecFourCC = codec;\n switch (codec) {\n case 'avc1':\n case 'avc2':\n case 'avc3':\n case 'avc4':\n {\n // extract profile + compatibility + level out of avcC box\n const avcCBox = findBox(sampleEntriesEnd, ['avcC'])[0];\n if (avcCBox && avcCBox.length > 3) {\n codec += '.' + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);\n supplemental = parseSupplementalDoViCodec(codecFourCC === 'avc1' ? 'dva1' : 'dvav', sampleEntriesEnd);\n }\n break;\n }\n case 'mp4a':\n {\n const codecBox = findBox(sampleEntries, [fourCC])[0];\n const esdsBox = findBox(codecBox.subarray(28), ['esds'])[0];\n if (esdsBox && esdsBox.length > 7) {\n let i = 4;\n // ES Descriptor tag\n if (esdsBox[i++] !== 0x03) {\n break;\n }\n i = skipBERInteger(esdsBox, i);\n i += 2; // skip es_id;\n const flags = esdsBox[i++];\n if (flags & 0x80) {\n i += 2; // skip dependency es_id\n }\n if (flags & 0x40) {\n i += esdsBox[i++]; // skip URL\n }\n // Decoder config descriptor\n if (esdsBox[i++] !== 0x04) {\n break;\n }\n i = skipBERInteger(esdsBox, i);\n const objectType = esdsBox[i++];\n if (objectType === 0x40) {\n codec += '.' + toHex(objectType);\n } else {\n break;\n }\n i += 12;\n // Decoder specific info\n if (esdsBox[i++] !== 0x05) {\n break;\n }\n i = skipBERInteger(esdsBox, i);\n const firstByte = esdsBox[i++];\n let audioObjectType = (firstByte & 0xf8) >> 3;\n if (audioObjectType === 31) {\n audioObjectType += 1 + ((firstByte & 0x7) << 3) + ((esdsBox[i] & 0xe0) >> 5);\n }\n codec += '.' + audioObjectType;\n }\n break;\n }\n case 'hvc1':\n case 'hev1':\n {\n const hvcCBox = findBox(sampleEntriesEnd, ['hvcC'])[0];\n if (hvcCBox && hvcCBox.length > 12) {\n const profileByte = hvcCBox[1];\n const profileSpace = ['', 'A', 'B', 'C'][profileByte >> 6];\n const generalProfileIdc = profileByte & 0x1f;\n const profileCompat = readUint32(hvcCBox, 2);\n const tierFlag = (profileByte & 0x20) >> 5 ? 'H' : 'L';\n const levelIDC = hvcCBox[12];\n const constraintIndicator = hvcCBox.subarray(6, 12);\n codec += '.' + profileSpace + generalProfileIdc;\n codec += '.' + profileCompat.toString(16).toUpperCase();\n codec += '.' + tierFlag + levelIDC;\n let constraintString = '';\n for (let i = constraintIndicator.length; i--;) {\n const byte = constraintIndicator[i];\n if (byte || constraintString) {\n const encodedByte = byte.toString(16).toUpperCase();\n constraintString = '.' + encodedByte + constraintString;\n }\n }\n codec += constraintString;\n }\n supplemental = parseSupplementalDoViCodec(codecFourCC == 'hev1' ? 'dvhe' : 'dvh1', sampleEntriesEnd);\n break;\n }\n case 'dvh1':\n case 'dvhe':\n case 'dvav':\n case 'dva1':\n case 'dav1':\n {\n codec = parseSupplementalDoViCodec(codec, sampleEntriesEnd) || codec;\n break;\n }\n case 'vp09':\n {\n const vpcCBox = findBox(sampleEntriesEnd, ['vpcC'])[0];\n if (vpcCBox && vpcCBox.length > 6) {\n const profile = vpcCBox[4];\n const level = vpcCBox[5];\n const bitDepth = vpcCBox[6] >> 4 & 0x0f;\n codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level) + '.' + addLeadingZero(bitDepth);\n }\n break;\n }\n case 'av01':\n {\n const av1CBox = findBox(sampleEntriesEnd, ['av1C'])[0];\n if (av1CBox && av1CBox.length > 2) {\n const profile = av1CBox[1] >>> 5;\n const level = av1CBox[1] & 0x1f;\n const tierFlag = av1CBox[2] >>> 7 ? 'H' : 'M';\n const highBitDepth = (av1CBox[2] & 0x40) >> 6;\n const twelveBit = (av1CBox[2] & 0x20) >> 5;\n const bitDepth = profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;\n const monochrome = (av1CBox[2] & 0x10) >> 4;\n const chromaSubsamplingX = (av1CBox[2] & 0x08) >> 3;\n const chromaSubsamplingY = (av1CBox[2] & 0x04) >> 2;\n const chromaSamplePosition = av1CBox[2] & 0x03;\n // TODO: parse color_description_present_flag\n // default it to BT.709/limited range for now\n // more info https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax\n const colorPrimaries = 1;\n const transferCharacteristics = 1;\n const matrixCoefficients = 1;\n const videoFullRangeFlag = 0;\n codec += '.' + profile + '.' + addLeadingZero(level) + tierFlag + '.' + addLeadingZero(bitDepth) + '.' + monochrome + '.' + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + '.' + addLeadingZero(colorPrimaries) + '.' + addLeadingZero(transferCharacteristics) + '.' + addLeadingZero(matrixCoefficients) + '.' + videoFullRangeFlag;\n supplemental = parseSupplementalDoViCodec('dav1', sampleEntriesEnd);\n }\n break;\n }\n }\n return {\n codec,\n encrypted,\n supplemental\n };\n}\nfunction parseSupplementalDoViCodec(fourCC, sampleEntriesEnd) {\n const dvvCResult = findBox(sampleEntriesEnd, ['dvvC']); // used by DoVi Profile 8 to 10\n const dvXCBox = dvvCResult.length ? dvvCResult[0] : findBox(sampleEntriesEnd, ['dvcC'])[0]; // used by DoVi Profiles up to 7 and 20\n if (dvXCBox) {\n const doViProfile = dvXCBox[2] >> 1 & 0x7f;\n const doViLevel = dvXCBox[2] << 5 & 0x20 | dvXCBox[3] >> 3 & 0x1f;\n return fourCC + '.' + addLeadingZero(doViProfile) + '.' + addLeadingZero(doViLevel);\n }\n}\nfunction skipBERInteger(bytes, i) {\n const limit = i + 5;\n while (bytes[i++] & 0x80 && i < limit) {\n /* do nothing */\n }\n return i;\n}\nfunction toHex(x) {\n return ('0' + x.toString(16).toUpperCase()).slice(-2);\n}\nfunction addLeadingZero(num) {\n return (num < 10 ? '0' : '') + num;\n}\nfunction patchEncyptionData(initSegment, decryptdata) {\n if (!initSegment || !decryptdata) {\n return initSegment;\n }\n const keyId = decryptdata.keyId;\n if (keyId && decryptdata.isCommonEncryption) {\n const traks = findBox(initSegment, ['moov', 'trak']);\n traks.forEach(trak => {\n const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];\n\n // skip the sample entry count\n const sampleEntries = stsd.subarray(8);\n let encBoxes = findBox(sampleEntries, ['enca']);\n const isAudio = encBoxes.length > 0;\n if (!isAudio) {\n encBoxes = findBox(sampleEntries, ['encv']);\n }\n encBoxes.forEach(enc => {\n const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);\n const sinfBoxes = findBox(encBoxChildren, ['sinf']);\n sinfBoxes.forEach(sinf => {\n const tenc = parseSinf(sinf);\n if (tenc) {\n // Look for default key id (keyID offset is always 8 within the tenc box):\n const tencKeyId = tenc.subarray(8, 24);\n if (!tencKeyId.some(b => b !== 0)) {\n logger.log(`[eme] Patching keyId in 'enc${isAudio ? 'a' : 'v'}>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(keyId)}`);\n tenc.set(keyId, 8);\n }\n }\n });\n });\n });\n }\n return initSegment;\n}\nfunction parseSinf(sinf) {\n const schm = findBox(sinf, ['schm'])[0];\n if (schm) {\n const scheme = bin2str(schm.subarray(4, 8));\n if (scheme === 'cbcs' || scheme === 'cenc') {\n return findBox(sinf, ['schi', 'tenc'])[0];\n }\n }\n return null;\n}\n\n/**\n * Determine the base media decode start time, in seconds, for an MP4\n * fragment. If multiple fragments are specified, the earliest time is\n * returned.\n *\n * The base media decode time can be parsed from track fragment\n * metadata:\n * ```\n * moof > traf > tfdt.baseMediaDecodeTime\n * ```\n * It requires the timescale value from the mdhd to interpret.\n *\n * @param initData - a hash of track type to timescale values\n * @param fmp4 - the bytes of the mp4 fragment\n * @returns the earliest base media decode start time for the\n * fragment, in seconds\n */\nfunction getStartDTS(initData, fmp4) {\n // we need info from two children of each track fragment box\n return findBox(fmp4, ['moof', 'traf']).reduce((result, traf) => {\n const tfdt = findBox(traf, ['tfdt'])[0];\n const version = tfdt[0];\n const start = findBox(traf, ['tfhd']).reduce((result, tfhd) => {\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (track) {\n let baseTime = readUint32(tfdt, 4);\n if (version === 1) {\n // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.\n // This prevents large values from being used for initPTS, which can cause playlist sync issues.\n // https://github.com/video-dev/hls.js/issues/5303\n if (baseTime === UINT32_MAX$1) {\n logger.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`);\n return result;\n }\n baseTime *= UINT32_MAX$1 + 1;\n baseTime += readUint32(tfdt, 8);\n }\n // assume a 90kHz clock if no timescale was specified\n const scale = track.timescale || 90e3;\n // convert base time to seconds\n const startTime = baseTime / scale;\n if (isFiniteNumber(startTime) && (result === null || startTime < result)) {\n return startTime;\n }\n }\n return result;\n }, null);\n if (start !== null && isFiniteNumber(start) && (result === null || start < result)) {\n return start;\n }\n return result;\n }, null);\n}\n\n/*\n For Reference:\n aligned(8) class TrackFragmentHeaderBox\n extends FullBox(‘tfhd’, 0, tf_flags){\n unsigned int(32) track_ID;\n // all the following are optional fields\n unsigned int(64) base_data_offset;\n unsigned int(32) sample_description_index;\n unsigned int(32) default_sample_duration;\n unsigned int(32) default_sample_size;\n unsigned int(32) default_sample_flags\n }\n */\nfunction getDuration(data, initData) {\n let rawDuration = 0;\n let videoDuration = 0;\n let audioDuration = 0;\n const trafs = findBox(data, ['moof', 'traf']);\n for (let i = 0; i < trafs.length; i++) {\n const traf = trafs[i];\n // There is only one tfhd & trun per traf\n // This is true for CMAF style content, and we should perhaps check the ftyp\n // and only look for a single trun then, but for ISOBMFF we should check\n // for multiple track runs.\n const tfhd = findBox(traf, ['tfhd'])[0];\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (!track) {\n continue;\n }\n const trackDefault = track.default;\n const tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);\n let sampleDuration = trackDefault == null ? void 0 : trackDefault.duration;\n if (tfhdFlags & 0x000008) {\n // 0x000008 indicates the presence of the default_sample_duration field\n if (tfhdFlags & 0x000002) {\n // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration\n // If present, the default_sample_duration exists at byte offset 12\n sampleDuration = readUint32(tfhd, 12);\n } else {\n // Otherwise, the duration is at byte offset 8\n sampleDuration = readUint32(tfhd, 8);\n }\n }\n // assume a 90kHz clock if no timescale was specified\n const timescale = track.timescale || 90e3;\n const truns = findBox(traf, ['trun']);\n for (let j = 0; j < truns.length; j++) {\n rawDuration = computeRawDurationFromSamples(truns[j]);\n if (!rawDuration && sampleDuration) {\n const sampleCount = readUint32(truns[j], 4);\n rawDuration = sampleDuration * sampleCount;\n }\n if (track.type === ElementaryStreamTypes.VIDEO) {\n videoDuration += rawDuration / timescale;\n } else if (track.type === ElementaryStreamTypes.AUDIO) {\n audioDuration += rawDuration / timescale;\n }\n }\n }\n if (videoDuration === 0 && audioDuration === 0) {\n // If duration samples are not available in the traf use sidx subsegment_duration\n let sidxMinStart = Infinity;\n let sidxMaxEnd = 0;\n let sidxDuration = 0;\n const sidxs = findBox(data, ['sidx']);\n for (let i = 0; i < sidxs.length; i++) {\n const sidx = parseSegmentIndex(sidxs[i]);\n if (sidx != null && sidx.references) {\n sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);\n const subSegmentDuration = sidx.references.reduce((dur, ref) => dur + ref.info.duration || 0, 0);\n sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);\n sidxDuration = sidxMaxEnd - sidxMinStart;\n }\n }\n if (sidxDuration && isFiniteNumber(sidxDuration)) {\n return sidxDuration;\n }\n }\n if (videoDuration) {\n return videoDuration;\n }\n return audioDuration;\n}\n\n/*\n For Reference:\n aligned(8) class TrackRunBox\n extends FullBox(‘trun’, version, tr_flags) {\n unsigned int(32) sample_count;\n // the following are optional fields\n signed int(32) data_offset;\n unsigned int(32) first_sample_flags;\n // all fields in the following array are optional\n {\n unsigned int(32) sample_duration;\n unsigned int(32) sample_size;\n unsigned int(32) sample_flags\n if (version == 0)\n { unsigned int(32)\n else\n { signed int(32)\n }[ sample_count ]\n }\n */\nfunction computeRawDurationFromSamples(trun) {\n const flags = readUint32(trun, 0);\n // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.\n // Each field is an int32, which is 4 bytes\n let offset = 8;\n // data-offset-present flag\n if (flags & 0x000001) {\n offset += 4;\n }\n // first-sample-flags-present flag\n if (flags & 0x000004) {\n offset += 4;\n }\n let duration = 0;\n const sampleCount = readUint32(trun, 4);\n for (let i = 0; i < sampleCount; i++) {\n // sample-duration-present flag\n if (flags & 0x000100) {\n const sampleDuration = readUint32(trun, offset);\n duration += sampleDuration;\n offset += 4;\n }\n // sample-size-present flag\n if (flags & 0x000200) {\n offset += 4;\n }\n // sample-flags-present flag\n if (flags & 0x000400) {\n offset += 4;\n }\n // sample-composition-time-offsets-present flag\n if (flags & 0x000800) {\n offset += 4;\n }\n }\n return duration;\n}\n\n// TODO: Remove `offsetStartDTS` in favor of using `timestampOffset` (issue #5715)\nfunction offsetStartDTS(initData, fmp4, timeOffset) {\n findBox(fmp4, ['moof', 'traf']).forEach(traf => {\n findBox(traf, ['tfhd']).forEach(tfhd => {\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (!track) {\n return;\n }\n // assume a 90kHz clock if no timescale was specified\n const timescale = track.timescale || 90e3;\n // get the base media decode time from the tfdt\n findBox(traf, ['tfdt']).forEach(tfdt => {\n const version = tfdt[0];\n const offset = timeOffset * timescale;\n if (offset) {\n let baseMediaDecodeTime = readUint32(tfdt, 4);\n if (version === 0) {\n baseMediaDecodeTime -= offset;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n writeUint32(tfdt, 4, baseMediaDecodeTime);\n } else {\n baseMediaDecodeTime *= Math.pow(2, 32);\n baseMediaDecodeTime += readUint32(tfdt, 8);\n baseMediaDecodeTime -= offset;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX$1 + 1));\n const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX$1 + 1));\n writeUint32(tfdt, 4, upper);\n writeUint32(tfdt, 8, lower);\n }\n }\n });\n });\n });\n}\n\n// TODO: Check if the last moof+mdat pair is part of the valid range\nfunction segmentValidRange(data) {\n const segmentedRange = {\n valid: null,\n remainder: null\n };\n const moofs = findBox(data, ['moof']);\n if (moofs.length < 2) {\n segmentedRange.remainder = data;\n return segmentedRange;\n }\n const last = moofs[moofs.length - 1];\n // Offset by 8 bytes; findBox offsets the start by as much\n segmentedRange.valid = data.slice(0, last.byteOffset - 8);\n segmentedRange.remainder = data.slice(last.byteOffset - 8);\n return segmentedRange;\n}\nfunction appendUint8Array(data1, data2) {\n const temp = new Uint8Array(data1.length + data2.length);\n temp.set(data1);\n temp.set(data2, data1.length);\n return temp;\n}\nfunction parseSamples(timeOffset, track) {\n const seiSamples = [];\n const videoData = track.samples;\n const timescale = track.timescale;\n const trackId = track.id;\n let isHEVCFlavor = false;\n const moofs = findBox(videoData, ['moof']);\n moofs.map(moof => {\n const moofOffset = moof.byteOffset - 8;\n const trafs = findBox(moof, ['traf']);\n trafs.map(traf => {\n // get the base media decode time from the tfdt\n const baseTime = findBox(traf, ['tfdt']).map(tfdt => {\n const version = tfdt[0];\n let result = readUint32(tfdt, 4);\n if (version === 1) {\n result *= Math.pow(2, 32);\n result += readUint32(tfdt, 8);\n }\n return result / timescale;\n })[0];\n if (baseTime !== undefined) {\n timeOffset = baseTime;\n }\n return findBox(traf, ['tfhd']).map(tfhd => {\n const id = readUint32(tfhd, 4);\n const tfhdFlags = readUint32(tfhd, 0) & 0xffffff;\n const baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;\n const sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;\n const defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;\n let defaultSampleDuration = 0;\n const defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;\n let defaultSampleSize = 0;\n const defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;\n let tfhdOffset = 8;\n if (id === trackId) {\n if (baseDataOffsetPresent) {\n tfhdOffset += 8;\n }\n if (sampleDescriptionIndexPresent) {\n tfhdOffset += 4;\n }\n if (defaultSampleDurationPresent) {\n defaultSampleDuration = readUint32(tfhd, tfhdOffset);\n tfhdOffset += 4;\n }\n if (defaultSampleSizePresent) {\n defaultSampleSize = readUint32(tfhd, tfhdOffset);\n tfhdOffset += 4;\n }\n if (defaultSampleFlagsPresent) {\n tfhdOffset += 4;\n }\n if (track.type === 'video') {\n isHEVCFlavor = isHEVC(track.codec);\n }\n findBox(traf, ['trun']).map(trun => {\n const version = trun[0];\n const flags = readUint32(trun, 0) & 0xffffff;\n const dataOffsetPresent = (flags & 0x000001) !== 0;\n let dataOffset = 0;\n const firstSampleFlagsPresent = (flags & 0x000004) !== 0;\n const sampleDurationPresent = (flags & 0x000100) !== 0;\n let sampleDuration = 0;\n const sampleSizePresent = (flags & 0x000200) !== 0;\n let sampleSize = 0;\n const sampleFlagsPresent = (flags & 0x000400) !== 0;\n const sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;\n let compositionOffset = 0;\n const sampleCount = readUint32(trun, 4);\n let trunOffset = 8; // past version, flags, and sample count\n\n if (dataOffsetPresent) {\n dataOffset = readUint32(trun, trunOffset);\n trunOffset += 4;\n }\n if (firstSampleFlagsPresent) {\n trunOffset += 4;\n }\n let sampleOffset = dataOffset + moofOffset;\n for (let ix = 0; ix < sampleCount; ix++) {\n if (sampleDurationPresent) {\n sampleDuration = readUint32(trun, trunOffset);\n trunOffset += 4;\n } else {\n sampleDuration = defaultSampleDuration;\n }\n if (sampleSizePresent) {\n sampleSize = readUint32(trun, trunOffset);\n trunOffset += 4;\n } else {\n sampleSize = defaultSampleSize;\n }\n if (sampleFlagsPresent) {\n trunOffset += 4;\n }\n if (sampleCompositionOffsetsPresent) {\n if (version === 0) {\n compositionOffset = readUint32(trun, trunOffset);\n } else {\n compositionOffset = readSint32(trun, trunOffset);\n }\n trunOffset += 4;\n }\n if (track.type === ElementaryStreamTypes.VIDEO) {\n let naluTotalSize = 0;\n while (naluTotalSize < sampleSize) {\n const naluSize = readUint32(videoData, sampleOffset);\n sampleOffset += 4;\n if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {\n const data = videoData.subarray(sampleOffset, sampleOffset + naluSize);\n parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);\n }\n sampleOffset += naluSize;\n naluTotalSize += naluSize + 4;\n }\n }\n timeOffset += sampleDuration / timescale;\n }\n });\n }\n });\n });\n });\n return seiSamples;\n}\nfunction isHEVC(codec) {\n if (!codec) {\n return false;\n }\n const baseCodec = codec.substring(0, 4);\n return baseCodec === 'hvc1' || baseCodec === 'hev1' ||\n // Dolby Vision\n baseCodec === 'dvh1' || baseCodec === 'dvhe';\n}\nfunction isSEIMessage(isHEVCFlavor, naluHeader) {\n if (isHEVCFlavor) {\n const naluType = naluHeader >> 1 & 0x3f;\n return naluType === 39 || naluType === 40;\n } else {\n const naluType = naluHeader & 0x1f;\n return naluType === 6;\n }\n}\nfunction parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {\n const data = discardEPB(unescapedData);\n let seiPtr = 0;\n // skip nal header\n seiPtr += headerSize;\n let payloadType = 0;\n let payloadSize = 0;\n let b = 0;\n while (seiPtr < data.length) {\n payloadType = 0;\n do {\n if (seiPtr >= data.length) {\n break;\n }\n b = data[seiPtr++];\n payloadType += b;\n } while (b === 0xff);\n\n // Parse payload size.\n payloadSize = 0;\n do {\n if (seiPtr >= data.length) {\n break;\n }\n b = data[seiPtr++];\n payloadSize += b;\n } while (b === 0xff);\n const leftOver = data.length - seiPtr;\n // Create a variable to process the payload\n let payPtr = seiPtr;\n\n // Increment the seiPtr to the end of the payload\n if (payloadSize < leftOver) {\n seiPtr += payloadSize;\n } else if (payloadSize > leftOver) {\n // Some type of corruption has happened?\n logger.error(`Malformed SEI payload. ${payloadSize} is too small, only ${leftOver} bytes left to parse.`);\n // We might be able to parse some data, but let's be safe and ignore it.\n break;\n }\n if (payloadType === 4) {\n const countryCode = data[payPtr++];\n if (countryCode === 181) {\n const providerCode = readUint16(data, payPtr);\n payPtr += 2;\n if (providerCode === 49) {\n const userStructure = readUint32(data, payPtr);\n payPtr += 4;\n if (userStructure === 0x47413934) {\n const userDataType = data[payPtr++];\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n const firstByte = data[payPtr++];\n const totalCCs = 0x1f & firstByte;\n const enabled = 0x40 & firstByte;\n const totalBytes = enabled ? 2 + totalCCs * 3 : 0;\n const byteArray = new Uint8Array(totalBytes);\n if (enabled) {\n byteArray[0] = firstByte;\n for (let i = 1; i < totalBytes; i++) {\n byteArray[i] = data[payPtr++];\n }\n }\n samples.push({\n type: userDataType,\n payloadType,\n pts,\n bytes: byteArray\n });\n }\n }\n }\n }\n } else if (payloadType === 5) {\n if (payloadSize > 16) {\n const uuidStrArray = [];\n for (let i = 0; i < 16; i++) {\n const _b = data[payPtr++].toString(16);\n uuidStrArray.push(_b.length == 1 ? '0' + _b : _b);\n if (i === 3 || i === 5 || i === 7 || i === 9) {\n uuidStrArray.push('-');\n }\n }\n const length = payloadSize - 16;\n const userDataBytes = new Uint8Array(length);\n for (let i = 0; i < length; i++) {\n userDataBytes[i] = data[payPtr++];\n }\n samples.push({\n payloadType,\n pts,\n uuid: uuidStrArray.join(''),\n userData: utf8ArrayToStr(userDataBytes),\n userDataBytes\n });\n }\n }\n }\n}\n\n/**\n * remove Emulation Prevention bytes from a RBSP\n */\nfunction discardEPB(data) {\n const length = data.byteLength;\n const EPBPositions = [];\n let i = 1;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {\n EPBPositions.push(i + 2);\n i += 2;\n } else {\n i++;\n }\n }\n\n // If no Emulation Prevention Bytes were found just return the original\n // array\n if (EPBPositions.length === 0) {\n return data;\n }\n\n // Create a new array to hold the NAL unit data\n const newLength = length - EPBPositions.length;\n const newData = new Uint8Array(newLength);\n let sourceIndex = 0;\n for (i = 0; i < newLength; sourceIndex++, i++) {\n if (sourceIndex === EPBPositions[0]) {\n // Skip this byte\n sourceIndex++;\n // Remove this position index\n EPBPositions.shift();\n }\n newData[i] = data[sourceIndex];\n }\n return newData;\n}\nfunction parseEmsg(data) {\n const version = data[0];\n let schemeIdUri = '';\n let value = '';\n let timeScale = 0;\n let presentationTimeDelta = 0;\n let presentationTime = 0;\n let eventDuration = 0;\n let id = 0;\n let offset = 0;\n if (version === 0) {\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n timeScale = readUint32(data, 12);\n presentationTimeDelta = readUint32(data, 16);\n eventDuration = readUint32(data, 20);\n id = readUint32(data, 24);\n offset = 28;\n } else if (version === 1) {\n offset += 4;\n timeScale = readUint32(data, offset);\n offset += 4;\n const leftPresentationTime = readUint32(data, offset);\n offset += 4;\n const rightPresentationTime = readUint32(data, offset);\n offset += 4;\n presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;\n if (!isSafeInteger(presentationTime)) {\n presentationTime = Number.MAX_SAFE_INTEGER;\n logger.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');\n }\n eventDuration = readUint32(data, offset);\n offset += 4;\n id = readUint32(data, offset);\n offset += 4;\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n const payload = data.subarray(offset, data.byteLength);\n return {\n schemeIdUri,\n value,\n timeScale,\n presentationTime,\n presentationTimeDelta,\n eventDuration,\n id,\n payload\n };\n}\nfunction mp4Box(type, ...payload) {\n const len = payload.length;\n let size = 8;\n let i = len;\n while (i--) {\n size += payload[i].byteLength;\n }\n const result = new Uint8Array(size);\n result[0] = size >> 24 & 0xff;\n result[1] = size >> 16 & 0xff;\n result[2] = size >> 8 & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n for (i = 0, size = 8; i < len; i++) {\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n}\nfunction mp4pssh(systemId, keyids, data) {\n if (systemId.byteLength !== 16) {\n throw new RangeError('Invalid system id');\n }\n let version;\n let kids;\n {\n version = 0;\n kids = new Uint8Array();\n }\n let kidCount;\n if (version > 0) {\n kidCount = new Uint8Array(4);\n if (keyids.length > 0) {\n new DataView(kidCount.buffer).setUint32(0, keyids.length, false);\n }\n } else {\n kidCount = new Uint8Array();\n }\n const dataSize = new Uint8Array(4);\n if (data && data.byteLength > 0) {\n new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);\n }\n return mp4Box([112, 115, 115, 104], new Uint8Array([version, 0x00, 0x00, 0x00 // Flags\n ]), systemId,\n // 16 bytes\n kidCount, kids, dataSize, data || new Uint8Array());\n}\nfunction parseMultiPssh(initData) {\n const results = [];\n if (initData instanceof ArrayBuffer) {\n const length = initData.byteLength;\n let offset = 0;\n while (offset + 32 < length) {\n const view = new DataView(initData, offset);\n const pssh = parsePssh(view);\n results.push(pssh);\n offset += pssh.size;\n }\n }\n return results;\n}\nfunction parsePssh(view) {\n const size = view.getUint32(0);\n const offset = view.byteOffset;\n const length = view.byteLength;\n if (length < size) {\n return {\n offset,\n size: length\n };\n }\n const type = view.getUint32(4);\n if (type !== 0x70737368) {\n return {\n offset,\n size\n };\n }\n const version = view.getUint32(8) >>> 24;\n if (version !== 0 && version !== 1) {\n return {\n offset,\n size\n };\n }\n const buffer = view.buffer;\n const systemId = Hex.hexDump(new Uint8Array(buffer, offset + 12, 16));\n const dataSizeOrKidCount = view.getUint32(28);\n let kids = null;\n let data = null;\n if (version === 0) {\n if (size - 32 < dataSizeOrKidCount || dataSizeOrKidCount < 22) {\n return {\n offset,\n size\n };\n }\n data = new Uint8Array(buffer, offset + 32, dataSizeOrKidCount);\n } else if (version === 1) {\n if (!dataSizeOrKidCount || length < offset + 32 + dataSizeOrKidCount * 16 + 16) {\n return {\n offset,\n size\n };\n }\n kids = [];\n for (let i = 0; i < dataSizeOrKidCount; i++) {\n kids.push(new Uint8Array(buffer, offset + 32 + i * 16, 16));\n }\n }\n return {\n version,\n systemId,\n kids,\n data,\n offset,\n size\n };\n}\n\nconst userAgentHevcSupportIsInaccurate = () => {\n return /\\(Windows.+Firefox\\//i.test(navigator.userAgent);\n};\n\n// from http://mp4ra.org/codecs.html\n// values indicate codec selection preference (lower is higher priority)\nconst sampleEntryCodesISO = {\n audio: {\n a3ds: 1,\n 'ac-3': 0.95,\n 'ac-4': 1,\n alac: 0.9,\n alaw: 1,\n dra1: 1,\n 'dts+': 1,\n 'dts-': 1,\n dtsc: 1,\n dtse: 1,\n dtsh: 1,\n 'ec-3': 0.9,\n enca: 1,\n fLaC: 0.9,\n // MP4-RA listed codec entry for FLAC\n flac: 0.9,\n // legacy browser codec name for FLAC\n FLAC: 0.9,\n // some manifests may list \"FLAC\" with Apple's tools\n g719: 1,\n g726: 1,\n m4ae: 1,\n mha1: 1,\n mha2: 1,\n mhm1: 1,\n mhm2: 1,\n mlpa: 1,\n mp4a: 1,\n 'raw ': 1,\n Opus: 1,\n opus: 1,\n // browsers expect this to be lowercase despite MP4RA says 'Opus'\n samr: 1,\n sawb: 1,\n sawp: 1,\n sevc: 1,\n sqcp: 1,\n ssmv: 1,\n twos: 1,\n ulaw: 1\n },\n video: {\n avc1: 1,\n avc2: 1,\n avc3: 1,\n avc4: 1,\n avcp: 1,\n av01: 0.8,\n dav1: 0.8,\n drac: 1,\n dva1: 1,\n dvav: 1,\n dvh1: 0.7,\n dvhe: 0.7,\n encv: 1,\n hev1: 0.75,\n hvc1: 0.75,\n mjp2: 1,\n mp4v: 1,\n mvc1: 1,\n mvc2: 1,\n mvc3: 1,\n mvc4: 1,\n resv: 1,\n rv60: 1,\n s263: 1,\n svc1: 1,\n svc2: 1,\n 'vc-1': 1,\n vp08: 1,\n vp09: 0.9\n },\n text: {\n stpp: 1,\n wvtt: 1\n }\n};\nfunction isCodecType(codec, type) {\n const typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && !!typeCodes[codec.slice(0, 4)];\n}\nfunction areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource = true) {\n return !codecs.split(',').some(codec => !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource));\n}\nfunction isCodecMediaSourceSupported(codec, type, preferManagedMediaSource = true) {\n var _MediaSource$isTypeSu;\n const MediaSource = getMediaSource(preferManagedMediaSource);\n return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;\n}\nfunction mimeTypeForCodec(codec, type) {\n return `${type}/mp4;codecs=${codec}`;\n}\nfunction videoCodecPreferenceValue(videoCodec) {\n if (videoCodec) {\n const fourCC = videoCodec.substring(0, 4);\n return sampleEntryCodesISO.video[fourCC];\n }\n return 2;\n}\nfunction codecsSetSelectionPreferenceValue(codecSet) {\n const limitedHevcSupport = userAgentHevcSupportIsInaccurate();\n return codecSet.split(',').reduce((num, fourCC) => {\n const lowerPriority = limitedHevcSupport && isHEVC(fourCC);\n const preferenceValue = lowerPriority ? 9 : sampleEntryCodesISO.video[fourCC];\n if (preferenceValue) {\n return (preferenceValue * 2 + num) / (num ? 3 : 2);\n }\n return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);\n }, 0);\n}\nconst CODEC_COMPATIBLE_NAMES = {};\nfunction getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource = true) {\n if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {\n return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];\n }\n const codecsToCheck = {\n // Idealy fLaC and Opus would be first (spec-compliant) but\n // some browsers will report that fLaC is supported then fail.\n // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728\n flac: ['flac', 'fLaC', 'FLAC'],\n opus: ['opus', 'Opus'],\n // Replace audio codec info if browser does not support mp4a.40.34,\n // and demuxer can fallback to 'audio/mpeg' or 'audio/mp4;codecs=\"mp3\"'\n 'mp4a.40.34': ['mp3']\n }[lowerCaseCodec];\n for (let i = 0; i < codecsToCheck.length; i++) {\n var _getMediaSource;\n if (isCodecMediaSourceSupported(codecsToCheck[i], 'audio', preferManagedMediaSource)) {\n CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];\n return codecsToCheck[i];\n } else if (codecsToCheck[i] === 'mp3' && (_getMediaSource = getMediaSource(preferManagedMediaSource)) != null && _getMediaSource.isTypeSupported('audio/mpeg')) {\n return '';\n }\n }\n return lowerCaseCodec;\n}\nconst AUDIO_CODEC_REGEXP = /flac|opus|mp4a\\.40\\.34/i;\nfunction getCodecCompatibleName(codec, preferManagedMediaSource = true) {\n return codec.replace(AUDIO_CODEC_REGEXP, m => getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource));\n}\nfunction replaceVideoCodec(originalCodecs, newVideoCodec) {\n const codecs = [];\n if (originalCodecs) {\n const allCodecs = originalCodecs.split(',');\n for (let i = 0; i < allCodecs.length; i++) {\n if (!isCodecType(allCodecs[i], 'video')) {\n codecs.push(allCodecs[i]);\n }\n }\n }\n if (newVideoCodec) {\n codecs.push(newVideoCodec);\n }\n return codecs.join(',');\n}\nfunction pickMostCompleteCodecName(parsedCodec, levelCodec) {\n // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a\n // so use level codec is parsed codec is unavailable or incomplete\n if (parsedCodec && (parsedCodec.length > 4 || ['ac-3', 'ec-3', 'alac', 'fLaC', 'Opus'].indexOf(parsedCodec) !== -1)) {\n return parsedCodec;\n }\n if (levelCodec) {\n const levelCodecs = levelCodec.split(',');\n if (levelCodecs.length > 1) {\n if (parsedCodec) {\n for (let i = levelCodecs.length; i--;) {\n if (levelCodecs[i].substring(0, 4) === parsedCodec.substring(0, 4)) {\n return levelCodecs[i];\n }\n }\n }\n return levelCodecs[0];\n }\n }\n return levelCodec || parsedCodec;\n}\nfunction convertAVC1ToAVCOTI(videoCodecs) {\n // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported\n // Examples: avc1.66.30 to avc1.42001e and avc1.77.30,avc1.66.30 to avc1.4d001e,avc1.42001e.\n const codecs = videoCodecs.split(',');\n for (let i = 0; i < codecs.length; i++) {\n const avcdata = codecs[i].split('.');\n if (avcdata.length > 2) {\n let result = avcdata.shift() + '.';\n result += parseInt(avcdata.shift()).toString(16);\n result += ('000' + parseInt(avcdata.shift()).toString(16)).slice(-4);\n codecs[i] = result;\n }\n }\n return codecs.join(',');\n}\nfunction fillInMissingAV01Params(videoCodec) {\n // Used to fill in incomplete AV1 playlist CODECS strings for mediaCapabilities.decodingInfo queries\n if (videoCodec.startsWith('av01.')) {\n const av1params = videoCodec.split('.');\n const placeholders = ['0', '111', '01', '01', '01', '0'];\n for (let i = av1params.length; i > 4 && i < 10; i++) {\n av1params[i] = placeholders[i - 4];\n }\n return av1params.join('.');\n }\n return videoCodec;\n}\nfunction getM2TSSupportedAudioTypes(preferManagedMediaSource) {\n const MediaSource = getMediaSource(preferManagedMediaSource) || {\n isTypeSupported: () => false\n };\n return {\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"'),\n ac3: MediaSource.isTypeSupported('audio/mp4; codecs=\"ac-3\"') \n };\n}\nfunction getCodecsForMimeType(mimeType) {\n return mimeType.replace(/^.+codecs=[\"']?([^\"']+).*$/, '$1');\n}\n\nconst SUPPORTED_INFO_DEFAULT = {\n supported: true,\n configurations: [],\n decodingInfoResults: [{\n supported: true,\n powerEfficient: true,\n smooth: true\n }]\n};\nfunction getUnsupportedResult(error, configurations) {\n return {\n supported: false,\n configurations,\n decodingInfoResults: [{\n supported: false,\n smooth: false,\n powerEfficient: false\n }],\n error\n };\n}\nconst SUPPORTED_INFO_CACHE = {};\nfunction requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) {\n // Only test support when configuration is exceeds minimum options\n const audioGroups = level.audioCodec ? level.audioGroups : null;\n const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;\n const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;\n const maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2;\n let audioChannels = null;\n if (audioGroups != null && audioGroups.length) {\n try {\n if (audioGroups.length === 1 && audioGroups[0]) {\n audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;\n } else {\n audioChannels = audioGroups.reduce((acc, groupId) => {\n if (groupId) {\n const audioTrackGroup = audioTracksByGroup.groups[groupId];\n if (!audioTrackGroup) {\n throw new Error(`Audio track group ${groupId} not found`);\n }\n // Sum all channel key values\n Object.keys(audioTrackGroup.channels).forEach(key => {\n acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];\n });\n }\n return acc;\n }, {\n 2: 0\n });\n }\n } catch (error) {\n return true;\n }\n }\n return level.videoCodec !== undefined && (level.width > 1920 && level.height > 1088 || level.height > 1920 && level.width > 1088 || level.frameRate > Math.max(currentFrameRate, 30) || level.videoRange !== 'SDR' && level.videoRange !== currentVideoRange || level.bitrate > Math.max(currentBw, 8e6)) || !!audioChannels && isFiniteNumber(maxChannels) && Object.keys(audioChannels).some(channels => parseInt(channels) > maxChannels);\n}\nfunction getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities) {\n const videoCodecs = level.videoCodec;\n const audioCodecs = level.audioCodec;\n if (!videoCodecs && !audioCodecs || !mediaCapabilities) {\n return Promise.resolve(SUPPORTED_INFO_DEFAULT);\n }\n const configurations = [];\n if (videoCodecs) {\n const baseVideoConfiguration = {\n width: level.width,\n height: level.height,\n bitrate: Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate)),\n // Assume a framerate of 30fps since MediaCapabilities will not accept Level default of 0.\n framerate: level.frameRate || 30\n };\n const videoRange = level.videoRange;\n if (videoRange !== 'SDR') {\n baseVideoConfiguration.transferFunction = videoRange.toLowerCase();\n }\n const videoCodecsArray = videoCodecs.split(',');\n // Override Windows Firefox HEVC MediaCapabilities result (https://github.com/video-dev/hls.js/issues/7046)\n const ua = navigator.userAgent;\n if (videoCodecsArray.some(videoCodec => isHEVC(videoCodec)) && userAgentHevcSupportIsInaccurate()) {\n return Promise.resolve(getUnsupportedResult(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent sting: (${ua})`), configurations));\n }\n configurations.push.apply(configurations, videoCodecsArray.map(videoCodec => ({\n type: 'media-source',\n video: _objectSpread2(_objectSpread2({}, baseVideoConfiguration), {}, {\n contentType: mimeTypeForCodec(fillInMissingAV01Params(videoCodec), 'video')\n })\n })));\n }\n if (audioCodecs && level.audioGroups) {\n level.audioGroups.forEach(audioGroupId => {\n var _audioTracksByGroup$g;\n if (!audioGroupId) {\n return;\n }\n (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks.forEach(audioTrack => {\n if (audioTrack.groupId === audioGroupId) {\n const channels = audioTrack.channels || '';\n const channelsNumber = parseFloat(channels);\n if (isFiniteNumber(channelsNumber) && channelsNumber > 2) {\n configurations.push.apply(configurations, audioCodecs.split(',').map(audioCodec => ({\n type: 'media-source',\n audio: {\n contentType: mimeTypeForCodec(audioCodec, 'audio'),\n channels: '' + channelsNumber\n // spatialRendering:\n // audioCodec === 'ec-3' && channels.indexOf('JOC'),\n }\n })));\n }\n }\n });\n });\n }\n return Promise.all(configurations.map(configuration => {\n // Cache MediaCapabilities promises\n const decodingInfoKey = getMediaDecodingInfoKey(configuration);\n return SUPPORTED_INFO_CACHE[decodingInfoKey] || (SUPPORTED_INFO_CACHE[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));\n })).then(decodingInfoResults => ({\n supported: !decodingInfoResults.some(info => !info.supported),\n configurations,\n decodingInfoResults\n })).catch(error => ({\n supported: false,\n configurations,\n decodingInfoResults: [],\n error\n }));\n}\nfunction getMediaDecodingInfoKey(config) {\n const {\n audio,\n video\n } = config;\n const mediaConfig = video || audio;\n if (mediaConfig) {\n const codec = getCodecsForMimeType(mediaConfig.contentType);\n if (video) {\n return `r${video.height}x${video.width}f${Math.ceil(video.framerate)}${video.transferFunction || 'sd'}_${codec}_${Math.ceil(video.bitrate / 1e5)}`;\n }\n if (audio) {\n return `c${audio.channels}${audio.spatialRendering ? 's' : 'n'}_${codec}`;\n }\n }\n return '';\n}\n\nconst HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null];\nfunction isHdcpLevel(value) {\n return HdcpLevels.indexOf(value) > -1;\n}\nconst VideoRangeValues = ['SDR', 'PQ', 'HLG'];\nfunction isVideoRange(value) {\n return !!value && VideoRangeValues.indexOf(value) > -1;\n}\nvar HlsSkip = {\n No: \"\",\n Yes: \"YES\",\n v2: \"v2\"\n};\nfunction getSkipValue(details) {\n const {\n canSkipUntil,\n canSkipDateRanges,\n age\n } = details;\n // A Client SHOULD NOT request a Playlist Delta Update unless it already\n // has a version of the Playlist that is no older than one-half of the Skip Boundary.\n // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7\n const playlistRecentEnough = age < canSkipUntil / 2;\n if (canSkipUntil && playlistRecentEnough) {\n if (canSkipDateRanges) {\n return HlsSkip.v2;\n }\n return HlsSkip.Yes;\n }\n return HlsSkip.No;\n}\nclass HlsUrlParameters {\n constructor(msn, part, skip) {\n this.msn = void 0;\n this.part = void 0;\n this.skip = void 0;\n this.msn = msn;\n this.part = part;\n this.skip = skip;\n }\n addDirectives(uri) {\n const url = new self.URL(uri);\n if (this.msn !== undefined) {\n url.searchParams.set('_HLS_msn', this.msn.toString());\n }\n if (this.part !== undefined) {\n url.searchParams.set('_HLS_part', this.part.toString());\n }\n if (this.skip) {\n url.searchParams.set('_HLS_skip', this.skip);\n }\n return url.href;\n }\n}\nclass Level {\n constructor(data) {\n this._attrs = void 0;\n this.audioCodec = void 0;\n this.bitrate = void 0;\n this.codecSet = void 0;\n this.url = void 0;\n this.frameRate = void 0;\n this.height = void 0;\n this.id = void 0;\n this.name = void 0;\n this.supplemental = void 0;\n this.videoCodec = void 0;\n this.width = void 0;\n this.details = void 0;\n this.fragmentError = 0;\n this.loadError = 0;\n this.loaded = void 0;\n this.realBitrate = 0;\n this.supportedPromise = void 0;\n this.supportedResult = void 0;\n this._avgBitrate = 0;\n this._audioGroups = void 0;\n this._subtitleGroups = void 0;\n // Deprecated (retained for backwards compatibility)\n this._urlId = 0;\n this.url = [data.url];\n this._attrs = [data.attrs];\n this.bitrate = data.bitrate;\n if (data.details) {\n this.details = data.details;\n }\n this.id = data.id || 0;\n this.name = data.name;\n this.width = data.width || 0;\n this.height = data.height || 0;\n this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);\n this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');\n this.audioCodec = data.audioCodec;\n this.videoCodec = data.videoCodec;\n this.codecSet = [data.videoCodec, data.audioCodec].filter(c => !!c).map(s => s.substring(0, 4)).join(',');\n if ('supplemental' in data) {\n var _data$supplemental;\n this.supplemental = data.supplemental;\n const supplementalVideo = (_data$supplemental = data.supplemental) == null ? void 0 : _data$supplemental.videoCodec;\n if (supplementalVideo && supplementalVideo !== data.videoCodec) {\n this.codecSet += `,${supplementalVideo.substring(0, 4)}`;\n }\n }\n this.addGroupId('audio', data.attrs.AUDIO);\n this.addGroupId('text', data.attrs.SUBTITLES);\n }\n get maxBitrate() {\n return Math.max(this.realBitrate, this.bitrate);\n }\n get averageBitrate() {\n return this._avgBitrate || this.realBitrate || this.bitrate;\n }\n get attrs() {\n return this._attrs[0];\n }\n get codecs() {\n return this.attrs.CODECS || '';\n }\n get pathwayId() {\n return this.attrs['PATHWAY-ID'] || '.';\n }\n get videoRange() {\n return this.attrs['VIDEO-RANGE'] || 'SDR';\n }\n get score() {\n return this.attrs.optionalFloat('SCORE', 0);\n }\n get uri() {\n return this.url[0] || '';\n }\n hasAudioGroup(groupId) {\n return hasGroup(this._audioGroups, groupId);\n }\n hasSubtitleGroup(groupId) {\n return hasGroup(this._subtitleGroups, groupId);\n }\n get audioGroups() {\n return this._audioGroups;\n }\n get subtitleGroups() {\n return this._subtitleGroups;\n }\n addGroupId(type, groupId) {\n if (!groupId) {\n return;\n }\n if (type === 'audio') {\n let audioGroups = this._audioGroups;\n if (!audioGroups) {\n audioGroups = this._audioGroups = [];\n }\n if (audioGroups.indexOf(groupId) === -1) {\n audioGroups.push(groupId);\n }\n } else if (type === 'text') {\n let subtitleGroups = this._subtitleGroups;\n if (!subtitleGroups) {\n subtitleGroups = this._subtitleGroups = [];\n }\n if (subtitleGroups.indexOf(groupId) === -1) {\n subtitleGroups.push(groupId);\n }\n }\n }\n\n // Deprecated methods (retained for backwards compatibility)\n get urlId() {\n return 0;\n }\n set urlId(value) {}\n get audioGroupIds() {\n return this.audioGroups ? [this.audioGroupId] : undefined;\n }\n get textGroupIds() {\n return this.subtitleGroups ? [this.textGroupId] : undefined;\n }\n get audioGroupId() {\n var _this$audioGroups;\n return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];\n }\n get textGroupId() {\n var _this$subtitleGroups;\n return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];\n }\n addFallback() {}\n}\nfunction hasGroup(groups, groupId) {\n if (!groupId || !groups) {\n return false;\n }\n return groups.indexOf(groupId) !== -1;\n}\n\n/**\n * @returns Whether we can detect and validate HDR capability within the window context\n */\nfunction isHdrSupported() {\n if (typeof matchMedia === 'function') {\n const mediaQueryList = matchMedia('(dynamic-range: high)');\n const badQuery = matchMedia('bad query');\n if (mediaQueryList.media !== badQuery.media) {\n return mediaQueryList.matches === true;\n }\n }\n return false;\n}\n\n/**\n * Sanitizes inputs to return the active video selection options for HDR/SDR.\n * When both inputs are null:\n *\n * `{ preferHDR: false, allowedVideoRanges: [] }`\n *\n * When `currentVideoRange` non-null, maintain the active range:\n *\n * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`\n *\n * When VideoSelectionOption non-null:\n *\n * - Allow all video ranges if `allowedVideoRanges` unspecified.\n * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.\n * - Else check window for HDR support and set `preferHDR` to the result.\n *\n * @param currentVideoRange\n * @param videoPreference\n */\nfunction getVideoSelectionOptions(currentVideoRange, videoPreference) {\n let preferHDR = false;\n let allowedVideoRanges = [];\n if (currentVideoRange) {\n preferHDR = currentVideoRange !== 'SDR';\n allowedVideoRanges = [currentVideoRange];\n }\n if (videoPreference) {\n allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);\n const allowAutoPreferHDR = allowedVideoRanges.join('') !== 'SDR' && !videoPreference.videoCodec;\n preferHDR = videoPreference.preferHDR !== undefined ? videoPreference.preferHDR : allowAutoPreferHDR && isHdrSupported();\n if (!preferHDR) {\n allowedVideoRanges = ['SDR'];\n }\n }\n return {\n preferHDR,\n allowedVideoRanges\n };\n}\n\nconst omitCircularRefsReplacer = replacer => {\n const known = new WeakSet();\n return (_, value) => {\n if (replacer) {\n value = replacer(_, value);\n }\n if (typeof value === 'object' && value !== null) {\n if (known.has(value)) {\n return;\n }\n known.add(value);\n }\n return value;\n };\n};\nconst stringify = (object, replacer) => JSON.stringify(object, omitCircularRefsReplacer(replacer));\n\nfunction getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {\n const codecSets = Object.keys(codecTiers);\n const channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;\n const audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;\n const videoCodecPreference = videoPreference == null ? void 0 : videoPreference.videoCodec;\n const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;\n // Use first level set to determine stereo, and minimum resolution and framerate\n let hasStereo = false;\n let hasCurrentVideoRange = false;\n let minHeight = Infinity;\n let minFramerate = Infinity;\n let minBitrate = Infinity;\n let minIndex = Infinity;\n let selectedScore = 0;\n let videoRanges = [];\n const {\n preferHDR,\n allowedVideoRanges\n } = getVideoSelectionOptions(currentVideoRange, videoPreference);\n for (let i = codecSets.length; i--;) {\n const tier = codecTiers[codecSets[i]];\n hasStereo || (hasStereo = tier.channels[2] > 0);\n minHeight = Math.min(minHeight, tier.minHeight);\n minFramerate = Math.min(minFramerate, tier.minFramerate);\n minBitrate = Math.min(minBitrate, tier.minBitrate);\n const matchingVideoRanges = allowedVideoRanges.filter(range => tier.videoRanges[range] > 0);\n if (matchingVideoRanges.length > 0) {\n hasCurrentVideoRange = true;\n }\n }\n minHeight = isFiniteNumber(minHeight) ? minHeight : 0;\n minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;\n const maxHeight = Math.max(1080, minHeight);\n const maxFramerate = Math.max(30, minFramerate);\n minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;\n currentBw = Math.max(minBitrate, currentBw);\n // If there are no variants with matching preference, set currentVideoRange to undefined\n if (!hasCurrentVideoRange) {\n currentVideoRange = undefined;\n }\n const hasMultipleSets = codecSets.length > 1;\n const codecSet = codecSets.reduce((selected, candidate) => {\n // Remove candiates which do not meet bitrate, default audio, stereo or channels preference, 1080p or lower, 30fps or lower, or SDR/HDR selection if present\n const candidateTier = codecTiers[candidate];\n if (candidate === selected) {\n return selected;\n }\n videoRanges = hasCurrentVideoRange ? allowedVideoRanges.filter(range => candidateTier.videoRanges[range] > 0) : [];\n if (hasMultipleSets) {\n if (candidateTier.minBitrate > currentBw) {\n logStartCodecCandidateIgnored(candidate, `min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`);\n return selected;\n }\n if (!candidateTier.hasDefaultAudio) {\n logStartCodecCandidateIgnored(candidate, `no renditions with default or auto-select sound found`);\n return selected;\n }\n if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {\n logStartCodecCandidateIgnored(candidate, `audio codec preference \"${audioCodecPreference}\" not found`);\n return selected;\n }\n if (channelsPreference && !preferStereo) {\n if (!candidateTier.channels[channelsPreference]) {\n logStartCodecCandidateIgnored(candidate, `no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(candidateTier.channels)})`);\n return selected;\n }\n } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels['2'] === 0) {\n logStartCodecCandidateIgnored(candidate, `no renditions with stereo sound found`);\n return selected;\n }\n if (candidateTier.minHeight > maxHeight) {\n logStartCodecCandidateIgnored(candidate, `min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`);\n return selected;\n }\n if (candidateTier.minFramerate > maxFramerate) {\n logStartCodecCandidateIgnored(candidate, `min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`);\n return selected;\n }\n if (!videoRanges.some(range => candidateTier.videoRanges[range] > 0)) {\n logStartCodecCandidateIgnored(candidate, `no variants with VIDEO-RANGE of ${stringify(videoRanges)} found`);\n return selected;\n }\n if (videoCodecPreference && candidate.indexOf(videoCodecPreference.substring(0, 4)) % 5 !== 0) {\n logStartCodecCandidateIgnored(candidate, `video codec preference \"${videoCodecPreference}\" not found`);\n return selected;\n }\n if (candidateTier.maxScore < selectedScore) {\n logStartCodecCandidateIgnored(candidate, `max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`);\n return selected;\n }\n }\n // Remove candiates with less preferred codecs or more errors\n if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {\n return selected;\n }\n minIndex = candidateTier.minIndex;\n selectedScore = candidateTier.maxScore;\n return candidate;\n }, undefined);\n return {\n codecSet,\n videoRanges,\n preferHDR,\n minFramerate,\n minBitrate,\n minIndex\n };\n}\nfunction logStartCodecCandidateIgnored(codeSet, reason) {\n logger.log(`[abr] start candidates with \"${codeSet}\" ignored because ${reason}`);\n}\nfunction getAudioTracksByGroup(allAudioTracks) {\n return allAudioTracks.reduce((audioTracksByGroup, track) => {\n let trackGroup = audioTracksByGroup.groups[track.groupId];\n if (!trackGroup) {\n trackGroup = audioTracksByGroup.groups[track.groupId] = {\n tracks: [],\n channels: {\n 2: 0\n },\n hasDefault: false,\n hasAutoSelect: false\n };\n }\n trackGroup.tracks.push(track);\n const channelsKey = track.channels || '2';\n trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;\n trackGroup.hasDefault = trackGroup.hasDefault || track.default;\n trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;\n if (trackGroup.hasDefault) {\n audioTracksByGroup.hasDefaultAudio = true;\n }\n if (trackGroup.hasAutoSelect) {\n audioTracksByGroup.hasAutoSelectAudio = true;\n }\n return audioTracksByGroup;\n }, {\n hasDefaultAudio: false,\n hasAutoSelectAudio: false,\n groups: {}\n });\n}\nfunction getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {\n return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce((tiers, level, index) => {\n if (!level.codecSet) {\n return tiers;\n }\n const audioGroups = level.audioGroups;\n let tier = tiers[level.codecSet];\n if (!tier) {\n tiers[level.codecSet] = tier = {\n minBitrate: Infinity,\n minHeight: Infinity,\n minFramerate: Infinity,\n minIndex: index,\n maxScore: 0,\n videoRanges: {\n SDR: 0\n },\n channels: {\n '2': 0\n },\n hasDefaultAudio: !audioGroups,\n fragmentError: 0\n };\n }\n tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);\n const lesserWidthOrHeight = Math.min(level.height, level.width);\n tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);\n tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);\n tier.minIndex = Math.min(tier.minIndex, index);\n tier.maxScore = Math.max(tier.maxScore, level.score);\n tier.fragmentError += level.fragmentError;\n tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;\n if (audioGroups) {\n audioGroups.forEach(audioGroupId => {\n if (!audioGroupId) {\n return;\n }\n const audioGroup = audioTracksByGroup.groups[audioGroupId];\n if (!audioGroup) {\n return;\n }\n // Default audio is any group with DEFAULT=YES, or if missing then any group with AUTOSELECT=YES, or all variants\n tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio;\n Object.keys(audioGroup.channels).forEach(channels => {\n tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels];\n });\n });\n }\n return tiers;\n }, {});\n}\nfunction getBasicSelectionOption(option) {\n if (!option) {\n return option;\n }\n const {\n lang,\n assocLang,\n characteristics,\n channels,\n audioCodec\n } = option;\n return {\n lang,\n assocLang,\n characteristics,\n channels,\n audioCodec\n };\n}\nfunction findMatchingOption(option, tracks, matchPredicate) {\n if ('attrs' in option) {\n const index = tracks.indexOf(option);\n if (index !== -1) {\n return index;\n }\n }\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n if (matchesOption(option, track, matchPredicate)) {\n return i;\n }\n }\n return -1;\n}\nfunction matchesOption(option, track, matchPredicate) {\n const {\n groupId,\n name,\n lang,\n assocLang,\n default: isDefault\n } = option;\n const forced = option.forced;\n return (groupId === undefined || track.groupId === groupId) && (name === undefined || track.name === name) && (lang === undefined || languagesMatch(lang, track.lang)) && (lang === undefined || track.assocLang === assocLang) && (isDefault === undefined || track.default === isDefault) && (forced === undefined || track.forced === forced) && (!('characteristics' in option) || characteristicsMatch(option.characteristics || '', track.characteristics)) && (matchPredicate === undefined || matchPredicate(option, track));\n}\nfunction languagesMatch(languageA, languageB = '--') {\n if (languageA.length === languageB.length) {\n return languageA === languageB;\n }\n return languageA.startsWith(languageB) || languageB.startsWith(languageA);\n}\nfunction characteristicsMatch(characteristicsA, characteristicsB = '') {\n const arrA = characteristicsA.split(',');\n const arrB = characteristicsB.split(',');\n // Expects each item to be unique:\n return arrA.length === arrB.length && !arrA.some(el => arrB.indexOf(el) === -1);\n}\nfunction audioMatchPredicate(option, track) {\n const {\n audioCodec,\n channels\n } = option;\n return (audioCodec === undefined || (track.audioCodec || '').substring(0, 4) === audioCodec.substring(0, 4)) && (channels === undefined || channels === (track.channels || '2'));\n}\nfunction findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) {\n const currentLevel = levels[searchIndex];\n // Are there variants with same URI as current level?\n // If so, find a match that does not require any level URI change\n const variants = levels.reduce((variantMap, level, index) => {\n const uri = level.uri;\n const renditions = variantMap[uri] || (variantMap[uri] = []);\n renditions.push(index);\n return variantMap;\n }, {});\n const renditions = variants[currentLevel.uri];\n if (renditions.length > 1) {\n searchIndex = Math.max.apply(Math, renditions);\n }\n // Find best match\n const currentVideoRange = currentLevel.videoRange;\n const currentFrameRate = currentLevel.frameRate;\n const currentVideoCodec = currentLevel.codecSet.substring(0, 4);\n const matchingVideo = searchDownAndUpList(levels, searchIndex, level => {\n if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) {\n return false;\n }\n const audioGroups = level.audioGroups;\n const tracks = allAudioTracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);\n return findMatchingOption(option, tracks, matchPredicate) > -1;\n });\n if (matchingVideo > -1) {\n return matchingVideo;\n }\n return searchDownAndUpList(levels, searchIndex, level => {\n const audioGroups = level.audioGroups;\n const tracks = allAudioTracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);\n return findMatchingOption(option, tracks, matchPredicate) > -1;\n });\n}\nfunction searchDownAndUpList(arr, searchIndex, predicate) {\n for (let i = searchIndex; i > -1; i--) {\n if (predicate(arr[i])) {\n return i;\n }\n }\n for (let i = searchIndex + 1; i < arr.length; i++) {\n if (predicate(arr[i])) {\n return i;\n }\n }\n return -1;\n}\nfunction useAlternateAudio(audioTrackUrl, hls) {\n var _hls$loadLevelObj;\n return !!audioTrackUrl && audioTrackUrl !== ((_hls$loadLevelObj = hls.loadLevelObj) == null ? void 0 : _hls$loadLevelObj.uri);\n}\n\nclass AbrController extends Logger {\n constructor(_hls) {\n super('abr', _hls.logger);\n this.hls = void 0;\n this.lastLevelLoadSec = 0;\n this.lastLoadedFragLevel = -1;\n this.firstSelection = -1;\n this._nextAutoLevel = -1;\n this.nextAutoLevelKey = '';\n this.audioTracksByGroup = null;\n this.codecTiers = null;\n this.timer = -1;\n this.fragCurrent = null;\n this.partCurrent = null;\n this.bitrateTestDelay = 0;\n this.rebufferNotice = -1;\n this.bwEstimator = void 0;\n /*\n This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load\n quickly enough to prevent underbuffering\n */\n this._abandonRulesCheck = levelLoaded => {\n var _ref;\n const {\n fragCurrent: frag,\n partCurrent: part,\n hls\n } = this;\n const {\n autoLevelEnabled,\n media\n } = hls;\n if (!frag || !media) {\n return;\n }\n const now = performance.now();\n const stats = part ? part.stats : frag.stats;\n const duration = part ? part.duration : frag.duration;\n const timeLoading = now - stats.loading.start;\n const minAutoLevel = hls.minAutoLevel;\n const loadingFragForLevel = frag.level;\n const currentAutoLevel = this._nextAutoLevel;\n // If frag loading is aborted, complete, or from lowest level, stop timer and return\n if (stats.aborted || stats.loaded && stats.loaded === stats.total || loadingFragForLevel <= minAutoLevel) {\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n return;\n }\n\n // This check only runs if we're in ABR mode\n if (!autoLevelEnabled) {\n return;\n }\n\n // Must be loading/loaded a new level or be in a playing state\n const fragBlockingSwitch = currentAutoLevel > -1 && currentAutoLevel !== loadingFragForLevel;\n const levelChange = !!levelLoaded || fragBlockingSwitch;\n if (!levelChange && (media.paused || !media.playbackRate || !media.readyState)) {\n return;\n }\n const bufferInfo = hls.mainForwardBufferInfo;\n if (!levelChange && bufferInfo === null) {\n return;\n }\n const ttfbEstimate = this.bwEstimator.getEstimateTTFB();\n const playbackRate = Math.abs(media.playbackRate);\n // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed\n if (timeLoading <= Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))) {\n return;\n }\n\n // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer\n const bufferStarvationDelay = bufferInfo ? bufferInfo.len / playbackRate : 0;\n const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;\n const loadedFirstByte = stats.loaded && ttfb > -1;\n const bwEstimate = this.getBwEstimate();\n const levels = hls.levels;\n const level = levels[loadingFragForLevel];\n const expectedLen = Math.max(stats.loaded, Math.round(duration * (frag.bitrate || level.averageBitrate) / 8));\n let timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;\n if (timeStreaming < 1 && loadedFirstByte) {\n timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);\n }\n const loadRate = loadedFirstByte ? stats.loaded * 1000 / timeStreaming : 0;\n // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment\n const ttfbSeconds = ttfbEstimate / 1000;\n const fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbSeconds;\n // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left\n if (fragLoadedDelay <= bufferStarvationDelay) {\n return;\n }\n const bwe = loadRate ? loadRate * 8 : bwEstimate;\n const live = ((_ref = (levelLoaded == null ? void 0 : levelLoaded.details) || this.hls.latestLevelDetails) == null ? void 0 : _ref.live) === true;\n const abrBandWidthUpFactor = this.hls.config.abrBandWidthUpFactor;\n let fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;\n let nextLoadLevel;\n // Iterate through lower level and try to find the largest one that avoids rebuffering\n for (nextLoadLevel = loadingFragForLevel - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {\n // compute time to load next fragment at lower level\n // 8 = bits per byte (bps/Bps)\n const levelNextBitrate = levels[nextLoadLevel].maxBitrate;\n const requiresLevelLoad = !levels[nextLoadLevel].details || live;\n fragLevelNextLoadedDelay = this.getTimeToLoadFrag(ttfbSeconds, bwe, duration * levelNextBitrate, requiresLevelLoad);\n if (fragLevelNextLoadedDelay < Math.min(bufferStarvationDelay, duration + ttfbSeconds)) {\n break;\n }\n }\n // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing\n // to load the current one\n if (fragLevelNextLoadedDelay >= fragLoadedDelay) {\n return;\n }\n\n // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down\n if (fragLevelNextLoadedDelay > duration * 10) {\n return;\n }\n if (loadedFirstByte) {\n // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time\n this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);\n } else {\n // If there has been no loading progress, sample TTFB\n this.bwEstimator.sampleTTFB(timeLoading);\n }\n const nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;\n if (this.getBwEstimate() * abrBandWidthUpFactor > nextLoadLevelBitrate) {\n this.resetEstimator(nextLoadLevelBitrate);\n }\n const bestSwitchLevel = this.findBestLevel(nextLoadLevelBitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);\n if (bestSwitchLevel > -1) {\n nextLoadLevel = bestSwitchLevel;\n }\n this.warn(`Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${loadingFragForLevel} is loading too slowly;\n Fragment duration: ${frag.duration.toFixed(3)}\n Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s\n Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s\n Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(3)} s\n TTFB estimate: ${ttfb | 0} ms\n Current BW estimate: ${isFiniteNumber(bwEstimate) ? bwEstimate | 0 : 'Unknown'} bps\n New BW estimate: ${this.getBwEstimate() | 0} bps\n Switching to level ${nextLoadLevel} @ ${nextLoadLevelBitrate | 0} bps`);\n hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;\n this.clearTimer();\n const abortAndSwitch = () => {\n // Are nextLoadLevel details available or is stream-controller still in \"WAITING_LEVEL\" state?\n this.clearTimer();\n if (this.fragCurrent === frag && this.hls.loadLevel === nextLoadLevel && nextLoadLevel > 0) {\n const bufferStarvationDelay = this.getStarvationDelay();\n this.warn(`Aborting inflight request ${nextLoadLevel > 0 ? 'and switching down' : ''}\n Fragment duration: ${frag.duration.toFixed(3)} s\n Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s`);\n frag.abortRequests();\n this.fragCurrent = this.partCurrent = null;\n if (nextLoadLevel > minAutoLevel) {\n let lowestSwitchLevel = this.findBestLevel(this.hls.levels[minAutoLevel].bitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);\n if (lowestSwitchLevel === -1) {\n lowestSwitchLevel = minAutoLevel;\n }\n this.hls.nextLoadLevel = this.hls.nextAutoLevel = lowestSwitchLevel;\n this.resetEstimator(this.hls.levels[lowestSwitchLevel].bitrate);\n }\n }\n };\n if (fragBlockingSwitch || fragLoadedDelay > fragLevelNextLoadedDelay * 2) {\n abortAndSwitch();\n } else {\n this.timer = self.setInterval(abortAndSwitch, fragLevelNextLoadedDelay * 1000);\n }\n hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {\n frag,\n part,\n stats\n });\n };\n this.hls = _hls;\n this.bwEstimator = this.initEstimator();\n this.registerListeners();\n }\n resetEstimator(abrEwmaDefaultEstimate) {\n if (abrEwmaDefaultEstimate) {\n this.log(`setting initial bwe to ${abrEwmaDefaultEstimate}`);\n this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;\n }\n this.firstSelection = -1;\n this.bwEstimator = this.initEstimator();\n }\n initEstimator() {\n const config = this.hls.config;\n return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);\n }\n registerListeners() {\n const {\n hls\n } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n unregisterListeners() {\n const {\n hls\n } = this;\n if (!hls) {\n return;\n }\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n destroy() {\n this.unregisterListeners();\n this.clearTimer();\n // @ts-ignore\n this.hls = this._abandonRulesCheck = null;\n this.fragCurrent = this.partCurrent = null;\n }\n onManifestLoading(event, data) {\n this.lastLoadedFragLevel = -1;\n this.firstSelection = -1;\n this.lastLevelLoadSec = 0;\n this.fragCurrent = this.partCurrent = null;\n this.onLevelsUpdated();\n this.clearTimer();\n }\n onLevelsUpdated() {\n if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {\n this.lastLoadedFragLevel = this.fragCurrent.level;\n }\n this._nextAutoLevel = -1;\n this.onMaxAutoLevelUpdated();\n this.codecTiers = null;\n this.audioTracksByGroup = null;\n }\n onMaxAutoLevelUpdated() {\n this.firstSelection = -1;\n this.nextAutoLevelKey = '';\n }\n onFragLoading(event, data) {\n const frag = data.frag;\n if (this.ignoreFragment(frag)) {\n return;\n }\n if (!frag.bitrateTest) {\n var _data$part;\n this.fragCurrent = frag;\n this.partCurrent = (_data$part = data.part) != null ? _data$part : null;\n }\n this.clearTimer();\n this.timer = self.setInterval(this._abandonRulesCheck, 100);\n }\n onLevelSwitching(event, data) {\n this.clearTimer();\n }\n onError(event, data) {\n if (data.fatal) {\n return;\n }\n switch (data.details) {\n case ErrorDetails.BUFFER_ADD_CODEC_ERROR:\n case ErrorDetails.BUFFER_APPEND_ERROR:\n // Reset last loaded level so that a new selection can be made after calling recoverMediaError\n this.lastLoadedFragLevel = -1;\n this.firstSelection = -1;\n break;\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n {\n const frag = data.frag;\n const {\n fragCurrent,\n partCurrent: part\n } = this;\n if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {\n const now = performance.now();\n const stats = part ? part.stats : frag.stats;\n const timeLoading = now - stats.loading.start;\n const ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;\n const loadedFirstByte = stats.loaded && ttfb > -1;\n if (loadedFirstByte) {\n const ttfbEstimate = this.bwEstimator.getEstimateTTFB();\n this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);\n } else {\n this.bwEstimator.sampleTTFB(timeLoading);\n }\n }\n break;\n }\n }\n }\n getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {\n const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;\n const playlistLoadSec = isSwitch ? timeToFirstByteSec + this.lastLevelLoadSec : 0;\n return fragLoadSec + playlistLoadSec;\n }\n onLevelLoaded(event, data) {\n const config = this.hls.config;\n const {\n loading\n } = data.stats;\n const timeLoadingMs = loading.end - loading.first;\n if (isFiniteNumber(timeLoadingMs)) {\n this.lastLevelLoadSec = timeLoadingMs / 1000;\n }\n if (data.details.live) {\n this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);\n } else {\n this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);\n }\n if (this.timer > -1) {\n this._abandonRulesCheck(data.levelInfo);\n }\n }\n onFragLoaded(event, {\n frag,\n part\n }) {\n const stats = part ? part.stats : frag.stats;\n if (frag.type === PlaylistLevelType.MAIN) {\n this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);\n }\n if (this.ignoreFragment(frag)) {\n return;\n }\n // stop monitoring bw once frag loaded\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n if (frag.level === this._nextAutoLevel) {\n this._nextAutoLevel = -1;\n }\n this.firstSelection = -1;\n\n // compute level average bitrate\n if (this.hls.config.abrMaxWithRealBitrate) {\n const duration = part ? part.duration : frag.duration;\n const level = this.hls.levels[frag.level];\n const loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;\n const loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;\n level.loaded = {\n bytes: loadedBytes,\n duration: loadedDuration\n };\n level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);\n }\n if (frag.bitrateTest) {\n const fragBufferedData = {\n stats,\n frag,\n part,\n id: frag.type\n };\n this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);\n frag.bitrateTest = false;\n } else {\n // store level id after successful fragment load for playback\n this.lastLoadedFragLevel = frag.level;\n }\n }\n onFragBuffered(event, data) {\n const {\n frag,\n part\n } = data;\n const stats = part != null && part.stats.loaded ? part.stats : frag.stats;\n if (stats.aborted) {\n return;\n }\n if (this.ignoreFragment(frag)) {\n return;\n }\n // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;\n // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch\n // is used. If we used buffering in that case, our BW estimate sample will be very large.\n const processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());\n this.bwEstimator.sample(processingMs, stats.loaded);\n stats.bwEstimate = this.getBwEstimate();\n if (frag.bitrateTest) {\n this.bitrateTestDelay = processingMs / 1000;\n } else {\n this.bitrateTestDelay = 0;\n }\n }\n ignoreFragment(frag) {\n // Only count non-alt-audio frags which were actually buffered in our BW calculations\n return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';\n }\n clearTimer() {\n if (this.timer > -1) {\n self.clearInterval(this.timer);\n this.timer = -1;\n }\n }\n get firstAutoLevel() {\n const {\n maxAutoLevel,\n minAutoLevel\n } = this.hls;\n const bwEstimate = this.getBwEstimate();\n const maxStartDelay = this.hls.config.maxStarvationDelay;\n const abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);\n if (abrAutoLevel > -1) {\n return abrAutoLevel;\n }\n const firstLevel = this.hls.firstLevel;\n const clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);\n this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${firstLevel} clamped to ${clamped}`);\n return clamped;\n }\n get forcedAutoLevel() {\n if (this.nextAutoLevelKey) {\n return -1;\n }\n return this._nextAutoLevel;\n }\n\n // return next auto level\n get nextAutoLevel() {\n const forcedAutoLevel = this.forcedAutoLevel;\n const bwEstimator = this.bwEstimator;\n const useEstimate = bwEstimator.canEstimate();\n const loadedFirstFrag = this.lastLoadedFragLevel > -1;\n // in case next auto level has been forced, and bw not available or not reliable, return forced value\n if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {\n return forcedAutoLevel;\n }\n\n // compute next level using ABR logic\n const nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;\n\n // use forced auto level while it hasn't errored more than ABR selection\n if (forcedAutoLevel !== -1) {\n const levels = this.hls.levels;\n if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {\n return forcedAutoLevel;\n }\n }\n\n // save result until state has changed\n this._nextAutoLevel = nextABRAutoLevel;\n this.nextAutoLevelKey = this.getAutoLevelKey();\n return nextABRAutoLevel;\n }\n getAutoLevelKey() {\n return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`;\n }\n getNextABRAutoLevel() {\n const {\n fragCurrent,\n partCurrent,\n hls\n } = this;\n if (hls.levels.length <= 1) {\n return hls.loadLevel;\n }\n const {\n maxAutoLevel,\n config,\n minAutoLevel\n } = hls;\n const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;\n const avgbw = this.getBwEstimate();\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n const bufferStarvationDelay = this.getStarvationDelay();\n let bwFactor = config.abrBandWidthFactor;\n let bwUpFactor = config.abrBandWidthUpFactor;\n\n // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n if (bufferStarvationDelay) {\n const _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);\n if (_bestLevel >= 0) {\n this.rebufferNotice = -1;\n return _bestLevel;\n }\n }\n // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering\n let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;\n if (!bufferStarvationDelay) {\n // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test\n const bitrateTestDelay = this.bitrateTestDelay;\n if (bitrateTestDelay) {\n // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value\n // max video loading delay used in automatic start level selection :\n // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +\n // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )\n // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration\n const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;\n maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n this.info(`bitrate test took ${Math.round(1000 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1000 * maxStarvationDelay)} ms`);\n // don't use conservative factor on bitrate test\n bwFactor = bwUpFactor = 1;\n }\n }\n const bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);\n if (this.rebufferNotice !== bestLevel) {\n this.rebufferNotice = bestLevel;\n this.info(`${bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'}, optimal quality level ${bestLevel}`);\n }\n if (bestLevel > -1) {\n return bestLevel;\n }\n // If no matching level found, see if min auto level would be a better option\n const minLevel = hls.levels[minAutoLevel];\n const autoLevel = hls.loadLevelObj;\n if (autoLevel && (minLevel == null ? void 0 : minLevel.bitrate) < autoLevel.bitrate) {\n return minAutoLevel;\n }\n // or if bitrate is not lower, continue to use loadLevel\n return hls.loadLevel;\n }\n getStarvationDelay() {\n const hls = this.hls;\n const media = hls.media;\n if (!media) {\n return Infinity;\n }\n // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n const playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;\n const bufferInfo = hls.mainForwardBufferInfo;\n return (bufferInfo ? bufferInfo.len : 0) / playbackRate;\n }\n getBwEstimate() {\n return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;\n }\n findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {\n var _this$hls$latestLevel;\n const maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;\n const lastLoadedFragLevel = this.lastLoadedFragLevel;\n const selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;\n const {\n fragCurrent,\n partCurrent\n } = this;\n const {\n levels,\n allAudioTracks,\n loadLevel,\n config\n } = this.hls;\n if (levels.length === 1) {\n return 0;\n }\n const level = levels[selectionBaseLevel];\n const live = !!((_this$hls$latestLevel = this.hls.latestLevelDetails) != null && _this$hls$latestLevel.live);\n const firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;\n let currentCodecSet;\n let currentVideoRange = 'SDR';\n let currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;\n const {\n audioPreference,\n videoPreference\n } = config;\n const audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));\n let minStartIndex = -1;\n if (firstSelection) {\n if (this.firstSelection !== -1) {\n return this.firstSelection;\n }\n const codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));\n const startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);\n const {\n codecSet,\n videoRanges,\n minFramerate,\n minBitrate,\n minIndex,\n preferHDR\n } = startTier;\n minStartIndex = minIndex;\n currentCodecSet = codecSet;\n currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];\n currentFrameRate = minFramerate;\n currentBw = Math.max(currentBw, minBitrate);\n this.log(`picked start tier ${stringify(startTier)}`);\n } else {\n currentCodecSet = level == null ? void 0 : level.codecSet;\n currentVideoRange = level == null ? void 0 : level.videoRange;\n }\n const currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;\n const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;\n const levelsSkipped = [];\n for (let i = maxAutoLevel; i >= minAutoLevel; i--) {\n var _levelInfo$supportedR;\n const levelInfo = levels[i];\n const upSwitch = i > selectionBaseLevel;\n if (!levelInfo) {\n continue;\n }\n if (config.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) {\n const mediaCapabilities = navigator.mediaCapabilities;\n if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === 'function' && (requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) || isHEVC(levelInfo.videoCodec)) // Force media capabilities check for HEVC to avoid failure on Windows\n ) {\n levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities);\n levelInfo.supportedPromise.then(decodingInfo => {\n if (!this.hls) {\n return;\n }\n levelInfo.supportedResult = decodingInfo;\n const levels = this.hls.levels;\n const index = levels.indexOf(levelInfo);\n if (decodingInfo.error) {\n this.warn(`MediaCapabilities decodingInfo error: \"${decodingInfo.error}\" for level ${index} ${stringify(decodingInfo)}`);\n } else if (!decodingInfo.supported) {\n this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${index} ${stringify(decodingInfo)}`);\n if (index > -1 && levels.length > 1) {\n this.log(`Removing unsupported level ${index}`);\n this.hls.removeLevel(index);\n if (this.hls.loadLevel === -1) {\n this.hls.nextLoadLevel = 0;\n }\n }\n }\n });\n } else {\n levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;\n }\n }\n\n // skip candidates which change codec-family or video-range,\n // and which decrease or increase frame-rate for up and down-switch respectfully\n if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || levelInfo.supportedResult && !((_levelInfo$supportedR = levelInfo.supportedResult.decodingInfoResults) != null && _levelInfo$supportedR[0].smooth)) {\n if (!firstSelection || i !== minStartIndex) {\n levelsSkipped.push(i);\n continue;\n }\n }\n const levelDetails = levelInfo.details;\n const avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;\n let adjustedbw;\n // follow algorithm captured from stagefright :\n // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp\n // Pick the highest bandwidth stream below or equal to estimated bandwidth.\n // consider only 80% of the available bandwidth, but if we are switching up,\n // be even more conservative (70%) to avoid overestimating and immediately\n // switching back.\n if (!upSwitch) {\n adjustedbw = bwFactor * currentBw;\n } else {\n adjustedbw = bwUpFactor * currentBw;\n }\n\n // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)\n const bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levelInfo.averageBitrate : levelInfo.maxBitrate;\n const fetchDuration = this.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === undefined);\n const canSwitchWithinTolerance =\n // if adjusted bw is greater than level bitrate AND\n adjustedbw >= bitrate && (\n // no level change, or new level has no error history\n i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && (\n // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...\n // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1\n fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration);\n if (canSwitchWithinTolerance) {\n const forcedAutoLevel = this.forcedAutoLevel;\n if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {\n if (levelsSkipped.length) {\n this.trace(`Skipped level(s) ${levelsSkipped.join(',')} of ${maxAutoLevel} max with CODECS and VIDEO-RANGE:\"${levels[levelsSkipped[0]].codecs}\" ${levels[levelsSkipped[0]].videoRange}; not compatible with \"${currentCodecSet}\" ${currentVideoRange}`);\n }\n this.info(`switch candidate:${selectionBaseLevel}->${i} adjustedbw(${Math.round(adjustedbw)})-bitrate=${Math.round(adjustedbw - bitrate)} ttfb:${ttfbEstimateSec.toFixed(1)} avgDuration:${avgDuration.toFixed(1)} maxFetchDuration:${maxFetchDuration.toFixed(1)} fetchDuration:${fetchDuration.toFixed(1)} firstSelection:${firstSelection} codecSet:${levelInfo.codecSet} videoRange:${levelInfo.videoRange} hls.loadLevel:${loadLevel}`);\n }\n if (firstSelection) {\n this.firstSelection = i;\n }\n // as we are looping from highest to lowest, this will return the best achievable quality level\n return i;\n }\n }\n // not enough time budget even with quality level 0 ... rebuffering might happen\n return -1;\n }\n set nextAutoLevel(nextLevel) {\n const value = this.deriveNextAutoLevel(nextLevel);\n if (this._nextAutoLevel !== value) {\n this.nextAutoLevelKey = '';\n this._nextAutoLevel = value;\n }\n }\n deriveNextAutoLevel(nextLevel) {\n const {\n maxAutoLevel,\n minAutoLevel\n } = this.hls;\n return Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);\n }\n}\n\nconst BinarySearch = {\n /**\n * Searches for an item in an array which matches a certain condition.\n * This requires the condition to only match one item in the array,\n * and for the array to be ordered.\n *\n * @param list The array to search.\n * @param comparisonFn\n * Called and provided a candidate item as the first argument.\n * Should return:\n * > -1 if the item should be located at a lower index than the provided item.\n * > 1 if the item should be located at a higher index than the provided item.\n * > 0 if the item is the item you're looking for.\n *\n * @returns the object if found, otherwise returns null\n */\n search: function (list, comparisonFn) {\n let minIndex = 0;\n let maxIndex = list.length - 1;\n let currentIndex = null;\n let currentElement = null;\n while (minIndex <= maxIndex) {\n currentIndex = (minIndex + maxIndex) / 2 | 0;\n currentElement = list[currentIndex];\n const comparisonResult = comparisonFn(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\n } else {\n return currentElement;\n }\n }\n return null;\n }\n};\n\n/**\n * Returns first fragment whose endPdt value exceeds the given PDT, or null.\n * @param fragments - The array of candidate fragments\n * @param PDTValue - The PDT value which must be exceeded\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n */\nfunction findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {\n if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {\n return null;\n }\n\n // if less than start\n const startPDT = fragments[0].programDateTime;\n if (PDTValue < (startPDT || 0)) {\n return null;\n }\n const endPDT = fragments[fragments.length - 1].endProgramDateTime;\n if (PDTValue >= (endPDT || 0)) {\n return null;\n }\n maxFragLookUpTolerance = maxFragLookUpTolerance || 0;\n for (let seg = 0; seg < fragments.length; ++seg) {\n const frag = fragments[seg];\n if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {\n return frag;\n }\n }\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param fragPrevious - The last frag successfully appended\n * @param fragments - The array of candidate fragments\n * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns a matching fragment or null\n */\nfunction findFragmentByPTS(fragPrevious, fragments, bufferEnd = 0, maxFragLookUpTolerance = 0, nextFragLookupTolerance = 0.005) {\n let fragNext = null;\n if (fragPrevious) {\n fragNext = fragments[1 + fragPrevious.sn - fragments[0].sn] || null;\n // check for buffer-end rounding error\n const bufferEdgeError = fragPrevious.endDTS - bufferEnd;\n if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {\n bufferEnd += 0.0000015;\n }\n if (fragNext && fragPrevious.level !== fragNext.level && fragNext.end <= fragPrevious.end) {\n fragNext = fragments[2 + fragPrevious.sn - fragments[0].sn] || null;\n }\n } else if (bufferEnd === 0 && fragments[0].start === 0) {\n fragNext = fragments[0];\n }\n // Prefer the next fragment if it's within tolerance\n if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {\n return fragNext;\n }\n // We might be seeking past the tolerance so find the best match\n const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {\n return foundFragment;\n }\n // If no match was found return the next fragment after fragPrevious, or null\n return fragNext;\n}\nfunction fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {\n if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {\n const firstDuration = fragPrevious.tagList.reduce((duration, tag) => {\n if (tag[0] === 'INF') {\n duration += parseFloat(tag[1]);\n }\n return duration;\n }, nextFragLookupTolerance);\n return fragNext.start <= firstDuration;\n }\n return false;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param candidate - The fragment to test\n * @param bufferEnd - The end of the current buffered range the playhead is currently within\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns 0 if it matches, 1 if too low, -1 if too high\n */\nfunction fragmentWithinToleranceTest(bufferEnd = 0, maxFragLookUpTolerance = 0, candidate) {\n // eagerly accept an accurate match (no tolerance)\n if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {\n return 0;\n }\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));\n if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {\n return 1;\n } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n return 0;\n}\n\n/**\n * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.\n * This function tests the candidate's program date time values, as represented in Unix time\n * @param candidate - The fragment to test\n * @param pdtBufferEnd - The Unix time representing the end of the current buffered range\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns true if contiguous, false otherwise\n */\nfunction pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {\n const candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;\n\n // endProgramDateTime can be null, default to zero\n const endProgramDateTime = candidate.endProgramDateTime || 0;\n return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;\n}\nfunction findFragWithCC(fragments, cc) {\n return BinarySearch.search(fragments, candidate => {\n if (candidate.cc < cc) {\n return 1;\n } else if (candidate.cc > cc) {\n return -1;\n } else {\n return 0;\n }\n });\n}\nfunction findNearestWithCC(details, cc, fragment) {\n if (details) {\n if (details.startCC <= cc && details.endCC >= cc) {\n const start = fragment.start;\n const end = fragment.end;\n let fragments = details.fragments;\n if (!fragment.relurl) {\n const {\n fragmentHint\n } = details;\n if (fragmentHint) {\n fragments = fragments.concat(fragmentHint);\n }\n }\n return BinarySearch.search(fragments, candidate => {\n if (candidate.cc < cc || candidate.end <= start) {\n return 1;\n } else if (candidate.cc > cc || candidate.start >= end) {\n return -1;\n } else {\n return 0;\n }\n });\n }\n }\n return null;\n}\n\nfunction isTimeoutError(error) {\n switch (error.details) {\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n case ErrorDetails.MANIFEST_LOAD_TIMEOUT:\n return true;\n }\n return false;\n}\nfunction getRetryConfig(loadPolicy, error) {\n const isTimeout = isTimeoutError(error);\n return loadPolicy.default[`${isTimeout ? 'timeout' : 'error'}Retry`];\n}\nfunction getRetryDelay(retryConfig, retryCount) {\n // exponential backoff capped to max retry delay\n const backoffFactor = retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);\n return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);\n}\nfunction getLoaderConfigWithoutReties(loderConfig) {\n return _objectSpread2(_objectSpread2({}, loderConfig), {\n errorRetry: null,\n timeoutRetry: null\n });\n}\nfunction shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {\n if (!retryConfig) {\n return false;\n }\n const httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;\n const retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);\n return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;\n}\nfunction retryForHttpStatus(httpStatus) {\n // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)\n return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);\n}\n\nvar NetworkErrorAction = {\n DoNothing: 0,\n SendEndCallback: 1,\n SendAlternateToPenaltyBox: 2,\n RemoveAlternatePermanently: 3,\n InsertDiscontinuity: 4,\n RetryRequest: 5\n};\nvar ErrorActionFlags = {\n None: 0,\n MoveAllAlternatesMatchingHost: 1,\n MoveAllAlternatesMatchingHDCP: 2,\n SwitchToSDR: 4\n};\nclass ErrorController extends Logger {\n constructor(hls) {\n super('error-controller', hls.logger);\n this.hls = void 0;\n this.playlistError = 0;\n this.penalizedRenditions = {};\n this.hls = hls;\n this.registerListeners();\n }\n registerListeners() {\n const hls = this.hls;\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n unregisterListeners() {\n const hls = this.hls;\n if (!hls) {\n return;\n }\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.ERROR, this.onErrorOut, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n destroy() {\n this.unregisterListeners();\n // @ts-ignore\n this.hls = null;\n this.penalizedRenditions = {};\n }\n startLoad(startPosition) {}\n stopLoad() {\n this.playlistError = 0;\n }\n getVariantLevelIndex(frag) {\n return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;\n }\n onManifestLoading() {\n this.playlistError = 0;\n this.penalizedRenditions = {};\n }\n onLevelUpdated() {\n this.playlistError = 0;\n }\n onError(event, data) {\n var _data$frag;\n if (data.fatal) {\n return;\n }\n const hls = this.hls;\n const context = data.context;\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n data.errorAction = this.getFragRetryOrSwitchAction(data);\n return;\n case ErrorDetails.FRAG_PARSING_ERROR:\n // ignore empty segment errors marked as gap\n if ((_data$frag = data.frag) != null && _data$frag.gap) {\n data.errorAction = createDoNothingErrorAction();\n return;\n }\n // falls through\n case ErrorDetails.FRAG_GAP:\n case ErrorDetails.FRAG_DECRYPT_ERROR:\n {\n // Switch level if possible, otherwise allow retry count to reach max error retries\n data.errorAction = this.getFragRetryOrSwitchAction(data);\n data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;\n return;\n }\n case ErrorDetails.LEVEL_EMPTY_ERROR:\n case ErrorDetails.LEVEL_PARSING_ERROR:\n {\n var _data$context, _data$context$levelDe;\n // Only retry when empty and live\n const levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;\n if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {\n data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);\n } else {\n // Escalate to fatal if not retrying or switching\n data.levelRetry = false;\n data.errorAction = this.getLevelSwitchAction(data, levelIndex);\n }\n }\n return;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n if (typeof (context == null ? void 0 : context.level) === 'number') {\n data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);\n }\n return;\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.SUBTITLE_LOAD_ERROR:\n case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:\n if (context) {\n const level = hls.loadLevelObj;\n if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {\n // Perform Pathway switch or Redundant failover if possible for fastest recovery\n // otherwise allow playlist retry count to reach max error retries\n data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);\n data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;\n data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;\n return;\n }\n }\n return;\n case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:\n {\n const level = hls.loadLevelObj;\n const restrictedHdcpLevel = level == null ? void 0 : level.attrs['HDCP-LEVEL'];\n if (restrictedHdcpLevel) {\n data.errorAction = {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,\n hdcpLevel: restrictedHdcpLevel\n };\n } else {\n this.keySystemError(data);\n }\n }\n return;\n case ErrorDetails.BUFFER_ADD_CODEC_ERROR:\n case ErrorDetails.REMUX_ALLOC_ERROR:\n case ErrorDetails.BUFFER_APPEND_ERROR:\n // Buffer-controller can set errorAction when append errors can be ignored or resolved locally\n if (!data.errorAction) {\n var _data$level;\n data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);\n }\n return;\n case ErrorDetails.INTERNAL_EXCEPTION:\n case ErrorDetails.BUFFER_APPENDING_ERROR:\n case ErrorDetails.BUFFER_FULL_ERROR:\n case ErrorDetails.LEVEL_SWITCH_ERROR:\n case ErrorDetails.BUFFER_STALLED_ERROR:\n case ErrorDetails.BUFFER_SEEK_OVER_HOLE:\n case ErrorDetails.BUFFER_NUDGE_ON_STALL:\n data.errorAction = createDoNothingErrorAction();\n return;\n }\n if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {\n this.keySystemError(data);\n }\n }\n keySystemError(data) {\n const levelIndex = this.getVariantLevelIndex(data.frag);\n // Do not retry level. Escalate to fatal if switching levels fails.\n data.levelRetry = false;\n data.errorAction = this.getLevelSwitchAction(data, levelIndex);\n }\n getPlaylistRetryOrSwitchAction(data, levelIndex) {\n const hls = this.hls;\n const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);\n const retryCount = this.playlistError++;\n const retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);\n if (retry) {\n return {\n action: NetworkErrorAction.RetryRequest,\n flags: ErrorActionFlags.None,\n retryConfig,\n retryCount\n };\n }\n const errorAction = this.getLevelSwitchAction(data, levelIndex);\n if (retryConfig) {\n errorAction.retryConfig = retryConfig;\n errorAction.retryCount = retryCount;\n }\n return errorAction;\n }\n getFragRetryOrSwitchAction(data) {\n const hls = this.hls;\n // Share fragment error count accross media options (main, audio, subs)\n // This allows for level based rendition switching when media option assets fail\n const variantLevelIndex = this.getVariantLevelIndex(data.frag);\n const level = hls.levels[variantLevelIndex];\n const {\n fragLoadPolicy,\n keyLoadPolicy\n } = hls.config;\n const retryConfig = getRetryConfig(data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy, data);\n const fragmentErrors = hls.levels.reduce((acc, level) => acc + level.fragmentError, 0);\n // Switch levels when out of retried or level index out of bounds\n if (level) {\n if (data.details !== ErrorDetails.FRAG_GAP) {\n level.fragmentError++;\n }\n const retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);\n if (retry) {\n return {\n action: NetworkErrorAction.RetryRequest,\n flags: ErrorActionFlags.None,\n retryConfig,\n retryCount: fragmentErrors\n };\n }\n }\n // Reach max retry count, or Missing level reference\n // Switch to valid index\n const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);\n // Add retry details to allow skipping of FRAG_PARSING_ERROR\n if (retryConfig) {\n errorAction.retryConfig = retryConfig;\n errorAction.retryCount = fragmentErrors;\n }\n return errorAction;\n }\n getLevelSwitchAction(data, levelIndex) {\n const hls = this.hls;\n if (levelIndex === null || levelIndex === undefined) {\n levelIndex = hls.loadLevel;\n }\n const level = this.hls.levels[levelIndex];\n if (level) {\n var _data$frag2, _data$context2;\n const errorDetails = data.details;\n level.loadError++;\n if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {\n level.fragmentError++;\n }\n // Search for next level to retry\n let nextLevel = -1;\n const {\n levels,\n loadLevel,\n minAutoLevel,\n maxAutoLevel\n } = hls;\n if (!hls.autoLevelEnabled) {\n hls.loadLevel = -1;\n }\n const fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;\n // Find alternate audio codec if available on audio codec error\n const isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === 'audio' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);\n const findAudioCodecAlternate = isAudioCodecError && levels.some(({\n audioCodec\n }) => level.audioCodec !== audioCodec);\n // Find alternate video codec if available on video codec error\n const isVideoCodecError = data.sourceBufferName === 'video' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);\n const findVideoCodecAlternate = isVideoCodecError && levels.some(({\n codecSet,\n audioCodec\n }) => level.codecSet !== codecSet && level.audioCodec === audioCodec);\n const {\n type: playlistErrorType,\n groupId: playlistErrorGroupId\n } = (_data$context2 = data.context) != null ? _data$context2 : {};\n for (let i = levels.length; i--;) {\n const candidate = (i + loadLevel) % levels.length;\n if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {\n var _level$audioGroups, _level$subtitleGroups;\n const levelCandidate = levels[candidate];\n // Skip level switch if GAP tag is found in next level at same position\n if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {\n const levelDetails = levels[candidate].details;\n if (levelDetails) {\n const fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);\n if (fragCandidate != null && fragCandidate.gap) {\n continue;\n }\n }\n } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {\n // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over\n continue;\n } else if (fragErrorType === PlaylistLevelType.AUDIO && (_level$audioGroups = level.audioGroups) != null && _level$audioGroups.some(groupId => levelCandidate.hasAudioGroup(groupId)) || fragErrorType === PlaylistLevelType.SUBTITLE && (_level$subtitleGroups = level.subtitleGroups) != null && _level$subtitleGroups.some(groupId => levelCandidate.hasSubtitleGroup(groupId)) || findAudioCodecAlternate && level.audioCodec === levelCandidate.audioCodec || !findAudioCodecAlternate && level.audioCodec !== levelCandidate.audioCodec || findVideoCodecAlternate && level.codecSet === levelCandidate.codecSet) {\n // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over\n continue;\n }\n nextLevel = candidate;\n break;\n }\n }\n if (nextLevel > -1 && hls.loadLevel !== nextLevel) {\n data.levelRetry = true;\n this.playlistError = 0;\n return {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.None,\n nextAutoLevel: nextLevel\n };\n }\n }\n // No levels to switch / Manual level selection / Level not found\n // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level\n return {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.MoveAllAlternatesMatchingHost\n };\n }\n onErrorOut(event, data) {\n var _data$errorAction;\n switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {\n case NetworkErrorAction.DoNothing:\n break;\n case NetworkErrorAction.SendAlternateToPenaltyBox:\n this.sendAlternateToPenaltyBox(data);\n if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {\n data.fatal = true;\n } else if (/MediaSource readyState: ended/.test(data.error.message)) {\n this.warn(`MediaSource ended after \"${data.sourceBufferName}\" sourceBuffer append error. Attempting to recover from media error.`);\n this.hls.recoverMediaError();\n }\n break;\n case NetworkErrorAction.RetryRequest:\n // handled by stream and playlist/level controllers\n break;\n }\n if (data.fatal) {\n this.hls.stopLoad();\n return;\n }\n }\n sendAlternateToPenaltyBox(data) {\n const hls = this.hls;\n const errorAction = data.errorAction;\n if (!errorAction) {\n return;\n }\n const {\n flags,\n hdcpLevel,\n nextAutoLevel\n } = errorAction;\n switch (flags) {\n case ErrorActionFlags.None:\n this.switchLevel(data, nextAutoLevel);\n break;\n case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:\n if (hdcpLevel) {\n hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];\n errorAction.resolved = true;\n }\n this.warn(`Restricting playback to HDCP-LEVEL of \"${hls.maxHdcpLevel}\" or lower`);\n break;\n }\n // If not resolved by previous actions try to switch to next level\n if (!errorAction.resolved) {\n this.switchLevel(data, nextAutoLevel);\n }\n }\n switchLevel(data, levelIndex) {\n if (levelIndex !== undefined && data.errorAction) {\n this.warn(`switching to level ${levelIndex} after ${data.details}`);\n this.hls.nextAutoLevel = levelIndex;\n data.errorAction.resolved = true;\n // Stream controller is responsible for this but won't switch on false start\n this.hls.nextLoadLevel = this.hls.nextAutoLevel;\n if (data.details === ErrorDetails.BUFFER_ADD_CODEC_ERROR && data.mimeType && data.sourceBufferName !== 'audiovideo') {\n const codec = getCodecsForMimeType(data.mimeType);\n const levels = this.hls.levels;\n for (let i = levels.length; i--;) {\n if (levels[i][`${data.sourceBufferName}Codec`] === codec) {\n this.hls.removeLevel(i);\n }\n }\n }\n }\n }\n}\nfunction createDoNothingErrorAction(resolved) {\n const errorAction = {\n action: NetworkErrorAction.DoNothing,\n flags: ErrorActionFlags.None\n };\n if (resolved) {\n errorAction.resolved = true;\n }\n return errorAction;\n}\n\nvar FragmentState = {\n NOT_LOADED: \"NOT_LOADED\",\n APPENDING: \"APPENDING\",\n PARTIAL: \"PARTIAL\",\n OK: \"OK\"\n};\nclass FragmentTracker {\n constructor(hls) {\n this.activePartLists = Object.create(null);\n this.endListFragments = Object.create(null);\n this.fragments = Object.create(null);\n this.timeRanges = Object.create(null);\n this.bufferPadding = 0.2;\n this.hls = void 0;\n this.hasGaps = false;\n this.hls = hls;\n this._registerListeners();\n }\n _registerListeners() {\n const {\n hls\n } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n }\n _unregisterListeners() {\n const {\n hls\n } = this;\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n }\n destroy() {\n this._unregisterListeners();\n // @ts-ignore\n this.fragments =\n // @ts-ignore\n this.activePartLists =\n // @ts-ignore\n this.endListFragments = this.timeRanges = null;\n }\n\n /**\n * Return a Fragment or Part with an appended range that matches the position and levelType\n * Otherwise, return null\n */\n getAppendedFrag(position, levelType) {\n const activeParts = this.activePartLists[levelType];\n if (activeParts) {\n for (let i = activeParts.length; i--;) {\n const activePart = activeParts[i];\n if (!activePart) {\n break;\n }\n const appendedPTS = activePart.end;\n if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {\n return activePart;\n }\n }\n }\n return this.getBufferedFrag(position, levelType);\n }\n\n /**\n * Return a buffered Fragment that matches the position and levelType.\n * A buffered Fragment is one whose loading, parsing and appending is done (completed or \"partial\" meaning aborted).\n * If not found any Fragment, return null\n */\n getBufferedFrag(position, levelType) {\n return this.getFragAtPos(position, levelType, true);\n }\n getFragAtPos(position, levelType, buffered) {\n const {\n fragments\n } = this;\n const keys = Object.keys(fragments);\n for (let i = keys.length; i--;) {\n const fragmentEntity = fragments[keys[i]];\n if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && (!buffered || fragmentEntity.buffered)) {\n const frag = fragmentEntity.body;\n if (frag.start <= position && position <= frag.end) {\n return frag;\n }\n }\n }\n return null;\n }\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)\n */\n detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart, removeAppending) {\n if (this.timeRanges) {\n this.timeRanges[elementaryStream] = timeRange;\n }\n // Check if any flagged fragments have been unloaded\n // excluding anything newer than appendedPartSn\n const appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity) {\n return;\n }\n if (appendedPartSn >= fragmentEntity.body.sn) {\n return;\n }\n if (!fragmentEntity.buffered && (!fragmentEntity.loaded || removeAppending)) {\n if (fragmentEntity.body.type === playlistType) {\n this.removeFragment(fragmentEntity.body);\n }\n return;\n }\n const esData = fragmentEntity.range[elementaryStream];\n if (!esData) {\n return;\n }\n if (esData.time.length === 0) {\n this.removeFragment(fragmentEntity.body);\n return;\n }\n esData.time.some(time => {\n const isNotBuffered = !this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);\n if (isNotBuffered) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n }\n return isNotBuffered;\n });\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n */\n detectPartialFragments(data) {\n const timeRanges = this.timeRanges;\n if (!timeRanges || data.frag.sn === 'initSegment') {\n return;\n }\n const frag = data.frag;\n const fragKey = getFragmentKey(frag);\n const fragmentEntity = this.fragments[fragKey];\n if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {\n return;\n }\n const isFragHint = !frag.relurl;\n Object.keys(timeRanges).forEach(elementaryStream => {\n const streamInfo = frag.elementaryStreams[elementaryStream];\n if (!streamInfo) {\n return;\n }\n const timeRange = timeRanges[elementaryStream];\n const partial = isFragHint || streamInfo.partial === true;\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(frag, data.part, partial, timeRange);\n });\n fragmentEntity.loaded = null;\n if (Object.keys(fragmentEntity.range).length) {\n fragmentEntity.buffered = true;\n const endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;\n if (endList) {\n this.endListFragments[fragmentEntity.body.type] = fragmentEntity;\n }\n if (!isPartial(fragmentEntity)) {\n // Remove older fragment parts from lookup after frag is tracked as buffered\n this.removeParts(frag.sn - 1, frag.type);\n }\n } else {\n // remove fragment if nothing was appended\n this.removeFragment(fragmentEntity.body);\n }\n }\n removeParts(snToKeep, levelType) {\n const activeParts = this.activePartLists[levelType];\n if (!activeParts) {\n return;\n }\n this.activePartLists[levelType] = filterParts(activeParts, part => part.fragment.sn >= snToKeep);\n }\n fragBuffered(frag, force) {\n const fragKey = getFragmentKey(frag);\n let fragmentEntity = this.fragments[fragKey];\n if (!fragmentEntity && force) {\n fragmentEntity = this.fragments[fragKey] = {\n body: frag,\n appendedPTS: null,\n loaded: null,\n buffered: false,\n range: Object.create(null)\n };\n if (frag.gap) {\n this.hasGaps = true;\n }\n }\n if (fragmentEntity) {\n fragmentEntity.loaded = null;\n fragmentEntity.buffered = true;\n }\n }\n getBufferedTimes(fragment, part, partial, timeRange) {\n const buffered = {\n time: [],\n partial\n };\n const startPTS = fragment.start;\n const endPTS = fragment.end;\n const minEndPTS = fragment.minEndPTS || endPTS;\n const maxStartPTS = fragment.maxStartPTS || startPTS;\n for (let i = 0; i < timeRange.length; i++) {\n const startTime = timeRange.start(i) - this.bufferPadding;\n const endTime = timeRange.end(i) + this.bufferPadding;\n if (maxStartPTS >= startTime && minEndPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n buffered.time.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n const start = Math.max(startPTS, timeRange.start(i));\n const end = Math.min(endPTS, timeRange.end(i));\n if (end > start) {\n buffered.partial = true;\n // Check for intersection with buffer\n // Get playable sections of the fragment\n buffered.time.push({\n startPTS: start,\n endPTS: end\n });\n }\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n return buffered;\n }\n\n /**\n * Gets the partial fragment for a certain time\n */\n getPartialFragment(time) {\n let bestFragment = null;\n let timePadding;\n let startTime;\n let endTime;\n let bestOverlap = 0;\n const {\n bufferPadding,\n fragments\n } = this;\n Object.keys(fragments).forEach(key => {\n const fragmentEntity = fragments[key];\n if (!fragmentEntity) {\n return;\n }\n if (isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.start - bufferPadding;\n endTime = fragmentEntity.body.end + bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n isEndListAppended(type) {\n const lastFragmentEntity = this.endListFragments[type];\n return lastFragmentEntity !== undefined && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));\n }\n getState(fragment) {\n const fragKey = getFragmentKey(fragment);\n const fragmentEntity = this.fragments[fragKey];\n if (fragmentEntity) {\n if (!fragmentEntity.buffered) {\n return FragmentState.APPENDING;\n } else if (isPartial(fragmentEntity)) {\n return FragmentState.PARTIAL;\n } else {\n return FragmentState.OK;\n }\n }\n return FragmentState.NOT_LOADED;\n }\n isTimeBuffered(startPTS, endPTS, timeRange) {\n let startTime;\n let endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n return false;\n }\n onManifestLoading() {\n this.removeAllFragments();\n }\n onFragLoaded(event, data) {\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (data.frag.sn === 'initSegment' || data.frag.bitrateTest) {\n return;\n }\n const frag = data.frag;\n // Fragment entity `loaded` FragLoadedData is null when loading parts\n const loaded = data.part ? null : data;\n const fragKey = getFragmentKey(frag);\n this.fragments[fragKey] = {\n body: frag,\n appendedPTS: null,\n loaded,\n buffered: false,\n range: Object.create(null)\n };\n }\n onBufferAppended(event, data) {\n const {\n frag,\n part,\n timeRanges,\n type\n } = data;\n if (frag.sn === 'initSegment') {\n return;\n }\n const playlistType = frag.type;\n if (part) {\n let activeParts = this.activePartLists[playlistType];\n if (!activeParts) {\n this.activePartLists[playlistType] = activeParts = [];\n }\n activeParts.push(part);\n }\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = timeRanges;\n const timeRange = timeRanges[type];\n this.detectEvictedFragments(type, timeRange, playlistType, part);\n }\n onFragBuffered(event, data) {\n this.detectPartialFragments(data);\n }\n hasFragment(fragment) {\n const fragKey = getFragmentKey(fragment);\n return !!this.fragments[fragKey];\n }\n hasFragments(type) {\n const {\n fragments\n } = this;\n const keys = Object.keys(fragments);\n if (!type) {\n return keys.length > 0;\n }\n for (let i = keys.length; i--;) {\n const fragmentEntity = fragments[keys[i]];\n if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === type) {\n return true;\n }\n }\n return false;\n }\n hasParts(type) {\n var _this$activePartLists;\n return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);\n }\n removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {\n if (withGapOnly && !this.hasGaps) {\n return;\n }\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity) {\n return;\n }\n const frag = fragmentEntity.body;\n if (frag.type !== playlistType || withGapOnly && !frag.gap) {\n return;\n }\n if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {\n this.removeFragment(frag);\n }\n });\n }\n removeFragment(fragment) {\n const fragKey = getFragmentKey(fragment);\n fragment.clearElementaryStreamInfo();\n const activeParts = this.activePartLists[fragment.type];\n if (activeParts) {\n const snToRemove = fragment.sn;\n this.activePartLists[fragment.type] = filterParts(activeParts, part => part.fragment.sn !== snToRemove);\n }\n delete this.fragments[fragKey];\n if (fragment.endList) {\n delete this.endListFragments[fragment.type];\n }\n }\n removeAllFragments() {\n var _this$hls, _this$hls$latestLevel;\n this.fragments = Object.create(null);\n this.endListFragments = Object.create(null);\n this.activePartLists = Object.create(null);\n this.hasGaps = false;\n const partlist = (_this$hls = this.hls) == null ? void 0 : (_this$hls$latestLevel = _this$hls.latestLevelDetails) == null ? void 0 : _this$hls$latestLevel.partList;\n if (partlist) {\n partlist.forEach(part => part.clearElementaryStreamInfo());\n }\n }\n}\nfunction isPartial(fragmentEntity) {\n var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;\n return fragmentEntity.buffered && (fragmentEntity.body.gap || ((_fragmentEntity$range = fragmentEntity.range.video) == null ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) == null ? void 0 : _fragmentEntity$range2.partial) || ((_fragmentEntity$range3 = fragmentEntity.range.audiovideo) == null ? void 0 : _fragmentEntity$range3.partial));\n}\nfunction getFragmentKey(fragment) {\n return `${fragment.type}_${fragment.level}_${fragment.sn}`;\n}\nfunction filterParts(partList, predicate) {\n return partList.filter(part => {\n const keep = predicate(part);\n if (!keep) {\n part.clearElementaryStreamInfo();\n }\n return keep;\n });\n}\n\nvar DecrypterAesMode = {\n cbc: 0,\n ctr: 1\n};\n\nclass AESCrypto {\n constructor(subtle, iv, aesMode) {\n this.subtle = void 0;\n this.aesIV = void 0;\n this.aesMode = void 0;\n this.subtle = subtle;\n this.aesIV = iv;\n this.aesMode = aesMode;\n }\n decrypt(data, key) {\n switch (this.aesMode) {\n case DecrypterAesMode.cbc:\n return this.subtle.decrypt({\n name: 'AES-CBC',\n iv: this.aesIV\n }, key, data);\n case DecrypterAesMode.ctr:\n return this.subtle.decrypt({\n name: 'AES-CTR',\n counter: this.aesIV,\n length: 64\n },\n //64 : NIST SP800-38A standard suggests that the counter should occupy half of the counter block\n key, data);\n default:\n throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`);\n }\n }\n}\n\n// PKCS7\nfunction removePadding(array) {\n const outputBytes = array.byteLength;\n const paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return array.slice(0, outputBytes - paddingBytes);\n }\n return array;\n}\nclass AESDecryptor {\n constructor() {\n this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];\n this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];\n this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];\n this.sBox = new Uint32Array(256);\n this.invSBox = new Uint32Array(256);\n this.key = new Uint32Array(0);\n this.ksRows = 0;\n this.keySize = 0;\n this.keySchedule = void 0;\n this.invKeySchedule = void 0;\n this.initTable();\n }\n\n // Using view.getUint32() also swaps the byte order.\n uint8ArrayToUint32Array_(arrayBuffer) {\n const view = new DataView(arrayBuffer);\n const newArray = new Uint32Array(4);\n for (let i = 0; i < 4; i++) {\n newArray[i] = view.getUint32(i * 4);\n }\n return newArray;\n }\n initTable() {\n const sBox = this.sBox;\n const invSBox = this.invSBox;\n const subMix = this.subMix;\n const subMix0 = subMix[0];\n const subMix1 = subMix[1];\n const subMix2 = subMix[2];\n const subMix3 = subMix[3];\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n const d = new Uint32Array(256);\n let x = 0;\n let xi = 0;\n let i = 0;\n for (i = 0; i < 256; i++) {\n if (i < 128) {\n d[i] = i << 1;\n } else {\n d[i] = i << 1 ^ 0x11b;\n }\n }\n for (i = 0; i < 256; i++) {\n let sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;\n sx = sx >>> 8 ^ sx & 0xff ^ 0x63;\n sBox[x] = sx;\n invSBox[sx] = x;\n\n // Compute multiplication\n const x2 = d[x];\n const x4 = d[x2];\n const x8 = d[x4];\n\n // Compute sub/invSub bytes, mix columns tables\n let t = d[sx] * 0x101 ^ sx * 0x1010100;\n subMix0[x] = t << 24 | t >>> 8;\n subMix1[x] = t << 16 | t >>> 16;\n subMix2[x] = t << 8 | t >>> 24;\n subMix3[x] = t;\n\n // Compute inv sub bytes, inv mix columns tables\n t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;\n invSubMix0[sx] = t << 24 | t >>> 8;\n invSubMix1[sx] = t << 16 | t >>> 16;\n invSubMix2[sx] = t << 8 | t >>> 24;\n invSubMix3[sx] = t;\n\n // Compute next counter\n if (!x) {\n x = xi = 1;\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]];\n xi ^= d[d[xi]];\n }\n }\n }\n expandKey(keyBuffer) {\n // convert keyBuffer to Uint32Array\n const key = this.uint8ArrayToUint32Array_(keyBuffer);\n let sameKey = true;\n let offset = 0;\n while (offset < key.length && sameKey) {\n sameKey = key[offset] === this.key[offset];\n offset++;\n }\n if (sameKey) {\n return;\n }\n this.key = key;\n const keySize = this.keySize = key.length;\n if (keySize !== 4 && keySize !== 6 && keySize !== 8) {\n throw new Error('Invalid aes key size=' + keySize);\n }\n const ksRows = this.ksRows = (keySize + 6 + 1) * 4;\n let ksRow;\n let invKsRow;\n const keySchedule = this.keySchedule = new Uint32Array(ksRows);\n const invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);\n const sbox = this.sBox;\n const rcon = this.rcon;\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n let prev;\n let t;\n for (ksRow = 0; ksRow < ksRows; ksRow++) {\n if (ksRow < keySize) {\n prev = keySchedule[ksRow] = key[ksRow];\n continue;\n }\n t = prev;\n if (ksRow % keySize === 0) {\n // Rot word\n t = t << 8 | t >>> 24;\n\n // Sub word\n t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];\n\n // Mix Rcon\n t ^= rcon[ksRow / keySize | 0] << 24;\n } else if (keySize > 6 && ksRow % keySize === 4) {\n // Sub word\n t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];\n }\n keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;\n }\n for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {\n ksRow = ksRows - invKsRow;\n if (invKsRow & 3) {\n t = keySchedule[ksRow];\n } else {\n t = keySchedule[ksRow - 4];\n }\n if (invKsRow < 4 || ksRow <= 4) {\n invKeySchedule[invKsRow] = t;\n } else {\n invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];\n }\n invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;\n }\n }\n\n // Adding this as a method greatly improves performance.\n networkToHostOrderSwap(word) {\n return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;\n }\n decrypt(inputArrayBuffer, offset, aesIV) {\n const nRounds = this.keySize + 6;\n const invKeySchedule = this.invKeySchedule;\n const invSBOX = this.invSBox;\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n const initVector = this.uint8ArrayToUint32Array_(aesIV);\n let initVector0 = initVector[0];\n let initVector1 = initVector[1];\n let initVector2 = initVector[2];\n let initVector3 = initVector[3];\n const inputInt32 = new Int32Array(inputArrayBuffer);\n const outputInt32 = new Int32Array(inputInt32.length);\n let t0, t1, t2, t3;\n let s0, s1, s2, s3;\n let inputWords0, inputWords1, inputWords2, inputWords3;\n let ksRow, i;\n const swapWord = this.networkToHostOrderSwap;\n while (offset < inputInt32.length) {\n inputWords0 = swapWord(inputInt32[offset]);\n inputWords1 = swapWord(inputInt32[offset + 1]);\n inputWords2 = swapWord(inputInt32[offset + 2]);\n inputWords3 = swapWord(inputInt32[offset + 3]);\n s0 = inputWords0 ^ invKeySchedule[0];\n s1 = inputWords3 ^ invKeySchedule[1];\n s2 = inputWords2 ^ invKeySchedule[2];\n s3 = inputWords1 ^ invKeySchedule[3];\n ksRow = 4;\n\n // Iterate through the rounds of decryption\n for (i = 1; i < nRounds; i++) {\n t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];\n t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];\n t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];\n t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];\n // Update state\n s0 = t0;\n s1 = t1;\n s2 = t2;\n s3 = t3;\n ksRow = ksRow + 4;\n }\n\n // Shift rows, sub bytes, add round key\n t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];\n t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];\n t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];\n t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];\n\n // Write\n outputInt32[offset] = swapWord(t0 ^ initVector0);\n outputInt32[offset + 1] = swapWord(t3 ^ initVector1);\n outputInt32[offset + 2] = swapWord(t2 ^ initVector2);\n outputInt32[offset + 3] = swapWord(t1 ^ initVector3);\n\n // reset initVector to last 4 unsigned int\n initVector0 = inputWords0;\n initVector1 = inputWords1;\n initVector2 = inputWords2;\n initVector3 = inputWords3;\n offset = offset + 4;\n }\n return outputInt32.buffer;\n }\n}\n\nclass FastAESKey {\n constructor(subtle, key, aesMode) {\n this.subtle = void 0;\n this.key = void 0;\n this.aesMode = void 0;\n this.subtle = subtle;\n this.key = key;\n this.aesMode = aesMode;\n }\n expandKey() {\n const subtleAlgoName = getSubtleAlgoName(this.aesMode);\n return this.subtle.importKey('raw', this.key, {\n name: subtleAlgoName\n }, false, ['encrypt', 'decrypt']);\n }\n}\nfunction getSubtleAlgoName(aesMode) {\n switch (aesMode) {\n case DecrypterAesMode.cbc:\n return 'AES-CBC';\n case DecrypterAesMode.ctr:\n return 'AES-CTR';\n default:\n throw new Error(`[FastAESKey] invalid aes mode ${aesMode}`);\n }\n}\n\nconst CHUNK_SIZE = 16; // 16 bytes, 128 bits\n\nclass Decrypter {\n constructor(config, {\n removePKCS7Padding = true\n } = {}) {\n this.logEnabled = true;\n this.removePKCS7Padding = void 0;\n this.subtle = null;\n this.softwareDecrypter = null;\n this.key = null;\n this.fastAesKey = null;\n this.remainderData = null;\n this.currentIV = null;\n this.currentResult = null;\n this.useSoftware = void 0;\n this.enableSoftwareAES = void 0;\n this.enableSoftwareAES = config.enableSoftwareAES;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n const browserCrypto = self.crypto;\n if (browserCrypto) {\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n }\n } catch (e) {\n /* no-op */\n }\n }\n this.useSoftware = !this.subtle;\n }\n destroy() {\n this.subtle = null;\n this.softwareDecrypter = null;\n this.key = null;\n this.fastAesKey = null;\n this.remainderData = null;\n this.currentIV = null;\n this.currentResult = null;\n }\n isSync() {\n return this.useSoftware;\n }\n flush() {\n const {\n currentResult,\n remainderData\n } = this;\n if (!currentResult || remainderData) {\n this.reset();\n return null;\n }\n const data = new Uint8Array(currentResult);\n this.reset();\n if (this.removePKCS7Padding) {\n return removePadding(data);\n }\n return data;\n }\n reset() {\n this.currentResult = null;\n this.currentIV = null;\n this.remainderData = null;\n if (this.softwareDecrypter) {\n this.softwareDecrypter = null;\n }\n }\n decrypt(data, key, iv, aesMode) {\n if (this.useSoftware) {\n return new Promise((resolve, reject) => {\n const dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);\n this.softwareDecrypt(dataView, key, iv, aesMode);\n const decryptResult = this.flush();\n if (decryptResult) {\n resolve(decryptResult.buffer);\n } else {\n reject(new Error('[softwareDecrypt] Failed to decrypt data'));\n }\n });\n }\n return this.webCryptoDecrypt(new Uint8Array(data), key, iv, aesMode);\n }\n\n // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached\n // data is handled in the flush() call\n softwareDecrypt(data, key, iv, aesMode) {\n const {\n currentIV,\n currentResult,\n remainderData\n } = this;\n if (aesMode !== DecrypterAesMode.cbc || key.byteLength !== 16) {\n logger.warn('SoftwareDecrypt: can only handle AES-128-CBC');\n return null;\n }\n this.logOnce('JS AES decrypt');\n // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call\n // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached\n // the end on flush(), but by that time we have already received all bytes for the segment.\n // Progressive decryption does not work with WebCrypto\n\n if (remainderData) {\n data = appendUint8Array(remainderData, data);\n this.remainderData = null;\n }\n\n // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)\n const currentChunk = this.getValidChunk(data);\n if (!currentChunk.length) {\n return null;\n }\n if (currentIV) {\n iv = currentIV;\n }\n let softwareDecrypter = this.softwareDecrypter;\n if (!softwareDecrypter) {\n softwareDecrypter = this.softwareDecrypter = new AESDecryptor();\n }\n softwareDecrypter.expandKey(key);\n const result = currentResult;\n this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);\n this.currentIV = currentChunk.slice(-16).buffer;\n if (!result) {\n return null;\n }\n return result;\n }\n webCryptoDecrypt(data, key, iv, aesMode) {\n if (this.key !== key || !this.fastAesKey) {\n if (!this.subtle) {\n return Promise.resolve(this.onWebCryptoError(data, key, iv, aesMode));\n }\n this.key = key;\n this.fastAesKey = new FastAESKey(this.subtle, key, aesMode);\n }\n return this.fastAesKey.expandKey().then(aesKey => {\n // decrypt using web crypto\n if (!this.subtle) {\n return Promise.reject(new Error('web crypto not initialized'));\n }\n this.logOnce('WebCrypto AES decrypt');\n const crypto = new AESCrypto(this.subtle, new Uint8Array(iv), aesMode);\n return crypto.decrypt(data.buffer, aesKey);\n }).catch(err => {\n logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`);\n return this.onWebCryptoError(data, key, iv, aesMode);\n });\n }\n onWebCryptoError(data, key, iv, aesMode) {\n const enableSoftwareAES = this.enableSoftwareAES;\n if (enableSoftwareAES) {\n this.useSoftware = true;\n this.logEnabled = true;\n this.softwareDecrypt(data, key, iv, aesMode);\n const decryptResult = this.flush();\n if (decryptResult) {\n return decryptResult.buffer;\n }\n }\n throw new Error('WebCrypto' + (enableSoftwareAES ? ' and softwareDecrypt' : '') + ': failed to decrypt data');\n }\n getValidChunk(data) {\n let currentChunk = data;\n const splitPoint = data.length - data.length % CHUNK_SIZE;\n if (splitPoint !== data.length) {\n currentChunk = data.slice(0, splitPoint);\n this.remainderData = data.slice(splitPoint);\n }\n return currentChunk;\n }\n logOnce(msg) {\n if (!this.logEnabled) {\n return;\n }\n logger.log(`[decrypter]: ${msg}`);\n this.logEnabled = false;\n }\n}\n\nconst MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb\n\nclass FragmentLoader {\n constructor(config) {\n this.config = void 0;\n this.loader = null;\n this.partLoadTimeout = -1;\n this.config = config;\n }\n destroy() {\n if (this.loader) {\n this.loader.destroy();\n this.loader = null;\n }\n }\n abort() {\n if (this.loader) {\n // Abort the loader for current fragment. Only one may load at any given time\n this.loader.abort();\n }\n }\n load(frag, onProgress) {\n const url = frag.url;\n if (!url) {\n return Promise.reject(new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n error: new Error(`Fragment does not have a ${url ? 'part list' : 'url'}`),\n networkDetails: null\n }));\n }\n this.abort();\n const config = this.config;\n const FragmentILoader = config.fLoader;\n const DefaultILoader = config.loader;\n return new Promise((resolve, reject) => {\n if (this.loader) {\n this.loader.destroy();\n }\n if (frag.gap) {\n if (frag.tagList.some(tags => tags[0] === 'GAP')) {\n reject(createGapLoadError(frag));\n return;\n } else {\n // Reset temporary treatment as GAP tag\n frag.gap = false;\n }\n }\n const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);\n const loaderContext = createLoaderContext(frag);\n frag.loader = loader;\n const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);\n const loaderConfig = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE\n };\n // Assign frag stats to the loader's stats reference\n frag.stats = loader.stats;\n const callbacks = {\n onSuccess: (response, stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n let payload = response.data;\n if (context.resetIV && frag.decryptdata) {\n frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));\n payload = payload.slice(16);\n }\n resolve({\n frag,\n part: null,\n payload,\n networkDetails\n });\n },\n onError: (response, context, networkDetails, stats) => {\n this.resetLoader(frag, loader);\n reject(new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n response: _objectSpread2({\n url,\n data: undefined\n }, response),\n error: new Error(`HTTP Error ${response.code} ${response.text}`),\n networkDetails,\n stats\n }));\n },\n onAbort: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.INTERNAL_ABORTED,\n fatal: false,\n frag,\n error: new Error('Aborted'),\n networkDetails,\n stats\n }));\n },\n onTimeout: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_TIMEOUT,\n fatal: false,\n frag,\n error: new Error(`Timeout after ${loaderConfig.timeout}ms`),\n networkDetails,\n stats\n }));\n }\n };\n if (onProgress) {\n callbacks.onProgress = (stats, context, data, networkDetails) => onProgress({\n frag,\n part: null,\n payload: data,\n networkDetails\n });\n }\n loader.load(loaderContext, loaderConfig, callbacks);\n });\n }\n loadPart(frag, part, onProgress) {\n this.abort();\n const config = this.config;\n const FragmentILoader = config.fLoader;\n const DefaultILoader = config.loader;\n return new Promise((resolve, reject) => {\n if (this.loader) {\n this.loader.destroy();\n }\n if (frag.gap || part.gap) {\n reject(createGapLoadError(frag, part));\n return;\n }\n const loader = this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);\n const loaderContext = createLoaderContext(frag, part);\n frag.loader = loader;\n // Should we define another load policy for parts?\n const loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);\n const loaderConfig = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n highWaterMark: MIN_CHUNK_SIZE\n };\n // Assign part stats to the loader's stats reference\n part.stats = loader.stats;\n loader.load(loaderContext, loaderConfig, {\n onSuccess: (response, stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n this.updateStatsFromPart(frag, part);\n const partLoadedData = {\n frag,\n part,\n payload: response.data,\n networkDetails\n };\n onProgress(partLoadedData);\n resolve(partLoadedData);\n },\n onError: (response, context, networkDetails, stats) => {\n this.resetLoader(frag, loader);\n reject(new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n part,\n response: _objectSpread2({\n url: loaderContext.url,\n data: undefined\n }, response),\n error: new Error(`HTTP Error ${response.code} ${response.text}`),\n networkDetails,\n stats\n }));\n },\n onAbort: (stats, context, networkDetails) => {\n frag.stats.aborted = part.stats.aborted;\n this.resetLoader(frag, loader);\n reject(new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.INTERNAL_ABORTED,\n fatal: false,\n frag,\n part,\n error: new Error('Aborted'),\n networkDetails,\n stats\n }));\n },\n onTimeout: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_TIMEOUT,\n fatal: false,\n frag,\n part,\n error: new Error(`Timeout after ${loaderConfig.timeout}ms`),\n networkDetails,\n stats\n }));\n }\n });\n });\n }\n updateStatsFromPart(frag, part) {\n const fragStats = frag.stats;\n const partStats = part.stats;\n const partTotal = partStats.total;\n fragStats.loaded += partStats.loaded;\n if (partTotal) {\n const estTotalParts = Math.round(frag.duration / part.duration);\n const estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);\n const estRemainingParts = estTotalParts - estLoadedParts;\n const estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);\n fragStats.total = fragStats.loaded + estRemainingBytes;\n } else {\n fragStats.total = Math.max(fragStats.loaded, fragStats.total);\n }\n const fragLoading = fragStats.loading;\n const partLoading = partStats.loading;\n if (fragLoading.start) {\n // add to fragment loader latency\n fragLoading.first += partLoading.first - partLoading.start;\n } else {\n fragLoading.start = partLoading.start;\n fragLoading.first = partLoading.first;\n }\n fragLoading.end = partLoading.end;\n }\n resetLoader(frag, loader) {\n frag.loader = null;\n if (this.loader === loader) {\n self.clearTimeout(this.partLoadTimeout);\n this.loader = null;\n }\n loader.destroy();\n }\n}\nfunction createLoaderContext(frag, part = null) {\n const segment = part || frag;\n const loaderContext = {\n frag,\n part,\n responseType: 'arraybuffer',\n url: segment.url,\n headers: {},\n rangeStart: 0,\n rangeEnd: 0\n };\n const start = segment.byteRangeStartOffset;\n const end = segment.byteRangeEndOffset;\n if (isFiniteNumber(start) && isFiniteNumber(end)) {\n var _frag$decryptdata;\n let byteRangeStart = start;\n let byteRangeEnd = end;\n if (frag.sn === 'initSegment' && isMethodFullSegmentAesCbc((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method)) {\n // MAP segment encrypted with method 'AES-128' or 'AES-256' (cbc), when served with HTTP Range,\n // has the unencrypted size specified in the range.\n // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6\n const fragmentLen = end - start;\n if (fragmentLen % 16) {\n byteRangeEnd = end + (16 - fragmentLen % 16);\n }\n if (start !== 0) {\n loaderContext.resetIV = true;\n byteRangeStart = start - 16;\n }\n }\n loaderContext.rangeStart = byteRangeStart;\n loaderContext.rangeEnd = byteRangeEnd;\n }\n return loaderContext;\n}\nfunction createGapLoadError(frag, part) {\n const error = new Error(`GAP ${frag.gap ? 'tag' : 'attribute'} found`);\n const errorData = {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_GAP,\n fatal: false,\n frag,\n error,\n networkDetails: null\n };\n if (part) {\n errorData.part = part;\n }\n (part ? part : frag).stats.aborted = true;\n return new LoadError(errorData);\n}\nfunction isMethodFullSegmentAesCbc(method) {\n return method === 'AES-128' || method === 'AES-256';\n}\nclass LoadError extends Error {\n constructor(data) {\n super(data.error.message);\n this.data = void 0;\n this.data = data;\n }\n}\n\n/**\n * @ignore\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\nclass TaskLoop extends Logger {\n constructor(label, logger) {\n super(label, logger);\n this._boundTick = void 0;\n this._tickTimer = null;\n this._tickInterval = null;\n this._tickCallCount = 0;\n this._boundTick = this.tick.bind(this);\n }\n destroy() {\n this.onHandlerDestroying();\n this.onHandlerDestroyed();\n }\n onHandlerDestroying() {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n }\n onHandlerDestroyed() {}\n hasInterval() {\n return !!this._tickInterval;\n }\n hasNextTick() {\n return !!this._tickTimer;\n }\n\n /**\n * @param millis - Interval time (ms)\n * @eturns True when interval has been scheduled, false when already scheduled (no effect)\n */\n setInterval(millis) {\n if (!this._tickInterval) {\n this._tickCallCount = 0;\n this._tickInterval = self.setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n }\n\n /**\n * @returns True when interval was cleared, false when none was set (no effect)\n */\n clearInterval() {\n if (this._tickInterval) {\n self.clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n }\n\n /**\n * @returns True when timeout was cleared, false when none was set (no effect)\n */\n clearNextTick() {\n if (this._tickTimer) {\n self.clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n }\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n tick() {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.tickImmediate();\n }\n this._tickCallCount = 0;\n }\n }\n tickImmediate() {\n this.clearNextTick();\n this._tickTimer = self.setTimeout(this._boundTick, 0);\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n doTick() {}\n}\n\nclass ChunkMetadata {\n constructor(level, sn, id, size = 0, part = -1, partial = false) {\n this.level = void 0;\n this.sn = void 0;\n this.part = void 0;\n this.id = void 0;\n this.size = void 0;\n this.partial = void 0;\n this.transmuxing = getNewPerformanceTiming();\n this.buffering = {\n audio: getNewPerformanceTiming(),\n video: getNewPerformanceTiming(),\n audiovideo: getNewPerformanceTiming()\n };\n this.level = level;\n this.sn = sn;\n this.id = id;\n this.size = size;\n this.part = part;\n this.partial = partial;\n }\n}\nfunction getNewPerformanceTiming() {\n return {\n start: 0,\n executeStart: 0,\n executeEnd: 0,\n end: 0\n };\n}\n\n/**\n * Provides methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n */\n\nconst noopBuffered = {\n length: 0,\n start: () => 0,\n end: () => 0\n};\nclass BufferHelper {\n /**\n * Return true if `media`'s buffered include `position`\n */\n static isBuffered(media, position) {\n if (media) {\n const buffered = BufferHelper.getBuffered(media);\n for (let i = buffered.length; i--;) {\n if (position >= buffered.start(i) && position <= buffered.end(i)) {\n return true;\n }\n }\n }\n return false;\n }\n static bufferedRanges(media) {\n if (media) {\n const timeRanges = BufferHelper.getBuffered(media);\n return BufferHelper.timeRangesToArray(timeRanges);\n }\n return [];\n }\n static timeRangesToArray(timeRanges) {\n const buffered = [];\n for (let i = 0; i < timeRanges.length; i++) {\n buffered.push({\n start: timeRanges.start(i),\n end: timeRanges.end(i)\n });\n }\n return buffered;\n }\n static bufferInfo(media, pos, maxHoleDuration) {\n if (media) {\n const buffered = BufferHelper.bufferedRanges(media);\n if (buffered.length) {\n return BufferHelper.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n }\n return {\n len: 0,\n start: pos,\n end: pos,\n bufferedIndex: -1\n };\n }\n static bufferedInfo(buffered, pos, maxHoleDuration) {\n pos = Math.max(0, pos);\n // sort on buffer.start/smaller end (IE does not always return sorted buffered range)\n if (buffered.length > 1) {\n buffered.sort((a, b) => a.start - b.start || b.end - a.end);\n }\n let bufferedIndex = -1;\n let buffered2 = [];\n if (maxHoleDuration) {\n // there might be some small holes between buffer time range\n // consider that holes smaller than maxHoleDuration are irrelevant and build another\n // buffer time range representations that discards those holes\n for (let i = 0; i < buffered.length; i++) {\n if (pos >= buffered[i].start && pos <= buffered[i].end) {\n bufferedIndex = i;\n }\n const buf2len = buffered2.length;\n if (buf2len) {\n const buf2end = buffered2[buf2len - 1].end;\n // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)\n if (buffered[i].start - buf2end < maxHoleDuration) {\n // merge overlapping time ranges\n // update lastRange.end only if smaller than item.end\n // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)\n // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])\n if (buffered[i].end > buf2end) {\n buffered2[buf2len - 1].end = buffered[i].end;\n }\n } else {\n // big hole\n buffered2.push(buffered[i]);\n }\n } else {\n // first value\n buffered2.push(buffered[i]);\n }\n }\n } else {\n buffered2 = buffered;\n }\n let bufferLen = 0;\n let nextStart;\n\n // bufferStart and bufferEnd are buffer boundaries around current playback position (pos)\n let bufferStart = pos;\n let bufferEnd = pos;\n for (let i = 0; i < buffered2.length; i++) {\n const start = buffered2[i].start;\n const end = buffered2[i].end;\n // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if (bufferedIndex === -1 && pos >= start && pos <= end) {\n bufferedIndex = i;\n }\n if (pos + maxHoleDuration >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if (pos + maxHoleDuration < start) {\n nextStart = start;\n break;\n }\n }\n return {\n len: bufferLen,\n start: bufferStart || 0,\n end: bufferEnd || 0,\n nextStart,\n buffered,\n bufferedIndex\n };\n }\n\n /**\n * Safe method to get buffered property.\n * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource\n */\n static getBuffered(media) {\n try {\n return media.buffered || noopBuffered;\n } catch (e) {\n logger.log('failed to get media.buffered', e);\n return noopBuffered;\n }\n }\n}\n\nconst VARIABLE_REPLACEMENT_REGEX = /\\{\\$([a-zA-Z0-9-_]+)\\}/g;\nfunction hasVariableReferences(str) {\n return VARIABLE_REPLACEMENT_REGEX.test(str);\n}\nfunction substituteVariables(parsed, value) {\n if (parsed.variableList !== null || parsed.hasVariableRefs) {\n const variableList = parsed.variableList;\n return value.replace(VARIABLE_REPLACEMENT_REGEX, variableReference => {\n const variableName = variableReference.substring(2, variableReference.length - 1);\n const variableValue = variableList == null ? void 0 : variableList[variableName];\n if (variableValue === undefined) {\n parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: \"${variableName}\"`));\n return variableReference;\n }\n return variableValue;\n });\n }\n return value;\n}\nfunction addVariableDefinition(parsed, attr, parentUrl) {\n let variableList = parsed.variableList;\n if (!variableList) {\n parsed.variableList = variableList = {};\n }\n let NAME;\n let VALUE;\n if ('QUERYPARAM' in attr) {\n NAME = attr.QUERYPARAM;\n try {\n const searchParams = new self.URL(parentUrl).searchParams;\n if (searchParams.has(NAME)) {\n VALUE = searchParams.get(NAME);\n } else {\n throw new Error(`\"${NAME}\" does not match any query parameter in URI: \"${parentUrl}\"`);\n }\n } catch (error) {\n parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE QUERYPARAM: ${error.message}`));\n }\n } else {\n NAME = attr.NAME;\n VALUE = attr.VALUE;\n }\n if (NAME in variableList) {\n parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE duplicate Variable Name declarations: \"${NAME}\"`));\n } else {\n variableList[NAME] = VALUE || '';\n }\n}\nfunction importVariableDefinition(parsed, attr, sourceVariableList) {\n const IMPORT = attr.IMPORT;\n if (sourceVariableList && IMPORT in sourceVariableList) {\n let variableList = parsed.variableList;\n if (!variableList) {\n parsed.variableList = variableList = {};\n }\n variableList[IMPORT] = sourceVariableList[IMPORT];\n } else {\n parsed.playlistParsingError || (parsed.playlistParsingError = new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: \"${IMPORT}\"`));\n }\n}\n\nconst DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/;\nconst ATTR_LIST_REGEX = /(.+?)=(\".*?\"|.*?)(?:,|$)/g;\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nclass AttrList {\n constructor(attrs, parsed) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs, parsed);\n }\n _extends(this, attrs);\n }\n get clientAttrs() {\n return Object.keys(this).filter(attr => attr.substring(0, 2) === 'X-');\n }\n decimalInteger(attrName) {\n const intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n return intValue;\n }\n hexadecimalInteger(attrName) {\n if (this[attrName]) {\n let stringValue = (this[attrName] || '0x').slice(2);\n stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;\n const value = new Uint8Array(stringValue.length / 2);\n for (let i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n return value;\n }\n return null;\n }\n hexadecimalIntegerAsNumber(attrName) {\n const intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n return intValue;\n }\n decimalFloatingPoint(attrName) {\n return parseFloat(this[attrName]);\n }\n optionalFloat(attrName, defaultValue) {\n const value = this[attrName];\n return value ? parseFloat(value) : defaultValue;\n }\n enumeratedString(attrName) {\n return this[attrName];\n }\n enumeratedStringList(attrName, dict) {\n const attrValue = this[attrName];\n return (attrValue ? attrValue.split(/[ ,]+/) : []).reduce((result, identifier) => {\n result[identifier.toLowerCase()] = true;\n return result;\n }, dict);\n }\n bool(attrName) {\n return this[attrName] === 'YES';\n }\n decimalResolution(attrName) {\n const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n }\n static parseAttrList(input, parsed) {\n let match;\n const attrs = {};\n const quote = '\"';\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n const name = match[1].trim();\n let value = match[2];\n const quotedString = value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1;\n let hexadecimalSequence = false;\n if (quotedString) {\n value = value.slice(1, -1);\n } else {\n switch (name) {\n case 'IV':\n case 'SCTE35-CMD':\n case 'SCTE35-IN':\n case 'SCTE35-OUT':\n hexadecimalSequence = true;\n }\n }\n if (parsed && (quotedString || hexadecimalSequence)) {\n {\n value = substituteVariables(parsed, value);\n }\n } else if (!hexadecimalSequence && !quotedString) {\n switch (name) {\n case 'CLOSED-CAPTIONS':\n if (value === 'NONE') {\n break;\n }\n // falls through\n case 'ALLOWED-CPC':\n case 'CLASS':\n case 'ASSOC-LANGUAGE':\n case 'AUDIO':\n case 'BYTERANGE':\n case 'CHANNELS':\n case 'CHARACTERISTICS':\n case 'CODECS':\n case 'DATA-ID':\n case 'END-DATE':\n case 'GROUP-ID':\n case 'ID':\n case 'IMPORT':\n case 'INSTREAM-ID':\n case 'KEYFORMAT':\n case 'KEYFORMATVERSIONS':\n case 'LANGUAGE':\n case 'NAME':\n case 'PATHWAY-ID':\n case 'QUERYPARAM':\n case 'RECENTLY-REMOVED-DATERANGES':\n case 'SERVER-URI':\n case 'STABLE-RENDITION-ID':\n case 'STABLE-VARIANT-ID':\n case 'START-DATE':\n case 'SUBTITLES':\n case 'SUPPLEMENTAL-CODECS':\n case 'URI':\n case 'VALUE':\n case 'VIDEO':\n case 'X-ASSET-LIST':\n case 'X-ASSET-URI':\n // Since we are not checking tag:attribute combination, just warn rather than ignoring attribute\n logger.warn(`${input}: attribute ${name} is missing quotes`);\n // continue;\n }\n }\n attrs[name] = value;\n }\n return attrs;\n }\n}\n\n// Avoid exporting const enum so that these values can be inlined\n\nconst CLASS_INTERSTITIAL = 'com.apple.hls.interstitial';\nfunction isDateRangeCueAttribute(attrName) {\n return attrName !== \"ID\" && attrName !== \"CLASS\" && attrName !== \"CUE\" && attrName !== \"START-DATE\" && attrName !== \"DURATION\" && attrName !== \"END-DATE\" && attrName !== \"END-ON-NEXT\";\n}\nfunction isSCTE35Attribute(attrName) {\n return attrName === \"SCTE35-OUT\" || attrName === \"SCTE35-IN\" || attrName === \"SCTE35-CMD\";\n}\nclass DateRange {\n constructor(dateRangeAttr, dateRangeWithSameId, tagCount = 0) {\n var _dateRangeWithSameId$;\n this.attr = void 0;\n this.tagAnchor = void 0;\n this.tagOrder = void 0;\n this._startDate = void 0;\n this._endDate = void 0;\n this._dateAtEnd = void 0;\n this._cue = void 0;\n this._badValueForSameId = void 0;\n this.tagAnchor = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagAnchor) || null;\n this.tagOrder = (_dateRangeWithSameId$ = dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagOrder) != null ? _dateRangeWithSameId$ : tagCount;\n if (dateRangeWithSameId) {\n const previousAttr = dateRangeWithSameId.attr;\n for (const key in previousAttr) {\n if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {\n logger.warn(`DATERANGE tag attribute: \"${key}\" does not match for tags with ID: \"${dateRangeAttr.ID}\"`);\n this._badValueForSameId = key;\n break;\n }\n }\n // Merge DateRange tags with the same ID\n dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);\n }\n this.attr = dateRangeAttr;\n if (dateRangeWithSameId) {\n this._startDate = dateRangeWithSameId._startDate;\n this._cue = dateRangeWithSameId._cue;\n this._endDate = dateRangeWithSameId._endDate;\n this._dateAtEnd = dateRangeWithSameId._dateAtEnd;\n } else {\n this._startDate = new Date(dateRangeAttr[\"START-DATE\"]);\n }\n if (\"END-DATE\" in this.attr) {\n const endDate = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.endDate) || new Date(this.attr[\"END-DATE\"]);\n if (isFiniteNumber(endDate.getTime())) {\n this._endDate = endDate;\n }\n }\n }\n get id() {\n return this.attr.ID;\n }\n get class() {\n return this.attr.CLASS;\n }\n get cue() {\n const _cue = this._cue;\n if (_cue === undefined) {\n return this._cue = this.attr.enumeratedStringList(this.attr.CUE ? 'CUE' : 'X-CUE', {\n pre: false,\n post: false,\n once: false\n });\n }\n return _cue;\n }\n get startTime() {\n const {\n tagAnchor\n } = this;\n // eslint-disable-next-line @typescript-eslint/prefer-optional-chain\n if (tagAnchor === null || tagAnchor.programDateTime === null) {\n logger.warn(`Expected tagAnchor Fragment with PDT set for DateRange \"${this.id}\": ${tagAnchor}`);\n return NaN;\n }\n return tagAnchor.start + (this.startDate.getTime() - tagAnchor.programDateTime) / 1000;\n }\n get startDate() {\n return this._startDate;\n }\n get endDate() {\n const dateAtEnd = this._endDate || this._dateAtEnd;\n if (dateAtEnd) {\n return dateAtEnd;\n }\n const duration = this.duration;\n if (duration !== null) {\n return this._dateAtEnd = new Date(this._startDate.getTime() + duration * 1000);\n }\n return null;\n }\n get duration() {\n if (\"DURATION\" in this.attr) {\n const duration = this.attr.decimalFloatingPoint(\"DURATION\");\n if (isFiniteNumber(duration)) {\n return duration;\n }\n } else if (this._endDate) {\n return (this._endDate.getTime() - this._startDate.getTime()) / 1000;\n }\n return null;\n }\n get plannedDuration() {\n if (\"PLANNED-DURATION\" in this.attr) {\n return this.attr.decimalFloatingPoint(\"PLANNED-DURATION\");\n }\n return null;\n }\n get endOnNext() {\n return this.attr.bool(\"END-ON-NEXT\");\n }\n get isInterstitial() {\n return this.class === CLASS_INTERSTITIAL;\n }\n get isValid() {\n return !!this.id && !this._badValueForSameId && isFiniteNumber(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class) && (!this.attr.CUE || !this.cue.pre && !this.cue.post || this.cue.pre !== this.cue.post) && (!this.isInterstitial || 'X-ASSET-URI' in this.attr || 'X-ASSET-LIST' in this.attr);\n }\n}\n\nconst DEFAULT_TARGET_DURATION = 10;\n\n/**\n * Object representing parsed data from an HLS Media Playlist. Found in {@link hls.js#Level.details}.\n */\nclass LevelDetails {\n constructor(baseUrl) {\n this.PTSKnown = false;\n this.alignedSliding = false;\n this.averagetargetduration = void 0;\n this.endCC = 0;\n this.endSN = 0;\n this.fragments = void 0;\n this.fragmentHint = void 0;\n this.partList = null;\n this.dateRanges = void 0;\n this.dateRangeTagCount = 0;\n this.live = true;\n this.requestScheduled = -1;\n this.ageHeader = 0;\n this.advancedDateTime = void 0;\n this.updated = true;\n this.advanced = true;\n this.misses = 0;\n this.startCC = 0;\n this.startSN = 0;\n this.startTimeOffset = null;\n this.targetduration = 0;\n this.totalduration = 0;\n this.type = null;\n this.url = void 0;\n this.m3u8 = '';\n this.version = null;\n this.canBlockReload = false;\n this.canSkipUntil = 0;\n this.canSkipDateRanges = false;\n this.skippedSegments = 0;\n this.recentlyRemovedDateranges = void 0;\n this.partHoldBack = 0;\n this.holdBack = 0;\n this.partTarget = 0;\n this.preloadHint = void 0;\n this.renditionReports = void 0;\n this.tuneInGoal = 0;\n this.deltaUpdateFailed = void 0;\n this.driftStartTime = 0;\n this.driftEndTime = 0;\n this.driftStart = 0;\n this.driftEnd = 0;\n this.encryptedFragments = void 0;\n this.playlistParsingError = null;\n this.variableList = null;\n this.hasVariableRefs = false;\n this.appliedTimelineOffset = void 0;\n this.fragments = [];\n this.encryptedFragments = [];\n this.dateRanges = {};\n this.url = baseUrl;\n }\n reloaded(previous) {\n if (!previous) {\n this.advanced = true;\n this.updated = true;\n return;\n }\n const partSnDiff = this.lastPartSn - previous.lastPartSn;\n const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;\n this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;\n this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;\n if (this.updated || this.advanced) {\n this.misses = Math.floor(previous.misses * 0.6);\n } else {\n this.misses = previous.misses + 1;\n }\n }\n get hasProgramDateTime() {\n if (this.fragments.length) {\n return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);\n }\n return false;\n }\n get levelTargetDuration() {\n return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;\n }\n get drift() {\n const runTime = this.driftEndTime - this.driftStartTime;\n if (runTime > 0) {\n const runDuration = this.driftEnd - this.driftStart;\n return runDuration * 1000 / runTime;\n }\n return 1;\n }\n get edge() {\n return this.partEnd || this.fragmentEnd;\n }\n get partEnd() {\n var _this$partList;\n if ((_this$partList = this.partList) != null && _this$partList.length) {\n return this.partList[this.partList.length - 1].end;\n }\n return this.fragmentEnd;\n }\n get fragmentEnd() {\n var _this$fragments;\n if ((_this$fragments = this.fragments) != null && _this$fragments.length) {\n return this.fragments[this.fragments.length - 1].end;\n }\n return 0;\n }\n get fragmentStart() {\n var _this$fragments2;\n if ((_this$fragments2 = this.fragments) != null && _this$fragments2.length) {\n return this.fragments[0].start;\n }\n return 0;\n }\n get age() {\n if (this.advancedDateTime) {\n return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;\n }\n return 0;\n }\n get lastPartIndex() {\n var _this$partList2;\n if ((_this$partList2 = this.partList) != null && _this$partList2.length) {\n return this.partList[this.partList.length - 1].index;\n }\n return -1;\n }\n get maxPartIndex() {\n const partList = this.partList;\n if (partList) {\n const lastIndex = this.lastPartIndex;\n if (lastIndex !== -1) {\n for (let i = partList.length; i--;) {\n if (partList[i].index > lastIndex) {\n return partList[i].index;\n }\n }\n return lastIndex;\n }\n }\n return 0;\n }\n get lastPartSn() {\n var _this$partList3;\n if ((_this$partList3 = this.partList) != null && _this$partList3.length) {\n return this.partList[this.partList.length - 1].fragment.sn;\n }\n return this.endSN;\n }\n get expired() {\n if (this.live && this.age && this.misses < 3) {\n const playlistWindowDuration = this.partEnd - this.fragmentStart;\n return this.age > Math.max(playlistWindowDuration, this.totalduration) + this.levelTargetDuration;\n }\n return false;\n }\n}\n\nfunction isFullSegmentEncryption(method) {\n return method === 'AES-128' || method === 'AES-256' || method === 'AES-256-CTR';\n}\nfunction getAesModeFromFullSegmentMethod(method) {\n switch (method) {\n case 'AES-128':\n case 'AES-256':\n return DecrypterAesMode.cbc;\n case 'AES-256-CTR':\n return DecrypterAesMode.ctr;\n default:\n throw new Error(`invalid full segment method ${method}`);\n }\n}\n\nfunction base64Decode(base64encodedStr) {\n return Uint8Array.from(atob(base64encodedStr), c => c.charCodeAt(0));\n}\n\n// breaking up those two types in order to clarify what is happening in the decoding path.\n\n// http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n/* utf.js - UTF-8 <=> UTF-16 convertion\n *\n * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n * Version: 1.0\n * LastModified: Dec 25 1999\n * This library is free. You can redistribute it and/or modify it.\n */\n\nfunction strToUtf8array(str) {\n return Uint8Array.from(unescape(encodeURIComponent(str)), c => c.charCodeAt(0));\n}\n\nfunction getKeyIdBytes(str) {\n const keyIdbytes = strToUtf8array(str).subarray(0, 16);\n const paddedkeyIdbytes = new Uint8Array(16);\n paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);\n return paddedkeyIdbytes;\n}\nfunction changeEndianness(keyId) {\n const swap = function swap(array, from, to) {\n const cur = array[from];\n array[from] = array[to];\n array[to] = cur;\n };\n swap(keyId, 0, 3);\n swap(keyId, 1, 2);\n swap(keyId, 4, 5);\n swap(keyId, 6, 7);\n}\nfunction convertDataUriToArrayBytes(uri) {\n // data:[<media type][;attribute=value][;base64],<data>\n const colonsplit = uri.split(':');\n let keydata = null;\n if (colonsplit[0] === 'data' && colonsplit.length === 2) {\n const semicolonsplit = colonsplit[1].split(';');\n const commasplit = semicolonsplit[semicolonsplit.length - 1].split(',');\n if (commasplit.length === 2) {\n const isbase64 = commasplit[0] === 'base64';\n const data = commasplit[1];\n if (isbase64) {\n semicolonsplit.splice(-1, 1); // remove from processing\n keydata = base64Decode(data);\n } else {\n keydata = getKeyIdBytes(data);\n }\n }\n }\n return keydata;\n}\n\n/** returns `undefined` is `self` is missing, e.g. in node */\nconst optionalSelf = typeof self !== 'undefined' ? self : undefined;\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess\n */\nvar KeySystems = {\n CLEARKEY: \"org.w3.clearkey\",\n FAIRPLAY: \"com.apple.fps\",\n PLAYREADY: \"com.microsoft.playready\",\n WIDEVINE: \"com.widevine.alpha\"\n};\n\n// Playlist #EXT-X-KEY KEYFORMAT values\nvar KeySystemFormats = {\n CLEARKEY: \"org.w3.clearkey\",\n FAIRPLAY: \"com.apple.streamingkeydelivery\",\n PLAYREADY: \"com.microsoft.playready\",\n WIDEVINE: \"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed\"\n};\nfunction keySystemFormatToKeySystemDomain(format) {\n switch (format) {\n case KeySystemFormats.FAIRPLAY:\n return KeySystems.FAIRPLAY;\n case KeySystemFormats.PLAYREADY:\n return KeySystems.PLAYREADY;\n case KeySystemFormats.WIDEVINE:\n return KeySystems.WIDEVINE;\n case KeySystemFormats.CLEARKEY:\n return KeySystems.CLEARKEY;\n }\n}\n\n// System IDs for which we can extract a key ID from \"encrypted\" event PSSH\nvar KeySystemIds = {\n CENC: \"1077efecc0b24d02ace33c1e52e2fb4b\",\n CLEARKEY: \"e2719d58a985b3c9781ab030af78d30e\",\n PLAYREADY: \"9a04f07998404286ab92e65be0885f95\",\n WIDEVINE: \"edef8ba979d64acea3c827dcd51d21ed\"\n};\nfunction keySystemIdToKeySystemDomain(systemId) {\n if (systemId === KeySystemIds.WIDEVINE) {\n return KeySystems.WIDEVINE;\n } else if (systemId === KeySystemIds.PLAYREADY) {\n return KeySystems.PLAYREADY;\n } else if (systemId === KeySystemIds.CENC || systemId === KeySystemIds.CLEARKEY) {\n return KeySystems.CLEARKEY;\n }\n}\nfunction keySystemDomainToKeySystemFormat(keySystem) {\n switch (keySystem) {\n case KeySystems.FAIRPLAY:\n return KeySystemFormats.FAIRPLAY;\n case KeySystems.PLAYREADY:\n return KeySystemFormats.PLAYREADY;\n case KeySystems.WIDEVINE:\n return KeySystemFormats.WIDEVINE;\n case KeySystems.CLEARKEY:\n return KeySystemFormats.CLEARKEY;\n }\n}\nfunction getKeySystemsForConfig(config) {\n const {\n drmSystems,\n widevineLicenseUrl\n } = config;\n const keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter(keySystem => !!drmSystems[keySystem]) : [];\n if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {\n keySystemsToAttempt.push(KeySystems.WIDEVINE);\n }\n return keySystemsToAttempt;\n}\nconst requestMediaKeySystemAccess = function (_optionalSelf$navigat) {\n if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) {\n return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);\n } else {\n return null;\n }\n}();\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration\n */\nfunction getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {\n let initDataTypes;\n switch (keySystem) {\n case KeySystems.FAIRPLAY:\n initDataTypes = ['cenc', 'sinf'];\n break;\n case KeySystems.WIDEVINE:\n case KeySystems.PLAYREADY:\n initDataTypes = ['cenc'];\n break;\n case KeySystems.CLEARKEY:\n initDataTypes = ['cenc', 'keyids'];\n break;\n default:\n throw new Error(`Unknown key-system: ${keySystem}`);\n }\n return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions);\n}\nfunction createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) {\n const baseConfig = {\n initDataTypes: initDataTypes,\n persistentState: drmSystemOptions.persistentState || 'optional',\n distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || 'optional',\n sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || 'temporary'],\n audioCapabilities: audioCodecs.map(codec => ({\n contentType: `audio/mp4; codecs=${codec}`,\n robustness: drmSystemOptions.audioRobustness || '',\n encryptionScheme: drmSystemOptions.audioEncryptionScheme || null\n })),\n videoCapabilities: videoCodecs.map(codec => ({\n contentType: `video/mp4; codecs=${codec}`,\n robustness: drmSystemOptions.videoRobustness || '',\n encryptionScheme: drmSystemOptions.videoEncryptionScheme || null\n }))\n };\n return [baseConfig];\n}\nfunction isPersistentSessionType(drmSystemOptions) {\n var _drmSystemOptions$ses;\n return drmSystemOptions.sessionType === 'persistent-license' || !!((_drmSystemOptions$ses = drmSystemOptions.sessionTypes) != null && _drmSystemOptions$ses.some(type => type === 'persistent-license'));\n}\nfunction parsePlayReadyWRM(keyBytes) {\n const keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);\n const keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));\n\n // Parse Playready WRMHeader XML\n const xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf('<'), keyByteStr.length);\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(xmlKeyBytes, 'text/xml');\n const keyData = xmlDoc.getElementsByTagName('KID')[0];\n if (keyData) {\n const keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute('VALUE');\n if (keyId) {\n const keyIdArray = base64Decode(keyId).subarray(0, 16);\n // KID value in PRO is a base64-encoded little endian GUID interpretation of UUID\n // KID value in ‘tenc’ is a big endian UUID GUID interpretation of UUID\n changeEndianness(keyIdArray);\n return keyIdArray;\n }\n }\n return null;\n}\n\nlet keyUriToKeyIdMap = {};\nclass LevelKey {\n static clearKeyUriToKeyIdMap() {\n keyUriToKeyIdMap = {};\n }\n constructor(method, uri, format, formatversions = [1], iv = null) {\n this.uri = void 0;\n this.method = void 0;\n this.keyFormat = void 0;\n this.keyFormatVersions = void 0;\n this.encrypted = void 0;\n this.isCommonEncryption = void 0;\n this.iv = null;\n this.key = null;\n this.keyId = null;\n this.pssh = null;\n this.method = method;\n this.uri = uri;\n this.keyFormat = format;\n this.keyFormatVersions = formatversions;\n this.iv = iv;\n this.encrypted = method ? method !== 'NONE' : false;\n this.isCommonEncryption = this.encrypted && !isFullSegmentEncryption(method);\n }\n isSupported() {\n // If it's Segment encryption or No encryption, just select that key system\n if (this.method) {\n if (isFullSegmentEncryption(this.method) || this.method === 'NONE') {\n return true;\n }\n if (this.keyFormat === 'identity') {\n // Maintain support for clear SAMPLE-AES with MPEG-3 TS\n return this.method === 'SAMPLE-AES';\n } else {\n switch (this.keyFormat) {\n case KeySystemFormats.FAIRPLAY:\n case KeySystemFormats.WIDEVINE:\n case KeySystemFormats.PLAYREADY:\n case KeySystemFormats.CLEARKEY:\n return ['ISO-23001-7', 'SAMPLE-AES', 'SAMPLE-AES-CENC', 'SAMPLE-AES-CTR'].indexOf(this.method) !== -1;\n }\n }\n }\n return false;\n }\n getDecryptData(sn) {\n if (!this.encrypted || !this.uri) {\n return null;\n }\n if (isFullSegmentEncryption(this.method) && this.uri && !this.iv) {\n if (typeof sn !== 'number') {\n // We are fetching decryption data for a initialization segment\n // If the segment was encrypted with AES-128/256\n // It must have an IV defined. We cannot substitute the Segment Number in.\n logger.warn(`missing IV for initialization segment with method=\"${this.method}\" - compliance issue`);\n\n // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.\n sn = 0;\n }\n const iv = createInitializationVector(sn);\n const decryptdata = new LevelKey(this.method, this.uri, 'identity', this.keyFormatVersions, iv);\n return decryptdata;\n }\n\n // Initialize keyId if possible\n const keyBytes = convertDataUriToArrayBytes(this.uri);\n if (keyBytes) {\n switch (this.keyFormat) {\n case KeySystemFormats.WIDEVINE:\n // Setting `pssh` on this LevelKey/DecryptData allows HLS.js to generate a session using\n // the playlist-key before the \"encrypted\" event. (Comment out to only use \"encrypted\" path.)\n this.pssh = keyBytes;\n // In case of widevine keyID is embedded in PSSH box. Read Key ID.\n if (keyBytes.length >= 22) {\n this.keyId = keyBytes.subarray(keyBytes.length - 22, keyBytes.length - 6);\n }\n break;\n case KeySystemFormats.PLAYREADY:\n {\n const PlayReadyKeySystemUUID = new Uint8Array([0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6, 0x5b, 0xe0, 0x88, 0x5f, 0x95]);\n\n // Setting `pssh` on this LevelKey/DecryptData allows HLS.js to generate a session using\n // the playlist-key before the \"encrypted\" event. (Comment out to only use \"encrypted\" path.)\n this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);\n this.keyId = parsePlayReadyWRM(keyBytes);\n break;\n }\n default:\n {\n let keydata = keyBytes.subarray(0, 16);\n if (keydata.length !== 16) {\n const padded = new Uint8Array(16);\n padded.set(keydata, 16 - keydata.length);\n keydata = padded;\n }\n this.keyId = keydata;\n break;\n }\n }\n }\n\n // Default behavior: assign a new keyId for each uri\n if (!this.keyId || this.keyId.byteLength !== 16) {\n let keyId = keyUriToKeyIdMap[this.uri];\n if (!keyId) {\n const val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;\n keyId = new Uint8Array(16);\n const dv = new DataView(keyId.buffer, 12, 4); // Just set the last 4 bytes\n dv.setUint32(0, val);\n keyUriToKeyIdMap[this.uri] = keyId;\n }\n this.keyId = keyId;\n }\n return this;\n }\n}\nfunction createInitializationVector(segmentNumber) {\n const uint8View = new Uint8Array(16);\n for (let i = 12; i < 16; i++) {\n uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;\n }\n return uint8View;\n}\n\nconst MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\\r\\n]*)(?:[\\r\\n](?:#[^\\r\\n]*)?)*([^\\r\\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\\r\\n]*)[\\r\\n]+/g;\nconst MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\nconst IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)\n\nconst LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source,\n// duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title\n/(?!#) *(\\S[^\\r\\n]*)/.source,\n// segment URI, group 3 => the URI (note newline is not eaten)\n/#.*/.source // All other non-segment oriented tags will match with all groups empty\n].join('|'), 'g');\nconst LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source, /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\\d+)/.source, /#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\\r?\\n?/.source].join('|'));\nclass M3U8Parser {\n static findGroup(groups, mediaGroupId) {\n for (let i = 0; i < groups.length; i++) {\n const group = groups[i];\n if (group.id === mediaGroupId) {\n return group;\n }\n }\n }\n static resolve(url, baseUrl) {\n return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {\n alwaysNormalize: true\n });\n }\n static isMediaPlaylist(str) {\n return IS_MEDIA_PLAYLIST.test(str);\n }\n static parseMasterPlaylist(string, baseurl) {\n const hasVariableRefs = hasVariableReferences(string) ;\n const parsed = {\n contentSteering: null,\n levels: [],\n playlistParsingError: null,\n sessionData: null,\n sessionKeys: null,\n startTimeOffset: null,\n variableList: null,\n hasVariableRefs\n };\n const levelsWithKnownCodecs = [];\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n let result;\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {\n if (result[1]) {\n var _level$unknownCodecs;\n // '#EXT-X-STREAM-INF' is found, parse level tag in group 1\n const attrs = new AttrList(result[1], parsed);\n const uri = substituteVariables(parsed, result[2]) ;\n const level = {\n attrs,\n bitrate: attrs.decimalInteger('BANDWIDTH') || attrs.decimalInteger('AVERAGE-BANDWIDTH'),\n name: attrs.NAME,\n url: M3U8Parser.resolve(uri, baseurl)\n };\n const resolution = attrs.decimalResolution('RESOLUTION');\n if (resolution) {\n level.width = resolution.width;\n level.height = resolution.height;\n }\n setCodecs(attrs.CODECS, level);\n const supplementalCodecs = attrs['SUPPLEMENTAL-CODECS'];\n if (supplementalCodecs) {\n level.supplemental = {};\n setCodecs(supplementalCodecs, level.supplemental);\n }\n if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {\n levelsWithKnownCodecs.push(level);\n }\n parsed.levels.push(level);\n } else if (result[3]) {\n const tag = result[3];\n const attributes = result[4];\n switch (tag) {\n case 'SESSION-DATA':\n {\n // #EXT-X-SESSION-DATA\n const sessionAttrs = new AttrList(attributes, parsed);\n const dataId = sessionAttrs['DATA-ID'];\n if (dataId) {\n if (parsed.sessionData === null) {\n parsed.sessionData = {};\n }\n parsed.sessionData[dataId] = sessionAttrs;\n }\n break;\n }\n case 'SESSION-KEY':\n {\n // #EXT-X-SESSION-KEY\n const sessionKey = parseKey(attributes, baseurl, parsed);\n if (sessionKey.encrypted && sessionKey.isSupported()) {\n if (parsed.sessionKeys === null) {\n parsed.sessionKeys = [];\n }\n parsed.sessionKeys.push(sessionKey);\n } else {\n logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: \"${attributes}\"`);\n }\n break;\n }\n case 'DEFINE':\n {\n // #EXT-X-DEFINE\n {\n const variableAttributes = new AttrList(attributes, parsed);\n addVariableDefinition(parsed, variableAttributes, baseurl);\n }\n break;\n }\n case 'CONTENT-STEERING':\n {\n // #EXT-X-CONTENT-STEERING\n const contentSteeringAttributes = new AttrList(attributes, parsed);\n parsed.contentSteering = {\n uri: M3U8Parser.resolve(contentSteeringAttributes['SERVER-URI'], baseurl),\n pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.'\n };\n break;\n }\n case 'START':\n {\n // #EXT-X-START\n parsed.startTimeOffset = parseStartTimeOffset(attributes);\n break;\n }\n }\n }\n }\n // Filter out levels with unknown codecs if it does not remove all levels\n const stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;\n parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;\n if (parsed.levels.length === 0) {\n parsed.playlistParsingError = new Error('no levels found in manifest');\n }\n return parsed;\n }\n static parseMasterPlaylistMedia(string, baseurl, parsed) {\n let result;\n const results = {};\n const levels = parsed.levels;\n const groupsByType = {\n AUDIO: levels.map(level => ({\n id: level.attrs.AUDIO,\n audioCodec: level.audioCodec\n })),\n SUBTITLES: levels.map(level => ({\n id: level.attrs.SUBTITLES,\n textCodec: level.textCodec\n })),\n 'CLOSED-CAPTIONS': []\n };\n let id = 0;\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n const attrs = new AttrList(result[1], parsed);\n const type = attrs.TYPE;\n if (type) {\n const groups = groupsByType[type];\n const medias = results[type] || [];\n results[type] = medias;\n const lang = attrs.LANGUAGE;\n const assocLang = attrs['ASSOC-LANGUAGE'];\n const channels = attrs.CHANNELS;\n const characteristics = attrs.CHARACTERISTICS;\n const instreamId = attrs['INSTREAM-ID'];\n const media = {\n attrs,\n bitrate: 0,\n id: id++,\n groupId: attrs['GROUP-ID'] || '',\n name: attrs.NAME || lang || '',\n type,\n default: attrs.bool('DEFAULT'),\n autoselect: attrs.bool('AUTOSELECT'),\n forced: attrs.bool('FORCED'),\n lang,\n url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''\n };\n if (assocLang) {\n media.assocLang = assocLang;\n }\n if (channels) {\n media.channels = channels;\n }\n if (characteristics) {\n media.characteristics = characteristics;\n }\n if (instreamId) {\n media.instreamId = instreamId;\n }\n if (groups != null && groups.length) {\n // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track\n // If we don't find the track signalled, lets use the first audio groups codec we have\n // Acting as a best guess\n const groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];\n assignCodec(media, groupCodec, 'audioCodec');\n assignCodec(media, groupCodec, 'textCodec');\n }\n medias.push(media);\n }\n }\n return results;\n }\n static parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {\n var _LEVEL_PLAYLIST_REGEX;\n const base = {\n url: baseurl\n };\n const level = new LevelDetails(baseurl);\n const fragments = level.fragments;\n const programDateTimes = [];\n // The most recent init segment seen (applies to all subsequent segments)\n let currentInitSegment = null;\n let currentSN = 0;\n let currentPart = 0;\n let totalduration = 0;\n let discontinuityCounter = 0;\n let currentBitrate = 0;\n let prevFrag = null;\n let frag = new Fragment(type, base);\n let result;\n let i;\n let levelkeys;\n let firstPdtIndex = -1;\n let createNextFrag = false;\n let nextByteRange = null;\n let serverControlAttrs;\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n level.m3u8 = string;\n level.hasVariableRefs = hasVariableReferences(string) ;\n if (((_LEVEL_PLAYLIST_REGEX = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) == null ? void 0 : _LEVEL_PLAYLIST_REGEX[0]) !== '#EXTM3U') {\n level.playlistParsingError = new Error('Missing format identifier #EXTM3U');\n return level;\n }\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n if (createNextFrag) {\n createNextFrag = false;\n frag = new Fragment(type, base);\n // setup the next fragment for part loading\n frag.playlistOffset = totalduration;\n frag.start = totalduration;\n frag.sn = currentSN;\n frag.cc = discontinuityCounter;\n if (currentBitrate) {\n frag.bitrate = currentBitrate;\n }\n frag.level = id;\n if (currentInitSegment) {\n frag.initSegment = currentInitSegment;\n if (currentInitSegment.rawProgramDateTime) {\n frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;\n currentInitSegment.rawProgramDateTime = null;\n }\n if (nextByteRange) {\n frag.setByteRange(nextByteRange);\n nextByteRange = null;\n }\n }\n }\n const duration = result[1];\n if (duration) {\n // INF\n frag.duration = parseFloat(duration);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const title = (' ' + result[2]).slice(1);\n frag.title = title || null;\n frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);\n } else if (result[3]) {\n // url\n if (isFiniteNumber(frag.duration)) {\n frag.playlistOffset = totalduration;\n frag.start = totalduration;\n if (levelkeys) {\n setFragLevelKeys(frag, levelkeys, level);\n }\n frag.sn = currentSN;\n frag.level = id;\n frag.cc = discontinuityCounter;\n fragments.push(frag);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const uri = (' ' + result[3]).slice(1);\n frag.relurl = substituteVariables(level, uri) ;\n assignProgramDateTime(frag, prevFrag, programDateTimes);\n prevFrag = frag;\n totalduration += frag.duration;\n currentSN++;\n currentPart = 0;\n createNextFrag = true;\n }\n } else {\n result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);\n if (!result) {\n logger.warn('No matches on slow regex match for level playlist!');\n continue;\n }\n for (i = 1; i < result.length; i++) {\n if (result[i] !== undefined) {\n break;\n }\n }\n\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const tag = (' ' + result[i]).slice(1);\n const value1 = (' ' + result[i + 1]).slice(1);\n const value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : null;\n switch (tag) {\n case 'BYTERANGE':\n if (prevFrag) {\n frag.setByteRange(value1, prevFrag);\n } else {\n frag.setByteRange(value1);\n }\n break;\n case 'PROGRAM-DATE-TIME':\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.rawProgramDateTime = value1;\n frag.tagList.push(['PROGRAM-DATE-TIME', value1]);\n if (firstPdtIndex === -1) {\n firstPdtIndex = fragments.length;\n }\n break;\n case 'PLAYLIST-TYPE':\n if (level.type) {\n assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);\n }\n level.type = value1.toUpperCase();\n break;\n case 'MEDIA-SEQUENCE':\n if (level.startSN !== 0) {\n assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);\n } else if (fragments.length > 0) {\n assignMustAppearBeforeSegmentsError(level, tag, result);\n }\n currentSN = level.startSN = parseInt(value1);\n break;\n case 'SKIP':\n {\n if (level.skippedSegments) {\n assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);\n }\n const skipAttrs = new AttrList(value1, level);\n const skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');\n if (isFiniteNumber(skippedSegments)) {\n level.skippedSegments += skippedSegments;\n // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`\n for (let _i = skippedSegments; _i--;) {\n fragments.push(null);\n }\n currentSN += skippedSegments;\n }\n const recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');\n if (recentlyRemovedDateranges) {\n level.recentlyRemovedDateranges = (level.recentlyRemovedDateranges || []).concat(recentlyRemovedDateranges.split('\\t'));\n }\n break;\n }\n case 'TARGETDURATION':\n if (level.targetduration !== 0) {\n assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);\n }\n level.targetduration = Math.max(parseInt(value1), 1);\n break;\n case 'VERSION':\n if (level.version !== null) {\n assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);\n }\n level.version = parseInt(value1);\n break;\n case 'INDEPENDENT-SEGMENTS':\n break;\n case 'ENDLIST':\n if (!level.live) {\n assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);\n }\n level.live = false;\n break;\n case '#':\n if (value1 || value2) {\n frag.tagList.push(value2 ? [value1, value2] : [value1]);\n }\n break;\n case 'DISCONTINUITY':\n discontinuityCounter++;\n frag.tagList.push(['DIS']);\n break;\n case 'GAP':\n frag.gap = true;\n frag.tagList.push([tag]);\n break;\n case 'BITRATE':\n frag.tagList.push([tag, value1]);\n currentBitrate = parseInt(value1) * 1000;\n if (isFiniteNumber(currentBitrate)) {\n frag.bitrate = currentBitrate;\n } else {\n currentBitrate = 0;\n }\n break;\n case 'DATERANGE':\n {\n const dateRangeAttr = new AttrList(value1, level);\n const dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID], level.dateRangeTagCount);\n level.dateRangeTagCount++;\n if (dateRange.isValid || level.skippedSegments) {\n level.dateRanges[dateRange.id] = dateRange;\n } else {\n logger.warn(`Ignoring invalid DATERANGE tag: \"${value1}\"`);\n }\n // Add to fragment tag list for backwards compatibility (< v1.2.0)\n frag.tagList.push(['EXT-X-DATERANGE', value1]);\n break;\n }\n case 'DEFINE':\n {\n {\n const variableAttributes = new AttrList(value1, level);\n if ('IMPORT' in variableAttributes) {\n importVariableDefinition(level, variableAttributes, multivariantVariableList);\n } else {\n addVariableDefinition(level, variableAttributes, baseurl);\n }\n }\n break;\n }\n case 'DISCONTINUITY-SEQUENCE':\n if (level.startCC !== 0) {\n assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);\n } else if (fragments.length > 0) {\n assignMustAppearBeforeSegmentsError(level, tag, result);\n }\n level.startCC = discontinuityCounter = parseInt(value1);\n break;\n case 'KEY':\n {\n const levelKey = parseKey(value1, baseurl, level);\n if (levelKey.isSupported()) {\n if (levelKey.method === 'NONE') {\n levelkeys = undefined;\n break;\n }\n if (!levelkeys) {\n levelkeys = {};\n }\n if (levelkeys[levelKey.keyFormat]) {\n levelkeys = _extends({}, levelkeys);\n }\n levelkeys[levelKey.keyFormat] = levelKey;\n } else {\n logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: \"${value1}\"`);\n }\n break;\n }\n case 'START':\n level.startTimeOffset = parseStartTimeOffset(value1);\n break;\n case 'MAP':\n {\n const mapAttrs = new AttrList(value1, level);\n if (frag.duration) {\n // Initial segment tag is after segment duration tag.\n // #EXTINF: 6.0\n // #EXT-X-MAP:URI=\"init.mp4\n const init = new Fragment(type, base);\n setInitSegment(init, mapAttrs, id, levelkeys);\n currentInitSegment = init;\n frag.initSegment = currentInitSegment;\n if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {\n frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;\n }\n } else {\n // Initial segment tag is before segment duration tag\n // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE\n const end = frag.byteRangeEndOffset;\n if (end) {\n const start = frag.byteRangeStartOffset;\n nextByteRange = `${end - start}@${start}`;\n } else {\n nextByteRange = null;\n }\n setInitSegment(frag, mapAttrs, id, levelkeys);\n currentInitSegment = frag;\n createNextFrag = true;\n }\n currentInitSegment.cc = discontinuityCounter;\n break;\n }\n case 'SERVER-CONTROL':\n {\n if (serverControlAttrs) {\n assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);\n }\n serverControlAttrs = new AttrList(value1);\n level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');\n level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);\n level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');\n level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);\n level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);\n break;\n }\n case 'PART-INF':\n {\n if (level.partTarget) {\n assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);\n }\n const partInfAttrs = new AttrList(value1);\n level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');\n break;\n }\n case 'PART':\n {\n let partList = level.partList;\n if (!partList) {\n partList = level.partList = [];\n }\n const previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;\n const index = currentPart++;\n const partAttrs = new AttrList(value1, level);\n const part = new Part(partAttrs, frag, base, index, previousFragmentPart);\n partList.push(part);\n frag.duration += part.duration;\n break;\n }\n case 'PRELOAD-HINT':\n {\n const preloadHintAttrs = new AttrList(value1, level);\n level.preloadHint = preloadHintAttrs;\n break;\n }\n case 'RENDITION-REPORT':\n {\n const renditionReportAttrs = new AttrList(value1, level);\n level.renditionReports = level.renditionReports || [];\n level.renditionReports.push(renditionReportAttrs);\n break;\n }\n default:\n logger.warn(`line parsed but not handled: ${result}`);\n break;\n }\n }\n }\n if (prevFrag && !prevFrag.relurl) {\n fragments.pop();\n totalduration -= prevFrag.duration;\n if (level.partList) {\n level.fragmentHint = prevFrag;\n }\n } else if (level.partList) {\n assignProgramDateTime(frag, prevFrag, programDateTimes);\n frag.cc = discontinuityCounter;\n level.fragmentHint = frag;\n if (levelkeys) {\n setFragLevelKeys(frag, levelkeys, level);\n }\n }\n if (!level.targetduration) {\n level.playlistParsingError = new Error(`#EXT-X-TARGETDURATION is required`);\n }\n const fragmentLength = fragments.length;\n const firstFragment = fragments[0];\n const lastFragment = fragments[fragmentLength - 1];\n totalduration += level.skippedSegments * level.targetduration;\n if (totalduration > 0 && fragmentLength && lastFragment) {\n level.averagetargetduration = totalduration / fragmentLength;\n const lastSn = lastFragment.sn;\n level.endSN = lastSn !== 'initSegment' ? lastSn : 0;\n if (!level.live) {\n lastFragment.endList = true;\n }\n if (firstFragment && level.startCC === undefined) {\n level.startCC = firstFragment.cc;\n }\n /**\n * Backfill any missing PDT values\n * \"If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after\n * one or more Media Segment URIs, the client SHOULD extrapolate\n * backward from that tag (using EXTINF durations and/or media\n * timestamps) to associate dates with those segments.\"\n * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs\n * computed.\n */\n if (firstPdtIndex > 0) {\n backfillProgramDateTimes(fragments, firstPdtIndex);\n if (firstFragment) {\n programDateTimes.unshift(firstFragment);\n }\n }\n } else {\n level.endSN = 0;\n level.startCC = 0;\n }\n if (level.fragmentHint) {\n totalduration += level.fragmentHint.duration;\n }\n level.totalduration = totalduration;\n if (programDateTimes.length && level.dateRangeTagCount && firstFragment) {\n mapDateRanges(programDateTimes, level);\n }\n level.endCC = discontinuityCounter;\n return level;\n }\n}\nfunction mapDateRanges(programDateTimes, details) {\n // Make sure DateRanges are mapped to a ProgramDateTime tag that applies a date to a segment that overlaps with its start date\n const programDateTimeCount = programDateTimes.length;\n const lastProgramDateTime = programDateTimes[programDateTimeCount - 1];\n const playlistEnd = details.live ? Infinity : details.totalduration;\n const dateRangeIds = Object.keys(details.dateRanges);\n for (let i = dateRangeIds.length; i--;) {\n const dateRange = details.dateRanges[dateRangeIds[i]];\n const startDateTime = dateRange.startDate.getTime();\n dateRange.tagAnchor = lastProgramDateTime.ref;\n for (let j = programDateTimeCount; j--;) {\n const fragIndex = findFragmentWithStartDate(details, startDateTime, programDateTimes, j, playlistEnd);\n if (fragIndex !== -1) {\n dateRange.tagAnchor = details.fragments[fragIndex].ref;\n break;\n }\n }\n }\n}\nfunction findFragmentWithStartDate(details, startDateTime, programDateTimes, index, endTime) {\n const pdtFragment = programDateTimes[index];\n if (pdtFragment) {\n // find matching range between PDT tags\n const pdtStart = pdtFragment.programDateTime;\n if (startDateTime >= pdtStart || index === 0) {\n var _programDateTimes;\n const durationBetweenPdt = (((_programDateTimes = programDateTimes[index + 1]) == null ? void 0 : _programDateTimes.start) || endTime) - pdtFragment.start;\n if (startDateTime <= pdtStart + durationBetweenPdt * 1000) {\n // map to fragment with date-time range\n const startIndex = programDateTimes[index].sn - details.startSN;\n const fragments = details.fragments;\n if (fragments.length > programDateTimes.length) {\n const endSegment = programDateTimes[index + 1] || fragments[fragments.length - 1];\n const endIndex = endSegment.sn - details.startSN;\n for (let i = endIndex; i > startIndex; i--) {\n const fragStartDateTime = fragments[i].programDateTime;\n if (startDateTime >= fragStartDateTime && startDateTime < fragStartDateTime + fragments[i].duration * 1000) {\n return i;\n }\n }\n }\n return startIndex;\n }\n }\n }\n return -1;\n}\nfunction parseKey(keyTagAttributes, baseurl, parsed) {\n var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;\n // https://tools.ietf.org/html/rfc8216#section-4.3.2.4\n const keyAttrs = new AttrList(keyTagAttributes, parsed);\n const decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : '';\n const decrypturi = keyAttrs.URI;\n const decryptiv = keyAttrs.hexadecimalInteger('IV');\n const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;\n // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of \"identity\".\n const decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : 'identity';\n if (decrypturi && keyAttrs.IV && !decryptiv) {\n logger.error(`Invalid IV: ${keyAttrs.IV}`);\n }\n // If decrypturi is a URI with a scheme, then baseurl will be ignored\n // No uri is allowed when METHOD is NONE\n const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';\n const keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : '1').split('/').map(Number).filter(Number.isFinite);\n return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv);\n}\nfunction parseStartTimeOffset(startAttributes) {\n const startAttrs = new AttrList(startAttributes);\n const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n if (isFiniteNumber(startTimeOffset)) {\n return startTimeOffset;\n }\n return null;\n}\nfunction setCodecs(codecsAttributeValue, level) {\n let codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter(c => c);\n ['video', 'audio', 'text'].forEach(type => {\n const filtered = codecs.filter(codec => isCodecType(codec, type));\n if (filtered.length) {\n // Comma separated list of all codecs for type\n level[`${type}Codec`] = filtered.map(c => c.split('/')[0]).join(',');\n // Remove known codecs so that only unknownCodecs are left after iterating through each type\n codecs = codecs.filter(codec => filtered.indexOf(codec) === -1);\n }\n });\n level.unknownCodecs = codecs;\n}\nfunction assignCodec(media, groupItem, codecProperty) {\n const codecValue = groupItem[codecProperty];\n if (codecValue) {\n media[codecProperty] = codecValue;\n }\n}\nfunction backfillProgramDateTimes(fragments, firstPdtIndex) {\n let fragPrev = fragments[firstPdtIndex];\n for (let i = firstPdtIndex; i--;) {\n const frag = fragments[i];\n // Exit on delta-playlist skipped segments\n if (!frag) {\n return;\n }\n frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;\n fragPrev = frag;\n }\n}\nfunction assignProgramDateTime(frag, prevFrag, programDateTimes) {\n if (frag.rawProgramDateTime) {\n programDateTimes.push(frag);\n } else if (prevFrag != null && prevFrag.programDateTime) {\n frag.programDateTime = prevFrag.endProgramDateTime;\n }\n}\nfunction setInitSegment(frag, mapAttrs, id, levelkeys) {\n frag.relurl = mapAttrs.URI;\n if (mapAttrs.BYTERANGE) {\n frag.setByteRange(mapAttrs.BYTERANGE);\n }\n frag.level = id;\n frag.sn = 'initSegment';\n if (levelkeys) {\n frag.levelkeys = levelkeys;\n }\n frag.initSegment = null;\n}\nfunction setFragLevelKeys(frag, levelkeys, level) {\n frag.levelkeys = levelkeys;\n const {\n encryptedFragments\n } = level;\n if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some(format => levelkeys[format].isCommonEncryption)) {\n encryptedFragments.push(frag);\n }\n}\nfunction assignMultipleMediaPlaylistTagOccuranceError(level, tag, result) {\n level.playlistParsingError = new Error(`#EXT-X-${tag} must not appear more than once (${result[0]})`);\n}\nfunction assignMustAppearBeforeSegmentsError(level, tag, result) {\n level.playlistParsingError = new Error(`#EXT-X-${tag} must appear before the first Media Segment (${result[0]})`);\n}\n\nfunction updateFromToPTS(fragFrom, fragTo) {\n const fragToPTS = fragTo.startPTS;\n // if we know startPTS[toIdx]\n if (isFiniteNumber(fragToPTS)) {\n // update fragment duration.\n // it helps to fix drifts between playlist reported duration and fragment real duration\n let duration = 0;\n let frag;\n if (fragTo.sn > fragFrom.sn) {\n duration = fragToPTS - fragFrom.start;\n frag = fragFrom;\n } else {\n duration = fragFrom.start - fragToPTS;\n frag = fragTo;\n }\n if (frag.duration !== duration) {\n frag.setDuration(duration);\n }\n // we dont know startPTS[toIdx]\n } else if (fragTo.sn > fragFrom.sn) {\n const contiguous = fragFrom.cc === fragTo.cc;\n // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS\n if (contiguous && fragFrom.minEndPTS) {\n fragTo.setStart(fragFrom.start + (fragFrom.minEndPTS - fragFrom.start));\n } else {\n fragTo.setStart(fragFrom.start + fragFrom.duration);\n }\n } else {\n fragTo.setStart(Math.max(fragFrom.start - fragTo.duration, 0));\n }\n}\nfunction updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {\n const parsedMediaDuration = endPTS - startPTS;\n if (parsedMediaDuration <= 0) {\n logger.warn('Fragment should have a positive duration', frag);\n endPTS = startPTS + frag.duration;\n endDTS = startDTS + frag.duration;\n }\n let maxStartPTS = startPTS;\n let minEndPTS = endPTS;\n const fragStartPts = frag.startPTS;\n const fragEndPts = frag.endPTS;\n if (isFiniteNumber(fragStartPts)) {\n // delta PTS between audio and video\n const deltaPTS = Math.abs(fragStartPts - startPTS);\n if (!isFiniteNumber(frag.deltaPTS)) {\n frag.deltaPTS = deltaPTS;\n } else {\n frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);\n }\n maxStartPTS = Math.max(startPTS, fragStartPts);\n startPTS = Math.min(startPTS, fragStartPts);\n startDTS = Math.min(startDTS, frag.startDTS);\n minEndPTS = Math.min(endPTS, fragEndPts);\n endPTS = Math.max(endPTS, fragEndPts);\n endDTS = Math.max(endDTS, frag.endDTS);\n }\n const drift = startPTS - frag.start;\n if (frag.start !== 0) {\n frag.setStart(startPTS);\n }\n frag.setDuration(endPTS - frag.start);\n frag.startPTS = startPTS;\n frag.maxStartPTS = maxStartPTS;\n frag.startDTS = startDTS;\n frag.endPTS = endPTS;\n frag.minEndPTS = minEndPTS;\n frag.endDTS = endDTS;\n const sn = frag.sn;\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n let i;\n const fragIdx = sn - details.startSN;\n const fragments = details.fragments;\n // update frag reference in fragments array\n // rationale is that fragments array might not contain this frag object.\n // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()\n // if we don't update frag, we won't be able to propagate PTS info on the playlist\n // resulting in invalid sliding computation\n fragments[fragIdx] = frag;\n // adjust fragment PTS/duration from seqnum-1 to frag 0\n for (i = fragIdx; i > 0; i--) {\n updateFromToPTS(fragments[i], fragments[i - 1]);\n }\n\n // adjust fragment PTS/duration from seqnum to last frag\n for (i = fragIdx; i < fragments.length - 1; i++) {\n updateFromToPTS(fragments[i], fragments[i + 1]);\n }\n if (details.fragmentHint) {\n updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);\n }\n details.PTSKnown = details.alignedSliding = true;\n return drift;\n}\nfunction mergeDetails(oldDetails, newDetails) {\n if (oldDetails === newDetails) {\n return;\n }\n // Track the last initSegment processed. Initialize it to the last one on the timeline.\n let currentInitSegment = null;\n const oldFragments = oldDetails.fragments;\n for (let i = oldFragments.length - 1; i >= 0; i--) {\n const oldInit = oldFragments[i].initSegment;\n if (oldInit) {\n currentInitSegment = oldInit;\n break;\n }\n }\n if (oldDetails.fragmentHint) {\n // prevent PTS and duration from being adjusted on the next hint\n delete oldDetails.fragmentHint.endPTS;\n }\n // check if old/new playlists have fragments in common\n // loop through overlapping SN and update startPTS, cc, and duration if any found\n let PTSFrag;\n mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag, newFragIndex, newFragments) => {\n if (!newDetails.startCC && newFrag.cc !== oldFrag.cc) {\n var _getFragmentWithSN$cc, _getFragmentWithSN;\n const ccOffset = oldFrag.cc - newFrag.cc;\n for (let i = newFragIndex; i < newFragments.length; i++) {\n newFragments[i].cc += ccOffset;\n }\n newDetails.startCC = (_getFragmentWithSN$cc = (_getFragmentWithSN = getFragmentWithSN(oldDetails, newDetails.startSN - 1)) == null ? void 0 : _getFragmentWithSN.cc) != null ? _getFragmentWithSN$cc : newFragments[0].cc;\n newDetails.endCC = newFragments[newFragments.length - 1].cc;\n }\n if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {\n newFrag.setStart(newFrag.startPTS = oldFrag.startPTS);\n newFrag.startDTS = oldFrag.startDTS;\n newFrag.maxStartPTS = oldFrag.maxStartPTS;\n newFrag.endPTS = oldFrag.endPTS;\n newFrag.endDTS = oldFrag.endDTS;\n newFrag.minEndPTS = oldFrag.minEndPTS;\n newFrag.setDuration(oldFrag.endPTS - oldFrag.startPTS);\n if (newFrag.duration) {\n PTSFrag = newFrag;\n }\n\n // PTS is known when any segment has startPTS and endPTS\n newDetails.PTSKnown = newDetails.alignedSliding = true;\n }\n if (oldFrag.hasStreams) {\n newFrag.elementaryStreams = oldFrag.elementaryStreams;\n }\n newFrag.loader = oldFrag.loader;\n if (oldFrag.hasStats) {\n newFrag.stats = oldFrag.stats;\n }\n if (oldFrag.initSegment) {\n newFrag.initSegment = oldFrag.initSegment;\n currentInitSegment = oldFrag.initSegment;\n }\n });\n const newFragments = newDetails.fragments;\n const fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments;\n if (currentInitSegment) {\n fragmentsToCheck.forEach(frag => {\n var _currentInitSegment;\n if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {\n frag.initSegment = currentInitSegment;\n }\n });\n }\n if (newDetails.skippedSegments) {\n newDetails.deltaUpdateFailed = newFragments.some(frag => !frag);\n if (newDetails.deltaUpdateFailed) {\n logger.warn('[level-helper] Previous playlist missing segments skipped in delta playlist');\n for (let i = newDetails.skippedSegments; i--;) {\n newFragments.shift();\n }\n newDetails.startSN = newFragments[0].sn;\n } else {\n newDetails.endCC = newFragments[newFragments.length - 1].cc;\n if (newDetails.canSkipDateRanges) {\n newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails);\n }\n const programDateTimes = oldDetails.fragments.filter(frag => frag.rawProgramDateTime);\n if (oldDetails.hasProgramDateTime && !newDetails.hasProgramDateTime) {\n for (let i = 1; i < fragmentsToCheck.length; i++) {\n if (fragmentsToCheck[i].programDateTime === null) {\n assignProgramDateTime(fragmentsToCheck[i], fragmentsToCheck[i - 1], programDateTimes);\n }\n }\n }\n mapDateRanges(programDateTimes, newDetails);\n }\n }\n\n // Merge parts\n mapPartIntersection(oldDetails.partList, newDetails.partList, (oldPart, newPart) => {\n newPart.elementaryStreams = oldPart.elementaryStreams;\n newPart.stats = oldPart.stats;\n });\n\n // if at least one fragment contains PTS info, recompute PTS information for all fragments\n if (PTSFrag) {\n updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);\n } else {\n // ensure that delta is within oldFragments range\n // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n // in that case we also need to adjust start offset of all fragments\n adjustSliding(oldDetails, newDetails);\n }\n if (newFragments.length) {\n newDetails.totalduration = newDetails.edge - newFragments[0].start;\n }\n newDetails.driftStartTime = oldDetails.driftStartTime;\n newDetails.driftStart = oldDetails.driftStart;\n const advancedDateTime = newDetails.advancedDateTime;\n if (newDetails.advanced && advancedDateTime) {\n const edge = newDetails.edge;\n if (!newDetails.driftStart) {\n newDetails.driftStartTime = advancedDateTime;\n newDetails.driftStart = edge;\n }\n newDetails.driftEndTime = advancedDateTime;\n newDetails.driftEnd = edge;\n } else {\n newDetails.driftEndTime = oldDetails.driftEndTime;\n newDetails.driftEnd = oldDetails.driftEnd;\n newDetails.advancedDateTime = oldDetails.advancedDateTime;\n }\n if (newDetails.requestScheduled === -1) {\n newDetails.requestScheduled = oldDetails.requestScheduled;\n }\n}\nfunction mergeDateRanges(oldDateRanges, newDetails) {\n const {\n dateRanges: deltaDateRanges,\n recentlyRemovedDateranges\n } = newDetails;\n const dateRanges = _extends({}, oldDateRanges);\n if (recentlyRemovedDateranges) {\n recentlyRemovedDateranges.forEach(id => {\n delete dateRanges[id];\n });\n }\n const mergeIds = Object.keys(dateRanges);\n const mergeCount = mergeIds.length;\n if (mergeCount) {\n Object.keys(deltaDateRanges).forEach(id => {\n const mergedDateRange = dateRanges[id];\n const dateRange = new DateRange(deltaDateRanges[id].attr, mergedDateRange);\n if (dateRange.isValid) {\n dateRanges[id] = dateRange;\n if (!mergedDateRange) {\n dateRange.tagOrder += mergeCount;\n }\n } else {\n logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: \"${stringify(deltaDateRanges[id].attr)}\"`);\n }\n });\n }\n return dateRanges;\n}\nfunction mapPartIntersection(oldParts, newParts, intersectionFn) {\n if (oldParts && newParts) {\n let delta = 0;\n for (let i = 0, len = oldParts.length; i <= len; i++) {\n const oldPart = oldParts[i];\n const newPart = newParts[i + delta];\n if (oldPart && newPart && oldPart.index === newPart.index && oldPart.fragment.sn === newPart.fragment.sn) {\n intersectionFn(oldPart, newPart);\n } else {\n delta--;\n }\n }\n }\n}\nfunction mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {\n const skippedSegments = newDetails.skippedSegments;\n const start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;\n const end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;\n const delta = newDetails.startSN - oldDetails.startSN;\n const newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;\n const oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;\n for (let i = start; i <= end; i++) {\n const oldFrag = oldFrags[delta + i];\n let newFrag = newFrags[i];\n if (skippedSegments && !newFrag && oldFrag) {\n // Fill in skipped segments in delta playlist\n newFrag = newDetails.fragments[i] = oldFrag;\n }\n if (oldFrag && newFrag) {\n intersectionFn(oldFrag, newFrag, i, newFrags);\n if (oldFrag.url && oldFrag.url !== newFrag.url) {\n newDetails.playlistParsingError = getSequenceError(`media sequence mismatch ${newFrag.sn}:`, oldDetails, newDetails, oldFrag, newFrag);\n return;\n } else if (oldFrag.cc !== newFrag.cc) {\n newDetails.playlistParsingError = getSequenceError(`discontinuity sequence mismatch (${oldFrag.cc}!=${newFrag.cc})`, oldDetails, newDetails, oldFrag, newFrag);\n return;\n }\n }\n }\n}\nfunction getSequenceError(message, oldDetails, newDetails, oldFrag, newFrag) {\n return new Error(`${message} ${newFrag.url}\nPlaylist starting @${oldDetails.startSN}\n${oldDetails.m3u8}\n\nPlaylist starting @${newDetails.startSN}\n${newDetails.m3u8}`);\n}\nfunction adjustSliding(oldDetails, newDetails, matchingStableVariantOrRendition = true) {\n const delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;\n const oldFragments = oldDetails.fragments;\n const advancedOrStable = delta >= 0;\n let sliding = 0;\n if (advancedOrStable && delta < oldFragments.length) {\n sliding = oldFragments[delta].start;\n } else if (advancedOrStable && newDetails.startSN === oldDetails.endSN + 1) {\n sliding = oldDetails.fragmentEnd;\n } else if (advancedOrStable && matchingStableVariantOrRendition) {\n // align with expected position (updated playlist start sequence is past end sequence of last update)\n sliding = oldDetails.fragmentStart + delta * newDetails.levelTargetDuration;\n } else if (!newDetails.skippedSegments && newDetails.fragmentStart === 0) {\n // align new start with old (playlist switch has a sequence with no overlap and should not be used for alignment)\n sliding = oldDetails.fragmentStart;\n } else {\n // new details already has a sliding offset or has skipped segments\n return;\n }\n addSliding(newDetails, sliding);\n}\nfunction addSliding(details, sliding) {\n if (sliding) {\n const fragments = details.fragments;\n for (let i = details.skippedSegments; i < fragments.length; i++) {\n fragments[i].addStart(sliding);\n }\n if (details.fragmentHint) {\n details.fragmentHint.addStart(sliding);\n }\n }\n}\nfunction computeReloadInterval(newDetails, distanceToLiveEdgeMs = Infinity) {\n let reloadInterval = 1000 * newDetails.targetduration;\n if (newDetails.updated) {\n // Use last segment duration when shorter than target duration and near live edge\n const fragments = newDetails.fragments;\n const liveEdgeMaxTargetDurations = 4;\n if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {\n const lastSegmentDuration = fragments[fragments.length - 1].duration * 1000;\n if (lastSegmentDuration < reloadInterval) {\n reloadInterval = lastSegmentDuration;\n }\n }\n } else {\n // estimate = 'miss half average';\n // follow HLS Spec, If the client reloads a Playlist file and finds that it has not\n // changed then it MUST wait for a period of one-half the target\n // duration before retrying.\n reloadInterval /= 2;\n }\n return Math.round(reloadInterval);\n}\nfunction getFragmentWithSN(details, sn, fragCurrent) {\n if (!details) {\n return null;\n }\n let fragment = details.fragments[sn - details.startSN];\n if (fragment) {\n return fragment;\n }\n fragment = details.fragmentHint;\n if (fragment && fragment.sn === sn) {\n return fragment;\n }\n if (sn < details.startSN && fragCurrent && fragCurrent.sn === sn) {\n return fragCurrent;\n }\n return null;\n}\nfunction getPartWith(details, sn, partIndex) {\n if (!details) {\n return null;\n }\n return findPart(details.partList, sn, partIndex);\n}\nfunction findPart(partList, sn, partIndex) {\n if (partList) {\n for (let i = partList.length; i--;) {\n const part = partList[i];\n if (part.index === partIndex && part.fragment.sn === sn) {\n return part;\n }\n }\n }\n return null;\n}\nfunction reassignFragmentLevelIndexes(levels) {\n levels.forEach((level, index) => {\n var _level$details;\n (_level$details = level.details) == null ? void 0 : _level$details.fragments.forEach(fragment => {\n fragment.level = index;\n if (fragment.initSegment) {\n fragment.initSegment.level = index;\n }\n });\n });\n}\n\nfunction findFirstFragWithCC(fragments, cc) {\n for (let i = 0, len = fragments.length; i < len; i++) {\n var _fragments$i;\n if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {\n return fragments[i];\n }\n }\n return null;\n}\nfunction shouldAlignOnDiscontinuities(refDetails, details) {\n if (refDetails) {\n if (details.startCC < refDetails.endCC && details.endCC > refDetails.startCC) {\n return true;\n }\n }\n return false;\n}\nfunction adjustFragmentStart(frag, sliding) {\n if (frag) {\n const start = frag.start + sliding;\n frag.start = frag.startPTS = start;\n frag.endPTS = start + frag.duration;\n }\n}\nfunction adjustSlidingStart(sliding, details) {\n // Update segments\n const fragments = details.fragments;\n for (let i = 0, len = fragments.length; i < len; i++) {\n adjustFragmentStart(fragments[i], sliding);\n }\n // Update LL-HLS parts at the end of the playlist\n if (details.fragmentHint) {\n adjustFragmentStart(details.fragmentHint, sliding);\n }\n details.alignedSliding = true;\n}\n\n/**\n * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a\n * contiguous stream with the last fragments.\n * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to\n * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time\n * and an extra download.\n * @param lastLevel\n * @param details\n */\nfunction alignStream(switchDetails, details) {\n if (!switchDetails) {\n return;\n }\n alignDiscontinuities(details, switchDetails);\n if (!details.alignedSliding && switchDetails) {\n // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.\n // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same\n // discontinuity sequence.\n alignMediaPlaylistByPDT(details, switchDetails);\n }\n if (!details.alignedSliding && switchDetails && !details.skippedSegments) {\n // Try to align on sn so that we pick a better start fragment.\n // Do not perform this on playlists with delta updates as this is only to align levels on switch\n // and adjustSliding only adjusts fragments after skippedSegments.\n adjustSliding(switchDetails, details, false);\n }\n}\n\n/**\n * Ajust the start of fragments in `details` by the difference in time between fragments of the latest\n * shared discontinuity sequence change.\n * @param lastLevel - The details of the last loaded level\n * @param details - The details of the new level\n */\nfunction alignDiscontinuities(details, refDetails) {\n if (!shouldAlignOnDiscontinuities(refDetails, details)) {\n return;\n }\n const targetCC = Math.min(refDetails.endCC, details.endCC);\n const refFrag = findFirstFragWithCC(refDetails.fragments, targetCC);\n const frag = findFirstFragWithCC(details.fragments, targetCC);\n if (!refFrag || !frag) {\n return;\n }\n logger.log(`Aligning playlist at start of dicontinuity sequence ${targetCC}`);\n const delta = refFrag.start - frag.start;\n adjustSlidingStart(delta, details);\n}\n\n/**\n * Ensures appropriate time-alignment between renditions based on PDT.\n * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs\n * for the last discontinuity sequence number shared by both playlists when present,\n * and uses the \"wallclock\"/PDT timeline as a cross-reference to `details`, adjusting the presentation\n * times/timelines of `details` accordingly.\n * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,\n * the primary purpose of this function is to ensure the \"local timelines\" of audio/subtitle tracks\n * are aligned to the main/video timeline, using PDT as the cross-reference/\"anchor\" that should\n * be consistent across playlists, per the HLS spec.\n * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).\n * @param refDetails - The details of the reference rendition with start and PDT times for alignment.\n */\nfunction alignMediaPlaylistByPDT(details, refDetails) {\n if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {\n return;\n }\n const fragments = details.fragments;\n const refFragments = refDetails.fragments;\n if (!fragments.length || !refFragments.length) {\n return;\n }\n\n // Calculate a delta to apply to all fragments according to the delta in PDT times and start times\n // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.\n // If a fragment of the same discontinuity was not found use the middle fragment of both.\n let refFrag;\n let frag;\n const targetCC = Math.min(refDetails.endCC, details.endCC);\n if (refDetails.startCC < targetCC && details.startCC < targetCC) {\n refFrag = findFirstFragWithCC(refFragments, targetCC);\n frag = findFirstFragWithCC(fragments, targetCC);\n }\n if (!refFrag || !frag) {\n refFrag = refFragments[Math.floor(refFragments.length / 2)];\n frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];\n }\n const refPDT = refFrag.programDateTime;\n const targetPDT = frag.programDateTime;\n if (!refPDT || !targetPDT) {\n return;\n }\n const delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);\n adjustSlidingStart(delta, details);\n}\n\n/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r) {\n let log = '';\n const len = r.length;\n for (let i = 0; i < len; i++) {\n log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;\n }\n return log;\n }\n};\n\nconst State = {\n STOPPED: 'STOPPED',\n IDLE: 'IDLE',\n KEY_LOADING: 'KEY_LOADING',\n FRAG_LOADING: 'FRAG_LOADING',\n FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',\n WAITING_TRACK: 'WAITING_TRACK',\n PARSING: 'PARSING',\n PARSED: 'PARSED',\n ENDED: 'ENDED',\n ERROR: 'ERROR',\n WAITING_INIT_PTS: 'WAITING_INIT_PTS',\n WAITING_LEVEL: 'WAITING_LEVEL'\n};\nclass BaseStreamController extends TaskLoop {\n constructor(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {\n super(logPrefix, hls.logger);\n this.hls = void 0;\n this.fragPrevious = null;\n this.fragCurrent = null;\n this.fragmentTracker = void 0;\n this.transmuxer = null;\n this._state = State.STOPPED;\n this.playlistType = void 0;\n this.media = null;\n this.mediaBuffer = null;\n this.config = void 0;\n this.bitrateTest = false;\n this.lastCurrentTime = 0;\n this.nextLoadPosition = 0;\n this.startPosition = 0;\n this.startTimeOffset = null;\n this.retryDate = 0;\n this.levels = null;\n this.fragmentLoader = void 0;\n this.keyLoader = void 0;\n this.levelLastLoaded = null;\n this.startFragRequested = false;\n this.decrypter = void 0;\n this.initPTS = [];\n this.buffering = true;\n this.loadingParts = false;\n this.loopSn = void 0;\n this.onMediaSeeking = () => {\n const {\n config,\n fragCurrent,\n media,\n mediaBuffer,\n state\n } = this;\n const currentTime = media ? media.currentTime : 0;\n const bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);\n this.log(`media seeking to ${isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime}, state: ${state}`);\n if (this.state === State.ENDED) {\n this.resetLoadingState();\n } else if (fragCurrent) {\n // Seeking while frag load is in progress\n const tolerance = config.maxFragLookUpTolerance;\n const fragStartOffset = fragCurrent.start - tolerance;\n const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;\n // if seeking out of buffered range or into new one\n if (!bufferInfo.len || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {\n const pastFragment = currentTime > fragEndOffset;\n // if the seek position is outside the current fragment range\n if (currentTime < fragStartOffset || pastFragment) {\n if (pastFragment && fragCurrent.loader) {\n this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');\n fragCurrent.abortRequests();\n this.resetLoadingState();\n }\n this.fragPrevious = null;\n }\n }\n }\n if (media) {\n // Remove gap fragments\n this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, this.playlistType, true);\n\n // Don't set lastCurrentTime with backward seeks (allows for frag selection with strict tolerances)\n const lastCurrentTime = this.lastCurrentTime;\n if (currentTime > lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\n if (!this.loadingParts) {\n const bufferEnd = Math.max(bufferInfo.end, currentTime);\n const shouldLoadParts = this.shouldLoadParts(this.getLevelDetails(), bufferEnd);\n if (shouldLoadParts) {\n this.log(`LL-Part loading ON after seeking to ${currentTime.toFixed(2)} with buffer @${bufferEnd.toFixed(2)}`);\n this.loadingParts = shouldLoadParts;\n }\n }\n }\n\n // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target\n if (!this.hls.hasEnoughToStart && !bufferInfo.len) {\n this.log(`setting startPosition to ${currentTime} because of seek before start`);\n this.nextLoadPosition = this.startPosition = currentTime;\n }\n\n // Async tick to speed up processing\n this.tickImmediate();\n };\n this.onMediaEnded = () => {\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.log(`setting startPosition to 0 because media ended`);\n this.startPosition = this.lastCurrentTime = 0;\n };\n this.playlistType = playlistType;\n this.hls = hls;\n this.fragmentLoader = new FragmentLoader(hls.config);\n this.keyLoader = keyLoader;\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.decrypter = new Decrypter(hls.config);\n }\n registerListeners() {\n const {\n hls\n } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n unregisterListeners() {\n const {\n hls\n } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n doTick() {\n this.onTickEnd();\n }\n onTickEnd() {}\n startLoad(startPosition) {}\n stopLoad() {\n if (this.state === State.STOPPED) {\n return;\n }\n this.fragmentLoader.abort();\n this.keyLoader.abort(this.playlistType);\n const frag = this.fragCurrent;\n if (frag != null && frag.loader) {\n frag.abortRequests();\n this.fragmentTracker.removeFragment(frag);\n }\n this.resetTransmuxer();\n this.fragCurrent = null;\n this.fragPrevious = null;\n this.clearInterval();\n this.clearNextTick();\n this.state = State.STOPPED;\n }\n get startPositionValue() {\n const {\n nextLoadPosition,\n startPosition\n } = this;\n if (startPosition === -1 && nextLoadPosition) {\n return nextLoadPosition;\n }\n return startPosition;\n }\n get bufferingEnabled() {\n return this.buffering;\n }\n pauseBuffering() {\n this.buffering = false;\n }\n resumeBuffering() {\n this.buffering = true;\n }\n get inFlightFrag() {\n return {\n frag: this.fragCurrent,\n state: this.state\n };\n }\n _streamEnded(bufferInfo, levelDetails) {\n // Stream is never \"ended\" when playlist is live or media is detached\n if (levelDetails.live || !this.media) {\n return false;\n }\n // Stream is not \"ended\" when nothing is buffered past the start\n const bufferEnd = bufferInfo.end || 0;\n const timelineStart = this.config.timelineOffset || 0;\n if (bufferEnd <= timelineStart) {\n return false;\n }\n // Stream is not \"ended\" when there is a second buffered range starting before the end of the playlist\n const nextStart = bufferInfo.nextStart;\n const hasSecondBufferedRange = nextStart && nextStart > timelineStart && nextStart < levelDetails.edge;\n if (hasSecondBufferedRange) {\n return false;\n }\n // Playhead is in unbuffered region. Marking EoS now could result in Safari failing to dispatch \"ended\" event following seek on start.\n if (this.media.currentTime < bufferInfo.start) {\n return false;\n }\n const partList = levelDetails.partList;\n // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,\n // check instead if the last part is buffered.\n if (partList != null && partList.length) {\n const lastPart = partList[partList.length - 1];\n\n // Checking the midpoint of the part for potential margin of error and related issues.\n // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)\n // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream\n // part mismatches for independent audio and video playlists/segments.\n const lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);\n return lastPartBuffered;\n }\n const playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;\n return this.fragmentTracker.isEndListAppended(playlistType);\n }\n getLevelDetails() {\n if (this.levels && this.levelLastLoaded !== null) {\n var _this$levelLastLoaded;\n return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;\n }\n }\n get timelineOffset() {\n const configuredTimelineOffset = this.config.timelineOffset;\n if (configuredTimelineOffset) {\n var _this$getLevelDetails;\n return ((_this$getLevelDetails = this.getLevelDetails()) == null ? void 0 : _this$getLevelDetails.appliedTimelineOffset) || configuredTimelineOffset;\n }\n return 0;\n }\n onMediaAttached(event, data) {\n const media = this.media = this.mediaBuffer = data.media;\n media.removeEventListener('seeking', this.onMediaSeeking);\n media.removeEventListener('ended', this.onMediaEnded);\n media.addEventListener('seeking', this.onMediaSeeking);\n media.addEventListener('ended', this.onMediaEnded);\n const config = this.config;\n if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {\n this.startLoad(config.startPosition);\n }\n }\n onMediaDetaching(event, data) {\n const transferringMedia = !!data.transferMedia;\n const media = this.media;\n if (media === null) {\n return;\n }\n if (media.ended) {\n this.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // remove video listeners\n media.removeEventListener('seeking', this.onMediaSeeking);\n media.removeEventListener('ended', this.onMediaEnded);\n if (this.keyLoader && !transferringMedia) {\n this.keyLoader.detach();\n }\n this.media = this.mediaBuffer = null;\n this.loopSn = undefined;\n if (transferringMedia) {\n this.resetLoadingState();\n this.resetTransmuxer();\n return;\n }\n this.loadingParts = false;\n this.fragmentTracker.removeAllFragments();\n this.stopLoad();\n }\n onManifestLoading() {\n this.initPTS = [];\n this.levels = this.levelLastLoaded = this.fragCurrent = null;\n this.lastCurrentTime = this.startPosition = 0;\n this.startFragRequested = false;\n }\n onError(event, data) {}\n onManifestLoaded(event, data) {\n this.startTimeOffset = data.startTimeOffset;\n }\n onHandlerDestroying() {\n this.stopLoad();\n if (this.transmuxer) {\n this.transmuxer.destroy();\n this.transmuxer = null;\n }\n super.onHandlerDestroying();\n // @ts-ignore\n this.hls = this.onMediaSeeking = this.onMediaEnded = null;\n }\n onHandlerDestroyed() {\n this.state = State.STOPPED;\n if (this.fragmentLoader) {\n this.fragmentLoader.destroy();\n }\n if (this.keyLoader) {\n this.keyLoader.destroy();\n }\n if (this.decrypter) {\n this.decrypter.destroy();\n }\n this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;\n super.onHandlerDestroyed();\n }\n loadFragment(frag, level, targetBufferTime) {\n this.startFragRequested = true;\n this._loadFragForPlayback(frag, level, targetBufferTime);\n }\n _loadFragForPlayback(fragment, level, targetBufferTime) {\n const progressCallback = data => {\n const frag = data.frag;\n if (this.fragContextChanged(frag)) {\n this.warn(`${frag.type} sn: ${frag.sn}${data.part ? ' part: ' + data.part.index : ''} of ${this.fragInfo(frag, false, data.part)}) was dropped during download.`);\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n frag.stats.chunkCount++;\n this._handleFragmentLoadProgress(data);\n };\n this._doFragLoad(fragment, level, targetBufferTime, progressCallback).then(data => {\n if (!data) {\n // if we're here we probably needed to backtrack or are waiting for more parts\n return;\n }\n const state = this.state;\n const frag = data.frag;\n if (this.fragContextChanged(frag)) {\n if (state === State.FRAG_LOADING || !this.fragCurrent && state === State.PARSING) {\n this.fragmentTracker.removeFragment(frag);\n this.state = State.IDLE;\n }\n return;\n }\n if ('payload' in data) {\n this.log(`Loaded ${frag.type} sn: ${frag.sn} of ${this.playlistLabel()} ${frag.level}`);\n this.hls.trigger(Events.FRAG_LOADED, data);\n }\n\n // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback\n this._handleFragmentLoadComplete(data);\n }).catch(reason => {\n if (this.state === State.STOPPED || this.state === State.ERROR) {\n return;\n }\n this.warn(`Frag error: ${(reason == null ? void 0 : reason.message) || reason}`);\n this.resetFragmentLoading(fragment);\n });\n }\n clearTrackerIfNeeded(frag) {\n var _this$mediaBuffer;\n const {\n fragmentTracker\n } = this;\n const fragState = fragmentTracker.getState(frag);\n if (fragState === FragmentState.APPENDING) {\n // Lower the max buffer length and try again\n const playlistType = frag.type;\n const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);\n const minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);\n // If backtracking, always remove from the tracker without reducing max buffer length\n const backtrackFragment = this.backtrackFragment;\n const backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;\n if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {\n fragmentTracker.removeFragment(frag);\n }\n } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {\n // Stop gap for bad tracker / buffer flush behavior\n fragmentTracker.removeAllFragments();\n } else if (fragmentTracker.hasParts(frag.type)) {\n // In low latency mode, remove fragments for which only some parts were buffered\n fragmentTracker.detectPartialFragments({\n frag,\n part: null,\n stats: frag.stats,\n id: frag.type\n });\n if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {\n fragmentTracker.removeFragment(frag);\n }\n }\n }\n checkLiveUpdate(details) {\n if (details.updated && !details.live) {\n // Live stream ended, update fragment tracker\n const lastFragment = details.fragments[details.fragments.length - 1];\n this.fragmentTracker.detectPartialFragments({\n frag: lastFragment,\n part: null,\n stats: lastFragment.stats,\n id: lastFragment.type\n });\n }\n if (!details.fragments[0]) {\n details.deltaUpdateFailed = true;\n }\n }\n waitForLive(levelInfo) {\n const details = levelInfo.details;\n return (details == null ? void 0 : details.live) && details.type !== 'EVENT' && (this.levelLastLoaded !== levelInfo || details.expired);\n }\n flushMainBuffer(startOffset, endOffset, type = null) {\n if (!(startOffset - endOffset)) {\n return;\n }\n // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,\n // passing a null type flushes both buffers\n const flushScope = {\n startOffset,\n endOffset,\n type\n };\n this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);\n }\n _loadInitSegment(fragment, level) {\n this._doFragLoad(fragment, level).then(data => {\n const frag = data == null ? void 0 : data.frag;\n if (!frag || this.fragContextChanged(frag) || !this.levels) {\n throw new Error('init load aborted');\n }\n return data;\n }).then(data => {\n const {\n hls\n } = this;\n const {\n frag,\n payload\n } = data;\n const decryptData = frag.decryptdata;\n\n // check to see if the payload needs to be decrypted\n if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {\n const startTime = self.performance.now();\n // decrypt init segment data\n return this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch(err => {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_DECRYPT_ERROR,\n fatal: false,\n error: err,\n reason: err.message,\n frag\n });\n throw err;\n }).then(decryptedData => {\n const endTime = self.performance.now();\n hls.trigger(Events.FRAG_DECRYPTED, {\n frag,\n payload: decryptedData,\n stats: {\n tstart: startTime,\n tdecrypt: endTime\n }\n });\n data.payload = decryptedData;\n return this.completeInitSegmentLoad(data);\n });\n }\n return this.completeInitSegmentLoad(data);\n }).catch(reason => {\n if (this.state === State.STOPPED || this.state === State.ERROR) {\n return;\n }\n this.warn(reason);\n this.resetFragmentLoading(fragment);\n });\n }\n completeInitSegmentLoad(data) {\n const {\n levels\n } = this;\n if (!levels) {\n throw new Error('init load aborted, missing levels');\n }\n const stats = data.frag.stats;\n if (this.state !== State.STOPPED) {\n this.state = State.IDLE;\n }\n data.frag.data = new Uint8Array(data.payload);\n stats.parsing.start = stats.buffering.start = self.performance.now();\n stats.parsing.end = stats.buffering.end = self.performance.now();\n this.tick();\n }\n fragContextChanged(frag) {\n const {\n fragCurrent\n } = this;\n return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;\n }\n fragBufferedComplete(frag, part) {\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n this.log(`Buffered ${frag.type} sn: ${frag.sn}${part ? ' part: ' + part.index : ''} of ${this.fragInfo(frag, false, part)} > buffer:${media ? TimeRanges.toString(BufferHelper.getBuffered(media)) : '(detached)'})`);\n if (isMediaFragment(frag)) {\n var _this$levels;\n if (frag.type !== PlaylistLevelType.SUBTITLE) {\n const el = frag.elementaryStreams;\n if (!Object.keys(el).some(type => !!el[type])) {\n // empty segment\n this.state = State.IDLE;\n return;\n }\n }\n const level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];\n if (level != null && level.fragmentError) {\n this.log(`Resetting level fragment error count of ${level.fragmentError} on frag buffered`);\n level.fragmentError = 0;\n }\n }\n this.state = State.IDLE;\n }\n _handleFragmentLoadComplete(fragLoadedEndData) {\n const {\n transmuxer\n } = this;\n if (!transmuxer) {\n return;\n }\n const {\n frag,\n part,\n partsLoaded\n } = fragLoadedEndData;\n // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data\n const complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(fragLoaded => !fragLoaded);\n const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);\n transmuxer.flush(chunkMeta);\n }\n _handleFragmentLoadProgress(frag) {}\n _doFragLoad(frag, level, targetBufferTime = null, progressCallback) {\n var _frag$decryptdata;\n this.fragCurrent = frag;\n const details = level == null ? void 0 : level.details;\n if (!this.levels || !details) {\n throw new Error(`frag load aborted, missing level${details ? '' : ' detail'}s`);\n }\n let keyLoadingPromise = null;\n if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {\n this.log(`Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${this.playlistLabel()} ${frag.level}`);\n this.state = State.KEY_LOADING;\n this.fragCurrent = frag;\n keyLoadingPromise = this.keyLoader.load(frag).then(keyLoadedData => {\n if (!this.fragContextChanged(keyLoadedData.frag)) {\n this.hls.trigger(Events.KEY_LOADED, keyLoadedData);\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n }\n return keyLoadedData;\n }\n });\n this.hls.trigger(Events.KEY_LOADING, {\n frag\n });\n if (this.fragCurrent === null) {\n keyLoadingPromise = Promise.reject(new Error(`frag load aborted, context changed in KEY_LOADING`));\n }\n } else if (!frag.encrypted && details.encryptedFragments.length) {\n this.keyLoader.loadClear(frag, details.encryptedFragments);\n }\n const fragPrevious = this.fragPrevious;\n if (isMediaFragment(frag) && (!fragPrevious || frag.sn !== fragPrevious.sn)) {\n const shouldLoadParts = this.shouldLoadParts(level.details, frag.end);\n if (shouldLoadParts !== this.loadingParts) {\n this.log(`LL-Part loading ${shouldLoadParts ? 'ON' : 'OFF'} loading sn ${fragPrevious == null ? void 0 : fragPrevious.sn}->${frag.sn}`);\n this.loadingParts = shouldLoadParts;\n }\n }\n targetBufferTime = Math.max(frag.start, targetBufferTime || 0);\n if (this.loadingParts && isMediaFragment(frag)) {\n const partList = details.partList;\n if (partList && progressCallback) {\n if (targetBufferTime > frag.end && details.fragmentHint) {\n frag = details.fragmentHint;\n }\n const partIndex = this.getNextPart(partList, frag, targetBufferTime);\n if (partIndex > -1) {\n const part = partList[partIndex];\n frag = this.fragCurrent = part.fragment;\n this.log(`Loading ${frag.type} sn: ${frag.sn} part: ${part.index} (${partIndex}/${partList.length - 1}) of ${this.fragInfo(frag, false, part)}) cc: ${frag.cc} [${details.startSN}-${details.endSN}], target: ${parseFloat(targetBufferTime.toFixed(3))}`);\n this.nextLoadPosition = part.start + part.duration;\n this.state = State.FRAG_LOADING;\n let _result;\n if (keyLoadingPromise) {\n _result = keyLoadingPromise.then(keyLoadedData => {\n if (!keyLoadedData || this.fragContextChanged(keyLoadedData.frag)) {\n return null;\n }\n return this.doFragPartsLoad(frag, part, level, progressCallback);\n }).catch(error => this.handleFragLoadError(error));\n } else {\n _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch(error => this.handleFragLoadError(error));\n }\n this.hls.trigger(Events.FRAG_LOADING, {\n frag,\n part,\n targetBufferTime\n });\n if (this.fragCurrent === null) {\n return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING parts`));\n }\n return _result;\n } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {\n // Fragment hint has no parts\n return Promise.resolve(null);\n }\n }\n }\n if (isMediaFragment(frag) && this.loadingParts) {\n this.log(`LL-Part loading OFF after next part miss @${targetBufferTime.toFixed(2)}`);\n this.loadingParts = false;\n } else if (!frag.url) {\n // Selected fragment hint for part but not loading parts\n return Promise.resolve(null);\n }\n this.log(`Loading ${frag.type} sn: ${frag.sn} of ${this.fragInfo(frag, false)}) cc: ${frag.cc} ${details ? '[' + details.startSN + '-' + details.endSN + ']' : ''}, target: ${parseFloat(targetBufferTime.toFixed(3))}`);\n // Don't update nextLoadPosition for fragments which are not buffered\n if (isFiniteNumber(frag.sn) && !this.bitrateTest) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n this.state = State.FRAG_LOADING;\n\n // Load key before streaming fragment data\n const dataOnProgress = this.config.progressive;\n let result;\n if (dataOnProgress && keyLoadingPromise) {\n result = keyLoadingPromise.then(keyLoadedData => {\n if (!keyLoadedData || this.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {\n return null;\n }\n return this.fragmentLoader.load(frag, progressCallback);\n }).catch(error => this.handleFragLoadError(error));\n } else {\n // load unencrypted fragment data with progress event,\n // or handle fragment result after key and fragment are finished loading\n result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : undefined), keyLoadingPromise]).then(([fragLoadedData]) => {\n if (!dataOnProgress && fragLoadedData && progressCallback) {\n progressCallback(fragLoadedData);\n }\n return fragLoadedData;\n }).catch(error => this.handleFragLoadError(error));\n }\n this.hls.trigger(Events.FRAG_LOADING, {\n frag,\n targetBufferTime\n });\n if (this.fragCurrent === null) {\n return Promise.reject(new Error(`frag load aborted, context changed in FRAG_LOADING`));\n }\n return result;\n }\n doFragPartsLoad(frag, fromPart, level, progressCallback) {\n return new Promise((resolve, reject) => {\n var _level$details;\n const partsLoaded = [];\n const initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;\n const loadPart = part => {\n this.fragmentLoader.loadPart(frag, part, progressCallback).then(partLoadedData => {\n partsLoaded[part.index] = partLoadedData;\n const loadedPart = partLoadedData.part;\n this.hls.trigger(Events.FRAG_LOADED, partLoadedData);\n const nextPart = getPartWith(level.details, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);\n if (nextPart) {\n loadPart(nextPart);\n } else {\n return resolve({\n frag,\n part: loadedPart,\n partsLoaded\n });\n }\n }).catch(reject);\n };\n loadPart(fromPart);\n });\n }\n handleFragLoadError(error) {\n if ('data' in error) {\n const data = error.data;\n if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {\n this.handleFragLoadAborted(data.frag, data.part);\n } else {\n this.hls.trigger(Events.ERROR, data);\n }\n } else {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n err: error,\n error,\n fatal: true\n });\n }\n return null;\n }\n _handleTransmuxerFlush(chunkMeta) {\n const context = this.getCurrentContext(chunkMeta);\n if (!context || this.state !== State.PARSING) {\n if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {\n this.state = State.IDLE;\n }\n return;\n }\n const {\n frag,\n part,\n level\n } = context;\n const now = self.performance.now();\n frag.stats.parsing.end = now;\n if (part) {\n part.stats.parsing.end = now;\n }\n // See if part loading should be disabled/enabled based on buffer and playback position.\n const levelDetails = this.getLevelDetails();\n const loadingPartsAtEdge = levelDetails && frag.sn > levelDetails.endSN;\n const shouldLoadParts = loadingPartsAtEdge || this.shouldLoadParts(levelDetails, frag.end);\n if (shouldLoadParts !== this.loadingParts) {\n this.log(`LL-Part loading ${shouldLoadParts ? 'ON' : 'OFF'} after parsing segment ending @${frag.end.toFixed(2)}`);\n this.loadingParts = shouldLoadParts;\n }\n this.updateLevelTiming(frag, part, level, chunkMeta.partial);\n }\n shouldLoadParts(details, bufferEnd) {\n if (this.config.lowLatencyMode) {\n if (!details) {\n return this.loadingParts;\n }\n if (details != null && details.partList) {\n var _details$fragmentHint;\n // Buffer must be ahead of first part + duration of parts after last segment\n // and playback must be at or past segment adjacent to part list\n const firstPart = details.partList[0];\n const safePartStart = firstPart.end + (((_details$fragmentHint = details.fragmentHint) == null ? void 0 : _details$fragmentHint.duration) || 0);\n if (bufferEnd >= safePartStart) {\n var _this$media;\n const playhead = this.hls.hasEnoughToStart ? ((_this$media = this.media) == null ? void 0 : _this$media.currentTime) || this.lastCurrentTime : this.getLoadPosition();\n if (playhead > firstPart.start - firstPart.fragment.duration) {\n return true;\n }\n }\n }\n }\n return false;\n }\n getCurrentContext(chunkMeta) {\n const {\n levels,\n fragCurrent\n } = this;\n const {\n level: levelIndex,\n sn,\n part: partIndex\n } = chunkMeta;\n if (!(levels != null && levels[levelIndex])) {\n this.warn(`Levels object was unset while buffering fragment ${sn} of ${this.playlistLabel()} ${levelIndex}. The current chunk will not be buffered.`);\n return null;\n }\n const level = levels[levelIndex];\n const levelDetails = level.details;\n const part = partIndex > -1 ? getPartWith(levelDetails, sn, partIndex) : null;\n const frag = part ? part.fragment : getFragmentWithSN(levelDetails, sn, fragCurrent);\n if (!frag) {\n return null;\n }\n if (fragCurrent && fragCurrent !== frag) {\n frag.stats = fragCurrent.stats;\n }\n return {\n frag,\n part,\n level\n };\n }\n bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {\n var _buffer;\n if (!data || this.state !== State.PARSING) {\n return;\n }\n const {\n data1,\n data2\n } = data;\n let buffer = data1;\n if (data1 && data2) {\n // Combine the moof + mdat so that we buffer with a single append\n buffer = appendUint8Array(data1, data2);\n }\n if (!((_buffer = buffer) != null && _buffer.length)) {\n return;\n }\n const segment = {\n type: data.type,\n frag,\n part,\n chunkMeta,\n parent: frag.type,\n data: buffer\n };\n this.hls.trigger(Events.BUFFER_APPENDING, segment);\n if (data.dropped && data.independent && !part) {\n if (noBacktracking) {\n return;\n }\n // Clear buffer so that we reload previous segments sequentially if required\n this.flushBufferGap(frag);\n }\n }\n flushBufferGap(frag) {\n const media = this.media;\n if (!media) {\n return;\n }\n // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed\n if (!BufferHelper.isBuffered(media, media.currentTime)) {\n this.flushMainBuffer(0, frag.start);\n return;\n }\n // Remove back-buffer without interrupting playback to allow back tracking\n const currentTime = media.currentTime;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const fragDuration = frag.duration;\n const segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);\n const start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);\n if (frag.start - start > segmentFraction) {\n this.flushMainBuffer(start, frag.start);\n }\n }\n getFwdBufferInfo(bufferable, type) {\n var _this$media2;\n const pos = this.getLoadPosition();\n if (!isFiniteNumber(pos)) {\n return null;\n }\n const backwardSeek = this.lastCurrentTime > pos;\n const maxBufferHole = backwardSeek || (_this$media2 = this.media) != null && _this$media2.paused ? 0 : this.config.maxBufferHole;\n return this.getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole);\n }\n getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole) {\n const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);\n // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos\n if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {\n const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);\n if (bufferedFragAtPos && (bufferInfo.nextStart <= bufferedFragAtPos.end || bufferedFragAtPos.gap)) {\n const gapDuration = Math.max(Math.min(bufferInfo.nextStart, bufferedFragAtPos.end) - pos, maxBufferHole);\n return BufferHelper.bufferInfo(bufferable, pos, gapDuration);\n }\n }\n return bufferInfo;\n }\n getMaxBufferLength(levelBitrate) {\n const {\n config\n } = this;\n let maxBufLen;\n if (levelBitrate) {\n maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);\n } else {\n maxBufLen = config.maxBufferLength;\n }\n return Math.min(maxBufLen, config.maxMaxBufferLength);\n }\n reduceMaxBufferLength(threshold, fragDuration) {\n const config = this.config;\n const minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);\n const reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);\n if (reducedLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength = reducedLength;\n this.warn(`Reduce max buffer length to ${reducedLength}s`);\n return true;\n }\n return false;\n }\n getAppendedFrag(position, playlistType = PlaylistLevelType.MAIN) {\n var _this$fragmentTracker;\n const fragOrPart = (_this$fragmentTracker = this.fragmentTracker) == null ? void 0 : _this$fragmentTracker.getAppendedFrag(position, playlistType);\n if (fragOrPart && 'fragment' in fragOrPart) {\n return fragOrPart.fragment;\n }\n return fragOrPart;\n }\n getNextFragment(pos, levelDetails) {\n const fragments = levelDetails.fragments;\n const fragLen = fragments.length;\n if (!fragLen) {\n return null;\n }\n\n // find fragment index, contiguous with end of buffer position\n const {\n config\n } = this;\n const start = fragments[0].start;\n const canLoadParts = config.lowLatencyMode && !!levelDetails.partList;\n let frag = null;\n if (levelDetails.live) {\n const initialLiveManifestSize = config.initialLiveManifestSize;\n if (fragLen < initialLiveManifestSize) {\n this.warn(`Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`);\n return null;\n }\n // The real fragment start times for a live stream are only known after the PTS range for that level is known.\n // In order to discover the range, we load the best matching fragment for that level and demux it.\n // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that\n // we get the fragment matching that start time\n if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {\n var _frag;\n if (canLoadParts && !this.loadingParts) {\n this.log(`LL-Part loading ON for initial live fragment`);\n this.loadingParts = true;\n }\n frag = this.getInitialLiveFragment(levelDetails, fragments);\n const mainStart = this.hls.startPosition;\n const liveSyncPosition = this.hls.liveSyncPosition;\n const startPosition = frag ? (mainStart !== -1 && mainStart >= start ? mainStart : liveSyncPosition) || frag.start : pos;\n this.log(`Setting startPosition to ${startPosition} to match start frag at live edge. mainStart: ${mainStart} liveSyncPosition: ${liveSyncPosition} frag.start: ${(_frag = frag) == null ? void 0 : _frag.start}`);\n this.startPosition = this.nextLoadPosition = startPosition;\n }\n } else if (pos <= start) {\n // VoD playlist: if loadPosition before start of playlist, load first fragment\n frag = fragments[0];\n }\n\n // If we haven't run into any special cases already, just load the fragment most closely matching the requested position\n if (!frag) {\n const end = this.loadingParts ? levelDetails.partEnd : levelDetails.fragmentEnd;\n frag = this.getFragmentAtPosition(pos, end, levelDetails);\n }\n let programFrag = this.filterReplacedPrimary(frag, levelDetails);\n if (!programFrag && frag) {\n const curSNIdx = frag.sn - levelDetails.startSN;\n programFrag = this.filterReplacedPrimary(fragments[curSNIdx + 1] || null, levelDetails);\n }\n return this.mapToInitFragWhenRequired(programFrag);\n }\n isLoopLoading(frag, targetBufferTime) {\n const trackerState = this.fragmentTracker.getState(frag);\n return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;\n }\n getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {\n let nextFragment = null;\n if (frag.gap) {\n nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);\n if (nextFragment && !nextFragment.gap && bufferInfo.nextStart) {\n // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length\n const nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType, 0);\n if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {\n // Returning here might result in not finding an audio and video candiate to skip to\n const sn = nextFragment.sn;\n if (this.loopSn !== sn) {\n this.log(`buffer full after gaps in \"${playlistType}\" playlist starting at sn: ${sn}`);\n this.loopSn = sn;\n }\n return null;\n }\n }\n }\n this.loopSn = undefined;\n return nextFragment;\n }\n get primaryPrefetch() {\n if (interstitialsEnabled(this.hls.config)) {\n var _this$hls$interstitia, _this$hls$interstitia2;\n const playingInterstitial = (_this$hls$interstitia = this.hls.interstitialsManager) == null ? void 0 : (_this$hls$interstitia2 = _this$hls$interstitia.playingItem) == null ? void 0 : _this$hls$interstitia2.event;\n if (playingInterstitial) {\n return true;\n }\n }\n return false;\n }\n filterReplacedPrimary(frag, details) {\n if (!frag) {\n return frag;\n }\n if (interstitialsEnabled(this.hls.config) && frag.type !== PlaylistLevelType.SUBTITLE) {\n // Do not load fragments outside the buffering schedule segment\n const interstitials = this.hls.interstitialsManager;\n const bufferingItem = interstitials == null ? void 0 : interstitials.bufferingItem;\n if (bufferingItem) {\n const bufferingInterstitial = bufferingItem.event;\n if (bufferingInterstitial) {\n // Do not stream fragments while buffering Interstitial Events (except for overlap at the start)\n if (bufferingInterstitial.appendInPlace || Math.abs(frag.start - bufferingItem.start) > 1 || bufferingItem.start === 0) {\n return null;\n }\n } else {\n // Limit fragment loading to media in schedule item\n if (frag.end <= bufferingItem.start && (details == null ? void 0 : details.live) === false) {\n // fragment ends by schedule item start\n // this.fragmentTracker.fragBuffered(frag, true);\n return null;\n }\n if (frag.start > bufferingItem.end && bufferingItem.nextEvent) {\n // fragment is past schedule item end\n // allow some overflow when not appending in place to prevent stalls\n if (bufferingItem.nextEvent.appendInPlace || frag.start - bufferingItem.end > 1) {\n return null;\n }\n }\n }\n }\n // Skip loading of fragments that overlap completely with appendInPlace interstitials\n const playerQueue = interstitials == null ? void 0 : interstitials.playerQueue;\n if (playerQueue) {\n for (let i = playerQueue.length; i--;) {\n const interstitial = playerQueue[i].interstitial;\n if (interstitial.appendInPlace && frag.start >= interstitial.startTime && frag.end <= interstitial.resumeTime) {\n return null;\n }\n }\n }\n }\n return frag;\n }\n mapToInitFragWhenRequired(frag) {\n // If an initSegment is present, it must be buffered first\n if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {\n return frag.initSegment;\n }\n return frag;\n }\n getNextPart(partList, frag, targetBufferTime) {\n let nextPart = -1;\n let contiguous = false;\n let independentAttrOmitted = true;\n for (let i = 0, len = partList.length; i < len; i++) {\n const part = partList[i];\n independentAttrOmitted = independentAttrOmitted && !part.independent;\n if (nextPart > -1 && targetBufferTime < part.start) {\n break;\n }\n const loaded = part.loaded;\n if (loaded) {\n nextPart = -1;\n } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {\n nextPart = i;\n }\n contiguous = loaded;\n }\n return nextPart;\n }\n loadedEndOfParts(partList, targetBufferTime) {\n const lastPart = partList[partList.length - 1];\n return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;\n }\n\n /*\n This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the\n \"sliding\" of the playlist, which is its offset from the start of playback. After sliding we can compute the real\n start and end times for each fragment in the playlist (after which this method will not need to be called).\n */\n getInitialLiveFragment(levelDetails, fragments) {\n const fragPrevious = this.fragPrevious;\n let frag = null;\n if (fragPrevious) {\n if (levelDetails.hasProgramDateTime) {\n // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding\n this.log(`Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);\n frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);\n }\n if (!frag) {\n // SN does not need to be accurate between renditions, but depending on the packaging it may be so.\n const targetSN = fragPrevious.sn + 1;\n if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {\n const fragNext = fragments[targetSN - levelDetails.startSN];\n // Ensure that we're staying within the continuity range, since PTS resets upon a new range\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n this.log(`Live playlist, switching playlist, load frag with next SN: ${frag.sn}`);\n }\n }\n // It's important to stay within the continuity range if available; otherwise the fragments in the playlist\n // will have the wrong start times\n if (!frag) {\n frag = findFragWithCC(fragments, fragPrevious.cc);\n if (frag) {\n this.log(`Live playlist, switching playlist, load frag with same CC: ${frag.sn}`);\n }\n }\n }\n } else {\n // Find a new start fragment when fragPrevious is null\n const liveStart = this.hls.liveSyncPosition;\n if (liveStart !== null) {\n frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);\n }\n }\n return frag;\n }\n\n /*\n This method finds the best matching fragment given the provided position.\n */\n getFragmentAtPosition(bufferEnd, end, levelDetails) {\n const {\n config\n } = this;\n let {\n fragPrevious\n } = this;\n let {\n fragments,\n endSN\n } = levelDetails;\n const {\n fragmentHint\n } = levelDetails;\n const {\n maxFragLookUpTolerance\n } = config;\n const partList = levelDetails.partList;\n const loadingParts = !!(this.loadingParts && partList != null && partList.length && fragmentHint);\n if (loadingParts && fragmentHint && !this.bitrateTest && partList[partList.length - 1].fragment.sn === fragmentHint.sn) {\n // Include incomplete fragment with parts at end\n fragments = fragments.concat(fragmentHint);\n endSN = fragmentHint.sn;\n }\n let frag;\n if (bufferEnd < end) {\n var _this$media3;\n const backwardSeek = bufferEnd < this.lastCurrentTime;\n const lookupTolerance = backwardSeek || bufferEnd > end - maxFragLookUpTolerance || (_this$media3 = this.media) != null && _this$media3.paused || !this.startFragRequested ? 0 : maxFragLookUpTolerance;\n // Remove the tolerance if it would put the bufferEnd past the actual end of stream\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);\n } else {\n // reach end of playlist\n frag = fragments[fragments.length - 1];\n }\n if (frag) {\n const curSNIdx = frag.sn - levelDetails.startSN;\n // Move fragPrevious forward to support forcing the next fragment to load\n // when the buffer catches up to a previously buffered range.\n const fragState = this.fragmentTracker.getState(frag);\n if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {\n fragPrevious = frag;\n }\n if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn || !levelDetails.live && !loadingParts)) {\n // Force the next fragment to load if the previous one was already selected. This can occasionally happen with\n // non-uniform fragment durations\n const sameLevel = fragPrevious && frag.level === fragPrevious.level;\n if (sameLevel) {\n const nextFrag = fragments[curSNIdx + 1];\n if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {\n frag = nextFrag;\n } else {\n frag = null;\n }\n }\n }\n }\n return frag;\n }\n alignPlaylists(details, previousDetails, switchDetails) {\n // TODO: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,\n // this could all go in level-helper mergeDetails()\n const length = details.fragments.length;\n if (!length) {\n this.warn(`No fragments in live playlist`);\n return 0;\n }\n const slidingStart = details.fragmentStart;\n const firstLevelLoad = !previousDetails;\n const aligned = details.alignedSliding && isFiniteNumber(slidingStart);\n if (firstLevelLoad || !aligned && !slidingStart) {\n alignStream(switchDetails, details);\n const alignedSlidingStart = details.fragmentStart;\n this.log(`Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${previousDetails ? previousDetails.startSN : 'na'}->${details.startSN} fragments: ${length}`);\n return alignedSlidingStart;\n }\n return slidingStart;\n }\n waitForCdnTuneIn(details) {\n // Wait for Low-Latency CDN Tune-in to get an updated playlist\n const advancePartLimit = 3;\n return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);\n }\n setStartPosition(details, sliding) {\n // compute start position if set to -1. use it straight away if value is defined\n let startPosition = this.startPosition;\n if (startPosition < sliding) {\n startPosition = -1;\n }\n const timelineOffset = this.timelineOffset;\n if (startPosition === -1) {\n // Use Playlist EXT-X-START:TIME-OFFSET when set\n // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match\n const offsetInMultivariantPlaylist = this.startTimeOffset !== null;\n const startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;\n if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {\n startPosition = sliding + startTimeOffset;\n if (startTimeOffset < 0) {\n startPosition += details.edge;\n }\n startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);\n this.log(`Setting startPosition to ${startPosition} for start time offset ${startTimeOffset} found in ${offsetInMultivariantPlaylist ? 'multivariant' : 'media'} playlist`);\n this.startPosition = startPosition;\n } else if (details.live) {\n // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has\n // not been specified via the config or an as an argument to startLoad (#3736).\n startPosition = this.hls.liveSyncPosition || sliding;\n this.log(`Setting startPosition to -1 to start at live edge ${startPosition}`);\n this.startPosition = -1;\n } else {\n this.log(`setting startPosition to 0 by default`);\n this.startPosition = startPosition = 0;\n }\n this.lastCurrentTime = startPosition + timelineOffset;\n }\n this.nextLoadPosition = startPosition + timelineOffset;\n }\n getLoadPosition() {\n var _this$hls;\n const {\n media\n } = this;\n // if we have not yet loaded any fragment, start loading from start position\n let pos = 0;\n if ((_this$hls = this.hls) != null && _this$hls.hasEnoughToStart && media) {\n pos = media.currentTime;\n } else if (this.nextLoadPosition >= 0) {\n pos = this.nextLoadPosition;\n }\n return pos;\n }\n handleFragLoadAborted(frag, part) {\n if (this.transmuxer && frag.type === this.playlistType && isMediaFragment(frag) && frag.stats.aborted) {\n this.warn(`Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of ${this.playlistLabel()} ${frag.level} was aborted`);\n this.resetFragmentLoading(frag);\n }\n }\n resetFragmentLoading(frag) {\n if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {\n this.state = State.IDLE;\n }\n }\n onFragmentOrKeyLoadError(filterType, data) {\n if (data.chunkMeta && !data.frag) {\n const context = this.getCurrentContext(data.chunkMeta);\n if (context) {\n data.frag = context.frag;\n }\n }\n const frag = data.frag;\n // Handle frag error related to caller's filterType\n if (!frag || frag.type !== filterType || !this.levels) {\n return;\n }\n if (this.fragContextChanged(frag)) {\n var _this$fragCurrent;\n this.warn(`Frag load error must match current frag to retry ${frag.url} > ${(_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.url}`);\n return;\n }\n const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;\n if (gapTagEncountered) {\n this.fragmentTracker.fragBuffered(frag, true);\n }\n // keep retrying until the limit will be reached\n const errorAction = data.errorAction;\n const {\n action,\n flags,\n retryCount = 0,\n retryConfig\n } = errorAction || {};\n const couldRetry = !!errorAction && !!retryConfig;\n const retry = couldRetry && action === NetworkErrorAction.RetryRequest;\n const noAlternate = couldRetry && !errorAction.resolved && flags === ErrorActionFlags.MoveAllAlternatesMatchingHost;\n if (!retry && noAlternate && isMediaFragment(frag) && !frag.endList) {\n this.resetFragmentErrors(filterType);\n this.treatAsGap(frag);\n errorAction.resolved = true;\n } else if ((retry || noAlternate) && retryCount < retryConfig.maxNumRetry) {\n this.resetStartWhenNotLoaded(this.levelLastLoaded);\n const delay = getRetryDelay(retryConfig, retryCount);\n this.warn(`Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${data.details}, retrying loading ${retryCount + 1}/${retryConfig.maxNumRetry} in ${delay}ms`);\n errorAction.resolved = true;\n this.retryDate = self.performance.now() + delay;\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else if (retryConfig && errorAction) {\n this.resetFragmentErrors(filterType);\n if (retryCount < retryConfig.maxNumRetry) {\n // Network retry is skipped when level switch is preferred\n if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {\n errorAction.resolved = true;\n }\n } else {\n this.warn(`${data.details} reached or exceeded max retry (${retryCount})`);\n return;\n }\n } else if (action === NetworkErrorAction.SendAlternateToPenaltyBox) {\n this.state = State.WAITING_LEVEL;\n } else {\n this.state = State.ERROR;\n }\n // Perform next async tick sooner to speed up error action resolution\n this.tickImmediate();\n }\n reduceLengthAndFlushBuffer(data) {\n // if in appending state\n if (this.state === State.PARSING || this.state === State.PARSED) {\n const frag = data.frag;\n const playlistType = data.parent;\n const bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n // reduce max buf len if current position is buffered\n const buffered = bufferedInfo && bufferedInfo.len > 0.5;\n if (buffered) {\n this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);\n }\n const flushBuffer = !buffered;\n if (flushBuffer) {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole audio buffer to recover\n this.warn(`Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`);\n }\n if (frag) {\n this.fragmentTracker.removeFragment(frag);\n this.nextLoadPosition = frag.start;\n }\n this.resetLoadingState();\n return flushBuffer;\n }\n return false;\n }\n resetFragmentErrors(filterType) {\n if (filterType === PlaylistLevelType.AUDIO) {\n // Reset current fragment since audio track audio is essential and may not have a fail-over track\n this.fragCurrent = null;\n }\n // Fragment errors that result in a level switch or redundant fail-over\n // should reset the stream controller state to idle\n if (!this.hls.hasEnoughToStart) {\n this.startFragRequested = false;\n }\n if (this.state !== State.STOPPED) {\n this.state = State.IDLE;\n }\n }\n afterBufferFlushed(media, bufferType, playlistType) {\n if (!media) {\n return;\n }\n // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media\n // (so that we will check against video.buffered ranges in case of alt audio track)\n const bufferedTimeRanges = BufferHelper.getBuffered(media);\n this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);\n if (this.state === State.ENDED) {\n this.resetLoadingState();\n }\n }\n resetLoadingState() {\n this.log('Reset loading state');\n this.fragCurrent = null;\n this.fragPrevious = null;\n if (this.state !== State.STOPPED) {\n this.state = State.IDLE;\n }\n }\n resetStartWhenNotLoaded(level) {\n // if loadedmetadata is not set, it means that first frag request failed\n // in that case, reset startFragRequested flag\n if (!this.hls.hasEnoughToStart) {\n this.startFragRequested = false;\n const details = level ? level.details : null;\n if (details != null && details.live) {\n // Update the start position and return to IDLE to recover live start\n this.log(`resetting startPosition for live start`);\n this.startPosition = -1;\n this.setStartPosition(details, details.fragmentStart);\n this.resetLoadingState();\n } else {\n this.nextLoadPosition = this.startPosition;\n }\n }\n }\n resetWhenMissingContext(chunkMeta) {\n this.warn(`The loading context changed while buffering fragment ${chunkMeta.sn} of ${this.playlistLabel()} ${chunkMeta.level}. This chunk will not be buffered.`);\n this.removeUnbufferedFrags();\n this.resetStartWhenNotLoaded(this.levelLastLoaded);\n this.resetLoadingState();\n }\n removeUnbufferedFrags(start = 0) {\n this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);\n }\n updateLevelTiming(frag, part, level, partial) {\n const details = level.details;\n if (!details) {\n this.warn('level.details undefined');\n return;\n }\n const parsed = Object.keys(frag.elementaryStreams).reduce((result, type) => {\n const info = frag.elementaryStreams[type];\n if (info) {\n const parsedDuration = info.endPTS - info.startPTS;\n if (parsedDuration <= 0) {\n // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.\n // The new transmuxer will be configured with a time offset matching the next fragment start,\n // preventing the timeline from shifting.\n this.warn(`Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`);\n return result || false;\n }\n const drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);\n this.hls.trigger(Events.LEVEL_PTS_UPDATED, {\n details,\n level,\n drift,\n type,\n frag,\n start: info.startPTS,\n end: info.endPTS\n });\n return true;\n }\n return result;\n }, false);\n if (!parsed) {\n var _this$transmuxer;\n if (level.fragmentError === 0) {\n // Mark and track the odd empty segment as a gap to avoid reloading\n this.treatAsGap(frag, level);\n }\n if (((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {\n const error = new Error(`Found no media in fragment ${frag.sn} of ${this.playlistLabel()} ${frag.level} resetting transmuxer to fallback to playlist timing`);\n this.warn(error.message);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n error,\n frag,\n reason: `Found no media in msn ${frag.sn} of ${this.playlistLabel()} \"${level.url}\"`\n });\n if (!this.hls) {\n return;\n }\n this.resetTransmuxer();\n }\n // For this error fallthrough. Marking parsed will allow advancing to next fragment.\n }\n this.state = State.PARSED;\n this.log(`Parsed ${frag.type} sn: ${frag.sn}${part ? ' part: ' + part.index : ''} of ${this.fragInfo(frag, false, part)})`);\n this.hls.trigger(Events.FRAG_PARSED, {\n frag,\n part\n });\n }\n playlistLabel() {\n return this.playlistType === PlaylistLevelType.MAIN ? 'level' : 'track';\n }\n fragInfo(frag, pts = true, part) {\n var _ref, _ref2;\n return `${this.playlistLabel()} ${frag.level} (${part ? 'part' : 'frag'}:[${((_ref = pts && !part ? frag.startPTS : (part || frag).start) != null ? _ref : NaN).toFixed(3)}-${((_ref2 = pts && !part ? frag.endPTS : (part || frag).end) != null ? _ref2 : NaN).toFixed(3)}]${part && frag.type === 'main' ? 'INDEPENDENT=' + (part.independent ? 'YES' : 'NO') : ''}`;\n }\n treatAsGap(frag, level) {\n if (level) {\n level.fragmentError++;\n }\n frag.gap = true;\n this.fragmentTracker.removeFragment(frag);\n this.fragmentTracker.fragBuffered(frag, true);\n }\n resetTransmuxer() {\n var _this$transmuxer2;\n (_this$transmuxer2 = this.transmuxer) == null ? void 0 : _this$transmuxer2.reset();\n }\n recoverWorkerError(data) {\n if (data.event === 'demuxerWorker') {\n this.fragmentTracker.removeAllFragments();\n if (this.transmuxer) {\n this.transmuxer.destroy();\n this.transmuxer = null;\n }\n this.resetStartWhenNotLoaded(this.levelLastLoaded);\n this.resetLoadingState();\n }\n }\n set state(nextState) {\n const previousState = this._state;\n if (previousState !== nextState) {\n this._state = nextState;\n this.log(`${previousState}->${nextState}`);\n }\n }\n get state() {\n return this._state;\n }\n}\nfunction interstitialsEnabled(config) {\n return !!config.interstitialsController && config.enableInterstitialPlayback !== false;\n}\n\nclass ChunkCache {\n constructor() {\n this.chunks = [];\n this.dataLength = 0;\n }\n push(chunk) {\n this.chunks.push(chunk);\n this.dataLength += chunk.length;\n }\n flush() {\n const {\n chunks,\n dataLength\n } = this;\n let result;\n if (!chunks.length) {\n return new Uint8Array(0);\n } else if (chunks.length === 1) {\n result = chunks[0];\n } else {\n result = concatUint8Arrays(chunks, dataLength);\n }\n this.reset();\n return result;\n }\n reset() {\n this.chunks.length = 0;\n this.dataLength = 0;\n }\n}\nfunction concatUint8Arrays(chunks, dataLength) {\n const result = new Uint8Array(dataLength);\n let offset = 0;\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n}\n\nvar eventemitter3 = {exports: {}};\n\nvar hasRequiredEventemitter3;\n\nfunction requireEventemitter3 () {\n\tif (hasRequiredEventemitter3) return eventemitter3.exports;\n\thasRequiredEventemitter3 = 1;\n\t(function (module) {\n\n\t\tvar has = Object.prototype.hasOwnProperty\n\t\t , prefix = '~';\n\n\t\t/**\n\t\t * Constructor to create a storage for our `EE` objects.\n\t\t * An `Events` instance is a plain object whose properties are event names.\n\t\t *\n\t\t * @constructor\n\t\t * @private\n\t\t */\n\t\tfunction Events() {}\n\n\t\t//\n\t\t// We try to not inherit from `Object.prototype`. In some engines creating an\n\t\t// instance in this way is faster than calling `Object.create(null)` directly.\n\t\t// If `Object.create(null)` is not supported we prefix the event names with a\n\t\t// character to make sure that the built-in object properties are not\n\t\t// overridden or used as an attack vector.\n\t\t//\n\t\tif (Object.create) {\n\t\t Events.prototype = Object.create(null);\n\n\t\t //\n\t\t // This hack is needed because the `__proto__` property is still inherited in\n\t\t // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n\t\t //\n\t\t if (!new Events().__proto__) prefix = false;\n\t\t}\n\n\t\t/**\n\t\t * Representation of a single event listener.\n\t\t *\n\t\t * @param {Function} fn The listener function.\n\t\t * @param {*} context The context to invoke the listener with.\n\t\t * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n\t\t * @constructor\n\t\t * @private\n\t\t */\n\t\tfunction EE(fn, context, once) {\n\t\t this.fn = fn;\n\t\t this.context = context;\n\t\t this.once = once || false;\n\t\t}\n\n\t\t/**\n\t\t * Add a listener for a given event.\n\t\t *\n\t\t * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n\t\t * @param {(String|Symbol)} event The event name.\n\t\t * @param {Function} fn The listener function.\n\t\t * @param {*} context The context to invoke the listener with.\n\t\t * @param {Boolean} once Specify if the listener is a one-time listener.\n\t\t * @returns {EventEmitter}\n\t\t * @private\n\t\t */\n\t\tfunction addListener(emitter, event, fn, context, once) {\n\t\t if (typeof fn !== 'function') {\n\t\t throw new TypeError('The listener must be a function');\n\t\t }\n\n\t\t var listener = new EE(fn, context || emitter, once)\n\t\t , evt = prefix ? prefix + event : event;\n\n\t\t if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n\t\t else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n\t\t else emitter._events[evt] = [emitter._events[evt], listener];\n\n\t\t return emitter;\n\t\t}\n\n\t\t/**\n\t\t * Clear event by name.\n\t\t *\n\t\t * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n\t\t * @param {(String|Symbol)} evt The Event name.\n\t\t * @private\n\t\t */\n\t\tfunction clearEvent(emitter, evt) {\n\t\t if (--emitter._eventsCount === 0) emitter._events = new Events();\n\t\t else delete emitter._events[evt];\n\t\t}\n\n\t\t/**\n\t\t * Minimal `EventEmitter` interface that is molded against the Node.js\n\t\t * `EventEmitter` interface.\n\t\t *\n\t\t * @constructor\n\t\t * @public\n\t\t */\n\t\tfunction EventEmitter() {\n\t\t this._events = new Events();\n\t\t this._eventsCount = 0;\n\t\t}\n\n\t\t/**\n\t\t * Return an array listing the events for which the emitter has registered\n\t\t * listeners.\n\t\t *\n\t\t * @returns {Array}\n\t\t * @public\n\t\t */\n\t\tEventEmitter.prototype.eventNames = function eventNames() {\n\t\t var names = []\n\t\t , events\n\t\t , name;\n\n\t\t if (this._eventsCount === 0) return names;\n\n\t\t for (name in (events = this._events)) {\n\t\t if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n\t\t }\n\n\t\t if (Object.getOwnPropertySymbols) {\n\t\t return names.concat(Object.getOwnPropertySymbols(events));\n\t\t }\n\n\t\t return names;\n\t\t};\n\n\t\t/**\n\t\t * Return the listeners registered for a given event.\n\t\t *\n\t\t * @param {(String|Symbol)} event The event name.\n\t\t * @returns {Array} The registered listeners.\n\t\t * @public\n\t\t */\n\t\tEventEmitter.prototype.listeners = function listeners(event) {\n\t\t var evt = prefix ? prefix + event : event\n\t\t , handlers = this._events[evt];\n\n\t\t if (!handlers) return [];\n\t\t if (handlers.fn) return [handlers.fn];\n\n\t\t for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n\t\t ee[i] = handlers[i].fn;\n\t\t }\n\n\t\t return ee;\n\t\t};\n\n\t\t/**\n\t\t * Return the number of listeners listening to a given event.\n\t\t *\n\t\t * @param {(String|Symbol)} event The event name.\n\t\t * @returns {Number} The number of listeners.\n\t\t * @public\n\t\t */\n\t\tEventEmitter.prototype.listenerCount = function listenerCount(event) {\n\t\t var evt = prefix ? prefix + event : event\n\t\t , listeners = this._events[evt];\n\n\t\t if (!listeners) return 0;\n\t\t if (listeners.fn) return 1;\n\t\t return listeners.length;\n\t\t};\n\n\t\t/**\n\t\t * Calls each of the listeners registered for a given event.\n\t\t *\n\t\t * @param {(String|Symbol)} event The event name.\n\t\t * @returns {Boolean} `true` if the event had listeners, else `false`.\n\t\t * @public\n\t\t */\n\t\tEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n\t\t var evt = prefix ? prefix + event : event;\n\n\t\t if (!this._events[evt]) return false;\n\n\t\t var listeners = this._events[evt]\n\t\t , len = arguments.length\n\t\t , args\n\t\t , i;\n\n\t\t if (listeners.fn) {\n\t\t if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n\t\t switch (len) {\n\t\t case 1: return listeners.fn.call(listeners.context), true;\n\t\t case 2: return listeners.fn.call(listeners.context, a1), true;\n\t\t case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n\t\t case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n\t\t case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n\t\t case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n\t\t }\n\n\t\t for (i = 1, args = new Array(len -1); i < len; i++) {\n\t\t args[i - 1] = arguments[i];\n\t\t }\n\n\t\t listeners.fn.apply(listeners.context, args);\n\t\t } else {\n\t\t var length = listeners.length\n\t\t , j;\n\n\t\t for (i = 0; i < length; i++) {\n\t\t if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n\t\t switch (len) {\n\t\t case 1: listeners[i].fn.call(listeners[i].context); break;\n\t\t case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n\t\t case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n\t\t case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n\t\t default:\n\t\t if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n\t\t args[j - 1] = arguments[j];\n\t\t }\n\n\t\t listeners[i].fn.apply(listeners[i].context, args);\n\t\t }\n\t\t }\n\t\t }\n\n\t\t return true;\n\t\t};\n\n\t\t/**\n\t\t * Add a listener for a given event.\n\t\t *\n\t\t * @param {(String|Symbol)} event The event name.\n\t\t * @param {Function} fn The listener function.\n\t\t * @param {*} [context=this] The context to invoke the listener with.\n\t\t * @returns {EventEmitter} `this`.\n\t\t * @public\n\t\t */\n\t\tEventEmitter.prototype.on = function on(event, fn, context) {\n\t\t return addListener(this, event, fn, context, false);\n\t\t};\n\n\t\t/**\n\t\t * Add a one-time listener for a given event.\n\t\t *\n\t\t * @param {(String|Symbol)} event The event name.\n\t\t * @param {Function} fn The listener function.\n\t\t * @param {*} [context=this] The context to invoke the listener with.\n\t\t * @returns {EventEmitter} `this`.\n\t\t * @public\n\t\t */\n\t\tEventEmitter.prototype.once = function once(event, fn, context) {\n\t\t return addListener(this, event, fn, context, true);\n\t\t};\n\n\t\t/**\n\t\t * Remove the listeners of a given event.\n\t\t *\n\t\t * @param {(String|Symbol)} event The event name.\n\t\t * @param {Function} fn Only remove the listeners that match this function.\n\t\t * @param {*} context Only remove the listeners that have this context.\n\t\t * @param {Boolean} once Only remove one-time listeners.\n\t\t * @returns {EventEmitter} `this`.\n\t\t * @public\n\t\t */\n\t\tEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n\t\t var evt = prefix ? prefix + event : event;\n\n\t\t if (!this._events[evt]) return this;\n\t\t if (!fn) {\n\t\t clearEvent(this, evt);\n\t\t return this;\n\t\t }\n\n\t\t var listeners = this._events[evt];\n\n\t\t if (listeners.fn) {\n\t\t if (\n\t\t listeners.fn === fn &&\n\t\t (!once || listeners.once) &&\n\t\t (!context || listeners.context === context)\n\t\t ) {\n\t\t clearEvent(this, evt);\n\t\t }\n\t\t } else {\n\t\t for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n\t\t if (\n\t\t listeners[i].fn !== fn ||\n\t\t (once && !listeners[i].once) ||\n\t\t (context && listeners[i].context !== context)\n\t\t ) {\n\t\t events.push(listeners[i]);\n\t\t }\n\t\t }\n\n\t\t //\n\t\t // Reset the array, or remove it completely if we have no more listeners.\n\t\t //\n\t\t if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n\t\t else clearEvent(this, evt);\n\t\t }\n\n\t\t return this;\n\t\t};\n\n\t\t/**\n\t\t * Remove all listeners, or those of the specified event.\n\t\t *\n\t\t * @param {(String|Symbol)} [event] The event name.\n\t\t * @returns {EventEmitter} `this`.\n\t\t * @public\n\t\t */\n\t\tEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n\t\t var evt;\n\n\t\t if (event) {\n\t\t evt = prefix ? prefix + event : event;\n\t\t if (this._events[evt]) clearEvent(this, evt);\n\t\t } else {\n\t\t this._events = new Events();\n\t\t this._eventsCount = 0;\n\t\t }\n\n\t\t return this;\n\t\t};\n\n\t\t//\n\t\t// Alias methods names because people roll like that.\n\t\t//\n\t\tEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\t\tEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n\t\t//\n\t\t// Expose the prefix.\n\t\t//\n\t\tEventEmitter.prefixed = prefix;\n\n\t\t//\n\t\t// Allow `EventEmitter` to be imported as module namespace.\n\t\t//\n\t\tEventEmitter.EventEmitter = EventEmitter;\n\n\t\t//\n\t\t// Expose the module.\n\t\t//\n\t\t{\n\t\t module.exports = EventEmitter;\n\t\t} \n\t} (eventemitter3));\n\treturn eventemitter3.exports;\n}\n\nvar eventemitter3Exports = requireEventemitter3();\nvar EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);\n\nconst version = \"1.6.2\";\n\n// ensure the worker ends up in the bundle\n// If the worker should not be included this gets aliased to empty.js\nconst workerStore = {};\nfunction hasUMDWorker() {\n return typeof __HLS_WORKER_BUNDLE__ === 'function';\n}\nfunction injectWorker() {\n const workerContext = workerStore[version];\n if (workerContext) {\n workerContext.clientCount++;\n return workerContext;\n }\n const blob = new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`], {\n type: 'text/javascript'\n });\n const objectURL = self.URL.createObjectURL(blob);\n const worker = new self.Worker(objectURL);\n const result = {\n worker,\n objectURL,\n clientCount: 1\n };\n workerStore[version] = result;\n return result;\n}\nfunction loadWorker(path) {\n const workerContext = workerStore[path];\n if (workerContext) {\n workerContext.clientCount++;\n return workerContext;\n }\n const scriptURL = new self.URL(path, self.location.href).href;\n const worker = new self.Worker(scriptURL);\n const result = {\n worker,\n scriptURL,\n clientCount: 1\n };\n workerStore[path] = result;\n return result;\n}\nfunction removeWorkerFromStore(path) {\n const workerContext = workerStore[path || version];\n if (workerContext) {\n const clientCount = workerContext.clientCount--;\n if (clientCount === 1) {\n const {\n worker,\n objectURL\n } = workerContext;\n delete workerStore[path || version];\n if (objectURL) {\n // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n self.URL.revokeObjectURL(objectURL);\n }\n worker.terminate();\n }\n }\n}\n\n/**\n * Returns true if an ID3 footer can be found at offset in data\n *\n * @param data - The data to search in\n * @param offset - The offset at which to start searching\n *\n * @returns `true` if an ID3 footer is found\n *\n * @internal\n *\n * @group ID3\n */\nfunction isId3Footer(data, offset) {\n /*\n * The footer is a copy of the header, but with a different identifier\n */\n if (offset + 10 <= data.length) {\n // look for '3DI' identifier\n if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {\n // check version is within range\n if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {\n // check size is within range\n if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Returns true if an ID3 header can be found at offset in data\n *\n * @param data - The data to search in\n * @param offset - The offset at which to start searching\n *\n * @returns `true` if an ID3 header is found\n *\n * @internal\n *\n * @group ID3\n */\nfunction isId3Header(data, offset) {\n /*\n * http://id3.org/id3v2.3.0\n * [0] = 'I'\n * [1] = 'D'\n * [2] = '3'\n * [3,4] = {Version}\n * [5] = {Flags}\n * [6-9] = {ID3 Size}\n *\n * An ID3v2 tag can be detected with the following pattern:\n * $49 44 33 yy yy xx zz zz zz zz\n * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80\n */\n if (offset + 10 <= data.length) {\n // look for 'ID3' identifier\n if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {\n // check version is within range\n if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {\n // check size is within range\n if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Read ID3 size\n *\n * @param data - The data to read from\n * @param offset - The offset at which to start reading\n *\n * @returns The size\n *\n * @internal\n *\n * @group ID3\n */\nfunction readId3Size(data, offset) {\n let size = 0;\n size = (data[offset] & 0x7f) << 21;\n size |= (data[offset + 1] & 0x7f) << 14;\n size |= (data[offset + 2] & 0x7f) << 7;\n size |= data[offset + 3] & 0x7f;\n return size;\n}\n\n/**\n * Returns any adjacent ID3 tags found in data starting at offset, as one block of data\n *\n * @param data - The data to search in\n * @param offset - The offset at which to start searching\n *\n * @returns The block of data containing any ID3 tags found\n * or `undefined` if no header is found at the starting offset\n *\n * @internal\n *\n * @group ID3\n */\nfunction getId3Data(data, offset) {\n const front = offset;\n let length = 0;\n while (isId3Header(data, offset)) {\n // ID3 header is 10 bytes\n length += 10;\n const size = readId3Size(data, offset + 6);\n length += size;\n if (isId3Footer(data, offset + 10)) {\n // ID3 footer is 10 bytes\n length += 10;\n }\n offset += length;\n }\n if (length > 0) {\n return data.subarray(front, front + length);\n }\n return undefined;\n}\n\nfunction getAudioConfig(observer, data, offset, manifestCodec) {\n const adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];\n const byte2 = data[offset + 2];\n const adtsSamplingIndex = byte2 >> 2 & 0xf;\n if (adtsSamplingIndex > 12) {\n const error = new Error(`invalid ADTS sampling index:${adtsSamplingIndex}`);\n observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: true,\n error,\n reason: error.message\n });\n return;\n }\n // MPEG-4 Audio Object Type (profile_ObjectType+1)\n const adtsObjectType = (byte2 >> 6 & 0x3) + 1;\n const channelCount = data[offset + 3] >> 6 & 0x3 | (byte2 & 1) << 2;\n const codec = 'mp4a.40.' + adtsObjectType;\n /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config\n ISO/IEC 14496-3 - Table 1.13 — Syntax of AudioSpecificConfig()\n Audio Profile / Audio Object Type\n 0: Null\n 1: AAC Main\n 2: AAC LC (Low Complexity)\n 3: AAC SSR (Scalable Sample Rate)\n 4: AAC LTP (Long Term Prediction)\n 5: SBR (Spectral Band Replication)\n 6: AAC Scalable\n sampling freq\n 0: 96000 Hz\n 1: 88200 Hz\n 2: 64000 Hz\n 3: 48000 Hz\n 4: 44100 Hz\n 5: 32000 Hz\n 6: 24000 Hz\n 7: 22050 Hz\n 8: 16000 Hz\n 9: 12000 Hz\n 10: 11025 Hz\n 11: 8000 Hz\n 12: 7350 Hz\n 13: Reserved\n 14: Reserved\n 15: frequency is written explictly\n Channel Configurations\n These are the channel configurations:\n 0: Defined in AOT Specifc Config\n 1: 1 channel: front-center\n 2: 2 channels: front-left, front-right\n */\n // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1\n const samplerate = adtsSamplingRates[adtsSamplingIndex];\n let aacSampleIndex = adtsSamplingIndex;\n if (adtsObjectType === 5 || adtsObjectType === 29) {\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table above, equivalent to substract 3)\n aacSampleIndex -= 3;\n }\n const config = [adtsObjectType << 3 | (aacSampleIndex & 0x0e) >> 1, (aacSampleIndex & 0x01) << 7 | channelCount << 3];\n logger.log(`manifest codec:${manifestCodec}, parsed codec:${codec}, channels:${channelCount}, rate:${samplerate} (ADTS object type:${adtsObjectType} sampling index:${adtsSamplingIndex})`);\n return {\n config,\n samplerate,\n channelCount,\n codec,\n parsedCodec: codec,\n manifestCodec\n };\n}\nfunction isHeaderPattern$1(data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n}\nfunction getHeaderLength(data, offset) {\n return data[offset + 1] & 0x01 ? 7 : 9;\n}\nfunction getFullFrameLength(data, offset) {\n return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;\n}\nfunction canGetFrameLength(data, offset) {\n return offset + 5 < data.length;\n}\nfunction isHeader$1(data, offset) {\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n return offset + 1 < data.length && isHeaderPattern$1(data, offset);\n}\nfunction canParse$1(data, offset) {\n return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;\n}\nfunction probe$1(data, offset) {\n // same as isHeader but we also check that ADTS frame follows last ADTS frame\n // or end of data is reached\n if (isHeader$1(data, offset)) {\n // ADTS header Length\n const headerLength = getHeaderLength(data, offset);\n if (offset + headerLength >= data.length) {\n return false;\n }\n // ADTS frame Length\n const frameLength = getFullFrameLength(data, offset);\n if (frameLength <= headerLength) {\n return false;\n }\n const newOffset = offset + frameLength;\n return newOffset === data.length || isHeader$1(data, newOffset);\n }\n return false;\n}\nfunction initTrackConfig(track, observer, data, offset, audioCodec) {\n if (!track.samplerate) {\n const config = getAudioConfig(observer, data, offset, audioCodec);\n if (!config) {\n return;\n }\n _extends(track, config);\n }\n}\nfunction getFrameDuration(samplerate) {\n return 1024 * 90000 / samplerate;\n}\nfunction parseFrameHeader(data, offset) {\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n const headerLength = getHeaderLength(data, offset);\n if (offset + headerLength <= data.length) {\n // retrieve frame size\n const frameLength = getFullFrameLength(data, offset) - headerLength;\n if (frameLength > 0) {\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);\n return {\n headerLength,\n frameLength\n };\n }\n }\n}\nfunction appendFrame$2(track, data, offset, pts, frameIndex) {\n const frameDuration = getFrameDuration(track.samplerate);\n const stamp = pts + frameIndex * frameDuration;\n const header = parseFrameHeader(data, offset);\n let unit;\n if (header) {\n const {\n frameLength,\n headerLength\n } = header;\n const _length = headerLength + frameLength;\n const missing = Math.max(0, offset + _length - data.length);\n // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);\n if (missing) {\n unit = new Uint8Array(_length - headerLength);\n unit.set(data.subarray(offset + headerLength, data.length), 0);\n } else {\n unit = data.subarray(offset + headerLength, offset + _length);\n }\n const _sample = {\n unit,\n pts: stamp\n };\n if (!missing) {\n track.samples.push(_sample);\n }\n return {\n sample: _sample,\n length: _length,\n missing\n };\n }\n // overflow incomplete header\n const length = data.length - offset;\n unit = new Uint8Array(length);\n unit.set(data.subarray(offset, data.length), 0);\n const sample = {\n unit,\n pts: stamp\n };\n return {\n sample,\n length,\n missing: -1\n };\n}\n\n/**\n * Checks if the given data contains an ID3 tag.\n *\n * @param data - The data to check\n * @param offset - The offset at which to start checking\n *\n * @returns `true` if an ID3 tag is found\n *\n * @group ID3\n *\n * @beta\n */\nfunction canParseId3(data, offset) {\n return isId3Header(data, offset) && readId3Size(data, offset + 6) + 10 <= data.length - offset;\n}\n\n/**\n * Decode an ID3 PRIV frame.\n *\n * @param frame - the ID3 PRIV frame\n *\n * @returns The decoded ID3 PRIV frame\n *\n * @internal\n *\n * @group ID3\n */\nfunction decodeId3PrivFrame(frame) {\n /*\n Format: <text string>\\0<binary data>\n */\n if (frame.size < 2) {\n return undefined;\n }\n const owner = utf8ArrayToStr(frame.data, true);\n const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));\n return {\n key: frame.type,\n info: owner,\n data: privateData.buffer\n };\n}\n\n/**\n * Decodes an ID3 text frame\n *\n * @param frame - the ID3 text frame\n *\n * @returns The decoded ID3 text frame\n *\n * @internal\n *\n * @group ID3\n */\nfunction decodeId3TextFrame(frame) {\n if (frame.size < 2) {\n return undefined;\n }\n if (frame.type === 'TXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{Value}\n */\n let index = 1;\n const description = utf8ArrayToStr(frame.data.subarray(index), true);\n index += description.length + 1;\n const value = utf8ArrayToStr(frame.data.subarray(index));\n return {\n key: frame.type,\n info: description,\n data: value\n };\n }\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Value}\n */\n const text = utf8ArrayToStr(frame.data.subarray(1));\n return {\n key: frame.type,\n info: '',\n data: text\n };\n}\n\n/**\n * Decode a URL frame\n *\n * @param frame - the ID3 URL frame\n *\n * @returns The decoded ID3 URL frame\n *\n * @internal\n *\n * @group ID3\n */\nfunction decodeId3UrlFrame(frame) {\n if (frame.type === 'WXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{URL}\n */\n if (frame.size < 2) {\n return undefined;\n }\n let index = 1;\n const description = utf8ArrayToStr(frame.data.subarray(index), true);\n index += description.length + 1;\n const value = utf8ArrayToStr(frame.data.subarray(index));\n return {\n key: frame.type,\n info: description,\n data: value\n };\n }\n /*\n Format:\n [0-?] = {URL}\n */\n const url = utf8ArrayToStr(frame.data);\n return {\n key: frame.type,\n info: '',\n data: url\n };\n}\n\n/**\n * Encodes binary data to base64\n *\n * @param binary - The binary data to encode\n * @returns The base64 encoded string\n *\n * @group Utils\n *\n * @beta\n */\nfunction base64encode(binary) {\n return btoa(String.fromCharCode(...binary));\n}\n\n/**\n * This implements the rounding procedure described in step 2 of the \"Serializing a Decimal\" specification.\n * This rounding style is known as \"even rounding\", \"banker's rounding\", or \"commercial rounding\".\n *\n * @param value - The value to round\n * @param precision - The number of decimal places to round to\n * @returns The rounded value\n *\n * @group Utils\n *\n * @beta\n */\nfunction roundToEven(value, precision) {\n if (value < 0) {\n return -roundToEven(-value, precision);\n }\n const decimalShift = Math.pow(10, precision);\n const isEquidistant = Math.abs(value * decimalShift % 1 - 0.5) < Number.EPSILON;\n if (isEquidistant) {\n // If the tail of the decimal place is 'equidistant' we round to the nearest even value\n const flooredValue = Math.floor(value * decimalShift);\n return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;\n } else {\n // Otherwise, proceed as normal\n return Math.round(value * decimalShift) / decimalShift;\n }\n}\n\n/**\n * Constructs a relative path from a URL.\n *\n * @param url - The destination URL\n * @param base - The base URL\n * @returns The relative path\n *\n * @group Utils\n *\n * @beta\n */\nfunction urlToRelativePath(url, base) {\n const to = new URL(url);\n const from = new URL(base);\n if (to.origin !== from.origin) {\n return url;\n }\n const toPath = to.pathname.split('/').slice(1);\n const fromPath = from.pathname.split('/').slice(1, -1);\n // remove common parents\n while (toPath[0] === fromPath[0]) {\n toPath.shift();\n fromPath.shift();\n }\n // add back paths\n while (fromPath.length) {\n fromPath.shift();\n toPath.unshift('..');\n }\n return toPath.join('/');\n}\n\n/**\n * Generate a random v4 UUID\n *\n * @returns A random v4 UUID\n *\n * @group Utils\n *\n * @beta\n */\nfunction uuid() {\n try {\n return crypto.randomUUID();\n } catch (error) {\n try {\n const url = URL.createObjectURL(new Blob());\n const uuid = url.toString();\n URL.revokeObjectURL(url);\n return uuid.slice(uuid.lastIndexOf('/') + 1);\n } catch (error) {\n let dt = new Date().getTime();\n const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\n const r = (dt + Math.random() * 16) % 16 | 0;\n dt = Math.floor(dt / 16);\n return (c == 'x' ? r : r & 0x3 | 0x8).toString(16);\n });\n return uuid;\n }\n }\n}\n\nfunction toArrayBuffer(view) {\n if (view instanceof ArrayBuffer) {\n return view;\n } else {\n if (view.byteOffset == 0 && view.byteLength == view.buffer.byteLength) {\n // This is a TypedArray over the whole buffer.\n return view.buffer;\n }\n // This is a 'view' on the buffer. Create a new buffer that only contains\n // the data. Note that since this isn't an ArrayBuffer, the 'new' call\n // will allocate a new buffer to hold the copy.\n return new Uint8Array(view).buffer;\n }\n}\n\nfunction toUint8(data, offset = 0, length = Infinity) {\n return view(data, offset, length, Uint8Array);\n}\nfunction view(data, offset, length, Type) {\n const buffer = unsafeGetArrayBuffer(data);\n let bytesPerElement = 1;\n if ('BYTES_PER_ELEMENT' in Type) {\n bytesPerElement = Type.BYTES_PER_ELEMENT;\n }\n // Absolute end of the |data| view within |buffer|.\n const dataOffset = isArrayBufferView(data) ? data.byteOffset : 0;\n const dataEnd = (dataOffset + data.byteLength) / bytesPerElement;\n // Absolute start of the result within |buffer|.\n const rawStart = (dataOffset + offset) / bytesPerElement;\n const start = Math.floor(Math.max(0, Math.min(rawStart, dataEnd)));\n // Absolute end of the result within |buffer|.\n const end = Math.floor(Math.min(start + Math.max(length, 0), dataEnd));\n return new Type(buffer, start, end - start);\n}\nfunction unsafeGetArrayBuffer(view) {\n if (view instanceof ArrayBuffer) {\n return view;\n } else {\n return view.buffer;\n }\n}\nfunction isArrayBufferView(obj) {\n return obj && obj.buffer instanceof ArrayBuffer && obj.byteLength !== undefined && obj.byteOffset !== undefined;\n}\n\nfunction decodeId3ImageFrame(frame) {\n const metadataFrame = {\n key: frame.type,\n description: '',\n data: '',\n mimeType: null,\n pictureType: null\n };\n const utf8Encoding = 0x03;\n if (frame.size < 2) {\n return undefined;\n }\n if (frame.data[0] !== utf8Encoding) {\n console.log('Ignore frame with unrecognized character ' + 'encoding');\n return undefined;\n }\n const mimeTypeEndIndex = frame.data.subarray(1).indexOf(0);\n if (mimeTypeEndIndex === -1) {\n return undefined;\n }\n const mimeType = utf8ArrayToStr(toUint8(frame.data, 1, mimeTypeEndIndex));\n const pictureType = frame.data[2 + mimeTypeEndIndex];\n const descriptionEndIndex = frame.data.subarray(3 + mimeTypeEndIndex).indexOf(0);\n if (descriptionEndIndex === -1) {\n return undefined;\n }\n const description = utf8ArrayToStr(toUint8(frame.data, 3 + mimeTypeEndIndex, descriptionEndIndex));\n let data;\n if (mimeType === '-->') {\n data = utf8ArrayToStr(toUint8(frame.data, 4 + mimeTypeEndIndex + descriptionEndIndex));\n } else {\n data = toArrayBuffer(frame.data.subarray(4 + mimeTypeEndIndex + descriptionEndIndex));\n }\n metadataFrame.mimeType = mimeType;\n metadataFrame.pictureType = pictureType;\n metadataFrame.description = description;\n metadataFrame.data = data;\n return metadataFrame;\n}\n\n/**\n * Decode an ID3 frame.\n *\n * @param frame - the ID3 frame\n *\n * @returns The decoded ID3 frame\n *\n * @internal\n *\n * @group ID3\n */\nfunction decodeId3Frame(frame) {\n if (frame.type === 'PRIV') {\n return decodeId3PrivFrame(frame);\n } else if (frame.type[0] === 'W') {\n return decodeId3UrlFrame(frame);\n } else if (frame.type === 'APIC') {\n return decodeId3ImageFrame(frame);\n }\n return decodeId3TextFrame(frame);\n}\n\n/**\n * Returns the data of an ID3 frame.\n *\n * @param data - The data to read from\n *\n * @returns The data of the ID3 frame\n *\n * @internal\n *\n * @group ID3\n */\nfunction getId3FrameData(data) {\n /*\n Frame ID $xx xx xx xx (four characters)\n Size $xx xx xx xx\n Flags $xx xx\n */\n const type = String.fromCharCode(data[0], data[1], data[2], data[3]);\n const size = readId3Size(data, 4);\n // skip frame id, size, and flags\n const offset = 10;\n return {\n type,\n size,\n data: data.subarray(offset, offset + size)\n };\n}\n\nconst HEADER_FOOTER_SIZE = 10;\nconst FRAME_SIZE = 10;\n/**\n * Returns an array of ID3 frames found in all the ID3 tags in the id3Data\n *\n * @param id3Data - The ID3 data containing one or more ID3 tags\n *\n * @returns Array of ID3 frame objects\n *\n * @group ID3\n *\n * @beta\n */\nfunction getId3Frames(id3Data) {\n let offset = 0;\n const frames = [];\n while (isId3Header(id3Data, offset)) {\n const size = readId3Size(id3Data, offset + 6);\n if (id3Data[offset + 5] >> 6 & 1) {\n // skip extended header\n offset += HEADER_FOOTER_SIZE;\n }\n // skip past ID3 header\n offset += HEADER_FOOTER_SIZE;\n const end = offset + size;\n // loop through frames in the ID3 tag\n while (offset + FRAME_SIZE < end) {\n const frameData = getId3FrameData(id3Data.subarray(offset));\n const frame = decodeId3Frame(frameData);\n if (frame) {\n frames.push(frame);\n }\n // skip frame header and frame data\n offset += frameData.size + HEADER_FOOTER_SIZE;\n }\n if (isId3Footer(id3Data, offset)) {\n offset += HEADER_FOOTER_SIZE;\n }\n }\n return frames;\n}\n\n/**\n * Returns true if the ID3 frame is an Elementary Stream timestamp frame\n *\n * @param frame - the ID3 frame\n *\n * @returns `true` if the ID3 frame is an Elementary Stream timestamp frame\n *\n * @internal\n *\n * @group ID3\n */\nfunction isId3TimestampFrame(frame) {\n return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';\n}\n\n/**\n * Read a 33 bit timestamp from an ID3 frame.\n *\n * @param timeStampFrame - the ID3 frame\n *\n * @returns The timestamp\n *\n * @internal\n *\n * @group ID3\n */\nfunction readId3Timestamp(timeStampFrame) {\n if (timeStampFrame.data.byteLength === 8) {\n const data = new Uint8Array(timeStampFrame.data);\n // timestamp is 33 bit expressed as a big-endian eight-octet number,\n // with the upper 31 bits set to zero.\n const pts33Bit = data[3] & 0x1;\n let timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];\n timestamp /= 45;\n if (pts33Bit) {\n timestamp += 47721858.84;\n } // 2^32 / 90\n return Math.round(timestamp);\n }\n return undefined;\n}\n\n/**\n * Searches for the Elementary Stream timestamp found in the ID3 data chunk\n *\n * @param data - Block of data containing one or more ID3 tags\n *\n * @returns The timestamp\n *\n * @group ID3\n *\n * @beta\n */\nfunction getId3Timestamp(data) {\n const frames = getId3Frames(data);\n for (let i = 0; i < frames.length; i++) {\n const frame = frames[i];\n if (isId3TimestampFrame(frame)) {\n return readId3Timestamp(frame);\n }\n }\n return undefined;\n}\n\nlet MetadataSchema = /*#__PURE__*/function (MetadataSchema) {\n MetadataSchema[\"audioId3\"] = \"org.id3\";\n MetadataSchema[\"dateRange\"] = \"com.apple.quicktime.HLS\";\n MetadataSchema[\"emsg\"] = \"https://aomedia.org/emsg/ID3\";\n MetadataSchema[\"misbklv\"] = \"urn:misb:KLV:bin:1910.1\";\n return MetadataSchema;\n}({});\n\nfunction dummyTrack(type = '', inputTimeScale = 90000) {\n return {\n type,\n id: -1,\n pid: -1,\n inputTimeScale,\n sequenceNumber: -1,\n samples: [],\n dropped: 0\n };\n}\n\nclass BaseAudioDemuxer {\n constructor() {\n this._audioTrack = void 0;\n this._id3Track = void 0;\n this.frameIndex = 0;\n this.cachedData = null;\n this.basePTS = null;\n this.initPTS = null;\n this.lastPTS = null;\n }\n resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {\n this._id3Track = {\n type: 'id3',\n id: 3,\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n dropped: 0\n };\n }\n resetTimeStamp(deaultTimestamp) {\n this.initPTS = deaultTimestamp;\n this.resetContiguity();\n }\n resetContiguity() {\n this.basePTS = null;\n this.lastPTS = null;\n this.frameIndex = 0;\n }\n canParse(data, offset) {\n return false;\n }\n appendFrame(track, data, offset) {}\n\n // feed incoming data to the front of the parsing pipeline\n demux(data, timeOffset) {\n if (this.cachedData) {\n data = appendUint8Array(this.cachedData, data);\n this.cachedData = null;\n }\n let id3Data = getId3Data(data, 0);\n let offset = id3Data ? id3Data.length : 0;\n let lastDataIndex;\n const track = this._audioTrack;\n const id3Track = this._id3Track;\n const timestamp = id3Data ? getId3Timestamp(id3Data) : undefined;\n const length = data.length;\n if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {\n this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);\n this.lastPTS = this.basePTS;\n }\n if (this.lastPTS === null) {\n this.lastPTS = this.basePTS;\n }\n\n // more expressive than alternative: id3Data?.length\n if (id3Data && id3Data.length > 0) {\n id3Track.samples.push({\n pts: this.lastPTS,\n dts: this.lastPTS,\n data: id3Data,\n type: MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY\n });\n }\n while (offset < length) {\n if (this.canParse(data, offset)) {\n const frame = this.appendFrame(track, data, offset);\n if (frame) {\n this.frameIndex++;\n this.lastPTS = frame.sample.pts;\n offset += frame.length;\n lastDataIndex = offset;\n } else {\n offset = length;\n }\n } else if (canParseId3(data, offset)) {\n // after a canParse, a call to getId3Data *should* always returns some data\n id3Data = getId3Data(data, offset);\n id3Track.samples.push({\n pts: this.lastPTS,\n dts: this.lastPTS,\n data: id3Data,\n type: MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY\n });\n offset += id3Data.length;\n lastDataIndex = offset;\n } else {\n offset++;\n }\n if (offset === length && lastDataIndex !== length) {\n const partialData = data.slice(lastDataIndex);\n if (this.cachedData) {\n this.cachedData = appendUint8Array(this.cachedData, partialData);\n } else {\n this.cachedData = partialData;\n }\n }\n }\n return {\n audioTrack: track,\n videoTrack: dummyTrack(),\n id3Track,\n textTrack: dummyTrack()\n };\n }\n demuxSampleAes(data, keyData, timeOffset) {\n return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`));\n }\n flush(timeOffset) {\n // Parse cache in case of remaining frames.\n const cachedData = this.cachedData;\n if (cachedData) {\n this.cachedData = null;\n this.demux(cachedData, 0);\n }\n return {\n audioTrack: this._audioTrack,\n videoTrack: dummyTrack(),\n id3Track: this._id3Track,\n textTrack: dummyTrack()\n };\n }\n destroy() {\n this.cachedData = null;\n // @ts-ignore\n this._audioTrack = this._id3Track = undefined;\n }\n}\n\n/**\n * Initialize PTS\n * <p>\n * use timestamp unless it is undefined, NaN or Infinity\n * </p>\n */\nconst initPTSFn = (timestamp, timeOffset, initPTS) => {\n if (isFiniteNumber(timestamp)) {\n return timestamp * 90;\n }\n const init90kHz = initPTS ? initPTS.baseTime * 90000 / initPTS.timescale : 0;\n return timeOffset * 90000 + init90kHz;\n};\n\n/**\n * MPEG parser helper\n */\n\nlet chromeVersion$1 = null;\nconst BitratesMap = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];\nconst SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];\nconst SamplesCoefficients = [\n// MPEG 2.5\n[0,\n// Reserved\n72,\n// Layer3\n144,\n// Layer2\n12 // Layer1\n],\n// Reserved\n[0,\n// Reserved\n0,\n// Layer3\n0,\n// Layer2\n0 // Layer1\n],\n// MPEG 2\n[0,\n// Reserved\n72,\n// Layer3\n144,\n// Layer2\n12 // Layer1\n],\n// MPEG 1\n[0,\n// Reserved\n144,\n// Layer3\n144,\n// Layer2\n12 // Layer1\n]];\nconst BytesInSlot = [0,\n// Reserved\n1,\n// Layer3\n1,\n// Layer2\n4 // Layer1\n];\nfunction appendFrame$1(track, data, offset, pts, frameIndex) {\n // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n if (offset + 24 > data.length) {\n return;\n }\n const header = parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n const frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;\n const stamp = pts + frameIndex * frameDuration;\n const sample = {\n unit: data.subarray(offset, offset + header.frameLength),\n pts: stamp,\n dts: stamp\n };\n track.config = [];\n track.channelCount = header.channelCount;\n track.samplerate = header.sampleRate;\n track.samples.push(sample);\n return {\n sample,\n length: header.frameLength,\n missing: 0\n };\n }\n}\nfunction parseHeader(data, offset) {\n const mpegVersion = data[offset + 1] >> 3 & 3;\n const mpegLayer = data[offset + 1] >> 1 & 3;\n const bitRateIndex = data[offset + 2] >> 4 & 15;\n const sampleRateIndex = data[offset + 2] >> 2 & 3;\n if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {\n const paddingBit = data[offset + 2] >> 1 & 1;\n const channelMode = data[offset + 3] >> 6;\n const columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;\n const bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;\n const columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;\n const sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];\n const channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];\n const bytesInSlot = BytesInSlot[mpegLayer];\n const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n const frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;\n if (chromeVersion$1 === null) {\n const userAgent = navigator.userAgent || '';\n const result = userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion$1 = result ? parseInt(result[1]) : 0;\n }\n const needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;\n if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {\n // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)\n data[offset + 3] = data[offset + 3] | 0x80;\n }\n return {\n sampleRate,\n channelCount,\n frameLength,\n samplesPerFrame\n };\n }\n}\nfunction isHeaderPattern(data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;\n}\nfunction isHeader(data, offset) {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n return offset + 1 < data.length && isHeaderPattern(data, offset);\n}\nfunction canParse(data, offset) {\n const headerSize = 4;\n return isHeaderPattern(data, offset) && headerSize <= data.length - offset;\n}\nfunction probe(data, offset) {\n // same as isHeader but we also check that MPEG frame follows last MPEG frame\n // or end of data is reached\n if (offset + 1 < data.length && isHeaderPattern(data, offset)) {\n // MPEG header Length\n const headerLength = 4;\n // MPEG frame Length\n const header = parseHeader(data, offset);\n let frameLength = headerLength;\n if (header != null && header.frameLength) {\n frameLength = header.frameLength;\n }\n const newOffset = offset + frameLength;\n return newOffset === data.length || isHeader(data, newOffset);\n }\n return false;\n}\n\n/**\n * AAC demuxer\n */\nclass AACDemuxer extends BaseAudioDemuxer {\n constructor(observer, config) {\n super();\n this.observer = void 0;\n this.config = void 0;\n this.observer = observer;\n this.config = config;\n }\n resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {\n super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);\n this._audioTrack = {\n container: 'audio/adts',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'aac',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0\n };\n }\n\n // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS\n static probe(data, logger) {\n if (!data) {\n return false;\n }\n\n // Check for the ADTS sync word\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n const id3Data = getId3Data(data, 0);\n let offset = (id3Data == null ? void 0 : id3Data.length) || 0;\n if (probe(data, offset)) {\n return false;\n }\n for (let length = data.length; offset < length; offset++) {\n if (probe$1(data, offset)) {\n logger.log('ADTS sync word found !');\n return true;\n }\n }\n return false;\n }\n canParse(data, offset) {\n return canParse$1(data, offset);\n }\n appendFrame(track, data, offset) {\n initTrackConfig(track, this.observer, data, offset, track.manifestCodec);\n const frame = appendFrame$2(track, data, offset, this.basePTS, this.frameIndex);\n if (frame && frame.missing === 0) {\n return frame;\n }\n }\n}\n\nconst getAudioBSID = (data, offset) => {\n // check the bsid to confirm ac-3 | ec-3\n let bsid = 0;\n let numBits = 5;\n offset += numBits;\n const temp = new Uint32Array(1); // unsigned 32 bit for temporary storage\n const mask = new Uint32Array(1); // unsigned 32 bit mask value\n const byte = new Uint8Array(1); // unsigned 8 bit for temporary storage\n while (numBits > 0) {\n byte[0] = data[offset];\n // read remaining bits, upto 8 bits at a time\n const bits = Math.min(numBits, 8);\n const shift = 8 - bits;\n mask[0] = 0xff000000 >>> 24 + shift << shift;\n temp[0] = (byte[0] & mask[0]) >> shift;\n bsid = !bsid ? temp[0] : bsid << bits | temp[0];\n offset += 1;\n numBits -= bits;\n }\n return bsid;\n};\n\nclass AC3Demuxer extends BaseAudioDemuxer {\n constructor(observer) {\n super();\n this.observer = void 0;\n this.observer = observer;\n }\n resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {\n super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);\n this._audioTrack = {\n container: 'audio/ac-3',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'ac3',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0\n };\n }\n canParse(data, offset) {\n return offset + 64 < data.length;\n }\n appendFrame(track, data, offset) {\n const frameLength = appendFrame(track, data, offset, this.basePTS, this.frameIndex);\n if (frameLength !== -1) {\n const sample = track.samples[track.samples.length - 1];\n return {\n sample,\n length: frameLength,\n missing: 0\n };\n }\n }\n static probe(data) {\n if (!data) {\n return false;\n }\n const id3Data = getId3Data(data, 0);\n if (!id3Data) {\n return false;\n }\n\n // look for the ac-3 sync bytes\n const offset = id3Data.length;\n if (data[offset] === 0x0b && data[offset + 1] === 0x77 && getId3Timestamp(id3Data) !== undefined &&\n // check the bsid to confirm ac-3\n getAudioBSID(data, offset) < 16) {\n return true;\n }\n return false;\n }\n}\nfunction appendFrame(track, data, start, pts, frameIndex) {\n if (start + 8 > data.length) {\n return -1; // not enough bytes left\n }\n if (data[start] !== 0x0b || data[start + 1] !== 0x77) {\n return -1; // invalid magic\n }\n\n // get sample rate\n const samplingRateCode = data[start + 4] >> 6;\n if (samplingRateCode >= 3) {\n return -1; // invalid sampling rate\n }\n const samplingRateMap = [48000, 44100, 32000];\n const sampleRate = samplingRateMap[samplingRateCode];\n\n // get frame size\n const frameSizeCode = data[start + 4] & 0x3f;\n const frameSizeMap = [64, 69, 96, 64, 70, 96, 80, 87, 120, 80, 88, 120, 96, 104, 144, 96, 105, 144, 112, 121, 168, 112, 122, 168, 128, 139, 192, 128, 140, 192, 160, 174, 240, 160, 175, 240, 192, 208, 288, 192, 209, 288, 224, 243, 336, 224, 244, 336, 256, 278, 384, 256, 279, 384, 320, 348, 480, 320, 349, 480, 384, 417, 576, 384, 418, 576, 448, 487, 672, 448, 488, 672, 512, 557, 768, 512, 558, 768, 640, 696, 960, 640, 697, 960, 768, 835, 1152, 768, 836, 1152, 896, 975, 1344, 896, 976, 1344, 1024, 1114, 1536, 1024, 1115, 1536, 1152, 1253, 1728, 1152, 1254, 1728, 1280, 1393, 1920, 1280, 1394, 1920];\n const frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;\n if (start + frameLength > data.length) {\n return -1;\n }\n\n // get channel count\n const channelMode = data[start + 6] >> 5;\n let skipCount = 0;\n if (channelMode === 2) {\n skipCount += 2;\n } else {\n if (channelMode & 1 && channelMode !== 1) {\n skipCount += 2;\n }\n if (channelMode & 4) {\n skipCount += 2;\n }\n }\n const lfeon = (data[start + 6] << 8 | data[start + 7]) >> 12 - skipCount & 1;\n const channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];\n const channelCount = channelsMap[channelMode] + lfeon;\n\n // build dac3 box\n const bsid = data[start + 5] >> 3;\n const bsmod = data[start + 5] & 7;\n const config = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 0xe0]);\n const frameDuration = 1536 / sampleRate * 90000;\n const stamp = pts + frameIndex * frameDuration;\n const unit = data.subarray(start, start + frameLength);\n track.config = config;\n track.channelCount = channelCount;\n track.samplerate = sampleRate;\n track.samples.push({\n unit,\n pts: stamp\n });\n return frameLength;\n}\n\n/**\n * MP3 demuxer\n */\nclass MP3Demuxer extends BaseAudioDemuxer {\n resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {\n super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);\n this._audioTrack = {\n container: 'audio/mpeg',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'mp3',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0\n };\n }\n static probe(data) {\n if (!data) {\n return false;\n }\n\n // check if data contains ID3 timestamp and MPEG sync word\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n const id3Data = getId3Data(data, 0);\n let offset = (id3Data == null ? void 0 : id3Data.length) || 0;\n\n // Check for ac-3|ec-3 sync bytes and return false if present\n if (id3Data && data[offset] === 0x0b && data[offset + 1] === 0x77 && getId3Timestamp(id3Data) !== undefined &&\n // check the bsid to confirm ac-3 or ec-3 (not mp3)\n getAudioBSID(data, offset) <= 16) {\n return false;\n }\n for (let length = data.length; offset < length; offset++) {\n if (probe(data, offset)) {\n logger.log('MPEG Audio sync word found !');\n return true;\n }\n }\n return false;\n }\n canParse(data, offset) {\n return canParse(data, offset);\n }\n appendFrame(track, data, offset) {\n if (this.basePTS === null) {\n return;\n }\n return appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);\n }\n}\n\nconst emsgSchemePattern = /\\/emsg[-/]ID3/i;\nclass MP4Demuxer {\n constructor(observer, config) {\n this.remainderData = null;\n this.timeOffset = 0;\n this.config = void 0;\n this.videoTrack = void 0;\n this.audioTrack = void 0;\n this.id3Track = void 0;\n this.txtTrack = void 0;\n this.config = config;\n }\n resetTimeStamp() {}\n resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {\n const videoTrack = this.videoTrack = dummyTrack('video', 1);\n const audioTrack = this.audioTrack = dummyTrack('audio', 1);\n const captionTrack = this.txtTrack = dummyTrack('text', 1);\n this.id3Track = dummyTrack('id3', 1);\n this.timeOffset = 0;\n if (!(initSegment != null && initSegment.byteLength)) {\n return;\n }\n const initData = parseInitSegment(initSegment);\n if (initData.video) {\n const {\n id,\n timescale,\n codec,\n supplemental\n } = initData.video;\n videoTrack.id = id;\n videoTrack.timescale = captionTrack.timescale = timescale;\n videoTrack.codec = codec;\n videoTrack.supplemental = supplemental;\n }\n if (initData.audio) {\n const {\n id,\n timescale,\n codec\n } = initData.audio;\n audioTrack.id = id;\n audioTrack.timescale = timescale;\n audioTrack.codec = codec;\n }\n captionTrack.id = RemuxerTrackIdConfig.text;\n videoTrack.sampleDuration = 0;\n videoTrack.duration = audioTrack.duration = trackDuration;\n }\n resetContiguity() {\n this.remainderData = null;\n }\n static probe(data) {\n return hasMoofData(data);\n }\n demux(data, timeOffset) {\n this.timeOffset = timeOffset;\n // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter\n let videoSamples = data;\n const videoTrack = this.videoTrack;\n const textTrack = this.txtTrack;\n if (this.config.progressive) {\n // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.\n // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee\n // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.\n if (this.remainderData) {\n videoSamples = appendUint8Array(this.remainderData, data);\n }\n const segmentedData = segmentValidRange(videoSamples);\n this.remainderData = segmentedData.remainder;\n videoTrack.samples = segmentedData.valid || new Uint8Array();\n } else {\n videoTrack.samples = videoSamples;\n }\n const id3Track = this.extractID3Track(videoTrack, timeOffset);\n textTrack.samples = parseSamples(timeOffset, videoTrack);\n return {\n videoTrack,\n audioTrack: this.audioTrack,\n id3Track,\n textTrack: this.txtTrack\n };\n }\n flush() {\n const timeOffset = this.timeOffset;\n const videoTrack = this.videoTrack;\n const textTrack = this.txtTrack;\n videoTrack.samples = this.remainderData || new Uint8Array();\n this.remainderData = null;\n const id3Track = this.extractID3Track(videoTrack, this.timeOffset);\n textTrack.samples = parseSamples(timeOffset, videoTrack);\n return {\n videoTrack,\n audioTrack: dummyTrack(),\n id3Track,\n textTrack: dummyTrack()\n };\n }\n extractID3Track(videoTrack, timeOffset) {\n const id3Track = this.id3Track;\n if (videoTrack.samples.length) {\n const emsgs = findBox(videoTrack.samples, ['emsg']);\n if (emsgs) {\n emsgs.forEach(data => {\n const emsgInfo = parseEmsg(data);\n if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {\n const pts = getEmsgStartTime(emsgInfo, timeOffset);\n let duration = emsgInfo.eventDuration === 0xffffffff ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;\n // Safari takes anything <= 0.001 seconds and maps it to Infinity\n if (duration <= 0.001) {\n duration = Number.POSITIVE_INFINITY;\n }\n const payload = emsgInfo.payload;\n id3Track.samples.push({\n data: payload,\n len: payload.byteLength,\n dts: pts,\n pts: pts,\n type: MetadataSchema.emsg,\n duration: duration\n });\n } else if (this.config.enableEmsgKLVMetadata && emsgInfo.schemeIdUri.startsWith('urn:misb:KLV:bin:1910.1')) {\n const pts = getEmsgStartTime(emsgInfo, timeOffset);\n id3Track.samples.push({\n data: emsgInfo.payload,\n len: emsgInfo.payload.byteLength,\n dts: pts,\n pts: pts,\n type: MetadataSchema.misbklv,\n duration: Number.POSITIVE_INFINITY\n });\n }\n });\n }\n }\n return id3Track;\n }\n demuxSampleAes(data, keyData, timeOffset) {\n return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));\n }\n destroy() {\n // @ts-ignore\n this.config = null;\n this.remainderData = null;\n this.videoTrack = this.audioTrack = this.id3Track = this.txtTrack = undefined;\n }\n}\nfunction getEmsgStartTime(emsgInfo, timeOffset) {\n return isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;\n}\n\n/**\n * SAMPLE-AES decrypter\n */\n\nclass SampleAesDecrypter {\n constructor(observer, config, keyData) {\n this.keyData = void 0;\n this.decrypter = void 0;\n this.keyData = keyData;\n this.decrypter = new Decrypter(config, {\n removePKCS7Padding: false\n });\n }\n decryptBuffer(encryptedData) {\n return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, DecrypterAesMode.cbc);\n }\n\n // AAC - encrypt all full 16 bytes blocks starting from offset 16\n decryptAacSample(samples, sampleIndex, callback) {\n const curUnit = samples[sampleIndex].unit;\n if (curUnit.length <= 16) {\n // No encrypted portion in this sample (first 16 bytes is not\n // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),\n return;\n }\n const encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);\n const encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);\n this.decryptBuffer(encryptedBuffer).then(decryptedBuffer => {\n const decryptedData = new Uint8Array(decryptedBuffer);\n curUnit.set(decryptedData, 16);\n if (!this.decrypter.isSync()) {\n this.decryptAacSamples(samples, sampleIndex + 1, callback);\n }\n });\n }\n decryptAacSamples(samples, sampleIndex, callback) {\n for (;; sampleIndex++) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n if (samples[sampleIndex].unit.length < 32) {\n continue;\n }\n this.decryptAacSample(samples, sampleIndex, callback);\n if (!this.decrypter.isSync()) {\n return;\n }\n }\n }\n\n // AVC - encrypt one 16 bytes block out of ten, starting from offset 32\n getAvcEncryptedData(decodedData) {\n const encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n const encryptedData = new Int8Array(encryptedDataLen);\n let outputPos = 0;\n for (let inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {\n encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n return encryptedData;\n }\n getAvcDecryptedUnit(decodedData, decryptedData) {\n const uint8DecryptedData = new Uint8Array(decryptedData);\n let inputPos = 0;\n for (let outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {\n decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n return decodedData;\n }\n decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {\n const decodedData = discardEPB(curUnit.data);\n const encryptedData = this.getAvcEncryptedData(decodedData);\n this.decryptBuffer(encryptedData.buffer).then(decryptedBuffer => {\n curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);\n if (!this.decrypter.isSync()) {\n this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);\n }\n });\n }\n decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {\n if (samples instanceof Uint8Array) {\n throw new Error('Cannot decrypt samples of type Uint8Array');\n }\n for (;; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n const curUnits = samples[sampleIndex].units;\n for (;; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n const curUnit = curUnits[unitIndex];\n if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {\n continue;\n }\n this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);\n if (!this.decrypter.isSync()) {\n return;\n }\n }\n }\n }\n}\n\nclass BaseVideoParser {\n constructor() {\n this.VideoSample = null;\n }\n createVideoSample(key, pts, dts) {\n return {\n key,\n frame: false,\n pts,\n dts,\n units: [],\n length: 0\n };\n }\n getLastNalUnit(samples) {\n var _VideoSample;\n let VideoSample = this.VideoSample;\n let lastUnit;\n // try to fallback to previous sample if current one is empty\n if (!VideoSample || VideoSample.units.length === 0) {\n VideoSample = samples[samples.length - 1];\n }\n if ((_VideoSample = VideoSample) != null && _VideoSample.units) {\n const units = VideoSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n }\n pushAccessUnit(VideoSample, videoTrack) {\n if (VideoSample.units.length && VideoSample.frame) {\n // if sample does not have PTS/DTS, patch with last sample PTS/DTS\n if (VideoSample.pts === undefined) {\n const samples = videoTrack.samples;\n const nbSamples = samples.length;\n if (nbSamples) {\n const lastSample = samples[nbSamples - 1];\n VideoSample.pts = lastSample.pts;\n VideoSample.dts = lastSample.dts;\n } else {\n // dropping samples, no timestamp found\n videoTrack.dropped++;\n return;\n }\n }\n videoTrack.samples.push(VideoSample);\n }\n }\n parseNALu(track, array, endOfSegment) {\n const len = array.byteLength;\n let state = track.naluState || 0;\n const lastState = state;\n const units = [];\n let i = 0;\n let value;\n let overflow;\n let unitType;\n let lastUnitStart = -1;\n let lastUnitType = 0;\n // logger.log('PES:' + Hex.hexDump(array));\n\n if (state === -1) {\n // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n lastUnitStart = 0;\n // NALu type is value read from offset 0\n lastUnitType = this.getNALuType(array, 0);\n state = 0;\n i = 1;\n }\n while (i < len) {\n value = array[i++];\n // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n if (!state) {\n state = value ? 0 : 1;\n continue;\n }\n if (state === 1) {\n state = value ? 0 : 2;\n continue;\n }\n // here we have state either equal to 2 or 3\n if (!value) {\n state = 3;\n } else if (value === 1) {\n overflow = i - state - 1;\n if (lastUnitStart >= 0) {\n const unit = {\n data: array.subarray(lastUnitStart, overflow),\n type: lastUnitType\n };\n // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);\n units.push(unit);\n } else {\n // lastUnitStart is undefined => this is the first start code found in this PES packet\n // first check if start code delimiter is overlapping between 2 PES packets,\n // ie it started in last packet (lastState not zero)\n // and ended at the beginning of this PES packet (i <= 4 - lastState)\n const lastUnit = this.getLastNalUnit(track.samples);\n if (lastUnit) {\n if (lastState && i <= 4 - lastState) {\n // start delimiter overlapping between PES packets\n // strip start delimiter bytes from the end of last NAL unit\n // check if lastUnit had a state different from zero\n if (lastUnit.state) {\n // strip last bytes\n lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);\n }\n }\n // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n\n if (overflow > 0) {\n // logger.log('first NALU found with overflow:' + overflow);\n lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));\n lastUnit.state = 0;\n }\n }\n }\n // check if we can read unit type\n if (i < len) {\n unitType = this.getNALuType(array, i);\n // logger.log('find NALU @ offset:' + i + ',type:' + unitType);\n lastUnitStart = i;\n lastUnitType = unitType;\n state = 0;\n } else {\n // not enough byte to read unit type. let's read it on next PES parsing\n state = -1;\n }\n } else {\n state = 0;\n }\n }\n if (lastUnitStart >= 0 && state >= 0) {\n const unit = {\n data: array.subarray(lastUnitStart, len),\n type: lastUnitType,\n state: state\n };\n units.push(unit);\n // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);\n }\n // no NALu found\n if (units.length === 0) {\n // append pes.data to previous NAL unit\n const lastUnit = this.getLastNalUnit(track.samples);\n if (lastUnit) {\n lastUnit.data = appendUint8Array(lastUnit.data, array);\n }\n }\n track.naluState = state;\n return units;\n }\n}\n\n/**\n * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n */\n\nclass ExpGolomb {\n constructor(data) {\n this.data = void 0;\n this.bytesAvailable = void 0;\n this.word = void 0;\n this.bitsAvailable = void 0;\n this.data = data;\n // the number of bytes left to examine in this.data\n this.bytesAvailable = data.byteLength;\n // the current word being examined\n this.word = 0; // :uint\n // the number of bits left to examine in the current word\n this.bitsAvailable = 0; // :uint\n }\n\n // ():void\n loadWord() {\n const data = this.data;\n const bytesAvailable = this.bytesAvailable;\n const position = data.byteLength - bytesAvailable;\n const workingBytes = new Uint8Array(4);\n const availableBytes = Math.min(4, bytesAvailable);\n if (availableBytes === 0) {\n throw new Error('no bytes available');\n }\n workingBytes.set(data.subarray(position, position + availableBytes));\n this.word = new DataView(workingBytes.buffer).getUint32(0);\n // track the amount of this.data that has been processed\n this.bitsAvailable = availableBytes * 8;\n this.bytesAvailable -= availableBytes;\n }\n\n // (count:int):void\n skipBits(count) {\n let skipBytes; // :int\n count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);\n if (this.bitsAvailable > count) {\n this.word <<= count;\n this.bitsAvailable -= count;\n } else {\n count -= this.bitsAvailable;\n skipBytes = count >> 3;\n count -= skipBytes << 3;\n this.bytesAvailable -= skipBytes;\n this.loadWord();\n this.word <<= count;\n this.bitsAvailable -= count;\n }\n }\n\n // (size:int):uint\n readBits(size) {\n let bits = Math.min(this.bitsAvailable, size); // :uint\n const valu = this.word >>> 32 - bits; // :uint\n if (size > 32) {\n logger.error('Cannot read more than 32 bits at a time');\n }\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n } else {\n throw new Error('no bits available');\n }\n bits = size - bits;\n if (bits > 0 && this.bitsAvailable) {\n return valu << bits | this.readBits(bits);\n } else {\n return valu;\n }\n }\n\n // ():uint\n skipLZ() {\n let leadingZeroCount; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {\n // the first bit of working word is 1\n this.word <<= leadingZeroCount;\n this.bitsAvailable -= leadingZeroCount;\n return leadingZeroCount;\n }\n }\n // we exhausted word and still have not found a 1\n this.loadWord();\n return leadingZeroCount + this.skipLZ();\n }\n\n // ():void\n skipUEG() {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():void\n skipEG() {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():uint\n readUEG() {\n const clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG() {\n const valu = this.readUEG(); // :int\n if (0x01 & valu) {\n // the number is odd if the low order bit is set\n return 1 + valu >>> 1; // add 1 to make it even, and divide by 2\n } else {\n return -1 * (valu >>> 1); // divide by two then make it negative\n }\n }\n\n // Some convenience functions\n // :Boolean\n readBoolean() {\n return this.readBits(1) === 1;\n }\n\n // ():int\n readUByte() {\n return this.readBits(8);\n }\n\n // ():int\n readUShort() {\n return this.readBits(16);\n }\n\n // ():int\n readUInt() {\n return this.readBits(32);\n }\n}\n\nclass AvcVideoParser extends BaseVideoParser {\n parsePES(track, textTrack, pes, endOfSegment) {\n const units = this.parseNALu(track, pes.data, endOfSegment);\n let VideoSample = this.VideoSample;\n let push;\n let spsfound = false;\n // free pes.data to save up some memory\n pes.data = null;\n\n // if new NAL units found and last sample still there, let's push ...\n // this helps parsing streams with missing AUD (only do this if AUD never found)\n if (VideoSample && units.length && !track.audFound) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);\n }\n units.forEach(unit => {\n var _VideoSample2, _VideoSample3;\n switch (unit.type) {\n // NDR\n case 1:\n {\n let iskey = false;\n push = true;\n const data = unit.data;\n // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)\n if (spsfound && data.length > 4) {\n // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\n const sliceType = this.readSliceType(data);\n // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice\n // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.\n // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.\n // I slice: A slice that is not an SI slice that is decoded using intra prediction only.\n // if (sliceType === 2 || sliceType === 7) {\n if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {\n iskey = true;\n }\n }\n if (iskey) {\n var _VideoSample;\n // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push\n if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = null;\n }\n }\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);\n }\n VideoSample.frame = true;\n VideoSample.key = iskey;\n break;\n // IDR\n }\n case 5:\n push = true;\n // handle PES not starting with AUD\n // if we have frame data already, that cannot belong to the same frame, so force a push\n if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = null;\n }\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);\n }\n VideoSample.key = true;\n VideoSample.frame = true;\n break;\n // SEI\n case 6:\n {\n push = true;\n parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);\n break;\n // SPS\n }\n case 7:\n {\n var _track$pixelRatio, _track$pixelRatio2;\n push = true;\n spsfound = true;\n const sps = unit.data;\n const config = this.readSPS(sps);\n if (!track.sps || track.width !== config.width || track.height !== config.height || ((_track$pixelRatio = track.pixelRatio) == null ? void 0 : _track$pixelRatio[0]) !== config.pixelRatio[0] || ((_track$pixelRatio2 = track.pixelRatio) == null ? void 0 : _track$pixelRatio2[1]) !== config.pixelRatio[1]) {\n track.width = config.width;\n track.height = config.height;\n track.pixelRatio = config.pixelRatio;\n track.sps = [sps];\n const codecarray = sps.subarray(1, 4);\n let codecstring = 'avc1.';\n for (let i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n codecstring += h;\n }\n track.codec = codecstring;\n }\n break;\n }\n // PPS\n case 8:\n push = true;\n track.pps = [unit.data];\n break;\n // AUD\n case 9:\n push = true;\n track.audFound = true;\n if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = null;\n }\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);\n }\n break;\n // Filler Data\n case 12:\n push = true;\n break;\n default:\n push = false;\n break;\n }\n if (VideoSample && push) {\n const units = VideoSample.units;\n units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (endOfSegment && VideoSample) {\n this.pushAccessUnit(VideoSample, track);\n this.VideoSample = null;\n }\n }\n getNALuType(data, offset) {\n return data[offset] & 0x1f;\n }\n readSliceType(data) {\n const eg = new ExpGolomb(data);\n // skip NALu type\n eg.readUByte();\n // discard first_mb_in_slice\n eg.readUEG();\n // return slice_type\n return eg.readUEG();\n }\n\n /**\n * The scaling list is optionally transmitted as part of a sequence parameter\n * set and is not relevant to transmuxing.\n * @param count the number of entries in this scaling list\n * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n */\n skipScalingList(count, reader) {\n let lastScale = 8;\n let nextScale = 8;\n let deltaScale;\n for (let j = 0; j < count; j++) {\n if (nextScale !== 0) {\n deltaScale = reader.readEG();\n nextScale = (lastScale + deltaScale + 256) % 256;\n }\n lastScale = nextScale === 0 ? lastScale : nextScale;\n }\n }\n\n /**\n * Read a sequence parameter set and return some interesting video\n * properties. A sequence parameter set is the H264 metadata that\n * describes the properties of upcoming video frames.\n * @returns an object with configuration parsed from the\n * sequence parameter set, including the dimensions of the\n * associated video frames.\n */\n readSPS(sps) {\n const eg = new ExpGolomb(sps);\n let frameCropLeftOffset = 0;\n let frameCropRightOffset = 0;\n let frameCropTopOffset = 0;\n let frameCropBottomOffset = 0;\n let numRefFramesInPicOrderCntCycle;\n let scalingListCount;\n let i;\n const readUByte = eg.readUByte.bind(eg);\n const readBits = eg.readBits.bind(eg);\n const readUEG = eg.readUEG.bind(eg);\n const readBoolean = eg.readBoolean.bind(eg);\n const skipBits = eg.skipBits.bind(eg);\n const skipEG = eg.skipEG.bind(eg);\n const skipUEG = eg.skipUEG.bind(eg);\n const skipScalingList = this.skipScalingList.bind(this);\n readUByte();\n const profileIdc = readUByte(); // profile_idc\n readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)\n skipBits(3); // reserved_zero_3bits u(3),\n readUByte(); // level_idc u(8)\n skipUEG(); // seq_parameter_set_id\n // some profiles have more optional data we don't need\n if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {\n const chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // separate_colour_plane_flag\n\n skipUEG(); // bit_depth_luma_minus8\n skipUEG(); // bit_depth_chroma_minus8\n skipBits(1); // qpprime_y_zero_transform_bypass_flag\n if (readBoolean()) {\n // seq_scaling_matrix_present_flag\n scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;\n for (i = 0; i < scalingListCount; i++) {\n if (readBoolean()) {\n // seq_scaling_list_present_flag[ i ]\n if (i < 6) {\n skipScalingList(16, eg);\n } else {\n skipScalingList(64, eg);\n }\n }\n }\n }\n }\n skipUEG(); // log2_max_frame_num_minus4\n const picOrderCntType = readUEG();\n if (picOrderCntType === 0) {\n readUEG(); // log2_max_pic_order_cnt_lsb_minus4\n } else if (picOrderCntType === 1) {\n skipBits(1); // delta_pic_order_always_zero_flag\n skipEG(); // offset_for_non_ref_pic\n skipEG(); // offset_for_top_to_bottom_field\n numRefFramesInPicOrderCntCycle = readUEG();\n for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n skipEG();\n } // offset_for_ref_frame[ i ]\n }\n skipUEG(); // max_num_ref_frames\n skipBits(1); // gaps_in_frame_num_value_allowed_flag\n const picWidthInMbsMinus1 = readUEG();\n const picHeightInMapUnitsMinus1 = readUEG();\n const frameMbsOnlyFlag = readBits(1);\n if (frameMbsOnlyFlag === 0) {\n skipBits(1);\n } // mb_adaptive_frame_field_flag\n\n skipBits(1); // direct_8x8_inference_flag\n if (readBoolean()) {\n // frame_cropping_flag\n frameCropLeftOffset = readUEG();\n frameCropRightOffset = readUEG();\n frameCropTopOffset = readUEG();\n frameCropBottomOffset = readUEG();\n }\n let pixelRatio = [1, 1];\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n const aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1:\n pixelRatio = [1, 1];\n break;\n case 2:\n pixelRatio = [12, 11];\n break;\n case 3:\n pixelRatio = [10, 11];\n break;\n case 4:\n pixelRatio = [16, 11];\n break;\n case 5:\n pixelRatio = [40, 33];\n break;\n case 6:\n pixelRatio = [24, 11];\n break;\n case 7:\n pixelRatio = [20, 11];\n break;\n case 8:\n pixelRatio = [32, 11];\n break;\n case 9:\n pixelRatio = [80, 33];\n break;\n case 10:\n pixelRatio = [18, 11];\n break;\n case 11:\n pixelRatio = [15, 11];\n break;\n case 12:\n pixelRatio = [64, 33];\n break;\n case 13:\n pixelRatio = [160, 99];\n break;\n case 14:\n pixelRatio = [4, 3];\n break;\n case 15:\n pixelRatio = [3, 2];\n break;\n case 16:\n pixelRatio = [2, 1];\n break;\n case 255:\n {\n pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];\n break;\n }\n }\n }\n }\n return {\n width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),\n height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),\n pixelRatio: pixelRatio\n };\n }\n}\n\nclass HevcVideoParser extends BaseVideoParser {\n constructor(...args) {\n super(...args);\n this.initVPS = null;\n }\n parsePES(track, textTrack, pes, endOfSegment) {\n const units = this.parseNALu(track, pes.data, endOfSegment);\n let VideoSample = this.VideoSample;\n let push;\n let spsfound = false;\n // free pes.data to save up some memory\n pes.data = null;\n\n // if new NAL units found and last sample still there, let's push ...\n // this helps parsing streams with missing AUD (only do this if AUD never found)\n if (VideoSample && units.length && !track.audFound) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);\n }\n units.forEach(unit => {\n var _VideoSample2, _VideoSample3;\n switch (unit.type) {\n // NON-IDR, NON RANDOM ACCESS SLICE\n case 0:\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n case 9:\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);\n }\n VideoSample.frame = true;\n push = true;\n break;\n\n // CRA, BLA (random access picture)\n case 16:\n case 17:\n case 18:\n case 21:\n push = true;\n if (spsfound) {\n var _VideoSample;\n // handle PES not starting with AUD\n // if we have frame data already, that cannot belong to the same frame, so force a push\n if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = null;\n }\n }\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);\n }\n VideoSample.key = true;\n VideoSample.frame = true;\n break;\n\n // IDR\n case 19:\n case 20:\n push = true;\n // handle PES not starting with AUD\n // if we have frame data already, that cannot belong to the same frame, so force a push\n if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = this.VideoSample = null;\n }\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);\n }\n VideoSample.key = true;\n VideoSample.frame = true;\n break;\n\n // SEI\n case 39:\n push = true;\n parseSEIMessageFromNALu(unit.data, 2,\n // NALu header size\n pes.pts, textTrack.samples);\n break;\n\n // VPS\n case 32:\n push = true;\n if (!track.vps) {\n if (typeof track.params !== 'object') {\n track.params = {};\n }\n track.params = _extends(track.params, this.readVPS(unit.data));\n this.initVPS = unit.data;\n }\n track.vps = [unit.data];\n break;\n\n // SPS\n case 33:\n push = true;\n spsfound = true;\n if (track.vps !== undefined && track.vps[0] !== this.initVPS && track.sps !== undefined && !this.matchSPS(track.sps[0], unit.data)) {\n this.initVPS = track.vps[0];\n track.sps = track.pps = undefined;\n }\n if (!track.sps) {\n const config = this.readSPS(unit.data);\n track.width = config.width;\n track.height = config.height;\n track.pixelRatio = config.pixelRatio;\n track.codec = config.codecString;\n track.sps = [];\n if (typeof track.params !== 'object') {\n track.params = {};\n }\n for (const prop in config.params) {\n track.params[prop] = config.params[prop];\n }\n }\n this.pushParameterSet(track.sps, unit.data, track.vps);\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(true, pes.pts, pes.dts);\n }\n VideoSample.key = true;\n break;\n\n // PPS\n case 34:\n push = true;\n if (typeof track.params === 'object') {\n if (!track.pps) {\n track.pps = [];\n const config = this.readPPS(unit.data);\n for (const prop in config) {\n track.params[prop] = config[prop];\n }\n }\n this.pushParameterSet(track.pps, unit.data, track.vps);\n }\n break;\n\n // ACCESS UNIT DELIMITER\n case 35:\n push = true;\n track.audFound = true;\n if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {\n this.pushAccessUnit(VideoSample, track);\n VideoSample = null;\n }\n if (!VideoSample) {\n VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);\n }\n break;\n default:\n push = false;\n break;\n }\n if (VideoSample && push) {\n const units = VideoSample.units;\n units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (endOfSegment && VideoSample) {\n this.pushAccessUnit(VideoSample, track);\n this.VideoSample = null;\n }\n }\n pushParameterSet(parameterSets, data, vps) {\n if (vps && vps[0] === this.initVPS || !vps && !parameterSets.length) {\n parameterSets.push(data);\n }\n }\n getNALuType(data, offset) {\n return (data[offset] & 0x7e) >>> 1;\n }\n ebsp2rbsp(arr) {\n const dst = new Uint8Array(arr.byteLength);\n let dstIdx = 0;\n for (let i = 0; i < arr.byteLength; i++) {\n if (i >= 2) {\n // Unescape: Skip 0x03 after 00 00\n if (arr[i] === 0x03 && arr[i - 1] === 0x00 && arr[i - 2] === 0x00) {\n continue;\n }\n }\n dst[dstIdx] = arr[i];\n dstIdx++;\n }\n return new Uint8Array(dst.buffer, 0, dstIdx);\n }\n pushAccessUnit(VideoSample, videoTrack) {\n super.pushAccessUnit(VideoSample, videoTrack);\n if (this.initVPS) {\n this.initVPS = null; // null initVPS to prevent possible track's sps/pps growth until next VPS\n }\n }\n readVPS(vps) {\n const eg = new ExpGolomb(vps);\n // remove header\n eg.readUByte();\n eg.readUByte();\n eg.readBits(4); // video_parameter_set_id\n eg.skipBits(2);\n eg.readBits(6); // max_layers_minus1\n const max_sub_layers_minus1 = eg.readBits(3);\n const temporal_id_nesting_flag = eg.readBoolean();\n // ...vui fps can be here, but empty fps value is not critical for metadata\n\n return {\n numTemporalLayers: max_sub_layers_minus1 + 1,\n temporalIdNested: temporal_id_nesting_flag\n };\n }\n readSPS(sps) {\n const eg = new ExpGolomb(this.ebsp2rbsp(sps));\n eg.readUByte();\n eg.readUByte();\n eg.readBits(4); //video_parameter_set_id\n const max_sub_layers_minus1 = eg.readBits(3);\n eg.readBoolean(); // temporal_id_nesting_flag\n\n // profile_tier_level\n const general_profile_space = eg.readBits(2);\n const general_tier_flag = eg.readBoolean();\n const general_profile_idc = eg.readBits(5);\n const general_profile_compatibility_flags_1 = eg.readUByte();\n const general_profile_compatibility_flags_2 = eg.readUByte();\n const general_profile_compatibility_flags_3 = eg.readUByte();\n const general_profile_compatibility_flags_4 = eg.readUByte();\n const general_constraint_indicator_flags_1 = eg.readUByte();\n const general_constraint_indicator_flags_2 = eg.readUByte();\n const general_constraint_indicator_flags_3 = eg.readUByte();\n const general_constraint_indicator_flags_4 = eg.readUByte();\n const general_constraint_indicator_flags_5 = eg.readUByte();\n const general_constraint_indicator_flags_6 = eg.readUByte();\n const general_level_idc = eg.readUByte();\n const sub_layer_profile_present_flags = [];\n const sub_layer_level_present_flags = [];\n for (let i = 0; i < max_sub_layers_minus1; i++) {\n sub_layer_profile_present_flags.push(eg.readBoolean());\n sub_layer_level_present_flags.push(eg.readBoolean());\n }\n if (max_sub_layers_minus1 > 0) {\n for (let i = max_sub_layers_minus1; i < 8; i++) {\n eg.readBits(2);\n }\n }\n for (let i = 0; i < max_sub_layers_minus1; i++) {\n if (sub_layer_profile_present_flags[i]) {\n eg.readUByte(); // sub_layer_profile_space, sub_layer_tier_flag, sub_layer_profile_idc\n eg.readUByte();\n eg.readUByte();\n eg.readUByte();\n eg.readUByte(); // sub_layer_profile_compatibility_flag\n eg.readUByte();\n eg.readUByte();\n eg.readUByte();\n eg.readUByte();\n eg.readUByte();\n eg.readUByte();\n }\n if (sub_layer_level_present_flags[i]) {\n eg.readUByte();\n }\n }\n eg.readUEG(); // seq_parameter_set_id\n const chroma_format_idc = eg.readUEG();\n if (chroma_format_idc == 3) {\n eg.skipBits(1); //separate_colour_plane_flag\n }\n const pic_width_in_luma_samples = eg.readUEG();\n const pic_height_in_luma_samples = eg.readUEG();\n const conformance_window_flag = eg.readBoolean();\n let pic_left_offset = 0,\n pic_right_offset = 0,\n pic_top_offset = 0,\n pic_bottom_offset = 0;\n if (conformance_window_flag) {\n pic_left_offset += eg.readUEG();\n pic_right_offset += eg.readUEG();\n pic_top_offset += eg.readUEG();\n pic_bottom_offset += eg.readUEG();\n }\n const bit_depth_luma_minus8 = eg.readUEG();\n const bit_depth_chroma_minus8 = eg.readUEG();\n const log2_max_pic_order_cnt_lsb_minus4 = eg.readUEG();\n const sub_layer_ordering_info_present_flag = eg.readBoolean();\n for (let i = sub_layer_ordering_info_present_flag ? 0 : max_sub_layers_minus1; i <= max_sub_layers_minus1; i++) {\n eg.skipUEG(); // max_dec_pic_buffering_minus1[i]\n eg.skipUEG(); // max_num_reorder_pics[i]\n eg.skipUEG(); // max_latency_increase_plus1[i]\n }\n eg.skipUEG(); // log2_min_luma_coding_block_size_minus3\n eg.skipUEG(); // log2_diff_max_min_luma_coding_block_size\n eg.skipUEG(); // log2_min_transform_block_size_minus2\n eg.skipUEG(); // log2_diff_max_min_transform_block_size\n eg.skipUEG(); // max_transform_hierarchy_depth_inter\n eg.skipUEG(); // max_transform_hierarchy_depth_intra\n const scaling_list_enabled_flag = eg.readBoolean();\n if (scaling_list_enabled_flag) {\n const sps_scaling_list_data_present_flag = eg.readBoolean();\n if (sps_scaling_list_data_present_flag) {\n for (let sizeId = 0; sizeId < 4; sizeId++) {\n for (let matrixId = 0; matrixId < (sizeId === 3 ? 2 : 6); matrixId++) {\n const scaling_list_pred_mode_flag = eg.readBoolean();\n if (!scaling_list_pred_mode_flag) {\n eg.readUEG(); // scaling_list_pred_matrix_id_delta\n } else {\n const coefNum = Math.min(64, 1 << 4 + (sizeId << 1));\n if (sizeId > 1) {\n eg.readEG();\n }\n for (let i = 0; i < coefNum; i++) {\n eg.readEG();\n }\n }\n }\n }\n }\n }\n eg.readBoolean(); // amp_enabled_flag\n eg.readBoolean(); // sample_adaptive_offset_enabled_flag\n const pcm_enabled_flag = eg.readBoolean();\n if (pcm_enabled_flag) {\n eg.readUByte();\n eg.skipUEG();\n eg.skipUEG();\n eg.readBoolean();\n }\n const num_short_term_ref_pic_sets = eg.readUEG();\n let num_delta_pocs = 0;\n for (let i = 0; i < num_short_term_ref_pic_sets; i++) {\n let inter_ref_pic_set_prediction_flag = false;\n if (i !== 0) {\n inter_ref_pic_set_prediction_flag = eg.readBoolean();\n }\n if (inter_ref_pic_set_prediction_flag) {\n if (i === num_short_term_ref_pic_sets) {\n eg.readUEG();\n }\n eg.readBoolean();\n eg.readUEG();\n let next_num_delta_pocs = 0;\n for (let j = 0; j <= num_delta_pocs; j++) {\n const used_by_curr_pic_flag = eg.readBoolean();\n let use_delta_flag = false;\n if (!used_by_curr_pic_flag) {\n use_delta_flag = eg.readBoolean();\n }\n if (used_by_curr_pic_flag || use_delta_flag) {\n next_num_delta_pocs++;\n }\n }\n num_delta_pocs = next_num_delta_pocs;\n } else {\n const num_negative_pics = eg.readUEG();\n const num_positive_pics = eg.readUEG();\n num_delta_pocs = num_negative_pics + num_positive_pics;\n for (let j = 0; j < num_negative_pics; j++) {\n eg.readUEG();\n eg.readBoolean();\n }\n for (let j = 0; j < num_positive_pics; j++) {\n eg.readUEG();\n eg.readBoolean();\n }\n }\n }\n const long_term_ref_pics_present_flag = eg.readBoolean();\n if (long_term_ref_pics_present_flag) {\n const num_long_term_ref_pics_sps = eg.readUEG();\n for (let i = 0; i < num_long_term_ref_pics_sps; i++) {\n for (let j = 0; j < log2_max_pic_order_cnt_lsb_minus4 + 4; j++) {\n eg.readBits(1);\n }\n eg.readBits(1);\n }\n }\n let min_spatial_segmentation_idc = 0;\n let sar_width = 1,\n sar_height = 1;\n let fps_fixed = true,\n fps_den = 1,\n fps_num = 0;\n eg.readBoolean(); // sps_temporal_mvp_enabled_flag\n eg.readBoolean(); // strong_intra_smoothing_enabled_flag\n let default_display_window_flag = false;\n const vui_parameters_present_flag = eg.readBoolean();\n if (vui_parameters_present_flag) {\n const aspect_ratio_info_present_flag = eg.readBoolean();\n if (aspect_ratio_info_present_flag) {\n const aspect_ratio_idc = eg.readUByte();\n const sar_width_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];\n const sar_height_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];\n if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {\n sar_width = sar_width_table[aspect_ratio_idc - 1];\n sar_height = sar_height_table[aspect_ratio_idc - 1];\n } else if (aspect_ratio_idc === 255) {\n sar_width = eg.readBits(16);\n sar_height = eg.readBits(16);\n }\n }\n const overscan_info_present_flag = eg.readBoolean();\n if (overscan_info_present_flag) {\n eg.readBoolean();\n }\n const video_signal_type_present_flag = eg.readBoolean();\n if (video_signal_type_present_flag) {\n eg.readBits(3);\n eg.readBoolean();\n const colour_description_present_flag = eg.readBoolean();\n if (colour_description_present_flag) {\n eg.readUByte();\n eg.readUByte();\n eg.readUByte();\n }\n }\n const chroma_loc_info_present_flag = eg.readBoolean();\n if (chroma_loc_info_present_flag) {\n eg.readUEG();\n eg.readUEG();\n }\n eg.readBoolean(); // neutral_chroma_indication_flag\n eg.readBoolean(); // field_seq_flag\n eg.readBoolean(); // frame_field_info_present_flag\n default_display_window_flag = eg.readBoolean();\n if (default_display_window_flag) {\n pic_left_offset += eg.readUEG();\n pic_right_offset += eg.readUEG();\n pic_top_offset += eg.readUEG();\n pic_bottom_offset += eg.readUEG();\n }\n const vui_timing_info_present_flag = eg.readBoolean();\n if (vui_timing_info_present_flag) {\n fps_den = eg.readBits(32);\n fps_num = eg.readBits(32);\n const vui_poc_proportional_to_timing_flag = eg.readBoolean();\n if (vui_poc_proportional_to_timing_flag) {\n eg.readUEG();\n }\n const vui_hrd_parameters_present_flag = eg.readBoolean();\n if (vui_hrd_parameters_present_flag) {\n //const commonInfPresentFlag = true;\n //if (commonInfPresentFlag) {\n const nal_hrd_parameters_present_flag = eg.readBoolean();\n const vcl_hrd_parameters_present_flag = eg.readBoolean();\n let sub_pic_hrd_params_present_flag = false;\n if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {\n sub_pic_hrd_params_present_flag = eg.readBoolean();\n if (sub_pic_hrd_params_present_flag) {\n eg.readUByte();\n eg.readBits(5);\n eg.readBoolean();\n eg.readBits(5);\n }\n eg.readBits(4); // bit_rate_scale\n eg.readBits(4); // cpb_size_scale\n if (sub_pic_hrd_params_present_flag) {\n eg.readBits(4);\n }\n eg.readBits(5);\n eg.readBits(5);\n eg.readBits(5);\n }\n //}\n for (let i = 0; i <= max_sub_layers_minus1; i++) {\n fps_fixed = eg.readBoolean(); // fixed_pic_rate_general_flag\n const fixed_pic_rate_within_cvs_flag = fps_fixed || eg.readBoolean();\n let low_delay_hrd_flag = false;\n if (fixed_pic_rate_within_cvs_flag) {\n eg.readEG();\n } else {\n low_delay_hrd_flag = eg.readBoolean();\n }\n const cpb_cnt = low_delay_hrd_flag ? 1 : eg.readUEG() + 1;\n if (nal_hrd_parameters_present_flag) {\n for (let j = 0; j < cpb_cnt; j++) {\n eg.readUEG();\n eg.readUEG();\n if (sub_pic_hrd_params_present_flag) {\n eg.readUEG();\n eg.readUEG();\n }\n eg.skipBits(1);\n }\n }\n if (vcl_hrd_parameters_present_flag) {\n for (let j = 0; j < cpb_cnt; j++) {\n eg.readUEG();\n eg.readUEG();\n if (sub_pic_hrd_params_present_flag) {\n eg.readUEG();\n eg.readUEG();\n }\n eg.skipBits(1);\n }\n }\n }\n }\n }\n const bitstream_restriction_flag = eg.readBoolean();\n if (bitstream_restriction_flag) {\n eg.readBoolean(); // tiles_fixed_structure_flag\n eg.readBoolean(); // motion_vectors_over_pic_boundaries_flag\n eg.readBoolean(); // restricted_ref_pic_lists_flag\n min_spatial_segmentation_idc = eg.readUEG();\n }\n }\n let width = pic_width_in_luma_samples,\n height = pic_height_in_luma_samples;\n if (conformance_window_flag || default_display_window_flag) {\n let chroma_scale_w = 1,\n chroma_scale_h = 1;\n if (chroma_format_idc === 1) {\n // YUV 420\n chroma_scale_w = chroma_scale_h = 2;\n } else if (chroma_format_idc == 2) {\n // YUV 422\n chroma_scale_w = 2;\n }\n width = pic_width_in_luma_samples - chroma_scale_w * pic_right_offset - chroma_scale_w * pic_left_offset;\n height = pic_height_in_luma_samples - chroma_scale_h * pic_bottom_offset - chroma_scale_h * pic_top_offset;\n }\n const profile_space_string = general_profile_space ? ['A', 'B', 'C'][general_profile_space] : '';\n const profile_compatibility_buf = general_profile_compatibility_flags_1 << 24 | general_profile_compatibility_flags_2 << 16 | general_profile_compatibility_flags_3 << 8 | general_profile_compatibility_flags_4;\n let profile_compatibility_rev = 0;\n for (let i = 0; i < 32; i++) {\n profile_compatibility_rev = (profile_compatibility_rev | (profile_compatibility_buf >> i & 1) << 31 - i) >>> 0; // reverse bit position (and cast as UInt32)\n }\n let profile_compatibility_flags_string = profile_compatibility_rev.toString(16);\n if (general_profile_idc === 1 && profile_compatibility_flags_string === '2') {\n profile_compatibility_flags_string = '6';\n }\n const tier_flag_string = general_tier_flag ? 'H' : 'L';\n return {\n codecString: `hvc1.${profile_space_string}${general_profile_idc}.${profile_compatibility_flags_string}.${tier_flag_string}${general_level_idc}.B0`,\n params: {\n general_tier_flag,\n general_profile_idc,\n general_profile_space,\n general_profile_compatibility_flags: [general_profile_compatibility_flags_1, general_profile_compatibility_flags_2, general_profile_compatibility_flags_3, general_profile_compatibility_flags_4],\n general_constraint_indicator_flags: [general_constraint_indicator_flags_1, general_constraint_indicator_flags_2, general_constraint_indicator_flags_3, general_constraint_indicator_flags_4, general_constraint_indicator_flags_5, general_constraint_indicator_flags_6],\n general_level_idc,\n bit_depth: bit_depth_luma_minus8 + 8,\n bit_depth_luma_minus8,\n bit_depth_chroma_minus8,\n min_spatial_segmentation_idc,\n chroma_format_idc: chroma_format_idc,\n frame_rate: {\n fixed: fps_fixed,\n fps: fps_num / fps_den\n }\n },\n width,\n height,\n pixelRatio: [sar_width, sar_height]\n };\n }\n readPPS(pps) {\n const eg = new ExpGolomb(this.ebsp2rbsp(pps));\n eg.readUByte();\n eg.readUByte();\n eg.skipUEG(); // pic_parameter_set_id\n eg.skipUEG(); // seq_parameter_set_id\n eg.skipBits(2); // dependent_slice_segments_enabled_flag, output_flag_present_flag\n eg.skipBits(3); // num_extra_slice_header_bits\n eg.skipBits(2); // sign_data_hiding_enabled_flag, cabac_init_present_flag\n eg.skipUEG();\n eg.skipUEG();\n eg.skipEG(); // init_qp_minus26\n eg.skipBits(2); // constrained_intra_pred_flag, transform_skip_enabled_flag\n const cu_qp_delta_enabled_flag = eg.readBoolean();\n if (cu_qp_delta_enabled_flag) {\n eg.skipUEG();\n }\n eg.skipEG(); // cb_qp_offset\n eg.skipEG(); // cr_qp_offset\n eg.skipBits(4); // pps_slice_chroma_qp_offsets_present_flag, weighted_pred_flag, weighted_bipred_flag, transquant_bypass_enabled_flag\n const tiles_enabled_flag = eg.readBoolean();\n const entropy_coding_sync_enabled_flag = eg.readBoolean();\n let parallelismType = 1; // slice-based parallel decoding\n if (entropy_coding_sync_enabled_flag && tiles_enabled_flag) {\n parallelismType = 0; // mixed-type parallel decoding\n } else if (entropy_coding_sync_enabled_flag) {\n parallelismType = 3; // wavefront-based parallel decoding\n } else if (tiles_enabled_flag) {\n parallelismType = 2; // tile-based parallel decoding\n }\n return {\n parallelismType\n };\n }\n matchSPS(sps1, sps2) {\n // compare without headers and VPS related params\n return String.fromCharCode.apply(null, sps1).substr(3) === String.fromCharCode.apply(null, sps2).substr(3);\n }\n}\n\nconst PACKET_LENGTH = 188;\nclass TSDemuxer {\n constructor(observer, config, typeSupported, logger) {\n this.logger = void 0;\n this.observer = void 0;\n this.config = void 0;\n this.typeSupported = void 0;\n this.sampleAes = null;\n this.pmtParsed = false;\n this.audioCodec = void 0;\n this.videoCodec = void 0;\n this._pmtId = -1;\n this._videoTrack = void 0;\n this._audioTrack = void 0;\n this._id3Track = void 0;\n this._txtTrack = void 0;\n this.aacOverFlow = null;\n this.remainderData = null;\n this.videoParser = void 0;\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.logger = logger;\n this.videoParser = null;\n }\n static probe(data, logger) {\n const syncOffset = TSDemuxer.syncOffset(data);\n if (syncOffset > 0) {\n logger.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}`);\n }\n return syncOffset !== -1;\n }\n static syncOffset(data) {\n const length = data.length;\n let scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;\n let i = 0;\n while (i < scanwindow) {\n // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47\n let foundPat = false;\n let packetStart = -1;\n let tsPackets = 0;\n for (let j = i; j < length; j += PACKET_LENGTH) {\n if (data[j] === 0x47 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)) {\n tsPackets++;\n if (packetStart === -1) {\n packetStart = j;\n // First sync word found at offset, increase scan length (#5251)\n if (packetStart !== 0) {\n scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;\n }\n }\n if (!foundPat) {\n foundPat = parsePID(data, j) === 0;\n }\n // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)\n if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {\n return packetStart;\n }\n } else if (tsPackets) {\n // Exit if sync word found, but does not contain contiguous packets\n return -1;\n } else {\n break;\n }\n }\n i++;\n }\n return -1;\n }\n\n /**\n * Creates a track model internal to demuxer used to drive remuxing input\n */\n static createTrack(type, duration) {\n return {\n container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,\n type,\n id: RemuxerTrackIdConfig[type],\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n dropped: 0,\n duration: type === 'audio' ? duration : undefined\n };\n }\n\n /**\n * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)\n * Resets all internal track instances of the demuxer.\n */\n resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {\n this.pmtParsed = false;\n this._pmtId = -1;\n this._videoTrack = TSDemuxer.createTrack('video');\n this._videoTrack.duration = trackDuration;\n this._audioTrack = TSDemuxer.createTrack('audio', trackDuration);\n this._id3Track = TSDemuxer.createTrack('id3');\n this._txtTrack = TSDemuxer.createTrack('text');\n this._audioTrack.segmentCodec = 'aac';\n\n // flush any partial content\n this.aacOverFlow = null;\n this.remainderData = null;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n }\n resetTimeStamp() {}\n resetContiguity() {\n const {\n _audioTrack,\n _videoTrack,\n _id3Track\n } = this;\n if (_audioTrack) {\n _audioTrack.pesData = null;\n }\n if (_videoTrack) {\n _videoTrack.pesData = null;\n }\n if (_id3Track) {\n _id3Track.pesData = null;\n }\n this.aacOverFlow = null;\n this.remainderData = null;\n }\n demux(data, timeOffset, isSampleAes = false, flush = false) {\n if (!isSampleAes) {\n this.sampleAes = null;\n }\n let pes;\n const videoTrack = this._videoTrack;\n const audioTrack = this._audioTrack;\n const id3Track = this._id3Track;\n const textTrack = this._txtTrack;\n let videoPid = videoTrack.pid;\n let videoData = videoTrack.pesData;\n let audioPid = audioTrack.pid;\n let id3Pid = id3Track.pid;\n let audioData = audioTrack.pesData;\n let id3Data = id3Track.pesData;\n let unknownPID = null;\n let pmtParsed = this.pmtParsed;\n let pmtId = this._pmtId;\n let len = data.length;\n if (this.remainderData) {\n data = appendUint8Array(this.remainderData, data);\n len = data.length;\n this.remainderData = null;\n }\n if (len < PACKET_LENGTH && !flush) {\n this.remainderData = data;\n return {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack\n };\n }\n const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));\n len -= (len - syncOffset) % PACKET_LENGTH;\n if (len < data.byteLength && !flush) {\n this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);\n }\n\n // loop through TS packets\n let tsPacketErrors = 0;\n for (let start = syncOffset; start < len; start += PACKET_LENGTH) {\n if (data[start] === 0x47) {\n const stt = !!(data[start + 1] & 0x40);\n const pid = parsePID(data, start);\n const atf = (data[start + 3] & 0x30) >> 4;\n\n // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n let offset;\n if (atf > 1) {\n offset = start + 5 + data[start + 4];\n // continue if there is only adaptation field\n if (offset === start + PACKET_LENGTH) {\n continue;\n }\n } else {\n offset = start + 4;\n }\n switch (pid) {\n case videoPid:\n if (stt) {\n if (videoData && (pes = parsePES(videoData, this.logger))) {\n if (this.videoParser === null) {\n switch (videoTrack.segmentCodec) {\n case 'avc':\n this.videoParser = new AvcVideoParser();\n break;\n case 'hevc':\n {\n this.videoParser = new HevcVideoParser();\n }\n break;\n }\n }\n if (this.videoParser !== null) {\n this.videoParser.parsePES(videoTrack, textTrack, pes, false);\n }\n }\n videoData = {\n data: [],\n size: 0\n };\n }\n if (videoData) {\n videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));\n videoData.size += start + PACKET_LENGTH - offset;\n }\n break;\n case audioPid:\n if (stt) {\n if (audioData && (pes = parsePES(audioData, this.logger))) {\n switch (audioTrack.segmentCodec) {\n case 'aac':\n this.parseAACPES(audioTrack, pes);\n break;\n case 'mp3':\n this.parseMPEGPES(audioTrack, pes);\n break;\n case 'ac3':\n {\n this.parseAC3PES(audioTrack, pes);\n }\n break;\n }\n }\n audioData = {\n data: [],\n size: 0\n };\n }\n if (audioData) {\n audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));\n audioData.size += start + PACKET_LENGTH - offset;\n }\n break;\n case id3Pid:\n if (stt) {\n if (id3Data && (pes = parsePES(id3Data, this.logger))) {\n this.parseID3PES(id3Track, pes);\n }\n id3Data = {\n data: [],\n size: 0\n };\n }\n if (id3Data) {\n id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));\n id3Data.size += start + PACKET_LENGTH - offset;\n }\n break;\n case 0:\n if (stt) {\n offset += data[offset] + 1;\n }\n pmtId = this._pmtId = parsePAT(data, offset);\n // this.logger.log('PMT PID:' + this._pmtId);\n break;\n case pmtId:\n {\n if (stt) {\n offset += data[offset] + 1;\n }\n const parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer, this.logger);\n\n // only update track id if track PID found while parsing PMT\n // this is to avoid resetting the PID to -1 in case\n // track PID transiently disappears from the stream\n // this could happen in case of transient missing audio samples for example\n // NOTE this is only the PID of the track as found in TS,\n // but we are not using this for MP4 track IDs.\n videoPid = parsedPIDs.videoPid;\n if (videoPid > 0) {\n videoTrack.pid = videoPid;\n videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;\n }\n audioPid = parsedPIDs.audioPid;\n if (audioPid > 0) {\n audioTrack.pid = audioPid;\n audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;\n }\n id3Pid = parsedPIDs.id3Pid;\n if (id3Pid > 0) {\n id3Track.pid = id3Pid;\n }\n if (unknownPID !== null && !pmtParsed) {\n this.logger.warn(`MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`);\n unknownPID = null;\n // we set it to -188, the += 188 in the for loop will reset start to 0\n start = syncOffset - 188;\n }\n pmtParsed = this.pmtParsed = true;\n break;\n }\n case 0x11:\n case 0x1fff:\n break;\n default:\n unknownPID = pid;\n break;\n }\n } else {\n tsPacketErrors++;\n }\n }\n if (tsPacketErrors > 0) {\n emitParsingError(this.observer, new Error(`Found ${tsPacketErrors} TS packet/s that do not start with 0x47`), undefined, this.logger);\n }\n videoTrack.pesData = videoData;\n audioTrack.pesData = audioData;\n id3Track.pesData = id3Data;\n const demuxResult = {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack\n };\n if (flush) {\n this.extractRemainingSamples(demuxResult);\n }\n return demuxResult;\n }\n flush() {\n const {\n remainderData\n } = this;\n this.remainderData = null;\n let result;\n if (remainderData) {\n result = this.demux(remainderData, -1, false, true);\n } else {\n result = {\n videoTrack: this._videoTrack,\n audioTrack: this._audioTrack,\n id3Track: this._id3Track,\n textTrack: this._txtTrack\n };\n }\n this.extractRemainingSamples(result);\n if (this.sampleAes) {\n return this.decrypt(result, this.sampleAes);\n }\n return result;\n }\n extractRemainingSamples(demuxResult) {\n const {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack\n } = demuxResult;\n const videoData = videoTrack.pesData;\n const audioData = audioTrack.pesData;\n const id3Data = id3Track.pesData;\n // try to parse last PES packets\n let pes;\n if (videoData && (pes = parsePES(videoData, this.logger))) {\n if (this.videoParser === null) {\n switch (videoTrack.segmentCodec) {\n case 'avc':\n this.videoParser = new AvcVideoParser();\n break;\n case 'hevc':\n {\n this.videoParser = new HevcVideoParser();\n }\n break;\n }\n }\n if (this.videoParser !== null) {\n this.videoParser.parsePES(videoTrack, textTrack, pes, true);\n videoTrack.pesData = null;\n }\n } else {\n // either avcData null or PES truncated, keep it for next frag parsing\n videoTrack.pesData = videoData;\n }\n if (audioData && (pes = parsePES(audioData, this.logger))) {\n switch (audioTrack.segmentCodec) {\n case 'aac':\n this.parseAACPES(audioTrack, pes);\n break;\n case 'mp3':\n this.parseMPEGPES(audioTrack, pes);\n break;\n case 'ac3':\n {\n this.parseAC3PES(audioTrack, pes);\n }\n break;\n }\n audioTrack.pesData = null;\n } else {\n if (audioData != null && audioData.size) {\n this.logger.log('last AAC PES packet truncated,might overlap between fragments');\n }\n\n // either audioData null or PES truncated, keep it for next frag parsing\n audioTrack.pesData = audioData;\n }\n if (id3Data && (pes = parsePES(id3Data, this.logger))) {\n this.parseID3PES(id3Track, pes);\n id3Track.pesData = null;\n } else {\n // either id3Data null or PES truncated, keep it for next frag parsing\n id3Track.pesData = id3Data;\n }\n }\n demuxSampleAes(data, keyData, timeOffset) {\n const demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);\n const sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);\n return this.decrypt(demuxResult, sampleAes);\n }\n decrypt(demuxResult, sampleAes) {\n return new Promise(resolve => {\n const {\n audioTrack,\n videoTrack\n } = demuxResult;\n if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {\n sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {\n if (videoTrack.samples) {\n sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {\n resolve(demuxResult);\n });\n } else {\n resolve(demuxResult);\n }\n });\n } else if (videoTrack.samples) {\n sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {\n resolve(demuxResult);\n });\n }\n });\n }\n destroy() {\n if (this.observer) {\n this.observer.removeAllListeners();\n }\n // @ts-ignore\n this.config = this.logger = this.observer = null;\n this.aacOverFlow = this.videoParser = this.remainderData = this.sampleAes = null;\n this._videoTrack = this._audioTrack = this._id3Track = this._txtTrack = undefined;\n }\n parseAACPES(track, pes) {\n let startOffset = 0;\n const aacOverFlow = this.aacOverFlow;\n let data = pes.data;\n if (aacOverFlow) {\n this.aacOverFlow = null;\n const frameMissingBytes = aacOverFlow.missing;\n const sampleLength = aacOverFlow.sample.unit.byteLength;\n // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);\n if (frameMissingBytes === -1) {\n data = appendUint8Array(aacOverFlow.sample.unit, data);\n } else {\n const frameOverflowBytes = sampleLength - frameMissingBytes;\n aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);\n track.samples.push(aacOverFlow.sample);\n startOffset = aacOverFlow.missing;\n }\n }\n // look for ADTS header (0xFFFx)\n let offset;\n let len;\n for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n if (isHeader$1(data, offset)) {\n break;\n }\n }\n // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n if (offset !== startOffset) {\n let reason;\n const recoverable = offset < len - 1;\n if (recoverable) {\n reason = `AAC PES did not start with ADTS header,offset:${offset}`;\n } else {\n reason = 'No ADTS header found in AAC PES';\n }\n emitParsingError(this.observer, new Error(reason), recoverable, this.logger);\n if (!recoverable) {\n return;\n }\n }\n initTrackConfig(track, this.observer, data, offset, this.audioCodec);\n let pts;\n if (pes.pts !== undefined) {\n pts = pes.pts;\n } else if (aacOverFlow) {\n // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n // first sample PTS should be equal to last sample PTS + frameDuration\n const frameDuration = getFrameDuration(track.samplerate);\n pts = aacOverFlow.sample.pts + frameDuration;\n } else {\n this.logger.warn('[tsdemuxer]: AAC PES unknown PTS');\n return;\n }\n\n // scan for aac samples\n let frameIndex = 0;\n let frame;\n while (offset < len) {\n frame = appendFrame$2(track, data, offset, pts, frameIndex);\n offset += frame.length;\n if (!frame.missing) {\n frameIndex++;\n for (; offset < len - 1; offset++) {\n if (isHeader$1(data, offset)) {\n break;\n }\n }\n } else {\n this.aacOverFlow = frame;\n break;\n }\n }\n }\n parseMPEGPES(track, pes) {\n const data = pes.data;\n const length = data.length;\n let frameIndex = 0;\n let offset = 0;\n const pts = pes.pts;\n if (pts === undefined) {\n this.logger.warn('[tsdemuxer]: MPEG PES unknown PTS');\n return;\n }\n while (offset < length) {\n if (isHeader(data, offset)) {\n const frame = appendFrame$1(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n frameIndex++;\n } else {\n // logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n }\n parseAC3PES(track, pes) {\n {\n const data = pes.data;\n const pts = pes.pts;\n if (pts === undefined) {\n this.logger.warn('[tsdemuxer]: AC3 PES unknown PTS');\n return;\n }\n const length = data.length;\n let frameIndex = 0;\n let offset = 0;\n let parsed;\n while (offset < length && (parsed = appendFrame(track, data, offset, pts, frameIndex++)) > 0) {\n offset += parsed;\n }\n }\n }\n parseID3PES(id3Track, pes) {\n if (pes.pts === undefined) {\n this.logger.warn('[tsdemuxer]: ID3 PES unknown PTS');\n return;\n }\n const id3Sample = _extends({}, pes, {\n type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY\n });\n id3Track.samples.push(id3Sample);\n }\n}\nfunction parsePID(data, offset) {\n // pid is a 13-bit field starting at the last bit of TS[1]\n return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];\n}\nfunction parsePAT(data, offset) {\n // skip the PSI header and parse the first PMT entry\n return (data[offset + 10] & 0x1f) << 8 | data[offset + 11];\n}\nfunction parsePMT(data, offset, typeSupported, isSampleAes, observer, logger) {\n const result = {\n audioPid: -1,\n videoPid: -1,\n id3Pid: -1,\n segmentVideoCodec: 'avc',\n segmentAudioCodec: 'aac'\n };\n const sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];\n const tableEnd = offset + 3 + sectionLength - 4;\n // to determine where the table is, we have to figure out how\n // long the program info descriptors are\n const programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];\n // advance the offset to the first entry in the mapping table\n offset += 12 + programInfoLength;\n while (offset < tableEnd) {\n const pid = parsePID(data, offset);\n const esInfoLength = (data[offset + 3] & 0x0f) << 8 | data[offset + 4];\n switch (data[offset]) {\n case 0xcf:\n // SAMPLE-AES AAC\n if (!isSampleAes) {\n logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC', logger);\n break;\n }\n /* falls through */\n case 0x0f:\n // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n // logger.log('AAC PID:' + pid);\n if (result.audioPid === -1) {\n result.audioPid = pid;\n }\n break;\n\n // Packetized metadata (ID3)\n case 0x15:\n // logger.log('ID3 PID:' + pid);\n if (result.id3Pid === -1) {\n result.id3Pid = pid;\n }\n break;\n case 0xdb:\n // SAMPLE-AES AVC\n if (!isSampleAes) {\n logEncryptedSamplesFoundInUnencryptedStream('H.264', logger);\n break;\n }\n /* falls through */\n case 0x1b:\n // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n // logger.log('AVC PID:' + pid);\n if (result.videoPid === -1) {\n result.videoPid = pid;\n }\n break;\n\n // ISO/IEC 11172-3 (MPEG-1 audio)\n // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n case 0x03:\n case 0x04:\n // logger.log('MPEG PID:' + pid);\n if (!typeSupported.mpeg && !typeSupported.mp3) {\n logger.log('MPEG audio found, not supported in this browser');\n } else if (result.audioPid === -1) {\n result.audioPid = pid;\n result.segmentAudioCodec = 'mp3';\n }\n break;\n case 0xc1:\n // SAMPLE-AES AC3\n if (!isSampleAes) {\n logEncryptedSamplesFoundInUnencryptedStream('AC-3', logger);\n break;\n }\n /* falls through */\n case 0x81:\n {\n if (!typeSupported.ac3) {\n logger.log('AC-3 audio found, not supported in this browser');\n } else if (result.audioPid === -1) {\n result.audioPid = pid;\n result.segmentAudioCodec = 'ac3';\n }\n }\n break;\n case 0x06:\n // stream_type 6 can mean a lot of different things in case of DVB.\n // We need to look at the descriptors. Right now, we're only interested\n // in AC-3 audio, so we do the descriptor parsing only when we don't have\n // an audio PID yet.\n if (result.audioPid === -1 && esInfoLength > 0) {\n let parsePos = offset + 5;\n let remaining = esInfoLength;\n while (remaining > 2) {\n const descriptorId = data[parsePos];\n switch (descriptorId) {\n case 0x6a:\n // DVB Descriptor for AC-3\n {\n if (typeSupported.ac3 !== true) {\n logger.log('AC-3 audio found, not supported in this browser for now');\n } else {\n result.audioPid = pid;\n result.segmentAudioCodec = 'ac3';\n }\n }\n break;\n }\n const descriptorLen = data[parsePos + 1] + 2;\n parsePos += descriptorLen;\n remaining -= descriptorLen;\n }\n }\n break;\n case 0xc2: // SAMPLE-AES EC3\n /* falls through */\n case 0x87:\n emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'), undefined, logger);\n return result;\n case 0x24:\n // ITU-T Rec. H.265 and ISO/IEC 23008-2 (HEVC)\n {\n if (result.videoPid === -1) {\n result.videoPid = pid;\n result.segmentVideoCodec = 'hevc';\n logger.log('HEVC in M2TS found');\n }\n }\n break;\n }\n // move to the next table entry\n // skip past the elementary stream descriptors, if present\n offset += esInfoLength + 5;\n }\n return result;\n}\nfunction emitParsingError(observer, error, levelRetry, logger) {\n logger.warn(`parsing error: ${error.message}`);\n observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n levelRetry,\n error,\n reason: error.message\n });\n}\nfunction logEncryptedSamplesFoundInUnencryptedStream(type, logger) {\n logger.log(`${type} with AES-128-CBC encryption found in unencrypted stream`);\n}\nfunction parsePES(stream, logger) {\n let i = 0;\n let frag;\n let pesLen;\n let pesHdrLen;\n let pesPts;\n let pesDts;\n const data = stream.data;\n // safety check\n if (!stream || stream.size === 0) {\n return null;\n }\n\n // we might need up to 19 bytes to read PES header\n // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n // usually only one merge is needed (and this is rare ...)\n while (data[0].length < 19 && data.length > 1) {\n data[0] = appendUint8Array(data[0], data[1]);\n data.splice(1, 1);\n }\n // retrieve PTS/DTS from first fragment\n frag = data[0];\n const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n if (pesPrefix === 1) {\n pesLen = (frag[4] << 8) + frag[5];\n // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n // minus 6 : PES header size\n if (pesLen && pesLen > stream.size - 6) {\n return null;\n }\n const pesFlags = frag[7];\n if (pesFlags & 0xc0) {\n /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n as Bitwise operators treat their operands as a sequence of 32 bits */\n pesPts = (frag[9] & 0x0e) * 536870912 +\n // 1 << 29\n (frag[10] & 0xff) * 4194304 +\n // 1 << 22\n (frag[11] & 0xfe) * 16384 +\n // 1 << 14\n (frag[12] & 0xff) * 128 +\n // 1 << 7\n (frag[13] & 0xfe) / 2;\n if (pesFlags & 0x40) {\n pesDts = (frag[14] & 0x0e) * 536870912 +\n // 1 << 29\n (frag[15] & 0xff) * 4194304 +\n // 1 << 22\n (frag[16] & 0xfe) * 16384 +\n // 1 << 14\n (frag[17] & 0xff) * 128 +\n // 1 << 7\n (frag[18] & 0xfe) / 2;\n if (pesPts - pesDts > 60 * 90000) {\n logger.warn(`${Math.round((pesPts - pesDts) / 90000)}s delta between PTS and DTS, align them`);\n pesPts = pesDts;\n }\n } else {\n pesDts = pesPts;\n }\n }\n pesHdrLen = frag[8];\n // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n let payloadStartOffset = pesHdrLen + 9;\n if (stream.size <= payloadStartOffset) {\n return null;\n }\n stream.size -= payloadStartOffset;\n // reassemble PES packet\n const pesData = new Uint8Array(stream.size);\n for (let j = 0, dataLen = data.length; j < dataLen; j++) {\n frag = data[j];\n let len = frag.byteLength;\n if (payloadStartOffset) {\n if (payloadStartOffset > len) {\n // trim full frag if PES header bigger than frag\n payloadStartOffset -= len;\n continue;\n } else {\n // trim partial frag if PES header smaller than frag\n frag = frag.subarray(payloadStartOffset);\n len -= payloadStartOffset;\n payloadStartOffset = 0;\n }\n }\n pesData.set(frag, i);\n i += len;\n }\n if (pesLen) {\n // payload size : remove PES header + PES extension\n pesLen -= pesHdrLen + 3;\n }\n return {\n data: pesData,\n pts: pesPts,\n dts: pesDts,\n len: pesLen\n };\n }\n return null;\n}\n\n/**\n * AAC helper\n */\n\nclass AAC {\n static getSilentFrame(codec, channelCount) {\n switch (codec) {\n case 'mp4a.40.2':\n if (channelCount === 1) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);\n } else if (channelCount === 2) {\n return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);\n } else if (channelCount === 3) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);\n } else if (channelCount === 4) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);\n } else if (channelCount === 5) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);\n } else if (channelCount === 6) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);\n }\n break;\n // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n default:\n if (channelCount === 1) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0:d=0.05\" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);\n } else if (channelCount === 2) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);\n } else if (channelCount === 3) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);\n }\n break;\n }\n return undefined;\n }\n}\n\n/**\n * Generate MP4 Box\n */\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\nclass MP4 {\n static init() {\n MP4.types = {\n avc1: [],\n // codingname\n avcC: [],\n hvc1: [],\n hvcC: [],\n btrt: [],\n dinf: [],\n dref: [],\n esds: [],\n ftyp: [],\n hdlr: [],\n mdat: [],\n mdhd: [],\n mdia: [],\n mfhd: [],\n minf: [],\n moof: [],\n moov: [],\n mp4a: [],\n '.mp3': [],\n dac3: [],\n 'ac-3': [],\n mvex: [],\n mvhd: [],\n pasp: [],\n sdtp: [],\n stbl: [],\n stco: [],\n stsc: [],\n stsd: [],\n stsz: [],\n stts: [],\n tfdt: [],\n tfhd: [],\n traf: [],\n trak: [],\n trun: [],\n trex: [],\n tkhd: [],\n vmhd: [],\n smhd: []\n };\n let i;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];\n }\n }\n const videoHdlr = new Uint8Array([0x00,\n // version 0\n 0x00, 0x00, 0x00,\n // flags\n 0x00, 0x00, 0x00, 0x00,\n // pre_defined\n 0x76, 0x69, 0x64, 0x65,\n // handler_type: 'vide'\n 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'\n ]);\n const audioHdlr = new Uint8Array([0x00,\n // version 0\n 0x00, 0x00, 0x00,\n // flags\n 0x00, 0x00, 0x00, 0x00,\n // pre_defined\n 0x73, 0x6f, 0x75, 0x6e,\n // handler_type: 'soun'\n 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'\n ]);\n MP4.HDLR_TYPES = {\n video: videoHdlr,\n audio: audioHdlr\n };\n const dref = new Uint8Array([0x00,\n // version 0\n 0x00, 0x00, 0x00,\n // flags\n 0x00, 0x00, 0x00, 0x01,\n // entry_count\n 0x00, 0x00, 0x00, 0x0c,\n // entry_size\n 0x75, 0x72, 0x6c, 0x20,\n // 'url' type\n 0x00,\n // version 0\n 0x00, 0x00, 0x01 // entry_flags\n ]);\n const stco = new Uint8Array([0x00,\n // version\n 0x00, 0x00, 0x00,\n // flags\n 0x00, 0x00, 0x00, 0x00 // entry_count\n ]);\n MP4.STTS = MP4.STSC = MP4.STCO = stco;\n MP4.STSZ = new Uint8Array([0x00,\n // version\n 0x00, 0x00, 0x00,\n // flags\n 0x00, 0x00, 0x00, 0x00,\n // sample_size\n 0x00, 0x00, 0x00, 0x00 // sample_count\n ]);\n MP4.VMHD = new Uint8Array([0x00,\n // version\n 0x00, 0x00, 0x01,\n // flags\n 0x00, 0x00,\n // graphicsmode\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor\n ]);\n MP4.SMHD = new Uint8Array([0x00,\n // version\n 0x00, 0x00, 0x00,\n // flags\n 0x00, 0x00,\n // balance\n 0x00, 0x00 // reserved\n ]);\n MP4.STSD = new Uint8Array([0x00,\n // version 0\n 0x00, 0x00, 0x00,\n // flags\n 0x00, 0x00, 0x00, 0x01]); // entry_count\n\n const majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n const avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n const minorVersion = new Uint8Array([0, 0, 0, 1]);\n MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);\n MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n }\n static box(type, ...payload) {\n let size = 8;\n let i = payload.length;\n const len = i;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\n const result = new Uint8Array(size);\n result[0] = size >> 24 & 0xff;\n result[1] = size >> 16 & 0xff;\n result[2] = size >> 8 & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n // copy the payload into the result\n for (i = 0, size = 8; i < len; i++) {\n // copy payload[i] array @ offset size\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n }\n static hdlr(type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n }\n static mdat(data) {\n return MP4.box(MP4.types.mdat, data);\n }\n static mdhd(timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.mdhd, new Uint8Array([0x01,\n // version 1\n 0x00, 0x00, 0x00,\n // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,\n // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,\n // modification_time\n timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,\n // timescale\n upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4,\n // 'und' language (undetermined)\n 0x00, 0x00]));\n }\n static mdia(track) {\n return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale || 0, track.duration || 0), MP4.hdlr(track.type), MP4.minf(track));\n }\n static mfhd(sequenceNumber) {\n return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,\n // flags\n sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number\n ]));\n }\n static minf(track) {\n if (track.type === 'audio') {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));\n } else {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));\n }\n }\n static moof(sn, baseMediaDecodeTime, track) {\n return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));\n }\n static moov(tracks) {\n let i = tracks.length;\n const boxes = [];\n while (i--) {\n boxes[i] = MP4.trak(tracks[i]);\n }\n return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale || 0, tracks[0].duration || 0)].concat(boxes).concat(MP4.mvex(tracks)));\n }\n static mvex(tracks) {\n let i = tracks.length;\n const boxes = [];\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);\n }\n static mvhd(timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n const bytes = new Uint8Array([0x01,\n // version 1\n 0x00, 0x00, 0x00,\n // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,\n // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,\n // modification_time\n timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,\n // timescale\n upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00,\n // 1.0 rate\n 0x01, 0x00,\n // 1.0 volume\n 0x00, 0x00,\n // reserved\n 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,\n // transformation: unity matrix\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n // pre_defined\n 0xff, 0xff, 0xff, 0xff // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n }\n static sdtp(track) {\n const samples = track.samples || [];\n const bytes = new Uint8Array(4 + samples.length);\n let i;\n let flags;\n // leave the full box header (4 bytes) all zero\n // write the sample table\n for (i = 0; i < samples.length; i++) {\n flags = samples[i].flags;\n bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;\n }\n return MP4.box(MP4.types.sdtp, bytes);\n }\n static stbl(track) {\n return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));\n }\n static avc1(track) {\n let sps = [];\n let pps = [];\n let i;\n let data;\n let len;\n // assemble the SPSs\n\n for (i = 0; i < track.sps.length; i++) {\n data = track.sps[i];\n len = data.byteLength;\n sps.push(len >>> 8 & 0xff);\n sps.push(len & 0xff);\n\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\n }\n\n // assemble the PPSs\n for (i = 0; i < track.pps.length; i++) {\n data = track.pps[i];\n len = data.byteLength;\n pps.push(len >>> 8 & 0xff);\n pps.push(len & 0xff);\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n const avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01,\n // version\n sps[3],\n // profile\n sps[4],\n // profile compat\n sps[5],\n // level\n 0xfc | 3,\n // lengthSizeMinusOne, hard-coded to 4 bytes\n 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets\n ].concat(sps).concat([track.pps.length // numOfPictureParameterSets\n ]).concat(pps))); // \"PPS\"\n const width = track.width;\n const height = track.height;\n const hSpacing = track.pixelRatio[0];\n const vSpacing = track.pixelRatio[1];\n return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x01,\n // data_reference_index\n 0x00, 0x00,\n // pre_defined\n 0x00, 0x00,\n // reserved\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n // pre_defined\n width >> 8 & 0xff, width & 0xff,\n // width\n height >> 8 & 0xff, height & 0xff,\n // height\n 0x00, 0x48, 0x00, 0x00,\n // horizresolution\n 0x00, 0x48, 0x00, 0x00,\n // vertresolution\n 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x01,\n // frame_count\n 0x12, 0x64, 0x61, 0x69, 0x6c,\n // dailymotion/hls.js\n 0x79, 0x6d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x68, 0x6c, 0x73, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n // compressorname\n 0x00, 0x18,\n // depth = 24\n 0x11, 0x11]),\n // pre_defined = -1\n avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,\n // bufferSizeDB\n 0x00, 0x2d, 0xc6, 0xc0,\n // maxBitrate\n 0x00, 0x2d, 0xc6, 0xc0])),\n // avgBitrate\n MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,\n // hSpacing\n hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,\n // vSpacing\n vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));\n }\n static esds(track) {\n const config = track.config;\n return new Uint8Array([0x00,\n // version 0\n 0x00, 0x00, 0x00,\n // flags\n\n 0x03,\n // descriptor_type\n 0x19,\n // length\n\n 0x00, 0x01,\n // es_id\n\n 0x00,\n // stream_priority\n\n 0x04,\n // descriptor_type\n 0x11,\n // length\n 0x40,\n // codec : mpeg4_audio\n 0x15,\n // stream_type\n 0x00, 0x00, 0x00,\n // buffer_size\n 0x00, 0x00, 0x00, 0x00,\n // maxBitrate\n 0x00, 0x00, 0x00, 0x00,\n // avgBitrate\n\n 0x05,\n // descriptor_type\n 0x02,\n // length\n ...config, 0x06, 0x01, 0x02 // GASpecificConfig)); // length + audio config descriptor\n ]);\n }\n static audioStsd(track) {\n const samplerate = track.samplerate || 0;\n return new Uint8Array([0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x01,\n // data_reference_index\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x00, track.channelCount || 0,\n // channelcount\n 0x00, 0x10,\n // sampleSize:16bits\n 0x00, 0x00, 0x00, 0x00,\n // reserved2\n samplerate >> 8 & 0xff, samplerate & 0xff,\n //\n 0x00, 0x00]);\n }\n static mp4a(track) {\n return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));\n }\n static mp3(track) {\n return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));\n }\n static ac3(track) {\n return MP4.box(MP4.types['ac-3'], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));\n }\n static stsd(track) {\n const {\n segmentCodec\n } = track;\n if (track.type === 'audio') {\n if (segmentCodec === 'aac') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));\n }\n if (segmentCodec === 'ac3' && track.config) {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));\n }\n if (segmentCodec === 'mp3' && track.codec === 'mp3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));\n }\n } else {\n if (track.pps && track.sps) {\n if (segmentCodec === 'avc') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n }\n if (segmentCodec === 'hevc' && track.vps) {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.hvc1(track));\n }\n } else {\n throw new Error(`video track missing pps or sps`);\n }\n }\n throw new Error(`unsupported ${track.type} segment codec (${segmentCodec}/${track.codec})`);\n }\n static tkhd(track) {\n const id = track.id;\n const duration = (track.duration || 0) * (track.timescale || 0);\n const width = track.width || 0;\n const height = track.height || 0;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.tkhd, new Uint8Array([0x01,\n // version 1\n 0x00, 0x00, 0x07,\n // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,\n // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,\n // modification_time\n id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,\n // track_ID\n 0x00, 0x00, 0x00, 0x00,\n // reserved\n upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x00,\n // layer\n 0x00, 0x00,\n // alternate_group\n 0x00, 0x00,\n // non-audio track volume\n 0x00, 0x00,\n // reserved\n 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,\n // transformation: unity matrix\n width >> 8 & 0xff, width & 0xff, 0x00, 0x00,\n // width\n height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height\n ]));\n }\n static traf(track, baseMediaDecodeTime) {\n const sampleDependencyTable = MP4.sdtp(track);\n const id = track.id;\n const upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n const lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00,\n // version 0\n 0x00, 0x00, 0x00,\n // flags\n id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID\n ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01,\n // version 1\n 0x00, 0x00, 0x00,\n // flags\n upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0xff, upperWordBaseMediaDecodeTime >> 8 & 0xff, upperWordBaseMediaDecodeTime & 0xff, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0xff, lowerWordBaseMediaDecodeTime >> 8 & 0xff, lowerWordBaseMediaDecodeTime & 0xff])), MP4.trun(track, sampleDependencyTable.length + 16 +\n // tfhd\n 20 +\n // tfdt\n 8 +\n // traf header\n 16 +\n // mfhd\n 8 +\n // moof header\n 8),\n // mdat header\n sampleDependencyTable);\n }\n\n /**\n * Generate a track box.\n * @param track a track definition\n */\n static trak(track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n }\n static trex(track) {\n const id = track.id;\n return MP4.box(MP4.types.trex, new Uint8Array([0x00,\n // version 0\n 0x00, 0x00, 0x00,\n // flags\n id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,\n // track_ID\n 0x00, 0x00, 0x00, 0x01,\n // default_sample_description_index\n 0x00, 0x00, 0x00, 0x00,\n // default_sample_duration\n 0x00, 0x00, 0x00, 0x00,\n // default_sample_size\n 0x00, 0x01, 0x00, 0x01 // default_sample_flags\n ]));\n }\n static trun(track, offset) {\n const samples = track.samples || [];\n const len = samples.length;\n const arraylen = 12 + 16 * len;\n const array = new Uint8Array(arraylen);\n let i;\n let sample;\n let duration;\n let size;\n let flags;\n let cts;\n offset += 8 + arraylen;\n array.set([track.type === 'video' ? 0x01 : 0x00,\n // version 1 for video with signed-int sample_composition_time_offset\n 0x00, 0x0f, 0x01,\n // flags\n len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff,\n // sample_count\n offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset\n ], 0);\n for (i = 0; i < len; i++) {\n sample = samples[i];\n duration = sample.duration;\n size = sample.size;\n flags = sample.flags;\n cts = sample.cts;\n array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff,\n // sample_duration\n size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff,\n // sample_size\n flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f,\n // sample_flags\n cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset\n ], 12 + 16 * i);\n }\n return MP4.box(MP4.types.trun, array);\n }\n static initSegment(tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n const movie = MP4.moov(tracks);\n const result = appendUint8Array(MP4.FTYP, movie);\n return result;\n }\n static hvc1(track) {\n const ps = track.params;\n const units = [track.vps, track.sps, track.pps];\n const NALuLengthSize = 4;\n const config = new Uint8Array([0x01, ps.general_profile_space << 6 | (ps.general_tier_flag ? 32 : 0) | ps.general_profile_idc, ps.general_profile_compatibility_flags[0], ps.general_profile_compatibility_flags[1], ps.general_profile_compatibility_flags[2], ps.general_profile_compatibility_flags[3], ps.general_constraint_indicator_flags[0], ps.general_constraint_indicator_flags[1], ps.general_constraint_indicator_flags[2], ps.general_constraint_indicator_flags[3], ps.general_constraint_indicator_flags[4], ps.general_constraint_indicator_flags[5], ps.general_level_idc, 240 | ps.min_spatial_segmentation_idc >> 8, 255 & ps.min_spatial_segmentation_idc, 252 | ps.parallelismType, 252 | ps.chroma_format_idc, 248 | ps.bit_depth_luma_minus8, 248 | ps.bit_depth_chroma_minus8, 0x00, parseInt(ps.frame_rate.fps), NALuLengthSize - 1 | ps.temporal_id_nested << 2 | ps.num_temporal_layers << 3 | (ps.frame_rate.fixed ? 64 : 0), units.length]);\n\n // compute hvcC size in bytes\n let length = config.length;\n for (let i = 0; i < units.length; i += 1) {\n length += 3;\n for (let j = 0; j < units[i].length; j += 1) {\n length += 2 + units[i][j].length;\n }\n }\n const hvcC = new Uint8Array(length);\n hvcC.set(config, 0);\n length = config.length;\n // append parameter set units: one vps, one or more sps and pps\n const iMax = units.length - 1;\n for (let i = 0; i < units.length; i += 1) {\n hvcC.set(new Uint8Array([32 + i | (i === iMax ? 128 : 0), 0x00, units[i].length]), length);\n length += 3;\n for (let j = 0; j < units[i].length; j += 1) {\n hvcC.set(new Uint8Array([units[i][j].length >> 8, units[i][j].length & 255]), length);\n length += 2;\n hvcC.set(units[i][j], length);\n length += units[i][j].length;\n }\n }\n const hvcc = MP4.box(MP4.types.hvcC, hvcC);\n const width = track.width;\n const height = track.height;\n const hSpacing = track.pixelRatio[0];\n const vSpacing = track.pixelRatio[1];\n return MP4.box(MP4.types.hvc1, new Uint8Array([0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x01,\n // data_reference_index\n 0x00, 0x00,\n // pre_defined\n 0x00, 0x00,\n // reserved\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n // pre_defined\n width >> 8 & 0xff, width & 0xff,\n // width\n height >> 8 & 0xff, height & 0xff,\n // height\n 0x00, 0x48, 0x00, 0x00,\n // horizresolution\n 0x00, 0x48, 0x00, 0x00,\n // vertresolution\n 0x00, 0x00, 0x00, 0x00,\n // reserved\n 0x00, 0x01,\n // frame_count\n 0x12, 0x64, 0x61, 0x69, 0x6c,\n // dailymotion/hls.js\n 0x79, 0x6d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x68, 0x6c, 0x73, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n // compressorname\n 0x00, 0x18,\n // depth = 24\n 0x11, 0x11]),\n // pre_defined = -1\n hvcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,\n // bufferSizeDB\n 0x00, 0x2d, 0xc6, 0xc0,\n // maxBitrate\n 0x00, 0x2d, 0xc6, 0xc0])),\n // avgBitrate\n MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,\n // hSpacing\n hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,\n // vSpacing\n vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));\n }\n}\nMP4.types = void 0;\nMP4.HDLR_TYPES = void 0;\nMP4.STTS = void 0;\nMP4.STSC = void 0;\nMP4.STCO = void 0;\nMP4.STSZ = void 0;\nMP4.VMHD = void 0;\nMP4.SMHD = void 0;\nMP4.STSD = void 0;\nMP4.FTYP = void 0;\nMP4.DINF = void 0;\n\nconst MPEG_TS_CLOCK_FREQ_HZ = 90000;\nfunction toTimescaleFromBase(baseTime, destScale, srcBase = 1, round = false) {\n const result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`\n return round ? Math.round(result) : result;\n}\nfunction toTimescaleFromScale(baseTime, destScale, srcScale = 1, round = false) {\n return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);\n}\nfunction toMsFromMpegTsClock(baseTime, round = false) {\n return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);\n}\nfunction toMpegTsClockFromTimescale(baseTime, srcScale = 1) {\n return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);\n}\n\nconst MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds\nconst AAC_SAMPLES_PER_FRAME = 1024;\nconst MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;\nconst AC3_SAMPLES_PER_FRAME = 1536;\nlet chromeVersion = null;\nlet safariWebkitVersion = null;\nfunction createMp4Sample(isKeyframe, duration, size, cts) {\n return {\n duration,\n size,\n cts,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: isKeyframe ? 2 : 1,\n isNonSync: isKeyframe ? 0 : 1\n }\n };\n}\nclass MP4Remuxer {\n constructor(observer, config, typeSupported, logger) {\n this.logger = void 0;\n this.observer = void 0;\n this.config = void 0;\n this.typeSupported = void 0;\n this.ISGenerated = false;\n this._initPTS = null;\n this._initDTS = null;\n this.nextAvcDts = null;\n this.nextAudioPts = null;\n this.videoSampleDuration = null;\n this.isAudioContiguous = false;\n this.isVideoContiguous = false;\n this.videoTrackConfig = void 0;\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.logger = logger;\n this.ISGenerated = false;\n if (chromeVersion === null) {\n const userAgent = navigator.userAgent || '';\n const result = userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\n if (safariWebkitVersion === null) {\n const result = navigator.userAgent.match(/Safari\\/(\\d+)/i);\n safariWebkitVersion = result ? parseInt(result[1]) : 0;\n }\n }\n destroy() {\n // @ts-ignore\n this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;\n }\n resetTimeStamp(defaultTimeStamp) {\n this.logger.log('[mp4-remuxer]: initPTS & initDTS reset');\n this._initPTS = this._initDTS = defaultTimeStamp;\n }\n resetNextTimestamp() {\n this.logger.log('[mp4-remuxer]: reset next timestamp');\n this.isVideoContiguous = false;\n this.isAudioContiguous = false;\n }\n resetInitSegment() {\n this.logger.log('[mp4-remuxer]: ISGenerated flag reset');\n this.ISGenerated = false;\n this.videoTrackConfig = undefined;\n }\n getVideoStartPts(videoSamples) {\n // Get the minimum PTS value relative to the first sample's PTS, normalized for 33-bit wrapping\n let rolloverDetected = false;\n const firstPts = videoSamples[0].pts;\n const startPTS = videoSamples.reduce((minPTS, sample) => {\n let pts = sample.pts;\n let delta = pts - minPTS;\n if (delta < -4294967296) {\n // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation\n rolloverDetected = true;\n pts = normalizePts(pts, firstPts);\n delta = pts - minPTS;\n }\n if (delta > 0) {\n return minPTS;\n }\n return pts;\n }, firstPts);\n if (rolloverDetected) {\n this.logger.debug('PTS rollover detected');\n }\n return startPTS;\n }\n remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {\n let video;\n let audio;\n let initSegment;\n let text;\n let id3;\n let independent;\n let audioTimeOffset = timeOffset;\n let videoTimeOffset = timeOffset;\n\n // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.\n // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the \"pid\"\n // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.\n // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),\n // then we can remux one track without waiting for the other.\n const hasAudio = audioTrack.pid > -1;\n const hasVideo = videoTrack.pid > -1;\n const length = videoTrack.samples.length;\n const enoughAudioSamples = audioTrack.samples.length > 0;\n const enoughVideoSamples = flush && length > 0 || length > 1;\n const canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;\n if (canRemuxAvc) {\n if (this.ISGenerated) {\n var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;\n const config = this.videoTrackConfig;\n if (config && (videoTrack.width !== config.width || videoTrack.height !== config.height || ((_videoTrack$pixelRati = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati[0]) !== ((_config$pixelRatio = config.pixelRatio) == null ? void 0 : _config$pixelRatio[0]) || ((_videoTrack$pixelRati2 = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati2[1]) !== ((_config$pixelRatio2 = config.pixelRatio) == null ? void 0 : _config$pixelRatio2[1])) || !config && enoughVideoSamples || this.nextAudioPts === null && enoughAudioSamples) {\n this.resetInitSegment();\n }\n }\n if (!this.ISGenerated) {\n initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);\n }\n const isVideoContiguous = this.isVideoContiguous;\n let firstKeyFrameIndex = -1;\n let firstKeyFramePTS;\n if (enoughVideoSamples) {\n firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);\n if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {\n independent = true;\n if (firstKeyFrameIndex > 0) {\n this.logger.warn(`[mp4-remuxer]: Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`);\n const startPTS = this.getVideoStartPts(videoTrack.samples);\n videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);\n videoTrack.dropped += firstKeyFrameIndex;\n videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;\n firstKeyFramePTS = videoTimeOffset;\n } else if (firstKeyFrameIndex === -1) {\n this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${length} video samples`);\n independent = false;\n }\n }\n }\n if (this.ISGenerated) {\n if (enoughAudioSamples && enoughVideoSamples) {\n // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)\n // if first audio DTS is not aligned with first video DTS then we need to take that into account\n // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small\n // drift between audio and video streams\n const startPTS = this.getVideoStartPts(videoTrack.samples);\n const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;\n const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;\n audioTimeOffset += Math.max(0, audiovideoTimestampDelta);\n videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);\n }\n\n // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.\n if (enoughAudioSamples) {\n // if initSegment was generated without audio samples, regenerate it again\n if (!audioTrack.samplerate) {\n this.logger.warn('[mp4-remuxer]: regenerate InitSegment as audio detected');\n initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);\n }\n audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : undefined);\n if (enoughVideoSamples) {\n const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;\n // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.inputTimeScale) {\n this.logger.warn('[mp4-remuxer]: regenerate InitSegment as video detected');\n initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);\n }\n video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);\n }\n } else if (enoughVideoSamples) {\n video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);\n }\n if (video) {\n video.firstKeyFrame = firstKeyFrameIndex;\n video.independent = firstKeyFrameIndex !== -1;\n video.firstKeyFramePTS = firstKeyFramePTS;\n }\n }\n }\n\n // Allow ID3 and text to remux, even if more audio/video samples are required\n if (this.ISGenerated && this._initPTS && this._initDTS) {\n if (id3Track.samples.length) {\n id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);\n }\n if (textTrack.samples.length) {\n text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);\n }\n }\n return {\n audio,\n video,\n initSegment,\n independent,\n text,\n id3\n };\n }\n generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {\n const audioSamples = audioTrack.samples;\n const videoSamples = videoTrack.samples;\n const typeSupported = this.typeSupported;\n const tracks = {};\n const _initPTS = this._initPTS;\n let computePTSDTS = !_initPTS || accurateTimeOffset;\n let container = 'audio/mp4';\n let initPTS;\n let initDTS;\n let timescale;\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n if (audioTrack.config && audioSamples.length) {\n // let's use audio sampling rate as MP4 time scale.\n // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n // using audio sampling rate here helps having an integer MP4 frame duration\n // this avoids potential rounding issue and AV sync issue\n audioTrack.timescale = audioTrack.samplerate;\n switch (audioTrack.segmentCodec) {\n case 'mp3':\n if (typeSupported.mpeg) {\n // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) {\n // Firefox\n audioTrack.codec = 'mp3';\n }\n break;\n case 'ac3':\n audioTrack.codec = 'ac-3';\n break;\n }\n tracks.audio = {\n id: 'audio',\n container: container,\n codec: audioTrack.codec,\n initSegment: audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),\n metadata: {\n channelCount: audioTrack.channelCount\n }\n };\n if (computePTSDTS) {\n timescale = audioTrack.inputTimeScale;\n if (!_initPTS || timescale !== _initPTS.timescale) {\n // remember first PTS of this demuxing context. for audio, PTS = DTS\n initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);\n } else {\n computePTSDTS = false;\n }\n }\n }\n if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n // let's use input time scale as MP4 video timescale\n // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n videoTrack.timescale = videoTrack.inputTimeScale;\n tracks.video = {\n id: 'main',\n container: 'video/mp4',\n codec: videoTrack.codec,\n initSegment: MP4.initSegment([videoTrack]),\n metadata: {\n width: videoTrack.width,\n height: videoTrack.height\n }\n };\n if (computePTSDTS) {\n timescale = videoTrack.inputTimeScale;\n if (!_initPTS || timescale !== _initPTS.timescale) {\n const startPTS = this.getVideoStartPts(videoSamples);\n const startOffset = Math.round(timescale * timeOffset);\n initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);\n initPTS = Math.min(initPTS, startPTS - startOffset);\n } else {\n computePTSDTS = false;\n }\n }\n this.videoTrackConfig = {\n width: videoTrack.width,\n height: videoTrack.height,\n pixelRatio: videoTrack.pixelRatio\n };\n }\n if (Object.keys(tracks).length) {\n this.ISGenerated = true;\n if (computePTSDTS) {\n this._initPTS = {\n baseTime: initPTS,\n timescale: timescale\n };\n this._initDTS = {\n baseTime: initDTS,\n timescale: timescale\n };\n } else {\n initPTS = timescale = undefined;\n }\n return {\n tracks,\n initPTS,\n timescale\n };\n }\n }\n remuxVideo(track, timeOffset, contiguous, audioTrackLength) {\n const timeScale = track.inputTimeScale;\n const inputSamples = track.samples;\n const outputSamples = [];\n const nbSamples = inputSamples.length;\n const initPTS = this._initPTS;\n let nextAvcDts = this.nextAvcDts;\n let offset = 8;\n let mp4SampleDuration = this.videoSampleDuration;\n let firstDTS;\n let lastDTS;\n let minPTS = Number.POSITIVE_INFINITY;\n let maxPTS = Number.NEGATIVE_INFINITY;\n let sortSamples = false;\n\n // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n if (!contiguous || nextAvcDts === null) {\n const pts = timeOffset * timeScale;\n const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);\n if (chromeVersion && nextAvcDts !== null && Math.abs(pts - cts - nextAvcDts) < 15000) {\n // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome\n contiguous = true;\n } else {\n // if not contiguous, let's use target timeOffset\n nextAvcDts = pts - cts;\n }\n }\n\n // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n const initTime = initPTS.baseTime * timeScale / initPTS.timescale;\n for (let i = 0; i < nbSamples; i++) {\n const sample = inputSamples[i];\n sample.pts = normalizePts(sample.pts - initTime, nextAvcDts);\n sample.dts = normalizePts(sample.dts - initTime, nextAvcDts);\n if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {\n sortSamples = true;\n }\n }\n\n // sort video samples by DTS then PTS then demux id order\n if (sortSamples) {\n inputSamples.sort(function (a, b) {\n const deltadts = a.dts - b.dts;\n const deltapts = a.pts - b.pts;\n return deltadts || deltapts;\n });\n }\n\n // Get first/last DTS\n firstDTS = inputSamples[0].dts;\n lastDTS = inputSamples[inputSamples.length - 1].dts;\n\n // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n // set this constant duration as being the avg delta between consecutive DTS.\n const inputDuration = lastDTS - firstDTS;\n const averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;\n\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)\n const delta = firstDTS - nextAvcDts;\n const foundHole = delta > averageSampleDuration;\n const foundOverlap = delta < -1;\n if (foundHole || foundOverlap) {\n if (foundHole) {\n this.logger.warn(`${(track.segmentCodec || '').toUpperCase()}: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected at ${timeOffset.toFixed(3)}`);\n } else {\n this.logger.warn(`${(track.segmentCodec || '').toUpperCase()}: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected at ${timeOffset.toFixed(3)}`);\n }\n if (!foundOverlap || nextAvcDts >= inputSamples[0].pts || chromeVersion) {\n firstDTS = nextAvcDts;\n const firstPTS = inputSamples[0].pts - delta;\n if (foundHole) {\n inputSamples[0].dts = firstDTS;\n inputSamples[0].pts = firstPTS;\n } else {\n let isPTSOrderRetained = true;\n for (let i = 0; i < inputSamples.length; i++) {\n if (inputSamples[i].dts > firstPTS && isPTSOrderRetained) {\n break;\n }\n const prevPTS = inputSamples[i].pts;\n inputSamples[i].dts -= delta;\n inputSamples[i].pts -= delta;\n\n // check to see if this sample's PTS order has changed\n // relative to the next one\n if (i < inputSamples.length - 1) {\n const nextSamplePTS = inputSamples[i + 1].pts;\n const currentSamplePTS = inputSamples[i].pts;\n const currentOrder = nextSamplePTS <= currentSamplePTS;\n const prevOrder = nextSamplePTS <= prevPTS;\n isPTSOrderRetained = currentOrder == prevOrder;\n }\n }\n }\n this.logger.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);\n }\n }\n }\n firstDTS = Math.max(0, firstDTS);\n let nbNalu = 0;\n let naluLen = 0;\n let dtsStep = firstDTS;\n for (let i = 0; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n const sample = inputSamples[i];\n const units = sample.units;\n const nbUnits = units.length;\n let sampleLen = 0;\n for (let j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\n naluLen += sampleLen;\n nbNalu += nbUnits;\n sample.length = sampleLen;\n\n // ensure sample monotonic DTS\n if (sample.dts < dtsStep) {\n sample.dts = dtsStep;\n dtsStep += averageSampleDuration / 4 | 0 || 1;\n } else {\n dtsStep = sample.dts;\n }\n minPTS = Math.min(sample.pts, minPTS);\n maxPTS = Math.max(sample.pts, maxPTS);\n }\n lastDTS = inputSamples[nbSamples - 1].dts;\n\n /* concatenate the video data and construct the mdat in place\n (need 8 more bytes to fill length and mpdat type) */\n const mdatSize = naluLen + 4 * nbNalu + 8;\n let mdat;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MUX_ERROR,\n details: ErrorDetails.REMUX_ALLOC_ERROR,\n fatal: false,\n error: err,\n bytes: mdatSize,\n reason: `fail allocating video mdat ${mdatSize}`\n });\n return;\n }\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n let stretchedLastFrame = false;\n let minDtsDelta = Number.POSITIVE_INFINITY;\n let minPtsDelta = Number.POSITIVE_INFINITY;\n let maxDtsDelta = Number.NEGATIVE_INFINITY;\n let maxPtsDelta = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < nbSamples; i++) {\n const VideoSample = inputSamples[i];\n const VideoSampleUnits = VideoSample.units;\n let mp4SampleLength = 0;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (let j = 0, nbUnits = VideoSampleUnits.length; j < nbUnits; j++) {\n const unit = VideoSampleUnits[j];\n const unitData = unit.data;\n const unitDataLen = unit.data.byteLength;\n view.setUint32(offset, unitDataLen);\n offset += 4;\n mdat.set(unitData, offset);\n offset += unitDataLen;\n mp4SampleLength += 4 + unitDataLen;\n }\n\n // expected sample duration is the Decoding Timestamp diff of consecutive samples\n let ptsDelta;\n if (i < nbSamples - 1) {\n mp4SampleDuration = inputSamples[i + 1].dts - VideoSample.dts;\n ptsDelta = inputSamples[i + 1].pts - VideoSample.pts;\n } else {\n const config = this.config;\n const lastFrameDuration = i > 0 ? VideoSample.dts - inputSamples[i - 1].dts : averageSampleDuration;\n ptsDelta = i > 0 ? VideoSample.pts - inputSamples[i - 1].pts : averageSampleDuration;\n if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {\n // In some cases, a segment's audio track duration may exceed the video track duration.\n // Since we've already remuxed audio, and we know how long the audio track is, we look to\n // see if the delta to the next segment is longer than maxBufferHole.\n // If so, playback would potentially get stuck, so we artificially inflate\n // the duration of the last frame to minimize any potential gap between segments.\n const gapTolerance = Math.floor(config.maxBufferHole * timeScale);\n const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - VideoSample.pts;\n if (deltaToFrameEnd > gapTolerance) {\n // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n } else {\n stretchedLastFrame = true;\n }\n this.logger.log(`[mp4-remuxer]: It is approximately ${deltaToFrameEnd / 90} ms to the next segment; using duration ${mp4SampleDuration / 90} ms for the last video frame.`);\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n }\n const compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);\n minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);\n maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);\n minPtsDelta = Math.min(minPtsDelta, ptsDelta);\n maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);\n outputSamples.push(createMp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));\n }\n if (outputSamples.length) {\n if (chromeVersion) {\n if (chromeVersion < 70) {\n // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue\n // https://code.google.com/p/chromium/issues/detail?id=229412\n const flags = outputSamples[0].flags;\n flags.dependsOn = 2;\n flags.isNonSync = 0;\n }\n } else if (safariWebkitVersion) {\n // Fix for \"CNN special report, with CC\" in test-streams (Safari browser only)\n // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.\n if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {\n this.logger.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');\n let dts = firstDTS;\n for (let i = 0, len = outputSamples.length; i < len; i++) {\n const nextDts = dts + outputSamples[i].duration;\n const pts = dts + outputSamples[i].cts;\n if (i < len - 1) {\n const nextPts = nextDts + outputSamples[i + 1].cts;\n outputSamples[i].duration = nextPts - pts;\n } else {\n outputSamples[i].duration = i ? outputSamples[i - 1].duration : averageSampleDuration;\n }\n outputSamples[i].cts = 0;\n dts = nextDts;\n }\n }\n }\n }\n // next AVC/HEVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;\n this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;\n this.videoSampleDuration = mp4SampleDuration;\n this.isVideoContiguous = true;\n const moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends(track, {\n samples: outputSamples\n }));\n const type = 'video';\n const data = {\n data1: moof,\n data2: mdat,\n startPTS: minPTS / timeScale,\n endPTS: (maxPTS + mp4SampleDuration) / timeScale,\n startDTS: firstDTS / timeScale,\n endDTS: nextAvcDts / timeScale,\n type,\n hasAudio: false,\n hasVideo: true,\n nb: outputSamples.length,\n dropped: track.dropped\n };\n track.samples = [];\n track.dropped = 0;\n return data;\n }\n getSamplesPerFrame(track) {\n switch (track.segmentCodec) {\n case 'mp3':\n return MPEG_AUDIO_SAMPLE_PER_FRAME;\n case 'ac3':\n return AC3_SAMPLES_PER_FRAME;\n default:\n return AAC_SAMPLES_PER_FRAME;\n }\n }\n remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {\n const inputTimeScale = track.inputTimeScale;\n const mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;\n const scaleFactor = inputTimeScale / mp4timeScale;\n const mp4SampleDuration = this.getSamplesPerFrame(track);\n const inputSampleDuration = mp4SampleDuration * scaleFactor;\n const initPTS = this._initPTS;\n const rawMPEG = track.segmentCodec === 'mp3' && this.typeSupported.mpeg;\n const outputSamples = [];\n const alignedWithVideo = videoTimeOffset !== undefined;\n let inputSamples = track.samples;\n let offset = rawMPEG ? 0 : 8;\n let nextAudioPts = this.nextAudioPts || -1;\n\n // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);\n\n // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n // - less than 20 audio frames distance\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n // this helps ensuring audio continuity\n // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame\n const timeOffsetMpegTS = timeOffset * inputTimeScale;\n const initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;\n this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initTime, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration);\n\n // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = normalizePts(sample.pts - initTime, timeOffsetMpegTS);\n });\n if (!contiguous || nextAudioPts < 0) {\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter(sample => sample.pts >= 0);\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (!inputSamples.length) {\n return;\n }\n if (videoTimeOffset === 0) {\n // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence\n nextAudioPts = 0;\n } else if (accurateTimeOffset && !alignedWithVideo) {\n // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS\n nextAudioPts = Math.max(0, timeOffsetMpegTS);\n } else {\n // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n }\n }\n\n // If the audio track is missing samples, the frames seem to get \"left-shifted\" within the\n // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.\n // In an effort to prevent this from happening, we inject frames here where there are gaps.\n // When possible, we inject a silent frame; when that's not possible, we duplicate the last\n // frame.\n\n if (track.segmentCodec === 'aac') {\n const maxAudioFramesDrift = this.config.maxAudioFramesDrift;\n for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {\n // First, let's see how far off this frame is from where we expect it to be\n const sample = inputSamples[i];\n const pts = sample.pts;\n const delta = pts - nextPts;\n const duration = Math.abs(1000 * delta / inputTimeScale);\n\n // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync\n if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {\n if (i === 0) {\n this.logger.warn(`Audio frame @ ${(pts / inputTimeScale).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1000 * delta / inputTimeScale)} ms.`);\n this.nextAudioPts = nextAudioPts = nextPts = pts;\n }\n } // eslint-disable-line brace-style\n\n // Insert missing frames if:\n // 1: We're more than maxAudioFramesDrift frame away\n // 2: Not more than MAX_SILENT_FRAME_DURATION away\n // 3: currentTime (aka nextPtsNorm) is not 0\n // 4: remuxing with video (videoTimeOffset !== undefined)\n else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {\n let missing = Math.round(delta / inputSampleDuration);\n // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from\n // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.\n nextPts = pts - missing * inputSampleDuration;\n if (nextPts < 0) {\n missing--;\n nextPts += inputSampleDuration;\n }\n if (i === 0) {\n this.nextAudioPts = nextAudioPts = nextPts;\n }\n this.logger.warn(`[mp4-remuxer]: Injecting ${missing} audio frame @ ${(nextPts / inputTimeScale).toFixed(3)}s due to ${Math.round(1000 * delta / inputTimeScale)} ms gap.`);\n for (let j = 0; j < missing; j++) {\n const newStamp = Math.max(nextPts, 0);\n let fillFrame = AAC.getSilentFrame(track.parsedCodec || track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n this.logger.log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.');\n fillFrame = sample.unit.subarray();\n }\n inputSamples.splice(i, 0, {\n unit: fillFrame,\n pts: newStamp\n });\n nextPts += inputSampleDuration;\n i++;\n }\n }\n sample.pts = nextPts;\n nextPts += inputSampleDuration;\n }\n }\n let firstPTS = null;\n let lastPTS = null;\n let mdat;\n let mdatSize = 0;\n let sampleLength = inputSamples.length;\n while (sampleLength--) {\n mdatSize += inputSamples[sampleLength].unit.byteLength;\n }\n for (let j = 0, _nbSamples = inputSamples.length; j < _nbSamples; j++) {\n const audioSample = inputSamples[j];\n const unit = audioSample.unit;\n let pts = audioSample.pts;\n if (lastPTS !== null) {\n // If we have more than one sample, set the duration of the sample to the \"real\" duration; the PTS diff with\n // the previous sample\n const prevSample = outputSamples[j - 1];\n prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);\n } else {\n if (contiguous && track.segmentCodec === 'aac') {\n // set PTS/DTS to expected PTS/DTS\n pts = nextAudioPts;\n }\n // remember first PTS of our audioSamples\n firstPTS = pts;\n if (mdatSize > 0) {\n /* concatenate the audio data and construct the mdat in place\n (need 8 more bytes to fill length and mdat type) */\n mdatSize += offset;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MUX_ERROR,\n details: ErrorDetails.REMUX_ALLOC_ERROR,\n fatal: false,\n error: err,\n bytes: mdatSize,\n reason: `fail allocating audio mdat ${mdatSize}`\n });\n return;\n }\n if (!rawMPEG) {\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n }\n } else {\n // no audio samples\n return;\n }\n }\n mdat.set(unit, offset);\n const unitLen = unit.byteLength;\n offset += unitLen;\n // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG\n // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration\n // becomes the PTS diff with the previous sample\n outputSamples.push(createMp4Sample(true, mp4SampleDuration, unitLen, 0));\n lastPTS = pts;\n }\n\n // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones\n const nbSamples = outputSamples.length;\n if (!nbSamples) {\n return;\n }\n\n // The next audio sample PTS should be equal to last sample PTS + duration\n const lastSample = outputSamples[outputSamples.length - 1];\n this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration;\n\n // Set the track samples from inputSamples to outputSamples before remuxing\n const moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {\n samples: outputSamples\n }));\n\n // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared\n track.samples = [];\n const start = firstPTS / inputTimeScale;\n const end = nextAudioPts / inputTimeScale;\n const type = 'audio';\n const audioData = {\n data1: moof,\n data2: mdat,\n startPTS: start,\n endPTS: end,\n startDTS: start,\n endDTS: end,\n type,\n hasAudio: true,\n hasVideo: false,\n nb: nbSamples\n };\n this.isAudioContiguous = true;\n return audioData;\n }\n}\nfunction normalizePts(value, reference) {\n let offset;\n if (reference === null) {\n return value;\n }\n if (reference < value) {\n // - 2^33\n offset = -8589934592;\n } else {\n // + 2^33\n offset = 8589934592;\n }\n /* PTS is 33bit (from 0 to 2^33 -1)\n if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n PTS looping occured. fill the gap */\n while (Math.abs(value - reference) > 4294967296) {\n value += offset;\n }\n return value;\n}\nfunction findKeyframeIndex(samples) {\n for (let i = 0; i < samples.length; i++) {\n if (samples[i].key) {\n return i;\n }\n }\n return -1;\n}\nfunction flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {\n const length = track.samples.length;\n if (!length) {\n return;\n }\n const inputTimeScale = track.inputTimeScale;\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting id3 pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;\n sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;\n }\n const samples = track.samples;\n track.samples = [];\n return {\n samples\n };\n}\nfunction flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {\n const length = track.samples.length;\n if (!length) {\n return;\n }\n const inputTimeScale = track.inputTimeScale;\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting text pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;\n }\n track.samples.sort((a, b) => a.pts - b.pts);\n const samples = track.samples;\n track.samples = [];\n return {\n samples\n };\n}\n\nclass PassThroughRemuxer {\n constructor(observer, config, typeSupported, logger) {\n this.logger = void 0;\n this.emitInitSegment = false;\n this.audioCodec = void 0;\n this.videoCodec = void 0;\n this.initData = void 0;\n this.initPTS = null;\n this.initTracks = void 0;\n this.lastEndTime = null;\n this.logger = logger;\n }\n destroy() {}\n resetTimeStamp(defaultInitPTS) {\n this.initPTS = defaultInitPTS;\n this.lastEndTime = null;\n }\n resetNextTimestamp() {\n this.lastEndTime = null;\n }\n resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));\n this.emitInitSegment = true;\n }\n generateInitSegment(initSegment) {\n let {\n audioCodec,\n videoCodec\n } = this;\n if (!(initSegment != null && initSegment.byteLength)) {\n this.initTracks = undefined;\n this.initData = undefined;\n return;\n }\n const initData = this.initData = parseInitSegment(initSegment);\n\n // Get codec from initSegment\n if (initData.audio) {\n audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO);\n }\n if (initData.video) {\n videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO);\n }\n const tracks = {};\n if (initData.audio && initData.video) {\n tracks.audiovideo = {\n container: 'video/mp4',\n codec: audioCodec + ',' + videoCodec,\n supplemental: initData.video.supplemental,\n initSegment,\n id: 'main'\n };\n } else if (initData.audio) {\n tracks.audio = {\n container: 'audio/mp4',\n codec: audioCodec,\n initSegment,\n id: 'audio'\n };\n } else if (initData.video) {\n tracks.video = {\n container: 'video/mp4',\n codec: videoCodec,\n supplemental: initData.video.supplemental,\n initSegment,\n id: 'main'\n };\n } else {\n this.logger.warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');\n }\n this.initTracks = tracks;\n }\n remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {\n var _initData, _initData2;\n let {\n initPTS,\n lastEndTime\n } = this;\n const result = {\n audio: undefined,\n video: undefined,\n text: textTrack,\n id3: id3Track,\n initSegment: undefined\n };\n\n // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the\n // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update\n // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.\n if (!isFiniteNumber(lastEndTime)) {\n lastEndTime = this.lastEndTime = timeOffset || 0;\n }\n\n // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only\n // audio or video (or both); adding it to video was an arbitrary choice.\n const data = videoTrack.samples;\n if (!(data != null && data.length)) {\n return result;\n }\n const initSegment = {\n initPTS: undefined,\n timescale: 1\n };\n let initData = this.initData;\n if (!((_initData = initData) != null && _initData.length)) {\n this.generateInitSegment(data);\n initData = this.initData;\n }\n if (!((_initData2 = initData) != null && _initData2.length)) {\n // We can't remux if the initSegment could not be generated\n this.logger.warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');\n return result;\n }\n if (this.emitInitSegment) {\n initSegment.tracks = this.initTracks;\n this.emitInitSegment = false;\n }\n const duration = getDuration(data, initData);\n const startDTS = getStartDTS(initData, data);\n const decodeTime = startDTS === null ? timeOffset : startDTS;\n if ((accurateTimeOffset || !initPTS) && (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale)) {\n initSegment.initPTS = decodeTime - timeOffset;\n if (initPTS && initPTS.timescale === 1) {\n this.logger.warn(`Adjusting initPTS @${timeOffset} from ${initPTS.baseTime / initPTS.timescale} to ${initSegment.initPTS}`);\n }\n this.initPTS = initPTS = {\n baseTime: initSegment.initPTS,\n timescale: 1\n };\n }\n const startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;\n const endTime = startTime + duration;\n offsetStartDTS(initData, data, initPTS.baseTime / initPTS.timescale);\n if (duration > 0) {\n this.lastEndTime = endTime;\n } else {\n this.logger.warn('Duration parsed from mp4 should be greater than zero');\n this.resetNextTimestamp();\n }\n const hasAudio = !!initData.audio;\n const hasVideo = !!initData.video;\n let type = '';\n if (hasAudio) {\n type += 'audio';\n }\n if (hasVideo) {\n type += 'video';\n }\n const track = {\n data1: data,\n startPTS: startTime,\n startDTS: startTime,\n endPTS: endTime,\n endDTS: endTime,\n type,\n hasAudio,\n hasVideo,\n nb: 1,\n dropped: 0\n };\n result.audio = track.type === 'audio' ? track : undefined;\n result.video = track.type !== 'audio' ? track : undefined;\n result.initSegment = initSegment;\n result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);\n if (textTrack.samples.length) {\n result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);\n }\n return result;\n }\n}\nfunction isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {\n if (initPTS === null) {\n return true;\n }\n // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second\n const minDuration = Math.max(duration, 1);\n const startTime = startDTS - initPTS.baseTime / initPTS.timescale;\n return Math.abs(startTime - timeOffset) > minDuration;\n}\nfunction getParsedTrackCodec(track, type) {\n const parsedCodec = track == null ? void 0 : track.codec;\n if (parsedCodec && parsedCodec.length > 4) {\n return parsedCodec;\n }\n if (type === ElementaryStreamTypes.AUDIO) {\n if (parsedCodec === 'ec-3' || parsedCodec === 'ac-3' || parsedCodec === 'alac') {\n return parsedCodec;\n }\n if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {\n // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity\n const preferManagedMediaSource = false;\n return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);\n }\n logger.warn(`Unhandled audio codec \"${parsedCodec}\" in mp4 MAP`);\n return parsedCodec || 'mp4a';\n }\n // Provide defaults based on codec type\n // This allows for some playback of some fmp4 playlists without CODECS defined in manifest\n logger.warn(`Unhandled video codec \"${parsedCodec}\" in mp4 MAP`);\n return parsedCodec || 'avc1';\n}\n\nlet now;\n// performance.now() not available on WebWorker, at least on Safari Desktop\ntry {\n now = self.performance.now.bind(self.performance);\n} catch (err) {\n now = Date.now;\n}\nconst muxConfig = [{\n demux: MP4Demuxer,\n remux: PassThroughRemuxer\n}, {\n demux: TSDemuxer,\n remux: MP4Remuxer\n}, {\n demux: AACDemuxer,\n remux: MP4Remuxer\n}, {\n demux: MP3Demuxer,\n remux: MP4Remuxer\n}];\n{\n muxConfig.splice(2, 0, {\n demux: AC3Demuxer,\n remux: MP4Remuxer\n });\n}\nclass Transmuxer {\n constructor(observer, typeSupported, config, vendor, id, logger) {\n this.asyncResult = false;\n this.logger = void 0;\n this.observer = void 0;\n this.typeSupported = void 0;\n this.config = void 0;\n this.id = void 0;\n this.demuxer = void 0;\n this.remuxer = void 0;\n this.decrypter = void 0;\n this.probe = void 0;\n this.decryptionPromise = null;\n this.transmuxConfig = void 0;\n this.currentTransmuxState = void 0;\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.id = id;\n this.logger = logger;\n }\n configure(transmuxConfig) {\n this.transmuxConfig = transmuxConfig;\n if (this.decrypter) {\n this.decrypter.reset();\n }\n }\n push(data, decryptdata, chunkMeta, state) {\n const stats = chunkMeta.transmuxing;\n stats.executeStart = now();\n let uintData = new Uint8Array(data);\n const {\n currentTransmuxState,\n transmuxConfig\n } = this;\n if (state) {\n this.currentTransmuxState = state;\n }\n const {\n contiguous,\n discontinuity,\n trackSwitch,\n accurateTimeOffset,\n timeOffset,\n initSegmentChange\n } = state || currentTransmuxState;\n const {\n audioCodec,\n videoCodec,\n defaultInitPts,\n duration,\n initSegmentData\n } = transmuxConfig;\n const keyData = getEncryptionType(uintData, decryptdata);\n if (keyData && isFullSegmentEncryption(keyData.method)) {\n const decrypter = this.getDecrypter();\n const aesMode = getAesModeFromFullSegmentMethod(keyData.method);\n\n // Software decryption is synchronous; webCrypto is not\n if (decrypter.isSync()) {\n // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached\n // data is handled in the flush() call\n let decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode);\n // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress\n const loadingParts = chunkMeta.part > -1;\n if (loadingParts) {\n const _data = decrypter.flush();\n decryptedData = _data ? _data.buffer : _data;\n }\n if (!decryptedData) {\n stats.executeEnd = now();\n return emptyResult(chunkMeta);\n }\n uintData = new Uint8Array(decryptedData);\n } else {\n this.asyncResult = true;\n this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode).then(decryptedData => {\n // Calling push here is important; if flush() is called while this is still resolving, this ensures that\n // the decrypted data has been transmuxed\n const result = this.push(decryptedData, null, chunkMeta);\n this.decryptionPromise = null;\n return result;\n });\n return this.decryptionPromise;\n }\n }\n const resetMuxers = this.needsProbing(discontinuity, trackSwitch);\n if (resetMuxers) {\n const error = this.configureTransmuxer(uintData);\n if (error) {\n this.logger.warn(`[transmuxer] ${error.message}`);\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n error,\n reason: error.message\n });\n stats.executeEnd = now();\n return emptyResult(chunkMeta);\n }\n }\n if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {\n this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);\n }\n if (discontinuity || initSegmentChange || resetMuxers) {\n this.resetInitialTimestamp(defaultInitPts);\n }\n if (!contiguous) {\n this.resetContiguity();\n }\n const result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);\n this.asyncResult = isPromise(result);\n const currentState = this.currentTransmuxState;\n currentState.contiguous = true;\n currentState.discontinuity = false;\n currentState.trackSwitch = false;\n stats.executeEnd = now();\n return result;\n }\n\n // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)\n flush(chunkMeta) {\n const stats = chunkMeta.transmuxing;\n stats.executeStart = now();\n const {\n decrypter,\n currentTransmuxState,\n decryptionPromise\n } = this;\n if (decryptionPromise) {\n this.asyncResult = true;\n // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore\n // only flushing is required for async decryption\n return decryptionPromise.then(() => {\n return this.flush(chunkMeta);\n });\n }\n const transmuxResults = [];\n const {\n timeOffset\n } = currentTransmuxState;\n if (decrypter) {\n // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults\n // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,\n // or for progressive downloads with small segments)\n const decryptedData = decrypter.flush();\n if (decryptedData) {\n // Push always returns a TransmuxerResult if decryptdata is null\n transmuxResults.push(this.push(decryptedData.buffer, null, chunkMeta));\n }\n }\n const {\n demuxer,\n remuxer\n } = this;\n if (!demuxer || !remuxer) {\n // If probing failed, then Hls.js has been given content its not able to handle\n stats.executeEnd = now();\n const emptyResults = [emptyResult(chunkMeta)];\n if (this.asyncResult) {\n return Promise.resolve(emptyResults);\n }\n return emptyResults;\n }\n const demuxResultOrPromise = demuxer.flush(timeOffset);\n if (isPromise(demuxResultOrPromise)) {\n this.asyncResult = true;\n // Decrypt final SAMPLE-AES samples\n return demuxResultOrPromise.then(demuxResult => {\n this.flushRemux(transmuxResults, demuxResult, chunkMeta);\n return transmuxResults;\n });\n }\n this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);\n if (this.asyncResult) {\n return Promise.resolve(transmuxResults);\n }\n return transmuxResults;\n }\n flushRemux(transmuxResults, demuxResult, chunkMeta) {\n const {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack\n } = demuxResult;\n const {\n accurateTimeOffset,\n timeOffset\n } = this.currentTransmuxState;\n this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${chunkMeta.sn}${chunkMeta.part > -1 ? ' part: ' + chunkMeta.part : ''} of ${this.id === PlaylistLevelType.MAIN ? 'level' : 'track'} ${chunkMeta.level}`);\n const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);\n transmuxResults.push({\n remuxResult,\n chunkMeta\n });\n chunkMeta.transmuxing.executeEnd = now();\n }\n resetInitialTimestamp(defaultInitPts) {\n const {\n demuxer,\n remuxer\n } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetTimeStamp(defaultInitPts);\n remuxer.resetTimeStamp(defaultInitPts);\n }\n resetContiguity() {\n const {\n demuxer,\n remuxer\n } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetContiguity();\n remuxer.resetNextTimestamp();\n }\n resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {\n const {\n demuxer,\n remuxer\n } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);\n remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);\n }\n destroy() {\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = undefined;\n }\n if (this.remuxer) {\n this.remuxer.destroy();\n this.remuxer = undefined;\n }\n }\n transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {\n let result;\n if (keyData && keyData.method === 'SAMPLE-AES') {\n result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);\n } else {\n result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);\n }\n return result;\n }\n transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {\n const {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack\n } = this.demuxer.demux(data, timeOffset, false, !this.config.progressive);\n const remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);\n return {\n remuxResult,\n chunkMeta\n };\n }\n transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {\n return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(demuxResult => {\n const remuxResult = this.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, this.id);\n return {\n remuxResult,\n chunkMeta\n };\n });\n }\n configureTransmuxer(data) {\n const {\n config,\n observer,\n typeSupported\n } = this;\n // probe for content type\n let mux;\n for (let i = 0, len = muxConfig.length; i < len; i++) {\n var _muxConfig$i$demux;\n if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data, this.logger)) {\n mux = muxConfig[i];\n break;\n }\n }\n if (!mux) {\n return new Error('Failed to find demuxer by probing fragment data');\n }\n // so let's check that current remuxer and demuxer are still valid\n const demuxer = this.demuxer;\n const remuxer = this.remuxer;\n const Remuxer = mux.remux;\n const Demuxer = mux.demux;\n if (!remuxer || !(remuxer instanceof Remuxer)) {\n this.remuxer = new Remuxer(observer, config, typeSupported, this.logger);\n }\n if (!demuxer || !(demuxer instanceof Demuxer)) {\n this.demuxer = new Demuxer(observer, config, typeSupported, this.logger);\n this.probe = Demuxer.probe;\n }\n }\n needsProbing(discontinuity, trackSwitch) {\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;\n }\n getDecrypter() {\n let decrypter = this.decrypter;\n if (!decrypter) {\n decrypter = this.decrypter = new Decrypter(this.config);\n }\n return decrypter;\n }\n}\nfunction getEncryptionType(data, decryptData) {\n let encryptionType = null;\n if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {\n encryptionType = decryptData;\n }\n return encryptionType;\n}\nconst emptyResult = chunkMeta => ({\n remuxResult: {},\n chunkMeta\n});\nfunction isPromise(p) {\n return 'then' in p && p.then instanceof Function;\n}\nclass TransmuxConfig {\n constructor(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {\n this.audioCodec = void 0;\n this.videoCodec = void 0;\n this.initSegmentData = void 0;\n this.duration = void 0;\n this.defaultInitPts = void 0;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this.initSegmentData = initSegmentData;\n this.duration = duration;\n this.defaultInitPts = defaultInitPts || null;\n }\n}\nclass TransmuxState {\n constructor(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {\n this.discontinuity = void 0;\n this.contiguous = void 0;\n this.accurateTimeOffset = void 0;\n this.trackSwitch = void 0;\n this.timeOffset = void 0;\n this.initSegmentChange = void 0;\n this.discontinuity = discontinuity;\n this.contiguous = contiguous;\n this.accurateTimeOffset = accurateTimeOffset;\n this.trackSwitch = trackSwitch;\n this.timeOffset = timeOffset;\n this.initSegmentChange = initSegmentChange;\n }\n}\n\nlet transmuxerInstanceCount = 0;\nclass TransmuxerInterface {\n constructor(_hls, id, onTransmuxComplete, onFlush) {\n this.error = null;\n this.hls = void 0;\n this.id = void 0;\n this.instanceNo = transmuxerInstanceCount++;\n this.observer = void 0;\n this.frag = null;\n this.part = null;\n this.useWorker = void 0;\n this.workerContext = null;\n this.transmuxer = null;\n this.onTransmuxComplete = void 0;\n this.onFlush = void 0;\n this.onWorkerMessage = event => {\n const data = event.data;\n const hls = this.hls;\n if (!hls || !(data != null && data.event) || data.instanceNo !== this.instanceNo) {\n return;\n }\n switch (data.event) {\n case 'init':\n {\n var _this$workerContext;\n const objectURL = (_this$workerContext = this.workerContext) == null ? void 0 : _this$workerContext.objectURL;\n if (objectURL) {\n // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n self.URL.revokeObjectURL(objectURL);\n }\n break;\n }\n case 'transmuxComplete':\n {\n this.handleTransmuxComplete(data.data);\n break;\n }\n case 'flush':\n {\n this.onFlush(data.data);\n break;\n }\n\n // pass logs from the worker thread to the main logger\n case 'workerLog':\n {\n if (hls.logger[data.data.logType]) {\n hls.logger[data.data.logType](data.data.message);\n }\n break;\n }\n default:\n {\n data.data = data.data || {};\n data.data.frag = this.frag;\n data.data.part = this.part;\n data.data.id = this.id;\n hls.trigger(data.event, data.data);\n break;\n }\n }\n };\n this.onWorkerError = event => {\n if (!this.hls) {\n return;\n }\n const error = new Error(`${event.message} (${event.filename}:${event.lineno})`);\n this.hls.config.enableWorker = false;\n this.hls.logger.warn(`Error in \"${this.id}\" Web Worker, fallback to inline`);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n fatal: false,\n event: 'demuxerWorker',\n error\n });\n };\n const config = _hls.config;\n this.hls = _hls;\n this.id = id;\n this.useWorker = !!config.enableWorker;\n this.onTransmuxComplete = onTransmuxComplete;\n this.onFlush = onFlush;\n const forwardMessage = (ev, data) => {\n data = data || {};\n data.frag = this.frag || undefined;\n if (ev === Events.ERROR) {\n data = data;\n data.parent = this.id;\n data.part = this.part;\n this.error = data.error;\n }\n this.hls.trigger(ev, data);\n };\n\n // forward events to main thread\n this.observer = new EventEmitter();\n this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);\n this.observer.on(Events.ERROR, forwardMessage);\n const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);\n if (this.useWorker && typeof Worker !== 'undefined') {\n const logger = this.hls.logger;\n const canCreateWorker = config.workerPath || hasUMDWorker();\n if (canCreateWorker) {\n try {\n if (config.workerPath) {\n logger.log(`loading Web Worker ${config.workerPath} for \"${id}\"`);\n this.workerContext = loadWorker(config.workerPath);\n } else {\n logger.log(`injecting Web Worker for \"${id}\"`);\n this.workerContext = injectWorker();\n }\n const {\n worker\n } = this.workerContext;\n worker.addEventListener('message', this.onWorkerMessage);\n worker.addEventListener('error', this.onWorkerError);\n worker.postMessage({\n instanceNo: this.instanceNo,\n cmd: 'init',\n typeSupported: m2tsTypeSupported,\n id,\n config: stringify(config)\n });\n } catch (err) {\n logger.warn(`Error setting up \"${id}\" Web Worker, fallback to inline`, err);\n this.terminateWorker();\n this.error = null;\n this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id, _hls.logger);\n }\n return;\n }\n }\n this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id, _hls.logger);\n }\n reset() {\n this.frag = null;\n this.part = null;\n if (this.workerContext) {\n const instanceNo = this.instanceNo;\n this.instanceNo = transmuxerInstanceCount++;\n const config = this.hls.config;\n const m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);\n this.workerContext.worker.postMessage({\n instanceNo: this.instanceNo,\n cmd: 'reset',\n resetNo: instanceNo,\n typeSupported: m2tsTypeSupported,\n id: this.id,\n config: stringify(config)\n });\n }\n }\n terminateWorker() {\n if (this.workerContext) {\n const {\n worker\n } = this.workerContext;\n this.workerContext = null;\n worker.removeEventListener('message', this.onWorkerMessage);\n worker.removeEventListener('error', this.onWorkerError);\n removeWorkerFromStore(this.hls.config.workerPath);\n }\n }\n destroy() {\n if (this.workerContext) {\n this.terminateWorker();\n // @ts-ignore\n this.onWorkerMessage = this.onWorkerError = null;\n } else {\n const transmuxer = this.transmuxer;\n if (transmuxer) {\n transmuxer.destroy();\n this.transmuxer = null;\n }\n }\n const observer = this.observer;\n if (observer) {\n observer.removeAllListeners();\n }\n this.frag = null;\n this.part = null;\n // @ts-ignore\n this.observer = null;\n // @ts-ignore\n this.hls = null;\n }\n push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {\n var _frag$initSegment, _lastFrag$initSegment;\n chunkMeta.transmuxing.start = self.performance.now();\n const {\n instanceNo,\n transmuxer\n } = this;\n const timeOffset = part ? part.start : frag.start;\n // TODO: push \"clear-lead\" decrypt data for unencrypted fragments in streams with encrypted ones\n const decryptdata = frag.decryptdata;\n const lastFrag = this.frag;\n const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);\n const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);\n const snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;\n const partDiff = this.part ? chunkMeta.part - this.part.index : -1;\n const progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);\n const contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));\n const now = self.performance.now();\n if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {\n frag.stats.parsing.start = now;\n }\n if (part && (partDiff || !contiguous)) {\n part.stats.parsing.start = now;\n }\n const initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));\n const state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);\n if (!contiguous || discontinuity || initSegmentChange) {\n this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${frag.type} sn: ${chunkMeta.sn}${chunkMeta.part > -1 ? ' part: ' + chunkMeta.part : ''} ${this.id === PlaylistLevelType.MAIN ? 'level' : 'track'}: ${chunkMeta.level} id: ${chunkMeta.id}\n discontinuity: ${discontinuity}\n trackSwitch: ${trackSwitch}\n contiguous: ${contiguous}\n accurateTimeOffset: ${accurateTimeOffset}\n timeOffset: ${timeOffset}\n initSegmentChange: ${initSegmentChange}`);\n const config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);\n this.configureTransmuxer(config);\n }\n this.frag = frag;\n this.part = part;\n\n // Frags with sn of 'initSegment' are not transmuxed\n if (this.workerContext) {\n // post fragment payload as transferable objects for ArrayBuffer (no copy)\n this.workerContext.worker.postMessage({\n instanceNo,\n cmd: 'demux',\n data,\n decryptdata,\n chunkMeta,\n state\n }, data instanceof ArrayBuffer ? [data] : []);\n } else if (transmuxer) {\n const transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);\n if (isPromise(transmuxResult)) {\n transmuxResult.then(data => {\n this.handleTransmuxComplete(data);\n }).catch(error => {\n this.transmuxerError(error, chunkMeta, 'transmuxer-interface push error');\n });\n } else {\n this.handleTransmuxComplete(transmuxResult);\n }\n }\n }\n flush(chunkMeta) {\n chunkMeta.transmuxing.start = self.performance.now();\n const {\n instanceNo,\n transmuxer\n } = this;\n if (this.workerContext) {\n this.workerContext.worker.postMessage({\n instanceNo,\n cmd: 'flush',\n chunkMeta\n });\n } else if (transmuxer) {\n const transmuxResult = transmuxer.flush(chunkMeta);\n if (isPromise(transmuxResult)) {\n transmuxResult.then(data => {\n this.handleFlushResult(data, chunkMeta);\n }).catch(error => {\n this.transmuxerError(error, chunkMeta, 'transmuxer-interface flush error');\n });\n } else {\n this.handleFlushResult(transmuxResult, chunkMeta);\n }\n }\n }\n transmuxerError(error, chunkMeta, reason) {\n if (!this.hls) {\n return;\n }\n this.error = error;\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n chunkMeta,\n frag: this.frag || undefined,\n part: this.part || undefined,\n fatal: false,\n error,\n err: error,\n reason\n });\n }\n handleFlushResult(results, chunkMeta) {\n results.forEach(result => {\n this.handleTransmuxComplete(result);\n });\n this.onFlush(chunkMeta);\n }\n configureTransmuxer(config) {\n const {\n instanceNo,\n transmuxer\n } = this;\n if (this.workerContext) {\n this.workerContext.worker.postMessage({\n instanceNo,\n cmd: 'configure',\n config\n });\n } else if (transmuxer) {\n transmuxer.configure(config);\n }\n }\n handleTransmuxComplete(result) {\n result.chunkMeta.transmuxing.end = self.performance.now();\n this.onTransmuxComplete(result);\n }\n}\n\nconst TICK_INTERVAL$3 = 100; // how often to tick in ms\n\nclass AudioStreamController extends BaseStreamController {\n constructor(hls, fragmentTracker, keyLoader) {\n super(hls, fragmentTracker, keyLoader, 'audio-stream-controller', PlaylistLevelType.AUDIO);\n this.mainAnchor = null;\n this.mainFragLoading = null;\n this.audioOnly = false;\n this.bufferedTrack = null;\n this.switchingTrack = null;\n this.trackId = -1;\n this.waitingData = null;\n this.mainDetails = null;\n this.flushing = false;\n this.bufferFlushed = false;\n this.cachedTrackLoadedData = null;\n this.registerListeners();\n }\n onHandlerDestroying() {\n this.unregisterListeners();\n super.onHandlerDestroying();\n this.resetItem();\n }\n resetItem() {\n this.mainDetails = this.mainAnchor = this.mainFragLoading = this.bufferedTrack = this.switchingTrack = this.waitingData = this.cachedTrackLoadedData = null;\n }\n registerListeners() {\n super.registerListeners();\n const {\n hls\n } = this;\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);\n hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.on(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.on(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n unregisterListeners() {\n const {\n hls\n } = this;\n if (!hls) {\n return;\n }\n super.unregisterListeners();\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);\n hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.off(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.off(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value\n onInitPtsFound(event, {\n frag,\n id,\n initPTS,\n timescale\n }) {\n // Always update the new INIT PTS\n // Can change due level switch\n if (id === PlaylistLevelType.MAIN) {\n const cc = frag.cc;\n const inFlightFrag = this.fragCurrent;\n this.initPTS[cc] = {\n baseTime: initPTS,\n timescale\n };\n this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}/${timescale}`);\n this.mainAnchor = frag;\n // If we are waiting, tick immediately to unblock audio fragment transmuxing\n if (this.state === State.WAITING_INIT_PTS) {\n const waitingData = this.waitingData;\n if (!waitingData && !this.loadingParts || waitingData && waitingData.frag.cc !== cc) {\n this.nextLoadPosition = this.findSyncFrag(frag).start;\n }\n this.tick();\n } else if (!this.hls.hasEnoughToStart && inFlightFrag && inFlightFrag.cc !== cc) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.findSyncFrag(frag).start;\n inFlightFrag.abortRequests();\n this.resetLoadingState();\n } else if (this.state === State.IDLE) {\n this.tick();\n }\n }\n }\n findSyncFrag(mainFrag) {\n const trackDetails = this.getLevelDetails();\n const cc = mainFrag.cc;\n return findNearestWithCC(trackDetails, cc, mainFrag) || trackDetails && findFragWithCC(trackDetails.fragments, cc) || mainFrag;\n }\n startLoad(startPosition, skipSeekToStartPosition) {\n if (!this.levels) {\n this.startPosition = startPosition;\n this.state = State.STOPPED;\n return;\n }\n const lastCurrentTime = this.lastCurrentTime;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL$3);\n if (lastCurrentTime > 0 && startPosition === -1) {\n this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n startPosition = lastCurrentTime;\n this.state = State.IDLE;\n } else {\n this.state = State.WAITING_TRACK;\n }\n this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;\n this.startPosition = skipSeekToStartPosition ? -1 : startPosition;\n this.tick();\n }\n doTick() {\n switch (this.state) {\n case State.IDLE:\n this.doTickIdle();\n break;\n case State.WAITING_TRACK:\n {\n const {\n levels,\n trackId\n } = this;\n const currenTrack = levels == null ? void 0 : levels[trackId];\n const details = currenTrack == null ? void 0 : currenTrack.details;\n if (details && !this.waitForLive(currenTrack)) {\n if (this.waitForCdnTuneIn(details)) {\n break;\n }\n this.state = State.WAITING_INIT_PTS;\n }\n break;\n }\n case State.FRAG_LOADING_WAITING_RETRY:\n {\n var _this$media;\n const now = performance.now();\n const retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {\n const {\n levels,\n trackId\n } = this;\n this.log('RetryDate reached, switch back to IDLE state');\n this.resetStartWhenNotLoaded((levels == null ? void 0 : levels[trackId]) || null);\n this.state = State.IDLE;\n }\n break;\n }\n case State.WAITING_INIT_PTS:\n {\n // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS\n const waitingData = this.waitingData;\n if (waitingData) {\n const {\n frag,\n part,\n cache,\n complete\n } = waitingData;\n const mainAnchor = this.mainAnchor;\n if (this.initPTS[frag.cc] !== undefined) {\n this.waitingData = null;\n this.state = State.FRAG_LOADING;\n const payload = cache.flush().buffer;\n const data = {\n frag,\n part,\n payload,\n networkDetails: null\n };\n this._handleFragmentLoadProgress(data);\n if (complete) {\n super._handleFragmentLoadComplete(data);\n }\n } else if (mainAnchor && mainAnchor.cc !== waitingData.frag.cc) {\n // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found\n this.log(`Waiting fragment cc (${frag.cc}) cancelled because video is at cc ${mainAnchor.cc}`);\n this.nextLoadPosition = this.findSyncFrag(mainAnchor).start;\n this.clearWaitingFragment();\n }\n } else {\n this.state = State.IDLE;\n }\n }\n }\n this.onTickEnd();\n }\n clearWaitingFragment() {\n const waitingData = this.waitingData;\n if (waitingData) {\n if (!this.hls.hasEnoughToStart) {\n // Load overlapping fragment on start when discontinuity start times are not aligned\n this.startFragRequested = false;\n }\n this.fragmentTracker.removeFragment(waitingData.frag);\n this.waitingData = null;\n if (this.state !== State.STOPPED) {\n this.state = State.IDLE;\n }\n }\n }\n resetLoadingState() {\n this.clearWaitingFragment();\n super.resetLoadingState();\n }\n onTickEnd() {\n const {\n media\n } = this;\n if (!(media != null && media.readyState)) {\n // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)\n return;\n }\n this.lastCurrentTime = media.currentTime;\n }\n doTickIdle() {\n var _this$mainFragLoading;\n const {\n hls,\n levels,\n media,\n trackId\n } = this;\n const config = hls.config;\n\n // 1. if buffering is suspended\n // 2. if video not attached AND\n // start fragment already requested OR start frag prefetch not enabled\n // 3. if tracks or track not loaded and selected\n // then exit loop\n // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop\n if (!this.buffering || !media && !this.primaryPrefetch && (this.startFragRequested || !config.startFragPrefetch) || !(levels != null && levels[trackId])) {\n return;\n }\n const levelInfo = levels[trackId];\n const trackDetails = levelInfo.details;\n if (!trackDetails || this.waitForLive(levelInfo) || this.waitForCdnTuneIn(trackDetails)) {\n this.state = State.WAITING_TRACK;\n this.startFragRequested = false;\n return;\n }\n const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;\n if (this.bufferFlushed && bufferable) {\n this.bufferFlushed = false;\n this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO);\n }\n const bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO);\n if (bufferInfo === null) {\n return;\n }\n if (!this.switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {\n hls.trigger(Events.BUFFER_EOS, {\n type: 'audio'\n });\n this.state = State.ENDED;\n return;\n }\n const bufferLen = bufferInfo.len;\n const maxBufLen = hls.maxBufferLength;\n const fragments = trackDetails.fragments;\n const start = fragments[0].start;\n const loadPosition = this.getLoadPosition();\n const targetBufferTime = this.flushing ? loadPosition : bufferInfo.end;\n if (this.switchingTrack && media) {\n const pos = loadPosition;\n // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime\n if (trackDetails.PTSKnown && pos < start) {\n // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start\n if (bufferInfo.end > start || bufferInfo.nextStart) {\n this.log('Alt audio track ahead of main track, seek to start of alt audio track');\n media.currentTime = start + 0.05;\n }\n }\n }\n\n // if buffer length is less than maxBufLen, or near the end, find a fragment to load\n if (bufferLen >= maxBufLen && !this.switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) {\n return;\n }\n let frag = this.getNextFragment(targetBufferTime, trackDetails);\n // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags\n if (frag && this.isLoopLoading(frag, targetBufferTime)) {\n frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);\n }\n if (!frag) {\n this.bufferFlushed = true;\n return;\n }\n\n // Request audio segments up to one fragment ahead of main stream-controller\n let mainFragLoading = ((_this$mainFragLoading = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading.frag) || null;\n if (!this.audioOnly && this.startFragRequested && mainFragLoading && isMediaFragment(frag) && !frag.endList && (!trackDetails.live || !this.loadingParts && targetBufferTime < this.hls.liveSyncPosition)) {\n if (this.fragmentTracker.getState(mainFragLoading) === FragmentState.OK) {\n this.mainFragLoading = mainFragLoading = null;\n }\n if (mainFragLoading && isMediaFragment(mainFragLoading)) {\n if (frag.start > mainFragLoading.end) {\n // Get buffered frag at target position from tracker (loaded out of sequence)\n const mainFragAtPos = this.fragmentTracker.getFragAtPos(targetBufferTime, PlaylistLevelType.MAIN);\n if (mainFragAtPos && mainFragAtPos.end > mainFragLoading.end) {\n mainFragLoading = mainFragAtPos;\n this.mainFragLoading = {\n frag: mainFragAtPos,\n targetBufferTime: null\n };\n }\n }\n const atBufferSyncLimit = frag.start > mainFragLoading.end;\n if (atBufferSyncLimit) {\n return;\n }\n }\n }\n this.loadFragment(frag, levelInfo, targetBufferTime);\n }\n onMediaDetaching(event, data) {\n this.bufferFlushed = this.flushing = false;\n super.onMediaDetaching(event, data);\n }\n onAudioTracksUpdated(event, {\n audioTracks\n }) {\n // Reset tranxmuxer is essential for large context switches (Content Steering)\n this.resetTransmuxer();\n this.levels = audioTracks.map(mediaPlaylist => new Level(mediaPlaylist));\n }\n onAudioTrackSwitching(event, data) {\n // if any URL found on new audio track, it is an alternate audio track\n const altAudio = !!data.url;\n this.trackId = data.id;\n const {\n fragCurrent\n } = this;\n if (fragCurrent) {\n fragCurrent.abortRequests();\n this.removeUnbufferedFrags(fragCurrent.start);\n }\n this.resetLoadingState();\n\n // should we switch tracks ?\n if (altAudio) {\n this.switchingTrack = data;\n // main audio track are handled by stream-controller, just do something if switching to alt audio track\n this.flushAudioIfNeeded(data);\n if (this.state !== State.STOPPED) {\n // switching to audio track, start timer if not already started\n this.setInterval(TICK_INTERVAL$3);\n this.state = State.IDLE;\n this.tick();\n }\n } else {\n // destroy useless transmuxer when switching audio to main\n this.resetTransmuxer();\n this.switchingTrack = null;\n this.bufferedTrack = data;\n this.clearInterval();\n }\n }\n onManifestLoading() {\n super.onManifestLoading();\n this.bufferFlushed = this.flushing = this.audioOnly = false;\n this.resetItem();\n this.trackId = -1;\n }\n onLevelLoaded(event, data) {\n this.mainDetails = data.details;\n const cachedTrackLoadedData = this.cachedTrackLoadedData;\n if (cachedTrackLoadedData) {\n this.cachedTrackLoadedData = null;\n this.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED, cachedTrackLoadedData);\n }\n }\n onAudioTrackLoaded(event, data) {\n var _trackLevel$details;\n const {\n levels\n } = this;\n const {\n details: newDetails,\n id: trackId,\n groupId,\n track\n } = data;\n if (!levels) {\n this.warn(`Audio tracks reset while loading track ${trackId} \"${track.name}\" of \"${groupId}\"`);\n return;\n }\n const mainDetails = this.mainDetails;\n if (!mainDetails || newDetails.endCC > mainDetails.endCC || mainDetails.expired) {\n this.cachedTrackLoadedData = data;\n if (this.state !== State.STOPPED) {\n this.state = State.WAITING_TRACK;\n }\n return;\n }\n this.cachedTrackLoadedData = null;\n this.log(`Audio track ${trackId} \"${track.name}\" of \"${groupId}\" loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''},duration:${newDetails.totalduration}`);\n const trackLevel = levels[trackId];\n let sliding = 0;\n if (newDetails.live || (_trackLevel$details = trackLevel.details) != null && _trackLevel$details.live) {\n this.checkLiveUpdate(newDetails);\n if (newDetails.deltaUpdateFailed) {\n return;\n }\n if (trackLevel.details) {\n var _this$levelLastLoaded;\n sliding = this.alignPlaylists(newDetails, trackLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);\n }\n if (!newDetails.alignedSliding) {\n // Align audio rendition with the \"main\" playlist on discontinuity change\n // or program-date-time (PDT)\n alignDiscontinuities(newDetails, mainDetails);\n if (!newDetails.alignedSliding) {\n alignMediaPlaylistByPDT(newDetails, mainDetails);\n }\n sliding = newDetails.fragmentStart;\n }\n }\n trackLevel.details = newDetails;\n this.levelLastLoaded = trackLevel;\n\n // compute start position if we are aligned with the main playlist\n if (!this.startFragRequested) {\n this.setStartPosition(mainDetails, sliding);\n }\n this.hls.trigger(Events.AUDIO_TRACK_UPDATED, {\n details: newDetails,\n id: trackId,\n groupId: data.groupId\n });\n\n // only switch back to IDLE state if we were waiting for track to start downloading a new fragment\n if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {\n this.state = State.IDLE;\n }\n\n // trigger handler right now\n this.tick();\n }\n _handleFragmentLoadProgress(data) {\n var _frag$initSegment;\n const frag = data.frag;\n const {\n part,\n payload\n } = data;\n const {\n config,\n trackId,\n levels\n } = this;\n if (!levels) {\n this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);\n return;\n }\n const track = levels[trackId];\n if (!track) {\n this.warn('Audio track is undefined on fragment load progress');\n return;\n }\n const details = track.details;\n if (!details) {\n this.warn('Audio track details undefined on fragment load progress');\n this.removeUnbufferedFrags(frag.start);\n return;\n }\n const audioCodec = config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2';\n let transmuxer = this.transmuxer;\n if (!transmuxer) {\n transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));\n }\n\n // Check if we have video initPTS\n // If not we need to wait for it\n const initPTS = this.initPTS[frag.cc];\n const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;\n if (initPTS !== undefined) {\n // this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n const accurateTimeOffset = false; // details.PTSKnown || !details.live;\n const partIndex = part ? part.index : -1;\n const partial = partIndex !== -1;\n const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);\n transmuxer.push(payload, initSegmentData, audioCodec, '', frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);\n } else {\n this.log(`Unknown video PTS for cc ${frag.cc}, waiting for video PTS before demuxing audio frag ${frag.sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n const {\n cache\n } = this.waitingData = this.waitingData || {\n frag,\n part,\n cache: new ChunkCache(),\n complete: false\n };\n cache.push(new Uint8Array(payload));\n if (this.state !== State.STOPPED) {\n this.state = State.WAITING_INIT_PTS;\n }\n }\n }\n _handleFragmentLoadComplete(fragLoadedData) {\n if (this.waitingData) {\n this.waitingData.complete = true;\n return;\n }\n super._handleFragmentLoadComplete(fragLoadedData);\n }\n onBufferReset(/* event: Events.BUFFER_RESET */\n ) {\n // reset reference to sourcebuffers\n this.mediaBuffer = null;\n }\n onBufferCreated(event, data) {\n this.bufferFlushed = this.flushing = false;\n const audioTrack = data.tracks.audio;\n if (audioTrack) {\n this.mediaBuffer = audioTrack.buffer || null;\n }\n }\n onFragLoading(event, data) {\n if (!this.audioOnly && data.frag.type === PlaylistLevelType.MAIN && isMediaFragment(data.frag)) {\n this.mainFragLoading = data;\n if (this.state === State.IDLE) {\n this.tick();\n }\n }\n }\n onFragBuffered(event, data) {\n const {\n frag,\n part\n } = data;\n if (frag.type !== PlaylistLevelType.AUDIO) {\n if (!this.audioOnly && frag.type === PlaylistLevelType.MAIN && !frag.elementaryStreams.video && !frag.elementaryStreams.audiovideo) {\n this.audioOnly = true;\n this.mainFragLoading = null;\n }\n return;\n }\n if (this.fragContextChanged(frag)) {\n // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion\n // Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer\n this.warn(`Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack ? this.switchingTrack.name : 'false'}`);\n return;\n }\n if (isMediaFragment(frag)) {\n this.fragPrevious = frag;\n const track = this.switchingTrack;\n if (track) {\n this.bufferedTrack = track;\n this.switchingTrack = null;\n this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, track));\n }\n }\n this.fragBufferedComplete(frag, part);\n if (this.media) {\n this.tick();\n }\n }\n onError(event, data) {\n var _data$context;\n if (data.fatal) {\n this.state = State.ERROR;\n return;\n }\n switch (data.details) {\n case ErrorDetails.FRAG_GAP:\n case ErrorDetails.FRAG_PARSING_ERROR:\n case ErrorDetails.FRAG_DECRYPT_ERROR:\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);\n break;\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.LEVEL_PARSING_ERROR:\n // in case of non fatal error while loading track, if not retrying to load track, switch back to IDLE\n if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) {\n this.state = State.IDLE;\n }\n break;\n case ErrorDetails.BUFFER_ADD_CODEC_ERROR:\n case ErrorDetails.BUFFER_APPEND_ERROR:\n if (data.parent !== 'audio') {\n return;\n }\n this.resetLoadingState();\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n if (data.parent !== 'audio') {\n return;\n }\n if (this.reduceLengthAndFlushBuffer(data)) {\n this.bufferedTrack = null;\n super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');\n }\n break;\n case ErrorDetails.INTERNAL_EXCEPTION:\n this.recoverWorkerError(data);\n break;\n }\n }\n onBufferFlushing(event, {\n type\n }) {\n if (type !== ElementaryStreamTypes.VIDEO) {\n this.flushing = true;\n }\n }\n onBufferFlushed(event, {\n type\n }) {\n if (type !== ElementaryStreamTypes.VIDEO) {\n this.flushing = false;\n this.bufferFlushed = true;\n if (this.state === State.ENDED) {\n this.state = State.IDLE;\n }\n const mediaBuffer = this.mediaBuffer || this.media;\n if (mediaBuffer) {\n this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO);\n this.tick();\n }\n }\n }\n _handleTransmuxComplete(transmuxResult) {\n var _id3$samples;\n const id = 'audio';\n const {\n hls\n } = this;\n const {\n remuxResult,\n chunkMeta\n } = transmuxResult;\n const context = this.getCurrentContext(chunkMeta);\n if (!context) {\n this.resetWhenMissingContext(chunkMeta);\n return;\n }\n const {\n frag,\n part,\n level\n } = context;\n const {\n details\n } = level;\n const {\n audio,\n text,\n id3,\n initSegment\n } = remuxResult;\n\n // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.\n // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.\n if (this.fragContextChanged(frag) || !details) {\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n this.state = State.PARSING;\n if (this.switchingTrack && audio) {\n this.completeAudioSwitch(this.switchingTrack);\n }\n if (initSegment != null && initSegment.tracks) {\n const mapFragment = frag.initSegment || frag;\n this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);\n hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {\n frag: mapFragment,\n id,\n tracks: initSegment.tracks\n });\n // Only flush audio from old audio tracks when PTS is known on new audio track\n }\n if (audio) {\n const {\n startPTS,\n endPTS,\n startDTS,\n endDTS\n } = audio;\n if (part) {\n part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS\n };\n }\n frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);\n this.bufferFragmentData(audio, frag, part, chunkMeta);\n }\n if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {\n const emittedID3 = _extends({\n id,\n frag,\n details\n }, id3);\n hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);\n }\n if (text) {\n const emittedText = _extends({\n id,\n frag,\n details\n }, text);\n hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);\n }\n }\n _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {\n if (this.state !== State.PARSING) {\n return;\n }\n // delete any video track found on audio transmuxer\n if (tracks.video) {\n delete tracks.video;\n }\n if (tracks.audiovideo) {\n delete tracks.audiovideo;\n }\n\n // include levelCodec in audio and video tracks\n if (!tracks.audio) {\n return;\n }\n const track = tracks.audio;\n track.id = PlaylistLevelType.AUDIO;\n const variantAudioCodecs = currentLevel.audioCodec;\n this.log(`Init audio buffer, container:${track.container}, codecs[level/parsed]=[${variantAudioCodecs}/${track.codec}]`);\n // SourceBuffer will use track.levelCodec if defined\n if (variantAudioCodecs && variantAudioCodecs.split(',').length === 1) {\n track.levelCodec = variantAudioCodecs;\n }\n this.hls.trigger(Events.BUFFER_CODECS, tracks);\n const initSegment = track.initSegment;\n if (initSegment != null && initSegment.byteLength) {\n const segment = {\n type: 'audio',\n frag,\n part: null,\n chunkMeta,\n parent: frag.type,\n data: initSegment\n };\n this.hls.trigger(Events.BUFFER_APPENDING, segment);\n }\n // trigger handler right now\n this.tickImmediate();\n }\n loadFragment(frag, track, targetBufferTime) {\n // only load if fragment is not loaded or if in audio switch\n const fragState = this.fragmentTracker.getState(frag);\n\n // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch\n if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {\n var _track$details;\n if (!isMediaFragment(frag)) {\n this._loadInitSegment(frag, track);\n } else if ((_track$details = track.details) != null && _track$details.live && !this.initPTS[frag.cc]) {\n this.log(`Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`);\n this.state = State.WAITING_INIT_PTS;\n const mainDetails = this.mainDetails;\n if (mainDetails && mainDetails.fragmentStart !== track.details.fragmentStart) {\n alignMediaPlaylistByPDT(track.details, mainDetails);\n }\n } else {\n super.loadFragment(frag, track, targetBufferTime);\n }\n } else {\n this.clearTrackerIfNeeded(frag);\n }\n }\n flushAudioIfNeeded(switchingTrack) {\n if (this.media && this.bufferedTrack) {\n const {\n name,\n lang,\n assocLang,\n characteristics,\n audioCodec,\n channels\n } = this.bufferedTrack;\n if (!matchesOption({\n name,\n lang,\n assocLang,\n characteristics,\n audioCodec,\n channels\n }, switchingTrack, audioMatchPredicate)) {\n if (useAlternateAudio(switchingTrack.url, this.hls)) {\n this.log('Switching audio track : flushing all audio');\n super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');\n this.bufferedTrack = null;\n } else {\n // Main is being buffered. Set bufferedTrack so that it is flushed when switching back to alt-audio\n this.bufferedTrack = switchingTrack;\n }\n }\n }\n }\n completeAudioSwitch(switchingTrack) {\n const {\n hls\n } = this;\n this.flushAudioIfNeeded(switchingTrack);\n this.bufferedTrack = switchingTrack;\n this.switchingTrack = null;\n hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, switchingTrack));\n }\n}\n\nclass BasePlaylistController extends Logger {\n constructor(hls, logPrefix) {\n super(logPrefix, hls.logger);\n this.hls = void 0;\n this.canLoad = false;\n this.timer = -1;\n this.hls = hls;\n }\n destroy() {\n this.clearTimer();\n // @ts-ignore\n this.hls = this.log = this.warn = null;\n }\n clearTimer() {\n if (this.timer !== -1) {\n self.clearTimeout(this.timer);\n this.timer = -1;\n }\n }\n startLoad() {\n this.canLoad = true;\n this.loadPlaylist();\n }\n stopLoad() {\n this.canLoad = false;\n this.clearTimer();\n }\n switchParams(playlistUri, previous, current) {\n const renditionReports = previous == null ? void 0 : previous.renditionReports;\n if (renditionReports) {\n let foundIndex = -1;\n for (let i = 0; i < renditionReports.length; i++) {\n const attr = renditionReports[i];\n let uri;\n try {\n uri = new self.URL(attr.URI, previous.url).href;\n } catch (error) {\n this.warn(`Could not construct new URL for Rendition Report: ${error}`);\n uri = attr.URI || '';\n }\n // Use exact match. Otherwise, the last partial match, if any, will be used\n // (Playlist URI includes a query string that the Rendition Report does not)\n if (uri === playlistUri) {\n foundIndex = i;\n break;\n } else if (uri === playlistUri.substring(0, uri.length)) {\n foundIndex = i;\n }\n }\n if (foundIndex !== -1) {\n const attr = renditionReports[foundIndex];\n const msn = parseInt(attr['LAST-MSN']) || (previous == null ? void 0 : previous.lastPartSn);\n let part = parseInt(attr['LAST-PART']) || (previous == null ? void 0 : previous.lastPartIndex);\n if (this.hls.config.lowLatencyMode) {\n const currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);\n if (part >= 0 && currentGoal > previous.partTarget) {\n part += 1;\n }\n }\n const skip = current && getSkipValue(current);\n return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);\n }\n }\n }\n loadPlaylist(hlsUrlParameters) {\n // Loading is handled by the subclasses\n this.clearTimer();\n }\n loadingPlaylist(playlist, hlsUrlParameters) {\n // Loading is handled by the subclasses\n this.clearTimer();\n }\n shouldLoadPlaylist(playlist) {\n return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);\n }\n getUrlWithDirectives(uri, hlsUrlParameters) {\n if (hlsUrlParameters) {\n try {\n return hlsUrlParameters.addDirectives(uri);\n } catch (error) {\n this.warn(`Could not construct new URL with HLS Delivery Directives: ${error}`);\n }\n }\n return uri;\n }\n playlistLoaded(index, data, previousDetails) {\n const {\n details,\n stats\n } = data;\n\n // Set last updated date-time\n const now = self.performance.now();\n const elapsed = stats.loading.first ? Math.max(0, now - stats.loading.first) : 0;\n details.advancedDateTime = Date.now() - elapsed;\n\n // shift fragment starts with timelineOffset\n const timelineOffset = this.hls.config.timelineOffset;\n if (timelineOffset !== details.appliedTimelineOffset) {\n const offset = Math.max(timelineOffset || 0, 0);\n details.appliedTimelineOffset = offset;\n details.fragments.forEach(frag => {\n frag.start = frag.playlistOffset + offset;\n });\n }\n\n // if current playlist is a live playlist, arm a timer to reload it\n if (details.live || previousDetails != null && previousDetails.live) {\n const levelOrTrack = 'levelInfo' in data ? data.levelInfo : data.track;\n details.reloaded(previousDetails);\n // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments\n if (previousDetails && details.fragments.length > 0) {\n mergeDetails(previousDetails, details);\n const error = details.playlistParsingError;\n if (error) {\n this.warn(error);\n const hls = this.hls;\n if (!hls.config.ignorePlaylistParsingErrors) {\n var _details$fragments$;\n const {\n networkDetails\n } = data;\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_PARSING_ERROR,\n fatal: false,\n url: details.url,\n error,\n reason: error.message,\n level: data.level || undefined,\n parent: (_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.type,\n networkDetails,\n stats\n });\n return;\n }\n details.playlistParsingError = null;\n }\n }\n if (details.requestScheduled === -1) {\n details.requestScheduled = stats.loading.start;\n }\n const bufferInfo = this.hls.mainForwardBufferInfo;\n const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;\n const distanceToLiveEdgeMs = (details.edge - position) * 1000;\n const reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);\n if (details.requestScheduled + reloadInterval < now) {\n details.requestScheduled = now;\n } else {\n details.requestScheduled += reloadInterval;\n }\n this.log(`live playlist ${index} ${details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : details.updated ? 'UPDATED' : 'MISSED'}`);\n if (!this.canLoad || !details.live) {\n return;\n }\n let deliveryDirectives;\n let msn = undefined;\n let part = undefined;\n if (details.canBlockReload && details.endSN && details.advanced) {\n // Load level with LL-HLS delivery directives\n const lowLatencyMode = this.hls.config.lowLatencyMode;\n const lastPartSn = details.lastPartSn;\n const endSn = details.endSN;\n const lastPartIndex = details.lastPartIndex;\n const hasParts = lastPartIndex !== -1;\n const atLastPartOfSegment = lastPartSn === endSn;\n if (hasParts) {\n // When low latency mode is disabled, request the last part of the next segment\n if (atLastPartOfSegment) {\n msn = endSn + 1;\n part = lowLatencyMode ? 0 : lastPartIndex;\n } else {\n msn = lastPartSn;\n part = lowLatencyMode ? lastPartIndex + 1 : details.maxPartIndex;\n }\n } else {\n msn = endSn + 1;\n }\n // Low-Latency CDN Tune-in: \"age\" header and time since load indicates we're behind by more than one part\n // Update directives to obtain the Playlist that has the estimated additional duration of media\n const lastAdvanced = details.age;\n const cdnAge = lastAdvanced + details.ageHeader;\n let currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);\n if (currentGoal > 0) {\n if (cdnAge > details.targetduration * 3) {\n // Omit segment and part directives when the last response was more than 3 target durations ago,\n this.log(`Playlist last advanced ${lastAdvanced.toFixed(2)}s ago. Omitting segment and part directives.`);\n msn = undefined;\n part = undefined;\n } else if (previousDetails != null && previousDetails.tuneInGoal && cdnAge - details.partTarget > previousDetails.tuneInGoal) {\n // If we attempted to get the next or latest playlist update, but currentGoal increased,\n // then we either can't catchup, or the \"age\" header cannot be trusted.\n this.warn(`CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`);\n currentGoal = 0;\n } else {\n const segments = Math.floor(currentGoal / details.targetduration);\n msn += segments;\n if (part !== undefined) {\n const parts = Math.round(currentGoal % details.targetduration / details.partTarget);\n part += parts;\n }\n this.log(`CDN Tune-in age: ${details.ageHeader}s last advanced ${lastAdvanced.toFixed(2)}s goal: ${currentGoal} skip sn ${segments} to part ${part}`);\n }\n details.tuneInGoal = currentGoal;\n }\n deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);\n if (lowLatencyMode || !atLastPartOfSegment) {\n details.requestScheduled = now;\n this.loadingPlaylist(levelOrTrack, deliveryDirectives);\n return;\n }\n } else if (details.canBlockReload || details.canSkipUntil) {\n deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);\n }\n if (deliveryDirectives && msn !== undefined && details.canBlockReload) {\n details.requestScheduled = stats.loading.first + Math.max(reloadInterval - elapsed * 2, reloadInterval / 2);\n }\n this.scheduleLoading(levelOrTrack, deliveryDirectives, details);\n } else {\n this.clearTimer();\n }\n }\n scheduleLoading(levelOrTrack, deliveryDirectives, updatedDetails) {\n const details = updatedDetails || levelOrTrack.details;\n if (!details) {\n this.loadingPlaylist(levelOrTrack, deliveryDirectives);\n return;\n }\n const now = self.performance.now();\n const requestScheduled = details.requestScheduled;\n if (now >= requestScheduled) {\n this.loadingPlaylist(levelOrTrack, deliveryDirectives);\n return;\n }\n const estimatedTimeUntilUpdate = requestScheduled - now;\n this.log(`reload live playlist ${levelOrTrack.name || levelOrTrack.bitrate + 'bps'} in ${Math.round(estimatedTimeUntilUpdate)} ms`);\n this.clearTimer();\n this.timer = self.setTimeout(() => this.loadingPlaylist(levelOrTrack, deliveryDirectives), estimatedTimeUntilUpdate);\n }\n getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {\n let skip = getSkipValue(details);\n if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {\n msn = previousDeliveryDirectives.msn;\n part = previousDeliveryDirectives.part;\n skip = HlsSkip.No;\n }\n return new HlsUrlParameters(msn, part, skip);\n }\n checkRetry(errorEvent) {\n const errorDetails = errorEvent.details;\n const isTimeout = isTimeoutError(errorEvent);\n const errorAction = errorEvent.errorAction;\n const {\n action,\n retryCount = 0,\n retryConfig\n } = errorAction || {};\n const retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);\n if (retry) {\n var _errorEvent$context;\n if (retryCount >= retryConfig.maxNumRetry) {\n return false;\n }\n if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {\n // The LL-HLS request already timed out so retry immediately\n this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after \"${errorDetails}\" without delivery-directives`);\n this.loadPlaylist();\n } else {\n const delay = getRetryDelay(retryConfig, retryCount);\n // Schedule level/track reload\n this.clearTimer();\n this.timer = self.setTimeout(() => this.loadPlaylist(), delay);\n this.warn(`Retrying playlist loading ${retryCount + 1}/${retryConfig.maxNumRetry} after \"${errorDetails}\" in ${delay}ms`);\n }\n // `levelRetry = true` used to inform other controllers that a retry is happening\n errorEvent.levelRetry = true;\n errorAction.resolved = true;\n }\n return retry;\n }\n}\n\nfunction subtitleOptionsIdentical(trackList1, trackList2) {\n if (trackList1.length !== trackList2.length) {\n return false;\n }\n for (let i = 0; i < trackList1.length; i++) {\n if (!mediaAttributesIdentical(trackList1[i].attrs, trackList2[i].attrs)) {\n return false;\n }\n }\n return true;\n}\nfunction mediaAttributesIdentical(attrs1, attrs2, customAttributes) {\n // Media options with the same rendition ID must be bit identical\n const stableRenditionId = attrs1['STABLE-RENDITION-ID'];\n if (stableRenditionId && !customAttributes) {\n return stableRenditionId === attrs2['STABLE-RENDITION-ID'];\n }\n // When rendition ID is not present, compare attributes\n return !(customAttributes || ['LANGUAGE', 'NAME', 'CHARACTERISTICS', 'AUTOSELECT', 'DEFAULT', 'FORCED', 'ASSOC-LANGUAGE']).some(subtitleAttribute => attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]);\n}\nfunction subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) {\n return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || '').toLowerCase());\n}\n\nclass AudioTrackController extends BasePlaylistController {\n constructor(hls) {\n super(hls, 'audio-track-controller');\n this.tracks = [];\n this.groupIds = null;\n this.tracksInGroup = [];\n this.trackId = -1;\n this.currentTrack = null;\n this.selectDefaultTrack = true;\n this.registerListeners();\n }\n registerListeners() {\n const {\n hls\n } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n unregisterListeners() {\n const {\n hls\n } = this;\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n destroy() {\n this.unregisterListeners();\n this.tracks.length = 0;\n this.tracksInGroup.length = 0;\n this.currentTrack = null;\n super.destroy();\n }\n onManifestLoading() {\n this.tracks = [];\n this.tracksInGroup = [];\n this.groupIds = null;\n this.currentTrack = null;\n this.trackId = -1;\n this.selectDefaultTrack = true;\n }\n onManifestParsed(event, data) {\n this.tracks = data.audioTracks || [];\n }\n onAudioTrackLoaded(event, data) {\n const {\n id,\n groupId,\n details\n } = data;\n const trackInActiveGroup = this.tracksInGroup[id];\n if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {\n this.warn(`Audio track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);\n return;\n }\n const curDetails = trackInActiveGroup.details;\n trackInActiveGroup.details = data.details;\n this.log(`Audio track ${id} \"${trackInActiveGroup.name}\" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);\n if (id === this.trackId) {\n this.playlistLoaded(id, data, curDetails);\n }\n }\n onLevelLoading(event, data) {\n this.switchLevel(data.level);\n }\n onLevelSwitching(event, data) {\n this.switchLevel(data.level);\n }\n switchLevel(levelIndex) {\n const levelInfo = this.hls.levels[levelIndex];\n if (!levelInfo) {\n return;\n }\n const audioGroups = levelInfo.audioGroups || null;\n const currentGroups = this.groupIds;\n let currentTrack = this.currentTrack;\n if (!audioGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (audioGroups == null ? void 0 : audioGroups.length) || audioGroups != null && audioGroups.some(groupId => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) {\n this.groupIds = audioGroups;\n this.trackId = -1;\n this.currentTrack = null;\n const audioTracks = this.tracks.filter(track => !audioGroups || audioGroups.indexOf(track.groupId) !== -1);\n if (audioTracks.length) {\n // Disable selectDefaultTrack if there are no default tracks\n if (this.selectDefaultTrack && !audioTracks.some(track => track.default)) {\n this.selectDefaultTrack = false;\n }\n // track.id should match hls.audioTracks index\n audioTracks.forEach((track, i) => {\n track.id = i;\n });\n } else if (!currentTrack && !this.tracksInGroup.length) {\n // Do not dispatch AUDIO_TRACKS_UPDATED when there were and are no tracks\n return;\n }\n this.tracksInGroup = audioTracks;\n\n // Find preferred track\n const audioPreference = this.hls.config.audioPreference;\n if (!currentTrack && audioPreference) {\n const groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate);\n if (groupIndex > -1) {\n currentTrack = audioTracks[groupIndex];\n } else {\n const allIndex = findMatchingOption(audioPreference, this.tracks);\n currentTrack = this.tracks[allIndex];\n }\n }\n\n // Select initial track\n let trackId = this.findTrackId(currentTrack);\n if (trackId === -1 && currentTrack) {\n trackId = this.findTrackId(null);\n }\n\n // Dispatch events and load track if needed\n const audioTracksUpdated = {\n audioTracks\n };\n this.log(`Updating audio tracks, ${audioTracks.length} track(s) found in group(s): ${audioGroups == null ? void 0 : audioGroups.join(',')}`);\n this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);\n const selectedTrackId = this.trackId;\n if (trackId !== -1 && selectedTrackId === -1) {\n this.setAudioTrack(trackId);\n } else if (audioTracks.length && selectedTrackId === -1) {\n var _this$groupIds;\n const error = new Error(`No audio track selected for current audio group-ID(s): ${(_this$groupIds = this.groupIds) == null ? void 0 : _this$groupIds.join(',')} track count: ${audioTracks.length}`);\n this.warn(error.message);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,\n fatal: true,\n error\n });\n }\n }\n }\n onError(event, data) {\n if (data.fatal || !data.context) {\n return;\n }\n if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {\n this.checkRetry(data);\n }\n }\n get allAudioTracks() {\n return this.tracks;\n }\n get audioTracks() {\n return this.tracksInGroup;\n }\n get audioTrack() {\n return this.trackId;\n }\n set audioTrack(newId) {\n // If audio track is selected from API then don't choose from the manifest default track\n this.selectDefaultTrack = false;\n this.setAudioTrack(newId);\n }\n setAudioOption(audioOption) {\n const hls = this.hls;\n hls.config.audioPreference = audioOption;\n if (audioOption) {\n const allAudioTracks = this.allAudioTracks;\n this.selectDefaultTrack = false;\n if (allAudioTracks.length) {\n // First see if current option matches (no switch op)\n const currentTrack = this.currentTrack;\n if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) {\n return currentTrack;\n }\n // Find option in available tracks (tracksInGroup)\n const groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate);\n if (groupIndex > -1) {\n const track = this.tracksInGroup[groupIndex];\n this.setAudioTrack(groupIndex);\n return track;\n } else if (currentTrack) {\n // Find option in nearest level audio group\n let searchIndex = hls.loadLevel;\n if (searchIndex === -1) {\n searchIndex = hls.firstAutoLevel;\n }\n const switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate);\n if (switchIndex === -1) {\n // could not find matching variant\n return null;\n }\n // and switch level to acheive the audio group switch\n hls.nextLoadLevel = switchIndex;\n }\n if (audioOption.channels || audioOption.audioCodec) {\n // Could not find a match with codec / channels predicate\n // Find a match without channels or codec\n const withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks);\n if (withoutCodecAndChannelsMatch > -1) {\n return allAudioTracks[withoutCodecAndChannelsMatch];\n }\n }\n }\n }\n return null;\n }\n setAudioTrack(newId) {\n const tracks = this.tracksInGroup;\n\n // check if level idx is valid\n if (newId < 0 || newId >= tracks.length) {\n this.warn(`Invalid audio track id: ${newId}`);\n return;\n }\n this.selectDefaultTrack = false;\n const lastTrack = this.currentTrack;\n const track = tracks[newId];\n const trackLoaded = track.details && !track.details.live;\n if (newId === this.trackId && track === lastTrack && trackLoaded) {\n return;\n }\n this.log(`Switching to audio-track ${newId} \"${track.name}\" lang:${track.lang} group:${track.groupId} channels:${track.channels}`);\n this.trackId = newId;\n this.currentTrack = track;\n this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread2({}, track));\n // Do not reload track unless live\n if (trackLoaded) {\n return;\n }\n const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);\n this.loadPlaylist(hlsUrlParameters);\n }\n findTrackId(currentTrack) {\n const audioTracks = this.tracksInGroup;\n for (let i = 0; i < audioTracks.length; i++) {\n const track = audioTracks[i];\n if (this.selectDefaultTrack && !track.default) {\n continue;\n }\n if (!currentTrack || matchesOption(currentTrack, track, audioMatchPredicate)) {\n return i;\n }\n }\n if (currentTrack) {\n const {\n name,\n lang,\n assocLang,\n characteristics,\n audioCodec,\n channels\n } = currentTrack;\n for (let i = 0; i < audioTracks.length; i++) {\n const track = audioTracks[i];\n if (matchesOption({\n name,\n lang,\n assocLang,\n characteristics,\n audioCodec,\n channels\n }, track, audioMatchPredicate)) {\n return i;\n }\n }\n for (let i = 0; i < audioTracks.length; i++) {\n const track = audioTracks[i];\n if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE', 'ASSOC-LANGUAGE', 'CHARACTERISTICS'])) {\n return i;\n }\n }\n for (let i = 0; i < audioTracks.length; i++) {\n const track = audioTracks[i];\n if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE'])) {\n return i;\n }\n }\n }\n return -1;\n }\n loadPlaylist(hlsUrlParameters) {\n super.loadPlaylist();\n const audioTrack = this.currentTrack;\n if (!this.shouldLoadPlaylist(audioTrack)) {\n return;\n }\n // Do not load audio rendition with URI matching main variant URI\n if (useAlternateAudio(audioTrack.url, this.hls)) {\n this.scheduleLoading(audioTrack, hlsUrlParameters);\n }\n }\n loadingPlaylist(audioTrack, hlsUrlParameters) {\n super.loadingPlaylist(audioTrack, hlsUrlParameters);\n const id = audioTrack.id;\n const groupId = audioTrack.groupId;\n const url = this.getUrlWithDirectives(audioTrack.url, hlsUrlParameters);\n const details = audioTrack.details;\n const age = details == null ? void 0 : details.age;\n this.log(`Loading audio-track ${id} \"${audioTrack.name}\" lang:${audioTrack.lang} group:${groupId}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : ''}${age && details.live ? ' age ' + age.toFixed(1) + (details.type ? ' ' + details.type || '' : '') : ''} ${url}`);\n this.hls.trigger(Events.AUDIO_TRACK_LOADING, {\n url,\n id,\n groupId,\n deliveryDirectives: hlsUrlParameters || null,\n track: audioTrack\n });\n }\n}\n\nclass BufferOperationQueue {\n constructor(sourceBufferReference) {\n this.tracks = void 0;\n this.queues = {\n video: [],\n audio: [],\n audiovideo: []\n };\n this.tracks = sourceBufferReference;\n }\n destroy() {\n this.tracks = this.queues = null;\n }\n append(operation, type, pending) {\n if (this.queues === null || this.tracks === null) {\n return;\n }\n const queue = this.queues[type];\n queue.push(operation);\n if (queue.length === 1 && !pending) {\n this.executeNext(type);\n }\n }\n appendBlocker(type) {\n return new Promise(resolve => {\n const operation = {\n label: 'async-blocker',\n execute: resolve,\n onStart: () => {},\n onComplete: () => {},\n onError: () => {}\n };\n this.append(operation, type);\n });\n }\n prependBlocker(type) {\n return new Promise(resolve => {\n if (this.queues) {\n const operation = {\n label: 'async-blocker-prepend',\n execute: resolve,\n onStart: () => {},\n onComplete: () => {},\n onError: () => {}\n };\n this.queues[type].unshift(operation);\n }\n });\n }\n removeBlockers() {\n if (this.queues === null) {\n return;\n }\n [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach(queue => {\n var _queue$;\n const label = (_queue$ = queue[0]) == null ? void 0 : _queue$.label;\n if (label === 'async-blocker' || label === 'async-blocker-prepend') {\n queue[0].execute();\n queue.splice(0, 1);\n }\n });\n }\n unblockAudio(op) {\n if (this.queues === null) {\n return;\n }\n const queue = this.queues.audio;\n if (queue[0] === op) {\n this.shiftAndExecuteNext('audio');\n }\n }\n executeNext(type) {\n if (this.queues === null || this.tracks === null) {\n return;\n }\n const queue = this.queues[type];\n if (queue.length) {\n const operation = queue[0];\n try {\n // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations\n // which do not end with this event must call _onSBUpdateEnd manually\n operation.execute();\n } catch (error) {\n var _this$tracks$type;\n operation.onError(error);\n if (this.queues === null || this.tracks === null) {\n return;\n }\n\n // Only shift the current operation off, otherwise the updateend handler will do this for us\n const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;\n if (!(sb != null && sb.updating)) {\n this.shiftAndExecuteNext(type);\n }\n }\n }\n }\n shiftAndExecuteNext(type) {\n if (this.queues === null) {\n return;\n }\n this.queues[type].shift();\n this.executeNext(type);\n }\n current(type) {\n var _this$queues;\n return ((_this$queues = this.queues) == null ? void 0 : _this$queues[type][0]) || null;\n }\n toString() {\n const {\n queues,\n tracks\n } = this;\n if (queues === null || tracks === null) {\n return `<destroyed>`;\n }\n return `\n${this.list('video')}\n${this.list('audio')}\n${this.list('audiovideo')}}`;\n }\n list(type) {\n var _this$queues2, _this$tracks;\n return (_this$queues2 = this.queues) != null && _this$queues2[type] || (_this$tracks = this.tracks) != null && _this$tracks[type] ? `${type}: (${this.listSbInfo(type)}) ${this.listOps(type)}` : '';\n }\n listSbInfo(type) {\n var _this$tracks2;\n const track = (_this$tracks2 = this.tracks) == null ? void 0 : _this$tracks2[type];\n const sb = track == null ? void 0 : track.buffer;\n if (!sb) {\n return 'none';\n }\n return `SourceBuffer${sb.updating ? ' updating' : ''}${track.ended ? ' ended' : ''}${track.ending ? ' ending' : ''}`;\n }\n listOps(type) {\n var _this$queues3;\n return ((_this$queues3 = this.queues) == null ? void 0 : _this$queues3[type].map(op => op.label).join(', ')) || '';\n }\n}\n\nconst VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\\.[^.,]+)+/;\nconst TRACK_REMOVED_ERROR_NAME = 'HlsJsTrackRemovedError';\nclass HlsJsTrackRemovedError extends Error {\n constructor(message) {\n super(message);\n this.name = TRACK_REMOVED_ERROR_NAME;\n }\n}\nclass BufferController extends Logger {\n constructor(hls, fragmentTracker) {\n super('buffer-controller', hls.logger);\n this.hls = void 0;\n this.fragmentTracker = void 0;\n // The level details used to determine duration, target-duration and live\n this.details = null;\n // cache the self generated object url to detect hijack of video tag\n this._objectUrl = null;\n // A queue of buffer operations which require the SourceBuffer to not be updating upon execution\n this.operationQueue = null;\n // The total number track codecs expected before any sourceBuffers are created (2: audio and video or 1: audiovideo | audio | video)\n this.bufferCodecEventsTotal = 0;\n // A reference to the attached media element\n this.media = null;\n // A reference to the active media source\n this.mediaSource = null;\n // Last MP3 audio chunk appended\n this.lastMpegAudioChunk = null;\n // Audio fragment blocked from appending until corresponding video appends or context changes\n this.blockedAudioAppend = null;\n // Keep track of video append position for unblocking audio\n this.lastVideoAppendEnd = 0;\n // Whether or not to use ManagedMediaSource API and append source element to media element.\n this.appendSource = void 0;\n // Transferred MediaSource information used to detmerine if duration end endstream may be appended\n this.transferData = void 0;\n // Directives used to override default MediaSource handling\n this.overrides = void 0;\n // Error counters\n this.appendErrors = {\n audio: 0,\n video: 0,\n audiovideo: 0\n };\n // Record of required or created buffers by type. SourceBuffer is stored in Track.buffer once created.\n this.tracks = {};\n // Array of SourceBuffer type and SourceBuffer (or null). One entry per TrackSet in this.tracks.\n this.sourceBuffers = [[null, null], [null, null]];\n this._onEndStreaming = event => {\n var _this$mediaSource;\n if (!this.hls) {\n return;\n }\n if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) !== 'open') {\n return;\n }\n this.hls.pauseBuffering();\n };\n this._onStartStreaming = event => {\n if (!this.hls) {\n return;\n }\n this.hls.resumeBuffering();\n };\n // Keep as arrow functions so that we can directly reference these functions directly as event listeners\n this._onMediaSourceOpen = e => {\n const {\n media,\n mediaSource\n } = this;\n if (e) {\n this.log('Media source opened');\n }\n if (!media || !mediaSource) {\n return;\n }\n // once received, don't listen anymore to sourceopen event\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n media.removeEventListener('emptied', this._onMediaEmptied);\n this.updateDuration();\n this.hls.trigger(Events.MEDIA_ATTACHED, {\n media,\n mediaSource: mediaSource\n });\n if (this.mediaSource !== null) {\n this.checkPendingTracks();\n }\n };\n this._onMediaSourceClose = () => {\n this.log('Media source closed');\n };\n this._onMediaSourceEnded = () => {\n this.log('Media source ended');\n };\n this._onMediaEmptied = () => {\n const {\n mediaSrc,\n _objectUrl\n } = this;\n if (mediaSrc !== _objectUrl) {\n this.error(`Media element src was set while attaching MediaSource (${_objectUrl} > ${mediaSrc})`);\n }\n };\n this.hls = hls;\n this.fragmentTracker = fragmentTracker;\n this.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));\n this.initTracks();\n this.registerListeners();\n }\n hasSourceTypes() {\n return Object.keys(this.tracks).length > 0;\n }\n destroy() {\n this.unregisterListeners();\n this.details = null;\n this.lastMpegAudioChunk = this.blockedAudioAppend = null;\n this.transferData = this.overrides = undefined;\n if (this.operationQueue) {\n this.operationQueue.destroy();\n this.operationQueue = null;\n }\n // @ts-ignore\n this.hls = this.fragmentTracker = null;\n // @ts-ignore\n this._onMediaSourceOpen = this._onMediaSourceClose = null;\n // @ts-ignore\n this._onMediaSourceEnded = null;\n // @ts-ignore\n this._onStartStreaming = this._onEndStreaming = null;\n }\n registerListeners() {\n const {\n hls\n } = this;\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);\n hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.on(Events.BUFFER_EOS, this.onBufferEos, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.on(Events.FRAG_PARSED, this.onFragParsed, this);\n hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n unregisterListeners() {\n const {\n hls\n } = this;\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);\n hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.off(Events.BUFFER_EOS, this.onBufferEos, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.off(Events.FRAG_PARSED, this.onFragParsed, this);\n hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n transferMedia() {\n const {\n media,\n mediaSource\n } = this;\n if (!media) {\n return null;\n }\n const tracks = {};\n if (this.operationQueue) {\n const updating = this.isUpdating();\n if (!updating) {\n this.operationQueue.removeBlockers();\n }\n const queued = this.isQueued();\n if (updating || queued) {\n this.warn(`Transfering MediaSource with${queued ? ' operations in queue' : ''}${updating ? ' updating SourceBuffer(s)' : ''} ${this.operationQueue}`);\n }\n this.operationQueue.destroy();\n }\n const transferData = this.transferData;\n if (!this.sourceBufferCount && transferData && transferData.mediaSource === mediaSource) {\n _extends(tracks, transferData.tracks);\n } else {\n this.sourceBuffers.forEach(tuple => {\n const [type] = tuple;\n if (type) {\n tracks[type] = _extends({}, this.tracks[type]);\n this.removeBuffer(type);\n }\n tuple[0] = tuple[1] = null;\n });\n }\n return {\n media,\n mediaSource,\n tracks\n };\n }\n initTracks() {\n const tracks = {};\n this.sourceBuffers = [[null, null], [null, null]];\n this.tracks = tracks;\n this.resetQueue();\n this.resetAppendErrors();\n this.lastMpegAudioChunk = this.blockedAudioAppend = null;\n this.lastVideoAppendEnd = 0;\n }\n onManifestLoading() {\n this.bufferCodecEventsTotal = 0;\n this.details = null;\n }\n onManifestParsed(event, data) {\n var _this$transferData;\n // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller\n // sourcebuffers will be created all at once when the expected nb of tracks will be reached\n // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller\n // it will contain the expected nb of source buffers, no need to compute it\n let codecEvents = 2;\n if (data.audio && !data.video || !data.altAudio) {\n codecEvents = 1;\n }\n this.bufferCodecEventsTotal = codecEvents;\n this.log(`${codecEvents} bufferCodec event(s) expected.`);\n if ((_this$transferData = this.transferData) != null && _this$transferData.mediaSource && this.sourceBufferCount && codecEvents) {\n this.bufferCreated();\n }\n }\n onMediaAttaching(event, data) {\n const media = this.media = data.media;\n const MediaSource = getMediaSource(this.appendSource);\n this.transferData = this.overrides = undefined;\n if (media && MediaSource) {\n const transferringMedia = !!data.mediaSource;\n if (transferringMedia || data.overrides) {\n this.transferData = data;\n this.overrides = data.overrides;\n }\n const ms = this.mediaSource = data.mediaSource || new MediaSource();\n this.assignMediaSource(ms);\n if (transferringMedia) {\n this._objectUrl = media.src;\n this.attachTransferred();\n } else {\n // cache the locally generated object url\n const objectUrl = this._objectUrl = self.URL.createObjectURL(ms);\n // link video and media Source\n if (this.appendSource) {\n try {\n media.removeAttribute('src');\n // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives\n const MMS = self.ManagedMediaSource;\n media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;\n removeSourceChildren(media);\n addSource(media, objectUrl);\n media.load();\n } catch (error) {\n media.src = objectUrl;\n }\n } else {\n media.src = objectUrl;\n }\n }\n media.addEventListener('emptied', this._onMediaEmptied);\n }\n }\n assignMediaSource(ms) {\n var _this$transferData2, _ms$constructor;\n this.log(`${((_this$transferData2 = this.transferData) == null ? void 0 : _this$transferData2.mediaSource) === ms ? 'transferred' : 'created'} media source: ${(_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name}`);\n // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound\n ms.addEventListener('sourceopen', this._onMediaSourceOpen);\n ms.addEventListener('sourceended', this._onMediaSourceEnded);\n ms.addEventListener('sourceclose', this._onMediaSourceClose);\n if (this.appendSource) {\n ms.addEventListener('startstreaming', this._onStartStreaming);\n ms.addEventListener('endstreaming', this._onEndStreaming);\n }\n }\n attachTransferred() {\n const media = this.media;\n const data = this.transferData;\n if (!data || !media) {\n return;\n }\n const requiredTracks = this.tracks;\n const transferredTracks = data.tracks;\n const trackNames = transferredTracks ? Object.keys(transferredTracks) : null;\n const trackCount = trackNames ? trackNames.length : 0;\n const mediaSourceOpenCallback = () => {\n if (this.media && this.mediaSourceOpenOrEnded) {\n this._onMediaSourceOpen();\n }\n };\n if (transferredTracks && trackNames && trackCount) {\n if (!this.tracksReady) {\n // Wait for CODECS event(s)\n this.hls.config.startFragPrefetch = true;\n this.log(`attachTransferred: waiting for SourceBuffer track info`);\n return;\n }\n this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${stringify(requiredTracks, (key, value) => key === 'initSegment' ? undefined : value)};\ntransfer tracks: ${stringify(transferredTracks, (key, value) => key === 'initSegment' ? undefined : value)}}`);\n if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {\n // destroy attaching media source\n data.mediaSource = null;\n data.tracks = undefined;\n const currentTime = media.currentTime;\n const details = this.details;\n const startTime = Math.max(currentTime, (details == null ? void 0 : details.fragments[0].start) || 0);\n if (startTime - currentTime > 1) {\n this.log(`attachTransferred: waiting for playback to reach new tracks start time ${currentTime} -> ${startTime}`);\n return;\n }\n this.warn(`attachTransferred: resetting MediaSource for incompatible tracks (\"${Object.keys(transferredTracks)}\"->\"${Object.keys(requiredTracks)}\") start time: ${startTime} currentTime: ${currentTime}`);\n this.onMediaDetaching(Events.MEDIA_DETACHING, {});\n this.onMediaAttaching(Events.MEDIA_ATTACHING, data);\n media.currentTime = startTime;\n return;\n }\n this.transferData = undefined;\n trackNames.forEach(trackName => {\n const type = trackName;\n const track = transferredTracks[type];\n if (track) {\n const sb = track.buffer;\n if (sb) {\n // Purge fragment tracker of ejected segments for existing buffer\n const fragmentTracker = this.fragmentTracker;\n const playlistType = track.id;\n if (fragmentTracker.hasFragments(playlistType) || fragmentTracker.hasParts(playlistType)) {\n const bufferedTimeRanges = BufferHelper.getBuffered(sb);\n fragmentTracker.detectEvictedFragments(type, bufferedTimeRanges, playlistType, null, true);\n }\n // Transfer SourceBuffer\n const sbIndex = sourceBufferNameToIndex(type);\n const sbTuple = [type, sb];\n this.sourceBuffers[sbIndex] = sbTuple;\n if (sb.updating && this.operationQueue) {\n this.operationQueue.prependBlocker(type);\n }\n this.trackSourceBuffer(type, track);\n }\n }\n });\n mediaSourceOpenCallback();\n this.bufferCreated();\n } else {\n this.log(`attachTransferred: MediaSource w/o SourceBuffers`);\n mediaSourceOpenCallback();\n }\n }\n get mediaSourceOpenOrEnded() {\n var _this$mediaSource2;\n const readyState = (_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState;\n return readyState === 'open' || readyState === 'ended';\n }\n onMediaDetaching(event, data) {\n const transferringMedia = !!data.transferMedia;\n this.transferData = this.overrides = undefined;\n const {\n media,\n mediaSource,\n _objectUrl\n } = this;\n if (mediaSource) {\n this.log(`media source ${transferringMedia ? 'transferring' : 'detaching'}`);\n if (transferringMedia) {\n // Detach SourceBuffers without removing from MediaSource\n // and leave `tracks` (required SourceBuffers configuration)\n this.sourceBuffers.forEach(([type]) => {\n if (type) {\n this.removeBuffer(type);\n }\n });\n this.resetQueue();\n } else {\n if (this.mediaSourceOpenOrEnded) {\n const open = mediaSource.readyState === 'open';\n try {\n const sourceBuffers = mediaSource.sourceBuffers;\n for (let i = sourceBuffers.length; i--;) {\n if (open) {\n sourceBuffers[i].abort();\n }\n mediaSource.removeSourceBuffer(sourceBuffers[i]);\n }\n if (open) {\n // endOfStream could trigger exception if any sourcebuffer is in updating state\n // we don't really care about checking sourcebuffer state here,\n // as we are anyway detaching the MediaSource\n // let's just avoid this exception to propagate\n mediaSource.endOfStream();\n }\n } catch (err) {\n this.warn(`onMediaDetaching: ${err.message} while calling endOfStream`);\n }\n }\n // Clean up the SourceBuffers by invoking onBufferReset\n if (this.sourceBufferCount) {\n this.onBufferReset();\n }\n }\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);\n mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);\n if (this.appendSource) {\n mediaSource.removeEventListener('startstreaming', this._onStartStreaming);\n mediaSource.removeEventListener('endstreaming', this._onEndStreaming);\n }\n this.mediaSource = null;\n this._objectUrl = null;\n }\n\n // Detach properly the MediaSource from the HTMLMediaElement as\n // suggested in https://github.com/w3c/media-source/issues/53.\n if (media) {\n media.removeEventListener('emptied', this._onMediaEmptied);\n if (!transferringMedia) {\n if (_objectUrl) {\n self.URL.revokeObjectURL(_objectUrl);\n }\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.mediaSrc === _objectUrl) {\n media.removeAttribute('src');\n if (this.appendSource) {\n removeSourceChildren(media);\n }\n media.load();\n } else {\n this.warn('media|source.src was changed by a third party - skip cleanup');\n }\n }\n this.media = null;\n }\n this.hls.trigger(Events.MEDIA_DETACHED, data);\n }\n onBufferReset() {\n this.sourceBuffers.forEach(([type]) => {\n if (type) {\n this.resetBuffer(type);\n }\n });\n this.initTracks();\n }\n resetBuffer(type) {\n var _this$tracks$type;\n const sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;\n this.removeBuffer(type);\n if (sb) {\n try {\n var _this$mediaSource3;\n if ((_this$mediaSource3 = this.mediaSource) != null && _this$mediaSource3.sourceBuffers.length) {\n this.mediaSource.removeSourceBuffer(sb);\n }\n } catch (err) {\n this.warn(`onBufferReset ${type}`, err);\n }\n }\n delete this.tracks[type];\n }\n removeBuffer(type) {\n this.removeBufferListeners(type);\n this.sourceBuffers[sourceBufferNameToIndex(type)] = [null, null];\n const track = this.tracks[type];\n if (track) {\n track.buffer = undefined;\n }\n }\n resetQueue() {\n if (this.operationQueue) {\n this.operationQueue.destroy();\n }\n this.operationQueue = new BufferOperationQueue(this.tracks);\n }\n onBufferCodecs(event, data) {\n const tracks = this.tracks;\n const trackNames = Object.keys(data);\n this.log(`BUFFER_CODECS: \"${trackNames}\" (current SB count ${this.sourceBufferCount})`);\n const unmuxedToMuxed = 'audiovideo' in data && (tracks.audio || tracks.video) || tracks.audiovideo && ('audio' in data || 'video' in data);\n const muxedToUnmuxed = !unmuxedToMuxed && this.sourceBufferCount && this.media && trackNames.some(sbName => !tracks[sbName]);\n if (unmuxedToMuxed || muxedToUnmuxed) {\n this.warn(`Unsupported transition between \"${Object.keys(tracks)}\" and \"${trackNames}\" SourceBuffers`);\n // Do not add incompatible track ('audiovideo' <-> 'video'/'audio').\n // Allow following onBufferAppending handle to trigger BUFFER_APPEND_ERROR.\n // This will either be resolved by level switch or could be handled with recoverMediaError().\n return;\n }\n trackNames.forEach(trackName => {\n var _this$transferData3, _this$transferData3$t, _trackCodec;\n const parsedTrack = data[trackName];\n const {\n id,\n codec,\n levelCodec,\n container,\n metadata,\n supplemental\n } = parsedTrack;\n let track = tracks[trackName];\n const transferredTrack = (_this$transferData3 = this.transferData) == null ? void 0 : (_this$transferData3$t = _this$transferData3.tracks) == null ? void 0 : _this$transferData3$t[trackName];\n const sbTrack = transferredTrack != null && transferredTrack.buffer ? transferredTrack : track;\n const sbCodec = (sbTrack == null ? void 0 : sbTrack.pendingCodec) || (sbTrack == null ? void 0 : sbTrack.codec);\n const trackLevelCodec = sbTrack == null ? void 0 : sbTrack.levelCodec;\n if (!track) {\n track = tracks[trackName] = {\n buffer: undefined,\n listeners: [],\n codec,\n supplemental,\n container,\n levelCodec,\n metadata,\n id\n };\n }\n // check if SourceBuffer codec needs to change\n const currentCodecFull = pickMostCompleteCodecName(sbCodec, trackLevelCodec);\n const currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');\n let trackCodec = pickMostCompleteCodecName(codec, levelCodec);\n const nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');\n if (trackCodec && currentCodecFull && currentCodec !== nextCodec) {\n if (trackName.slice(0, 5) === 'audio') {\n trackCodec = getCodecCompatibleName(trackCodec, this.appendSource);\n }\n this.log(`switching codec ${sbCodec} to ${trackCodec}`);\n if (trackCodec !== (track.pendingCodec || track.codec)) {\n track.pendingCodec = trackCodec;\n }\n track.container = container;\n this.appendChangeType(trackName, container, trackCodec);\n }\n });\n if (this.tracksReady || this.sourceBufferCount) {\n data.tracks = this.sourceBufferTracks;\n }\n\n // if sourcebuffers already created, do nothing ...\n if (this.sourceBufferCount) {\n return;\n }\n if (this.mediaSourceOpenOrEnded) {\n this.checkPendingTracks();\n }\n }\n get sourceBufferTracks() {\n return Object.keys(this.tracks).reduce((baseTracks, type) => {\n const track = this.tracks[type];\n baseTracks[type] = {\n id: track.id,\n container: track.container,\n codec: track.codec,\n levelCodec: track.levelCodec\n };\n return baseTracks;\n }, {});\n }\n appendChangeType(type, container, codec) {\n const mimeType = `${container};codecs=${codec}`;\n const operation = {\n label: `change-type=${mimeType}`,\n execute: () => {\n const track = this.tracks[type];\n if (track) {\n const sb = track.buffer;\n if (sb != null && sb.changeType) {\n this.log(`changing ${type} sourceBuffer type to ${mimeType}`);\n sb.changeType(mimeType);\n track.codec = codec;\n track.container = container;\n }\n }\n this.shiftAndExecuteNext(type);\n },\n onStart: () => {},\n onComplete: () => {},\n onError: error => {\n this.warn(`Failed to change ${type} SourceBuffer type`, error);\n }\n };\n this.append(operation, type, this.isPending(this.tracks[type]));\n }\n blockAudio(partOrFrag) {\n var _this$fragmentTracker;\n const pStart = partOrFrag.start;\n const pTime = pStart + partOrFrag.duration * 0.05;\n const atGap = ((_this$fragmentTracker = this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker.gap) === true;\n if (atGap) {\n return;\n }\n const op = {\n label: 'block-audio',\n execute: () => {\n var _this$fragmentTracker2;\n const videoTrack = this.tracks.video;\n if (this.lastVideoAppendEnd > pTime || videoTrack != null && videoTrack.buffer && BufferHelper.isBuffered(videoTrack.buffer, pTime) || ((_this$fragmentTracker2 = this.fragmentTracker.getAppendedFrag(pTime, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker2.gap) === true) {\n this.blockedAudioAppend = null;\n this.shiftAndExecuteNext('audio');\n }\n },\n onStart: () => {},\n onComplete: () => {},\n onError: error => {\n this.warn('Error executing block-audio operation', error);\n }\n };\n this.blockedAudioAppend = {\n op,\n frag: partOrFrag\n };\n this.append(op, 'audio', true);\n }\n unblockAudio() {\n const {\n blockedAudioAppend,\n operationQueue\n } = this;\n if (blockedAudioAppend && operationQueue) {\n this.blockedAudioAppend = null;\n operationQueue.unblockAudio(blockedAudioAppend.op);\n }\n }\n onBufferAppending(event, eventData) {\n const {\n tracks\n } = this;\n const {\n data,\n type,\n parent,\n frag,\n part,\n chunkMeta\n } = eventData;\n const chunkStats = chunkMeta.buffering[type];\n const sn = frag.sn;\n const bufferAppendingStart = self.performance.now();\n chunkStats.start = bufferAppendingStart;\n const fragBuffering = frag.stats.buffering;\n const partBuffering = part ? part.stats.buffering : null;\n if (fragBuffering.start === 0) {\n fragBuffering.start = bufferAppendingStart;\n }\n if (partBuffering && partBuffering.start === 0) {\n partBuffering.start = bufferAppendingStart;\n }\n\n // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended\n // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)\n // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`\n // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).\n // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486\n const audioTrack = tracks.audio;\n let checkTimestampOffset = false;\n if (type === 'audio' && (audioTrack == null ? void 0 : audioTrack.container) === 'audio/mpeg') {\n checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;\n this.lastMpegAudioChunk = chunkMeta;\n }\n\n // Block audio append until overlapping video append\n const videoTrack = this.tracks.video;\n const videoSb = videoTrack == null ? void 0 : videoTrack.buffer;\n if (videoSb && sn !== 'initSegment') {\n const partOrFrag = part || frag;\n const blockedAudioAppend = this.blockedAudioAppend;\n if (type === 'audio' && parent !== 'main' && !this.blockedAudioAppend) {\n const pStart = partOrFrag.start;\n const pTime = pStart + partOrFrag.duration * 0.05;\n const vbuffered = videoSb.buffered;\n const vappending = this.currentOp('video');\n if (!vbuffered.length && !vappending) {\n // wait for video before appending audio\n this.blockAudio(partOrFrag);\n } else if (!vappending && !BufferHelper.isBuffered(videoSb, pTime) && this.lastVideoAppendEnd < pTime) {\n // audio is ahead of video\n this.blockAudio(partOrFrag);\n }\n } else if (type === 'video') {\n const videoAppendEnd = partOrFrag.end;\n if (blockedAudioAppend) {\n const audioStart = blockedAudioAppend.frag.start;\n if (videoAppendEnd > audioStart || videoAppendEnd < this.lastVideoAppendEnd || BufferHelper.isBuffered(videoSb, audioStart)) {\n this.unblockAudio();\n }\n }\n this.lastVideoAppendEnd = videoAppendEnd;\n }\n }\n const fragStart = (part || frag).start;\n const operation = {\n label: `append-${type}`,\n execute: () => {\n chunkStats.executeStart = self.performance.now();\n if (checkTimestampOffset) {\n const track = this.tracks[type];\n if (track) {\n const sb = track.buffer;\n if (sb) {\n const delta = fragStart - sb.timestampOffset;\n if (Math.abs(delta) >= 0.1) {\n this.log(`Updating audio SourceBuffer timestampOffset to ${fragStart} (delta: ${delta}) sn: ${sn})`);\n sb.timestampOffset = fragStart;\n }\n }\n }\n }\n this.appendExecutor(data, type);\n },\n onStart: () => {\n // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);\n },\n onComplete: () => {\n // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);\n const end = self.performance.now();\n chunkStats.executeEnd = chunkStats.end = end;\n if (fragBuffering.first === 0) {\n fragBuffering.first = end;\n }\n if (partBuffering && partBuffering.first === 0) {\n partBuffering.first = end;\n }\n const timeRanges = {};\n this.sourceBuffers.forEach(([type, sb]) => {\n if (type) {\n timeRanges[type] = BufferHelper.getBuffered(sb);\n }\n });\n this.appendErrors[type] = 0;\n if (type === 'audio' || type === 'video') {\n this.appendErrors.audiovideo = 0;\n } else {\n this.appendErrors.audio = 0;\n this.appendErrors.video = 0;\n }\n this.hls.trigger(Events.BUFFER_APPENDED, {\n type,\n frag,\n part,\n chunkMeta,\n parent: frag.type,\n timeRanges\n });\n },\n onError: error => {\n var _this$media;\n // in case any error occured while appending, put back segment in segments table\n const event = {\n type: ErrorTypes.MEDIA_ERROR,\n parent: frag.type,\n details: ErrorDetails.BUFFER_APPEND_ERROR,\n sourceBufferName: type,\n frag,\n part,\n chunkMeta,\n error,\n err: error,\n fatal: false\n };\n const mediaError = (_this$media = this.media) == null ? void 0 : _this$media.error;\n if (error.code === DOMException.QUOTA_EXCEEDED_ERR) {\n // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror\n // let's stop appending any segments, and report BUFFER_FULL_ERROR error\n event.details = ErrorDetails.BUFFER_FULL_ERROR;\n } else if (error.code === DOMException.INVALID_STATE_ERR && this.mediaSourceOpenOrEnded && !mediaError) {\n // Allow retry for \"Failed to execute 'appendBuffer' on 'SourceBuffer': This SourceBuffer is still processing\" errors\n event.errorAction = createDoNothingErrorAction(true);\n } else if (error.name === TRACK_REMOVED_ERROR_NAME && this.sourceBufferCount === 0) {\n // Do nothing if sourceBuffers were removed (media is detached and append was not aborted)\n event.errorAction = createDoNothingErrorAction(true);\n } else {\n const appendErrorCount = ++this.appendErrors[type];\n /* with UHD content, we could get loop of quota exceeded error until\n browser is able to evict some data from sourcebuffer. Retrying can help recover.\n */\n this.warn(`Failed ${appendErrorCount}/${this.hls.config.appendErrorMaxRetry} times to append segment in \"${type}\" sourceBuffer (${mediaError ? mediaError : 'no media error'})`);\n if (appendErrorCount >= this.hls.config.appendErrorMaxRetry || !!mediaError) {\n event.fatal = true;\n }\n }\n this.hls.trigger(Events.ERROR, event);\n }\n };\n this.append(operation, type, this.isPending(this.tracks[type]));\n }\n getFlushOp(type, start, end) {\n this.log(`queuing \"${type}\" remove ${start}-${end}`);\n return {\n label: 'remove',\n execute: () => {\n this.removeExecutor(type, start, end);\n },\n onStart: () => {\n // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n },\n onComplete: () => {\n // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n this.hls.trigger(Events.BUFFER_FLUSHED, {\n type\n });\n },\n onError: error => {\n this.warn(`Failed to remove ${start}-${end} from \"${type}\" SourceBuffer`, error);\n }\n };\n }\n onBufferFlushing(event, data) {\n const {\n type,\n startOffset,\n endOffset\n } = data;\n if (type) {\n this.append(this.getFlushOp(type, startOffset, endOffset), type);\n } else {\n this.sourceBuffers.forEach(([type]) => {\n if (type) {\n this.append(this.getFlushOp(type, startOffset, endOffset), type);\n }\n });\n }\n }\n onFragParsed(event, data) {\n const {\n frag,\n part\n } = data;\n const buffersAppendedTo = [];\n const elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;\n if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {\n buffersAppendedTo.push('audiovideo');\n } else {\n if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {\n buffersAppendedTo.push('audio');\n }\n if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {\n buffersAppendedTo.push('video');\n }\n }\n const onUnblocked = () => {\n const now = self.performance.now();\n frag.stats.buffering.end = now;\n if (part) {\n part.stats.buffering.end = now;\n }\n const stats = part ? part.stats : frag.stats;\n this.hls.trigger(Events.FRAG_BUFFERED, {\n frag,\n part,\n stats,\n id: frag.type\n });\n };\n if (buffersAppendedTo.length === 0) {\n this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`);\n }\n this.blockBuffers(onUnblocked, buffersAppendedTo).catch(error => {\n this.warn(`Fragment buffered callback ${error}`);\n this.stepOperationQueue(this.sourceBufferTypes);\n });\n }\n onFragChanged(event, data) {\n this.trimBuffers();\n }\n get bufferedToEnd() {\n return this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {\n var _this$tracks$type2, _this$tracks$type3;\n return type && (!((_this$tracks$type2 = this.tracks[type]) != null && _this$tracks$type2.ended) || ((_this$tracks$type3 = this.tracks[type]) == null ? void 0 : _this$tracks$type3.ending));\n });\n }\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as \"ending\" and \"ended\" and queue endOfStream after remaining operations(s)\n // an undefined data.type will mark all buffers as EOS.\n onBufferEos(event, data) {\n var _this$overrides;\n this.sourceBuffers.forEach(([type]) => {\n if (type) {\n const track = this.tracks[type];\n if (!data.type || data.type === type) {\n track.ending = true;\n if (!track.ended) {\n track.ended = true;\n this.log(`${type} buffer reached EOS`);\n }\n }\n }\n });\n const allowEndOfStream = ((_this$overrides = this.overrides) == null ? void 0 : _this$overrides.endOfStream) !== false;\n const allTracksEnding = this.sourceBufferCount > 0 && !this.sourceBuffers.some(([type]) => {\n var _this$tracks$type4;\n return type && !((_this$tracks$type4 = this.tracks[type]) != null && _this$tracks$type4.ended);\n });\n if (allTracksEnding) {\n if (allowEndOfStream) {\n this.log(`Queueing EOS`);\n this.blockUntilOpen(() => {\n this.tracksEnded();\n const {\n mediaSource\n } = this;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n if (mediaSource) {\n this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`);\n }\n return;\n }\n this.log(`Calling mediaSource.endOfStream()`);\n // Allow this to throw and be caught by the enqueueing function\n mediaSource.endOfStream();\n this.hls.trigger(Events.BUFFERED_TO_END, undefined);\n });\n } else {\n this.tracksEnded();\n this.hls.trigger(Events.BUFFERED_TO_END, undefined);\n }\n }\n }\n tracksEnded() {\n this.sourceBuffers.forEach(([type]) => {\n if (type !== null) {\n const track = this.tracks[type];\n if (track) {\n track.ending = false;\n }\n }\n });\n }\n onLevelUpdated(event, {\n details\n }) {\n if (!details.fragments.length) {\n return;\n }\n this.details = details;\n this.updateDuration();\n }\n updateDuration() {\n const durationAndRange = this.getDurationAndRange();\n if (!durationAndRange) {\n return;\n }\n this.blockUntilOpen(() => this.updateMediaSource(durationAndRange));\n }\n onError(event, data) {\n if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && data.frag) {\n var _data$errorAction;\n const nextAutoLevel = (_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.nextAutoLevel;\n if (isFiniteNumber(nextAutoLevel) && nextAutoLevel !== data.frag.level) {\n this.resetAppendErrors();\n }\n }\n }\n resetAppendErrors() {\n this.appendErrors = {\n audio: 0,\n video: 0,\n audiovideo: 0\n };\n }\n trimBuffers() {\n const {\n hls,\n details,\n media\n } = this;\n if (!media || details === null) {\n return;\n }\n if (!this.sourceBufferCount) {\n return;\n }\n const config = hls.config;\n const currentTime = media.currentTime;\n const targetDuration = details.levelTargetDuration;\n\n // Support for deprecated liveBackBufferLength\n const backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;\n if (isFiniteNumber(backBufferLength) && backBufferLength >= 0) {\n const maxBackBufferLength = Math.max(backBufferLength, targetDuration);\n const targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;\n this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);\n }\n if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {\n const frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);\n const maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);\n const targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;\n this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);\n }\n }\n flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {\n this.sourceBuffers.forEach(([type, sb]) => {\n if (sb) {\n const buffered = BufferHelper.getBuffered(sb);\n // when target buffer start exceeds actual buffer start\n if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {\n var _this$details;\n this.hls.trigger(Events.BACK_BUFFER_REACHED, {\n bufferEnd: targetBackBufferPosition\n });\n\n // Support for deprecated event:\n const track = this.tracks[type];\n if ((_this$details = this.details) != null && _this$details.live) {\n this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {\n bufferEnd: targetBackBufferPosition\n });\n } else if (track != null && track.ended) {\n this.log(`Cannot flush ${type} back buffer while SourceBuffer is in ended state`);\n return;\n }\n this.hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: targetBackBufferPosition,\n type\n });\n }\n }\n });\n }\n flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {\n this.sourceBuffers.forEach(([type, sb]) => {\n if (sb) {\n const buffered = BufferHelper.getBuffered(sb);\n const numBufferedRanges = buffered.length;\n // The buffer is either empty or contiguous\n if (numBufferedRanges < 2) {\n return;\n }\n const bufferStart = buffered.start(numBufferedRanges - 1);\n const bufferEnd = buffered.end(numBufferedRanges - 1);\n // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position\n if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {\n return;\n }\n this.hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: bufferStart,\n endOffset: Infinity,\n type\n });\n }\n });\n }\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n getDurationAndRange() {\n var _this$overrides2;\n const {\n details,\n mediaSource\n } = this;\n if (!details || !this.media || (mediaSource == null ? void 0 : mediaSource.readyState) !== 'open') {\n return null;\n }\n const playlistEnd = details.edge;\n if (details.live && this.hls.config.liveDurationInfinity) {\n const len = details.fragments.length;\n if (len && details.live && !!mediaSource.setLiveSeekableRange) {\n const start = Math.max(0, details.fragmentStart);\n const end = Math.max(start, playlistEnd);\n return {\n duration: Infinity,\n start,\n end\n };\n }\n return {\n duration: Infinity\n };\n }\n const overrideDuration = (_this$overrides2 = this.overrides) == null ? void 0 : _this$overrides2.duration;\n if (overrideDuration) {\n if (!isFiniteNumber(overrideDuration)) {\n return null;\n }\n return {\n duration: overrideDuration\n };\n }\n const mediaDuration = this.media.duration;\n const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;\n if (playlistEnd > msDuration && playlistEnd > mediaDuration || !isFiniteNumber(mediaDuration)) {\n return {\n duration: playlistEnd\n };\n }\n return null;\n }\n updateMediaSource({\n duration,\n start,\n end\n }) {\n const mediaSource = this.mediaSource;\n if (!this.media || !mediaSource || mediaSource.readyState !== 'open') {\n return;\n }\n if (mediaSource.duration !== duration) {\n if (isFiniteNumber(duration)) {\n this.log(`Updating MediaSource duration to ${duration.toFixed(3)}`);\n }\n mediaSource.duration = duration;\n }\n if (start !== undefined && end !== undefined) {\n this.log(`MediaSource duration is set to ${mediaSource.duration}. Setting seekable range to ${start}-${end}.`);\n mediaSource.setLiveSeekableRange(start, end);\n }\n }\n get tracksReady() {\n const pendingTrackCount = this.pendingTrackCount;\n return pendingTrackCount > 0 && (pendingTrackCount >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));\n }\n checkPendingTracks() {\n const {\n bufferCodecEventsTotal,\n pendingTrackCount,\n tracks\n } = this;\n this.log(`checkPendingTracks (pending: ${pendingTrackCount} codec events expected: ${bufferCodecEventsTotal}) ${stringify(tracks)}`);\n // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.\n // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after\n // data has been appended to existing ones.\n // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.\n if (this.tracksReady) {\n var _this$transferData4;\n const transferredTracks = (_this$transferData4 = this.transferData) == null ? void 0 : _this$transferData4.tracks;\n if (transferredTracks && Object.keys(transferredTracks).length) {\n this.attachTransferred();\n } else {\n // ok, let's create them now !\n this.createSourceBuffers();\n }\n }\n }\n bufferCreated() {\n if (this.sourceBufferCount) {\n const tracks = {};\n this.sourceBuffers.forEach(([type, buffer]) => {\n if (type) {\n const track = this.tracks[type];\n tracks[type] = {\n buffer,\n container: track.container,\n codec: track.codec,\n supplemental: track.supplemental,\n levelCodec: track.levelCodec,\n id: track.id,\n metadata: track.metadata\n };\n }\n });\n this.hls.trigger(Events.BUFFER_CREATED, {\n tracks\n });\n this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`);\n this.sourceBuffers.forEach(([type]) => {\n this.executeNext(type);\n });\n } else {\n const error = new Error('could not create source buffer for media codec(s)');\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n error,\n reason: error.message\n });\n }\n }\n createSourceBuffers() {\n const {\n tracks,\n sourceBuffers,\n mediaSource\n } = this;\n if (!mediaSource) {\n throw new Error('createSourceBuffers called when mediaSource was null');\n }\n for (const trackName in tracks) {\n const type = trackName;\n const track = tracks[type];\n if (this.isPending(track)) {\n const codec = this.getTrackCodec(track, type);\n const mimeType = `${track.container};codecs=${codec}`;\n track.codec = codec;\n this.log(`creating sourceBuffer(${mimeType})${this.currentOp(type) ? ' Queued' : ''} ${stringify(track)}`);\n try {\n const sb = mediaSource.addSourceBuffer(mimeType);\n const sbIndex = sourceBufferNameToIndex(type);\n const sbTuple = [type, sb];\n sourceBuffers[sbIndex] = sbTuple;\n track.buffer = sb;\n } catch (error) {\n var _this$operationQueue;\n this.error(`error while trying to add sourceBuffer: ${error.message}`);\n // remove init segment from queue and delete track info\n this.shiftAndExecuteNext(type);\n (_this$operationQueue = this.operationQueue) == null ? void 0 : _this$operationQueue.removeBlockers();\n delete this.tracks[type];\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,\n fatal: false,\n error,\n sourceBufferName: type,\n mimeType: mimeType,\n parent: track.id\n });\n return;\n }\n this.trackSourceBuffer(type, track);\n }\n }\n this.bufferCreated();\n }\n getTrackCodec(track, trackName) {\n // Use supplemental video codec when supported when adding SourceBuffer (#5558)\n const supplementalCodec = track.supplemental;\n let trackCodec = track.codec;\n if (supplementalCodec && (trackName === 'video' || trackName === 'audiovideo') && areCodecsMediaSourceSupported(supplementalCodec, 'video')) {\n trackCodec = replaceVideoCodec(trackCodec, supplementalCodec);\n }\n const codec = pickMostCompleteCodecName(trackCodec, track.levelCodec);\n if (codec) {\n if (trackName.slice(0, 5) === 'audio') {\n return getCodecCompatibleName(codec, this.appendSource);\n }\n return codec;\n }\n return '';\n }\n trackSourceBuffer(type, track) {\n const buffer = track.buffer;\n if (!buffer) {\n return;\n }\n const codec = this.getTrackCodec(track, type);\n this.tracks[type] = {\n buffer,\n codec,\n container: track.container,\n levelCodec: track.levelCodec,\n supplemental: track.supplemental,\n metadata: track.metadata,\n id: track.id,\n listeners: []\n };\n this.removeBufferListeners(type);\n this.addBufferListener(type, 'updatestart', this.onSBUpdateStart);\n this.addBufferListener(type, 'updateend', this.onSBUpdateEnd);\n this.addBufferListener(type, 'error', this.onSBUpdateError);\n // ManagedSourceBuffer bufferedchange event\n if (this.appendSource) {\n this.addBufferListener(type, 'bufferedchange', (type, event) => {\n // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.\n const removedRanges = event.removedRanges;\n if (removedRanges != null && removedRanges.length) {\n this.hls.trigger(Events.BUFFER_FLUSHED, {\n type: type\n });\n }\n });\n }\n }\n get mediaSrc() {\n var _this$media2, _this$media2$querySel;\n const media = ((_this$media2 = this.media) == null ? void 0 : (_this$media2$querySel = _this$media2.querySelector) == null ? void 0 : _this$media2$querySel.call(_this$media2, 'source')) || this.media;\n return media == null ? void 0 : media.src;\n }\n onSBUpdateStart(type) {\n const operation = this.currentOp(type);\n if (!operation) {\n return;\n }\n operation.onStart();\n }\n onSBUpdateEnd(type) {\n var _this$mediaSource4;\n if (((_this$mediaSource4 = this.mediaSource) == null ? void 0 : _this$mediaSource4.readyState) === 'closed') {\n this.resetBuffer(type);\n return;\n }\n const operation = this.currentOp(type);\n if (!operation) {\n return;\n }\n operation.onComplete();\n this.shiftAndExecuteNext(type);\n }\n onSBUpdateError(type, event) {\n var _this$mediaSource5;\n const error = new Error(`${type} SourceBuffer error. MediaSource readyState: ${(_this$mediaSource5 = this.mediaSource) == null ? void 0 : _this$mediaSource5.readyState}`);\n this.error(`${error}`, event);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_APPENDING_ERROR,\n sourceBufferName: type,\n error,\n fatal: false\n });\n // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue\n const operation = this.currentOp(type);\n if (operation) {\n operation.onError(error);\n }\n }\n\n // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually\n removeExecutor(type, startOffset, endOffset) {\n const {\n media,\n mediaSource\n } = this;\n const track = this.tracks[type];\n const sb = track == null ? void 0 : track.buffer;\n if (!media || !mediaSource || !sb) {\n this.warn(`Attempting to remove from the ${type} SourceBuffer, but it does not exist`);\n this.shiftAndExecuteNext(type);\n return;\n }\n const mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;\n const msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;\n const removeStart = Math.max(0, startOffset);\n const removeEnd = Math.min(endOffset, mediaDuration, msDuration);\n if (removeEnd > removeStart && (!track.ending || track.ended)) {\n track.ended = false;\n this.log(`Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`);\n sb.remove(removeStart, removeEnd);\n } else {\n // Cycle the queue\n this.shiftAndExecuteNext(type);\n }\n }\n\n // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually\n appendExecutor(data, type) {\n const track = this.tracks[type];\n const sb = track == null ? void 0 : track.buffer;\n if (!sb) {\n throw new HlsJsTrackRemovedError(`Attempting to append to the ${type} SourceBuffer, but it does not exist`);\n }\n track.ending = false;\n track.ended = false;\n sb.appendBuffer(data);\n }\n blockUntilOpen(callback) {\n if (this.isUpdating() || this.isQueued()) {\n this.blockBuffers(callback).catch(error => {\n this.warn(`SourceBuffer blocked callback ${error}`);\n this.stepOperationQueue(this.sourceBufferTypes);\n });\n } else {\n try {\n callback();\n } catch (error) {\n this.warn(`Callback run without blocking ${this.operationQueue} ${error}`);\n }\n }\n }\n isUpdating() {\n return this.sourceBuffers.some(([type, sb]) => type && sb.updating);\n }\n isQueued() {\n return this.sourceBuffers.some(([type]) => type && !!this.currentOp(type));\n }\n isPending(track) {\n return !!track && !track.buffer;\n }\n\n // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises\n // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue\n // upon completion, since we already do it here\n blockBuffers(onUnblocked, bufferNames = this.sourceBufferTypes) {\n if (!bufferNames.length) {\n this.log('Blocking operation requested, but no SourceBuffers exist');\n return Promise.resolve().then(onUnblocked);\n }\n const {\n operationQueue\n } = this;\n\n // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);\n const blockingOperations = bufferNames.map(type => this.appendBlocker(type));\n const audioBlocked = bufferNames.length > 1 && !!this.blockedAudioAppend;\n if (audioBlocked) {\n this.unblockAudio();\n }\n return Promise.all(blockingOperations).then(result => {\n if (operationQueue !== this.operationQueue) {\n return;\n }\n // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);\n onUnblocked();\n this.stepOperationQueue(this.sourceBufferTypes);\n });\n }\n stepOperationQueue(bufferNames) {\n bufferNames.forEach(type => {\n var _this$tracks$type5;\n const sb = (_this$tracks$type5 = this.tracks[type]) == null ? void 0 : _this$tracks$type5.buffer;\n // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to\n // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)\n // While this is a workaround, it's probably useful to have around\n if (!sb || sb.updating) {\n return;\n }\n this.shiftAndExecuteNext(type);\n });\n }\n append(operation, type, pending) {\n if (this.operationQueue) {\n this.operationQueue.append(operation, type, pending);\n }\n }\n appendBlocker(type) {\n if (this.operationQueue) {\n return this.operationQueue.appendBlocker(type);\n }\n }\n currentOp(type) {\n if (this.operationQueue) {\n return this.operationQueue.current(type);\n }\n return null;\n }\n executeNext(type) {\n if (type && this.operationQueue) {\n this.operationQueue.executeNext(type);\n }\n }\n shiftAndExecuteNext(type) {\n if (this.operationQueue) {\n this.operationQueue.shiftAndExecuteNext(type);\n }\n }\n get pendingTrackCount() {\n return Object.keys(this.tracks).reduce((acc, type) => acc + (this.isPending(this.tracks[type]) ? 1 : 0), 0);\n }\n get sourceBufferCount() {\n return this.sourceBuffers.reduce((acc, [type]) => acc + (type ? 1 : 0), 0);\n }\n get sourceBufferTypes() {\n return this.sourceBuffers.map(([type]) => type).filter(type => !!type);\n }\n addBufferListener(type, event, fn) {\n const track = this.tracks[type];\n if (!track) {\n return;\n }\n const buffer = track.buffer;\n if (!buffer) {\n return;\n }\n const listener = fn.bind(this, type);\n track.listeners.push({\n event,\n listener\n });\n buffer.addEventListener(event, listener);\n }\n removeBufferListeners(type) {\n const track = this.tracks[type];\n if (!track) {\n return;\n }\n const buffer = track.buffer;\n if (!buffer) {\n return;\n }\n track.listeners.forEach(l => {\n buffer.removeEventListener(l.event, l.listener);\n });\n track.listeners.length = 0;\n }\n}\nfunction removeSourceChildren(node) {\n const sourceChildren = node.querySelectorAll('source');\n [].slice.call(sourceChildren).forEach(source => {\n node.removeChild(source);\n });\n}\nfunction addSource(media, url) {\n const source = self.document.createElement('source');\n source.type = 'video/mp4';\n source.src = url;\n media.appendChild(source);\n}\nfunction sourceBufferNameToIndex(type) {\n return type === 'audio' ? 1 : 0;\n}\n\nclass CapLevelController {\n constructor(hls) {\n this.hls = void 0;\n this.autoLevelCapping = void 0;\n this.firstLevel = void 0;\n this.media = void 0;\n this.restrictedLevels = void 0;\n this.timer = void 0;\n this.clientRect = void 0;\n this.streamController = void 0;\n this.hls = hls;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = -1;\n this.media = null;\n this.restrictedLevels = [];\n this.timer = undefined;\n this.clientRect = null;\n this.registerListeners();\n }\n setStreamController(streamController) {\n this.streamController = streamController;\n }\n destroy() {\n if (this.hls) {\n this.unregisterListener();\n }\n if (this.timer) {\n this.stopCapping();\n }\n this.media = null;\n this.clientRect = null;\n // @ts-ignore\n this.hls = this.streamController = null;\n }\n registerListeners() {\n const {\n hls\n } = this;\n hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n unregisterListener() {\n const {\n hls\n } = this;\n hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n onFpsDropLevelCapping(event, data) {\n // Don't add a restricted level more than once\n const level = this.hls.levels[data.droppedLevel];\n if (this.isLevelAllowed(level)) {\n this.restrictedLevels.push({\n bitrate: level.bitrate,\n height: level.height,\n width: level.width\n });\n }\n }\n onMediaAttaching(event, data) {\n this.media = data.media instanceof HTMLVideoElement ? data.media : null;\n this.clientRect = null;\n if (this.timer && this.hls.levels.length) {\n this.detectPlayerSize();\n }\n }\n onManifestParsed(event, data) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // Start capping immediately if the manifest has signaled video codecs\n this.startCapping();\n }\n }\n onLevelsUpdated(event, data) {\n if (this.timer && isFiniteNumber(this.autoLevelCapping)) {\n this.detectPlayerSize();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n onBufferCodecs(event, data) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this.startCapping();\n }\n }\n onMediaDetaching() {\n this.stopCapping();\n this.media = null;\n }\n detectPlayerSize() {\n if (this.media) {\n if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {\n this.clientRect = null;\n return;\n }\n const levels = this.hls.levels;\n if (levels.length) {\n const hls = this.hls;\n const maxLevel = this.getMaxLevel(levels.length - 1);\n if (maxLevel !== this.autoLevelCapping) {\n hls.logger.log(`Setting autoLevelCapping to ${maxLevel}: ${levels[maxLevel].height}p@${levels[maxLevel].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);\n }\n hls.autoLevelCapping = maxLevel;\n if (hls.autoLevelEnabled && hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {\n // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n // usually happen when the user go to the fullscreen mode.\n this.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = hls.autoLevelCapping;\n }\n }\n }\n\n /*\n * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n */\n getMaxLevel(capLevelIndex) {\n const levels = this.hls.levels;\n if (!levels.length) {\n return -1;\n }\n const validLevels = levels.filter((level, index) => this.isLevelAllowed(level) && index <= capLevelIndex);\n this.clientRect = null;\n return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);\n }\n startCapping() {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n self.clearInterval(this.timer);\n this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n stopCapping() {\n this.restrictedLevels = [];\n this.firstLevel = -1;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n self.clearInterval(this.timer);\n this.timer = undefined;\n }\n }\n getDimensions() {\n if (this.clientRect) {\n return this.clientRect;\n }\n const media = this.media;\n const boundsRect = {\n width: 0,\n height: 0\n };\n if (media) {\n const clientRect = media.getBoundingClientRect();\n boundsRect.width = clientRect.width;\n boundsRect.height = clientRect.height;\n if (!boundsRect.width && !boundsRect.height) {\n // When the media element has no width or height (equivalent to not being in the DOM),\n // then use its width and height attributes (media.width, media.height)\n boundsRect.width = clientRect.right - clientRect.left || media.width || 0;\n boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;\n }\n }\n this.clientRect = boundsRect;\n return boundsRect;\n }\n get mediaWidth() {\n return this.getDimensions().width * this.contentScaleFactor;\n }\n get mediaHeight() {\n return this.getDimensions().height * this.contentScaleFactor;\n }\n get contentScaleFactor() {\n let pixelRatio = 1;\n if (!this.hls.config.ignoreDevicePixelRatio) {\n try {\n pixelRatio = self.devicePixelRatio;\n } catch (e) {\n /* no-op */\n }\n }\n return Math.min(pixelRatio, this.hls.config.maxDevicePixelRatio);\n }\n isLevelAllowed(level) {\n const restrictedLevels = this.restrictedLevels;\n return !restrictedLevels.some(restrictedLevel => {\n return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;\n });\n }\n static getMaxLevelByMediaSize(levels, width, height) {\n if (!(levels != null && levels.length)) {\n return -1;\n }\n\n // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n const atGreatestBandwidth = (curLevel, nextLevel) => {\n if (!nextLevel) {\n return true;\n }\n return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;\n };\n\n // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n // the max level\n let maxLevelIndex = levels.length - 1;\n // Prevent changes in aspect-ratio from causing capping to toggle back and forth\n const squareSize = Math.max(width, height);\n for (let i = 0; i < levels.length; i += 1) {\n const level = levels[i];\n if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {\n maxLevelIndex = i;\n break;\n }\n }\n return maxLevelIndex;\n }\n}\n\n/**\n * Common Media Object Type\n *\n * @internal\n */\nconst CmObjectType = {\n /**\n * text file, such as a manifest or playlist\n */\n MANIFEST: 'm',\n /**\n * audio only\n */\n AUDIO: 'a',\n /**\n * video only\n */\n VIDEO: 'v',\n /**\n * muxed audio and video\n */\n MUXED: 'av',\n /**\n * init segment\n */\n INIT: 'i',\n /**\n * caption or subtitle\n */\n CAPTION: 'c',\n /**\n * ISOBMFF timed text track\n */\n TIMED_TEXT: 'tt',\n /**\n * cryptographic key, license or certificate.\n */\n KEY: 'k',\n /**\n * other\n */\n OTHER: 'o'\n};\n\n/**\n * Common Media Client Data Object Type\n *\n * @group CMCD\n *\n * @beta\n *\n * @enum\n */\nconst CmcdObjectType = CmObjectType;\n\n/**\n * Common Media Streaming Format\n *\n * @internal\n */\nconst CmStreamingFormat = {\n /**\n * HTTP Live Streaming (HLS)\n */\n HLS: 'h'};\n\n/**\n * Common Media Client Data Streaming Format\n *\n * @group CMCD\n *\n * @enum\n *\n * @beta\n */\nconst CmcdStreamingFormat = CmStreamingFormat;\n\n/**\n * CMCD object header name.\n *\n * @group CMCD\n *\n * @beta\n */\nconst CMCD_OBJECT = 'CMCD-Object';\n\n/**\n * CMCD request header name.\n *\n * @group CMCD\n *\n * @beta\n */\nconst CMCD_REQUEST = 'CMCD-Request';\n\n/**\n * CMCD session header name.\n *\n * @group CMCD\n *\n * @beta\n */\nconst CMCD_SESSION = 'CMCD-Session';\n\n/**\n * CMCD status header name.\n *\n * @group CMCD\n *\n * @beta\n */\nconst CMCD_STATUS = 'CMCD-Status';\n\n/**\n * CMCD header fields.\n *\n * @group CMCD\n *\n * @enum\n *\n * @beta\n */\nconst CmcdHeaderField = {\n /**\n * keys whose values vary with the object being requested.\n */\n OBJECT: CMCD_OBJECT,\n /**\n * keys whose values vary with each request.\n */\n REQUEST: CMCD_REQUEST,\n /**\n * keys whose values are expected to be invariant over the life of the session.\n */\n SESSION: CMCD_SESSION,\n /**\n * keys whose values do not vary with every request or object.\n */\n STATUS: CMCD_STATUS\n};\n\n/**\n * The map of CMCD header fields to official CMCD keys.\n *\n * @internal\n *\n * @group CMCD\n */\nconst CmcdHeaderMap = {\n [CmcdHeaderField.OBJECT]: ['br', 'd', 'ot', 'tb'],\n [CmcdHeaderField.REQUEST]: ['bl', 'dl', 'mtp', 'nor', 'nrr', 'su'],\n [CmcdHeaderField.SESSION]: ['cid', 'pr', 'sf', 'sid', 'st', 'v'],\n [CmcdHeaderField.STATUS]: ['bs', 'rtp']\n};\n\n/**\n * Structured Field Item\n *\n * @group Structured Field\n *\n * @beta\n */\nclass SfItem {\n constructor(value, params) {\n if (Array.isArray(value)) {\n value = value.map(v => v instanceof SfItem ? v : new SfItem(v));\n }\n this.value = value;\n this.params = params;\n }\n}\n\nconst DICT = 'Dict';\n\nfunction format(value) {\n if (Array.isArray(value)) {\n return JSON.stringify(value);\n }\n if (value instanceof Map) {\n return 'Map{}';\n }\n if (value instanceof Set) {\n return 'Set{}';\n }\n if (typeof value === 'object') {\n return JSON.stringify(value);\n }\n return String(value);\n}\nfunction throwError(action, src, type, cause) {\n return new Error(`failed to ${action} \"${format(src)}\" as ${type}`, {\n cause\n });\n}\n\nfunction serializeError(src, type, cause) {\n return throwError('serialize', src, type, cause);\n}\n\n/**\n * A class to represent structured field tokens when `Symbol` is not available.\n *\n * @group Structured Field\n *\n * @beta\n */\nclass SfToken {\n constructor(description) {\n this.description = description;\n }\n}\n\nconst BARE_ITEM = 'Bare Item';\n\nconst BOOLEAN = 'Boolean';\n\n// 4.1.9. Serializing a Boolean\n//\n// Given a Boolean as input_boolean, return an ASCII string suitable for\n// use in a HTTP field value.\n//\n// 1. If input_boolean is not a boolean, fail serialization.\n//\n// 2. Let output be an empty string.\n//\n// 3. Append \"?\" to output.\n//\n// 4. If input_boolean is true, append \"1\" to output.\n//\n// 5. If input_boolean is false, append \"0\" to output.\n//\n// 6. Return output.\nfunction serializeBoolean(value) {\n if (typeof value !== 'boolean') {\n throw serializeError(value, BOOLEAN);\n }\n return value ? '?1' : '?0';\n}\n\nconst BYTES = 'Byte Sequence';\n\n// 4.1.8. Serializing a Byte Sequence\n//\n// Given a Byte Sequence as input_bytes, return an ASCII string suitable\n// for use in a HTTP field value.\n//\n// 1. If input_bytes is not a sequence of bytes, fail serialization.\n//\n// 2. Let output be an empty string.\n//\n// 3. Append \":\" to output.\n//\n// 4. Append the result of base64-encoding input_bytes as per\n// [RFC4648], Section 4, taking account of the requirements below.\n//\n// 5. Append \":\" to output.\n//\n// 6. Return output.\n//\n// The encoded data is required to be padded with \"=\", as per [RFC4648],\n// Section 3.2.\n//\n// Likewise, encoded data SHOULD have pad bits set to zero, as per\n// [RFC4648], Section 3.5, unless it is not possible to do so due to\n// implementation constraints.\nfunction serializeByteSequence(value) {\n if (ArrayBuffer.isView(value) === false) {\n throw serializeError(value, BYTES);\n }\n return `:${base64encode(value)}:`;\n}\n\nconst INTEGER = 'Integer';\n\nfunction isInvalidInt(value) {\n return value < -999999999999999 || 999999999999999 < value;\n}\n\n// 4.1.4. Serializing an Integer\n//\n// Given an Integer as input_integer, return an ASCII string suitable\n// for use in a HTTP field value.\n//\n// 1. If input_integer is not an integer in the range of\n// -999,999,999,999,999 to 999,999,999,999,999 inclusive, fail\n// serialization.\n//\n// 2. Let output be an empty string.\n//\n// 3. If input_integer is less than (but not equal to) 0, append \"-\" to\n// output.\n//\n// 4. Append input_integer's numeric value represented in base 10 using\n// only decimal digits to output.\n//\n// 5. Return output.\nfunction serializeInteger(value) {\n if (isInvalidInt(value)) {\n throw serializeError(value, INTEGER);\n }\n return value.toString();\n}\n\n// 4.1.10. Serializing a Date\n//\n// Given a Date as input_integer, return an ASCII string suitable for\n// use in an HTTP field value.\n// 1. Let output be \"@\".\n// 2. Append to output the result of running Serializing an Integer\n// with input_date (Section 4.1.4).\n// 3. Return output.\nfunction serializeDate(value) {\n return `@${serializeInteger(value.getTime() / 1000)}`;\n}\n\nconst DECIMAL = 'Decimal';\n\n// 4.1.5. Serializing a Decimal\n//\n// Given a decimal number as input_decimal, return an ASCII string\n// suitable for use in a HTTP field value.\n//\n// 1. If input_decimal is not a decimal number, fail serialization.\n//\n// 2. If input_decimal has more than three significant digits to the\n// right of the decimal point, round it to three decimal places,\n// rounding the final digit to the nearest value, or to the even\n// value if it is equidistant.\n//\n// 3. If input_decimal has more than 12 significant digits to the left\n// of the decimal point after rounding, fail serialization.\n//\n// 4. Let output be an empty string.\n//\n// 5. If input_decimal is less than (but not equal to) 0, append \"-\"\n// to output.\n//\n// 6. Append input_decimal's integer component represented in base 10\n// (using only decimal digits) to output; if it is zero, append\n// \"0\".\n//\n// 7. Append \".\" to output.\n//\n// 8. If input_decimal's fractional component is zero, append \"0\" to\n// output.\n//\n// 9. Otherwise, append the significant digits of input_decimal's\n// fractional component represented in base 10 (using only decimal\n// digits) to output.\n//\n// 10. Return output.\nfunction serializeDecimal(value) {\n const roundedValue = roundToEven(value, 3); // round to 3 decimal places\n if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {\n throw serializeError(value, DECIMAL);\n }\n const stringValue = roundedValue.toString();\n return stringValue.includes('.') ? stringValue : `${stringValue}.0`;\n}\n\nconst STRING = 'String';\n\nconst STRING_REGEX = /[\\x00-\\x1f\\x7f]+/; // eslint-disable-line no-control-regex\n\n// 4.1.6. Serializing a String\n//\n// Given a String as input_string, return an ASCII string suitable for\n// use in a HTTP field value.\n//\n// 1. Convert input_string into a sequence of ASCII characters; if\n// conversion fails, fail serialization.\n//\n// 2. If input_string contains characters in the range %x00-1f or %x7f\n// (i.e., not in VCHAR or SP), fail serialization.\n//\n// 3. Let output be the string DQUOTE.\n//\n// 4. For each character char in input_string:\n//\n// 1. If char is \"\\\" or DQUOTE:\n//\n// 1. Append \"\\\" to output.\n//\n// 2. Append char to output.\n//\n// 5. Append DQUOTE to output.\n//\n// 6. Return output.\nfunction serializeString(value) {\n if (STRING_REGEX.test(value)) {\n throw serializeError(value, STRING);\n }\n return `\"${value.replace(/\\\\/g, `\\\\\\\\`).replace(/\"/g, `\\\\\"`)}\"`;\n}\n\n/**\n * Converts a symbol to a string.\n *\n * @param symbol - The symbol to convert.\n *\n * @returns The string representation of the symbol.\n *\n * @internal\n */\nfunction symbolToStr(symbol) {\n return symbol.description || symbol.toString().slice(7, -1);\n}\n\nconst TOKEN = 'Token';\n\nfunction serializeToken(token) {\n const value = symbolToStr(token);\n if (/^([a-zA-Z*])([!#$%&'*+\\-.^_`|~\\w:/]*)$/.test(value) === false) {\n throw serializeError(value, TOKEN);\n }\n return value;\n}\n\n// 4.1.3.1. Serializing a Bare Item\n//\n// Given an Item as input_item, return an ASCII string suitable for use\n// in a HTTP field value.\n//\n// 1. If input_item is an Integer, return the result of running\n// Serializing an Integer (Section 4.1.4) with input_item.\n//\n// 2. If input_item is a Decimal, return the result of running\n// Serializing a Decimal (Section 4.1.5) with input_item.\n//\n// 3. If input_item is a String, return the result of running\n// Serializing a String (Section 4.1.6) with input_item.\n//\n// 4. If input_item is a Token, return the result of running\n// Serializing a Token (Section 4.1.7) with input_item.\n//\n// 5. If input_item is a Boolean, return the result of running\n// Serializing a Boolean (Section 4.1.9) with input_item.\n//\n// 6. If input_item is a Byte Sequence, return the result of running\n// Serializing a Byte Sequence (Section 4.1.8) with input_item.\n//\n// 7. If input_item is a Date, return the result of running Serializing\n// a Date (Section 4.1.10) with input_item.\n//\n// 8. Otherwise, fail serialization.\nfunction serializeBareItem(value) {\n switch (typeof value) {\n case 'number':\n if (!isFiniteNumber(value)) {\n throw serializeError(value, BARE_ITEM);\n }\n if (Number.isInteger(value)) {\n return serializeInteger(value);\n }\n return serializeDecimal(value);\n case 'string':\n return serializeString(value);\n case 'symbol':\n return serializeToken(value);\n case 'boolean':\n return serializeBoolean(value);\n case 'object':\n if (value instanceof Date) {\n return serializeDate(value);\n }\n if (value instanceof Uint8Array) {\n return serializeByteSequence(value);\n }\n if (value instanceof SfToken) {\n return serializeToken(value);\n }\n default:\n // fail\n throw serializeError(value, BARE_ITEM);\n }\n}\n\nconst KEY = 'Key';\n\n// 4.1.1.3. Serializing a Key\n//\n// Given a key as input_key, return an ASCII string suitable for use in\n// a HTTP field value.\n//\n// 1. Convert input_key into a sequence of ASCII characters; if\n// conversion fails, fail serialization.\n//\n// 2. If input_key contains characters not in lcalpha, DIGIT, \"_\", \"-\",\n// \".\", or \"*\" fail serialization.\n//\n// 3. If the first character of input_key is not lcalpha or \"*\", fail\n// serialization.\n//\n// 4. Let output be an empty string.\n//\n// 5. Append input_key to output.\n//\n// 6. Return output.\nfunction serializeKey(value) {\n if (/^[a-z*][a-z0-9\\-_.*]*$/.test(value) === false) {\n throw serializeError(value, KEY);\n }\n return value;\n}\n\n// 4.1.1.2. Serializing Parameters\n//\n// Given an ordered Dictionary as input_parameters (each member having a\n// param_name and a param_value), return an ASCII string suitable for\n// use in a HTTP field value.\n//\n// 1. Let output be an empty string.\n//\n// 2. For each param_name with a value of param_value in\n// input_parameters:\n//\n// 1. Append \";\" to output.\n//\n// 2. Append the result of running Serializing a Key\n// (Section 4.1.1.3) with param_name to output.\n//\n// 3. If param_value is not Boolean true:\n//\n// 1. Append \"=\" to output.\n//\n// 2. Append the result of running Serializing a bare Item\n// (Section 4.1.3.1) with param_value to output.\n//\n// 3. Return output.\nfunction serializeParams(params) {\n if (params == null) {\n return '';\n }\n return Object.entries(params).map(([key, value]) => {\n if (value === true) {\n return `;${serializeKey(key)}`; // omit true\n }\n return `;${serializeKey(key)}=${serializeBareItem(value)}`;\n }).join('');\n}\n\n// 4.1.3. Serializing an Item\n//\n// Given an Item as bare_item and Parameters as item_parameters, return\n// an ASCII string suitable for use in a HTTP field value.\n//\n// 1. Let output be an empty string.\n//\n// 2. Append the result of running Serializing a Bare Item\n// Section 4.1.3.1 with bare_item to output.\n//\n// 3. Append the result of running Serializing Parameters\n// Section 4.1.1.2 with item_parameters to output.\n//\n// 4. Return output.\nfunction serializeItem(value) {\n if (value instanceof SfItem) {\n return `${serializeBareItem(value.value)}${serializeParams(value.params)}`;\n } else {\n return serializeBareItem(value);\n }\n}\n\n// 4.1.1.1. Serializing an Inner List\n//\n// Given an array of (member_value, parameters) tuples as inner_list,\n// and parameters as list_parameters, return an ASCII string suitable\n// for use in a HTTP field value.\n//\n// 1. Let output be the string \"(\".\n//\n// 2. For each (member_value, parameters) of inner_list:\n//\n// 1. Append the result of running Serializing an Item\n// (Section 4.1.3) with (member_value, parameters) to output.\n//\n// 2. If more values remain in inner_list, append a single SP to\n// output.\n//\n// 3. Append \")\" to output.\n//\n// 4. Append the result of running Serializing Parameters\n// (Section 4.1.1.2) with list_parameters to output.\n//\n// 5. Return output.\nfunction serializeInnerList(value) {\n return `(${value.value.map(serializeItem).join(' ')})${serializeParams(value.params)}`;\n}\n\n// 4.1.2. Serializing a Dictionary\n//\n// Given an ordered Dictionary as input_dictionary (each member having a\n// member_name and a tuple value of (member_value, parameters)), return\n// an ASCII string suitable for use in a HTTP field value.\n//\n// 1. Let output be an empty string.\n//\n// 2. For each member_name with a value of (member_value, parameters)\n// in input_dictionary:\n//\n// 1. Append the result of running Serializing a Key\n// (Section 4.1.1.3) with member's member_name to output.\n//\n// 2. If member_value is Boolean true:\n//\n// 1. Append the result of running Serializing Parameters\n// (Section 4.1.1.2) with parameters to output.\n//\n// 3. Otherwise:\n//\n// 1. Append \"=\" to output.\n//\n// 2. If member_value is an array, append the result of running\n// Serializing an Inner List (Section 4.1.1.1) with\n// (member_value, parameters) to output.\n//\n// 3. Otherwise, append the result of running Serializing an\n// Item (Section 4.1.3) with (member_value, parameters) to\n// output.\n//\n// 4. If more members remain in input_dictionary:\n//\n// 1. Append \",\" to output.\n//\n// 2. Append a single SP to output.\n//\n// 3. Return output.\nfunction serializeDict(dict, options = {\n whitespace: true\n}) {\n if (typeof dict !== 'object') {\n throw serializeError(dict, DICT);\n }\n const entries = dict instanceof Map ? dict.entries() : Object.entries(dict);\n const optionalWhiteSpace = (options === null || options === void 0 ? void 0 : options.whitespace) ? ' ' : '';\n return Array.from(entries).map(([key, item]) => {\n if (item instanceof SfItem === false) {\n item = new SfItem(item);\n }\n let output = serializeKey(key);\n if (item.value === true) {\n output += serializeParams(item.params);\n } else {\n output += '=';\n if (Array.isArray(item.value)) {\n output += serializeInnerList(item);\n } else {\n output += serializeItem(item);\n }\n }\n return output;\n }).join(`,${optionalWhiteSpace}`);\n}\n\n/**\n * Encode an object into a structured field dictionary\n *\n * @param value - The structured field dictionary to encode\n * @param options - Encoding options\n *\n * @returns The structured field string\n *\n * @group Structured Field\n *\n * @beta\n */\nfunction encodeSfDict(value, options) {\n return serializeDict(value, options);\n}\n\n/**\n * Checks if the given key is a token field.\n *\n * @param key - The key to check.\n *\n * @returns `true` if the key is a token field.\n *\n * @internal\n */\nfunction isTokenField(key) {\n return key === 'ot' || key === 'sf' || key === 'st';\n}\n\n/**\n * Checks if the given value is valid\n *\n * @param value - The value to check.\n *\n * @returns `true` if the key is a value is valid.\n *\n * @internal\n */\nfunction isValid(value) {\n if (typeof value === 'number') {\n return isFiniteNumber(value);\n }\n return value != null && value !== '' && value !== false;\n}\n\nconst toRounded = value => Math.round(value);\nconst toUrlSafe = (value, options) => {\n if (options === null || options === void 0 ? void 0 : options.baseUrl) {\n value = urlToRelativePath(value, options.baseUrl);\n }\n return encodeURIComponent(value);\n};\nconst toHundred = value => toRounded(value / 100) * 100;\n/**\n * The default formatters for CMCD values.\n *\n * @group CMCD\n *\n * @beta\n */\nconst CmcdFormatters = {\n /**\n * Bitrate (kbps) rounded integer\n */\n br: toRounded,\n /**\n * Duration (milliseconds) rounded integer\n */\n d: toRounded,\n /**\n * Buffer Length (milliseconds) rounded nearest 100ms\n */\n bl: toHundred,\n /**\n * Deadline (milliseconds) rounded nearest 100ms\n */\n dl: toHundred,\n /**\n * Measured Throughput (kbps) rounded nearest 100kbps\n */\n mtp: toHundred,\n /**\n * Next Object Request URL encoded\n */\n nor: toUrlSafe,\n /**\n * Requested maximum throughput (kbps) rounded nearest 100kbps\n */\n rtp: toHundred,\n /**\n * Top Bitrate (kbps) rounded integer\n */\n tb: toRounded\n};\n\n/**\n * Internal CMCD processing function.\n *\n * @param obj - The CMCD object to process.\n * @param map - The mapping function to use.\n * @param options - Options for encoding.\n *\n * @internal\n *\n * @group CMCD\n */\nfunction processCmcd(obj, options) {\n const results = {};\n if (obj == null || typeof obj !== 'object') {\n return results;\n }\n const keys = Object.keys(obj).sort();\n const formatters = _extends({}, CmcdFormatters, options === null || options === void 0 ? void 0 : options.formatters);\n const filter = options === null || options === void 0 ? void 0 : options.filter;\n keys.forEach(key => {\n if (filter === null || filter === void 0 ? void 0 : filter(key)) {\n return;\n }\n let value = obj[key];\n const formatter = formatters[key];\n if (formatter) {\n value = formatter(value, options);\n }\n // Version should only be reported if not equal to 1.\n if (key === 'v' && value === 1) {\n return;\n }\n // Playback rate should only be sent if not equal to 1.\n if (key == 'pr' && value === 1) {\n return;\n }\n // ignore invalid values\n if (!isValid(value)) {\n return;\n }\n if (isTokenField(key) && typeof value === 'string') {\n value = new SfToken(value);\n }\n results[key] = value;\n });\n return results;\n}\n\n/**\n * Encode a CMCD object to a string.\n *\n * @param cmcd - The CMCD object to encode.\n * @param options - Options for encoding.\n *\n * @returns The encoded CMCD string.\n *\n * @group CMCD\n *\n * @beta\n */\nfunction encodeCmcd(cmcd, options = {}) {\n if (!cmcd) {\n return '';\n }\n return encodeSfDict(processCmcd(cmcd, options), _extends({\n whitespace: false\n }, options));\n}\n\n/**\n * Convert a CMCD data object to request headers\n *\n * @param cmcd - The CMCD data object to convert.\n * @param options - Options for encoding the CMCD object.\n *\n * @returns The CMCD header shards.\n *\n * @group CMCD\n *\n * @beta\n */\nfunction toCmcdHeaders(cmcd, options = {}) {\n const result = {};\n if (!cmcd) {\n return result;\n }\n const entries = Object.entries(cmcd);\n const headerMap = Object.entries(CmcdHeaderMap).concat(Object.entries((options === null || options === void 0 ? void 0 : options.customHeaderMap) || {}));\n const shards = entries.reduce((acc, entry) => {\n var _a, _b;\n const [key, value] = entry;\n const field = ((_a = headerMap.find(entry => entry[1].includes(key))) === null || _a === void 0 ? void 0 : _a[0]) || CmcdHeaderField.REQUEST;\n (_b = acc[field]) !== null && _b !== void 0 ? _b : acc[field] = {};\n acc[field][key] = value;\n return acc;\n }, {});\n return Object.entries(shards).reduce((acc, [field, value]) => {\n acc[field] = encodeCmcd(value, options);\n return acc;\n }, result);\n}\n\n/**\n * Append CMCD query args to a header object.\n *\n * @param headers - The headers to append to.\n * @param cmcd - The CMCD object to append.\n * @param options - Encode options.\n *\n * @returns The headers with the CMCD header shards appended.\n *\n * @group CMCD\n *\n * @beta\n */\nfunction appendCmcdHeaders(headers, cmcd, options) {\n return _extends(headers, toCmcdHeaders(cmcd, options));\n}\n\n/**\n * CMCD parameter name.\n *\n * @group CMCD\n *\n * @beta\n */\nconst CMCD_PARAM = 'CMCD';\n\n/**\n * Convert a CMCD data object to a query arg.\n *\n * @param cmcd - The CMCD object to convert.\n * @param options - Options for encoding the CMCD object.\n *\n * @returns The CMCD query arg.\n *\n * @group CMCD\n *\n * @beta\n */\nfunction toCmcdQuery(cmcd, options = {}) {\n if (!cmcd) {\n return '';\n }\n const params = encodeCmcd(cmcd, options);\n return `${CMCD_PARAM}=${encodeURIComponent(params)}`;\n}\n\nconst REGEX = /CMCD=[^&#]+/;\n/**\n * Append CMCD query args to a URL.\n *\n * @param url - The URL to append to.\n * @param cmcd - The CMCD object to append.\n * @param options - Options for encoding the CMCD object.\n *\n * @returns The URL with the CMCD query args appended.\n *\n * @group CMCD\n *\n * @beta\n */\nfunction appendCmcdQuery(url, cmcd, options) {\n // TODO: Replace with URLSearchParams once we drop Safari < 10.1 & Chrome < 49 support.\n // https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\n const query = toCmcdQuery(cmcd, options);\n if (!query) {\n return url;\n }\n if (REGEX.test(url)) {\n return url.replace(REGEX, query);\n }\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}${query}`;\n}\n\n/**\n * Controller to deal with Common Media Client Data (CMCD)\n * @see https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf\n */\nclass CMCDController {\n constructor(hls) {\n this.hls = void 0;\n this.config = void 0;\n this.media = void 0;\n this.sid = void 0;\n this.cid = void 0;\n this.useHeaders = false;\n this.includeKeys = void 0;\n this.initialized = false;\n this.starved = false;\n this.buffering = true;\n this.audioBuffer = void 0;\n this.videoBuffer = void 0;\n this.onWaiting = () => {\n if (this.initialized) {\n this.starved = true;\n }\n this.buffering = true;\n };\n this.onPlaying = () => {\n if (!this.initialized) {\n this.initialized = true;\n }\n this.buffering = false;\n };\n /**\n * Apply CMCD data to a manifest request.\n */\n this.applyPlaylistData = context => {\n try {\n this.apply(context, {\n ot: CmcdObjectType.MANIFEST,\n su: !this.initialized\n });\n } catch (error) {\n this.hls.logger.warn('Could not generate manifest CMCD data.', error);\n }\n };\n /**\n * Apply CMCD data to a segment request\n */\n this.applyFragmentData = context => {\n try {\n const {\n frag,\n part\n } = context;\n const level = this.hls.levels[frag.level];\n const ot = this.getObjectType(frag);\n const data = {\n d: (part || frag).duration * 1000,\n ot\n };\n if (ot === CmcdObjectType.VIDEO || ot === CmcdObjectType.AUDIO || ot == CmcdObjectType.MUXED) {\n data.br = level.bitrate / 1000;\n data.tb = this.getTopBandwidth(ot) / 1000;\n data.bl = this.getBufferLength(ot);\n }\n const next = part ? this.getNextPart(part) : this.getNextFrag(frag);\n if (next != null && next.url && next.url !== frag.url) {\n data.nor = next.url;\n }\n this.apply(context, data);\n } catch (error) {\n this.hls.logger.warn('Could not generate segment CMCD data.', error);\n }\n };\n this.hls = hls;\n const config = this.config = hls.config;\n const {\n cmcd\n } = config;\n if (cmcd != null) {\n config.pLoader = this.createPlaylistLoader();\n config.fLoader = this.createFragmentLoader();\n this.sid = cmcd.sessionId || hls.sessionId;\n this.cid = cmcd.contentId;\n this.useHeaders = cmcd.useHeaders === true;\n this.includeKeys = cmcd.includeKeys;\n this.registerListeners();\n }\n }\n registerListeners() {\n const hls = this.hls;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n }\n unregisterListeners() {\n const hls = this.hls;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n }\n destroy() {\n this.unregisterListeners();\n this.onMediaDetached();\n\n // @ts-ignore\n this.hls = this.config = this.audioBuffer = this.videoBuffer = null;\n // @ts-ignore\n this.onWaiting = this.onPlaying = this.media = null;\n }\n onMediaAttached(event, data) {\n this.media = data.media;\n this.media.addEventListener('waiting', this.onWaiting);\n this.media.addEventListener('playing', this.onPlaying);\n }\n onMediaDetached() {\n if (!this.media) {\n return;\n }\n this.media.removeEventListener('waiting', this.onWaiting);\n this.media.removeEventListener('playing', this.onPlaying);\n\n // @ts-ignore\n this.media = null;\n }\n onBufferCreated(event, data) {\n var _data$tracks$audio, _data$tracks$video;\n this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer;\n this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer;\n }\n /**\n * Create baseline CMCD data\n */\n createData() {\n var _this$media;\n return {\n v: 1,\n sf: CmcdStreamingFormat.HLS,\n sid: this.sid,\n cid: this.cid,\n pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate,\n mtp: this.hls.bandwidthEstimate / 1000\n };\n }\n\n /**\n * Apply CMCD data to a request.\n */\n apply(context, data = {}) {\n // apply baseline data\n _extends(data, this.createData());\n const isVideo = data.ot === CmcdObjectType.INIT || data.ot === CmcdObjectType.VIDEO || data.ot === CmcdObjectType.MUXED;\n if (this.starved && isVideo) {\n data.bs = true;\n data.su = true;\n this.starved = false;\n }\n if (data.su == null) {\n data.su = this.buffering;\n }\n\n // TODO: Implement rtp, nrr, dl\n\n const {\n includeKeys\n } = this;\n if (includeKeys) {\n data = Object.keys(data).reduce((acc, key) => {\n includeKeys.includes(key) && (acc[key] = data[key]);\n return acc;\n }, {});\n }\n const options = {\n baseUrl: context.url\n };\n if (this.useHeaders) {\n if (!context.headers) {\n context.headers = {};\n }\n appendCmcdHeaders(context.headers, data, options);\n } else {\n context.url = appendCmcdQuery(context.url, data, options);\n }\n }\n getNextFrag(fragment) {\n var _this$hls$levels$frag;\n const levelDetails = (_this$hls$levels$frag = this.hls.levels[fragment.level]) == null ? void 0 : _this$hls$levels$frag.details;\n if (levelDetails) {\n const index = fragment.sn - levelDetails.startSN;\n return levelDetails.fragments[index + 1];\n }\n return undefined;\n }\n getNextPart(part) {\n var _this$hls$levels$frag2, _this$hls$levels$frag3;\n const {\n index,\n fragment\n } = part;\n const partList = (_this$hls$levels$frag2 = this.hls.levels[fragment.level]) == null ? void 0 : (_this$hls$levels$frag3 = _this$hls$levels$frag2.details) == null ? void 0 : _this$hls$levels$frag3.partList;\n if (partList) {\n const {\n sn\n } = fragment;\n for (let i = partList.length - 1; i >= 0; i--) {\n const p = partList[i];\n if (p.index === index && p.fragment.sn === sn) {\n return partList[i + 1];\n }\n }\n }\n return undefined;\n }\n\n /**\n * The CMCD object type.\n */\n getObjectType(fragment) {\n const {\n type\n } = fragment;\n if (type === 'subtitle') {\n return CmcdObjectType.TIMED_TEXT;\n }\n if (fragment.sn === 'initSegment') {\n return CmcdObjectType.INIT;\n }\n if (type === 'audio') {\n return CmcdObjectType.AUDIO;\n }\n if (type === 'main') {\n if (!this.hls.audioTracks.length) {\n return CmcdObjectType.MUXED;\n }\n return CmcdObjectType.VIDEO;\n }\n return undefined;\n }\n\n /**\n * Get the highest bitrate.\n */\n getTopBandwidth(type) {\n let bitrate = 0;\n let levels;\n const hls = this.hls;\n if (type === CmcdObjectType.AUDIO) {\n levels = hls.audioTracks;\n } else {\n const max = hls.maxAutoLevel;\n const len = max > -1 ? max + 1 : hls.levels.length;\n levels = hls.levels.slice(0, len);\n }\n for (const level of levels) {\n if (level.bitrate > bitrate) {\n bitrate = level.bitrate;\n }\n }\n return bitrate > 0 ? bitrate : NaN;\n }\n\n /**\n * Get the buffer length for a media type in milliseconds\n */\n getBufferLength(type) {\n const media = this.media;\n const buffer = type === CmcdObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;\n if (!buffer || !media) {\n return NaN;\n }\n const info = BufferHelper.bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);\n return info.len * 1000;\n }\n\n /**\n * Create a playlist loader\n */\n createPlaylistLoader() {\n const {\n pLoader\n } = this.config;\n const apply = this.applyPlaylistData;\n const Ctor = pLoader || this.config.loader;\n return class CmcdPlaylistLoader {\n constructor(config) {\n this.loader = void 0;\n this.loader = new Ctor(config);\n }\n get stats() {\n return this.loader.stats;\n }\n get context() {\n return this.loader.context;\n }\n destroy() {\n this.loader.destroy();\n }\n abort() {\n this.loader.abort();\n }\n load(context, config, callbacks) {\n apply(context);\n this.loader.load(context, config, callbacks);\n }\n };\n }\n\n /**\n * Create a playlist loader\n */\n createFragmentLoader() {\n const {\n fLoader\n } = this.config;\n const apply = this.applyFragmentData;\n const Ctor = fLoader || this.config.loader;\n return class CmcdFragmentLoader {\n constructor(config) {\n this.loader = void 0;\n this.loader = new Ctor(config);\n }\n get stats() {\n return this.loader.stats;\n }\n get context() {\n return this.loader.context;\n }\n destroy() {\n this.loader.destroy();\n }\n abort() {\n this.loader.abort();\n }\n load(context, config, callbacks) {\n apply(context);\n this.loader.load(context, config, callbacks);\n }\n };\n }\n}\n\nconst PATHWAY_PENALTY_DURATION_MS = 300000;\nclass ContentSteeringController extends Logger {\n constructor(hls) {\n super('content-steering', hls.logger);\n this.hls = void 0;\n this.loader = null;\n this.uri = null;\n this.pathwayId = '.';\n this._pathwayPriority = null;\n this.timeToLoad = 300;\n this.reloadTimer = -1;\n this.updated = 0;\n this.started = false;\n this.enabled = true;\n this.levels = null;\n this.audioTracks = null;\n this.subtitleTracks = null;\n this.penalizedPathways = {};\n this.hls = hls;\n this.registerListeners();\n }\n registerListeners() {\n const hls = this.hls;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n unregisterListeners() {\n const hls = this.hls;\n if (!hls) {\n return;\n }\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n pathways() {\n return (this.levels || []).reduce((pathways, level) => {\n if (pathways.indexOf(level.pathwayId) === -1) {\n pathways.push(level.pathwayId);\n }\n return pathways;\n }, []);\n }\n get pathwayPriority() {\n return this._pathwayPriority;\n }\n set pathwayPriority(pathwayPriority) {\n this.updatePathwayPriority(pathwayPriority);\n }\n startLoad() {\n this.started = true;\n this.clearTimeout();\n if (this.enabled && this.uri) {\n if (this.updated) {\n const ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);\n if (ttl > 0) {\n this.scheduleRefresh(this.uri, ttl);\n return;\n }\n }\n this.loadSteeringManifest(this.uri);\n }\n }\n stopLoad() {\n this.started = false;\n if (this.loader) {\n this.loader.destroy();\n this.loader = null;\n }\n this.clearTimeout();\n }\n clearTimeout() {\n if (this.reloadTimer !== -1) {\n self.clearTimeout(this.reloadTimer);\n this.reloadTimer = -1;\n }\n }\n destroy() {\n this.unregisterListeners();\n this.stopLoad();\n // @ts-ignore\n this.hls = null;\n this.levels = this.audioTracks = this.subtitleTracks = null;\n }\n removeLevel(levelToRemove) {\n const levels = this.levels;\n if (levels) {\n this.levels = levels.filter(level => level !== levelToRemove);\n }\n }\n onManifestLoading() {\n this.stopLoad();\n this.enabled = true;\n this.timeToLoad = 300;\n this.updated = 0;\n this.uri = null;\n this.pathwayId = '.';\n this.levels = this.audioTracks = this.subtitleTracks = null;\n }\n onManifestLoaded(event, data) {\n const {\n contentSteering\n } = data;\n if (contentSteering === null) {\n return;\n }\n this.pathwayId = contentSteering.pathwayId;\n this.uri = contentSteering.uri;\n if (this.started) {\n this.startLoad();\n }\n }\n onManifestParsed(event, data) {\n this.audioTracks = data.audioTracks;\n this.subtitleTracks = data.subtitleTracks;\n }\n onError(event, data) {\n const {\n errorAction\n } = data;\n if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {\n const levels = this.levels;\n let pathwayPriority = this._pathwayPriority;\n let errorPathway = this.pathwayId;\n if (data.context) {\n const {\n groupId,\n pathwayId,\n type\n } = data.context;\n if (groupId && levels) {\n errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);\n } else if (pathwayId) {\n errorPathway = pathwayId;\n }\n }\n if (!(errorPathway in this.penalizedPathways)) {\n this.penalizedPathways[errorPathway] = performance.now();\n }\n if (!pathwayPriority && levels) {\n // If PATHWAY-PRIORITY was not provided, list pathways for error handling\n pathwayPriority = this.pathways();\n }\n if (pathwayPriority && pathwayPriority.length > 1) {\n this.updatePathwayPriority(pathwayPriority);\n errorAction.resolved = this.pathwayId !== errorPathway;\n }\n if (!errorAction.resolved) {\n this.warn(`Could not resolve ${data.details} (\"${data.error.message}\") with content-steering for Pathway: ${errorPathway} levels: ${levels ? levels.length : levels} priorities: ${stringify(pathwayPriority)} penalized: ${stringify(this.penalizedPathways)}`);\n }\n }\n }\n filterParsedLevels(levels) {\n // Filter levels to only include those that are in the initial pathway\n this.levels = levels;\n let pathwayLevels = this.getLevelsForPathway(this.pathwayId);\n if (pathwayLevels.length === 0) {\n const pathwayId = levels[0].pathwayId;\n this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to \"${pathwayId}\"`);\n pathwayLevels = this.getLevelsForPathway(pathwayId);\n this.pathwayId = pathwayId;\n }\n if (pathwayLevels.length !== levels.length) {\n this.log(`Found ${pathwayLevels.length}/${levels.length} levels in Pathway \"${this.pathwayId}\"`);\n }\n return pathwayLevels;\n }\n getLevelsForPathway(pathwayId) {\n if (this.levels === null) {\n return [];\n }\n return this.levels.filter(level => pathwayId === level.pathwayId);\n }\n updatePathwayPriority(pathwayPriority) {\n this._pathwayPriority = pathwayPriority;\n let levels;\n\n // Evaluate if we should remove the pathway from the penalized list\n const penalizedPathways = this.penalizedPathways;\n const now = performance.now();\n Object.keys(penalizedPathways).forEach(pathwayId => {\n if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {\n delete penalizedPathways[pathwayId];\n }\n });\n for (let i = 0; i < pathwayPriority.length; i++) {\n const pathwayId = pathwayPriority[i];\n if (pathwayId in penalizedPathways) {\n continue;\n }\n if (pathwayId === this.pathwayId) {\n return;\n }\n const selectedIndex = this.hls.nextLoadLevel;\n const selectedLevel = this.hls.levels[selectedIndex];\n levels = this.getLevelsForPathway(pathwayId);\n if (levels.length > 0) {\n this.log(`Setting Pathway to \"${pathwayId}\"`);\n this.pathwayId = pathwayId;\n reassignFragmentLevelIndexes(levels);\n this.hls.trigger(Events.LEVELS_UPDATED, {\n levels\n });\n // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed\n const levelAfterChange = this.hls.levels[selectedIndex];\n if (selectedLevel && levelAfterChange && this.levels) {\n if (levelAfterChange.attrs['STABLE-VARIANT-ID'] !== selectedLevel.attrs['STABLE-VARIANT-ID'] && levelAfterChange.bitrate !== selectedLevel.bitrate) {\n this.log(`Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`);\n }\n this.hls.nextLoadLevel = selectedIndex;\n }\n break;\n }\n }\n }\n getPathwayForGroupId(groupId, type, defaultPathway) {\n const levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);\n for (let i = 0; i < levels.length; i++) {\n if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {\n return levels[i].pathwayId;\n }\n }\n return defaultPathway;\n }\n clonePathways(pathwayClones) {\n const levels = this.levels;\n if (!levels) {\n return;\n }\n const audioGroupCloneMap = {};\n const subtitleGroupCloneMap = {};\n pathwayClones.forEach(pathwayClone => {\n const {\n ID: cloneId,\n 'BASE-ID': baseId,\n 'URI-REPLACEMENT': uriReplacement\n } = pathwayClone;\n if (levels.some(level => level.pathwayId === cloneId)) {\n return;\n }\n const clonedVariants = this.getLevelsForPathway(baseId).map(baseLevel => {\n const attributes = new AttrList(baseLevel.attrs);\n attributes['PATHWAY-ID'] = cloneId;\n const clonedAudioGroupId = attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;\n const clonedSubtitleGroupId = attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;\n if (clonedAudioGroupId) {\n audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;\n attributes.AUDIO = clonedAudioGroupId;\n }\n if (clonedSubtitleGroupId) {\n subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;\n attributes.SUBTITLES = clonedSubtitleGroupId;\n }\n const url = performUriReplacement(baseLevel.uri, attributes['STABLE-VARIANT-ID'], 'PER-VARIANT-URIS', uriReplacement);\n const clonedLevel = new Level({\n attrs: attributes,\n audioCodec: baseLevel.audioCodec,\n bitrate: baseLevel.bitrate,\n height: baseLevel.height,\n name: baseLevel.name,\n url,\n videoCodec: baseLevel.videoCodec,\n width: baseLevel.width\n });\n if (baseLevel.audioGroups) {\n for (let i = 1; i < baseLevel.audioGroups.length; i++) {\n clonedLevel.addGroupId('audio', `${baseLevel.audioGroups[i]}_clone_${cloneId}`);\n }\n }\n if (baseLevel.subtitleGroups) {\n for (let i = 1; i < baseLevel.subtitleGroups.length; i++) {\n clonedLevel.addGroupId('text', `${baseLevel.subtitleGroups[i]}_clone_${cloneId}`);\n }\n }\n return clonedLevel;\n });\n levels.push(...clonedVariants);\n cloneRenditionGroups(this.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);\n cloneRenditionGroups(this.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);\n });\n }\n loadSteeringManifest(uri) {\n const config = this.hls.config;\n const Loader = config.loader;\n if (this.loader) {\n this.loader.destroy();\n }\n this.loader = new Loader(config);\n let url;\n try {\n url = new self.URL(uri);\n } catch (error) {\n this.enabled = false;\n this.log(`Failed to parse Steering Manifest URI: ${uri}`);\n return;\n }\n if (url.protocol !== 'data:') {\n const throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;\n url.searchParams.set('_HLS_pathway', this.pathwayId);\n url.searchParams.set('_HLS_throughput', '' + throughput);\n }\n const context = {\n responseType: 'json',\n url: url.href\n };\n const loadPolicy = config.steeringManifestLoadPolicy.default;\n const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};\n const loaderConfig = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: legacyRetryCompatibility.maxNumRetry || 0,\n retryDelay: legacyRetryCompatibility.retryDelayMs || 0,\n maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0\n };\n const callbacks = {\n onSuccess: (response, stats, context, networkDetails) => {\n this.log(`Loaded steering manifest: \"${url}\"`);\n const steeringData = response.data;\n if ((steeringData == null ? void 0 : steeringData.VERSION) !== 1) {\n this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);\n return;\n }\n this.updated = performance.now();\n this.timeToLoad = steeringData.TTL;\n const {\n 'RELOAD-URI': reloadUri,\n 'PATHWAY-CLONES': pathwayClones,\n 'PATHWAY-PRIORITY': pathwayPriority\n } = steeringData;\n if (reloadUri) {\n try {\n this.uri = new self.URL(reloadUri, url).href;\n } catch (error) {\n this.enabled = false;\n this.log(`Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`);\n return;\n }\n }\n this.scheduleRefresh(this.uri || context.url);\n if (pathwayClones) {\n this.clonePathways(pathwayClones);\n }\n const loadedSteeringData = {\n steeringManifest: steeringData,\n url: url.toString()\n };\n this.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);\n if (pathwayPriority) {\n this.updatePathwayPriority(pathwayPriority);\n }\n },\n onError: (error, context, networkDetails, stats) => {\n this.log(`Error loading steering manifest: ${error.code} ${error.text} (${context.url})`);\n this.stopLoad();\n if (error.code === 410) {\n this.enabled = false;\n this.log(`Steering manifest ${context.url} no longer available`);\n return;\n }\n let ttl = this.timeToLoad * 1000;\n if (error.code === 429) {\n const loader = this.loader;\n if (typeof (loader == null ? void 0 : loader.getResponseHeader) === 'function') {\n const retryAfter = loader.getResponseHeader('Retry-After');\n if (retryAfter) {\n ttl = parseFloat(retryAfter) * 1000;\n }\n }\n this.log(`Steering manifest ${context.url} rate limited`);\n return;\n }\n this.scheduleRefresh(this.uri || context.url, ttl);\n },\n onTimeout: (stats, context, networkDetails) => {\n this.log(`Timeout loading steering manifest (${context.url})`);\n this.scheduleRefresh(this.uri || context.url);\n }\n };\n this.log(`Requesting steering manifest: ${url}`);\n this.loader.load(context, loaderConfig, callbacks);\n }\n scheduleRefresh(uri, ttlMs = this.timeToLoad * 1000) {\n this.clearTimeout();\n this.reloadTimer = self.setTimeout(() => {\n var _this$hls;\n const media = (_this$hls = this.hls) == null ? void 0 : _this$hls.media;\n if (media && !media.ended) {\n this.loadSteeringManifest(uri);\n return;\n }\n this.scheduleRefresh(uri, this.timeToLoad * 1000);\n }, ttlMs);\n }\n}\nfunction cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {\n if (!tracks) {\n return;\n }\n Object.keys(groupCloneMap).forEach(audioGroupId => {\n const clonedTracks = tracks.filter(track => track.groupId === audioGroupId).map(track => {\n const clonedTrack = _extends({}, track);\n clonedTrack.details = undefined;\n clonedTrack.attrs = new AttrList(clonedTrack.attrs);\n clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs['STABLE-RENDITION-ID'], 'PER-RENDITION-URIS', uriReplacement);\n clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] = groupCloneMap[audioGroupId];\n clonedTrack.attrs['PATHWAY-ID'] = cloneId;\n return clonedTrack;\n });\n tracks.push(...clonedTracks);\n });\n}\nfunction performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {\n const {\n HOST: host,\n PARAMS: params,\n [perOptionKey]: perOptionUris\n } = uriReplacement;\n let perVariantUri;\n if (stableId) {\n perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];\n if (perVariantUri) {\n uri = perVariantUri;\n }\n }\n const url = new self.URL(uri);\n if (host && !perVariantUri) {\n url.host = host;\n }\n if (params) {\n Object.keys(params).sort().forEach(key => {\n if (key) {\n url.searchParams.set(key, params[key]);\n }\n });\n }\n return url.href;\n}\n\n/**\n * Controller to deal with encrypted media extensions (EME)\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API\n *\n * @class\n * @constructor\n */\nclass EMEController extends Logger {\n constructor(hls) {\n super('eme', hls.logger);\n this.hls = void 0;\n this.config = void 0;\n this.media = null;\n this.keyFormatPromise = null;\n this.keySystemAccessPromises = {};\n this._requestLicenseFailureCount = 0;\n this.mediaKeySessions = [];\n this.keyIdToKeySessionPromise = {};\n this.setMediaKeysQueue = EMEController.CDMCleanupPromise ? [EMEController.CDMCleanupPromise] : [];\n this.onMediaEncrypted = event => {\n const {\n initDataType,\n initData\n } = event;\n const logMessage = `\"${event.type}\" event: init data type: \"${initDataType}\"`;\n this.debug(logMessage);\n\n // Ignore event when initData is null\n if (initData === null) {\n return;\n }\n if (!this.keyFormatPromise) {\n let keySystems = Object.keys(this.keySystemAccessPromises);\n if (!keySystems.length) {\n keySystems = getKeySystemsForConfig(this.config);\n }\n const keyFormats = keySystems.map(keySystemDomainToKeySystemFormat).filter(k => !!k);\n this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);\n }\n this.keyFormatPromise.then(keySystemFormat => {\n const keySystem = keySystemFormatToKeySystemDomain(keySystemFormat);\n let keyId;\n let keySystemDomain;\n if (initDataType === 'sinf') {\n if (keySystem !== KeySystems.FAIRPLAY) {\n this.warn(`Ignoring unexpected \"${event.type}\" event with init data type: \"${initDataType}\" for selected key-system ${keySystem}`);\n return;\n }\n // Match sinf keyId to playlist skd://keyId=\n const json = bin2str(new Uint8Array(initData));\n try {\n const sinf = base64Decode(JSON.parse(json).sinf);\n const tenc = parseSinf(sinf);\n if (!tenc) {\n throw new Error(`'schm' box missing or not cbcs/cenc with schi > tenc`);\n }\n keyId = new Uint8Array(tenc.subarray(8, 24));\n keySystemDomain = KeySystems.FAIRPLAY;\n } catch (error) {\n this.warn(`${logMessage} Failed to parse sinf: ${error}`);\n return;\n }\n } else {\n if (keySystem !== KeySystems.WIDEVINE && keySystem !== KeySystems.PLAYREADY) {\n this.warn(`Ignoring unexpected \"${event.type}\" event with init data type: \"${initDataType}\" for selected key-system ${keySystem}`);\n return;\n }\n // Support Widevine/PlayReady clear-lead key-session creation (otherwise depend on playlist keys)\n const psshResults = parseMultiPssh(initData);\n const psshInfos = psshResults.filter(pssh => !!pssh.systemId && keySystemIdToKeySystemDomain(pssh.systemId) === keySystem);\n if (psshInfos.length > 1) {\n this.warn(`${logMessage} Using first of ${psshInfos.length} pssh found for selected key-system ${keySystem}`);\n }\n const psshInfo = psshInfos[0];\n if (!psshInfo) {\n if (psshResults.length === 0 || psshResults.some(pssh => !pssh.systemId)) {\n this.warn(`${logMessage} contains incomplete or invalid pssh data`);\n } else {\n this.log(`ignoring ${logMessage} for ${psshResults.map(pssh => keySystemIdToKeySystemDomain(pssh.systemId)).join(',')} pssh data in favor of playlist keys`);\n }\n return;\n }\n keySystemDomain = keySystemIdToKeySystemDomain(psshInfo.systemId);\n if (psshInfo.version === 0 && psshInfo.data) {\n if (keySystemDomain === KeySystems.WIDEVINE) {\n const offset = psshInfo.data.length - 22;\n keyId = new Uint8Array(psshInfo.data.subarray(offset, offset + 16));\n } else if (keySystemDomain === KeySystems.PLAYREADY) {\n keyId = parsePlayReadyWRM(psshInfo.data);\n }\n }\n }\n if (!keySystemDomain || !keyId) {\n return;\n }\n const keyIdHex = Hex.hexDump(keyId);\n const {\n keyIdToKeySessionPromise,\n mediaKeySessions\n } = this;\n let keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex];\n for (let i = 0; i < mediaKeySessions.length; i++) {\n // Match playlist key\n const keyContext = mediaKeySessions[i];\n const decryptdata = keyContext.decryptdata;\n if (!decryptdata.keyId) {\n continue;\n }\n const oldKeyIdHex = Hex.hexDump(decryptdata.keyId);\n if (keyIdHex === oldKeyIdHex || decryptdata.uri.replace(/-/g, '').indexOf(keyIdHex) !== -1) {\n keySessionContextPromise = keyIdToKeySessionPromise[oldKeyIdHex];\n if (decryptdata.pssh) {\n break;\n }\n delete keyIdToKeySessionPromise[oldKeyIdHex];\n decryptdata.pssh = new Uint8Array(initData);\n decryptdata.keyId = keyId;\n keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] = keySessionContextPromise.then(() => {\n return this.generateRequestWithPreferredKeySession(keyContext, initDataType, initData, 'encrypted-event-key-match');\n });\n keySessionContextPromise.catch(error => this.handleError(error));\n break;\n }\n }\n if (!keySessionContextPromise) {\n if (keySystemDomain !== keySystem) {\n this.log(`Ignoring \"${event.type}\" event with ${keySystemDomain} init data for selected key-system ${keySystem}`);\n return;\n }\n // \"Clear-lead\" (misc key not encountered in playlist)\n keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] = this.getKeySystemSelectionPromise([keySystemDomain]).then(({\n keySystem,\n mediaKeys\n }) => {\n var _keySystemToKeySystem;\n this.throwIfDestroyed();\n const decryptdata = new LevelKey('ISO-23001-7', keyIdHex, (_keySystemToKeySystem = keySystemDomainToKeySystemFormat(keySystem)) != null ? _keySystemToKeySystem : '');\n decryptdata.pssh = new Uint8Array(initData);\n decryptdata.keyId = keyId;\n return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {\n this.throwIfDestroyed();\n const keySessionContext = this.createMediaKeySessionContext({\n decryptdata,\n keySystem,\n mediaKeys\n });\n return this.generateRequestWithPreferredKeySession(keySessionContext, initDataType, initData, 'encrypted-event-no-match');\n });\n });\n keySessionContextPromise.catch(error => this.handleError(error));\n }\n });\n };\n this.onWaitingForKey = event => {\n this.log(`\"${event.type}\" event`);\n };\n this.hls = hls;\n this.config = hls.config;\n this.registerListeners();\n }\n destroy() {\n const media = this.media;\n this.unregisterListeners();\n this.onMediaDetached();\n this._clear(media);\n // Remove any references that could be held in config options or callbacks\n const config = this.config;\n config.requestMediaKeySystemAccessFunc = null;\n config.licenseXhrSetup = config.licenseResponseCallback = undefined;\n config.drmSystems = config.drmSystemOptions = {};\n // @ts-ignore\n this.hls = this.config = this.keyIdToKeySessionPromise = null;\n // @ts-ignore\n this.onMediaEncrypted = this.onWaitingForKey = null;\n }\n registerListeners() {\n this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n }\n unregisterListeners() {\n this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n }\n getLicenseServerUrl(keySystem) {\n const {\n drmSystems,\n widevineLicenseUrl\n } = this.config;\n const keySystemConfiguration = drmSystems[keySystem];\n if (keySystemConfiguration) {\n return keySystemConfiguration.licenseUrl;\n }\n\n // For backward compatibility\n if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {\n return widevineLicenseUrl;\n }\n }\n getLicenseServerUrlOrThrow(keySystem) {\n const url = this.getLicenseServerUrl(keySystem);\n if (url === undefined) {\n throw new Error(`no license server URL configured for key-system \"${keySystem}\"`);\n }\n return url;\n }\n getServerCertificateUrl(keySystem) {\n const {\n drmSystems\n } = this.config;\n const keySystemConfiguration = drmSystems[keySystem];\n if (keySystemConfiguration) {\n return keySystemConfiguration.serverCertificateUrl;\n } else {\n this.log(`No Server Certificate in config.drmSystems[\"${keySystem}\"]`);\n }\n }\n attemptKeySystemAccess(keySystemsToAttempt) {\n const levels = this.hls.levels;\n const uniqueCodec = (value, i, a) => !!value && a.indexOf(value) === i;\n const audioCodecs = levels.map(level => level.audioCodec).filter(uniqueCodec);\n const videoCodecs = levels.map(level => level.videoCodec).filter(uniqueCodec);\n if (audioCodecs.length + videoCodecs.length === 0) {\n videoCodecs.push('avc1.42e01e');\n }\n return new Promise((resolve, reject) => {\n const attempt = keySystems => {\n const keySystem = keySystems.shift();\n this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then(mediaKeys => resolve({\n keySystem,\n mediaKeys\n })).catch(error => {\n if (keySystems.length) {\n attempt(keySystems);\n } else if (error instanceof EMEKeyError) {\n reject(error);\n } else {\n reject(new EMEKeyError({\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n error,\n fatal: true\n }, error.message));\n }\n });\n };\n attempt(keySystemsToAttempt);\n });\n }\n requestMediaKeySystemAccess(keySystem, supportedConfigurations) {\n const {\n requestMediaKeySystemAccessFunc\n } = this.config;\n if (!(typeof requestMediaKeySystemAccessFunc === 'function')) {\n let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;\n if (requestMediaKeySystemAccess === null && self.location.protocol === 'http:') {\n errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;\n }\n return Promise.reject(new Error(errMessage));\n }\n return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);\n }\n getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) {\n // This can throw, but is caught in event handler callpath\n const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions);\n const keySystemAccessPromises = this.keySystemAccessPromises[keySystem];\n let keySystemAccess = keySystemAccessPromises == null ? void 0 : keySystemAccessPromises.keySystemAccess;\n if (!keySystemAccess) {\n this.log(`Requesting encrypted media \"${keySystem}\" key-system access with config: ${stringify(mediaKeySystemConfigs)}`);\n keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);\n const _keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = {\n keySystemAccess\n };\n keySystemAccess.catch(error => {\n this.log(`Failed to obtain access to key-system \"${keySystem}\": ${error}`);\n });\n return keySystemAccess.then(mediaKeySystemAccess => {\n this.log(`Access for key-system \"${mediaKeySystemAccess.keySystem}\" obtained`);\n const certificateRequest = this.fetchServerCertificate(keySystem);\n this.log(`Create media-keys for \"${keySystem}\"`);\n _keySystemAccessPromises.mediaKeys = mediaKeySystemAccess.createMediaKeys().then(mediaKeys => {\n this.log(`Media-keys created for \"${keySystem}\"`);\n return certificateRequest.then(certificate => {\n if (certificate) {\n return this.setMediaKeysServerCertificate(mediaKeys, keySystem, certificate);\n }\n return mediaKeys;\n });\n });\n _keySystemAccessPromises.mediaKeys.catch(error => {\n this.error(`Failed to create media-keys for \"${keySystem}\"}: ${error}`);\n });\n return _keySystemAccessPromises.mediaKeys;\n });\n }\n return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys);\n }\n createMediaKeySessionContext({\n decryptdata,\n keySystem,\n mediaKeys\n }) {\n this.log(`Creating key-system session \"${keySystem}\" keyId: ${Hex.hexDump(decryptdata.keyId || [])}`);\n const mediaKeysSession = mediaKeys.createSession();\n const mediaKeySessionContext = {\n decryptdata,\n keySystem,\n mediaKeys,\n mediaKeysSession,\n keyStatus: 'status-pending'\n };\n this.mediaKeySessions.push(mediaKeySessionContext);\n return mediaKeySessionContext;\n }\n renewKeySession(mediaKeySessionContext) {\n const decryptdata = mediaKeySessionContext.decryptdata;\n if (decryptdata.pssh) {\n const keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext);\n const keyId = this.getKeyIdString(decryptdata);\n const scheme = 'cenc';\n this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh.buffer, 'expired');\n } else {\n this.warn(`Could not renew expired session. Missing pssh initData.`);\n }\n this.removeSession(mediaKeySessionContext);\n }\n getKeyIdString(decryptdata) {\n if (!decryptdata) {\n throw new Error('Could not read keyId of undefined decryptdata');\n }\n if (decryptdata.keyId === null) {\n throw new Error('keyId is null');\n }\n return Hex.hexDump(decryptdata.keyId);\n }\n updateKeySession(mediaKeySessionContext, data) {\n var _mediaKeySessionConte;\n const keySession = mediaKeySessionContext.mediaKeysSession;\n this.log(`Updating key-session \"${keySession.sessionId}\" for keyID ${Hex.hexDump(((_mediaKeySessionConte = mediaKeySessionContext.decryptdata) == null ? void 0 : _mediaKeySessionConte.keyId) || [])}\n } (data length: ${data ? data.byteLength : data})`);\n return keySession.update(data);\n }\n selectKeySystemFormat(frag) {\n const keyFormats = Object.keys(frag.levelkeys || {});\n if (!this.keyFormatPromise) {\n this.log(`Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${frag.level}) key formats ${keyFormats.join(', ')}`);\n this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);\n }\n return this.keyFormatPromise;\n }\n getKeyFormatPromise(keyFormats) {\n return new Promise((resolve, reject) => {\n const keySystemsInConfig = getKeySystemsForConfig(this.config);\n const keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter(value => !!value && keySystemsInConfig.indexOf(value) !== -1);\n return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(({\n keySystem\n }) => {\n const keySystemFormat = keySystemDomainToKeySystemFormat(keySystem);\n if (keySystemFormat) {\n resolve(keySystemFormat);\n } else {\n reject(new Error(`Unable to find format for key-system \"${keySystem}\"`));\n }\n }).catch(reject);\n });\n }\n loadKey(data) {\n const decryptdata = data.keyInfo.decryptdata;\n const keyId = this.getKeyIdString(decryptdata);\n const keyDetails = `(keyId: ${keyId} format: \"${decryptdata.keyFormat}\" method: ${decryptdata.method} uri: ${decryptdata.uri})`;\n this.log(`Starting session for key ${keyDetails}`);\n let keyContextPromise = this.keyIdToKeySessionPromise[keyId];\n if (!keyContextPromise) {\n keyContextPromise = this.getKeySystemForKeyPromise(decryptdata).then(({\n keySystem,\n mediaKeys\n }) => {\n this.throwIfDestroyed();\n this.log(`Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`);\n return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {\n this.throwIfDestroyed();\n return this.createMediaKeySessionContext({\n keySystem,\n mediaKeys,\n decryptdata\n });\n });\n });\n const keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] = keyContextPromise.then(keySessionContext => {\n const scheme = 'cenc';\n const initData = decryptdata.pssh ? decryptdata.pssh.buffer : null;\n return this.generateRequestWithPreferredKeySession(keySessionContext, scheme, initData, 'playlist-key');\n });\n keySessionContextPromise.catch(error => this.handleError(error));\n }\n return keyContextPromise;\n }\n throwIfDestroyed(message = 'Invalid state') {\n if (!this.hls) {\n throw new Error('invalid state');\n }\n }\n handleError(error) {\n if (!this.hls) {\n return;\n }\n this.error(error.message);\n if (error instanceof EMEKeyError) {\n this.hls.trigger(Events.ERROR, error.data);\n } else {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_KEYS,\n error,\n fatal: true\n });\n }\n }\n getKeySystemForKeyPromise(decryptdata) {\n const keyId = this.getKeyIdString(decryptdata);\n const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];\n if (!mediaKeySessionContext) {\n const keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat);\n const keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config);\n return this.attemptKeySystemAccess(keySystemsToAttempt);\n }\n return mediaKeySessionContext;\n }\n getKeySystemSelectionPromise(keySystemsToAttempt) {\n if (!keySystemsToAttempt.length) {\n keySystemsToAttempt = getKeySystemsForConfig(this.config);\n }\n if (keySystemsToAttempt.length === 0) {\n throw new EMEKeyError({\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,\n fatal: true\n }, `Missing key-system license configuration options ${stringify({\n drmSystems: this.config.drmSystems\n })}`);\n }\n return this.attemptKeySystemAccess(keySystemsToAttempt);\n }\n attemptSetMediaKeys(keySystem, mediaKeys) {\n const queue = this.setMediaKeysQueue.slice();\n this.log(`Setting media-keys for \"${keySystem}\"`);\n // Only one setMediaKeys() can run at one time, and multiple setMediaKeys() operations\n // can be queued for execution for multiple key sessions.\n const setMediaKeysPromise = Promise.all(queue).then(() => {\n if (!this.media) {\n throw new Error('Attempted to set mediaKeys without media element attached');\n }\n return this.media.setMediaKeys(mediaKeys);\n });\n this.setMediaKeysQueue.push(setMediaKeysPromise);\n return setMediaKeysPromise.then(() => {\n this.log(`Media-keys set for \"${keySystem}\"`);\n queue.push(setMediaKeysPromise);\n this.setMediaKeysQueue = this.setMediaKeysQueue.filter(p => queue.indexOf(p) === -1);\n });\n }\n generateRequestWithPreferredKeySession(context, initDataType, initData, reason) {\n var _this$config$drmSyste, _this$config$drmSyste2;\n const generateRequestFilter = (_this$config$drmSyste = this.config.drmSystems) == null ? void 0 : (_this$config$drmSyste2 = _this$config$drmSyste[context.keySystem]) == null ? void 0 : _this$config$drmSyste2.generateRequest;\n if (generateRequestFilter) {\n try {\n const mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData, context);\n if (!mappedInitData) {\n throw new Error('Invalid response from configured generateRequest filter');\n }\n initDataType = mappedInitData.initDataType;\n initData = mappedInitData.initData ? mappedInitData.initData : null;\n context.decryptdata.pssh = initData ? new Uint8Array(initData) : null;\n } catch (error) {\n var _this$hls;\n this.warn(error.message);\n if ((_this$hls = this.hls) != null && _this$hls.config.debug) {\n throw error;\n }\n }\n }\n if (initData === null) {\n this.log(`Skipping key-session request for \"${reason}\" (no initData)`);\n return Promise.resolve(context);\n }\n const keyId = this.getKeyIdString(context.decryptdata);\n this.log(`Generating key-session request for \"${reason}\": ${keyId} (init data type: ${initDataType} length: ${initData ? initData.byteLength : null})`);\n const licenseStatus = new EventEmitter();\n const onmessage = context._onmessage = event => {\n const keySession = context.mediaKeysSession;\n if (!keySession) {\n licenseStatus.emit('error', new Error('invalid state'));\n return;\n }\n const {\n messageType,\n message\n } = event;\n this.log(`\"${messageType}\" message event for session \"${keySession.sessionId}\" message size: ${message.byteLength}`);\n if (messageType === 'license-request' || messageType === 'license-renewal') {\n this.renewLicense(context, message).catch(error => {\n if (licenseStatus.eventNames().length) {\n licenseStatus.emit('error', error);\n } else {\n this.handleError(error);\n }\n });\n } else if (messageType === 'license-release') {\n if (context.keySystem === KeySystems.FAIRPLAY) {\n this.updateKeySession(context, strToUtf8array('acknowledged'));\n this.removeSession(context);\n }\n } else {\n this.warn(`unhandled media key message type \"${messageType}\"`);\n }\n };\n const onkeystatuseschange = context._onkeystatuseschange = event => {\n const keySession = context.mediaKeysSession;\n if (!keySession) {\n licenseStatus.emit('error', new Error('invalid state'));\n return;\n }\n this.onKeyStatusChange(context);\n const keyStatus = context.keyStatus;\n licenseStatus.emit('keyStatus', keyStatus);\n if (keyStatus === 'expired') {\n this.warn(`${context.keySystem} expired for key ${keyId}`);\n this.renewKeySession(context);\n }\n };\n context.mediaKeysSession.addEventListener('message', onmessage);\n context.mediaKeysSession.addEventListener('keystatuseschange', onkeystatuseschange);\n const keyUsablePromise = new Promise((resolve, reject) => {\n licenseStatus.on('error', reject);\n licenseStatus.on('keyStatus', keyStatus => {\n if (keyStatus.startsWith('usable')) {\n resolve();\n } else if (keyStatus === 'output-restricted') {\n reject(new EMEKeyError({\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,\n fatal: false\n }, 'HDCP level output restricted'));\n } else if (keyStatus === 'internal-error') {\n reject(new EMEKeyError({\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,\n fatal: true\n }, `key status changed to \"${keyStatus}\"`));\n } else if (keyStatus === 'expired') {\n reject(new Error('key expired while generating request'));\n } else {\n this.warn(`unhandled key status change \"${keyStatus}\"`);\n }\n });\n });\n return context.mediaKeysSession.generateRequest(initDataType, initData).then(() => {\n var _context$mediaKeysSes;\n this.log(`Request generated for key-session \"${(_context$mediaKeysSes = context.mediaKeysSession) == null ? void 0 : _context$mediaKeysSes.sessionId}\" keyId: ${keyId}`);\n }).catch(error => {\n throw new EMEKeyError({\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n error,\n fatal: false\n }, `Error generating key-session request: ${error}`);\n }).then(() => keyUsablePromise).catch(error => {\n licenseStatus.removeAllListeners();\n this.removeSession(context);\n throw error;\n }).then(() => {\n licenseStatus.removeAllListeners();\n return context;\n });\n }\n onKeyStatusChange(mediaKeySessionContext) {\n mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach((status, keyId) => {\n // keyStatuses.forEach is not standard API so the callback value looks weird on xboxone\n // xboxone callback(keyId, status) so we need to exchange them\n if (typeof keyId === 'string' && typeof status === 'object') {\n const temp = keyId;\n keyId = status;\n status = temp;\n }\n this.log(`key status change \"${status}\" for keyStatuses keyId: ${Hex.hexDump('buffer' in keyId ? new Uint8Array(keyId.buffer, keyId.byteOffset, keyId.byteLength) : new Uint8Array(keyId))} session keyId: ${Hex.hexDump(new Uint8Array(mediaKeySessionContext.decryptdata.keyId || []))} uri: ${mediaKeySessionContext.decryptdata.uri}`);\n mediaKeySessionContext.keyStatus = status;\n });\n }\n fetchServerCertificate(keySystem) {\n const config = this.config;\n const Loader = config.loader;\n const certLoader = new Loader(config);\n const url = this.getServerCertificateUrl(keySystem);\n if (!url) {\n return Promise.resolve();\n }\n this.log(`Fetching server certificate for \"${keySystem}\"`);\n return new Promise((resolve, reject) => {\n const loaderContext = {\n responseType: 'arraybuffer',\n url\n };\n const loadPolicy = config.certLoadPolicy.default;\n const loaderConfig = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0\n };\n const loaderCallbacks = {\n onSuccess: (response, stats, context, networkDetails) => {\n resolve(response.data);\n },\n onError: (response, contex, networkDetails, stats) => {\n reject(new EMEKeyError({\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,\n fatal: true,\n networkDetails,\n response: _objectSpread2({\n url: loaderContext.url,\n data: undefined\n }, response)\n }, `\"${keySystem}\" certificate request failed (${url}). Status: ${response.code} (${response.text})`));\n },\n onTimeout: (stats, context, networkDetails) => {\n reject(new EMEKeyError({\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,\n fatal: true,\n networkDetails,\n response: {\n url: loaderContext.url,\n data: undefined\n }\n }, `\"${keySystem}\" certificate request timed out (${url})`));\n },\n onAbort: (stats, context, networkDetails) => {\n reject(new Error('aborted'));\n }\n };\n certLoader.load(loaderContext, loaderConfig, loaderCallbacks);\n });\n }\n setMediaKeysServerCertificate(mediaKeys, keySystem, cert) {\n return new Promise((resolve, reject) => {\n mediaKeys.setServerCertificate(cert).then(success => {\n this.log(`setServerCertificate ${success ? 'success' : 'not supported by CDM'} (${cert == null ? void 0 : cert.byteLength}) on \"${keySystem}\"`);\n resolve(mediaKeys);\n }).catch(error => {\n reject(new EMEKeyError({\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,\n error,\n fatal: true\n }, error.message));\n });\n });\n }\n renewLicense(context, keyMessage) {\n return this.requestLicense(context, new Uint8Array(keyMessage)).then(data => {\n return this.updateKeySession(context, new Uint8Array(data)).catch(error => {\n throw new EMEKeyError({\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,\n error,\n fatal: true\n }, error.message);\n });\n });\n }\n unpackPlayReadyKeyMessage(xhr, licenseChallenge) {\n // On Edge, the raw license message is UTF-16-encoded XML. We need\n // to unpack the Challenge element (base64-encoded string containing the\n // actual license request) and any HttpHeader elements (sent as request\n // headers).\n // For PlayReady CDMs, we need to dig the Challenge out of the XML.\n const xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer));\n if (!xmlString.includes('PlayReadyKeyMessage')) {\n // This does not appear to be a wrapped message as on Edge. Some\n // clients do not need this unwrapping, so we will assume this is one of\n // them. Note that \"xml\" at this point probably looks like random\n // garbage, since we interpreted UTF-8 as UTF-16.\n xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');\n return licenseChallenge;\n }\n const keyMessageXml = new DOMParser().parseFromString(xmlString, 'application/xml');\n // Set request headers.\n const headers = keyMessageXml.querySelectorAll('HttpHeader');\n if (headers.length > 0) {\n let header;\n for (let i = 0, len = headers.length; i < len; i++) {\n var _header$querySelector, _header$querySelector2;\n header = headers[i];\n const name = (_header$querySelector = header.querySelector('name')) == null ? void 0 : _header$querySelector.textContent;\n const value = (_header$querySelector2 = header.querySelector('value')) == null ? void 0 : _header$querySelector2.textContent;\n if (name && value) {\n xhr.setRequestHeader(name, value);\n }\n }\n }\n const challengeElement = keyMessageXml.querySelector('Challenge');\n const challengeText = challengeElement == null ? void 0 : challengeElement.textContent;\n if (!challengeText) {\n throw new Error(`Cannot find <Challenge> in key message`);\n }\n return strToUtf8array(atob(challengeText));\n }\n setupLicenseXHR(xhr, url, keysListItem, licenseChallenge) {\n const licenseXhrSetup = this.config.licenseXhrSetup;\n if (!licenseXhrSetup) {\n xhr.open('POST', url, true);\n return Promise.resolve({\n xhr,\n licenseChallenge\n });\n }\n return Promise.resolve().then(() => {\n if (!keysListItem.decryptdata) {\n throw new Error('Key removed');\n }\n return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);\n }).catch(error => {\n if (!keysListItem.decryptdata) {\n // Key session removed. Cancel license request.\n throw error;\n }\n // let's try to open before running setup\n xhr.open('POST', url, true);\n return licenseXhrSetup.call(this.hls, xhr, url, keysListItem, licenseChallenge);\n }).then(licenseXhrSetupResult => {\n // if licenseXhrSetup did not yet call open, let's do it now\n if (!xhr.readyState) {\n xhr.open('POST', url, true);\n }\n const finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge;\n return {\n xhr,\n licenseChallenge: finalLicenseChallenge\n };\n });\n }\n requestLicense(keySessionContext, licenseChallenge) {\n const keyLoadPolicy = this.config.keyLoadPolicy.default;\n return new Promise((resolve, reject) => {\n const url = this.getLicenseServerUrlOrThrow(keySessionContext.keySystem);\n this.log(`Sending license request to URL: ${url}`);\n const xhr = new XMLHttpRequest();\n xhr.responseType = 'arraybuffer';\n xhr.onreadystatechange = () => {\n if (!this.hls || !keySessionContext.mediaKeysSession) {\n return reject(new Error('invalid state'));\n }\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n this._requestLicenseFailureCount = 0;\n let data = xhr.response;\n this.log(`License received ${data instanceof ArrayBuffer ? data.byteLength : data}`);\n const licenseResponseCallback = this.config.licenseResponseCallback;\n if (licenseResponseCallback) {\n try {\n data = licenseResponseCallback.call(this.hls, xhr, url, keySessionContext);\n } catch (error) {\n this.error(error);\n }\n }\n resolve(data);\n } else {\n const retryConfig = keyLoadPolicy.errorRetry;\n const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;\n this._requestLicenseFailureCount++;\n if (this._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) {\n reject(new EMEKeyError({\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true,\n networkDetails: xhr,\n response: {\n url,\n data: undefined,\n code: xhr.status,\n text: xhr.statusText\n }\n }, `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`));\n } else {\n const attemptsLeft = maxNumRetry - this._requestLicenseFailureCount + 1;\n this.warn(`Retrying license request, ${attemptsLeft} attempts left`);\n this.requestLicense(keySessionContext, licenseChallenge).then(resolve, reject);\n }\n }\n }\n };\n if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) {\n keySessionContext.licenseXhr.abort();\n }\n keySessionContext.licenseXhr = xhr;\n this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(({\n xhr,\n licenseChallenge\n }) => {\n if (keySessionContext.keySystem == KeySystems.PLAYREADY) {\n licenseChallenge = this.unpackPlayReadyKeyMessage(xhr, licenseChallenge);\n }\n xhr.send(licenseChallenge);\n });\n });\n }\n onMediaAttached(event, data) {\n if (!this.config.emeEnabled) {\n return;\n }\n const media = data.media;\n\n // keep reference of media\n this.media = media;\n media.removeEventListener('encrypted', this.onMediaEncrypted);\n media.removeEventListener('waitingforkey', this.onWaitingForKey);\n media.addEventListener('encrypted', this.onMediaEncrypted);\n media.addEventListener('waitingforkey', this.onWaitingForKey);\n }\n onMediaDetached() {\n const media = this.media;\n if (media) {\n media.removeEventListener('encrypted', this.onMediaEncrypted);\n media.removeEventListener('waitingforkey', this.onWaitingForKey);\n this.media = null;\n }\n }\n _clear(media) {\n var _media$setMediaKeys;\n const mediaKeysList = this.mediaKeySessions;\n this._requestLicenseFailureCount = 0;\n this.setMediaKeysQueue = [];\n this.mediaKeySessions = [];\n this.keyIdToKeySessionPromise = {};\n LevelKey.clearKeyUriToKeyIdMap();\n\n // Close all sessions and remove media keys from the video element.\n const keySessionCount = mediaKeysList.length;\n EMEController.CDMCleanupPromise = Promise.all(mediaKeysList.map(mediaKeySessionContext => this.removeSession(mediaKeySessionContext)).concat(media == null ? void 0 : (_media$setMediaKeys = media.setMediaKeys(null)) == null ? void 0 : _media$setMediaKeys.catch(error => {\n var _this$hls2;\n this.log(`Could not clear media keys: ${error}`);\n (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,\n fatal: false,\n error: new Error(`Could not clear media keys: ${error}`)\n });\n }))).then(() => {\n if (keySessionCount) {\n this.log('finished closing key sessions and clearing media keys');\n mediaKeysList.length = 0;\n }\n }).catch(error => {\n var _this$hls3;\n this.log(`Could not close sessions and clear media keys: ${error}`);\n (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,\n fatal: false,\n error: new Error(`Could not close sessions and clear media keys: ${error}`)\n });\n });\n }\n onManifestLoading() {\n this.keyFormatPromise = null;\n }\n onManifestLoaded(event, {\n sessionKeys\n }) {\n if (!sessionKeys || !this.config.emeEnabled) {\n return;\n }\n if (!this.keyFormatPromise) {\n const keyFormats = sessionKeys.reduce((formats, sessionKey) => {\n if (formats.indexOf(sessionKey.keyFormat) === -1) {\n formats.push(sessionKey.keyFormat);\n }\n return formats;\n }, []);\n this.log(`Selecting key-system from session-keys ${keyFormats.join(', ')}`);\n this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);\n }\n }\n removeSession(mediaKeySessionContext) {\n const {\n mediaKeysSession,\n licenseXhr\n } = mediaKeySessionContext;\n if (mediaKeysSession) {\n this.log(`Remove licenses and keys and close session ${mediaKeysSession.sessionId}`);\n if (mediaKeySessionContext._onmessage) {\n mediaKeysSession.removeEventListener('message', mediaKeySessionContext._onmessage);\n mediaKeySessionContext._onmessage = undefined;\n }\n if (mediaKeySessionContext._onkeystatuseschange) {\n mediaKeysSession.removeEventListener('keystatuseschange', mediaKeySessionContext._onkeystatuseschange);\n mediaKeySessionContext._onkeystatuseschange = undefined;\n }\n if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {\n licenseXhr.abort();\n }\n mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = undefined;\n const index = this.mediaKeySessions.indexOf(mediaKeySessionContext);\n if (index > -1) {\n this.mediaKeySessions.splice(index, 1);\n }\n const {\n drmSystemOptions\n } = this.config;\n const removePromise = isPersistentSessionType(drmSystemOptions) ? new Promise((resolve, reject) => {\n self.setTimeout(() => reject(new Error(`MediaKeySession.remove() timeout`)), 8000);\n mediaKeysSession.remove().then(resolve);\n }) : Promise.resolve();\n return removePromise.catch(error => {\n var _this$hls4;\n this.log(`Could not remove session: ${error}`);\n (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,\n fatal: false,\n error: new Error(`Could not remove session: ${error}`)\n });\n }).then(() => {\n return mediaKeysSession.close();\n }).catch(error => {\n var _this$hls5;\n this.log(`Could not close session: ${error}`);\n (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,\n fatal: false,\n error: new Error(`Could not close session: ${error}`)\n });\n });\n }\n }\n}\nEMEController.CDMCleanupPromise = void 0;\nclass EMEKeyError extends Error {\n constructor(data, message) {\n super(message);\n this.data = void 0;\n data.error || (data.error = new Error(message));\n this.data = data;\n data.err = data.error;\n }\n}\n\nclass FPSController {\n constructor(hls) {\n this.hls = void 0;\n this.isVideoPlaybackQualityAvailable = false;\n this.timer = void 0;\n this.media = null;\n this.lastTime = void 0;\n this.lastDroppedFrames = 0;\n this.lastDecodedFrames = 0;\n // stream controller must be provided as a dependency!\n this.streamController = void 0;\n this.hls = hls;\n this.registerListeners();\n }\n setStreamController(streamController) {\n this.streamController = streamController;\n }\n registerListeners() {\n this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n unregisterListeners() {\n this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n destroy() {\n if (this.timer) {\n clearInterval(this.timer);\n }\n this.unregisterListeners();\n this.isVideoPlaybackQualityAvailable = false;\n this.media = null;\n }\n onMediaAttaching(event, data) {\n const config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n const media = data.media instanceof self.HTMLVideoElement ? data.media : null;\n this.media = media;\n if (media && typeof media.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n self.clearInterval(this.timer);\n this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);\n }\n }\n onMediaDetaching() {\n this.media = null;\n }\n checkFPS(video, decodedFrames, droppedFrames) {\n const currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n const currentPeriod = currentTime - this.lastTime;\n const currentDropped = droppedFrames - this.lastDroppedFrames;\n const currentDecoded = decodedFrames - this.lastDecodedFrames;\n const droppedFPS = 1000 * currentDropped / currentPeriod;\n const hls = this.hls;\n hls.trigger(Events.FPS_DROP, {\n currentDropped: currentDropped,\n currentDecoded: currentDecoded,\n totalDroppedFrames: droppedFrames\n });\n if (droppedFPS > 0) {\n // hls.logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {\n let currentLevel = hls.currentLevel;\n hls.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);\n if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {\n currentLevel = currentLevel - 1;\n hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {\n level: currentLevel,\n droppedLevel: hls.currentLevel\n });\n hls.autoLevelCapping = currentLevel;\n this.streamController.nextLevelSwitch();\n }\n }\n }\n }\n this.lastTime = currentTime;\n this.lastDroppedFrames = droppedFrames;\n this.lastDecodedFrames = decodedFrames;\n }\n }\n checkFPSInterval() {\n const video = this.media;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n const videoPlaybackQuality = video.getVideoPlaybackQuality();\n this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);\n } else {\n // HTMLVideoElement doesn't include the webkit types\n this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);\n }\n }\n }\n}\n\nfunction sendAddTrackEvent(track, videoEl) {\n let event;\n try {\n event = new Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n event.track = track;\n videoEl.dispatchEvent(event);\n}\nfunction addCueToTrack(track, cue) {\n // Sometimes there are cue overlaps on segmented vtts so the same\n // cue can appear more than once in different vtt files.\n // This avoid showing duplicated cues with same timecode and text.\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n if (track.cues && !track.cues.getCueById(cue.id)) {\n try {\n track.addCue(cue);\n if (!track.cues.getCueById(cue.id)) {\n throw new Error(`addCue is failed for: ${cue}`);\n }\n } catch (err) {\n logger.debug(`[texttrack-utils]: ${err}`);\n try {\n const textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);\n textTrackCue.id = cue.id;\n track.addCue(textTrackCue);\n } catch (err2) {\n logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`);\n }\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\nfunction clearCurrentCues(track, enterHandler) {\n // When track.mode is disabled, track.cues will be null.\n // To guarantee the removal of cues, we need to temporarily\n // change the mode to hidden\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n if (track.cues) {\n for (let i = track.cues.length; i--;) {\n if (enterHandler) {\n track.cues[i].removeEventListener('enter', enterHandler);\n }\n track.removeCue(track.cues[i]);\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\nfunction removeCuesInRange(track, start, end, predicate) {\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n if (track.cues && track.cues.length > 0) {\n const cues = getCuesInRange(track.cues, start, end);\n for (let i = 0; i < cues.length; i++) {\n if (!predicate || predicate(cues[i])) {\n track.removeCue(cues[i]);\n }\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\n\n// Find first cue starting at or after given time.\n// Modified version of binary search O(log(n)).\nfunction getFirstCueIndexFromTime(cues, time) {\n // If first cue starts at or after time, start there\n if (time <= cues[0].startTime) {\n return 0;\n }\n // If the last cue ends before time there is no overlap\n const len = cues.length - 1;\n if (time > cues[len].endTime) {\n return -1;\n }\n let left = 0;\n let right = len;\n let mid;\n while (left <= right) {\n mid = Math.floor((right + left) / 2);\n if (time < cues[mid].startTime) {\n right = mid - 1;\n } else if (time > cues[mid].startTime && left < len) {\n left = mid + 1;\n } else {\n // If it's not lower or higher, it must be equal.\n return mid;\n }\n }\n // At this point, left and right have swapped.\n // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.\n return cues[left].startTime - time < time - cues[right].startTime ? left : right;\n}\nfunction getCuesInRange(cues, start, end) {\n const cuesFound = [];\n const firstCueInRange = getFirstCueIndexFromTime(cues, start);\n if (firstCueInRange > -1) {\n for (let i = firstCueInRange, len = cues.length; i < len; i++) {\n const cue = cues[i];\n if (cue.startTime >= start && cue.endTime <= end) {\n cuesFound.push(cue);\n } else if (cue.startTime > end) {\n return cuesFound;\n }\n }\n }\n return cuesFound;\n}\nfunction filterSubtitleTracks(textTrackList) {\n const tracks = [];\n for (let i = 0; i < textTrackList.length; i++) {\n const track = textTrackList[i];\n // Edge adds a track without a label; we don't want to use it\n if ((track.kind === 'subtitles' || track.kind === 'captions') && track.label) {\n tracks.push(textTrackList[i]);\n }\n }\n return tracks;\n}\n\nclass SubtitleTrackController extends BasePlaylistController {\n constructor(hls) {\n super(hls, 'subtitle-track-controller');\n this.media = null;\n this.tracks = [];\n this.groupIds = null;\n this.tracksInGroup = [];\n this.trackId = -1;\n this.currentTrack = null;\n this.selectDefaultTrack = true;\n this.queuedDefaultTrack = -1;\n this.useTextTrackPolling = false;\n this.subtitlePollingInterval = -1;\n this._subtitleDisplay = true;\n this.asyncPollTrackChange = () => this.pollTrackChange(0);\n this.onTextTracksChanged = () => {\n if (!this.useTextTrackPolling) {\n self.clearInterval(this.subtitlePollingInterval);\n }\n // Media is undefined when switching streams via loadSource()\n if (!this.media || !this.hls.config.renderTextTracksNatively) {\n return;\n }\n let textTrack = null;\n const tracks = filterSubtitleTracks(this.media.textTracks);\n for (let i = 0; i < tracks.length; i++) {\n if (tracks[i].mode === 'hidden') {\n // Do not break in case there is a following track with showing.\n textTrack = tracks[i];\n } else if (tracks[i].mode === 'showing') {\n textTrack = tracks[i];\n break;\n }\n }\n\n // Find internal track index for TextTrack\n const trackId = this.findTrackForTextTrack(textTrack);\n if (this.subtitleTrack !== trackId) {\n this.setSubtitleTrack(trackId);\n }\n };\n this.registerListeners();\n }\n destroy() {\n this.unregisterListeners();\n this.tracks.length = 0;\n this.tracksInGroup.length = 0;\n this.currentTrack = null;\n // @ts-ignore\n this.onTextTracksChanged = this.asyncPollTrackChange = null;\n super.destroy();\n }\n get subtitleDisplay() {\n return this._subtitleDisplay;\n }\n set subtitleDisplay(value) {\n this._subtitleDisplay = value;\n if (this.trackId > -1) {\n this.toggleTrackModes();\n }\n }\n registerListeners() {\n const {\n hls\n } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n unregisterListeners() {\n const {\n hls\n } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n // Listen for subtitle track change, then extract the current track ID.\n onMediaAttached(event, data) {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n if (this.queuedDefaultTrack > -1) {\n this.subtitleTrack = this.queuedDefaultTrack;\n this.queuedDefaultTrack = -1;\n }\n this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);\n if (this.useTextTrackPolling) {\n this.pollTrackChange(500);\n } else {\n this.media.textTracks.addEventListener('change', this.asyncPollTrackChange);\n }\n }\n pollTrackChange(timeout) {\n self.clearInterval(this.subtitlePollingInterval);\n this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout);\n }\n onMediaDetaching(event, data) {\n const media = this.media;\n if (!media) {\n return;\n }\n const transferringMedia = !!data.transferMedia;\n self.clearInterval(this.subtitlePollingInterval);\n if (!this.useTextTrackPolling) {\n media.textTracks.removeEventListener('change', this.asyncPollTrackChange);\n }\n if (this.trackId > -1) {\n this.queuedDefaultTrack = this.trackId;\n }\n\n // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.\n this.subtitleTrack = -1;\n this.media = null;\n if (transferringMedia) {\n return;\n }\n const textTracks = filterSubtitleTracks(media.textTracks);\n // Clear loaded cues on media detachment from tracks\n textTracks.forEach(track => {\n clearCurrentCues(track);\n });\n }\n onManifestLoading() {\n this.tracks = [];\n this.groupIds = null;\n this.tracksInGroup = [];\n this.trackId = -1;\n this.currentTrack = null;\n this.selectDefaultTrack = true;\n }\n\n // Fired whenever a new manifest is loaded.\n onManifestParsed(event, data) {\n this.tracks = data.subtitleTracks;\n }\n onSubtitleTrackLoaded(event, data) {\n const {\n id,\n groupId,\n details\n } = data;\n const trackInActiveGroup = this.tracksInGroup[id];\n if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {\n this.warn(`Subtitle track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId}`);\n return;\n }\n const curDetails = trackInActiveGroup.details;\n trackInActiveGroup.details = data.details;\n this.log(`Subtitle track ${id} \"${trackInActiveGroup.name}\" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`);\n if (id === this.trackId) {\n this.playlistLoaded(id, data, curDetails);\n }\n }\n onLevelLoading(event, data) {\n this.switchLevel(data.level);\n }\n onLevelSwitching(event, data) {\n this.switchLevel(data.level);\n }\n switchLevel(levelIndex) {\n const levelInfo = this.hls.levels[levelIndex];\n if (!levelInfo) {\n return;\n }\n const subtitleGroups = levelInfo.subtitleGroups || null;\n const currentGroups = this.groupIds;\n let currentTrack = this.currentTrack;\n if (!subtitleGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (subtitleGroups == null ? void 0 : subtitleGroups.length) || subtitleGroups != null && subtitleGroups.some(groupId => (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1)) {\n this.groupIds = subtitleGroups;\n this.trackId = -1;\n this.currentTrack = null;\n const subtitleTracks = this.tracks.filter(track => !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1);\n if (subtitleTracks.length) {\n // Disable selectDefaultTrack if there are no default tracks\n if (this.selectDefaultTrack && !subtitleTracks.some(track => track.default)) {\n this.selectDefaultTrack = false;\n }\n // track.id should match hls.audioTracks index\n subtitleTracks.forEach((track, i) => {\n track.id = i;\n });\n } else if (!currentTrack && !this.tracksInGroup.length) {\n // Do not dispatch SUBTITLE_TRACKS_UPDATED when there were and are no tracks\n return;\n }\n this.tracksInGroup = subtitleTracks;\n\n // Find preferred track\n const subtitlePreference = this.hls.config.subtitlePreference;\n if (!currentTrack && subtitlePreference) {\n this.selectDefaultTrack = false;\n const groupIndex = findMatchingOption(subtitlePreference, subtitleTracks);\n if (groupIndex > -1) {\n currentTrack = subtitleTracks[groupIndex];\n } else {\n const allIndex = findMatchingOption(subtitlePreference, this.tracks);\n currentTrack = this.tracks[allIndex];\n }\n }\n\n // Select initial track\n let trackId = this.findTrackId(currentTrack);\n if (trackId === -1 && currentTrack) {\n trackId = this.findTrackId(null);\n }\n\n // Dispatch events and load track if needed\n const subtitleTracksUpdated = {\n subtitleTracks\n };\n this.log(`Updating subtitle tracks, ${subtitleTracks.length} track(s) found in \"${subtitleGroups == null ? void 0 : subtitleGroups.join(',')}\" group-id`);\n this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);\n if (trackId !== -1 && this.trackId === -1) {\n this.setSubtitleTrack(trackId);\n }\n }\n }\n findTrackId(currentTrack) {\n const tracks = this.tracksInGroup;\n const selectDefault = this.selectDefaultTrack;\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n if (selectDefault && !track.default || !selectDefault && !currentTrack) {\n continue;\n }\n if (!currentTrack || matchesOption(track, currentTrack)) {\n return i;\n }\n }\n if (currentTrack) {\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE', 'ASSOC-LANGUAGE', 'CHARACTERISTICS'])) {\n return i;\n }\n }\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n if (mediaAttributesIdentical(currentTrack.attrs, track.attrs, ['LANGUAGE'])) {\n return i;\n }\n }\n }\n return -1;\n }\n findTrackForTextTrack(textTrack) {\n if (textTrack) {\n const tracks = this.tracksInGroup;\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n if (subtitleTrackMatchesTextTrack(track, textTrack)) {\n return i;\n }\n }\n }\n return -1;\n }\n onError(event, data) {\n if (data.fatal || !data.context) {\n return;\n }\n if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {\n this.checkRetry(data);\n }\n }\n get allSubtitleTracks() {\n return this.tracks;\n }\n\n /** get alternate subtitle tracks list from playlist **/\n get subtitleTracks() {\n return this.tracksInGroup;\n }\n\n /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/\n get subtitleTrack() {\n return this.trackId;\n }\n set subtitleTrack(newId) {\n this.selectDefaultTrack = false;\n this.setSubtitleTrack(newId);\n }\n setSubtitleOption(subtitleOption) {\n this.hls.config.subtitlePreference = subtitleOption;\n if (subtitleOption) {\n if (subtitleOption.id === -1) {\n this.setSubtitleTrack(-1);\n return null;\n }\n const allSubtitleTracks = this.allSubtitleTracks;\n this.selectDefaultTrack = false;\n if (allSubtitleTracks.length) {\n // First see if current option matches (no switch op)\n const currentTrack = this.currentTrack;\n if (currentTrack && matchesOption(subtitleOption, currentTrack)) {\n return currentTrack;\n }\n // Find option in current group\n const groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup);\n if (groupIndex > -1) {\n const track = this.tracksInGroup[groupIndex];\n this.setSubtitleTrack(groupIndex);\n return track;\n } else if (currentTrack) {\n // If this is not the initial selection return null\n // option should have matched one in active group\n return null;\n } else {\n // Find the option in all tracks for initial selection\n const allIndex = findMatchingOption(subtitleOption, allSubtitleTracks);\n if (allIndex > -1) {\n return allSubtitleTracks[allIndex];\n }\n }\n }\n }\n return null;\n }\n loadPlaylist(hlsUrlParameters) {\n super.loadPlaylist();\n if (this.shouldLoadPlaylist(this.currentTrack)) {\n this.scheduleLoading(this.currentTrack, hlsUrlParameters);\n }\n }\n loadingPlaylist(currentTrack, hlsUrlParameters) {\n super.loadingPlaylist(currentTrack, hlsUrlParameters);\n const id = currentTrack.id;\n const groupId = currentTrack.groupId;\n const url = this.getUrlWithDirectives(currentTrack.url, hlsUrlParameters);\n const details = currentTrack.details;\n const age = details == null ? void 0 : details.age;\n this.log(`Loading subtitle ${id} \"${currentTrack.name}\" lang:${currentTrack.lang} group:${groupId}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : ''}${age && details.live ? ' age ' + age.toFixed(1) + (details.type ? ' ' + details.type || '' : '') : ''} ${url}`);\n this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {\n url,\n id,\n groupId,\n deliveryDirectives: hlsUrlParameters || null,\n track: currentTrack\n });\n }\n\n /**\n * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.\n * This operates on the DOM textTracks.\n * A value of -1 will disable all subtitle tracks.\n */\n toggleTrackModes() {\n const {\n media\n } = this;\n if (!media) {\n return;\n }\n const textTracks = filterSubtitleTracks(media.textTracks);\n const currentTrack = this.currentTrack;\n let nextTrack;\n if (currentTrack) {\n nextTrack = textTracks.filter(textTrack => subtitleTrackMatchesTextTrack(currentTrack, textTrack))[0];\n if (!nextTrack) {\n this.warn(`Unable to find subtitle TextTrack with name \"${currentTrack.name}\" and language \"${currentTrack.lang}\"`);\n }\n }\n [].slice.call(textTracks).forEach(track => {\n if (track.mode !== 'disabled' && track !== nextTrack) {\n track.mode = 'disabled';\n }\n });\n if (nextTrack) {\n const mode = this.subtitleDisplay ? 'showing' : 'hidden';\n if (nextTrack.mode !== mode) {\n nextTrack.mode = mode;\n }\n }\n }\n\n /**\n * This method is responsible for validating the subtitle index and periodically reloading if live.\n * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.\n */\n setSubtitleTrack(newId) {\n const tracks = this.tracksInGroup;\n\n // setting this.subtitleTrack will trigger internal logic\n // if media has not been attached yet, it will fail\n // we keep a reference to the default track id\n // and we'll set subtitleTrack when onMediaAttached is triggered\n if (!this.media) {\n this.queuedDefaultTrack = newId;\n return;\n }\n\n // exit if track id as already set or invalid\n if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) {\n this.warn(`Invalid subtitle track id: ${newId}`);\n return;\n }\n this.selectDefaultTrack = false;\n const lastTrack = this.currentTrack;\n const track = tracks[newId] || null;\n this.trackId = newId;\n this.currentTrack = track;\n this.toggleTrackModes();\n if (!track) {\n // switch to -1\n this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {\n id: newId\n });\n return;\n }\n const trackLoaded = !!track.details && !track.details.live;\n if (newId === this.trackId && track === lastTrack && trackLoaded) {\n return;\n }\n this.log(`Switching to subtitle-track ${newId}` + (track ? ` \"${track.name}\" lang:${track.lang} group:${track.groupId}` : ''));\n const {\n id,\n groupId = '',\n name,\n type,\n url\n } = track;\n this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {\n id,\n groupId,\n name,\n type,\n url\n });\n const hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);\n this.loadPlaylist(hlsUrlParameters);\n }\n}\n\n// From https://github.com/darkskyapp/string-hash\nfunction hash(text) {\n let hash = 5381;\n let i = text.length;\n while (i) {\n hash = hash * 33 ^ text.charCodeAt(--i);\n }\n return (hash >>> 0).toString();\n}\n\nconst ALIGNED_END_THRESHOLD_SECONDS = 0.025;\nlet TimelineOccupancy = /*#__PURE__*/function (TimelineOccupancy) {\n TimelineOccupancy[TimelineOccupancy[\"Point\"] = 0] = \"Point\";\n TimelineOccupancy[TimelineOccupancy[\"Range\"] = 1] = \"Range\";\n return TimelineOccupancy;\n}({});\nfunction generateAssetIdentifier(interstitial, uri, assetListIndex) {\n return `${interstitial.identifier}-${assetListIndex + 1}-${hash(uri)}`;\n}\nclass InterstitialEvent {\n constructor(dateRange, base) {\n this.base = void 0;\n this._duration = null;\n this._timelineStart = null;\n this.appendInPlaceDisabled = void 0;\n this.appendInPlaceStarted = void 0;\n this.dateRange = void 0;\n this.hasPlayed = false;\n this.cumulativeDuration = 0;\n this.resumeOffset = NaN;\n this.playoutLimit = NaN;\n this.restrictions = {\n skip: false,\n jump: false\n };\n this.snapOptions = {\n out: false,\n in: false\n };\n this.assetList = [];\n this.assetListLoader = void 0;\n this.assetListResponse = null;\n this.resumeAnchor = void 0;\n this.error = void 0;\n this.resetOnResume = void 0;\n this.base = base;\n this.dateRange = dateRange;\n this.setDateRange(dateRange);\n }\n setDateRange(dateRange) {\n this.dateRange = dateRange;\n this.resumeOffset = dateRange.attr.optionalFloat('X-RESUME-OFFSET', this.resumeOffset);\n this.playoutLimit = dateRange.attr.optionalFloat('X-PLAYOUT-LIMIT', this.playoutLimit);\n this.restrictions = dateRange.attr.enumeratedStringList('X-RESTRICT', this.restrictions);\n this.snapOptions = dateRange.attr.enumeratedStringList('X-SNAP', this.snapOptions);\n }\n reset() {\n var _this$assetListLoader;\n this.appendInPlaceStarted = false;\n (_this$assetListLoader = this.assetListLoader) == null ? void 0 : _this$assetListLoader.destroy();\n this.assetListLoader = undefined;\n if (!this.supplementsPrimary) {\n this.assetListResponse = null;\n this.assetList = [];\n this._duration = null;\n }\n // `error?` is reset when seeking back over interstitial `startOffset`\n // using `schedule.resetErrorsInRange(start, end)`.\n }\n isAssetPastPlayoutLimit(assetIndex) {\n if (assetIndex >= this.assetList.length) {\n return true;\n }\n const playoutLimit = this.playoutLimit;\n if (assetIndex <= 0 || isNaN(playoutLimit)) {\n return false;\n }\n const assetOffset = this.assetList[assetIndex].startOffset;\n return assetOffset > playoutLimit;\n }\n findAssetIndex(asset) {\n const index = this.assetList.indexOf(asset);\n return index;\n }\n get identifier() {\n return this.dateRange.id;\n }\n get startDate() {\n return this.dateRange.startDate;\n }\n get startTime() {\n // Primary media timeline start time\n const startTime = this.dateRange.startTime;\n if (this.snapOptions.out) {\n const frag = this.dateRange.tagAnchor;\n if (frag) {\n return getSnapToFragmentTime(startTime, frag);\n }\n }\n return startTime;\n }\n get startOffset() {\n return this.cue.pre ? 0 : this.startTime;\n }\n get startIsAligned() {\n if (this.startTime === 0 || this.snapOptions.out) {\n return true;\n }\n const frag = this.dateRange.tagAnchor;\n if (frag) {\n const startTime = this.dateRange.startTime;\n const snappedStart = getSnapToFragmentTime(startTime, frag);\n return startTime - snappedStart < 0.1;\n }\n return false;\n }\n get resumptionOffset() {\n const resumeOffset = this.resumeOffset;\n const offset = isFiniteNumber(resumeOffset) ? resumeOffset : this.duration;\n return this.cumulativeDuration + offset;\n }\n get resumeTime() {\n // Primary media timeline resumption time\n const resumeTime = this.startOffset + this.resumptionOffset;\n if (this.snapOptions.in) {\n const frag = this.resumeAnchor;\n if (frag) {\n return getSnapToFragmentTime(resumeTime, frag);\n }\n }\n return resumeTime;\n }\n get appendInPlace() {\n if (this.appendInPlaceStarted) {\n return true;\n }\n if (this.appendInPlaceDisabled) {\n return false;\n }\n if (!this.cue.once && !this.cue.pre &&\n // preroll starts at startPosition before startPosition is known (live)\n this.startIsAligned && (isNaN(this.playoutLimit) && isNaN(this.resumeOffset) || this.resumeOffset && this.duration && Math.abs(this.resumeOffset - this.duration) < ALIGNED_END_THRESHOLD_SECONDS)) {\n return true;\n }\n return false;\n }\n set appendInPlace(value) {\n if (this.appendInPlaceStarted) {\n this.resetOnResume = !value;\n return;\n }\n this.appendInPlaceDisabled = !value;\n }\n\n // Extended timeline start time\n get timelineStart() {\n if (this._timelineStart !== null) {\n return this._timelineStart;\n }\n return this.startTime;\n }\n set timelineStart(value) {\n this._timelineStart = value;\n }\n get duration() {\n const playoutLimit = this.playoutLimit;\n let duration;\n if (this._duration !== null) {\n duration = this._duration;\n } else if (this.dateRange.duration) {\n duration = this.dateRange.duration;\n } else {\n duration = this.dateRange.plannedDuration || 0;\n }\n if (!isNaN(playoutLimit) && playoutLimit < duration) {\n duration = playoutLimit;\n }\n return duration;\n }\n set duration(value) {\n this._duration = value;\n }\n get cue() {\n return this.dateRange.cue;\n }\n get timelineOccupancy() {\n if (this.dateRange.attr['X-TIMELINE-OCCUPIES'] === 'RANGE') {\n return TimelineOccupancy.Range;\n }\n return TimelineOccupancy.Point;\n }\n get supplementsPrimary() {\n return this.dateRange.attr['X-TIMELINE-STYLE'] === 'PRIMARY';\n }\n get contentMayVary() {\n return this.dateRange.attr['X-CONTENT-MAY-VARY'] !== 'NO';\n }\n get assetUrl() {\n return this.dateRange.attr['X-ASSET-URI'];\n }\n get assetListUrl() {\n return this.dateRange.attr['X-ASSET-LIST'];\n }\n get baseUrl() {\n return this.base.url;\n }\n get assetListLoaded() {\n return this.assetList.length > 0 || this.assetListResponse !== null;\n }\n toString() {\n return eventToString(this);\n }\n}\nfunction getSnapToFragmentTime(time, frag) {\n return time - frag.start < frag.duration / 2 && !(Math.abs(time - (frag.start + frag.duration)) < ALIGNED_END_THRESHOLD_SECONDS) ? frag.start : frag.start + frag.duration;\n}\nfunction getInterstitialUrl(uri, sessionId, baseUrl) {\n const url = new self.URL(uri, baseUrl);\n if (url.protocol !== 'data:') {\n url.searchParams.set('_HLS_primary_id', sessionId);\n }\n return url;\n}\nfunction eventToString(interstitial) {\n return `[\"${interstitial.identifier}\" ${interstitial.cue.pre ? '<pre>' : interstitial.cue.post ? '<post>' : ''}${interstitial.timelineStart.toFixed(2)}-${interstitial.resumeTime.toFixed(2)}]`;\n}\nfunction eventAssetToString(asset) {\n const start = asset.timelineStart;\n const duration = asset.duration || 0;\n return `[\"${asset.identifier}\" ${start.toFixed(2)}-${(start + duration).toFixed(2)}]`;\n}\n\nclass HlsAssetPlayer {\n constructor(HlsPlayerClass, userConfig, _interstitial, assetItem) {\n this.hls = void 0;\n this.interstitial = void 0;\n this.assetItem = void 0;\n this.tracks = null;\n this.hasDetails = false;\n this.mediaAttached = null;\n this._currentTime = void 0;\n this._bufferedEosTime = void 0;\n this.checkPlayout = () => {\n const interstitial = this.interstitial;\n const playoutLimit = interstitial.playoutLimit;\n const currentTime = this.currentTime;\n if (this.startOffset + currentTime >= playoutLimit) {\n this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED, {});\n }\n };\n const hls = this.hls = new HlsPlayerClass(userConfig);\n this.interstitial = _interstitial;\n this.assetItem = assetItem;\n let uri = assetItem.uri;\n try {\n uri = getInterstitialUrl(uri, hls.sessionId).href;\n } catch (error) {\n // Ignore error parsing ASSET_URI or adding _HLS_primary_id to it. The\n // issue should surface as an INTERSTITIAL_ASSET_ERROR loading the asset.\n }\n hls.loadSource(uri);\n const detailsLoaded = () => {\n this.hasDetails = true;\n };\n hls.once(Events.LEVEL_LOADED, detailsLoaded);\n hls.once(Events.AUDIO_TRACK_LOADED, detailsLoaded);\n hls.once(Events.SUBTITLE_TRACK_LOADED, detailsLoaded);\n hls.on(Events.MEDIA_ATTACHING, (name, {\n media\n }) => {\n this.removeMediaListeners();\n this.mediaAttached = media;\n const event = this.interstitial;\n if (event.playoutLimit) {\n media.addEventListener('timeupdate', this.checkPlayout);\n }\n });\n }\n bufferedInPlaceToEnd(media) {\n var _this$hls;\n if (!this.interstitial.appendInPlace) {\n return false;\n }\n if ((_this$hls = this.hls) != null && _this$hls.bufferedToEnd) {\n return true;\n }\n if (!media || !this._bufferedEosTime) {\n return false;\n }\n const start = this.timelineOffset;\n const bufferInfo = BufferHelper.bufferInfo(media, start, 0);\n const bufferedEnd = this.getAssetTime(bufferInfo.end);\n return bufferedEnd >= this._bufferedEosTime - 0.02;\n }\n get destroyed() {\n var _this$hls2;\n return !((_this$hls2 = this.hls) != null && _this$hls2.userConfig);\n }\n get assetId() {\n return this.assetItem.identifier;\n }\n get interstitialId() {\n return this.assetItem.parentIdentifier;\n }\n get media() {\n var _this$hls3;\n return ((_this$hls3 = this.hls) == null ? void 0 : _this$hls3.media) || null;\n }\n get bufferedEnd() {\n const media = this.media || this.mediaAttached;\n if (!media) {\n if (this._bufferedEosTime) {\n return this._bufferedEosTime;\n }\n return this.currentTime;\n }\n const bufferInfo = BufferHelper.bufferInfo(media, media.currentTime, 0.001);\n return this.getAssetTime(bufferInfo.end);\n }\n get currentTime() {\n const media = this.media || this.mediaAttached;\n if (!media) {\n return this._currentTime || 0;\n }\n return this.getAssetTime(media.currentTime);\n }\n get duration() {\n const duration = this.assetItem.duration;\n if (!duration) {\n return 0;\n }\n return duration;\n }\n get remaining() {\n const duration = this.duration;\n if (!duration) {\n return 0;\n }\n return Math.max(0, duration - this.currentTime);\n }\n get startOffset() {\n return this.assetItem.startOffset;\n }\n get timelineOffset() {\n var _this$hls4;\n return ((_this$hls4 = this.hls) == null ? void 0 : _this$hls4.config.timelineOffset) || 0;\n }\n set timelineOffset(value) {\n const timelineOffset = this.timelineOffset;\n if (value !== timelineOffset) {\n const diff = value - timelineOffset;\n if (Math.abs(diff) > 1 / 90000) {\n if (this.hasDetails) {\n throw new Error(`Cannot set timelineOffset after playlists are loaded`);\n }\n this.hls.config.timelineOffset = value;\n }\n }\n }\n getAssetTime(time) {\n const timelineOffset = this.timelineOffset;\n const duration = this.duration;\n return Math.min(Math.max(0, time - timelineOffset), duration);\n }\n removeMediaListeners() {\n const media = this.mediaAttached;\n if (media) {\n this._currentTime = media.currentTime;\n this.bufferSnapShot();\n media.removeEventListener('timeupdate', this.checkPlayout);\n }\n }\n bufferSnapShot() {\n if (this.mediaAttached) {\n var _this$hls5;\n if ((_this$hls5 = this.hls) != null && _this$hls5.bufferedToEnd) {\n this._bufferedEosTime = this.bufferedEnd;\n }\n }\n }\n destroy() {\n this.removeMediaListeners();\n this.hls.destroy();\n // @ts-ignore\n this.hls = this.interstitial = null;\n // @ts-ignore\n this.tracks = this.mediaAttached = this.checkPlayout = null;\n }\n attachMedia(data) {\n this.hls.attachMedia(data);\n }\n detachMedia() {\n this.removeMediaListeners();\n this.mediaAttached = null;\n this.hls.detachMedia();\n }\n resumeBuffering() {\n this.hls.resumeBuffering();\n }\n pauseBuffering() {\n this.hls.pauseBuffering();\n }\n transferMedia() {\n this.bufferSnapShot();\n return this.hls.transferMedia();\n }\n on(event, listener, context) {\n this.hls.on(event, listener);\n }\n once(event, listener, context) {\n this.hls.once(event, listener);\n }\n off(event, listener, context) {\n this.hls.off(event, listener);\n }\n toString() {\n var _this$hls6, _this$interstitial;\n return `HlsAssetPlayer: ${eventAssetToString(this.assetItem)} ${(_this$hls6 = this.hls) == null ? void 0 : _this$hls6.sessionId} ${(_this$interstitial = this.interstitial) != null && _this$interstitial.appendInPlace ? 'append-in-place' : ''}`;\n }\n}\n\nconst ABUTTING_THRESHOLD_SECONDS = 0.033;\nclass InterstitialsSchedule extends Logger {\n constructor(onScheduleUpdate, logger) {\n super('interstitials-sched', logger);\n this.onScheduleUpdate = void 0;\n this.eventMap = {};\n this.events = null;\n this.items = null;\n this.durations = {\n primary: 0,\n playout: 0,\n integrated: 0\n };\n this.onScheduleUpdate = onScheduleUpdate;\n }\n destroy() {\n this.reset();\n // @ts-ignore\n this.onScheduleUpdate = null;\n }\n reset() {\n this.eventMap = {};\n this.setDurations(0, 0, 0);\n if (this.events) {\n this.events.forEach(interstitial => interstitial.reset());\n }\n this.events = this.items = null;\n }\n resetErrorsInRange(start, end) {\n if (this.events) {\n return this.events.reduce((count, interstitial) => {\n if (start <= interstitial.startOffset && end > interstitial.startOffset) {\n delete interstitial.error;\n return count + 1;\n }\n return count;\n }, 0);\n }\n return 0;\n }\n get duration() {\n const items = this.items;\n return items ? items[items.length - 1].end : 0;\n }\n get length() {\n return this.items ? this.items.length : 0;\n }\n getEvent(identifier) {\n return identifier ? this.eventMap[identifier] || null : null;\n }\n hasEvent(identifier) {\n return identifier in this.eventMap;\n }\n findItemIndex(item, time) {\n if (item.event) {\n // Find Event Item\n return this.findEventIndex(item.event.identifier);\n }\n // Find Primary Item\n let index = -1;\n if (item.nextEvent) {\n index = this.findEventIndex(item.nextEvent.identifier) - 1;\n } else if (item.previousEvent) {\n index = this.findEventIndex(item.previousEvent.identifier) + 1;\n }\n const items = this.items;\n if (items) {\n if (!items[index]) {\n if (time === undefined) {\n time = item.start;\n }\n index = this.findItemIndexAtTime(time);\n }\n // Only return index of a Primary Item\n while (index >= 0 && (_items$index = items[index]) != null && _items$index.event) {\n var _items$index;\n // If index found is an interstitial it is not a valid result as it should have been matched up top\n // decrement until result is negative (not found) or a primary segment\n index--;\n }\n }\n return index;\n }\n findItemIndexAtTime(timelinePos, timelineType) {\n const items = this.items;\n if (items) {\n for (let i = 0; i < items.length; i++) {\n let timeRange = items[i];\n if (timelineType && timelineType !== 'primary') {\n timeRange = timeRange[timelineType];\n }\n if (timelinePos === timeRange.start || timelinePos > timeRange.start && timelinePos < timeRange.end) {\n return i;\n }\n }\n }\n return -1;\n }\n findJumpRestrictedIndex(startIndex, endIndex) {\n const items = this.items;\n if (items) {\n for (let i = startIndex; i <= endIndex; i++) {\n if (!items[i]) {\n break;\n }\n const event = items[i].event;\n if (event != null && event.restrictions.jump && !event.appendInPlace) {\n return i;\n }\n }\n }\n return -1;\n }\n findEventIndex(identifier) {\n const items = this.items;\n if (items) {\n for (let i = items.length; i--;) {\n var _items$i$event;\n if (((_items$i$event = items[i].event) == null ? void 0 : _items$i$event.identifier) === identifier) {\n return i;\n }\n }\n }\n return -1;\n }\n findAssetIndex(event, timelinePos) {\n const assetList = event.assetList;\n const length = assetList.length;\n if (length > 1) {\n for (let i = 0; i < length; i++) {\n const asset = assetList[i];\n if (!asset.error) {\n const timelineStart = asset.timelineStart;\n if (timelinePos === timelineStart || timelinePos > timelineStart && timelinePos < timelineStart + (asset.duration || 0)) {\n return i;\n }\n }\n }\n }\n return 0;\n }\n get assetIdAtEnd() {\n var _this$items, _this$items2;\n const interstitialAtEnd = (_this$items = this.items) == null ? void 0 : (_this$items2 = _this$items[this.length - 1]) == null ? void 0 : _this$items2.event;\n if (interstitialAtEnd) {\n const assetList = interstitialAtEnd.assetList;\n const assetAtEnd = assetList[assetList.length - 1];\n if (assetAtEnd) {\n return assetAtEnd.identifier;\n }\n }\n return null;\n }\n parseInterstitialDateRanges(mediaSelection, enableAppendInPlace) {\n const details = mediaSelection.main.details;\n const {\n dateRanges\n } = details;\n const previousInterstitialEvents = this.events;\n const interstitialEvents = this.parseDateRanges(dateRanges, {\n url: details.url\n }, enableAppendInPlace);\n const ids = Object.keys(dateRanges);\n const removedInterstitials = previousInterstitialEvents ? previousInterstitialEvents.filter(event => !ids.includes(event.identifier)) : [];\n if (interstitialEvents.length) {\n // pre-rolls, post-rolls, and events with the same start time are played in playlist tag order\n // all other events are ordered by start time\n interstitialEvents.sort((a, b) => {\n const aPre = a.cue.pre;\n const aPost = a.cue.post;\n const bPre = b.cue.pre;\n const bPost = b.cue.post;\n if (aPre && !bPre) {\n return -1;\n }\n if (bPre && !aPre) {\n return 1;\n }\n if (aPost && !bPost) {\n return 1;\n }\n if (bPost && !aPost) {\n return -1;\n }\n if (!aPre && !bPre && !aPost && !bPost) {\n const startA = a.startTime;\n const startB = b.startTime;\n if (startA !== startB) {\n return startA - startB;\n }\n }\n return a.dateRange.tagOrder - b.dateRange.tagOrder;\n });\n }\n this.events = interstitialEvents;\n\n // Clear removed DateRanges from buffered list (kills playback of active Interstitials)\n removedInterstitials.forEach(interstitial => {\n this.removeEvent(interstitial);\n });\n this.updateSchedule(mediaSelection, removedInterstitials);\n }\n updateSchedule(mediaSelection, removedInterstitials = []) {\n const events = this.events || [];\n if (events.length || removedInterstitials.length || this.length < 2) {\n const currentItems = this.items;\n const updatedItems = this.parseSchedule(events, mediaSelection);\n const updated = removedInterstitials.length || (currentItems == null ? void 0 : currentItems.length) !== updatedItems.length || updatedItems.some((item, i) => {\n return Math.abs(item.playout.start - currentItems[i].playout.start) > 0.005 || Math.abs(item.playout.end - currentItems[i].playout.end) > 0.005;\n });\n if (updated) {\n this.items = updatedItems;\n // call interstitials-controller onScheduleUpdated()\n this.onScheduleUpdate(removedInterstitials, currentItems);\n }\n }\n }\n parseDateRanges(dateRanges, baseData, enableAppendInPlace) {\n const interstitialEvents = [];\n const ids = Object.keys(dateRanges);\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i];\n const dateRange = dateRanges[id];\n if (dateRange.isInterstitial) {\n let interstitial = this.eventMap[id];\n if (interstitial) {\n // Update InterstitialEvent already parsed and mapped\n // This retains already loaded duration and loaded asset list info\n interstitial.setDateRange(dateRange);\n } else {\n interstitial = new InterstitialEvent(dateRange, baseData);\n this.eventMap[id] = interstitial;\n if (enableAppendInPlace === false) {\n interstitial.appendInPlace = enableAppendInPlace;\n }\n }\n interstitialEvents.push(interstitial);\n }\n }\n return interstitialEvents;\n }\n parseSchedule(interstitialEvents, mediaSelection) {\n const schedule = [];\n const details = mediaSelection.main.details;\n const primaryDuration = details.live ? Infinity : details.edge;\n let playoutDuration = 0;\n\n // Filter events that have errored from the schedule (Primary fallback)\n interstitialEvents = interstitialEvents.filter(event => !event.error && !(event.cue.once && event.hasPlayed));\n if (interstitialEvents.length) {\n // Update Schedule\n this.resolveOffsets(interstitialEvents, mediaSelection);\n\n // Populate Schedule with Interstitial Event and Primary Segment Items\n let primaryPosition = 0;\n let integratedTime = 0;\n interstitialEvents.forEach((interstitial, i) => {\n const preroll = interstitial.cue.pre;\n const postroll = interstitial.cue.post;\n const previousEvent = interstitialEvents[i - 1] || null;\n const appendInPlace = interstitial.appendInPlace;\n const eventStart = postroll ? primaryDuration : interstitial.startOffset;\n const interstitialDuration = interstitial.duration;\n const timelineDuration = interstitial.timelineOccupancy === TimelineOccupancy.Range ? interstitialDuration : 0;\n const resumptionOffset = interstitial.resumptionOffset;\n const inSameStartTimeSequence = (previousEvent == null ? void 0 : previousEvent.startTime) === eventStart;\n const start = eventStart + interstitial.cumulativeDuration;\n let end = appendInPlace ? start + interstitialDuration : eventStart + resumptionOffset;\n if (preroll || !postroll && eventStart <= 0) {\n // preroll or in-progress midroll\n const integratedStart = integratedTime;\n integratedTime += timelineDuration;\n interstitial.timelineStart = start;\n const playoutStart = playoutDuration;\n playoutDuration += interstitialDuration;\n schedule.push({\n event: interstitial,\n start,\n end,\n playout: {\n start: playoutStart,\n end: playoutDuration\n },\n integrated: {\n start: integratedStart,\n end: integratedTime\n }\n });\n } else if (eventStart <= primaryDuration) {\n if (!inSameStartTimeSequence) {\n const segmentDuration = eventStart - primaryPosition;\n // Do not schedule a primary segment if interstitials are abutting by less than ABUTTING_THRESHOLD_SECONDS\n if (segmentDuration > ABUTTING_THRESHOLD_SECONDS) {\n // primary segment\n const timelineStart = primaryPosition;\n const _integratedStart = integratedTime;\n integratedTime += segmentDuration;\n const _playoutStart = playoutDuration;\n playoutDuration += segmentDuration;\n const primarySegment = {\n previousEvent: interstitialEvents[i - 1] || null,\n nextEvent: interstitial,\n start: timelineStart,\n end: timelineStart + segmentDuration,\n playout: {\n start: _playoutStart,\n end: playoutDuration\n },\n integrated: {\n start: _integratedStart,\n end: integratedTime\n }\n };\n schedule.push(primarySegment);\n } else if (segmentDuration > 0 && previousEvent) {\n // Add previous event `resumeTime` (based on duration or resumeOffset) so that it ends aligned with this one\n previousEvent.cumulativeDuration += segmentDuration;\n schedule[schedule.length - 1].end = eventStart;\n }\n }\n // midroll / postroll\n if (postroll) {\n end = start;\n }\n interstitial.timelineStart = start;\n const integratedStart = integratedTime;\n integratedTime += timelineDuration;\n const playoutStart = playoutDuration;\n playoutDuration += interstitialDuration;\n schedule.push({\n event: interstitial,\n start,\n end,\n playout: {\n start: playoutStart,\n end: playoutDuration\n },\n integrated: {\n start: integratedStart,\n end: integratedTime\n }\n });\n } else {\n // Interstitial starts after end of primary VOD - not included in schedule\n return;\n }\n const resumeTime = interstitial.resumeTime;\n if (postroll || resumeTime > primaryDuration) {\n primaryPosition = primaryDuration;\n } else {\n primaryPosition = resumeTime;\n }\n });\n if (primaryPosition < primaryDuration) {\n var _schedule;\n // last primary segment\n const timelineStart = primaryPosition;\n const integratedStart = integratedTime;\n const segmentDuration = primaryDuration - primaryPosition;\n integratedTime += segmentDuration;\n const playoutStart = playoutDuration;\n playoutDuration += segmentDuration;\n schedule.push({\n previousEvent: ((_schedule = schedule[schedule.length - 1]) == null ? void 0 : _schedule.event) || null,\n nextEvent: null,\n start: primaryPosition,\n end: timelineStart + segmentDuration,\n playout: {\n start: playoutStart,\n end: playoutDuration\n },\n integrated: {\n start: integratedStart,\n end: integratedTime\n }\n });\n }\n this.setDurations(primaryDuration, playoutDuration, integratedTime);\n } else {\n // no interstials - schedule is one primary segment\n const start = 0;\n schedule.push({\n previousEvent: null,\n nextEvent: null,\n start,\n end: primaryDuration,\n playout: {\n start,\n end: primaryDuration\n },\n integrated: {\n start,\n end: primaryDuration\n }\n });\n this.setDurations(primaryDuration, primaryDuration, primaryDuration);\n }\n return schedule;\n }\n setDurations(primary, playout, integrated) {\n this.durations = {\n primary,\n playout,\n integrated\n };\n }\n resolveOffsets(interstitialEvents, mediaSelection) {\n const details = mediaSelection.main.details;\n const primaryDuration = details.live ? Infinity : details.edge;\n\n // First resolve cumulative resumption offsets for Interstitials that start at the same DateTime\n let cumulativeDuration = 0;\n let lastScheduledStart = -1;\n interstitialEvents.forEach((interstitial, i) => {\n const preroll = interstitial.cue.pre;\n const postroll = interstitial.cue.post;\n const eventStart = preroll ? 0 : postroll ? primaryDuration : interstitial.startTime;\n this.updateAssetDurations(interstitial);\n\n // X-RESUME-OFFSET values of interstitials scheduled at the same time are cumulative\n const inSameStartTimeSequence = lastScheduledStart === eventStart;\n if (inSameStartTimeSequence) {\n interstitial.cumulativeDuration = cumulativeDuration;\n } else {\n cumulativeDuration = 0;\n lastScheduledStart = eventStart;\n }\n if (!postroll && interstitial.snapOptions.in) {\n // FIXME: Include audio playlist in snapping\n interstitial.resumeAnchor = findFragmentByPTS(null, details.fragments, interstitial.startOffset + interstitial.resumptionOffset, 0, 0) || undefined;\n }\n // Check if primary fragments align with resumption offset and disable appendInPlace if they do not\n if (interstitial.appendInPlace && !interstitial.appendInPlaceStarted) {\n const alignedSegmentStart = this.primaryCanResumeInPlaceAt(interstitial, mediaSelection);\n if (!alignedSegmentStart) {\n interstitial.appendInPlace = false;\n }\n }\n if (!interstitial.appendInPlace && i + 1 < interstitialEvents.length) {\n // abutting Interstitials must use the same MediaSource strategy, this applies to all whether or not they are back to back:\n const timeBetween = interstitialEvents[i + 1].startTime - interstitialEvents[i].resumeTime;\n if (timeBetween < ABUTTING_THRESHOLD_SECONDS) {\n interstitialEvents[i + 1].appendInPlace = false;\n if (interstitialEvents[i + 1].appendInPlace) {\n this.warn(`Could not change append strategy for abutting event ${interstitial}`);\n }\n }\n }\n // Update cumulativeDuration for next abutting interstitial with the same start date\n const resumeOffset = isFiniteNumber(interstitial.resumeOffset) ? interstitial.resumeOffset : interstitial.duration;\n cumulativeDuration += resumeOffset;\n });\n }\n primaryCanResumeInPlaceAt(interstitial, mediaSelection) {\n const resumeTime = interstitial.resumeTime;\n const resumesInPlaceAt = interstitial.startTime + interstitial.resumptionOffset;\n if (Math.abs(resumeTime - resumesInPlaceAt) > ALIGNED_END_THRESHOLD_SECONDS) {\n this.log(`\"${interstitial.identifier}\" resumption ${resumeTime} not aligned with estimated timeline end ${resumesInPlaceAt}`);\n return false;\n }\n if (!mediaSelection) {\n this.log(`\"${interstitial.identifier}\" resumption ${resumeTime} can not be aligned with media (none selected)`);\n return false;\n }\n const playlists = Object.keys(mediaSelection);\n return !playlists.some(playlistType => {\n const details = mediaSelection[playlistType].details;\n const playlistEnd = details.edge;\n if (resumeTime >= playlistEnd) {\n // Live playback - resumption segments are not yet available\n this.log(`\"${interstitial.identifier}\" resumption ${resumeTime} past ${playlistType} playlist end ${playlistEnd}`);\n // Assume alignment is possible (or reset can take place)\n return false;\n }\n const startFragment = findFragmentByPTS(null, details.fragments, resumeTime);\n if (!startFragment) {\n this.log(`\"${interstitial.identifier}\" resumption ${resumeTime} does not align with any fragments in ${playlistType} playlist (${details.fragStart}-${details.fragmentEnd})`);\n return true;\n }\n const allowance = playlistType === 'audio' ? 0.175 : 0;\n const alignedWithSegment = Math.abs(startFragment.start - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance || Math.abs(startFragment.end - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance;\n if (!alignedWithSegment) {\n this.log(`\"${interstitial.identifier}\" resumption ${resumeTime} not aligned with ${playlistType} fragment bounds (${startFragment.start}-${startFragment.end} sn: ${startFragment.sn} cc: ${startFragment.cc})`);\n return true;\n }\n return false;\n });\n }\n updateAssetDurations(interstitial) {\n if (!interstitial.assetListLoaded) {\n return;\n }\n const eventStart = interstitial.timelineStart;\n let sumDuration = 0;\n let hasUnknownDuration = false;\n let hasErrors = false;\n interstitial.assetList.forEach((asset, i) => {\n const timelineStart = eventStart + sumDuration;\n asset.startOffset = sumDuration;\n asset.timelineStart = timelineStart;\n hasUnknownDuration || (hasUnknownDuration = asset.duration === null);\n hasErrors || (hasErrors = !!asset.error);\n const duration = asset.error ? 0 : asset.duration || 0;\n sumDuration += duration;\n });\n // Use the sum of known durations when it is greater than the stated duration\n if (hasUnknownDuration && !hasErrors) {\n interstitial.duration = Math.max(sumDuration, interstitial.duration);\n } else {\n interstitial.duration = sumDuration;\n }\n }\n removeEvent(interstitial) {\n interstitial.reset();\n delete this.eventMap[interstitial.identifier];\n }\n}\nfunction segmentToString(segment) {\n return `[${segment.event ? '\"' + segment.event.identifier + '\"' : 'primary'}: ${segment.start.toFixed(2)}-${segment.end.toFixed(2)}]`;\n}\n\nclass AssetListLoader {\n constructor(hls) {\n this.hls = void 0;\n this.hls = hls;\n }\n destroy() {\n // @ts-ignore\n this.hls = null;\n }\n loadAssetList(interstitial, hlsStartOffset) {\n const assetListUrl = interstitial.assetListUrl;\n let url;\n try {\n url = getInterstitialUrl(assetListUrl, this.hls.sessionId, interstitial.baseUrl);\n } catch (error) {\n const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, error, assetListUrl);\n this.hls.trigger(Events.ERROR, errorData);\n return;\n }\n if (hlsStartOffset && url.protocol !== 'data:') {\n url.searchParams.set('_HLS_start_offset', '' + hlsStartOffset);\n }\n const config = this.hls.config;\n const Loader = config.loader;\n const loader = new Loader(config);\n const context = {\n responseType: 'json',\n url: url.href\n };\n const loadPolicy = config.interstitialAssetListLoadPolicy.default;\n const loaderConfig = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0\n };\n const callbacks = {\n onSuccess: (response, stats, context, networkDetails) => {\n const assetListResponse = response.data;\n const assets = assetListResponse == null ? void 0 : assetListResponse.ASSETS;\n if (!Array.isArray(assets)) {\n const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_PARSING_ERROR, new Error(`Invalid interstitial asset list`), context.url, stats, networkDetails);\n this.hls.trigger(Events.ERROR, errorData);\n return;\n }\n interstitial.assetListResponse = assetListResponse;\n this.hls.trigger(Events.ASSET_LIST_LOADED, {\n event: interstitial,\n assetListResponse,\n networkDetails\n });\n },\n onError: (error, context, networkDetails, stats) => {\n const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, new Error(`Error loading X-ASSET-LIST: HTTP status ${error.code} ${error.text} (${context.url})`), context.url, stats, networkDetails);\n this.hls.trigger(Events.ERROR, errorData);\n },\n onTimeout: (stats, context, networkDetails) => {\n const errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_TIMEOUT, new Error(`Timeout loading X-ASSET-LIST (${context.url})`), context.url, stats, networkDetails);\n this.hls.trigger(Events.ERROR, errorData);\n }\n };\n loader.load(context, loaderConfig, callbacks);\n this.hls.trigger(Events.ASSET_LIST_LOADING, {\n event: interstitial\n });\n return loader;\n }\n assignAssetListError(interstitial, details, error, url, stats, networkDetails) {\n interstitial.error = error;\n return {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal: false,\n interstitial,\n url,\n error,\n networkDetails,\n stats\n };\n }\n}\n\nfunction addEventListener(el, type, listener) {\n removeEventListener(el, type, listener);\n el.addEventListener(type, listener);\n}\nfunction removeEventListener(el, type, listener) {\n el.removeEventListener(type, listener);\n}\n\nfunction playWithCatch(media) {\n media == null ? void 0 : media.play().catch(() => {\n /* no-op */\n });\n}\nclass InterstitialsController extends Logger {\n constructor(hls, HlsPlayerClass) {\n super('interstitials', hls.logger);\n this.HlsPlayerClass = void 0;\n this.hls = void 0;\n this.assetListLoader = void 0;\n // Last updated LevelDetails\n this.mediaSelection = null;\n this.altSelection = null;\n // Media and MediaSource/SourceBuffers\n this.media = null;\n this.detachedData = null;\n this.requiredTracks = null;\n // Public Interface for Interstitial playback state and control\n this.manager = null;\n // Interstitial Asset Players\n this.playerQueue = [];\n // Timeline position tracking\n this.bufferedPos = -1;\n this.timelinePos = -1;\n // Schedule\n this.schedule = void 0;\n // Schedule playback and buffering state\n this.playingItem = null;\n this.bufferingItem = null;\n this.waitingItem = null;\n this.endedItem = null;\n this.playingAsset = null;\n this.endedAsset = null;\n this.bufferingAsset = null;\n this.shouldPlay = false;\n this.onPlay = () => {\n this.shouldPlay = true;\n };\n this.onPause = () => {\n this.shouldPlay = false;\n };\n this.onSeeking = () => {\n const currentTime = this.currentTime;\n if (currentTime === undefined || this.playbackDisabled) {\n return;\n }\n const diff = currentTime - this.timelinePos;\n const roundingError = Math.abs(diff) < 1 / 705600000; // one flick\n if (roundingError) {\n return;\n }\n const backwardSeek = diff <= -0.01;\n this.timelinePos = currentTime;\n this.bufferedPos = currentTime;\n\n // Check if seeking out of an item\n const playingItem = this.playingItem;\n if (!playingItem) {\n this.checkBuffer();\n return;\n }\n if (backwardSeek) {\n const resetCount = this.schedule.resetErrorsInRange(currentTime, currentTime - diff);\n if (resetCount) {\n this.updateSchedule();\n }\n }\n this.checkBuffer();\n if (backwardSeek && currentTime < playingItem.start || currentTime >= playingItem.end) {\n var _this$media;\n const scheduleIndex = this.schedule.findItemIndexAtTime(this.timelinePos);\n if (!this.isInterstitial(playingItem) && (_this$media = this.media) != null && _this$media.paused) {\n this.shouldPlay = false;\n }\n if (!backwardSeek) {\n // check if an Interstitial between the current item and target item has an X-RESTRICT JUMP restriction\n const playingIndex = this.findItemIndex(playingItem);\n if (scheduleIndex > playingIndex) {\n const jumpIndex = this.schedule.findJumpRestrictedIndex(playingIndex + 1, scheduleIndex);\n if (jumpIndex > playingIndex) {\n this.setSchedulePosition(jumpIndex);\n return;\n }\n }\n }\n this.setSchedulePosition(scheduleIndex);\n return;\n }\n // Check if seeking out of an asset (assumes same item following above check)\n const playingAsset = this.playingAsset;\n if (!playingAsset) {\n // restart Interstitial at end\n if (this.playingLastItem && this.isInterstitial(playingItem)) {\n const restartAsset = playingItem.event.assetList[0];\n if (restartAsset) {\n this.endedItem = this.playingItem;\n this.playingItem = null;\n this.setScheduleToAssetAtTime(currentTime, restartAsset);\n }\n }\n return;\n }\n const start = playingAsset.timelineStart;\n const duration = playingAsset.duration || 0;\n if (backwardSeek && currentTime < start || currentTime >= start + duration) {\n this.setScheduleToAssetAtTime(currentTime, playingAsset);\n }\n };\n this.onTimeupdate = () => {\n const currentTime = this.currentTime;\n if (currentTime === undefined || this.playbackDisabled) {\n return;\n }\n\n // Only allow timeupdate to advance primary position, seeking is used for jumping back\n // this prevents primaryPos from being reset to 0 after re-attach\n if (currentTime > this.timelinePos) {\n this.timelinePos = currentTime;\n if (currentTime > this.bufferedPos) {\n this.checkBuffer();\n }\n } else {\n return;\n }\n\n // Check if playback has entered the next item\n const playingItem = this.playingItem;\n if (!playingItem || this.playingLastItem) {\n return;\n }\n if (currentTime >= playingItem.end) {\n this.timelinePos = playingItem.end;\n const playingIndex = this.findItemIndex(playingItem);\n this.setSchedulePosition(playingIndex + 1);\n }\n // Check if playback has entered the next asset\n const playingAsset = this.playingAsset;\n if (!playingAsset) {\n return;\n }\n const end = playingAsset.timelineStart + (playingAsset.duration || 0);\n if (currentTime >= end) {\n this.setScheduleToAssetAtTime(currentTime, playingAsset);\n }\n };\n // Schedule update callback\n this.onScheduleUpdate = (removedInterstitials, previousItems) => {\n const schedule = this.schedule;\n const playingItem = this.playingItem;\n const interstitialEvents = schedule.events || [];\n const scheduleItems = schedule.items || [];\n const durations = schedule.durations;\n const removedIds = removedInterstitials.map(interstitial => interstitial.identifier);\n const interstitialsUpdated = !!(interstitialEvents.length || removedIds.length);\n if (interstitialsUpdated) {\n this.log(`INTERSTITIALS_UPDATED (${interstitialEvents.length}): ${interstitialEvents}\nSchedule: ${scheduleItems.map(seg => segmentToString(seg))}`);\n }\n if (removedIds.length) {\n this.log(`Removed events ${removedIds}`);\n }\n this.playerQueue.forEach(player => {\n if (player.interstitial.appendInPlace) {\n const timelineStart = player.assetItem.timelineStart;\n const diff = player.timelineOffset - timelineStart;\n if (diff) {\n try {\n player.timelineOffset = timelineStart;\n } catch (e) {\n if (Math.abs(diff) > ALIGNED_END_THRESHOLD_SECONDS) {\n this.warn(`${e} (\"${player.assetId}\" ${player.timelineOffset}->${timelineStart})`);\n }\n }\n }\n }\n });\n\n // Update schedule item references\n // Do not replace Interstitial playingItem without a match - used for INTERSTITIAL_ASSET_ENDED and INTERSTITIAL_ENDED\n if (playingItem) {\n const updatedPlayingItem = this.updateItem(playingItem, this.timelinePos);\n if (this.itemsMatch(playingItem, updatedPlayingItem)) {\n this.playingItem = updatedPlayingItem;\n this.waitingItem = this.endedItem = null;\n }\n } else {\n // Clear waitingItem if it has been removed from the schedule\n this.waitingItem = this.updateItem(this.waitingItem);\n this.endedItem = this.updateItem(this.endedItem);\n }\n // Do not replace Interstitial bufferingItem without a match - used for transfering media element or source\n const bufferingItem = this.bufferingItem;\n if (bufferingItem) {\n const updatedBufferingItem = this.updateItem(bufferingItem, this.bufferedPos);\n if (this.itemsMatch(bufferingItem, updatedBufferingItem)) {\n this.bufferingItem = updatedBufferingItem;\n } else if (bufferingItem.event) {\n // Interstitial removed from schedule (Live -> VOD or other scenario where Start Date is outside the range of VOD Playlist)\n this.bufferingItem = this.playingItem;\n this.clearInterstitial(bufferingItem.event, null);\n }\n }\n removedInterstitials.forEach(interstitial => {\n interstitial.assetList.forEach(asset => {\n this.clearAssetPlayer(asset.identifier, null);\n });\n });\n if (interstitialsUpdated || previousItems) {\n this.hls.trigger(Events.INTERSTITIALS_UPDATED, {\n events: interstitialEvents.slice(0),\n schedule: scheduleItems.slice(0),\n durations,\n removedIds\n });\n if (this.isInterstitial(playingItem) && removedIds.includes(playingItem.event.identifier)) {\n this.warn(`Interstitial \"${playingItem.event.identifier}\" removed while playing`);\n this.primaryFallback(playingItem.event);\n return;\n }\n\n // Check is buffered to new Interstitial event boundary\n // (Live update publishes Interstitial with new segment)\n this.checkBuffer();\n }\n };\n this.hls = hls;\n this.HlsPlayerClass = HlsPlayerClass;\n this.assetListLoader = new AssetListLoader(hls);\n this.schedule = new InterstitialsSchedule(this.onScheduleUpdate, hls.logger);\n this.registerListeners();\n }\n registerListeners() {\n const hls = this.hls;\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.on(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);\n hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n hls.on(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);\n hls.on(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);\n hls.on(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);\n hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.on(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);\n hls.on(Events.MEDIA_ENDED, this.onMediaEnded, this);\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.DESTROYING, this.onDestroying, this);\n }\n unregisterListeners() {\n const hls = this.hls;\n if (!hls) {\n return;\n }\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.off(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);\n hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n hls.off(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);\n hls.off(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);\n hls.off(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);\n hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.off(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);\n hls.off(Events.MEDIA_ENDED, this.onMediaEnded, this);\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.DESTROYING, this.onDestroying, this);\n }\n startLoad() {\n // TODO: startLoad - check for waitingItem and retry by resetting schedule\n this.resumeBuffering();\n }\n stopLoad() {\n // TODO: stopLoad - stop all scheule.events[].assetListLoader?.abort() then delete the loaders\n this.pauseBuffering();\n }\n resumeBuffering() {\n var _this$getBufferingPla;\n (_this$getBufferingPla = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla.resumeBuffering();\n }\n pauseBuffering() {\n var _this$getBufferingPla2;\n (_this$getBufferingPla2 = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla2.pauseBuffering();\n }\n destroy() {\n this.unregisterListeners();\n this.stopLoad();\n if (this.assetListLoader) {\n this.assetListLoader.destroy();\n }\n this.emptyPlayerQueue();\n this.clearScheduleState();\n if (this.schedule) {\n this.schedule.destroy();\n }\n this.media = this.detachedData = this.mediaSelection = this.requiredTracks = this.altSelection = this.manager = null;\n // @ts-ignore\n this.hls = this.HlsPlayerClass = this.schedule = this.log = null;\n // @ts-ignore\n this.assetListLoader = null;\n // @ts-ignore\n this.onPlay = this.onPause = this.onSeeking = this.onTimeupdate = null;\n // @ts-ignore\n this.onScheduleUpdate = null;\n }\n onDestroying() {\n const media = this.primaryMedia || this.media;\n if (media) {\n this.removeMediaListeners(media);\n }\n }\n removeMediaListeners(media) {\n removeEventListener(media, 'play', this.onPlay);\n removeEventListener(media, 'pause', this.onPause);\n removeEventListener(media, 'seeking', this.onSeeking);\n removeEventListener(media, 'timeupdate', this.onTimeupdate);\n }\n onMediaAttaching(event, data) {\n const media = this.media = data.media;\n addEventListener(media, 'seeking', this.onSeeking);\n addEventListener(media, 'timeupdate', this.onTimeupdate);\n addEventListener(media, 'play', this.onPlay);\n addEventListener(media, 'pause', this.onPause);\n }\n onMediaAttached(event, data) {\n const playingItem = this.effectivePlayingItem;\n const detachedMedia = this.detachedData;\n this.detachedData = null;\n if (playingItem === null) {\n this.checkStart();\n } else if (!detachedMedia) {\n // Resume schedule after detached externally\n this.clearScheduleState();\n const playingIndex = this.findItemIndex(playingItem);\n this.setSchedulePosition(playingIndex);\n }\n }\n clearScheduleState() {\n this.playingItem = this.bufferingItem = this.waitingItem = this.endedItem = this.playingAsset = this.endedAsset = this.bufferingAsset = null;\n }\n onMediaDetaching(event, data) {\n const transferringMedia = !!data.transferMedia;\n const media = this.media;\n this.media = null;\n if (transferringMedia) {\n return;\n }\n if (media) {\n this.removeMediaListeners(media);\n }\n // If detachMedia is called while in an Interstitial, detach the asset player as well and reset the schedule position\n if (this.detachedData) {\n const player = this.getBufferingPlayer();\n if (player) {\n this.playingAsset = this.endedAsset = this.bufferingAsset = this.bufferingItem = this.waitingItem = this.detachedData = null;\n player.detachMedia();\n }\n this.shouldPlay = false;\n }\n }\n get interstitialsManager() {\n if (!this.manager) {\n if (!this.hls) {\n return null;\n }\n const c = this;\n const effectiveBufferingItem = () => c.bufferingItem || c.waitingItem;\n const getAssetPlayer = asset => asset ? c.getAssetPlayer(asset.identifier) : asset;\n const getMappedTime = (item, timelineType, asset, controllerField, assetPlayerField) => {\n if (item) {\n let time = item[timelineType].start;\n const interstitial = item.event;\n if (interstitial) {\n if (timelineType === 'playout' || interstitial.timelineOccupancy !== TimelineOccupancy.Point) {\n const assetPlayer = getAssetPlayer(asset);\n if ((assetPlayer == null ? void 0 : assetPlayer.interstitial) === interstitial) {\n time += assetPlayer.assetItem.startOffset + assetPlayer[assetPlayerField];\n }\n }\n } else {\n const value = controllerField === 'bufferedPos' ? getBufferedEnd() : c[controllerField];\n time += value - item.start;\n }\n return time;\n }\n return 0;\n };\n const findMappedTime = (primaryTime, timelineType) => {\n if (primaryTime !== 0 && timelineType !== 'primary' && c.schedule.length) {\n var _c$schedule$items;\n const index = c.schedule.findItemIndexAtTime(primaryTime);\n const item = (_c$schedule$items = c.schedule.items) == null ? void 0 : _c$schedule$items[index];\n if (item) {\n const diff = item[timelineType].start - item.start;\n return primaryTime + diff;\n }\n }\n return primaryTime;\n };\n const getBufferedEnd = () => {\n const value = c.bufferedPos;\n if (value === Number.MAX_VALUE) {\n return getMappedDuration('primary');\n }\n return Math.max(value, 0);\n };\n const getMappedDuration = timelineType => {\n var _c$primaryDetails;\n if ((_c$primaryDetails = c.primaryDetails) != null && _c$primaryDetails.live) {\n // return end of last event item or playlist\n return c.primaryDetails.edge;\n }\n return c.schedule.durations[timelineType];\n };\n const seekTo = (time, timelineType) => {\n var _item$event, _c$schedule$items2;\n const item = c.effectivePlayingItem;\n if (item != null && (_item$event = item.event) != null && _item$event.restrictions.skip) {\n return;\n }\n c.log(`seek to ${time} \"${timelineType}\"`);\n const playingItem = c.effectivePlayingItem;\n const targetIndex = c.schedule.findItemIndexAtTime(time, timelineType);\n const targetItem = (_c$schedule$items2 = c.schedule.items) == null ? void 0 : _c$schedule$items2[targetIndex];\n const bufferingPlayer = c.getBufferingPlayer();\n const bufferingInterstitial = bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial;\n const appendInPlace = bufferingInterstitial == null ? void 0 : bufferingInterstitial.appendInPlace;\n const seekInItem = playingItem && c.itemsMatch(playingItem, targetItem);\n if (playingItem && (appendInPlace || seekInItem)) {\n // seek in asset player or primary media (appendInPlace)\n const assetPlayer = getAssetPlayer(c.playingAsset);\n const media = (assetPlayer == null ? void 0 : assetPlayer.media) || c.primaryMedia;\n if (media) {\n const currentTime = timelineType === 'primary' ? media.currentTime : getMappedTime(playingItem, timelineType, c.playingAsset, 'timelinePos', 'currentTime');\n const diff = time - currentTime;\n const seekToTime = (appendInPlace ? currentTime : media.currentTime) + diff;\n if (seekToTime >= 0 && (!assetPlayer || appendInPlace || seekToTime <= assetPlayer.duration)) {\n media.currentTime = seekToTime;\n return;\n }\n }\n }\n // seek out of item or asset\n if (targetItem) {\n let seekToTime = time;\n if (timelineType !== 'primary') {\n const primarySegmentStart = targetItem[timelineType].start;\n const diff = time - primarySegmentStart;\n seekToTime = targetItem.start + diff;\n }\n const targetIsPrimary = !c.isInterstitial(targetItem);\n if ((!c.isInterstitial(playingItem) || playingItem.event.appendInPlace) && (targetIsPrimary || targetItem.event.appendInPlace)) {\n const media = c.media || (appendInPlace ? bufferingPlayer == null ? void 0 : bufferingPlayer.media : null);\n if (media) {\n media.currentTime = seekToTime;\n }\n } else if (playingItem) {\n // check if an Interstitial between the current item and target item has an X-RESTRICT JUMP restriction\n const playingIndex = c.findItemIndex(playingItem);\n if (targetIndex > playingIndex) {\n const jumpIndex = c.schedule.findJumpRestrictedIndex(playingIndex + 1, targetIndex);\n if (jumpIndex > playingIndex) {\n c.setSchedulePosition(jumpIndex);\n return;\n }\n }\n let assetIndex = 0;\n if (targetIsPrimary) {\n c.timelinePos = seekToTime;\n c.checkBuffer();\n } else {\n var _targetItem$event;\n const assetList = targetItem == null ? void 0 : (_targetItem$event = targetItem.event) == null ? void 0 : _targetItem$event.assetList;\n if (assetList) {\n const eventTime = time - (targetItem[timelineType] || targetItem).start;\n for (let i = assetList.length; i--;) {\n const asset = assetList[i];\n if (asset.duration && eventTime >= asset.startOffset && eventTime < asset.startOffset + asset.duration) {\n assetIndex = i;\n break;\n }\n }\n }\n }\n c.setSchedulePosition(targetIndex, assetIndex);\n }\n }\n };\n const getActiveInterstitial = () => {\n const playingItem = c.effectivePlayingItem;\n if (c.isInterstitial(playingItem)) {\n return playingItem;\n }\n const bufferingItem = effectiveBufferingItem();\n if (c.isInterstitial(bufferingItem)) {\n return bufferingItem;\n }\n return null;\n };\n const interstitialPlayer = {\n get currentTime() {\n const interstitialItem = getActiveInterstitial();\n const playingItem = c.effectivePlayingItem;\n if (playingItem && playingItem === interstitialItem) {\n return getMappedTime(playingItem, 'playout', c.effectivePlayingAsset, 'timelinePos', 'currentTime') - playingItem.playout.start;\n }\n return 0;\n },\n set currentTime(time) {\n const interstitialItem = getActiveInterstitial();\n const playingItem = c.effectivePlayingItem;\n if (playingItem && playingItem === interstitialItem) {\n seekTo(time + playingItem.playout.start, 'playout');\n }\n },\n get duration() {\n const interstitialItem = getActiveInterstitial();\n if (interstitialItem) {\n return interstitialItem.playout.end - interstitialItem.playout.start;\n }\n return 0;\n },\n get assetPlayers() {\n var _getActiveInterstitia;\n const assetList = (_getActiveInterstitia = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia.event.assetList;\n if (assetList) {\n return assetList.map(asset => c.getAssetPlayer(asset.identifier));\n }\n return [];\n },\n get playingIndex() {\n var _getActiveInterstitia2;\n const interstitial = (_getActiveInterstitia2 = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia2.event;\n if (interstitial && c.effectivePlayingAsset) {\n return interstitial.findAssetIndex(c.effectivePlayingAsset);\n }\n return -1;\n },\n get scheduleItem() {\n return getActiveInterstitial();\n }\n };\n this.manager = {\n get events() {\n var _c$schedule, _c$schedule$events;\n return ((_c$schedule = c.schedule) == null ? void 0 : (_c$schedule$events = _c$schedule.events) == null ? void 0 : _c$schedule$events.slice(0)) || [];\n },\n get schedule() {\n var _c$schedule2, _c$schedule2$items;\n return ((_c$schedule2 = c.schedule) == null ? void 0 : (_c$schedule2$items = _c$schedule2.items) == null ? void 0 : _c$schedule2$items.slice(0)) || [];\n },\n get interstitialPlayer() {\n if (getActiveInterstitial()) {\n return interstitialPlayer;\n }\n return null;\n },\n get playerQueue() {\n return c.playerQueue.slice(0);\n },\n get bufferingAsset() {\n return c.bufferingAsset;\n },\n get bufferingItem() {\n return effectiveBufferingItem();\n },\n get bufferingIndex() {\n const item = effectiveBufferingItem();\n return c.findItemIndex(item);\n },\n get playingAsset() {\n return c.effectivePlayingAsset;\n },\n get playingItem() {\n return c.effectivePlayingItem;\n },\n get playingIndex() {\n const item = c.effectivePlayingItem;\n return c.findItemIndex(item);\n },\n primary: {\n get bufferedEnd() {\n return getBufferedEnd();\n },\n get currentTime() {\n const timelinePos = c.timelinePos;\n return timelinePos > 0 ? timelinePos : 0;\n },\n set currentTime(time) {\n seekTo(time, 'primary');\n },\n get duration() {\n return getMappedDuration('primary');\n },\n get seekableStart() {\n var _c$primaryDetails2;\n return ((_c$primaryDetails2 = c.primaryDetails) == null ? void 0 : _c$primaryDetails2.fragmentStart) || 0;\n }\n },\n integrated: {\n get bufferedEnd() {\n return getMappedTime(effectiveBufferingItem(), 'integrated', c.bufferingAsset, 'bufferedPos', 'bufferedEnd');\n },\n get currentTime() {\n return getMappedTime(c.effectivePlayingItem, 'integrated', c.effectivePlayingAsset, 'timelinePos', 'currentTime');\n },\n set currentTime(time) {\n seekTo(time, 'integrated');\n },\n get duration() {\n return getMappedDuration('integrated');\n },\n get seekableStart() {\n var _c$primaryDetails3;\n return findMappedTime(((_c$primaryDetails3 = c.primaryDetails) == null ? void 0 : _c$primaryDetails3.fragmentStart) || 0, 'integrated');\n }\n },\n skip: () => {\n const item = c.effectivePlayingItem;\n const event = item == null ? void 0 : item.event;\n if (event && !event.restrictions.skip) {\n const index = c.findItemIndex(item);\n if (event.appendInPlace) {\n const time = item.playout.start + item.event.duration;\n seekTo(time + 0.001, 'playout');\n } else {\n c.advanceAfterAssetEnded(event, index, Infinity);\n }\n }\n }\n };\n }\n return this.manager;\n }\n\n // Schedule getters\n get effectivePlayingItem() {\n return this.waitingItem || this.playingItem || this.endedItem;\n }\n get effectivePlayingAsset() {\n return this.playingAsset || this.endedAsset;\n }\n get playingLastItem() {\n var _this$schedule;\n const playingItem = this.playingItem;\n const items = (_this$schedule = this.schedule) == null ? void 0 : _this$schedule.items;\n if (!this.playbackStarted || !playingItem || !items) {\n return false;\n }\n return this.findItemIndex(playingItem) === items.length - 1;\n }\n get playbackStarted() {\n return this.effectivePlayingItem !== null;\n }\n\n // Media getters and event callbacks\n get currentTime() {\n var _this$bufferingItem, _this$bufferingItem$e, _media;\n if (this.mediaSelection === null) {\n // Do not advance before schedule is known\n return undefined;\n }\n // Ignore currentTime when detached for Interstitial playback with source reset\n const queuedForPlayback = this.waitingItem || this.playingItem;\n if (this.isInterstitial(queuedForPlayback) && !queuedForPlayback.event.appendInPlace) {\n return undefined;\n }\n let media = this.media;\n if (!media && (_this$bufferingItem = this.bufferingItem) != null && (_this$bufferingItem$e = _this$bufferingItem.event) != null && _this$bufferingItem$e.appendInPlace) {\n // Observe detached media currentTime when appending in place\n media = this.primaryMedia;\n }\n const currentTime = (_media = media) == null ? void 0 : _media.currentTime;\n if (currentTime === undefined || !isFiniteNumber(currentTime)) {\n return undefined;\n }\n return currentTime;\n }\n get primaryMedia() {\n var _this$detachedData;\n return this.media || ((_this$detachedData = this.detachedData) == null ? void 0 : _this$detachedData.media) || null;\n }\n isInterstitial(item) {\n return !!(item != null && item.event);\n }\n retreiveMediaSource(assetId, toSegment) {\n const player = this.getAssetPlayer(assetId);\n if (player) {\n this.transferMediaFromPlayer(player, toSegment);\n }\n }\n transferMediaFromPlayer(player, toSegment) {\n const appendInPlace = player.interstitial.appendInPlace;\n const playerMedia = player.media;\n if (appendInPlace && playerMedia === this.primaryMedia) {\n this.bufferingAsset = null;\n if (!toSegment || this.isInterstitial(toSegment) && !toSegment.event.appendInPlace) {\n // MediaSource cannot be transfered back to an Interstitial that requires a source reset\n // no-op when toSegment is undefined\n if (toSegment && playerMedia) {\n this.detachedData = {\n media: playerMedia\n };\n return;\n }\n }\n const attachMediaSourceData = player.transferMedia();\n this.log(`transfer MediaSource from ${player} ${stringify(attachMediaSourceData)}`);\n this.detachedData = attachMediaSourceData;\n } else if (toSegment && playerMedia) {\n this.shouldPlay || (this.shouldPlay = !playerMedia.paused);\n }\n }\n transferMediaTo(player, media) {\n var _this$detachedData2, _attachMediaSourceDat;\n if (player.media === media) {\n return;\n }\n let attachMediaSourceData = null;\n const primaryPlayer = this.hls;\n const isAssetPlayer = player !== primaryPlayer;\n const appendInPlace = isAssetPlayer && player.interstitial.appendInPlace;\n const detachedMediaSource = (_this$detachedData2 = this.detachedData) == null ? void 0 : _this$detachedData2.mediaSource;\n let logFromSource;\n if (primaryPlayer.media) {\n if (appendInPlace) {\n attachMediaSourceData = primaryPlayer.transferMedia();\n this.detachedData = attachMediaSourceData;\n }\n logFromSource = `Primary`;\n } else if (detachedMediaSource) {\n const bufferingPlayer = this.getBufferingPlayer();\n if (bufferingPlayer) {\n attachMediaSourceData = bufferingPlayer.transferMedia();\n logFromSource = `${bufferingPlayer}`;\n } else {\n logFromSource = `detached MediaSource`;\n }\n } else {\n logFromSource = `detached media`;\n }\n if (!attachMediaSourceData) {\n if (detachedMediaSource) {\n attachMediaSourceData = this.detachedData;\n this.log(`using detachedData: MediaSource ${stringify(attachMediaSourceData)}`);\n } else if (!this.detachedData || primaryPlayer.media === media) {\n // Keep interstitial media transition consistent\n const playerQueue = this.playerQueue;\n if (playerQueue.length > 1) {\n playerQueue.forEach(queuedPlayer => {\n if (isAssetPlayer && queuedPlayer.interstitial.appendInPlace !== appendInPlace) {\n const interstitial = queuedPlayer.interstitial;\n this.clearInterstitial(queuedPlayer.interstitial, null);\n interstitial.appendInPlace = false;\n if (interstitial.appendInPlace) {\n this.warn(`Could not change append strategy for queued assets ${interstitial}`);\n }\n }\n });\n }\n this.hls.detachMedia();\n this.detachedData = {\n media\n };\n }\n }\n const transferring = attachMediaSourceData && 'mediaSource' in attachMediaSourceData && ((_attachMediaSourceDat = attachMediaSourceData.mediaSource) == null ? void 0 : _attachMediaSourceDat.readyState) !== 'closed';\n const dataToAttach = transferring && attachMediaSourceData ? attachMediaSourceData : media;\n this.log(`${transferring ? 'transfering MediaSource' : 'attaching media'} to ${isAssetPlayer ? player : 'Primary'} from ${logFromSource}`);\n if (dataToAttach === attachMediaSourceData) {\n const isAssetAtEndOfSchedule = isAssetPlayer && player.assetId === this.schedule.assetIdAtEnd;\n // Prevent asset players from marking EoS on transferred MediaSource\n dataToAttach.overrides = {\n duration: this.schedule.duration,\n endOfStream: !isAssetPlayer || isAssetAtEndOfSchedule,\n cueRemoval: !isAssetPlayer\n };\n }\n player.attachMedia(dataToAttach);\n }\n onInterstitialCueEnter() {\n this.onTimeupdate();\n }\n // Scheduling methods\n checkStart() {\n const schedule = this.schedule;\n const interstitialEvents = schedule.events;\n if (!interstitialEvents || this.playbackDisabled || !this.media) {\n return;\n }\n // Check buffered to pre-roll\n if (this.bufferedPos === -1) {\n this.bufferedPos = 0;\n }\n // Start stepping through schedule when playback begins for the first time and we have a pre-roll\n const timelinePos = this.timelinePos;\n const effectivePlayingItem = this.effectivePlayingItem;\n if (timelinePos === -1) {\n const startPosition = this.hls.startPosition;\n this.timelinePos = startPosition;\n if (interstitialEvents.length && interstitialEvents[0].cue.pre) {\n const index = schedule.findEventIndex(interstitialEvents[0].identifier);\n this.setSchedulePosition(index);\n } else if (startPosition >= 0 || !this.primaryLive) {\n const start = this.timelinePos = startPosition > 0 ? startPosition : 0;\n const index = schedule.findItemIndexAtTime(start);\n this.setSchedulePosition(index);\n }\n } else if (effectivePlayingItem && !this.playingItem) {\n const index = schedule.findItemIndex(effectivePlayingItem);\n this.setSchedulePosition(index);\n }\n }\n advanceAfterAssetEnded(interstitial, index, assetListIndex) {\n const nextAssetIndex = assetListIndex + 1;\n if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex) && !interstitial.assetList[nextAssetIndex].error) {\n // Advance to next asset list item\n this.setSchedulePosition(index, nextAssetIndex);\n } else {\n // Advance to next schedule segment\n // check if we've reached the end of the program\n const scheduleItems = this.schedule.items;\n if (scheduleItems) {\n const nextIndex = index + 1;\n const scheduleLength = scheduleItems.length;\n if (nextIndex >= scheduleLength) {\n this.setSchedulePosition(-1);\n return;\n }\n const resumptionTime = interstitial.resumeTime;\n if (this.timelinePos < resumptionTime) {\n this.timelinePos = resumptionTime;\n this.checkBuffer();\n }\n this.setSchedulePosition(nextIndex);\n }\n }\n }\n setScheduleToAssetAtTime(time, playingAsset) {\n const schedule = this.schedule;\n const parentIdentifier = playingAsset.parentIdentifier;\n const interstitial = schedule.getEvent(parentIdentifier);\n if (interstitial) {\n const itemIndex = schedule.findEventIndex(parentIdentifier);\n const assetListIndex = schedule.findAssetIndex(interstitial, time);\n this.setSchedulePosition(itemIndex, assetListIndex);\n }\n }\n setSchedulePosition(index, assetListIndex) {\n const scheduleItems = this.schedule.items;\n if (!scheduleItems || this.playbackDisabled) {\n return;\n }\n this.log(`setSchedulePosition ${index}, ${assetListIndex}`);\n const scheduledItem = index >= 0 ? scheduleItems[index] : null;\n // Cleanup current item / asset\n const currentItem = this.playingItem;\n const playingLastItem = this.playingLastItem;\n if (this.isInterstitial(currentItem)) {\n var _interstitial$assetLi;\n const interstitial = currentItem.event;\n const playingAsset = this.playingAsset;\n const assetId = playingAsset == null ? void 0 : playingAsset.identifier;\n const player = assetId ? this.getAssetPlayer(assetId) : null;\n if (player && assetId && (!this.eventItemsMatch(currentItem, scheduledItem) || assetListIndex !== undefined && assetId !== ((_interstitial$assetLi = interstitial.assetList) == null ? void 0 : _interstitial$assetLi[assetListIndex].identifier))) {\n var _this$detachedData3;\n const _assetListIndex = interstitial.findAssetIndex(playingAsset);\n this.log(`INTERSTITIAL_ASSET_ENDED ${_assetListIndex + 1}/${interstitial.assetList.length} ${eventAssetToString(playingAsset)}`);\n this.endedAsset = playingAsset;\n this.playingAsset = null;\n this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED, {\n asset: playingAsset,\n assetListIndex: _assetListIndex,\n event: interstitial,\n schedule: scheduleItems.slice(0),\n scheduleIndex: index,\n player\n });\n this.retreiveMediaSource(assetId, scheduledItem);\n if (player.media && !((_this$detachedData3 = this.detachedData) != null && _this$detachedData3.mediaSource)) {\n player.detachMedia();\n }\n }\n if (!this.eventItemsMatch(currentItem, scheduledItem)) {\n this.endedItem = currentItem;\n this.playingItem = null;\n this.log(`INTERSTITIAL_ENDED ${interstitial} ${segmentToString(currentItem)}`);\n interstitial.hasPlayed = true;\n this.hls.trigger(Events.INTERSTITIAL_ENDED, {\n event: interstitial,\n schedule: scheduleItems.slice(0),\n scheduleIndex: index\n });\n // Exiting an Interstitial\n if (interstitial.cue.once) {\n // Remove interstitial with CUE attribute value of ONCE after it has played\n this.updateSchedule();\n const items = this.schedule.items;\n if (scheduledItem && items) {\n const updatedIndex = this.schedule.findItemIndex(scheduledItem);\n this.advanceSchedule(updatedIndex, items, assetListIndex, currentItem, playingLastItem);\n }\n return;\n }\n }\n }\n this.advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playingLastItem);\n }\n advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playedLastItem) {\n const scheduledItem = index >= 0 ? scheduleItems[index] : null;\n const media = this.primaryMedia;\n // Cleanup out of range Interstitials\n const playerQueue = this.playerQueue;\n if (playerQueue.length) {\n playerQueue.forEach(player => {\n const interstitial = player.interstitial;\n const queuedIndex = this.schedule.findEventIndex(interstitial.identifier);\n if (queuedIndex < index || queuedIndex > index + 1) {\n this.clearInterstitial(interstitial, scheduledItem);\n }\n });\n }\n // Setup scheduled item\n if (this.isInterstitial(scheduledItem)) {\n this.timelinePos = Math.min(Math.max(this.timelinePos, scheduledItem.start), scheduledItem.end);\n // Handle Interstitial\n const interstitial = scheduledItem.event;\n // find asset index\n if (assetListIndex === undefined) {\n assetListIndex = this.schedule.findAssetIndex(interstitial, this.timelinePos);\n }\n // Ensure Interstitial is enqueued\n const waitingItem = this.waitingItem;\n if (!this.assetsBuffered(scheduledItem, media)) {\n this.setBufferingItem(scheduledItem);\n }\n let player = this.preloadAssets(interstitial, assetListIndex);\n if (!this.eventItemsMatch(scheduledItem, waitingItem || currentItem)) {\n this.waitingItem = scheduledItem;\n this.log(`INTERSTITIAL_STARTED ${segmentToString(scheduledItem)} ${interstitial.appendInPlace ? 'append in place' : ''}`);\n this.hls.trigger(Events.INTERSTITIAL_STARTED, {\n event: interstitial,\n schedule: scheduleItems.slice(0),\n scheduleIndex: index\n });\n }\n if (!interstitial.assetListLoaded) {\n // Waiting at end of primary content segment\n // Expect setSchedulePosition to be called again once ASSET-LIST is loaded\n this.log(`Waiting for ASSET-LIST to complete loading ${interstitial}`);\n return;\n }\n if (interstitial.assetListLoader) {\n interstitial.assetListLoader.destroy();\n interstitial.assetListLoader = undefined;\n }\n if (!media) {\n this.log(`Waiting for attachMedia to start Interstitial ${interstitial}`);\n return;\n }\n // Update schedule and asset list position now that it can start\n this.waitingItem = this.endedItem = null;\n this.playingItem = scheduledItem;\n\n // If asset-list is empty or missing asset index, advance to next item\n const assetItem = interstitial.assetList[assetListIndex];\n if (!assetItem) {\n const nextItem = scheduleItems[index + 1];\n const _media2 = this.media;\n if (nextItem && _media2 && !this.isInterstitial(nextItem) && _media2.currentTime < nextItem.start) {\n _media2.currentTime = this.timelinePos = nextItem.start;\n }\n this.advanceAfterAssetEnded(interstitial, index, assetListIndex || 0);\n return;\n }\n\n // Start Interstitial Playback\n if (!player) {\n player = this.getAssetPlayer(assetItem.identifier);\n }\n if (player === null || player.destroyed) {\n const assetListLength = interstitial.assetList.length;\n this.warn(`asset ${assetListIndex + 1}/${assetListLength} player destroyed ${interstitial}`);\n player = this.createAssetPlayer(interstitial, assetItem, assetListIndex);\n }\n if (!this.eventItemsMatch(scheduledItem, this.bufferingItem)) {\n if (interstitial.appendInPlace && this.isAssetBuffered(assetItem)) {\n return;\n }\n }\n this.startAssetPlayer(player, assetListIndex, scheduleItems, index, media);\n if (this.shouldPlay) {\n playWithCatch(player.media);\n }\n } else if (scheduledItem !== null) {\n this.resumePrimary(scheduledItem, index, currentItem);\n if (this.shouldPlay) {\n playWithCatch(this.hls.media);\n }\n } else if (playedLastItem && this.isInterstitial(currentItem)) {\n // Maintain playingItem state at end of schedule (setSchedulePosition(-1) called to end program)\n // this allows onSeeking handler to update schedule position\n this.endedItem = null;\n this.playingItem = currentItem;\n if (!currentItem.event.appendInPlace) {\n // Media must be re-attached to resume primary schedule if not sharing source\n this.attachPrimary(this.schedule.durations.primary, null);\n }\n }\n }\n get playbackDisabled() {\n return this.hls.config.enableInterstitialPlayback === false;\n }\n get primaryDetails() {\n var _this$mediaSelection, _this$mediaSelection$;\n return (_this$mediaSelection = this.mediaSelection) == null ? void 0 : (_this$mediaSelection$ = _this$mediaSelection.main) == null ? void 0 : _this$mediaSelection$.details;\n }\n get primaryLive() {\n var _this$primaryDetails;\n return !!((_this$primaryDetails = this.primaryDetails) != null && _this$primaryDetails.live);\n }\n resumePrimary(scheduledItem, index, fromItem) {\n var _this$detachedData4;\n this.playingItem = scheduledItem;\n this.playingAsset = this.endedAsset = null;\n this.waitingItem = this.endedItem = null;\n this.bufferedToItem(scheduledItem);\n this.log(`resuming ${segmentToString(scheduledItem)}`);\n if (!((_this$detachedData4 = this.detachedData) != null && _this$detachedData4.mediaSource)) {\n let timelinePos = this.timelinePos;\n if (timelinePos < scheduledItem.start || timelinePos >= scheduledItem.end) {\n timelinePos = this.getPrimaryResumption(scheduledItem, index);\n this.timelinePos = timelinePos;\n }\n this.attachPrimary(timelinePos, scheduledItem);\n }\n if (!fromItem) {\n return;\n }\n const scheduleItems = this.schedule.items;\n if (!scheduleItems) {\n return;\n }\n this.log(`resumed ${segmentToString(scheduledItem)}`);\n this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED, {\n schedule: scheduleItems.slice(0),\n scheduleIndex: index\n });\n this.checkBuffer();\n }\n getPrimaryResumption(scheduledItem, index) {\n const itemStart = scheduledItem.start;\n if (this.primaryLive) {\n const details = this.primaryDetails;\n if (index === 0) {\n return this.hls.startPosition;\n } else if (details && (itemStart < details.fragmentStart || itemStart > details.edge)) {\n return this.hls.liveSyncPosition || -1;\n }\n }\n return itemStart;\n }\n isAssetBuffered(asset) {\n const player = this.getAssetPlayer(asset.identifier);\n if (player != null && player.hls) {\n return player.hls.bufferedToEnd;\n }\n const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);\n return bufferInfo.end + 1 >= asset.timelineStart + (asset.duration || 0);\n }\n attachPrimary(timelinePos, item, skipSeekToStartPosition) {\n if (item) {\n this.setBufferingItem(item);\n } else {\n this.bufferingItem = this.playingItem;\n }\n this.bufferingAsset = null;\n const media = this.primaryMedia;\n if (!media) {\n return;\n }\n const hls = this.hls;\n if (hls.media) {\n this.checkBuffer();\n } else {\n this.transferMediaTo(hls, media);\n if (skipSeekToStartPosition) {\n this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);\n }\n }\n if (!skipSeekToStartPosition) {\n // Set primary position to resume time\n this.timelinePos = timelinePos;\n this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);\n }\n }\n startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition) {\n var _hls$mainForwardBuffe;\n const hls = this.hls;\n if (!hls.loadingEnabled || !hls.media || Math.abs((((_hls$mainForwardBuffe = hls.mainForwardBufferInfo) == null ? void 0 : _hls$mainForwardBuffe.start) || hls.media.currentTime) - timelinePos) > 0.5) {\n hls.startLoad(timelinePos, skipSeekToStartPosition);\n } else if (!hls.bufferingEnabled) {\n hls.resumeBuffering();\n }\n }\n\n // HLS.js event callbacks\n onManifestLoading() {\n this.stopLoad();\n this.schedule.reset();\n this.emptyPlayerQueue();\n this.clearScheduleState();\n this.shouldPlay = false;\n this.bufferedPos = this.timelinePos = -1;\n this.mediaSelection = this.altSelection = this.manager = this.requiredTracks = null;\n // BUFFER_CODECS listener added here for buffer-controller to handle it first where it adds tracks\n this.hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n this.hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n }\n onLevelUpdated(event, data) {\n if (data.level === -1) {\n // level was removed\n return;\n }\n const main = this.hls.levels[data.level];\n const currentSelection = _objectSpread2(_objectSpread2({}, this.mediaSelection || this.altSelection), {}, {\n main\n });\n this.mediaSelection = currentSelection;\n this.schedule.parseInterstitialDateRanges(currentSelection, this.hls.config.interstitialAppendInPlace);\n if (!this.effectivePlayingItem && this.schedule.items) {\n this.checkStart();\n }\n }\n onAudioTrackUpdated(event, data) {\n const audio = this.hls.audioTracks[data.id];\n const previousSelection = this.mediaSelection;\n if (!previousSelection) {\n this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {\n audio\n });\n return;\n }\n const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {\n audio\n });\n this.mediaSelection = currentSelection;\n }\n onSubtitleTrackUpdated(event, data) {\n const subtitles = this.hls.subtitleTracks[data.id];\n const previousSelection = this.mediaSelection;\n if (!previousSelection) {\n this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {\n subtitles\n });\n return;\n }\n const currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {\n subtitles\n });\n this.mediaSelection = currentSelection;\n }\n onAudioTrackSwitching(event, data) {\n const audioOption = getBasicSelectionOption(data);\n this.playerQueue.forEach(player => player.hls.setAudioOption(data) || player.hls.setAudioOption(audioOption));\n }\n onSubtitleTrackSwitch(event, data) {\n const subtitleOption = getBasicSelectionOption(data);\n this.playerQueue.forEach(player => player.hls.setSubtitleOption(data) || data.id !== -1 && player.hls.setSubtitleOption(subtitleOption));\n }\n onBufferCodecs(event, data) {\n const requiredTracks = data.tracks;\n if (requiredTracks) {\n this.requiredTracks = requiredTracks;\n }\n }\n onBufferAppended(event, data) {\n this.checkBuffer();\n }\n onBufferFlushed(event, data) {\n const playingItem = this.playingItem;\n if (playingItem && !this.itemsMatch(playingItem, this.bufferingItem) && !this.isInterstitial(playingItem)) {\n const timelinePos = this.timelinePos;\n this.bufferedPos = timelinePos;\n this.checkBuffer();\n }\n }\n onBufferedToEnd(event) {\n // Buffered to post-roll\n const interstitialEvents = this.schedule.events;\n if (this.bufferedPos < Number.MAX_VALUE && interstitialEvents) {\n for (let i = 0; i < interstitialEvents.length; i++) {\n const interstitial = interstitialEvents[i];\n if (interstitial.cue.post) {\n var _this$schedule$items;\n const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);\n const item = (_this$schedule$items = this.schedule.items) == null ? void 0 : _this$schedule$items[scheduleIndex];\n if (this.isInterstitial(item) && this.eventItemsMatch(item, this.bufferingItem)) {\n this.bufferedToItem(item, 0);\n }\n break;\n }\n }\n this.bufferedPos = Number.MAX_VALUE;\n }\n }\n onMediaEnded(event) {\n const playingItem = this.playingItem;\n if (!this.playingLastItem && playingItem) {\n const playingIndex = this.findItemIndex(playingItem);\n this.setSchedulePosition(playingIndex + 1);\n } else {\n this.shouldPlay = false;\n }\n }\n updateItem(previousItem, time) {\n // find item in this.schedule.items;\n const items = this.schedule.items;\n if (previousItem && items) {\n const index = this.findItemIndex(previousItem, time);\n return items[index] || null;\n }\n return null;\n }\n itemsMatch(a, b) {\n return !!b && (a === b || a.event && b.event && this.eventItemsMatch(a, b) || !a.event && !b.event && this.findItemIndex(a) === this.findItemIndex(b));\n }\n eventItemsMatch(a, b) {\n var _b$event;\n return !!b && (a === b || a.event.identifier === ((_b$event = b.event) == null ? void 0 : _b$event.identifier));\n }\n findItemIndex(item, time) {\n return item ? this.schedule.findItemIndex(item, time) : -1;\n }\n updateSchedule() {\n const mediaSelection = this.mediaSelection;\n if (!mediaSelection) {\n return;\n }\n this.schedule.updateSchedule(mediaSelection, []);\n }\n\n // Schedule buffer control\n checkBuffer(starved) {\n const items = this.schedule.items;\n if (!items) {\n return;\n }\n // Find when combined forward buffer change reaches next schedule segment\n const bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);\n if (starved) {\n this.bufferedPos = this.timelinePos;\n }\n starved || (starved = bufferInfo.len < 1);\n this.updateBufferedPos(bufferInfo.end, items, starved);\n }\n updateBufferedPos(bufferEnd, items, bufferIsEmpty) {\n const schedule = this.schedule;\n const bufferingItem = this.bufferingItem;\n if (this.bufferedPos > bufferEnd) {\n return;\n }\n if (items.length === 1 && this.itemsMatch(items[0], bufferingItem)) {\n this.bufferedPos = bufferEnd;\n return;\n }\n const playingItem = this.playingItem;\n const playingIndex = this.findItemIndex(playingItem);\n let bufferEndIndex = schedule.findItemIndexAtTime(bufferEnd);\n if (this.bufferedPos < bufferEnd) {\n var _nextItemToBuffer$eve, _bufferingItem$event;\n const bufferingIndex = this.findItemIndex(bufferingItem);\n const nextToBufferIndex = Math.min(bufferingIndex + 1, items.length - 1);\n const nextItemToBuffer = items[nextToBufferIndex];\n if (bufferEndIndex === -1 && bufferingItem && bufferEnd >= bufferingItem.end || (_nextItemToBuffer$eve = nextItemToBuffer.event) != null && _nextItemToBuffer$eve.appendInPlace && bufferEnd + 0.01 >= nextItemToBuffer.start) {\n bufferEndIndex = nextToBufferIndex;\n }\n if (nextToBufferIndex - playingIndex > 1 && (bufferingItem == null ? void 0 : (_bufferingItem$event = bufferingItem.event) == null ? void 0 : _bufferingItem$event.appendInPlace) === false) {\n // do not advance buffering item past Interstitial that requires source reset\n return;\n }\n this.bufferedPos = bufferEnd;\n if (bufferEndIndex > bufferingIndex && bufferEndIndex > playingIndex) {\n this.bufferedToItem(nextItemToBuffer);\n } else {\n // allow more time than distance from edge for assets to load\n const details = this.primaryDetails;\n if (this.primaryLive && details && bufferEnd > details.edge - details.targetduration && nextItemToBuffer.start < details.edge + this.hls.config.interstitialLiveLookAhead && this.isInterstitial(nextItemToBuffer)) {\n this.preloadAssets(nextItemToBuffer.event, 0);\n }\n }\n } else if (bufferIsEmpty && playingItem && !this.itemsMatch(playingItem, bufferingItem)) {\n if (bufferEndIndex === playingIndex) {\n this.bufferedToItem(playingItem);\n } else if (bufferEndIndex === playingIndex + 1) {\n this.bufferedToItem(items[bufferEndIndex]);\n }\n }\n }\n assetsBuffered(item, media) {\n const assetList = item.event.assetList;\n if (assetList.length === 0) {\n return false;\n }\n return !item.event.assetList.some(asset => {\n const player = this.getAssetPlayer(asset.identifier);\n return !(player != null && player.bufferedInPlaceToEnd(media));\n });\n }\n setBufferingItem(item) {\n const bufferingLast = this.bufferingItem;\n const schedule = this.schedule;\n if (!this.itemsMatch(item, bufferingLast)) {\n const {\n items,\n events\n } = schedule;\n if (!items || !events) {\n return bufferingLast;\n }\n const isInterstitial = this.isInterstitial(item);\n const bufferingPlayer = this.getBufferingPlayer();\n this.bufferingItem = item;\n this.bufferedPos = Math.max(item.start, Math.min(item.end, this.timelinePos));\n if (!this.playbackDisabled) {\n const timeRemaining = bufferingPlayer ? bufferingPlayer.remaining : bufferingLast ? bufferingLast.end - this.timelinePos : 0;\n this.log(`buffered to boundary ${segmentToString(item)}` + (bufferingLast ? ` (${timeRemaining.toFixed(2)} remaining)` : ''));\n if (isInterstitial) {\n // primary fragment loading will exit early in base-stream-controller while `bufferingItem` is set to an Interstitial block\n item.event.assetList.forEach(asset => {\n const player = this.getAssetPlayer(asset.identifier);\n if (player) {\n player.resumeBuffering();\n }\n });\n } else {\n this.hls.resumeBuffering();\n this.playerQueue.forEach(player => player.pauseBuffering());\n }\n }\n this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY, {\n events: events.slice(0),\n schedule: items.slice(0),\n bufferingIndex: this.findItemIndex(item),\n playingIndex: this.findItemIndex(this.playingItem)\n });\n } else if (this.bufferingItem !== item) {\n this.bufferingItem = item;\n }\n return bufferingLast;\n }\n bufferedToItem(item, assetListIndex = 0) {\n const bufferingLast = this.setBufferingItem(item);\n if (this.playbackDisabled) {\n return;\n }\n if (this.isInterstitial(item)) {\n // Ensure asset list is loaded\n this.bufferedToEvent(item, assetListIndex);\n } else if (bufferingLast !== null) {\n // If primary player is detached, it is also stopped, restart loading at primary position\n this.bufferingAsset = null;\n const detachedData = this.detachedData;\n if (detachedData) {\n if (detachedData.mediaSource) {\n const skipSeekToStartPosition = true;\n this.attachPrimary(item.start, item, skipSeekToStartPosition);\n } else {\n this.preloadPrimary(item);\n }\n } else {\n // If not detached seek to resumption point\n this.preloadPrimary(item);\n }\n }\n }\n preloadPrimary(item) {\n const index = this.findItemIndex(item);\n const timelinePos = this.getPrimaryResumption(item, index);\n this.startLoadingPrimaryAt(timelinePos);\n }\n bufferedToEvent(item, assetListIndex) {\n const interstitial = item.event;\n const neverLoaded = interstitial.assetList.length === 0 && !interstitial.assetListLoader;\n const playOnce = interstitial.cue.once;\n if (neverLoaded || !playOnce) {\n // Buffered to Interstitial boundary\n const player = this.preloadAssets(interstitial, assetListIndex);\n if (player != null && player.interstitial.appendInPlace) {\n // If we have a player and asset list info, start buffering\n const assetItem = interstitial.assetList[assetListIndex];\n const media = this.primaryMedia;\n if (assetItem && media) {\n this.bufferAssetPlayer(player, media);\n }\n }\n }\n }\n preloadAssets(interstitial, assetListIndex) {\n const uri = interstitial.assetUrl;\n const assetListLength = interstitial.assetList.length;\n const neverLoaded = assetListLength === 0 && !interstitial.assetListLoader;\n const playOnce = interstitial.cue.once;\n if (neverLoaded) {\n const timelineStart = interstitial.timelineStart;\n if (interstitial.appendInPlace) {\n var _playingItem$nextEven;\n const playingItem = this.playingItem;\n if (!this.isInterstitial(playingItem) && (playingItem == null ? void 0 : (_playingItem$nextEven = playingItem.nextEvent) == null ? void 0 : _playingItem$nextEven.identifier) === interstitial.identifier) {\n this.flushFrontBuffer(timelineStart + 0.25);\n }\n }\n let hlsStartOffset;\n let liveStartPosition = 0;\n if (!this.playingItem && this.primaryLive) {\n liveStartPosition = this.hls.startPosition;\n if (liveStartPosition === -1) {\n liveStartPosition = this.hls.liveSyncPosition || 0;\n }\n }\n if (liveStartPosition && !(interstitial.cue.pre || interstitial.cue.post)) {\n const startOffset = liveStartPosition - timelineStart;\n if (startOffset > 0) {\n hlsStartOffset = Math.round(startOffset * 1000) / 1000;\n }\n }\n this.log(`Load interstitial asset ${assetListIndex + 1}/${uri ? 1 : assetListLength} ${interstitial}${hlsStartOffset ? ` live-start: ${liveStartPosition} start-offset: ${hlsStartOffset}` : ''}`);\n if (uri) {\n return this.createAsset(interstitial, 0, 0, timelineStart, interstitial.duration, uri);\n }\n const assetListLoader = this.assetListLoader.loadAssetList(interstitial, hlsStartOffset);\n if (assetListLoader) {\n interstitial.assetListLoader = assetListLoader;\n }\n } else if (!playOnce && assetListLength) {\n // Re-buffered to Interstitial boundary, re-create asset player(s)\n for (let i = assetListIndex; i < assetListLength; i++) {\n const asset = interstitial.assetList[i];\n const playerIndex = this.getAssetPlayerQueueIndex(asset.identifier);\n if ((playerIndex === -1 || this.playerQueue[playerIndex].destroyed) && !asset.error) {\n this.createAssetPlayer(interstitial, asset, i);\n }\n }\n return this.getAssetPlayer(interstitial.assetList[assetListIndex].identifier);\n }\n return null;\n }\n flushFrontBuffer(startOffset) {\n // Force queued flushing of all buffers\n const requiredTracks = this.requiredTracks;\n if (!requiredTracks) {\n return;\n }\n this.log(`Removing front buffer starting at ${startOffset}`);\n const sourceBufferNames = Object.keys(requiredTracks);\n sourceBufferNames.forEach(type => {\n this.hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset,\n endOffset: Infinity,\n type\n });\n });\n }\n\n // Interstitial Asset Player control\n getAssetPlayerQueueIndex(assetId) {\n const playerQueue = this.playerQueue;\n for (let i = 0; i < playerQueue.length; i++) {\n if (assetId === playerQueue[i].assetId) {\n return i;\n }\n }\n return -1;\n }\n getAssetPlayer(assetId) {\n const index = this.getAssetPlayerQueueIndex(assetId);\n return this.playerQueue[index] || null;\n }\n getBufferingPlayer() {\n const {\n playerQueue,\n primaryMedia\n } = this;\n if (primaryMedia) {\n for (let i = 0; i < playerQueue.length; i++) {\n if (playerQueue[i].media === primaryMedia) {\n return playerQueue[i];\n }\n }\n }\n return null;\n }\n createAsset(interstitial, assetListIndex, startOffset, timelineStart, duration, uri) {\n const assetItem = {\n parentIdentifier: interstitial.identifier,\n identifier: generateAssetIdentifier(interstitial, uri, assetListIndex),\n duration,\n startOffset,\n timelineStart,\n uri\n };\n return this.createAssetPlayer(interstitial, assetItem, assetListIndex);\n }\n createAssetPlayer(interstitial, assetItem, assetListIndex) {\n this.log(`create HLSAssetPlayer for ${eventAssetToString(assetItem)}`);\n const primary = this.hls;\n const userConfig = primary.userConfig;\n let videoPreference = userConfig.videoPreference;\n const currentLevel = primary.loadLevelObj || primary.levels[primary.currentLevel];\n if (videoPreference || currentLevel) {\n videoPreference = _extends({}, videoPreference);\n if (currentLevel.videoCodec) {\n videoPreference.videoCodec = currentLevel.videoCodec;\n }\n if (currentLevel.videoRange) {\n videoPreference.allowedVideoRanges = [currentLevel.videoRange];\n }\n }\n const selectedAudio = primary.audioTracks[primary.audioTrack];\n const selectedSubtitle = primary.subtitleTracks[primary.subtitleTrack];\n let startPosition = 0;\n if (this.primaryLive || interstitial.appendInPlace) {\n const timePastStart = this.timelinePos - assetItem.timelineStart;\n if (timePastStart > 1) {\n const duration = assetItem.duration;\n if (duration && timePastStart < duration) {\n startPosition = timePastStart;\n }\n }\n }\n const assetId = assetItem.identifier;\n const playerConfig = _objectSpread2(_objectSpread2({}, userConfig), {}, {\n autoStartLoad: true,\n startFragPrefetch: true,\n primarySessionId: primary.sessionId,\n assetPlayerId: assetId,\n abrEwmaDefaultEstimate: primary.bandwidthEstimate,\n interstitialsController: undefined,\n startPosition,\n liveDurationInfinity: false,\n testBandwidth: false,\n videoPreference,\n audioPreference: selectedAudio || userConfig.audioPreference,\n subtitlePreference: selectedSubtitle || userConfig.subtitlePreference\n });\n if (interstitial.appendInPlace) {\n interstitial.appendInPlaceStarted = true;\n if (assetItem.timelineStart) {\n playerConfig.timelineOffset = assetItem.timelineStart;\n }\n }\n const cmcd = playerConfig.cmcd;\n if (cmcd != null && cmcd.sessionId && cmcd.contentId) {\n playerConfig.cmcd = _extends({}, cmcd, {\n contentId: hash(assetItem.uri)\n });\n }\n if (this.getAssetPlayer(assetId)) {\n this.warn(`Duplicate date range identifier ${interstitial} and asset ${assetId}`);\n }\n const player = new HlsAssetPlayer(this.HlsPlayerClass, playerConfig, interstitial, assetItem);\n this.playerQueue.push(player);\n interstitial.assetList[assetListIndex] = assetItem;\n // Listen for LevelDetails and PTS change to update duration\n const updateAssetPlayerDetails = details => {\n if (details.live) {\n const error = new Error(`Interstitials MUST be VOD assets ${interstitial}`);\n const errorData = {\n fatal: true,\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,\n error\n };\n this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);\n return;\n }\n // Get time at end of last fragment\n const duration = details.edge - details.fragmentStart;\n const currentAssetDuration = assetItem.duration;\n if (currentAssetDuration === null || duration > currentAssetDuration) {\n this.log(`Interstitial asset \"${assetId}\" duration change ${currentAssetDuration} > ${duration}`);\n assetItem.duration = duration;\n // Update schedule with new event and asset duration\n this.updateSchedule();\n }\n };\n player.on(Events.LEVEL_UPDATED, (event, {\n details\n }) => updateAssetPlayerDetails(details));\n player.on(Events.LEVEL_PTS_UPDATED, (event, {\n details\n }) => updateAssetPlayerDetails(details));\n const onBufferCodecs = (event, data) => {\n const inQueuPlayer = this.getAssetPlayer(assetId);\n if (inQueuPlayer && data.tracks) {\n inQueuPlayer.off(Events.BUFFER_CODECS, onBufferCodecs);\n inQueuPlayer.tracks = data.tracks;\n const media = this.primaryMedia;\n if (this.bufferingAsset === inQueuPlayer.assetItem && media && !inQueuPlayer.media) {\n this.bufferAssetPlayer(inQueuPlayer, media);\n }\n }\n };\n player.on(Events.BUFFER_CODECS, onBufferCodecs);\n const bufferedToEnd = () => {\n var _this$schedule$items2;\n const inQueuPlayer = this.getAssetPlayer(assetId);\n this.log(`buffered to end of asset ${inQueuPlayer}`);\n if (!inQueuPlayer) {\n return;\n }\n // Preload at end of asset\n const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);\n const assetListIndex = interstitial.findAssetIndex(assetItem);\n const nextAssetIndex = assetListIndex + 1;\n const item = (_this$schedule$items2 = this.schedule.items) == null ? void 0 : _this$schedule$items2[scheduleIndex];\n if (this.isInterstitial(item)) {\n if (assetListIndex !== -1 && !interstitial.isAssetPastPlayoutLimit(nextAssetIndex) && !interstitial.assetList[nextAssetIndex].error) {\n this.bufferedToItem(item, nextAssetIndex);\n } else {\n var _this$schedule$items3;\n const nextItem = (_this$schedule$items3 = this.schedule.items) == null ? void 0 : _this$schedule$items3[scheduleIndex + 1];\n if (nextItem) {\n this.bufferedToItem(nextItem);\n }\n }\n }\n };\n player.on(Events.BUFFERED_TO_END, bufferedToEnd);\n const endedWithAssetIndex = assetIndex => {\n return () => {\n const inQueuPlayer = this.getAssetPlayer(assetId);\n if (!inQueuPlayer) {\n return;\n }\n this.shouldPlay = true;\n const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);\n this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetIndex);\n };\n };\n player.once(Events.MEDIA_ENDED, endedWithAssetIndex(assetListIndex));\n player.once(Events.PLAYOUT_LIMIT_REACHED, endedWithAssetIndex(Infinity));\n player.on(Events.ERROR, (event, data) => {\n const inQueuPlayer = this.getAssetPlayer(assetId);\n if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {\n if (inQueuPlayer != null && inQueuPlayer.media) {\n const assetCurrentTime = inQueuPlayer.currentTime;\n const distanceFromEnd = inQueuPlayer.duration - assetCurrentTime;\n if (assetCurrentTime && interstitial.appendInPlace && distanceFromEnd / inQueuPlayer.media.playbackRate < 0.5) {\n this.log(`Advancing buffer past end of asset ${assetId} ${interstitial} at ${inQueuPlayer.media.currentTime}`);\n bufferedToEnd();\n } else {\n this.warn(`Stalled at ${assetCurrentTime} of ${assetCurrentTime + distanceFromEnd} in asset ${assetId} ${interstitial}`);\n this.onTimeupdate();\n this.checkBuffer(true);\n }\n }\n return;\n }\n this.handleAssetItemError(data, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, `Asset player error ${data.error} ${interstitial}`);\n });\n player.on(Events.DESTROYING, () => {\n const inQueuPlayer = this.getAssetPlayer(assetId);\n if (!inQueuPlayer) {\n return;\n }\n const error = new Error(`Asset player destroyed unexpectedly ${assetId}`);\n const errorData = {\n fatal: true,\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,\n error\n };\n this.handleAssetItemError(errorData, interstitial, this.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);\n });\n this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED, {\n asset: assetItem,\n assetListIndex,\n event: interstitial,\n player\n });\n return player;\n }\n clearInterstitial(interstitial, toSegment) {\n interstitial.assetList.forEach(asset => {\n this.clearAssetPlayer(asset.identifier, toSegment);\n });\n // Remove asset list and resolved duration\n interstitial.reset();\n }\n clearAssetPlayer(assetId, toSegment) {\n const playerIndex = this.getAssetPlayerQueueIndex(assetId);\n if (playerIndex !== -1) {\n this.log(`clearAssetPlayer \"${assetId}\" toSegment: ${toSegment ? segmentToString(toSegment) : toSegment}`);\n const player = this.playerQueue[playerIndex];\n this.transferMediaFromPlayer(player, toSegment);\n this.playerQueue.splice(playerIndex, 1);\n player.destroy();\n }\n }\n emptyPlayerQueue() {\n let player;\n while (player = this.playerQueue.pop()) {\n player.destroy();\n }\n this.playerQueue = [];\n }\n startAssetPlayer(player, assetListIndex, scheduleItems, scheduleIndex, media) {\n const {\n interstitial,\n assetItem,\n assetId\n } = player;\n const assetListLength = interstitial.assetList.length;\n const playingAsset = this.playingAsset;\n this.endedAsset = null;\n this.playingAsset = assetItem;\n if (!playingAsset || playingAsset.identifier !== assetId) {\n if (playingAsset) {\n // Exiting another Interstitial asset\n this.clearAssetPlayer(playingAsset.identifier, scheduleItems[scheduleIndex]);\n delete playingAsset.error;\n }\n this.log(`INTERSTITIAL_ASSET_STARTED ${assetListIndex + 1}/${assetListLength} ${player}`);\n this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED, {\n asset: assetItem,\n assetListIndex,\n event: interstitial,\n schedule: scheduleItems.slice(0),\n scheduleIndex,\n player\n });\n }\n\n // detach media and attach to interstitial player if it does not have another element attached\n this.bufferAssetPlayer(player, media);\n }\n bufferAssetPlayer(player, media) {\n var _this$schedule$items4, _this$detachedData5;\n const {\n interstitial,\n assetItem,\n assetId\n } = player;\n const scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);\n const item = (_this$schedule$items4 = this.schedule.items) == null ? void 0 : _this$schedule$items4[scheduleIndex];\n if (!item) {\n return;\n }\n this.setBufferingItem(item);\n this.bufferingAsset = assetItem;\n const bufferingPlayer = this.getBufferingPlayer();\n if (bufferingPlayer === player) {\n return;\n }\n const appendInPlaceNext = interstitial.appendInPlace;\n if (appendInPlaceNext && (bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial.appendInPlace) === false) {\n // Media is detached and not available to append in place\n return;\n }\n const activeTracks = (bufferingPlayer == null ? void 0 : bufferingPlayer.tracks) || ((_this$detachedData5 = this.detachedData) == null ? void 0 : _this$detachedData5.tracks) || this.requiredTracks;\n if (appendInPlaceNext && assetItem !== this.playingAsset) {\n // Do not buffer another item if tracks are unknown or incompatible\n if (!player.tracks) {\n return;\n }\n if (activeTracks && !isCompatibleTrackChange(activeTracks, player.tracks)) {\n const error = new Error(`Asset \"${assetId}\" SourceBuffer tracks ('${Object.keys(player.tracks)}') are not compatible with primary content tracks ('${Object.keys(activeTracks)}')`);\n const errorData = {\n fatal: true,\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,\n error\n };\n const assetListIndex = interstitial.findAssetIndex(assetItem);\n this.handleAssetItemError(errorData, interstitial, scheduleIndex, assetListIndex, error.message);\n return;\n }\n }\n this.transferMediaTo(player, media);\n }\n handleAssetItemError(data, interstitial, scheduleIndex, assetListIndex, errorMessage) {\n if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {\n return;\n }\n const assetItem = interstitial.assetList[assetListIndex] || null;\n let player = null;\n if (assetItem) {\n const playerIndex = this.getAssetPlayerQueueIndex(assetItem.identifier);\n player = this.playerQueue[playerIndex] || null;\n }\n const items = this.schedule.items;\n const interstitialAssetError = _extends({}, data, {\n fatal: false,\n errorAction: createDoNothingErrorAction(true),\n asset: assetItem,\n assetListIndex,\n event: interstitial,\n schedule: items,\n scheduleIndex,\n player\n });\n this.warn(`Asset item error: ${data.error}`);\n this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR, interstitialAssetError);\n if (!data.fatal) {\n return;\n }\n const error = new Error(errorMessage);\n if (assetItem) {\n if (this.playingAsset !== assetItem) {\n this.clearAssetPlayer(assetItem.identifier, null);\n }\n assetItem.error = error;\n }\n\n // If all assets in interstitial fail, mark the interstitial with an error\n if (!interstitial.assetList.some(asset => !asset.error)) {\n interstitial.error = error;\n } else if (interstitial.appendInPlace) {\n // Skip entire interstitial since moving up subsequent assets is error prone\n interstitial.error = error;\n }\n this.primaryFallback(interstitial);\n }\n primaryFallback(interstitial) {\n // Fallback to Primary by on current or future events by updating schedule to skip errored interstitials/assets\n const flushStart = interstitial.timelineStart;\n const playingItem = this.effectivePlayingItem;\n // Update schedule now that interstitial/assets are flagged with `error` for fallback\n this.updateSchedule();\n if (playingItem) {\n this.log(`Fallback to primary from event \"${interstitial.identifier}\" start: ${flushStart} pos: ${this.timelinePos} playing: ${playingItem ? segmentToString(playingItem) : '<none>'} error: ${interstitial.error}`);\n if (interstitial.appendInPlace) {\n this.attachPrimary(flushStart, null);\n this.flushFrontBuffer(flushStart);\n }\n let timelinePos = this.timelinePos;\n if (timelinePos === -1) {\n timelinePos = this.hls.startPosition;\n }\n const newPlayingItem = this.updateItem(playingItem, timelinePos);\n if (!this.itemsMatch(playingItem, newPlayingItem)) {\n const scheduleIndex = this.schedule.findItemIndexAtTime(timelinePos);\n this.setSchedulePosition(scheduleIndex);\n } else {\n this.clearInterstitial(interstitial, null);\n }\n } else {\n this.checkStart();\n }\n }\n\n // Asset List loading\n onAssetListLoaded(event, data) {\n var _this$bufferingItem2;\n const interstitial = data.event;\n const interstitialId = interstitial.identifier;\n const assets = data.assetListResponse.ASSETS;\n if (!this.schedule.hasEvent(interstitialId)) {\n // Interstitial with id was removed\n return;\n }\n const eventStart = interstitial.timelineStart;\n const previousDuration = interstitial.duration;\n let sumDuration = 0;\n assets.forEach((asset, assetListIndex) => {\n const duration = parseFloat(asset.DURATION);\n this.createAsset(interstitial, assetListIndex, sumDuration, eventStart + sumDuration, duration, asset.URI);\n sumDuration += duration;\n });\n interstitial.duration = sumDuration;\n this.log(`Loaded asset-list with duration: ${sumDuration} (was: ${previousDuration}) ${interstitial}`);\n const waitingItem = this.waitingItem;\n const waitingForItem = (waitingItem == null ? void 0 : waitingItem.event.identifier) === interstitialId;\n\n // Update schedule now that asset.DURATION(s) are parsed\n this.updateSchedule();\n const bufferingEvent = (_this$bufferingItem2 = this.bufferingItem) == null ? void 0 : _this$bufferingItem2.event;\n\n // If buffer reached Interstitial, start buffering first asset\n if (waitingForItem) {\n var _this$schedule$items5;\n // Advance schedule when waiting for asset list data to play\n const scheduleIndex = this.schedule.findEventIndex(interstitialId);\n const item = (_this$schedule$items5 = this.schedule.items) == null ? void 0 : _this$schedule$items5[scheduleIndex];\n if (item) {\n if (!this.playingItem && this.timelinePos > item.end) {\n // Abandon if new duration is reduced enough to land playback in primary start\n const index = this.schedule.findItemIndexAtTime(this.timelinePos);\n if (index !== scheduleIndex) {\n interstitial.error = new Error(`Interstitial no longer within playback range ${this.timelinePos} ${interstitial}`);\n this.primaryFallback(interstitial);\n return;\n }\n }\n this.setBufferingItem(item);\n }\n this.setSchedulePosition(scheduleIndex);\n } else if ((bufferingEvent == null ? void 0 : bufferingEvent.identifier) === interstitialId && bufferingEvent.appendInPlace) {\n // If buffering (but not playback) has reached this item transfer media-source\n const assetItem = interstitial.assetList[0];\n const player = this.getAssetPlayer(assetItem.identifier);\n const media = this.primaryMedia;\n if (assetItem && player && media) {\n this.bufferAssetPlayer(player, media);\n }\n }\n }\n onError(event, data) {\n switch (data.details) {\n case ErrorDetails.ASSET_LIST_PARSING_ERROR:\n case ErrorDetails.ASSET_LIST_LOAD_ERROR:\n case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT:\n {\n const interstitial = data.interstitial;\n if (interstitial) {\n this.primaryFallback(interstitial);\n }\n break;\n }\n case ErrorDetails.BUFFER_STALLED_ERROR:\n {\n this.onTimeupdate();\n this.checkBuffer(true);\n break;\n }\n }\n }\n}\n\nconst TICK_INTERVAL$2 = 500; // how often to tick in ms\n\nclass SubtitleStreamController extends BaseStreamController {\n constructor(hls, fragmentTracker, keyLoader) {\n super(hls, fragmentTracker, keyLoader, 'subtitle-stream-controller', PlaylistLevelType.SUBTITLE);\n this.currentTrackId = -1;\n this.tracksBuffered = [];\n this.mainDetails = null;\n this.registerListeners();\n }\n onHandlerDestroying() {\n this.unregisterListeners();\n super.onHandlerDestroying();\n this.mainDetails = null;\n }\n registerListeners() {\n super.registerListeners();\n const {\n hls\n } = this;\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n }\n unregisterListeners() {\n super.unregisterListeners();\n const {\n hls\n } = this;\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n }\n startLoad(startPosition, skipSeekToStartPosition) {\n this.stopLoad();\n this.state = State.IDLE;\n this.setInterval(TICK_INTERVAL$2);\n this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;\n this.startPosition = skipSeekToStartPosition ? -1 : startPosition;\n this.tick();\n }\n onManifestLoading() {\n super.onManifestLoading();\n this.mainDetails = null;\n }\n onMediaDetaching(event, data) {\n this.tracksBuffered = [];\n super.onMediaDetaching(event, data);\n }\n onLevelLoaded(event, data) {\n this.mainDetails = data.details;\n }\n onSubtitleFragProcessed(event, data) {\n const {\n frag,\n success\n } = data;\n if (isMediaFragment(frag)) {\n this.fragPrevious = frag;\n }\n this.state = State.IDLE;\n if (!success) {\n return;\n }\n const buffered = this.tracksBuffered[this.currentTrackId];\n if (!buffered) {\n return;\n }\n\n // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo\n // so we can re-use the logic used to detect how much has been buffered\n let timeRange;\n const fragStart = frag.start;\n for (let i = 0; i < buffered.length; i++) {\n if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {\n timeRange = buffered[i];\n break;\n }\n }\n const fragEnd = frag.start + frag.duration;\n if (timeRange) {\n timeRange.end = fragEnd;\n } else {\n timeRange = {\n start: fragStart,\n end: fragEnd\n };\n buffered.push(timeRange);\n }\n this.fragmentTracker.fragBuffered(frag);\n this.fragBufferedComplete(frag, null);\n if (this.media) {\n this.tick();\n }\n }\n onBufferFlushing(event, data) {\n const {\n startOffset,\n endOffset\n } = data;\n if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {\n const endOffsetSubtitles = endOffset - 1;\n if (endOffsetSubtitles <= 0) {\n return;\n }\n data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);\n this.tracksBuffered.forEach(buffered => {\n for (let i = 0; i < buffered.length;) {\n if (buffered[i].end <= endOffsetSubtitles) {\n buffered.shift();\n continue;\n } else if (buffered[i].start < endOffsetSubtitles) {\n buffered[i].start = endOffsetSubtitles;\n } else {\n break;\n }\n i++;\n }\n });\n this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE);\n }\n }\n\n // If something goes wrong, proceed to next frag, if we were processing one.\n onError(event, data) {\n const frag = data.frag;\n if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) {\n if (data.details === ErrorDetails.FRAG_GAP) {\n this.fragmentTracker.fragBuffered(frag, true);\n }\n if (this.fragCurrent) {\n this.fragCurrent.abortRequests();\n }\n if (this.state !== State.STOPPED) {\n this.state = State.IDLE;\n }\n }\n }\n\n // Got all new subtitle levels.\n onSubtitleTracksUpdated(event, {\n subtitleTracks\n }) {\n if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) {\n this.levels = subtitleTracks.map(mediaPlaylist => new Level(mediaPlaylist));\n return;\n }\n this.tracksBuffered = [];\n this.levels = subtitleTracks.map(mediaPlaylist => {\n const level = new Level(mediaPlaylist);\n this.tracksBuffered[level.id] = [];\n return level;\n });\n this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE);\n this.fragPrevious = null;\n this.mediaBuffer = null;\n }\n onSubtitleTrackSwitch(event, data) {\n var _this$levels;\n this.currentTrackId = data.id;\n if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) {\n this.clearInterval();\n return;\n }\n\n // Check if track has the necessary details to load fragments\n const currentTrack = this.levels[this.currentTrackId];\n if (currentTrack != null && currentTrack.details) {\n this.mediaBuffer = this.mediaBufferTimeRanges;\n } else {\n this.mediaBuffer = null;\n }\n if (currentTrack && this.state !== State.STOPPED) {\n this.setInterval(TICK_INTERVAL$2);\n }\n }\n\n // Got a new set of subtitle fragments.\n onSubtitleTrackLoaded(event, data) {\n var _track$details;\n const {\n currentTrackId,\n levels\n } = this;\n const {\n details: newDetails,\n id: trackId\n } = data;\n if (!levels) {\n this.warn(`Subtitle tracks were reset while loading level ${trackId}`);\n return;\n }\n const track = levels[trackId];\n if (trackId >= levels.length || !track) {\n return;\n }\n this.log(`Subtitle track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''},duration:${newDetails.totalduration}`);\n this.mediaBuffer = this.mediaBufferTimeRanges;\n let sliding = 0;\n if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {\n const mainDetails = this.mainDetails;\n if (newDetails.deltaUpdateFailed || !mainDetails) {\n return;\n }\n const mainSlidingStartFragment = mainDetails.fragments[0];\n if (!track.details) {\n if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {\n alignMediaPlaylistByPDT(newDetails, mainDetails);\n sliding = newDetails.fragmentStart;\n } else if (mainSlidingStartFragment) {\n // line up live playlist with main so that fragments in range are loaded\n sliding = mainSlidingStartFragment.start;\n addSliding(newDetails, sliding);\n }\n } else {\n var _this$levelLastLoaded;\n sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);\n if (sliding === 0 && mainSlidingStartFragment) {\n // realign with main when there is no overlap with last refresh\n sliding = mainSlidingStartFragment.start;\n addSliding(newDetails, sliding);\n }\n }\n }\n track.details = newDetails;\n this.levelLastLoaded = track;\n if (trackId !== currentTrackId) {\n return;\n }\n this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED, {\n details: newDetails,\n id: trackId,\n groupId: data.groupId\n });\n\n // trigger handler right now\n this.tick();\n\n // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload\n if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) {\n const foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0);\n if (!foundFrag) {\n this.warn('Subtitle playlist not aligned with playback');\n track.details = undefined;\n }\n }\n }\n _handleFragmentLoadComplete(fragLoadedData) {\n const {\n frag,\n payload\n } = fragLoadedData;\n const decryptData = frag.decryptdata;\n const hls = this.hls;\n if (this.fragContextChanged(frag)) {\n return;\n }\n // check to see if the payload needs to be decrypted\n if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {\n const startTime = performance.now();\n // decrypt the subtitles\n this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch(err => {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_DECRYPT_ERROR,\n fatal: false,\n error: err,\n reason: err.message,\n frag\n });\n throw err;\n }).then(decryptedData => {\n const endTime = performance.now();\n hls.trigger(Events.FRAG_DECRYPTED, {\n frag,\n payload: decryptedData,\n stats: {\n tstart: startTime,\n tdecrypt: endTime\n }\n });\n }).catch(err => {\n this.warn(`${err.name}: ${err.message}`);\n this.state = State.IDLE;\n });\n }\n }\n doTick() {\n if (!this.media) {\n this.state = State.IDLE;\n return;\n }\n if (this.state === State.IDLE) {\n const {\n currentTrackId,\n levels\n } = this;\n const track = levels == null ? void 0 : levels[currentTrackId];\n if (!track || !levels.length || !track.details) {\n return;\n }\n if (this.waitForLive(track)) {\n return;\n }\n const {\n config\n } = this;\n const currentTime = this.getLoadPosition();\n const bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config.maxBufferHole);\n const {\n end: targetBufferTime,\n len: bufferLen\n } = bufferedInfo;\n const trackDetails = track.details;\n const maxBufLen = this.hls.maxBufferLength + trackDetails.levelTargetDuration;\n if (bufferLen > maxBufLen) {\n return;\n }\n const fragments = trackDetails.fragments;\n const fragLen = fragments.length;\n const end = trackDetails.edge;\n let foundFrag = null;\n const fragPrevious = this.fragPrevious;\n if (targetBufferTime < end) {\n const tolerance = config.maxFragLookUpTolerance;\n const lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance;\n foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance);\n if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {\n foundFrag = fragments[0];\n }\n } else {\n foundFrag = fragments[fragLen - 1];\n }\n foundFrag = this.filterReplacedPrimary(foundFrag, track.details);\n if (!foundFrag) {\n return;\n }\n // Load earlier fragment in same discontinuity to make up for misaligned playlists and cues that extend beyond end of segment\n const curSNIdx = foundFrag.sn - trackDetails.startSN;\n const prevFrag = fragments[curSNIdx - 1];\n if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) {\n foundFrag = prevFrag;\n }\n if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {\n // only load if fragment is not loaded\n const fragToLoad = this.mapToInitFragWhenRequired(foundFrag);\n if (fragToLoad) {\n this.loadFragment(fragToLoad, track, targetBufferTime);\n }\n }\n }\n }\n loadFragment(frag, level, targetBufferTime) {\n if (!isMediaFragment(frag)) {\n this._loadInitSegment(frag, level);\n } else {\n super.loadFragment(frag, level, targetBufferTime);\n }\n }\n get mediaBufferTimeRanges() {\n return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []);\n }\n}\nclass BufferableInstance {\n constructor(timeranges) {\n this.buffered = void 0;\n const getRange = (name, index, length) => {\n index = index >>> 0;\n if (index > length - 1) {\n throw new DOMException(`Failed to execute '${name}' on 'TimeRanges': The index provided (${index}) is greater than the maximum bound (${length})`);\n }\n return timeranges[index][name];\n };\n this.buffered = {\n get length() {\n return timeranges.length;\n },\n end(index) {\n return getRange('end', index, timeranges.length);\n },\n start(index) {\n return getRange('start', index, timeranges.length);\n }\n };\n }\n}\n\n/**\n *\n * This code was ported from the dash.js project at:\n * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js\n * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2\n *\n * The original copyright appears below:\n *\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2015-2016, DASH Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * 2. Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n */\n\nconst specialCea608CharsCodes = {\n 0x2a: 0xe1,\n // lowercase a, acute accent\n 0x5c: 0xe9,\n // lowercase e, acute accent\n 0x5e: 0xed,\n // lowercase i, acute accent\n 0x5f: 0xf3,\n // lowercase o, acute accent\n 0x60: 0xfa,\n // lowercase u, acute accent\n 0x7b: 0xe7,\n // lowercase c with cedilla\n 0x7c: 0xf7,\n // division symbol\n 0x7d: 0xd1,\n // uppercase N tilde\n 0x7e: 0xf1,\n // lowercase n tilde\n 0x7f: 0x2588,\n // Full block\n // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n 0x80: 0xae,\n // Registered symbol (R)\n 0x81: 0xb0,\n // degree sign\n 0x82: 0xbd,\n // 1/2 symbol\n 0x83: 0xbf,\n // Inverted (open) question mark\n 0x84: 0x2122,\n // Trademark symbol (TM)\n 0x85: 0xa2,\n // Cents symbol\n 0x86: 0xa3,\n // Pounds sterling\n 0x87: 0x266a,\n // Music 8'th note\n 0x88: 0xe0,\n // lowercase a, grave accent\n 0x89: 0x20,\n // transparent space (regular)\n 0x8a: 0xe8,\n // lowercase e, grave accent\n 0x8b: 0xe2,\n // lowercase a, circumflex accent\n 0x8c: 0xea,\n // lowercase e, circumflex accent\n 0x8d: 0xee,\n // lowercase i, circumflex accent\n 0x8e: 0xf4,\n // lowercase o, circumflex accent\n 0x8f: 0xfb,\n // lowercase u, circumflex accent\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n 0x90: 0xc1,\n // capital letter A with acute\n 0x91: 0xc9,\n // capital letter E with acute\n 0x92: 0xd3,\n // capital letter O with acute\n 0x93: 0xda,\n // capital letter U with acute\n 0x94: 0xdc,\n // capital letter U with diaresis\n 0x95: 0xfc,\n // lowercase letter U with diaeresis\n 0x96: 0x2018,\n // opening single quote\n 0x97: 0xa1,\n // inverted exclamation mark\n 0x98: 0x2a,\n // asterisk\n 0x99: 0x2019,\n // closing single quote\n 0x9a: 0x2501,\n // box drawings heavy horizontal\n 0x9b: 0xa9,\n // copyright sign\n 0x9c: 0x2120,\n // Service mark\n 0x9d: 0x2022,\n // (round) bullet\n 0x9e: 0x201c,\n // Left double quotation mark\n 0x9f: 0x201d,\n // Right double quotation mark\n 0xa0: 0xc0,\n // uppercase A, grave accent\n 0xa1: 0xc2,\n // uppercase A, circumflex\n 0xa2: 0xc7,\n // uppercase C with cedilla\n 0xa3: 0xc8,\n // uppercase E, grave accent\n 0xa4: 0xca,\n // uppercase E, circumflex\n 0xa5: 0xcb,\n // capital letter E with diaresis\n 0xa6: 0xeb,\n // lowercase letter e with diaresis\n 0xa7: 0xce,\n // uppercase I, circumflex\n 0xa8: 0xcf,\n // uppercase I, with diaresis\n 0xa9: 0xef,\n // lowercase i, with diaresis\n 0xaa: 0xd4,\n // uppercase O, circumflex\n 0xab: 0xd9,\n // uppercase U, grave accent\n 0xac: 0xf9,\n // lowercase u, grave accent\n 0xad: 0xdb,\n // uppercase U, circumflex\n 0xae: 0xab,\n // left-pointing double angle quotation mark\n 0xaf: 0xbb,\n // right-pointing double angle quotation mark\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n 0xb0: 0xc3,\n // Uppercase A, tilde\n 0xb1: 0xe3,\n // Lowercase a, tilde\n 0xb2: 0xcd,\n // Uppercase I, acute accent\n 0xb3: 0xcc,\n // Uppercase I, grave accent\n 0xb4: 0xec,\n // Lowercase i, grave accent\n 0xb5: 0xd2,\n // Uppercase O, grave accent\n 0xb6: 0xf2,\n // Lowercase o, grave accent\n 0xb7: 0xd5,\n // Uppercase O, tilde\n 0xb8: 0xf5,\n // Lowercase o, tilde\n 0xb9: 0x7b,\n // Open curly brace\n 0xba: 0x7d,\n // Closing curly brace\n 0xbb: 0x5c,\n // Backslash\n 0xbc: 0x5e,\n // Caret\n 0xbd: 0x5f,\n // Underscore\n 0xbe: 0x7c,\n // Pipe (vertical line)\n 0xbf: 0x223c,\n // Tilde operator\n 0xc0: 0xc4,\n // Uppercase A, umlaut\n 0xc1: 0xe4,\n // Lowercase A, umlaut\n 0xc2: 0xd6,\n // Uppercase O, umlaut\n 0xc3: 0xf6,\n // Lowercase o, umlaut\n 0xc4: 0xdf,\n // Esszett (sharp S)\n 0xc5: 0xa5,\n // Yen symbol\n 0xc6: 0xa4,\n // Generic currency sign\n 0xc7: 0x2503,\n // Box drawings heavy vertical\n 0xc8: 0xc5,\n // Uppercase A, ring\n 0xc9: 0xe5,\n // Lowercase A, ring\n 0xca: 0xd8,\n // Uppercase O, stroke\n 0xcb: 0xf8,\n // Lowercase o, strok\n 0xcc: 0x250f,\n // Box drawings heavy down and right\n 0xcd: 0x2513,\n // Box drawings heavy down and left\n 0xce: 0x2517,\n // Box drawings heavy up and right\n 0xcf: 0x251b // Box drawings heavy up and left\n};\n\n/**\n * Utils\n */\nconst getCharForByte = byte => String.fromCharCode(specialCea608CharsCodes[byte] || byte);\nconst NR_ROWS = 15;\nconst NR_COLS = 100;\n// Tables to look up row from PAC data\nconst rowsLowCh1 = {\n 0x11: 1,\n 0x12: 3,\n 0x15: 5,\n 0x16: 7,\n 0x17: 9,\n 0x10: 11,\n 0x13: 12,\n 0x14: 14\n};\nconst rowsHighCh1 = {\n 0x11: 2,\n 0x12: 4,\n 0x15: 6,\n 0x16: 8,\n 0x17: 10,\n 0x13: 13,\n 0x14: 15\n};\nconst rowsLowCh2 = {\n 0x19: 1,\n 0x1a: 3,\n 0x1d: 5,\n 0x1e: 7,\n 0x1f: 9,\n 0x18: 11,\n 0x1b: 12,\n 0x1c: 14\n};\nconst rowsHighCh2 = {\n 0x19: 2,\n 0x1a: 4,\n 0x1d: 6,\n 0x1e: 8,\n 0x1f: 10,\n 0x1b: 13,\n 0x1c: 15\n};\nconst backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];\nclass CaptionsLogger {\n constructor() {\n this.time = null;\n this.verboseLevel = 0;\n }\n log(severity, msg) {\n if (this.verboseLevel >= severity) {\n const m = typeof msg === 'function' ? msg() : msg;\n logger.log(`${this.time} [${severity}] ${m}`);\n }\n }\n}\nconst numArrayToHexArray = function numArrayToHexArray(numArray) {\n const hexArray = [];\n for (let j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n return hexArray;\n};\nclass PenState {\n constructor() {\n this.foreground = 'white';\n this.underline = false;\n this.italics = false;\n this.background = 'black';\n this.flash = false;\n }\n reset() {\n this.foreground = 'white';\n this.underline = false;\n this.italics = false;\n this.background = 'black';\n this.flash = false;\n }\n setStyles(styles) {\n const attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];\n for (let i = 0; i < attribs.length; i++) {\n const style = attribs[i];\n if (styles.hasOwnProperty(style)) {\n this[style] = styles[style];\n }\n }\n }\n isDefault() {\n return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;\n }\n equals(other) {\n return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;\n }\n copy(newPenState) {\n this.foreground = newPenState.foreground;\n this.underline = newPenState.underline;\n this.italics = newPenState.italics;\n this.background = newPenState.background;\n this.flash = newPenState.flash;\n }\n toString() {\n return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;\n }\n}\n\n/**\n * Unicode character with styling and background.\n * @constructor\n */\nclass StyledUnicodeChar {\n constructor() {\n this.uchar = ' ';\n this.penState = new PenState();\n }\n reset() {\n this.uchar = ' ';\n this.penState.reset();\n }\n setChar(uchar, newPenState) {\n this.uchar = uchar;\n this.penState.copy(newPenState);\n }\n setPenState(newPenState) {\n this.penState.copy(newPenState);\n }\n equals(other) {\n return this.uchar === other.uchar && this.penState.equals(other.penState);\n }\n copy(newChar) {\n this.uchar = newChar.uchar;\n this.penState.copy(newChar.penState);\n }\n isEmpty() {\n return this.uchar === ' ' && this.penState.isDefault();\n }\n}\n\n/**\n * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n * @constructor\n */\nclass Row {\n constructor(logger) {\n this.chars = [];\n this.pos = 0;\n this.currPenState = new PenState();\n this.cueStartTime = null;\n this.logger = void 0;\n for (let i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n this.logger = logger;\n }\n equals(other) {\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].equals(other.chars[i])) {\n return false;\n }\n }\n return true;\n }\n copy(other) {\n for (let i = 0; i < NR_COLS; i++) {\n this.chars[i].copy(other.chars[i]);\n }\n }\n isEmpty() {\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n /**\n * Set the cursor to a valid column.\n */\n setCursor(absPos) {\n if (this.pos !== absPos) {\n this.pos = absPos;\n }\n if (this.pos < 0) {\n this.logger.log(3, 'Negative cursor position ' + this.pos);\n this.pos = 0;\n } else if (this.pos > NR_COLS) {\n this.logger.log(3, 'Too large cursor position ' + this.pos);\n this.pos = NR_COLS;\n }\n }\n\n /**\n * Move the cursor relative to current position.\n */\n moveCursor(relPos) {\n const newPos = this.pos + relPos;\n if (relPos > 1) {\n for (let i = this.pos + 1; i < newPos + 1; i++) {\n this.chars[i].setPenState(this.currPenState);\n }\n }\n this.setCursor(newPos);\n }\n\n /**\n * Backspace, move one step back and clear character.\n */\n backSpace() {\n this.moveCursor(-1);\n this.chars[this.pos].setChar(' ', this.currPenState);\n }\n insertChar(byte) {\n if (byte >= 0x90) {\n // Extended char\n this.backSpace();\n }\n const char = getCharForByte(byte);\n if (this.pos >= NR_COLS) {\n this.logger.log(0, () => 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');\n return;\n }\n this.chars[this.pos].setChar(char, this.currPenState);\n this.moveCursor(1);\n }\n clearFromPos(startPos) {\n let i;\n for (i = startPos; i < NR_COLS; i++) {\n this.chars[i].reset();\n }\n }\n clear() {\n this.clearFromPos(0);\n this.pos = 0;\n this.currPenState.reset();\n }\n clearToEndOfRow() {\n this.clearFromPos(this.pos);\n }\n getTextString() {\n const chars = [];\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n const char = this.chars[i].uchar;\n if (char !== ' ') {\n empty = false;\n }\n chars.push(char);\n }\n if (empty) {\n return '';\n } else {\n return chars.join('');\n }\n }\n setPenStyles(styles) {\n this.currPenState.setStyles(styles);\n const currChar = this.chars[this.pos];\n currChar.setPenState(this.currPenState);\n }\n}\n\n/**\n * Keep a CEA-608 screen of 32x15 styled characters\n * @constructor\n */\nclass CaptionScreen {\n constructor(logger) {\n this.rows = [];\n this.currRow = NR_ROWS - 1;\n this.nrRollUpRows = null;\n this.lastOutputScreen = null;\n this.logger = void 0;\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row(logger));\n }\n this.logger = logger;\n }\n reset() {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n this.currRow = NR_ROWS - 1;\n }\n equals(other) {\n let equal = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].equals(other.rows[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n copy(other) {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n }\n isEmpty() {\n let empty = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n backSpace() {\n const row = this.rows[this.currRow];\n row.backSpace();\n }\n clearToEndOfRow() {\n const row = this.rows[this.currRow];\n row.clearToEndOfRow();\n }\n\n /**\n * Insert a character (without styling) in the current row.\n */\n insertChar(char) {\n const row = this.rows[this.currRow];\n row.insertChar(char);\n }\n setPen(styles) {\n const row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n moveCursor(relPos) {\n const row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n setCursor(absPos) {\n this.logger.log(2, 'setCursor: ' + absPos);\n const row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n setPAC(pacData) {\n this.logger.log(2, () => 'pacData = ' + stringify(pacData));\n let newRow = pacData.row - 1;\n if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n newRow = this.nrRollUpRows - 1;\n }\n\n // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows\n if (this.nrRollUpRows && this.currRow !== newRow) {\n // clear all rows first\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n // topRowIndex - the start of rows to copy (inclusive index)\n const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n // We only copy if the last position was already shown.\n // We use the cueStartTime value to check this.\n const lastOutputScreen = this.lastOutputScreen;\n if (lastOutputScreen) {\n const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n const time = this.logger.time;\n if (prevLineTime !== null && time !== null && prevLineTime < time) {\n for (let i = 0; i < this.nrRollUpRows; i++) {\n this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);\n }\n }\n }\n }\n this.currRow = newRow;\n const row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n const indent = pacData.indent;\n const prevPos = Math.max(indent - 1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n const styles = {\n foreground: pacData.color,\n underline: pacData.underline,\n italics: pacData.italics,\n background: 'black',\n flash: false\n };\n this.setPen(styles);\n }\n\n /**\n * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).\n */\n setBkgData(bkgData) {\n this.logger.log(2, () => 'bkgData = ' + stringify(bkgData));\n this.backSpace();\n this.setPen(bkgData);\n this.insertChar(0x20); // Space\n }\n setRollUpRows(nrRows) {\n this.nrRollUpRows = nrRows;\n }\n rollUp() {\n if (this.nrRollUpRows === null) {\n this.logger.log(3, 'roll_up but nrRollUpRows not set yet');\n return; // Not properly setup\n }\n this.logger.log(1, () => this.getDisplayText());\n const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n const topRow = this.rows.splice(topRowIndex, 1)[0];\n topRow.clear();\n this.rows.splice(this.currRow, 0, topRow);\n this.logger.log(2, 'Rolling up');\n // this.logger.log(VerboseLevel.TEXT, this.get_display_text())\n }\n\n /**\n * Get all non-empty rows with as unicode text.\n */\n getDisplayText(asOneRow) {\n asOneRow = asOneRow || false;\n const displayText = [];\n let text = '';\n let rowNr = -1;\n for (let i = 0; i < NR_ROWS; i++) {\n const rowText = this.rows[i].getTextString();\n if (rowText) {\n rowNr = i + 1;\n if (asOneRow) {\n displayText.push('Row ' + rowNr + \": '\" + rowText + \"'\");\n } else {\n displayText.push(rowText.trim());\n }\n }\n }\n if (displayText.length > 0) {\n if (asOneRow) {\n text = '[' + displayText.join(' | ') + ']';\n } else {\n text = displayText.join('\\n');\n }\n }\n return text;\n }\n getTextAndFormat() {\n return this.rows;\n }\n}\n\n// var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n\nclass Cea608Channel {\n constructor(channelNumber, outputFilter, logger) {\n this.chNr = void 0;\n this.outputFilter = void 0;\n this.mode = void 0;\n this.verbose = void 0;\n this.displayedMemory = void 0;\n this.nonDisplayedMemory = void 0;\n this.lastOutputScreen = void 0;\n this.currRollUpRow = void 0;\n this.writeScreen = void 0;\n this.cueStartTime = void 0;\n this.logger = void 0;\n this.chNr = channelNumber;\n this.outputFilter = outputFilter;\n this.mode = null;\n this.verbose = 0;\n this.displayedMemory = new CaptionScreen(logger);\n this.nonDisplayedMemory = new CaptionScreen(logger);\n this.lastOutputScreen = new CaptionScreen(logger);\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null; // Keeps track of where a cue started.\n this.logger = logger;\n }\n reset() {\n this.mode = null;\n this.displayedMemory.reset();\n this.nonDisplayedMemory.reset();\n this.lastOutputScreen.reset();\n this.outputFilter.reset();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null;\n }\n getHandler() {\n return this.outputFilter;\n }\n setHandler(newHandler) {\n this.outputFilter = newHandler;\n }\n setPAC(pacData) {\n this.writeScreen.setPAC(pacData);\n }\n setBkgData(bkgData) {\n this.writeScreen.setBkgData(bkgData);\n }\n setMode(newMode) {\n if (newMode === this.mode) {\n return;\n }\n this.mode = newMode;\n this.logger.log(2, () => 'MODE=' + newMode);\n if (this.mode === 'MODE_POP-ON') {\n this.writeScreen = this.nonDisplayedMemory;\n } else {\n this.writeScreen = this.displayedMemory;\n this.writeScreen.reset();\n }\n if (this.mode !== 'MODE_ROLL-UP') {\n this.displayedMemory.nrRollUpRows = null;\n this.nonDisplayedMemory.nrRollUpRows = null;\n }\n this.mode = newMode;\n }\n insertChars(chars) {\n for (let i = 0; i < chars.length; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n const screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';\n this.logger.log(2, () => screen + ': ' + this.writeScreen.getDisplayText(true));\n if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {\n this.logger.log(1, () => 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));\n this.outputDataUpdate();\n }\n }\n ccRCL() {\n // Resume Caption Loading (switch mode to Pop On)\n this.logger.log(2, 'RCL - Resume Caption Loading');\n this.setMode('MODE_POP-ON');\n }\n ccBS() {\n // BackSpace\n this.logger.log(2, 'BS - BackSpace');\n if (this.mode === 'MODE_TEXT') {\n return;\n }\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n }\n ccAOF() {\n // Reserved (formerly Alarm Off)\n }\n ccAON() {\n // Reserved (formerly Alarm On)\n }\n ccDER() {\n // Delete to End of Row\n this.logger.log(2, 'DER- Delete to End of Row');\n this.writeScreen.clearToEndOfRow();\n this.outputDataUpdate();\n }\n ccRU(nrRows) {\n // Roll-Up Captions-2,3,or 4 Rows\n this.logger.log(2, 'RU(' + nrRows + ') - Roll Up');\n this.writeScreen = this.displayedMemory;\n this.setMode('MODE_ROLL-UP');\n this.writeScreen.setRollUpRows(nrRows);\n }\n ccFON() {\n // Flash On\n this.logger.log(2, 'FON - Flash On');\n this.writeScreen.setPen({\n flash: true\n });\n }\n ccRDC() {\n // Resume Direct Captioning (switch mode to PaintOn)\n this.logger.log(2, 'RDC - Resume Direct Captioning');\n this.setMode('MODE_PAINT-ON');\n }\n ccTR() {\n // Text Restart in text mode (not supported, however)\n this.logger.log(2, 'TR');\n this.setMode('MODE_TEXT');\n }\n ccRTD() {\n // Resume Text Display in Text mode (not supported, however)\n this.logger.log(2, 'RTD');\n this.setMode('MODE_TEXT');\n }\n ccEDM() {\n // Erase Displayed Memory\n this.logger.log(2, 'EDM - Erase Displayed Memory');\n this.displayedMemory.reset();\n this.outputDataUpdate(true);\n }\n ccCR() {\n // Carriage Return\n this.logger.log(2, 'CR - Carriage Return');\n this.writeScreen.rollUp();\n this.outputDataUpdate(true);\n }\n ccENM() {\n // Erase Non-Displayed Memory\n this.logger.log(2, 'ENM - Erase Non-displayed Memory');\n this.nonDisplayedMemory.reset();\n }\n ccEOC() {\n // End of Caption (Flip Memories)\n this.logger.log(2, 'EOC - End Of Caption');\n if (this.mode === 'MODE_POP-ON') {\n const tmp = this.displayedMemory;\n this.displayedMemory = this.nonDisplayedMemory;\n this.nonDisplayedMemory = tmp;\n this.writeScreen = this.nonDisplayedMemory;\n this.logger.log(1, () => 'DISP: ' + this.displayedMemory.getDisplayText());\n }\n this.outputDataUpdate(true);\n }\n ccTO(nrCols) {\n // Tab Offset 1,2, or 3 columns\n this.logger.log(2, 'TO(' + nrCols + ') - Tab Offset');\n this.writeScreen.moveCursor(nrCols);\n }\n ccMIDROW(secondByte) {\n // Parse MIDROW command\n const styles = {\n flash: false\n };\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n const colorIndex = Math.floor(secondByte / 2) - 0x10;\n const colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];\n styles.foreground = colors[colorIndex];\n } else {\n styles.foreground = 'white';\n }\n this.logger.log(2, 'MIDROW: ' + stringify(styles));\n this.writeScreen.setPen(styles);\n }\n outputDataUpdate(dispatch = false) {\n const time = this.logger.time;\n if (time === null) {\n return;\n }\n if (this.outputFilter) {\n if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {\n // Start of a new cue\n this.cueStartTime = time;\n } else {\n if (!this.displayedMemory.equals(this.lastOutputScreen)) {\n this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);\n if (dispatch && this.outputFilter.dispatchCue) {\n this.outputFilter.dispatchCue();\n }\n this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;\n }\n }\n this.lastOutputScreen.copy(this.displayedMemory);\n }\n }\n cueSplitAtTime(t) {\n if (this.outputFilter) {\n if (!this.displayedMemory.isEmpty()) {\n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);\n }\n this.cueStartTime = t;\n }\n }\n }\n}\n\n// Will be 1 or 2 when parsing captions\n\nclass Cea608Parser {\n constructor(field, out1, out2) {\n this.channels = void 0;\n this.currentChannel = 0;\n this.cmdHistory = createCmdHistory();\n this.logger = void 0;\n const logger = this.logger = new CaptionsLogger();\n this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];\n }\n getHandler(channel) {\n return this.channels[channel].getHandler();\n }\n setHandler(channel, newHandler) {\n this.channels[channel].setHandler(newHandler);\n }\n\n /**\n * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.\n */\n addData(time, byteList) {\n this.logger.time = time;\n for (let i = 0; i < byteList.length; i += 2) {\n const a = byteList[i] & 0x7f;\n const b = byteList[i + 1] & 0x7f;\n let cmdFound = false;\n let charsFound = null;\n if (a === 0 && b === 0) {\n continue;\n } else {\n this.logger.log(3, () => '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');\n }\n const cmdHistory = this.cmdHistory;\n const isControlCode = a >= 0x10 && a <= 0x1f;\n if (isControlCode) {\n // Skip redundant control codes\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n this.logger.log(3, () => 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');\n continue;\n }\n setLastCmd(a, b, this.cmdHistory);\n cmdFound = this.parseCmd(a, b);\n if (!cmdFound) {\n cmdFound = this.parseMidrow(a, b);\n }\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n } else {\n setLastCmd(null, null, cmdHistory);\n }\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n const currChNr = this.currentChannel;\n if (currChNr && currChNr > 0) {\n const channel = this.channels[currChNr];\n channel.insertChars(charsFound);\n } else {\n this.logger.log(2, 'No channel found yet. TEXT-MODE?');\n }\n }\n }\n if (!cmdFound && !charsFound) {\n this.logger.log(2, () => \"Couldn't parse cleaned data \" + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));\n }\n }\n }\n\n /**\n * Parse Command.\n * @returns True if a command was found\n */\n parseCmd(a, b) {\n const cond1 = (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) && b >= 0x20 && b <= 0x2f;\n const cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;\n if (!(cond1 || cond2)) {\n return false;\n }\n const chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;\n const channel = this.channels[chNr];\n if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {\n if (b === 0x20) {\n channel.ccRCL();\n } else if (b === 0x21) {\n channel.ccBS();\n } else if (b === 0x22) {\n channel.ccAOF();\n } else if (b === 0x23) {\n channel.ccAON();\n } else if (b === 0x24) {\n channel.ccDER();\n } else if (b === 0x25) {\n channel.ccRU(2);\n } else if (b === 0x26) {\n channel.ccRU(3);\n } else if (b === 0x27) {\n channel.ccRU(4);\n } else if (b === 0x28) {\n channel.ccFON();\n } else if (b === 0x29) {\n channel.ccRDC();\n } else if (b === 0x2a) {\n channel.ccTR();\n } else if (b === 0x2b) {\n channel.ccRTD();\n } else if (b === 0x2c) {\n channel.ccEDM();\n } else if (b === 0x2d) {\n channel.ccCR();\n } else if (b === 0x2e) {\n channel.ccENM();\n } else if (b === 0x2f) {\n channel.ccEOC();\n }\n } else {\n // a == 0x17 || a == 0x1F\n channel.ccTO(b - 0x20);\n }\n this.currentChannel = chNr;\n return true;\n }\n\n /**\n * Parse midrow styling command\n */\n parseMidrow(a, b) {\n let chNr = 0;\n if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n if (chNr !== this.currentChannel) {\n this.logger.log(0, 'Mismatch channel in midrow parsing');\n return false;\n }\n const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.ccMIDROW(b);\n this.logger.log(3, () => 'MIDROW (' + numArrayToHexArray([a, b]) + ')');\n return true;\n }\n return false;\n }\n\n /**\n * Parse Preable Access Codes (Table 53).\n * @returns {Boolean} Tells if PAC found\n */\n parsePAC(a, b) {\n let row;\n const case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1f) && b >= 0x40 && b <= 0x7f;\n const case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;\n if (!(case1 || case2)) {\n return false;\n }\n const chNr = a <= 0x17 ? 1 : 2;\n if (b >= 0x40 && b <= 0x5f) {\n row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];\n } else {\n // 0x60 <= b <= 0x7F\n row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];\n }\n const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.setPAC(this.interpretPAC(row, b));\n this.currentChannel = chNr;\n return true;\n }\n\n /**\n * Interpret the second byte of the pac, and return the information.\n * @returns pacData with style parameters\n */\n interpretPAC(row, byte) {\n let pacIndex;\n const pacData = {\n color: null,\n italics: false,\n indent: null,\n underline: false,\n row: row\n };\n if (byte > 0x5f) {\n pacIndex = byte - 0x60;\n } else {\n pacIndex = byte - 0x40;\n }\n pacData.underline = (pacIndex & 1) === 1;\n if (pacIndex <= 0xd) {\n pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];\n } else if (pacIndex <= 0xf) {\n pacData.italics = true;\n pacData.color = 'white';\n } else {\n pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;\n }\n return pacData; // Note that row has zero offset. The spec uses 1.\n }\n\n /**\n * Parse characters.\n * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.\n */\n parseChars(a, b) {\n let channelNr;\n let charCodes = null;\n let charCode1 = null;\n if (a >= 0x19) {\n channelNr = 2;\n charCode1 = a - 8;\n } else {\n channelNr = 1;\n charCode1 = a;\n }\n if (charCode1 >= 0x11 && charCode1 <= 0x13) {\n // Special character\n let oneCode;\n if (charCode1 === 0x11) {\n oneCode = b + 0x50;\n } else if (charCode1 === 0x12) {\n oneCode = b + 0x70;\n } else {\n oneCode = b + 0x90;\n }\n this.logger.log(2, () => \"Special char '\" + getCharForByte(oneCode) + \"' in channel \" + channelNr);\n charCodes = [oneCode];\n } else if (a >= 0x20 && a <= 0x7f) {\n charCodes = b === 0 ? [a] : [a, b];\n }\n if (charCodes) {\n this.logger.log(3, () => 'Char codes = ' + numArrayToHexArray(charCodes).join(','));\n }\n return charCodes;\n }\n\n /**\n * Parse extended background attributes as well as new foreground color black.\n * @returns True if background attributes are found\n */\n parseBackgroundAttributes(a, b) {\n const case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;\n const case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;\n if (!(case1 || case2)) {\n return false;\n }\n let index;\n const bkgData = {};\n if (a === 0x10 || a === 0x18) {\n index = Math.floor((b - 0x20) / 2);\n bkgData.background = backgroundColors[index];\n if (b % 2 === 1) {\n bkgData.background = bkgData.background + '_semi';\n }\n } else if (b === 0x2d) {\n bkgData.background = 'transparent';\n } else {\n bkgData.foreground = 'black';\n if (b === 0x2f) {\n bkgData.underline = true;\n }\n }\n const chNr = a <= 0x17 ? 1 : 2;\n const channel = this.channels[chNr];\n channel.setBkgData(bkgData);\n return true;\n }\n\n /**\n * Reset state of parser and its channels.\n */\n reset() {\n for (let i = 0; i < Object.keys(this.channels).length; i++) {\n const channel = this.channels[i];\n if (channel) {\n channel.reset();\n }\n }\n setLastCmd(null, null, this.cmdHistory);\n }\n\n /**\n * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.\n */\n cueSplitAtTime(t) {\n for (let i = 0; i < this.channels.length; i++) {\n const channel = this.channels[i];\n if (channel) {\n channel.cueSplitAtTime(t);\n }\n }\n }\n}\nfunction setLastCmd(a, b, cmdHistory) {\n cmdHistory.a = a;\n cmdHistory.b = b;\n}\nfunction hasCmdRepeated(a, b, cmdHistory) {\n return cmdHistory.a === a && cmdHistory.b === b;\n}\nfunction createCmdHistory() {\n return {\n a: null,\n b: null\n };\n}\n\n/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an 'AS IS' BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nvar VTTCue = (function () {\n if (optionalSelf != null && optionalSelf.VTTCue) {\n return self.VTTCue;\n }\n const AllowedDirections = ['', 'lr', 'rl'];\n const AllowedAlignments = ['start', 'middle', 'end', 'left', 'right'];\n function isAllowedValue(allowed, value) {\n if (typeof value !== 'string') {\n return false;\n }\n // necessary for assuring the generic conforms to the Array interface\n if (!Array.isArray(allowed)) {\n return false;\n }\n // reset the type so that the next narrowing works well\n const lcValue = value.toLowerCase();\n // use the allow list to narrow the type to a specific subset of strings\n if (~allowed.indexOf(lcValue)) {\n return lcValue;\n }\n return false;\n }\n function findDirectionSetting(value) {\n return isAllowedValue(AllowedDirections, value);\n }\n function findAlignSetting(value) {\n return isAllowedValue(AllowedAlignments, value);\n }\n function extend(obj, ...rest) {\n let i = 1;\n for (; i < arguments.length; i++) {\n const cobj = arguments[i];\n for (const p in cobj) {\n obj[p] = cobj[p];\n }\n }\n return obj;\n }\n function VTTCue(startTime, endTime, text) {\n const cue = this;\n const baseObj = {\n enumerable: true\n };\n /**\n * Shim implementation specific properties. These properties are not in\n * the spec.\n */\n\n // Lets us know when the VTTCue's data has changed in such a way that we need\n // to recompute its display state. This lets us compute its display state\n // lazily.\n cue.hasBeenReset = false;\n\n /**\n * VTTCue and TextTrackCue properties\n * http://dev.w3.org/html5/webvtt/#vttcue-interface\n */\n\n let _id = '';\n let _pauseOnExit = false;\n let _startTime = startTime;\n let _endTime = endTime;\n let _text = text;\n let _region = null;\n let _vertical = '';\n let _snapToLines = true;\n let _line = 'auto';\n let _lineAlign = 'start';\n let _position = 50;\n let _positionAlign = 'middle';\n let _size = 50;\n let _align = 'middle';\n Object.defineProperty(cue, 'id', extend({}, baseObj, {\n get: function () {\n return _id;\n },\n set: function (value) {\n _id = '' + value;\n }\n }));\n Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {\n get: function () {\n return _pauseOnExit;\n },\n set: function (value) {\n _pauseOnExit = !!value;\n }\n }));\n Object.defineProperty(cue, 'startTime', extend({}, baseObj, {\n get: function () {\n return _startTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('Start time must be set to a number.');\n }\n _startTime = value;\n this.hasBeenReset = true;\n }\n }));\n Object.defineProperty(cue, 'endTime', extend({}, baseObj, {\n get: function () {\n return _endTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('End time must be set to a number.');\n }\n _endTime = value;\n this.hasBeenReset = true;\n }\n }));\n Object.defineProperty(cue, 'text', extend({}, baseObj, {\n get: function () {\n return _text;\n },\n set: function (value) {\n _text = '' + value;\n this.hasBeenReset = true;\n }\n }));\n\n // todo: implement VTTRegion polyfill?\n Object.defineProperty(cue, 'region', extend({}, baseObj, {\n get: function () {\n return _region;\n },\n set: function (value) {\n _region = value;\n this.hasBeenReset = true;\n }\n }));\n Object.defineProperty(cue, 'vertical', extend({}, baseObj, {\n get: function () {\n return _vertical;\n },\n set: function (value) {\n const setting = findDirectionSetting(value);\n // Have to check for false because the setting an be an empty string.\n if (setting === false) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _vertical = setting;\n this.hasBeenReset = true;\n }\n }));\n Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {\n get: function () {\n return _snapToLines;\n },\n set: function (value) {\n _snapToLines = !!value;\n this.hasBeenReset = true;\n }\n }));\n Object.defineProperty(cue, 'line', extend({}, baseObj, {\n get: function () {\n return _line;\n },\n set: function (value) {\n if (typeof value !== 'number' && value !== 'auto') {\n throw new SyntaxError('An invalid number or illegal string was specified.');\n }\n _line = value;\n this.hasBeenReset = true;\n }\n }));\n Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {\n get: function () {\n return _lineAlign;\n },\n set: function (value) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _lineAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n Object.defineProperty(cue, 'position', extend({}, baseObj, {\n get: function () {\n return _position;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Position must be between 0 and 100.');\n }\n _position = value;\n this.hasBeenReset = true;\n }\n }));\n Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {\n get: function () {\n return _positionAlign;\n },\n set: function (value) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _positionAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n Object.defineProperty(cue, 'size', extend({}, baseObj, {\n get: function () {\n return _size;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Size must be between 0 and 100.');\n }\n _size = value;\n this.hasBeenReset = true;\n }\n }));\n Object.defineProperty(cue, 'align', extend({}, baseObj, {\n get: function () {\n return _align;\n },\n set: function (value) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _align = setting;\n this.hasBeenReset = true;\n }\n }));\n\n /**\n * Other <track> spec defined properties\n */\n\n // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state\n cue.displayState = undefined;\n }\n\n /**\n * VTTCue methods\n */\n\n VTTCue.prototype.getCueAsHTML = function () {\n // Assume WebVTT.convertCueToDOMTree is on the global.\n const WebVTT = self.WebVTT;\n return WebVTT.convertCueToDOMTree(self, this.text);\n };\n // this is a polyfill hack\n return VTTCue;\n})();\n\n/*\n * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js\n */\n\nclass StringDecoder {\n decode(data, options) {\n if (!data) {\n return '';\n }\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\n return decodeURIComponent(encodeURIComponent(data));\n }\n}\n\n// Try to parse input as a time stamp.\nfunction parseTimeStamp(input) {\n function computeSeconds(h, m, s, f) {\n return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);\n }\n const m = input.match(/^(?:(\\d+):)?(\\d{2}):(\\d{2})(\\.\\d+)?/);\n if (!m) {\n return null;\n }\n if (parseFloat(m[2]) > 59) {\n // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n // First position is hours as it's over 59.\n return computeSeconds(m[2], m[3], 0, m[4]);\n }\n // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]\n return computeSeconds(m[1], m[2], m[3], m[4]);\n}\n\n// A settings object holds key/value pairs and will ignore anything but the first\n// assignment to a specific key.\nclass Settings {\n constructor() {\n this.values = Object.create(null);\n }\n // Only accept the first assignment to any key.\n set(k, v) {\n if (!this.get(k) && v !== '') {\n this.values[k] = v;\n }\n }\n // Return the value for a key, or a default value.\n // If 'defaultKey' is passed then 'dflt' is assumed to be an object with\n // a number of possible default values as properties where 'defaultKey' is\n // the key of the property that will be chosen; otherwise it's assumed to be\n // a single value.\n get(k, dflt, defaultKey) {\n if (defaultKey) {\n return this.has(k) ? this.values[k] : dflt[defaultKey];\n }\n return this.has(k) ? this.values[k] : dflt;\n }\n // Check whether we have a value for a key.\n has(k) {\n return k in this.values;\n }\n // Accept a setting if its one of the given alternatives.\n alt(k, v, a) {\n for (let n = 0; n < a.length; ++n) {\n if (v === a[n]) {\n this.set(k, v);\n break;\n }\n }\n }\n // Accept a setting if its a valid (signed) integer.\n integer(k, v) {\n if (/^-?\\d+$/.test(v)) {\n // integer\n this.set(k, parseInt(v, 10));\n }\n }\n // Accept a setting if its a valid percentage.\n percent(k, v) {\n if (/^([\\d]{1,3})(\\.[\\d]*)?%$/.test(v)) {\n const percent = parseFloat(v);\n if (percent >= 0 && percent <= 100) {\n this.set(k, percent);\n return true;\n }\n }\n return false;\n }\n}\n\n// Helper function to parse input into groups separated by 'groupDelim', and\n// interpret each group as a key/value pair separated by 'keyValueDelim'.\nfunction parseOptions(input, callback, keyValueDelim, groupDelim) {\n const groups = groupDelim ? input.split(groupDelim) : [input];\n for (const i in groups) {\n if (typeof groups[i] !== 'string') {\n continue;\n }\n const kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n const k = kv[0];\n const v = kv[1];\n callback(k, v);\n }\n}\nconst defaults = new VTTCue(0, 0, '');\n// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244\n// Safari doesn't yet support this change, but FF and Chrome do.\nconst center = defaults.align === 'middle' ? 'middle' : 'center';\nfunction parseCue(input, cue, regionList) {\n // Remember the original input if we need to throw an error.\n const oInput = input;\n // 4.1 WebVTT timestamp\n function consumeTimeStamp() {\n const ts = parseTimeStamp(input);\n if (ts === null) {\n throw new Error('Malformed timestamp: ' + oInput);\n }\n\n // Remove time stamp from input.\n input = input.replace(/^[^\\sa-zA-Z-]+/, '');\n return ts;\n }\n\n // 4.4.2 WebVTT cue settings\n function consumeCueSettings(input, cue) {\n const settings = new Settings();\n parseOptions(input, function (k, v) {\n let vals;\n switch (k) {\n case 'region':\n // Find the last region we parsed with the same region id.\n for (let i = regionList.length - 1; i >= 0; i--) {\n if (regionList[i].id === v) {\n settings.set(k, regionList[i].region);\n break;\n }\n }\n break;\n case 'vertical':\n settings.alt(k, v, ['rl', 'lr']);\n break;\n case 'line':\n vals = v.split(',');\n settings.integer(k, vals[0]);\n if (settings.percent(k, vals[0])) {\n settings.set('snapToLines', false);\n }\n settings.alt(k, vals[0], ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\n break;\n case 'position':\n vals = v.split(',');\n settings.percent(k, vals[0]);\n if (vals.length === 2) {\n settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);\n }\n break;\n case 'size':\n settings.percent(k, v);\n break;\n case 'align':\n settings.alt(k, v, ['start', center, 'end', 'left', 'right']);\n break;\n }\n }, /:/, /\\s/);\n\n // Apply default values for any missing fields.\n cue.region = settings.get('region', null);\n cue.vertical = settings.get('vertical', '');\n let line = settings.get('line', 'auto');\n if (line === 'auto' && defaults.line === -1) {\n // set numeric line number for Safari\n line = -1;\n }\n cue.line = line;\n cue.lineAlign = settings.get('lineAlign', 'start');\n cue.snapToLines = settings.get('snapToLines', true);\n cue.size = settings.get('size', 100);\n cue.align = settings.get('align', center);\n let position = settings.get('position', 'auto');\n if (position === 'auto' && defaults.position === 50) {\n // set numeric position for Safari\n position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;\n }\n cue.position = position;\n }\n function skipWhitespace() {\n input = input.replace(/^\\s+/, '');\n }\n\n // 4.1 WebVTT cue timings.\n skipWhitespace();\n cue.startTime = consumeTimeStamp(); // (1) collect cue start time\n skipWhitespace();\n if (input.slice(0, 3) !== '-->') {\n // (3) next characters must match '-->'\n throw new Error(\"Malformed time stamp (time stamps must be separated by '-->'): \" + oInput);\n }\n input = input.slice(3);\n skipWhitespace();\n cue.endTime = consumeTimeStamp(); // (5) collect cue end time\n\n // 4.1 WebVTT cue settings list.\n skipWhitespace();\n consumeCueSettings(input, cue);\n}\nfunction fixLineBreaks(input) {\n return input.replace(/<br(?: \\/)?>/gi, '\\n');\n}\nclass VTTParser {\n constructor() {\n this.state = 'INITIAL';\n this.buffer = '';\n this.decoder = new StringDecoder();\n this.regionList = [];\n this.cue = null;\n this.oncue = void 0;\n this.onparsingerror = void 0;\n this.onflush = void 0;\n }\n parse(data) {\n const _this = this;\n\n // If there is no data then we won't decode it, but will just try to parse\n // whatever is in buffer already. This may occur in circumstances, for\n // example when flush() is called.\n if (data) {\n // Try to decode the data that we received.\n _this.buffer += _this.decoder.decode(data, {\n stream: true\n });\n }\n function collectNextLine() {\n let buffer = _this.buffer;\n let pos = 0;\n buffer = fixLineBreaks(buffer);\n while (pos < buffer.length && buffer[pos] !== '\\r' && buffer[pos] !== '\\n') {\n ++pos;\n }\n const line = buffer.slice(0, pos);\n // Advance the buffer early in case we fail below.\n if (buffer[pos] === '\\r') {\n ++pos;\n }\n if (buffer[pos] === '\\n') {\n ++pos;\n }\n _this.buffer = buffer.slice(pos);\n return line;\n }\n\n // 3.2 WebVTT metadata header syntax\n function parseHeader(input) {\n parseOptions(input, function (k, v) {\n // switch (k) {\n // case 'region':\n // 3.3 WebVTT region metadata header syntax\n // console.log('parse region', v);\n // parseRegion(v);\n // break;\n // }\n }, /:/);\n }\n\n // 5.1 WebVTT file parsing.\n try {\n let line = '';\n if (_this.state === 'INITIAL') {\n // We can't start parsing until we have the first line.\n if (!/\\r\\n|\\n/.test(_this.buffer)) {\n return this;\n }\n line = collectNextLine();\n // strip of UTF-8 BOM if any\n // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8\n const m = line.match(/^()?WEBVTT([ \\t].*)?$/);\n if (!(m != null && m[0])) {\n throw new Error('Malformed WebVTT signature.');\n }\n _this.state = 'HEADER';\n }\n let alreadyCollectedLine = false;\n while (_this.buffer) {\n // We can't parse a line until we have the full line.\n if (!/\\r\\n|\\n/.test(_this.buffer)) {\n return this;\n }\n if (!alreadyCollectedLine) {\n line = collectNextLine();\n } else {\n alreadyCollectedLine = false;\n }\n switch (_this.state) {\n case 'HEADER':\n // 13-18 - Allow a header (metadata) under the WEBVTT line.\n if (/:/.test(line)) {\n parseHeader(line);\n } else if (!line) {\n // An empty line terminates the header and starts the body (cues).\n _this.state = 'ID';\n }\n continue;\n case 'NOTE':\n // Ignore NOTE blocks.\n if (!line) {\n _this.state = 'ID';\n }\n continue;\n case 'ID':\n // Check for the start of NOTE blocks.\n if (/^NOTE($|[ \\t])/.test(line)) {\n _this.state = 'NOTE';\n break;\n }\n // 19-29 - Allow any number of line terminators, then initialize new cue values.\n if (!line) {\n continue;\n }\n _this.cue = new VTTCue(0, 0, '');\n _this.state = 'CUE';\n // 30-39 - Check if self line contains an optional identifier or timing data.\n if (line.indexOf('-->') === -1) {\n _this.cue.id = line;\n continue;\n }\n // Process line as start of a cue.\n /* falls through */\n case 'CUE':\n // 40 - Collect cue timings and settings.\n if (!_this.cue) {\n _this.state = 'BADCUE';\n continue;\n }\n try {\n parseCue(line, _this.cue, _this.regionList);\n } catch (e) {\n // In case of an error ignore rest of the cue.\n _this.cue = null;\n _this.state = 'BADCUE';\n continue;\n }\n _this.state = 'CUETEXT';\n continue;\n case 'CUETEXT':\n {\n const hasSubstring = line.indexOf('-->') !== -1;\n // 34 - If we have an empty line then report the cue.\n // 35 - If we have the special substring '-->' then report the cue,\n // but do not collect the line as we need to process the current\n // one as a new cue.\n if (!line || hasSubstring && (alreadyCollectedLine = true)) {\n // We are done parsing self cue.\n if (_this.oncue && _this.cue) {\n _this.oncue(_this.cue);\n }\n _this.cue = null;\n _this.state = 'ID';\n continue;\n }\n if (_this.cue === null) {\n continue;\n }\n if (_this.cue.text) {\n _this.cue.text += '\\n';\n }\n _this.cue.text += line;\n }\n continue;\n case 'BADCUE':\n // 54-62 - Collect and discard the remaining cue.\n if (!line) {\n _this.state = 'ID';\n }\n }\n }\n } catch (e) {\n // If we are currently parsing a cue, report what we have.\n if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) {\n _this.oncue(_this.cue);\n }\n _this.cue = null;\n // Enter BADWEBVTT state if header was not parsed correctly otherwise\n // another exception occurred so enter BADCUE state.\n _this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';\n }\n return this;\n }\n flush() {\n const _this = this;\n try {\n // Finish decoding the stream.\n // _this.buffer += _this.decoder.decode();\n // Synthesize the end of the current cue or region.\n if (_this.cue || _this.state === 'HEADER') {\n _this.buffer += '\\n\\n';\n _this.parse();\n }\n // If we've flushed, parsed, and we're still on the INITIAL state then\n // that means we don't have enough of the stream to parse the first\n // line.\n if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') {\n throw new Error('Malformed WebVTT signature.');\n }\n } catch (e) {\n if (_this.onparsingerror) {\n _this.onparsingerror(e);\n }\n }\n if (_this.onflush) {\n _this.onflush();\n }\n return this;\n }\n}\n\nconst LINEBREAKS = /\\r\\n|\\n\\r|\\n|\\r/g;\n\n// String.prototype.startsWith is not supported in IE11\nconst startsWith = function startsWith(inputString, searchString, position = 0) {\n return inputString.slice(position, position + searchString.length) === searchString;\n};\nconst cueString2millis = function cueString2millis(timeString) {\n let ts = parseInt(timeString.slice(-3));\n const secs = parseInt(timeString.slice(-6, -4));\n const mins = parseInt(timeString.slice(-9, -7));\n const hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(':'))) : 0;\n if (!isFiniteNumber(ts) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {\n throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);\n }\n ts += 1000 * secs;\n ts += 60 * 1000 * mins;\n ts += 60 * 60 * 1000 * hours;\n return ts;\n};\n\n// Create a unique hash id for a cue based on start/end times and text.\n// This helps timeline-controller to avoid showing repeated captions.\nfunction generateCueId(startTime, endTime, text) {\n return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);\n}\nconst calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {\n let currCC = vttCCs[cc];\n let prevCC = vttCCs[currCC.prevCC];\n\n // This is the first discontinuity or cues have been processed since the last discontinuity\n // Offset = current discontinuity time\n if (!prevCC || !prevCC.new && currCC.new) {\n vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;\n currCC.new = false;\n return;\n }\n\n // There have been discontinuities since cues were last parsed.\n // Offset = time elapsed\n while ((_prevCC = prevCC) != null && _prevCC.new) {\n var _prevCC;\n vttCCs.ccOffset += currCC.start - prevCC.start;\n currCC.new = false;\n currCC = prevCC;\n prevCC = vttCCs[currCC.prevCC];\n }\n vttCCs.presentationOffset = presentationTime;\n};\nfunction parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) {\n const parser = new VTTParser();\n // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n // Uint8Array.prototype.reduce is not implemented in IE11\n const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, '\\n').split('\\n');\n const cues = [];\n const init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0;\n let cueTime = '00:00.000';\n let timestampMapMPEGTS = 0;\n let timestampMapLOCAL = 0;\n let parsingError;\n let inHeader = true;\n parser.oncue = function (cue) {\n // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.\n const currCC = vttCCs[cc];\n let cueOffset = vttCCs.ccOffset;\n\n // Calculate subtitle PTS offset\n const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 90000;\n\n // Update offsets for new discontinuities\n if (currCC != null && currCC.new) {\n if (timestampMapLOCAL !== undefined) {\n // When local time is provided, offset = discontinuity start time - local time\n cueOffset = vttCCs.ccOffset = currCC.start;\n } else {\n calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);\n }\n }\n if (webVttMpegTsMapOffset) {\n if (!initPTS) {\n parsingError = new Error('Missing initPTS for VTT MPEGTS');\n return;\n }\n // If we have MPEGTS, offset = presentation time + discontinuity offset\n cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;\n }\n const duration = cue.endTime - cue.startTime;\n const startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 90000, timeOffset * 90000) / 90000;\n cue.startTime = Math.max(startTime, 0);\n cue.endTime = Math.max(startTime + duration, 0);\n\n //trim trailing webvtt block whitespaces\n const text = cue.text.trim();\n\n // Fix encoding of special characters\n cue.text = decodeURIComponent(encodeURIComponent(text));\n\n // If the cue was not assigned an id from the VTT file (line above the content), create one.\n if (!cue.id) {\n cue.id = generateCueId(cue.startTime, cue.endTime, text);\n }\n if (cue.endTime > 0) {\n cues.push(cue);\n }\n };\n parser.onparsingerror = function (error) {\n parsingError = error;\n };\n parser.onflush = function () {\n if (parsingError) {\n errorCallBack(parsingError);\n return;\n }\n callBack(cues);\n };\n\n // Go through contents line by line.\n vttLines.forEach(line => {\n if (inHeader) {\n // Look for X-TIMESTAMP-MAP in header.\n if (startsWith(line, 'X-TIMESTAMP-MAP=')) {\n // Once found, no more are allowed anyway, so stop searching.\n inHeader = false;\n // Extract LOCAL and MPEGTS.\n line.slice(16).split(',').forEach(timestamp => {\n if (startsWith(timestamp, 'LOCAL:')) {\n cueTime = timestamp.slice(6);\n } else if (startsWith(timestamp, 'MPEGTS:')) {\n timestampMapMPEGTS = parseInt(timestamp.slice(7));\n }\n });\n try {\n // Convert cue time to seconds\n timestampMapLOCAL = cueString2millis(cueTime) / 1000;\n } catch (error) {\n parsingError = error;\n }\n // Return without parsing X-TIMESTAMP-MAP line.\n return;\n } else if (line === '') {\n inHeader = false;\n }\n }\n // Parse line by default.\n parser.parse(line + '\\n');\n });\n parser.flush();\n}\n\nconst IMSC1_CODEC = 'stpp.ttml.im1t';\n\n// Time format: h:m:s:frames(.subframes)\nconst HMSF_REGEX = /^(\\d{2,}):(\\d{2}):(\\d{2}):(\\d{2})\\.?(\\d+)?$/;\n\n// Time format: hours, minutes, seconds, milliseconds, frames, ticks\nconst TIME_UNIT_REGEX = /^(\\d*(?:\\.\\d*)?)(h|m|s|ms|f|t)$/;\nconst textAlignToLineAlign = {\n left: 'start',\n center: 'center',\n right: 'end',\n start: 'start',\n end: 'end'\n};\nfunction parseIMSC1(payload, initPTS, callBack, errorCallBack) {\n const results = findBox(new Uint8Array(payload), ['mdat']);\n if (results.length === 0) {\n errorCallBack(new Error('Could not parse IMSC1 mdat'));\n return;\n }\n const ttmlList = results.map(mdat => utf8ArrayToStr(mdat));\n const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);\n try {\n ttmlList.forEach(ttml => callBack(parseTTML(ttml, syncTime)));\n } catch (error) {\n errorCallBack(error);\n }\n}\nfunction parseTTML(ttml, syncTime) {\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(ttml, 'text/xml');\n const tt = xmlDoc.getElementsByTagName('tt')[0];\n if (!tt) {\n throw new Error('Invalid ttml');\n }\n const defaultRateInfo = {\n frameRate: 30,\n subFrameRate: 1,\n frameRateMultiplier: 0,\n tickRate: 0\n };\n const rateInfo = Object.keys(defaultRateInfo).reduce((result, key) => {\n result[key] = tt.getAttribute(`ttp:${key}`) || defaultRateInfo[key];\n return result;\n }, {});\n const trim = tt.getAttribute('xml:space') !== 'preserve';\n const styleElements = collectionToDictionary(getElementCollection(tt, 'styling', 'style'));\n const regionElements = collectionToDictionary(getElementCollection(tt, 'layout', 'region'));\n const cueElements = getElementCollection(tt, 'body', '[begin]');\n return [].map.call(cueElements, cueElement => {\n const cueText = getTextContent(cueElement, trim);\n if (!cueText || !cueElement.hasAttribute('begin')) {\n return null;\n }\n const startTime = parseTtmlTime(cueElement.getAttribute('begin'), rateInfo);\n const duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo);\n let endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo);\n if (startTime === null) {\n throw timestampParsingError(cueElement);\n }\n if (endTime === null) {\n if (duration === null) {\n throw timestampParsingError(cueElement);\n }\n endTime = startTime + duration;\n }\n const cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);\n cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);\n const region = regionElements[cueElement.getAttribute('region')];\n const style = styleElements[cueElement.getAttribute('style')];\n\n // Apply styles to cue\n const styles = getTtmlStyles(region, style, styleElements);\n const {\n textAlign\n } = styles;\n if (textAlign) {\n // cue.positionAlign not settable in FF~2016\n const lineAlign = textAlignToLineAlign[textAlign];\n if (lineAlign) {\n cue.lineAlign = lineAlign;\n }\n cue.align = textAlign;\n }\n _extends(cue, styles);\n return cue;\n }).filter(cue => cue !== null);\n}\nfunction getElementCollection(fromElement, parentName, childName) {\n const parent = fromElement.getElementsByTagName(parentName)[0];\n if (parent) {\n return [].slice.call(parent.querySelectorAll(childName));\n }\n return [];\n}\nfunction collectionToDictionary(elementsWithId) {\n return elementsWithId.reduce((dict, element) => {\n const id = element.getAttribute('xml:id');\n if (id) {\n dict[id] = element;\n }\n return dict;\n }, {});\n}\nfunction getTextContent(element, trim) {\n return [].slice.call(element.childNodes).reduce((str, node, i) => {\n var _node$childNodes;\n if (node.nodeName === 'br' && i) {\n return str + '\\n';\n }\n if ((_node$childNodes = node.childNodes) != null && _node$childNodes.length) {\n return getTextContent(node, trim);\n } else if (trim) {\n return str + node.textContent.trim().replace(/\\s+/g, ' ');\n }\n return str + node.textContent;\n }, '');\n}\nfunction getTtmlStyles(region, style, styleElements) {\n const ttsNs = 'http://www.w3.org/ns/ttml#styling';\n let regionStyle = null;\n const styleAttributes = ['displayAlign', 'textAlign', 'color', 'backgroundColor', 'fontSize', 'fontFamily'\n // 'fontWeight',\n // 'lineHeight',\n // 'wrapOption',\n // 'fontStyle',\n // 'direction',\n // 'writingMode'\n ];\n const regionStyleName = region != null && region.hasAttribute('style') ? region.getAttribute('style') : null;\n if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {\n regionStyle = styleElements[regionStyleName];\n }\n return styleAttributes.reduce((styles, name) => {\n const value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name);\n if (value) {\n styles[name] = value;\n }\n return styles;\n }, {});\n}\nfunction getAttributeNS(element, ns, name) {\n if (!element) {\n return null;\n }\n return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;\n}\nfunction timestampParsingError(node) {\n return new Error(`Could not parse ttml timestamp ${node}`);\n}\nfunction parseTtmlTime(timeAttributeValue, rateInfo) {\n if (!timeAttributeValue) {\n return null;\n }\n let seconds = parseTimeStamp(timeAttributeValue);\n if (seconds === null) {\n if (HMSF_REGEX.test(timeAttributeValue)) {\n seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);\n } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {\n seconds = parseTimeUnits(timeAttributeValue, rateInfo);\n }\n }\n return seconds;\n}\nfunction parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {\n const m = HMSF_REGEX.exec(timeAttributeValue);\n const frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;\n return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;\n}\nfunction parseTimeUnits(timeAttributeValue, rateInfo) {\n const m = TIME_UNIT_REGEX.exec(timeAttributeValue);\n const value = Number(m[1]);\n const unit = m[2];\n switch (unit) {\n case 'h':\n return value * 3600;\n case 'm':\n return value * 60;\n case 'ms':\n return value * 1000;\n case 'f':\n return value / rateInfo.frameRate;\n case 't':\n return value / rateInfo.tickRate;\n }\n return value;\n}\n\nclass OutputFilter {\n constructor(timelineController, trackName) {\n this.timelineController = void 0;\n this.cueRanges = [];\n this.trackName = void 0;\n this.startTime = null;\n this.endTime = null;\n this.screen = null;\n this.timelineController = timelineController;\n this.trackName = trackName;\n }\n dispatchCue() {\n if (this.startTime === null) {\n return;\n }\n this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);\n this.startTime = null;\n }\n newCue(startTime, endTime, screen) {\n if (this.startTime === null || this.startTime > startTime) {\n this.startTime = startTime;\n }\n this.endTime = endTime;\n this.screen = screen;\n this.timelineController.createCaptionsTrack(this.trackName);\n }\n reset() {\n this.cueRanges = [];\n this.startTime = null;\n }\n}\n\nclass TimelineController {\n constructor(hls) {\n this.hls = void 0;\n this.media = null;\n this.config = void 0;\n this.enabled = true;\n this.Cues = void 0;\n this.textTracks = [];\n this.tracks = [];\n this.initPTS = [];\n this.unparsedVttFrags = [];\n this.captionsTracks = {};\n this.nonNativeCaptionsTracks = {};\n this.cea608Parser1 = void 0;\n this.cea608Parser2 = void 0;\n this.lastCc = -1;\n // Last video (CEA-608) fragment CC\n this.lastSn = -1;\n // Last video (CEA-608) fragment MSN\n this.lastPartIndex = -1;\n // Last video (CEA-608) fragment Part Index\n this.prevCC = -1;\n // Last subtitle fragment CC\n this.vttCCs = newVTTCCs();\n this.captionsProperties = void 0;\n this.hls = hls;\n this.config = hls.config;\n this.Cues = hls.config.cueHandler;\n this.captionsProperties = {\n textTrack1: {\n label: this.config.captionsTextTrack1Label,\n languageCode: this.config.captionsTextTrack1LanguageCode\n },\n textTrack2: {\n label: this.config.captionsTextTrack2Label,\n languageCode: this.config.captionsTextTrack2LanguageCode\n },\n textTrack3: {\n label: this.config.captionsTextTrack3Label,\n languageCode: this.config.captionsTextTrack3LanguageCode\n },\n textTrack4: {\n label: this.config.captionsTextTrack4Label,\n languageCode: this.config.captionsTextTrack4LanguageCode\n }\n };\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.on(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);\n hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);\n hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n }\n destroy() {\n const {\n hls\n } = this;\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.off(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);\n hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);\n hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n // @ts-ignore\n this.hls = this.config = this.media = null;\n this.cea608Parser1 = this.cea608Parser2 = undefined;\n }\n initCea608Parsers() {\n const channel1 = new OutputFilter(this, 'textTrack1');\n const channel2 = new OutputFilter(this, 'textTrack2');\n const channel3 = new OutputFilter(this, 'textTrack3');\n const channel4 = new OutputFilter(this, 'textTrack4');\n this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);\n this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);\n }\n addCues(trackName, startTime, endTime, screen, cueRanges) {\n // skip cues which overlap more than 50% with previously parsed time ranges\n let merged = false;\n for (let i = cueRanges.length; i--;) {\n const cueRange = cueRanges[i];\n const overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);\n if (overlap >= 0) {\n cueRange[0] = Math.min(cueRange[0], startTime);\n cueRange[1] = Math.max(cueRange[1], endTime);\n merged = true;\n if (overlap / (endTime - startTime) > 0.5) {\n return;\n }\n }\n }\n if (!merged) {\n cueRanges.push([startTime, endTime]);\n }\n if (this.config.renderTextTracksNatively) {\n const track = this.captionsTracks[trackName];\n this.Cues.newCue(track, startTime, endTime, screen);\n } else {\n const cues = this.Cues.newCue(null, startTime, endTime, screen);\n this.hls.trigger(Events.CUES_PARSED, {\n type: 'captions',\n cues,\n track: trackName\n });\n }\n }\n\n // Triggered when an initial PTS is found; used for synchronisation of WebVTT.\n onInitPtsFound(event, {\n frag,\n id,\n initPTS,\n timescale\n }) {\n const {\n unparsedVttFrags\n } = this;\n if (id === PlaylistLevelType.MAIN) {\n this.initPTS[frag.cc] = {\n baseTime: initPTS,\n timescale\n };\n }\n\n // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.\n // Parse any unparsed fragments upon receiving the initial PTS.\n if (unparsedVttFrags.length) {\n this.unparsedVttFrags = [];\n unparsedVttFrags.forEach(frag => {\n this.onFragLoaded(Events.FRAG_LOADED, frag);\n });\n }\n }\n getExistingTrack(label, language) {\n const {\n media\n } = this;\n if (media) {\n for (let i = 0; i < media.textTracks.length; i++) {\n const textTrack = media.textTracks[i];\n if (canReuseVttTextTrack(textTrack, {\n name: label,\n lang: language,\n characteristics: 'transcribes-spoken-dialog,describes-music-and-sound'})) {\n return textTrack;\n }\n }\n }\n return null;\n }\n createCaptionsTrack(trackName) {\n if (this.config.renderTextTracksNatively) {\n this.createNativeTrack(trackName);\n } else {\n this.createNonNativeTrack(trackName);\n }\n }\n createNativeTrack(trackName) {\n if (this.captionsTracks[trackName]) {\n return;\n }\n const {\n captionsProperties,\n captionsTracks,\n media\n } = this;\n const {\n label,\n languageCode\n } = captionsProperties[trackName];\n // Enable reuse of existing text track.\n const existingTrack = this.getExistingTrack(label, languageCode);\n if (!existingTrack) {\n const textTrack = this.createTextTrack('captions', label, languageCode);\n if (textTrack) {\n // Set a special property on the track so we know it's managed by Hls.js\n textTrack[trackName] = true;\n captionsTracks[trackName] = textTrack;\n }\n } else {\n captionsTracks[trackName] = existingTrack;\n clearCurrentCues(captionsTracks[trackName]);\n sendAddTrackEvent(captionsTracks[trackName], media);\n }\n }\n createNonNativeTrack(trackName) {\n if (this.nonNativeCaptionsTracks[trackName]) {\n return;\n }\n // Create a list of a single track for the provider to consume\n const trackProperties = this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n const label = trackProperties.label;\n const track = {\n _id: trackName,\n label,\n kind: 'captions',\n default: trackProperties.media ? !!trackProperties.media.default : false,\n closedCaptions: trackProperties.media\n };\n this.nonNativeCaptionsTracks[trackName] = track;\n this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {\n tracks: [track]\n });\n }\n createTextTrack(kind, label, lang) {\n const media = this.media;\n if (!media) {\n return;\n }\n return media.addTextTrack(kind, label, lang);\n }\n onMediaAttaching(event, data) {\n this.media = data.media;\n if (!data.mediaSource) {\n this._cleanTracks();\n }\n }\n onMediaDetaching(event, data) {\n const transferringMedia = !!data.transferMedia;\n this.media = null;\n if (transferringMedia) {\n return;\n }\n const {\n captionsTracks\n } = this;\n Object.keys(captionsTracks).forEach(trackName => {\n clearCurrentCues(captionsTracks[trackName]);\n delete captionsTracks[trackName];\n });\n this.nonNativeCaptionsTracks = {};\n }\n onManifestLoading() {\n // Detect discontinuity in video fragment (CEA-608) parsing\n this.lastCc = -1;\n this.lastSn = -1;\n this.lastPartIndex = -1;\n // Detect discontinuity in subtitle manifests\n this.prevCC = -1;\n this.vttCCs = newVTTCCs();\n // Reset tracks\n this._cleanTracks();\n this.tracks = [];\n this.captionsTracks = {};\n this.nonNativeCaptionsTracks = {};\n this.textTracks = [];\n this.unparsedVttFrags = [];\n this.initPTS = [];\n if (this.cea608Parser1 && this.cea608Parser2) {\n this.cea608Parser1.reset();\n this.cea608Parser2.reset();\n }\n }\n _cleanTracks() {\n // clear outdated subtitles\n const {\n media\n } = this;\n if (!media) {\n return;\n }\n const textTracks = media.textTracks;\n if (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n clearCurrentCues(textTracks[i]);\n }\n }\n }\n onSubtitleTracksUpdated(event, data) {\n const tracks = data.subtitleTracks || [];\n const hasIMSC1 = tracks.some(track => track.textCodec === IMSC1_CODEC);\n if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {\n const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);\n if (listIsIdentical) {\n this.tracks = tracks;\n return;\n }\n this.textTracks = [];\n this.tracks = tracks;\n if (this.config.renderTextTracksNatively) {\n const media = this.media;\n const inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null;\n this.tracks.forEach((track, index) => {\n // Reuse tracks with the same label and lang, but do not reuse 608/708 tracks\n let textTrack;\n if (inUseTracks) {\n let inUseTrack = null;\n for (let i = 0; i < inUseTracks.length; i++) {\n if (inUseTracks[i] && canReuseVttTextTrack(inUseTracks[i], track)) {\n inUseTrack = inUseTracks[i];\n inUseTracks[i] = null;\n break;\n }\n }\n if (inUseTrack) {\n textTrack = inUseTrack;\n }\n }\n if (textTrack) {\n clearCurrentCues(textTrack);\n } else {\n const textTrackKind = captionsOrSubtitlesFromCharacteristics(track);\n textTrack = this.createTextTrack(textTrackKind, track.name, track.lang);\n if (textTrack) {\n textTrack.mode = 'disabled';\n }\n }\n if (textTrack) {\n this.textTracks.push(textTrack);\n }\n });\n // Warn when video element has captions or subtitle TextTracks carried over from another source\n if (inUseTracks != null && inUseTracks.length) {\n const unusedTextTracks = inUseTracks.filter(t => t !== null).map(t => t.label);\n if (unusedTextTracks.length) {\n this.hls.logger.warn(`Media element contains unused subtitle tracks: ${unusedTextTracks.join(', ')}. Replace media element for each source to clear TextTracks and captions menu.`);\n }\n }\n } else if (this.tracks.length) {\n // Create a list of tracks for the provider to consume\n const tracksList = this.tracks.map(track => {\n return {\n label: track.name,\n kind: track.type.toLowerCase(),\n default: track.default,\n subtitleTrack: track\n };\n });\n this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {\n tracks: tracksList\n });\n }\n }\n }\n onManifestLoaded(event, data) {\n if (this.config.enableCEA708Captions && data.captions) {\n data.captions.forEach(captionsTrack => {\n const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);\n if (!instreamIdMatch) {\n return;\n }\n const trackName = `textTrack${instreamIdMatch[1]}`;\n const trackProperties = this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n trackProperties.label = captionsTrack.name;\n if (captionsTrack.lang) {\n // optional attribute\n trackProperties.languageCode = captionsTrack.lang;\n }\n trackProperties.media = captionsTrack;\n });\n }\n }\n closedCaptionsForLevel(frag) {\n const level = this.hls.levels[frag.level];\n return level == null ? void 0 : level.attrs['CLOSED-CAPTIONS'];\n }\n onFragLoading(event, data) {\n // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {\n var _data$part$index, _data$part;\n const {\n cea608Parser1,\n cea608Parser2,\n lastSn\n } = this;\n const {\n cc,\n sn\n } = data.frag;\n const partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1;\n if (cea608Parser1 && cea608Parser2) {\n if (sn !== lastSn + 1 || sn === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) {\n cea608Parser1.reset();\n cea608Parser2.reset();\n }\n }\n this.lastCc = cc;\n this.lastSn = sn;\n this.lastPartIndex = partIndex;\n }\n }\n onFragLoaded(event, data) {\n const {\n frag,\n payload\n } = data;\n if (frag.type === PlaylistLevelType.SUBTITLE) {\n // If fragment is subtitle type, parse as WebVTT.\n if (payload.byteLength) {\n const decryptData = frag.decryptdata;\n // fragment after decryption has a stats object\n const decrypted = 'stats' in data;\n // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.\n if (decryptData == null || !decryptData.encrypted || decrypted) {\n const trackPlaylistMedia = this.tracks[frag.level];\n const vttCCs = this.vttCCs;\n if (!vttCCs[frag.cc]) {\n vttCCs[frag.cc] = {\n start: frag.start,\n prevCC: this.prevCC,\n new: true\n };\n this.prevCC = frag.cc;\n }\n if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) {\n this._parseIMSC1(frag, payload);\n } else {\n this._parseVTTs(data);\n }\n }\n } else {\n // In case there is no payload, finish unsuccessfully.\n this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: false,\n frag,\n error: new Error('Empty subtitle payload')\n });\n }\n }\n }\n _parseIMSC1(frag, payload) {\n const hls = this.hls;\n parseIMSC1(payload, this.initPTS[frag.cc], cues => {\n this._appendCues(cues, frag.level);\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: true,\n frag: frag\n });\n }, error => {\n hls.logger.log(`Failed to parse IMSC1: ${error}`);\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: false,\n frag: frag,\n error\n });\n });\n }\n _parseVTTs(data) {\n var _frag$initSegment;\n const {\n frag,\n payload\n } = data;\n // We need an initial synchronisation PTS. Store fragments as long as none has arrived\n const {\n initPTS,\n unparsedVttFrags\n } = this;\n const maxAvCC = initPTS.length - 1;\n if (!initPTS[frag.cc] && maxAvCC === -1) {\n unparsedVttFrags.push(data);\n return;\n }\n const hls = this.hls;\n // Parse the WebVTT file contents.\n const payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)).buffer : payload;\n parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, cues => {\n this._appendCues(cues, frag.level);\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: true,\n frag: frag\n });\n }, error => {\n const missingInitPTS = error.message === 'Missing initPTS for VTT MPEGTS';\n if (missingInitPTS) {\n unparsedVttFrags.push(data);\n } else {\n this._fallbackToIMSC1(frag, payload);\n }\n // Something went wrong while parsing. Trigger event with success false.\n hls.logger.log(`Failed to parse VTT cue: ${error}`);\n if (missingInitPTS && maxAvCC > frag.cc) {\n return;\n }\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: false,\n frag: frag,\n error\n });\n });\n }\n _fallbackToIMSC1(frag, payload) {\n // If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result\n const trackPlaylistMedia = this.tracks[frag.level];\n if (!trackPlaylistMedia.textCodec) {\n parseIMSC1(payload, this.initPTS[frag.cc], () => {\n trackPlaylistMedia.textCodec = IMSC1_CODEC;\n this._parseIMSC1(frag, payload);\n }, () => {\n trackPlaylistMedia.textCodec = 'wvtt';\n });\n }\n }\n _appendCues(cues, fragLevel) {\n const hls = this.hls;\n if (this.config.renderTextTracksNatively) {\n const textTrack = this.textTracks[fragLevel];\n // WebVTTParser.parse is an async method and if the currently selected text track mode is set to \"disabled\"\n // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null\n // and trying to access getCueById method of cues will throw an exception\n // Because we check if the mode is disabled, we can force check `cues` below. They can't be null.\n if (!textTrack || textTrack.mode === 'disabled') {\n return;\n }\n cues.forEach(cue => addCueToTrack(textTrack, cue));\n } else {\n const currentTrack = this.tracks[fragLevel];\n if (!currentTrack) {\n return;\n }\n const track = currentTrack.default ? 'default' : 'subtitles' + fragLevel;\n hls.trigger(Events.CUES_PARSED, {\n type: 'subtitles',\n cues,\n track\n });\n }\n }\n onFragDecrypted(event, data) {\n const {\n frag\n } = data;\n if (frag.type === PlaylistLevelType.SUBTITLE) {\n this.onFragLoaded(Events.FRAG_LOADED, data);\n }\n }\n onSubtitleTracksCleared() {\n this.tracks = [];\n this.captionsTracks = {};\n }\n onFragParsingUserdata(event, data) {\n if (!this.enabled || !this.config.enableCEA708Captions) {\n return;\n }\n const {\n frag,\n samples\n } = data;\n if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === 'NONE') {\n return;\n }\n // If the event contains captions (found in the bytes property), push all bytes into the parser immediately\n // It will create the proper timestamps based on the PTS value\n for (let i = 0; i < samples.length; i++) {\n const ccBytes = samples[i].bytes;\n if (ccBytes) {\n if (!this.cea608Parser1) {\n this.initCea608Parsers();\n }\n const ccdatas = this.extractCea608Data(ccBytes);\n this.cea608Parser1.addData(samples[i].pts, ccdatas[0]);\n this.cea608Parser2.addData(samples[i].pts, ccdatas[1]);\n }\n }\n }\n onBufferFlushing(event, {\n startOffset,\n endOffset,\n endOffsetSubtitles,\n type\n }) {\n const {\n media\n } = this;\n if (!media || media.currentTime < endOffset) {\n return;\n }\n // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed\n // Forward cues are never removed because we can loose streamed 608 content from recent fragments\n if (!type || type === 'video') {\n const {\n captionsTracks\n } = this;\n Object.keys(captionsTracks).forEach(trackName => removeCuesInRange(captionsTracks[trackName], startOffset, endOffset));\n }\n if (this.config.renderTextTracksNatively) {\n // Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed\n if (startOffset === 0 && endOffsetSubtitles !== undefined) {\n const {\n textTracks\n } = this;\n Object.keys(textTracks).forEach(trackName => removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles));\n }\n }\n }\n extractCea608Data(byteArray) {\n const actualCCBytes = [[], []];\n const count = byteArray[0] & 0x1f;\n let position = 2;\n for (let j = 0; j < count; j++) {\n const tmpByte = byteArray[position++];\n const ccbyte1 = 0x7f & byteArray[position++];\n const ccbyte2 = 0x7f & byteArray[position++];\n if (ccbyte1 === 0 && ccbyte2 === 0) {\n continue;\n }\n const ccValid = (0x04 & tmpByte) !== 0; // Support all four channels\n if (ccValid) {\n const ccType = 0x03 & tmpByte;\n if (0x00 /* CEA608 field1*/ === ccType || 0x01 /* CEA608 field2*/ === ccType) {\n // Exclude CEA708 CC data.\n actualCCBytes[ccType].push(ccbyte1);\n actualCCBytes[ccType].push(ccbyte2);\n }\n }\n }\n return actualCCBytes;\n }\n}\nfunction captionsOrSubtitlesFromCharacteristics(track) {\n if (track.characteristics) {\n if (/transcribes-spoken-dialog/gi.test(track.characteristics) && /describes-music-and-sound/gi.test(track.characteristics)) {\n return 'captions';\n }\n }\n return 'subtitles';\n}\nfunction canReuseVttTextTrack(inUseTrack, manifestTrack) {\n return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack);\n}\nfunction intersection(x1, x2, y1, y2) {\n return Math.min(x2, y2) - Math.max(x1, y1);\n}\nfunction newVTTCCs() {\n return {\n ccOffset: 0,\n presentationOffset: 0,\n 0: {\n start: 0,\n prevCC: -1,\n new: true\n }\n };\n}\n\nconst WHITESPACE_CHAR = /\\s/;\nconst Cues = {\n newCue(track, startTime, endTime, captionScreen) {\n const result = [];\n let row;\n // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers\n let cue;\n let indenting;\n let indent;\n let text;\n const Cue = self.VTTCue || self.TextTrackCue;\n for (let r = 0; r < captionScreen.rows.length; r++) {\n row = captionScreen.rows[r];\n indenting = true;\n indent = 0;\n text = '';\n if (!row.isEmpty()) {\n var _track$cues;\n for (let c = 0; c < row.chars.length; c++) {\n if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {\n indent++;\n } else {\n text += row.chars[c].uchar;\n indenting = false;\n }\n }\n // To be used for cleaning-up orphaned roll-up captions\n row.cueStartTime = startTime;\n\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n if (startTime === endTime) {\n endTime += 0.0001;\n }\n if (indent >= 16) {\n indent--;\n } else {\n indent++;\n }\n const cueText = fixLineBreaks(text.trim());\n const id = generateCueId(startTime, endTime, cueText);\n\n // If this cue already exists in the track do not push it\n if (!(track != null && (_track$cues = track.cues) != null && _track$cues.getCueById(id))) {\n cue = new Cue(startTime, endTime, cueText);\n cue.id = id;\n cue.line = r + 1;\n cue.align = 'left';\n // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)\n // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608\n // Firefox throws an exception and captions break with out of bounds 0-100 values\n cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);\n result.push(cue);\n }\n }\n }\n if (track && result.length) {\n // Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome\n result.sort((cueA, cueB) => {\n if (cueA.line === 'auto' || cueB.line === 'auto') {\n return 0;\n }\n if (cueA.line > 8 && cueB.line > 8) {\n return cueB.line - cueA.line;\n }\n return cueA.line - cueB.line;\n });\n result.forEach(cue => addCueToTrack(track, cue));\n }\n return result;\n }\n};\n\nfunction fetchSupported() {\n if (\n // @ts-ignore\n self.fetch && self.AbortController && self.ReadableStream && self.Request) {\n try {\n new self.ReadableStream({}); // eslint-disable-line no-new\n return true;\n } catch (e) {\n /* noop */\n }\n }\n return false;\n}\nconst BYTERANGE = /(\\d+)-(\\d+)\\/(\\d+)/;\nclass FetchLoader {\n constructor(config) {\n this.fetchSetup = void 0;\n this.requestTimeout = void 0;\n this.request = null;\n this.response = null;\n this.controller = void 0;\n this.context = null;\n this.config = null;\n this.callbacks = null;\n this.stats = void 0;\n this.loader = null;\n this.fetchSetup = config.fetchSetup || getRequest;\n this.controller = new self.AbortController();\n this.stats = new LoadStats();\n }\n destroy() {\n this.loader = this.callbacks = this.context = this.config = this.request = null;\n this.abortInternal();\n this.response = null;\n // @ts-ignore\n this.fetchSetup = this.controller = this.stats = null;\n }\n abortInternal() {\n if (this.controller && !this.stats.loading.end) {\n this.stats.aborted = true;\n this.controller.abort();\n }\n }\n abort() {\n var _this$callbacks;\n this.abortInternal();\n if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {\n this.callbacks.onAbort(this.stats, this.context, this.response);\n }\n }\n load(context, config, callbacks) {\n const stats = this.stats;\n if (stats.loading.start) {\n throw new Error('Loader can only be used once.');\n }\n stats.loading.start = self.performance.now();\n const initParams = getRequestParameters(context, this.controller.signal);\n const isArrayBuffer = context.responseType === 'arraybuffer';\n const LENGTH = isArrayBuffer ? 'byteLength' : 'length';\n const {\n maxTimeToFirstByteMs,\n maxLoadTimeMs\n } = config.loadPolicy;\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.request = this.fetchSetup(context, initParams);\n self.clearTimeout(this.requestTimeout);\n config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(() => {\n if (this.callbacks) {\n this.abortInternal();\n this.callbacks.onTimeout(stats, context, this.response);\n }\n }, config.timeout);\n const fetchPromise = isPromise(this.request) ? this.request.then(self.fetch) : self.fetch(this.request);\n fetchPromise.then(response => {\n var _this$callbacks2;\n this.response = this.loader = response;\n const first = Math.max(self.performance.now(), stats.loading.start);\n self.clearTimeout(this.requestTimeout);\n config.timeout = maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(() => {\n if (this.callbacks) {\n this.abortInternal();\n this.callbacks.onTimeout(stats, context, this.response);\n }\n }, maxLoadTimeMs - (first - stats.loading.start));\n if (!response.ok) {\n const {\n status,\n statusText\n } = response;\n throw new FetchError(statusText || 'fetch, bad network response', status, response);\n }\n stats.loading.first = first;\n stats.total = getContentLength(response.headers) || stats.total;\n const onProgress = (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onProgress;\n if (onProgress && isFiniteNumber(config.highWaterMark)) {\n return this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);\n }\n if (isArrayBuffer) {\n return response.arrayBuffer();\n }\n if (context.responseType === 'json') {\n return response.json();\n }\n return response.text();\n }).then(responseData => {\n var _this$callbacks3, _this$callbacks4;\n const response = this.response;\n if (!response) {\n throw new Error('loader destroyed');\n }\n self.clearTimeout(this.requestTimeout);\n stats.loading.end = Math.max(self.performance.now(), stats.loading.first);\n const total = responseData[LENGTH];\n if (total) {\n stats.loaded = stats.total = total;\n }\n const loaderResponse = {\n url: response.url,\n data: responseData,\n code: response.status\n };\n const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;\n if (onProgress && !isFiniteNumber(config.highWaterMark)) {\n onProgress(stats, context, responseData, response);\n }\n (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(loaderResponse, stats, context, response);\n }).catch(error => {\n var _this$callbacks5;\n self.clearTimeout(this.requestTimeout);\n if (stats.aborted) {\n return;\n }\n // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior\n // when destroying, 'error' itself can be undefined\n const code = !error ? 0 : error.code || 0;\n const text = !error ? null : error.message;\n (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({\n code,\n text\n }, context, error ? error.details : null, stats);\n });\n }\n getCacheAge() {\n let result = null;\n if (this.response) {\n const ageHeader = this.response.headers.get('age');\n result = ageHeader ? parseFloat(ageHeader) : null;\n }\n return result;\n }\n getResponseHeader(name) {\n return this.response ? this.response.headers.get(name) : null;\n }\n loadProgressively(response, stats, context, highWaterMark = 0, onProgress) {\n const chunkCache = new ChunkCache();\n const reader = response.body.getReader();\n const pump = () => {\n return reader.read().then(data => {\n if (data.done) {\n if (chunkCache.dataLength) {\n onProgress(stats, context, chunkCache.flush().buffer, response);\n }\n return Promise.resolve(new ArrayBuffer(0));\n }\n const chunk = data.value;\n const len = chunk.length;\n stats.loaded += len;\n if (len < highWaterMark || chunkCache.dataLength) {\n // The current chunk is too small to to be emitted or the cache already has data\n // Push it to the cache\n chunkCache.push(chunk);\n if (chunkCache.dataLength >= highWaterMark) {\n // flush in order to join the typed arrays\n onProgress(stats, context, chunkCache.flush().buffer, response);\n }\n } else {\n // If there's nothing cached already, and the chache is large enough\n // just emit the progress event\n onProgress(stats, context, chunk.buffer, response);\n }\n return pump();\n }).catch(() => {\n /* aborted */\n return Promise.reject();\n });\n };\n return pump();\n }\n}\nfunction getRequestParameters(context, signal) {\n const initParams = {\n method: 'GET',\n mode: 'cors',\n credentials: 'same-origin',\n signal,\n headers: new self.Headers(_extends({}, context.headers))\n };\n if (context.rangeEnd) {\n initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));\n }\n return initParams;\n}\nfunction getByteRangeLength(byteRangeHeader) {\n const result = BYTERANGE.exec(byteRangeHeader);\n if (result) {\n return parseInt(result[2]) - parseInt(result[1]) + 1;\n }\n}\nfunction getContentLength(headers) {\n const contentRange = headers.get('Content-Range');\n if (contentRange) {\n const byteRangeLength = getByteRangeLength(contentRange);\n if (isFiniteNumber(byteRangeLength)) {\n return byteRangeLength;\n }\n }\n const contentLength = headers.get('Content-Length');\n if (contentLength) {\n return parseInt(contentLength);\n }\n}\nfunction getRequest(context, initParams) {\n return new self.Request(context.url, initParams);\n}\nclass FetchError extends Error {\n constructor(message, code, details) {\n super(message);\n this.code = void 0;\n this.details = void 0;\n this.code = code;\n this.details = details;\n }\n}\n\nconst AGE_HEADER_LINE_REGEX = /^age:\\s*[\\d.]+\\s*$/im;\nclass XhrLoader {\n constructor(config) {\n this.xhrSetup = void 0;\n this.requestTimeout = void 0;\n this.retryTimeout = void 0;\n this.retryDelay = void 0;\n this.config = null;\n this.callbacks = null;\n this.context = null;\n this.loader = null;\n this.stats = void 0;\n this.xhrSetup = config ? config.xhrSetup || null : null;\n this.stats = new LoadStats();\n this.retryDelay = 0;\n }\n destroy() {\n this.callbacks = null;\n this.abortInternal();\n this.loader = null;\n this.config = null;\n this.context = null;\n this.xhrSetup = null;\n }\n abortInternal() {\n const loader = this.loader;\n self.clearTimeout(this.requestTimeout);\n self.clearTimeout(this.retryTimeout);\n if (loader) {\n loader.onreadystatechange = null;\n loader.onprogress = null;\n if (loader.readyState !== 4) {\n this.stats.aborted = true;\n loader.abort();\n }\n }\n }\n abort() {\n var _this$callbacks;\n this.abortInternal();\n if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {\n this.callbacks.onAbort(this.stats, this.context, this.loader);\n }\n }\n load(context, config, callbacks) {\n if (this.stats.loading.start) {\n throw new Error('Loader can only be used once.');\n }\n this.stats.loading.start = self.performance.now();\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.loadInternal();\n }\n loadInternal() {\n const {\n config,\n context\n } = this;\n if (!config || !context) {\n return;\n }\n const xhr = this.loader = new self.XMLHttpRequest();\n const stats = this.stats;\n stats.loading.first = 0;\n stats.loaded = 0;\n stats.aborted = false;\n const xhrSetup = this.xhrSetup;\n if (xhrSetup) {\n Promise.resolve().then(() => {\n if (this.loader !== xhr || this.stats.aborted) return;\n return xhrSetup(xhr, context.url);\n }).catch(error => {\n if (this.loader !== xhr || this.stats.aborted) return;\n xhr.open('GET', context.url, true);\n return xhrSetup(xhr, context.url);\n }).then(() => {\n if (this.loader !== xhr || this.stats.aborted) return;\n this.openAndSendXhr(xhr, context, config);\n }).catch(error => {\n var _this$callbacks2;\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n (_this$callbacks2 = this.callbacks) == null ? void 0 : _this$callbacks2.onError({\n code: xhr.status,\n text: error.message\n }, context, xhr, stats);\n return;\n });\n } else {\n this.openAndSendXhr(xhr, context, config);\n }\n }\n openAndSendXhr(xhr, context, config) {\n if (!xhr.readyState) {\n xhr.open('GET', context.url, true);\n }\n const headers = context.headers;\n const {\n maxTimeToFirstByteMs,\n maxLoadTimeMs\n } = config.loadPolicy;\n if (headers) {\n for (const header in headers) {\n xhr.setRequestHeader(header, headers[header]);\n }\n }\n if (context.rangeEnd) {\n xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));\n }\n xhr.onreadystatechange = this.readystatechange.bind(this);\n xhr.onprogress = this.loadprogress.bind(this);\n xhr.responseType = context.responseType;\n // setup timeout before we perform request\n self.clearTimeout(this.requestTimeout);\n config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);\n xhr.send();\n }\n readystatechange() {\n const {\n context,\n loader: xhr,\n stats\n } = this;\n if (!context || !xhr) {\n return;\n }\n const readyState = xhr.readyState;\n const config = this.config;\n\n // don't proceed if xhr has been aborted\n if (stats.aborted) {\n return;\n }\n\n // >= HEADERS_RECEIVED\n if (readyState >= 2) {\n if (stats.loading.first === 0) {\n stats.loading.first = Math.max(self.performance.now(), stats.loading.start);\n // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {\n self.clearTimeout(this.requestTimeout);\n config.timeout = config.loadPolicy.maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));\n }\n }\n if (readyState === 4) {\n self.clearTimeout(this.requestTimeout);\n xhr.onreadystatechange = null;\n xhr.onprogress = null;\n const status = xhr.status;\n // http status between 200 to 299 are all successful\n const useResponseText = xhr.responseType === 'text' ? xhr.responseText : null;\n if (status >= 200 && status < 300) {\n const data = useResponseText != null ? useResponseText : xhr.response;\n if (data != null) {\n var _this$callbacks3, _this$callbacks4;\n stats.loading.end = Math.max(self.performance.now(), stats.loading.first);\n const len = xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;\n stats.loaded = stats.total = len;\n stats.bwEstimate = stats.total * 8000 / (stats.loading.end - stats.loading.first);\n const onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;\n if (onProgress) {\n onProgress(stats, context, data, xhr);\n }\n const _response = {\n url: xhr.responseURL,\n data: data,\n code: status\n };\n (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(_response, stats, context, xhr);\n return;\n }\n }\n\n // Handle bad status or nullish response\n const retryConfig = config.loadPolicy.errorRetry;\n const retryCount = stats.retry;\n // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n const response = {\n url: context.url,\n data: undefined,\n code: status\n };\n if (shouldRetry(retryConfig, retryCount, false, response)) {\n this.retry(retryConfig);\n } else {\n var _this$callbacks5;\n logger.error(`${status} while loading ${context.url}`);\n (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({\n code: status,\n text: xhr.statusText\n }, context, xhr, stats);\n }\n }\n }\n }\n loadtimeout() {\n if (!this.config) return;\n const retryConfig = this.config.loadPolicy.timeoutRetry;\n const retryCount = this.stats.retry;\n if (shouldRetry(retryConfig, retryCount, true)) {\n this.retry(retryConfig);\n } else {\n var _this$context;\n logger.warn(`timeout while loading ${(_this$context = this.context) == null ? void 0 : _this$context.url}`);\n const callbacks = this.callbacks;\n if (callbacks) {\n this.abortInternal();\n callbacks.onTimeout(this.stats, this.context, this.loader);\n }\n }\n }\n retry(retryConfig) {\n const {\n context,\n stats\n } = this;\n this.retryDelay = getRetryDelay(retryConfig, stats.retry);\n stats.retry++;\n logger.warn(`${status ? 'HTTP Status ' + status : 'Timeout'} while loading ${context == null ? void 0 : context.url}, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${this.retryDelay}ms`);\n // abort and reset internal state\n this.abortInternal();\n this.loader = null;\n // schedule retry\n self.clearTimeout(this.retryTimeout);\n this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);\n }\n loadprogress(event) {\n const stats = this.stats;\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\n }\n getCacheAge() {\n let result = null;\n if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {\n const ageHeader = this.loader.getResponseHeader('age');\n result = ageHeader ? parseFloat(ageHeader) : null;\n }\n return result;\n }\n getResponseHeader(name) {\n if (this.loader && new RegExp(`^${name}:\\\\s*[\\\\d.]+\\\\s*$`, 'im').test(this.loader.getAllResponseHeaders())) {\n return this.loader.getResponseHeader(name);\n }\n return null;\n }\n}\n\n/**\n * @deprecated use fragLoadPolicy.default\n */\n\n/**\n * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default\n */\n\nconst defaultLoadPolicy = {\n maxTimeToFirstByteMs: 8000,\n maxLoadTimeMs: 20000,\n timeoutRetry: null,\n errorRetry: null\n};\n\n/**\n * @ignore\n * If possible, keep hlsDefaultConfig shallow\n * It is cloned whenever a new Hls instance is created, by keeping the config\n * shallow the properties are cloned, and we don't end up manipulating the default\n */\nconst hlsDefaultConfig = _objectSpread2(_objectSpread2({\n autoStartLoad: true,\n // used by stream-controller\n startPosition: -1,\n // used by stream-controller\n defaultAudioCodec: undefined,\n // used by stream-controller\n debug: false,\n // used by logger\n capLevelOnFPSDrop: false,\n // used by fps-controller\n capLevelToPlayerSize: false,\n // used by cap-level-controller\n ignoreDevicePixelRatio: false,\n // used by cap-level-controller\n maxDevicePixelRatio: Number.POSITIVE_INFINITY,\n // used by cap-level-controller\n preferManagedMediaSource: true,\n initialLiveManifestSize: 1,\n // used by stream-controller\n maxBufferLength: 30,\n // used by stream-controller\n backBufferLength: Infinity,\n // used by buffer-controller\n frontBufferFlushThreshold: Infinity,\n maxBufferSize: 60 * 1000 * 1000,\n // used by stream-controller\n maxFragLookUpTolerance: 0.25,\n // used by stream-controller\n maxBufferHole: 0.1,\n // used by stream-controller and gap-controller\n detectStallWithCurrentTimeMs: 1250,\n // used by gap-controller\n highBufferWatchdogPeriod: 2,\n // used by gap-controller\n nudgeOffset: 0.1,\n // used by gap-controller\n nudgeMaxRetry: 3,\n // used by gap-controller\n nudgeOnVideoHole: true,\n // used by gap-controller\n liveSyncDurationCount: 3,\n // used by latency-controller\n liveSyncOnStallIncrease: 1,\n // used by latency-controller\n liveMaxLatencyDurationCount: Infinity,\n // used by latency-controller\n liveSyncDuration: undefined,\n // used by latency-controller\n liveMaxLatencyDuration: undefined,\n // used by latency-controller\n maxLiveSyncPlaybackRate: 1,\n // used by latency-controller\n liveDurationInfinity: false,\n // used by buffer-controller\n /**\n * @deprecated use backBufferLength\n */\n liveBackBufferLength: null,\n // used by buffer-controller\n maxMaxBufferLength: 600,\n // used by stream-controller\n enableWorker: true,\n // used by transmuxer\n workerPath: null,\n // used by transmuxer\n enableSoftwareAES: true,\n // used by decrypter\n startLevel: undefined,\n // used by level-controller\n startFragPrefetch: false,\n // used by stream-controller\n fpsDroppedMonitoringPeriod: 5000,\n // used by fps-controller\n fpsDroppedMonitoringThreshold: 0.2,\n // used by fps-controller\n appendErrorMaxRetry: 3,\n // used by buffer-controller\n ignorePlaylistParsingErrors: false,\n loader: XhrLoader,\n // loader: FetchLoader,\n fLoader: undefined,\n // used by fragment-loader\n pLoader: undefined,\n // used by playlist-loader\n xhrSetup: undefined,\n // used by xhr-loader\n licenseXhrSetup: undefined,\n // used by eme-controller\n licenseResponseCallback: undefined,\n // used by eme-controller\n abrController: AbrController,\n bufferController: BufferController,\n capLevelController: CapLevelController,\n errorController: ErrorController,\n fpsController: FPSController,\n stretchShortVideoTrack: false,\n // used by mp4-remuxer\n maxAudioFramesDrift: 1,\n // used by mp4-remuxer\n forceKeyFrameOnDiscontinuity: true,\n // used by ts-demuxer\n abrEwmaFastLive: 3,\n // used by abr-controller\n abrEwmaSlowLive: 9,\n // used by abr-controller\n abrEwmaFastVoD: 3,\n // used by abr-controller\n abrEwmaSlowVoD: 9,\n // used by abr-controller\n abrEwmaDefaultEstimate: 5e5,\n // 500 kbps // used by abr-controller\n abrEwmaDefaultEstimateMax: 5e6,\n // 5 mbps\n abrBandWidthFactor: 0.95,\n // used by abr-controller\n abrBandWidthUpFactor: 0.7,\n // used by abr-controller\n abrMaxWithRealBitrate: false,\n // used by abr-controller\n maxStarvationDelay: 4,\n // used by abr-controller\n maxLoadingDelay: 4,\n // used by abr-controller\n minAutoBitrate: 0,\n // used by hls\n emeEnabled: false,\n // used by eme-controller\n widevineLicenseUrl: undefined,\n // used by eme-controller\n drmSystems: {},\n // used by eme-controller\n drmSystemOptions: {},\n // used by eme-controller\n requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess ,\n // used by eme-controller\n testBandwidth: true,\n progressive: false,\n lowLatencyMode: true,\n cmcd: undefined,\n enableDateRangeMetadataCues: true,\n enableEmsgMetadataCues: true,\n enableEmsgKLVMetadata: false,\n enableID3MetadataCues: true,\n enableInterstitialPlayback: true,\n interstitialAppendInPlace: true,\n interstitialLiveLookAhead: 10,\n useMediaCapabilities: true,\n certLoadPolicy: {\n default: defaultLoadPolicy\n },\n keyLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 8000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 20000,\n backoff: 'linear'\n },\n errorRetry: {\n maxNumRetry: 8,\n retryDelayMs: 1000,\n maxRetryDelayMs: 20000,\n backoff: 'linear'\n }\n }\n },\n manifestLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: Infinity,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0\n },\n errorRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000\n }\n }\n },\n playlistLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0\n },\n errorRetry: {\n maxNumRetry: 2,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000\n }\n }\n },\n fragLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 120000,\n timeoutRetry: {\n maxNumRetry: 4,\n retryDelayMs: 0,\n maxRetryDelayMs: 0\n },\n errorRetry: {\n maxNumRetry: 6,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000\n }\n }\n },\n steeringManifestLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0\n },\n errorRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000\n }\n } \n },\n interstitialAssetListLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 30000,\n timeoutRetry: {\n maxNumRetry: 0,\n retryDelayMs: 0,\n maxRetryDelayMs: 0\n },\n errorRetry: {\n maxNumRetry: 0,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000\n }\n } \n },\n // These default settings are deprecated in favor of the above policies\n // and are maintained for backwards compatibility\n manifestLoadingTimeOut: 10000,\n manifestLoadingMaxRetry: 1,\n manifestLoadingRetryDelay: 1000,\n manifestLoadingMaxRetryTimeout: 64000,\n levelLoadingTimeOut: 10000,\n levelLoadingMaxRetry: 4,\n levelLoadingRetryDelay: 1000,\n levelLoadingMaxRetryTimeout: 64000,\n fragLoadingTimeOut: 20000,\n fragLoadingMaxRetry: 6,\n fragLoadingRetryDelay: 1000,\n fragLoadingMaxRetryTimeout: 64000\n}, timelineConfig()), {}, {\n subtitleStreamController: SubtitleStreamController ,\n subtitleTrackController: SubtitleTrackController ,\n timelineController: TimelineController ,\n audioStreamController: AudioStreamController ,\n audioTrackController: AudioTrackController ,\n emeController: EMEController ,\n cmcdController: CMCDController ,\n contentSteeringController: ContentSteeringController ,\n interstitialsController: InterstitialsController \n});\nfunction timelineConfig() {\n return {\n cueHandler: Cues,\n // used by timeline-controller\n enableWebVTT: true,\n // used by timeline-controller\n enableIMSC1: true,\n // used by timeline-controller\n enableCEA708Captions: true,\n // used by timeline-controller\n captionsTextTrack1Label: 'English',\n // used by timeline-controller\n captionsTextTrack1LanguageCode: 'en',\n // used by timeline-controller\n captionsTextTrack2Label: 'Spanish',\n // used by timeline-controller\n captionsTextTrack2LanguageCode: 'es',\n // used by timeline-controller\n captionsTextTrack3Label: 'Unknown CC',\n // used by timeline-controller\n captionsTextTrack3LanguageCode: '',\n // used by timeline-controller\n captionsTextTrack4Label: 'Unknown CC',\n // used by timeline-controller\n captionsTextTrack4LanguageCode: '',\n // used by timeline-controller\n renderTextTracksNatively: true\n };\n}\n\n/**\n * @ignore\n */\nfunction mergeConfig(defaultConfig, userConfig, logger) {\n if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {\n throw new Error(\"Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration\");\n }\n if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be greater than \"liveSyncDurationCount\"');\n }\n if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDuration\" must be greater than \"liveSyncDuration\"');\n }\n const defaultsCopy = deepCpy(defaultConfig);\n\n // Backwards compatibility with deprecated config values\n const deprecatedSettingTypes = ['manifest', 'level', 'frag'];\n const deprecatedSettings = ['TimeOut', 'MaxRetry', 'RetryDelay', 'MaxRetryTimeout'];\n deprecatedSettingTypes.forEach(type => {\n const policyName = `${type === 'level' ? 'playlist' : type}LoadPolicy`;\n const policyNotSet = userConfig[policyName] === undefined;\n const report = [];\n deprecatedSettings.forEach(setting => {\n const deprecatedSetting = `${type}Loading${setting}`;\n const value = userConfig[deprecatedSetting];\n if (value !== undefined && policyNotSet) {\n report.push(deprecatedSetting);\n const settings = defaultsCopy[policyName].default;\n userConfig[policyName] = {\n default: settings\n };\n switch (setting) {\n case 'TimeOut':\n settings.maxLoadTimeMs = value;\n settings.maxTimeToFirstByteMs = value;\n break;\n case 'MaxRetry':\n settings.errorRetry.maxNumRetry = value;\n settings.timeoutRetry.maxNumRetry = value;\n break;\n case 'RetryDelay':\n settings.errorRetry.retryDelayMs = value;\n settings.timeoutRetry.retryDelayMs = value;\n break;\n case 'MaxRetryTimeout':\n settings.errorRetry.maxRetryDelayMs = value;\n settings.timeoutRetry.maxRetryDelayMs = value;\n break;\n }\n }\n });\n if (report.length) {\n logger.warn(`hls.js config: \"${report.join('\", \"')}\" setting(s) are deprecated, use \"${policyName}\": ${stringify(userConfig[policyName])}`);\n }\n });\n return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);\n}\nfunction deepCpy(obj) {\n if (obj && typeof obj === 'object') {\n if (Array.isArray(obj)) {\n return obj.map(deepCpy);\n }\n return Object.keys(obj).reduce((result, key) => {\n result[key] = deepCpy(obj[key]);\n return result;\n }, {});\n }\n return obj;\n}\n\n/**\n * @ignore\n */\nfunction enableStreamingMode(config, logger) {\n const currentLoader = config.loader;\n if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {\n // If a developer has configured their own loader, respect that choice\n logger.log('[config]: Custom loader detected, cannot enable progressive streaming');\n config.progressive = false;\n } else {\n const canStreamProgressively = fetchSupported();\n if (canStreamProgressively) {\n config.loader = FetchLoader;\n config.progressive = true;\n config.enableSoftwareAES = true;\n logger.log('[config]: Progressive streaming enabled, using FetchLoader');\n }\n }\n}\n\nconst MAX_START_GAP_JUMP = 2.0;\nconst SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;\nconst SKIP_BUFFER_RANGE_START = 0.05;\nconst TICK_INTERVAL$1 = 100;\nclass GapController extends TaskLoop {\n constructor(hls, fragmentTracker) {\n super('gap-controller', hls.logger);\n this.hls = null;\n this.fragmentTracker = null;\n this.media = null;\n this.mediaSource = void 0;\n this.nudgeRetry = 0;\n this.stallReported = false;\n this.stalled = null;\n this.moved = false;\n this.seeking = false;\n this.buffered = {};\n this.lastCurrentTime = 0;\n this.ended = 0;\n this.waiting = 0;\n this.onMediaPlaying = () => {\n this.ended = 0;\n this.waiting = 0;\n };\n this.onMediaWaiting = () => {\n var _this$media;\n if ((_this$media = this.media) != null && _this$media.seeking) {\n return;\n }\n this.waiting = self.performance.now();\n this.tick();\n };\n this.onMediaEnded = () => {\n if (this.hls) {\n var _this$media2;\n // ended is set when triggering MEDIA_ENDED so that we do not trigger it again on stall or on tick with media.ended\n this.ended = ((_this$media2 = this.media) == null ? void 0 : _this$media2.currentTime) || 1;\n this.hls.trigger(Events.MEDIA_ENDED, {\n stalled: false\n });\n }\n };\n this.hls = hls;\n this.fragmentTracker = fragmentTracker;\n this.registerListeners();\n }\n registerListeners() {\n const {\n hls\n } = this;\n if (hls) {\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n }\n }\n unregisterListeners() {\n const {\n hls\n } = this;\n if (hls) {\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n }\n }\n destroy() {\n super.destroy();\n this.unregisterListeners();\n this.media = this.hls = this.fragmentTracker = null;\n this.mediaSource = undefined;\n }\n onMediaAttached(event, data) {\n this.setInterval(TICK_INTERVAL$1);\n this.mediaSource = data.mediaSource;\n const media = this.media = data.media;\n addEventListener(media, 'playing', this.onMediaPlaying);\n addEventListener(media, 'waiting', this.onMediaWaiting);\n addEventListener(media, 'ended', this.onMediaEnded);\n }\n onMediaDetaching(event, data) {\n this.clearInterval();\n const {\n media\n } = this;\n if (media) {\n removeEventListener(media, 'playing', this.onMediaPlaying);\n removeEventListener(media, 'waiting', this.onMediaWaiting);\n removeEventListener(media, 'ended', this.onMediaEnded);\n this.media = null;\n }\n this.mediaSource = undefined;\n }\n onBufferAppended(event, data) {\n this.buffered = data.timeRanges;\n }\n get hasBuffered() {\n return Object.keys(this.buffered).length > 0;\n }\n tick() {\n var _this$media3;\n if (!((_this$media3 = this.media) != null && _this$media3.readyState) || !this.hasBuffered) {\n return;\n }\n const currentTime = this.media.currentTime;\n this.poll(currentTime, this.lastCurrentTime);\n this.lastCurrentTime = currentTime;\n }\n\n /**\n * Checks if the playhead is stuck within a gap, and if so, attempts to free it.\n * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).\n *\n * @param lastCurrentTime - Previously read playhead position\n */\n poll(currentTime, lastCurrentTime) {\n var _this$hls, _this$hls2;\n const config = (_this$hls = this.hls) == null ? void 0 : _this$hls.config;\n if (!config) {\n return;\n }\n const {\n media,\n stalled\n } = this;\n if (!media) {\n return;\n }\n const {\n seeking\n } = media;\n const seeked = this.seeking && !seeking;\n const beginSeek = !this.seeking && seeking;\n const pausedEndedOrHalted = media.paused && !seeking || media.ended || media.playbackRate === 0;\n this.seeking = seeking;\n\n // The playhead is moving, no-op\n if (currentTime !== lastCurrentTime) {\n if (lastCurrentTime) {\n this.ended = 0;\n }\n this.moved = true;\n if (!seeking) {\n this.nudgeRetry = 0;\n // When crossing between buffered video time ranges, but not audio, flush pipeline with seek (Chrome)\n if (config.nudgeOnVideoHole && !pausedEndedOrHalted && currentTime > lastCurrentTime) {\n this.nudgeOnVideoHole(currentTime, lastCurrentTime);\n }\n }\n if (this.waiting === 0) {\n this.stallResolved(currentTime);\n }\n return;\n }\n\n // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek\n if (beginSeek || seeked) {\n if (seeked) {\n this.stallResolved(currentTime);\n }\n return;\n }\n\n // The playhead should not be moving\n if (pausedEndedOrHalted) {\n this.nudgeRetry = 0;\n this.stallResolved(currentTime);\n // Fire MEDIA_ENDED to workaround event not being dispatched by browser\n if (!this.ended && media.ended && this.hls) {\n this.ended = currentTime || 1;\n this.hls.trigger(Events.MEDIA_ENDED, {\n stalled: false\n });\n }\n return;\n }\n if (!BufferHelper.getBuffered(media).length) {\n this.nudgeRetry = 0;\n return;\n }\n\n // Resolve stalls at buffer holes using the main buffer, whose ranges are the intersections of the A/V sourcebuffers\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const nextStart = bufferInfo.nextStart || 0;\n const fragmentTracker = this.fragmentTracker;\n if (seeking && fragmentTracker && this.hls) {\n // Is there a fragment loading/parsing/appending before currentTime?\n const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, currentTime);\n\n // Waiting for seeking in a buffered range to complete\n const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;\n // Next buffered range is too far ahead to jump to while still seeking\n const noBufferHole = !nextStart || inFlightDependency || nextStart - currentTime > MAX_START_GAP_JUMP && !fragmentTracker.getPartialFragment(currentTime);\n if (hasEnoughBuffer || noBufferHole) {\n return;\n }\n // Reset moved state when seeking to a point in or before a gap/hole\n this.moved = false;\n }\n\n // Skip start gaps if we haven't played, but the last poll detected the start of a stall\n // The addition poll gives the browser a chance to jump the gap for us\n const levelDetails = (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails;\n if (!this.moved && this.stalled !== null && fragmentTracker) {\n // There is no playable buffer (seeked, waiting for buffer)\n const isBuffered = bufferInfo.len > 0;\n if (!isBuffered && !nextStart) {\n return;\n }\n // Jump start gaps within jump threshold\n const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;\n\n // When joining a live stream with audio tracks, account for live playlist window sliding by allowing\n // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment\n // that begins over 1 target duration after the video start position.\n const isLive = !!(levelDetails != null && levelDetails.live);\n const maxStartGapJump = isLive ? levelDetails.targetduration * 2 : MAX_START_GAP_JUMP;\n const partialOrGap = fragmentTracker.getPartialFragment(currentTime);\n if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {\n if (!media.paused) {\n this._trySkipBufferHole(partialOrGap);\n }\n return;\n }\n }\n\n // Start tracking stall time\n const detectStallWithCurrentTimeMs = config.detectStallWithCurrentTimeMs;\n const tnow = self.performance.now();\n const tWaiting = this.waiting;\n if (stalled === null) {\n // Use time of recent \"waiting\" event\n if (tWaiting > 0 && tnow - tWaiting < detectStallWithCurrentTimeMs) {\n this.stalled = tWaiting;\n } else {\n this.stalled = tnow;\n }\n return;\n }\n const stalledDuration = tnow - stalled;\n if (!seeking && (stalledDuration >= detectStallWithCurrentTimeMs || tWaiting) && this.hls) {\n var _this$mediaSource;\n // Dispatch MEDIA_ENDED when media.ended/ended event is not signalled at end of stream\n if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) === 'ended' && !(levelDetails != null && levelDetails.live) && Math.abs(currentTime - ((levelDetails == null ? void 0 : levelDetails.edge) || 0)) < 1) {\n if (this.ended) {\n return;\n }\n this.ended = currentTime || 1;\n this.hls.trigger(Events.MEDIA_ENDED, {\n stalled: true\n });\n return;\n }\n // Report stalling after trying to fix\n this._reportStall(bufferInfo);\n if (!this.media || !this.hls) {\n return;\n }\n }\n const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);\n this._tryFixBufferStall(bufferedWithHoles, stalledDuration);\n }\n stallResolved(currentTime) {\n const stalled = this.stalled;\n if (stalled && this.hls) {\n this.stalled = null;\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n const stalledDuration = self.performance.now() - stalled;\n this.log(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);\n this.stallReported = false;\n this.waiting = 0;\n this.hls.trigger(Events.STALL_RESOLVED, {});\n }\n }\n }\n nudgeOnVideoHole(currentTime, lastCurrentTime) {\n var _this$buffered$audio;\n // Chrome will play one second past a hole in video buffered time ranges without rendering any video from the subsequent range and then stall as long as audio is buffered:\n // https://github.com/video-dev/hls.js/issues/5631\n // https://issues.chromium.org/issues/40280613#comment10\n // Detect the potential for this situation and proactively seek to flush the video pipeline once the playhead passes the start of the video hole.\n // When there are audio and video buffers and currentTime is past the end of the first video buffered range...\n const videoSourceBuffered = this.buffered.video;\n if (this.hls && this.media && this.fragmentTracker && (_this$buffered$audio = this.buffered.audio) != null && _this$buffered$audio.length && videoSourceBuffered && videoSourceBuffered.length > 1 && currentTime > videoSourceBuffered.end(0)) {\n // and audio is buffered at the playhead\n const audioBufferInfo = BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio), currentTime, 0);\n if (audioBufferInfo.len > 1 && lastCurrentTime >= audioBufferInfo.start) {\n const videoTimes = BufferHelper.timeRangesToArray(videoSourceBuffered);\n const lastBufferedIndex = BufferHelper.bufferedInfo(videoTimes, lastCurrentTime, 0).bufferedIndex;\n // nudge when crossing into another video buffered range (hole).\n if (lastBufferedIndex > -1 && lastBufferedIndex < videoTimes.length - 1) {\n const bufferedIndex = BufferHelper.bufferedInfo(videoTimes, currentTime, 0).bufferedIndex;\n const holeStart = videoTimes[lastBufferedIndex].end;\n const holeEnd = videoTimes[lastBufferedIndex + 1].start;\n if ((bufferedIndex === -1 || bufferedIndex > lastBufferedIndex) && holeEnd - holeStart < 1 &&\n // `maxBufferHole` may be too small and setting it to 0 should not disable this feature\n currentTime - holeStart < 2) {\n const error = new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${currentTime} hole: ${holeStart} -> ${holeEnd} buffered index: ${bufferedIndex}`);\n this.warn(error.message);\n // Magic number to flush the pipeline without interuption to audio playback:\n this.media.currentTime += 0.000001;\n const frag = this.fragmentTracker.getPartialFragment(currentTime) || undefined;\n const bufferInfo = BufferHelper.bufferInfo(this.media, currentTime, 0);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n error,\n reason: error.message,\n frag,\n buffer: bufferInfo.len,\n bufferInfo\n });\n }\n }\n }\n }\n }\n\n /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDurationMs - The amount of time Hls.js has been stalling for.\n * @private\n */\n _tryFixBufferStall(bufferInfo, stalledDurationMs) {\n var _this$hls3, _this$hls4;\n const {\n fragmentTracker,\n media\n } = this;\n const config = (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.config;\n if (!media || !fragmentTracker || !config) {\n return;\n }\n const currentTime = media.currentTime;\n const levelDetails = (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.latestLevelDetails;\n const partial = fragmentTracker.getPartialFragment(currentTime);\n if (partial || levelDetails != null && levelDetails.live && currentTime < levelDetails.fragmentStart) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n const targetTime = this._trySkipBufferHole(partial);\n // we return here in this case, meaning\n // the branch below only executes when we haven't seeked to a new position\n if (targetTime || !this.media) {\n return;\n }\n }\n\n // if we haven't had to skip over a buffer hole of a partial fragment\n // we may just have to \"nudge\" the playlist as the browser decoding/rendering engine\n // needs to cross some sort of threshold covering all source-buffers content\n // to start playing properly.\n const bufferedRanges = bufferInfo.buffered;\n if ((bufferedRanges && bufferedRanges.length > 1 && bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && bufferInfo.nextStart - currentTime < config.maxBufferHole) && (stalledDurationMs > config.highBufferWatchdogPeriod * 1000 || this.waiting)) {\n this.warn('Trying to nudge playhead over buffer-hole');\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n this._tryNudgeBuffer(bufferInfo);\n }\n }\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n _reportStall(bufferInfo) {\n const {\n hls,\n media,\n stallReported,\n stalled\n } = this;\n if (!stallReported && stalled !== null && media && hls) {\n // Report stalled error once\n this.stallReported = true;\n const error = new Error(`Playback stalling at @${media.currentTime} due to low buffer (${stringify(bufferInfo)})`);\n this.warn(error.message);\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\n error,\n buffer: bufferInfo.len,\n bufferInfo,\n stalled: {\n start: stalled\n }\n });\n }\n }\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n _trySkipBufferHole(partial) {\n var _this$hls5;\n const {\n fragmentTracker,\n media\n } = this;\n const config = (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.config;\n if (!media || !fragmentTracker || !config) {\n return 0;\n }\n\n // Check if currentTime is between unbuffered regions of partial fragments\n const currentTime = media.currentTime;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;\n if (startTime && this.hls) {\n const bufferStarved = bufferInfo.len <= config.maxBufferHole;\n const waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;\n const gapLength = startTime - currentTime;\n if (gapLength > 0 && (bufferStarved || waiting)) {\n // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial\n if (gapLength > config.maxBufferHole) {\n let startGap = false;\n if (currentTime === 0) {\n const startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);\n if (startFrag && startTime < startFrag.end) {\n startGap = true;\n }\n }\n if (!startGap) {\n const startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);\n if (startProvisioned) {\n var _this$hls$loadLevelOb;\n // Do not seek when selected variant playlist is unloaded\n if (!((_this$hls$loadLevelOb = this.hls.loadLevelObj) != null && _this$hls$loadLevelOb.details)) {\n return 0;\n }\n // Do not seek when required fragments are inflight or appending\n const inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, startTime);\n if (inFlightDependency) {\n return 0;\n }\n // Do not seek if we can't walk tracked fragments to end of gap\n let moreToLoad = false;\n let pos = startProvisioned.end;\n while (pos < startTime) {\n const provisioned = fragmentTracker.getPartialFragment(pos);\n if (provisioned) {\n pos += provisioned.duration;\n } else {\n moreToLoad = true;\n break;\n }\n }\n if (moreToLoad) {\n return 0;\n }\n }\n }\n }\n const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);\n this.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);\n this.moved = true;\n media.currentTime = targetTime;\n if (!(partial != null && partial.gap)) {\n const error = new Error(`fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n error,\n reason: error.message,\n frag: partial || undefined,\n buffer: bufferInfo.len,\n bufferInfo\n });\n }\n return targetTime;\n }\n }\n return 0;\n }\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n _tryNudgeBuffer(bufferInfo) {\n const {\n hls,\n media,\n nudgeRetry\n } = this;\n const config = hls == null ? void 0 : hls.config;\n if (!media || !config) {\n return 0;\n }\n const currentTime = media.currentTime;\n this.nudgeRetry++;\n if (nudgeRetry < config.nudgeMaxRetry) {\n const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;\n // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n const error = new Error(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);\n this.warn(error.message);\n media.currentTime = targetTime;\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n error,\n fatal: false,\n buffer: bufferInfo.len,\n bufferInfo\n });\n } else {\n const error = new Error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);\n this.error(error.message);\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n error,\n fatal: true,\n buffer: bufferInfo.len,\n bufferInfo\n });\n }\n }\n}\nfunction getInFlightDependency(inFlightFragments, currentTime) {\n const main = inFlight(inFlightFragments.main);\n if (main && main.start <= currentTime) {\n return main;\n }\n const audio = inFlight(inFlightFragments.audio);\n if (audio && audio.start <= currentTime) {\n return audio;\n }\n return null;\n}\nfunction inFlight(inFlightData) {\n if (!inFlightData) {\n return null;\n }\n switch (inFlightData.state) {\n case State.IDLE:\n case State.STOPPED:\n case State.ENDED:\n case State.ERROR:\n return null;\n }\n return inFlightData.frag;\n}\n\nconst MIN_CUE_DURATION = 0.25;\nfunction getCueClass() {\n if (typeof self === 'undefined') return undefined;\n return self.VTTCue || self.TextTrackCue;\n}\nfunction createCueWithDataFields(Cue, startTime, endTime, data, type) {\n let cue = new Cue(startTime, endTime, '');\n try {\n cue.value = data;\n if (type) {\n cue.type = type;\n }\n } catch (e) {\n cue = new Cue(startTime, endTime, stringify(type ? _objectSpread2({\n type\n }, data) : data));\n }\n return cue;\n}\n\n// VTTCue latest draft allows an infinite duration, fallback\n// to MAX_VALUE if necessary\nconst MAX_CUE_ENDTIME = (() => {\n const Cue = getCueClass();\n try {\n Cue && new Cue(0, Number.POSITIVE_INFINITY, '');\n } catch (e) {\n return Number.MAX_VALUE;\n }\n return Number.POSITIVE_INFINITY;\n})();\nfunction hexToArrayBuffer(str) {\n return Uint8Array.from(str.replace(/^0x/, '').replace(/([\\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ')).buffer;\n}\nclass ID3TrackController {\n constructor(hls) {\n this.hls = void 0;\n this.id3Track = null;\n this.media = null;\n this.dateRangeCuesAppended = {};\n this.removeCues = true;\n this.onEventCueEnter = () => {\n if (!this.hls) {\n return;\n }\n this.hls.trigger(Events.EVENT_CUE_ENTER, {});\n };\n this.hls = hls;\n this._registerListeners();\n }\n destroy() {\n this._unregisterListeners();\n this.id3Track = null;\n this.media = null;\n this.dateRangeCuesAppended = {};\n // @ts-ignore\n this.hls = this.onEventCueEnter = null;\n }\n _registerListeners() {\n const {\n hls\n } = this;\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.on(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);\n }\n _unregisterListeners() {\n const {\n hls\n } = this;\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.off(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);\n }\n // Add ID3 metatadata text track.\n onMediaAttaching(event, data) {\n var _data$overrides;\n this.media = data.media;\n if (((_data$overrides = data.overrides) == null ? void 0 : _data$overrides.cueRemoval) === false) {\n this.removeCues = false;\n }\n }\n onMediaAttached() {\n const details = this.hls.latestLevelDetails;\n if (details) {\n this.updateDateRangeCues(details);\n }\n }\n onMediaDetaching(event, data) {\n this.media = null;\n const transferringMedia = !!data.transferMedia;\n if (transferringMedia) {\n return;\n }\n if (this.id3Track) {\n if (this.removeCues) {\n clearCurrentCues(this.id3Track, this.onEventCueEnter);\n }\n this.id3Track = null;\n }\n this.dateRangeCuesAppended = {};\n }\n onManifestLoading() {\n this.dateRangeCuesAppended = {};\n }\n createTrack(media) {\n const track = this.getID3Track(media.textTracks);\n track.mode = 'hidden';\n return track;\n }\n getID3Track(textTracks) {\n if (!this.media) {\n return;\n }\n for (let i = 0; i < textTracks.length; i++) {\n const textTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n sendAddTrackEvent(textTrack, this.media);\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\n }\n onFragParsingMetadata(event, data) {\n if (!this.media) {\n return;\n }\n const {\n hls: {\n config: {\n enableEmsgMetadataCues,\n enableID3MetadataCues\n }\n }\n } = this;\n if (!enableEmsgMetadataCues && !enableID3MetadataCues) {\n return;\n }\n const {\n samples\n } = data;\n\n // create track dynamically\n if (!this.id3Track) {\n this.id3Track = this.createTrack(this.media);\n }\n const Cue = getCueClass();\n if (!Cue) {\n return;\n }\n for (let i = 0; i < samples.length; i++) {\n const type = samples[i].type;\n if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {\n continue;\n }\n const frames = getId3Frames(samples[i].data);\n if (frames) {\n const startTime = samples[i].pts;\n let endTime = startTime + samples[i].duration;\n if (endTime > MAX_CUE_ENDTIME) {\n endTime = MAX_CUE_ENDTIME;\n }\n const timeDiff = endTime - startTime;\n if (timeDiff <= 0) {\n endTime = startTime + MIN_CUE_DURATION;\n }\n for (let j = 0; j < frames.length; j++) {\n const frame = frames[j];\n // Safari doesn't put the timestamp frame in the TextTrack\n if (!isId3TimestampFrame(frame)) {\n // add a bounds to any unbounded cues\n this.updateId3CueEnds(startTime, type);\n const cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);\n if (cue) {\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n }\n }\n updateId3CueEnds(startTime, type) {\n var _this$id3Track;\n const cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;\n if (cues) {\n for (let i = cues.length; i--;) {\n const cue = cues[i];\n if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {\n cue.endTime = startTime;\n }\n }\n }\n }\n onBufferFlushing(event, {\n startOffset,\n endOffset,\n type\n }) {\n const {\n id3Track,\n hls\n } = this;\n if (!hls) {\n return;\n }\n const {\n config: {\n enableEmsgMetadataCues,\n enableID3MetadataCues\n }\n } = hls;\n if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {\n let predicate;\n if (type === 'audio') {\n predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;\n } else if (type === 'video') {\n predicate = cue => cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;\n } else {\n predicate = cue => cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;\n }\n removeCuesInRange(id3Track, startOffset, endOffset, predicate);\n }\n }\n onLevelUpdated(event, {\n details\n }) {\n this.updateDateRangeCues(details, true);\n }\n onLevelPtsUpdated(event, data) {\n if (Math.abs(data.drift) > 0.01) {\n this.updateDateRangeCues(data.details);\n }\n }\n updateDateRangeCues(details, removeOldCues) {\n if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {\n return;\n }\n const {\n id3Track\n } = this;\n const {\n dateRanges\n } = details;\n const ids = Object.keys(dateRanges);\n let dateRangeCuesAppended = this.dateRangeCuesAppended;\n // Remove cues from track not found in details.dateRanges\n if (id3Track && removeOldCues) {\n var _id3Track$cues;\n if ((_id3Track$cues = id3Track.cues) != null && _id3Track$cues.length) {\n const idsToRemove = Object.keys(dateRangeCuesAppended).filter(id => !ids.includes(id));\n for (let i = idsToRemove.length; i--;) {\n const id = idsToRemove[i];\n const cues = dateRangeCuesAppended[id].cues;\n delete dateRangeCuesAppended[id];\n Object.keys(cues).forEach(key => {\n try {\n const cue = cues[key];\n cue.removeEventListener('enter', this.onEventCueEnter);\n id3Track.removeCue(cue);\n } catch (e) {\n /* no-op */\n }\n });\n }\n } else {\n dateRangeCuesAppended = this.dateRangeCuesAppended = {};\n }\n }\n // Exit if the playlist does not have Date Ranges or does not have Program Date Time\n const lastFragment = details.fragments[details.fragments.length - 1];\n if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {\n return;\n }\n if (!this.id3Track) {\n this.id3Track = this.createTrack(this.media);\n }\n const Cue = getCueClass();\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i];\n const dateRange = dateRanges[id];\n const startTime = dateRange.startTime;\n\n // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)\n const appendedDateRangeCues = dateRangeCuesAppended[id];\n const cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};\n let durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;\n let endTime = MAX_CUE_ENDTIME;\n const {\n duration,\n endDate\n } = dateRange;\n if (endDate && duration !== null) {\n endTime = startTime + duration;\n durationKnown = true;\n } else if (dateRange.endOnNext && !durationKnown) {\n const nextDateRangeWithSameClass = ids.reduce((candidateDateRange, id) => {\n if (id !== dateRange.id) {\n const otherDateRange = dateRanges[id];\n if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {\n return otherDateRange;\n }\n }\n return candidateDateRange;\n }, null);\n if (nextDateRangeWithSameClass) {\n endTime = nextDateRangeWithSameClass.startTime;\n durationKnown = true;\n }\n }\n\n // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)\n // This is to emulate Safari HLS playback handling of DateRange tags\n const attributes = Object.keys(dateRange.attr);\n for (let j = 0; j < attributes.length; j++) {\n const key = attributes[j];\n if (!isDateRangeCueAttribute(key)) {\n continue;\n }\n const cue = cues[key];\n if (cue) {\n if (durationKnown && !appendedDateRangeCues.durationKnown) {\n cue.endTime = endTime;\n } else if (Math.abs(cue.startTime - startTime) > 0.01) {\n cue.startTime = startTime;\n cue.endTime = endTime;\n }\n } else if (Cue) {\n let data = dateRange.attr[key];\n if (isSCTE35Attribute(key)) {\n data = hexToArrayBuffer(data);\n }\n const payload = {\n key,\n data\n };\n const _cue = createCueWithDataFields(Cue, startTime, endTime, payload, MetadataSchema.dateRange);\n if (_cue) {\n _cue.id = id;\n this.id3Track.addCue(_cue);\n cues[key] = _cue;\n if (this.hls.config.interstitialsController) {\n if (key === 'X-ASSET-LIST' || key === 'X-ASSET-URL') {\n _cue.addEventListener('enter', this.onEventCueEnter);\n }\n }\n }\n }\n }\n\n // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes\n dateRangeCuesAppended[id] = {\n cues,\n dateRange,\n durationKnown\n };\n }\n }\n}\n\nclass LatencyController {\n constructor(hls) {\n this.hls = void 0;\n this.config = void 0;\n this.media = null;\n this.currentTime = 0;\n this.stallCount = 0;\n this._latency = null;\n this._targetLatencyUpdated = false;\n this.onTimeupdate = () => {\n const {\n media\n } = this;\n const levelDetails = this.levelDetails;\n if (!media || !levelDetails) {\n return;\n }\n this.currentTime = media.currentTime;\n const latency = this.computeLatency();\n if (latency === null) {\n return;\n }\n this._latency = latency;\n\n // Adapt playbackRate to meet target latency in low-latency mode\n const {\n lowLatencyMode,\n maxLiveSyncPlaybackRate\n } = this.config;\n if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {\n return;\n }\n const targetLatency = this.targetLatency;\n if (targetLatency === null) {\n return;\n }\n const distanceFromTarget = latency - targetLatency;\n // Only adjust playbackRate when within one target duration of targetLatency\n // and more than one second from under-buffering.\n // Playback further than one target duration from target can be considered DVR playback.\n const liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);\n const inLiveRange = distanceFromTarget < liveMinLatencyDuration;\n if (inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {\n const max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));\n const rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;\n const playbackRate = Math.min(max, Math.max(1, rate));\n this.changeMediaPlaybackRate(media, playbackRate);\n } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {\n this.changeMediaPlaybackRate(media, 1);\n }\n };\n this.hls = hls;\n this.config = hls.config;\n this.registerListeners();\n }\n get levelDetails() {\n var _this$hls;\n return ((_this$hls = this.hls) == null ? void 0 : _this$hls.latestLevelDetails) || null;\n }\n get latency() {\n return this._latency || 0;\n }\n get maxLatency() {\n const {\n config\n } = this;\n if (config.liveMaxLatencyDuration !== undefined) {\n return config.liveMaxLatencyDuration;\n }\n const levelDetails = this.levelDetails;\n return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;\n }\n get targetLatency() {\n const levelDetails = this.levelDetails;\n if (levelDetails === null || this.hls === null) {\n return null;\n }\n const {\n holdBack,\n partHoldBack,\n targetduration\n } = levelDetails;\n const {\n liveSyncDuration,\n liveSyncDurationCount,\n lowLatencyMode\n } = this.config;\n const userConfig = this.hls.userConfig;\n let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;\n if (this._targetLatencyUpdated || userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {\n targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;\n }\n const maxLiveSyncOnStallIncrease = targetduration;\n return targetLatency + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);\n }\n set targetLatency(latency) {\n this.stallCount = 0;\n this.config.liveSyncDuration = latency;\n this._targetLatencyUpdated = true;\n }\n get liveSyncPosition() {\n const liveEdge = this.estimateLiveEdge();\n const targetLatency = this.targetLatency;\n if (liveEdge === null || targetLatency === null) {\n return null;\n }\n const levelDetails = this.levelDetails;\n if (levelDetails === null) {\n return null;\n }\n const edge = levelDetails.edge;\n const syncPosition = liveEdge - targetLatency - this.edgeStalled;\n const min = edge - levelDetails.totalduration;\n const max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);\n return Math.min(Math.max(min, syncPosition), max);\n }\n get drift() {\n const levelDetails = this.levelDetails;\n if (levelDetails === null) {\n return 1;\n }\n return levelDetails.drift;\n }\n get edgeStalled() {\n const levelDetails = this.levelDetails;\n if (levelDetails === null) {\n return 0;\n }\n const maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;\n return Math.max(levelDetails.age - maxLevelUpdateAge, 0);\n }\n get forwardBufferLength() {\n const {\n media\n } = this;\n const levelDetails = this.levelDetails;\n if (!media || !levelDetails) {\n return 0;\n }\n const bufferedRanges = media.buffered.length;\n return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;\n }\n destroy() {\n this.unregisterListeners();\n this.onMediaDetaching();\n this.hls = null;\n }\n registerListeners() {\n const {\n hls\n } = this;\n if (!hls) {\n return;\n }\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n unregisterListeners() {\n const {\n hls\n } = this;\n if (!hls) {\n return;\n }\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n onMediaAttached(event, data) {\n this.media = data.media;\n this.media.addEventListener('timeupdate', this.onTimeupdate);\n }\n onMediaDetaching() {\n if (this.media) {\n this.media.removeEventListener('timeupdate', this.onTimeupdate);\n this.media = null;\n }\n }\n onManifestLoading() {\n this._latency = null;\n this.stallCount = 0;\n }\n onLevelUpdated(event, {\n details\n }) {\n if (details.advanced) {\n this.onTimeupdate();\n }\n if (!details.live && this.media) {\n this.media.removeEventListener('timeupdate', this.onTimeupdate);\n }\n }\n onError(event, data) {\n var _this$levelDetails;\n if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {\n return;\n }\n this.stallCount++;\n if (this.hls && (_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {\n this.hls.logger.warn('[latency-controller]: Stall detected, adjusting target latency');\n }\n }\n changeMediaPlaybackRate(media, playbackRate) {\n var _this$hls2, _this$targetLatency;\n if (media.playbackRate === playbackRate) {\n return;\n }\n (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(_this$targetLatency = this.targetLatency) == null ? void 0 : _this$targetLatency.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${media.playbackRate} to ${playbackRate}`);\n media.playbackRate = playbackRate;\n }\n estimateLiveEdge() {\n const levelDetails = this.levelDetails;\n if (levelDetails === null) {\n return null;\n }\n return levelDetails.edge + levelDetails.age;\n }\n computeLatency() {\n const liveEdge = this.estimateLiveEdge();\n if (liveEdge === null) {\n return null;\n }\n return liveEdge - this.currentTime;\n }\n}\n\nclass LevelController extends BasePlaylistController {\n constructor(hls, contentSteeringController) {\n super(hls, 'level-controller');\n this._levels = [];\n this._firstLevel = -1;\n this._maxAutoLevel = -1;\n this._startLevel = void 0;\n this.currentLevel = null;\n this.currentLevelIndex = -1;\n this.manualLevelIndex = -1;\n this.steering = void 0;\n this.onParsedComplete = void 0;\n this.steering = contentSteeringController;\n this._registerListeners();\n }\n _registerListeners() {\n const {\n hls\n } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n _unregisterListeners() {\n const {\n hls\n } = this;\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n destroy() {\n this._unregisterListeners();\n this.steering = null;\n this.resetLevels();\n super.destroy();\n }\n stopLoad() {\n const levels = this._levels;\n\n // clean up live level details to force reload them, and reset load errors\n levels.forEach(level => {\n level.loadError = 0;\n level.fragmentError = 0;\n });\n super.stopLoad();\n }\n resetLevels() {\n this._startLevel = undefined;\n this.manualLevelIndex = -1;\n this.currentLevelIndex = -1;\n this.currentLevel = null;\n this._levels = [];\n this._maxAutoLevel = -1;\n }\n onManifestLoading(event, data) {\n this.resetLevels();\n }\n onManifestLoaded(event, data) {\n const preferManagedMediaSource = this.hls.config.preferManagedMediaSource;\n const levels = [];\n const redundantSet = {};\n const generatePathwaySet = {};\n let resolutionFound = false;\n let videoCodecFound = false;\n let audioCodecFound = false;\n data.levels.forEach(levelParsed => {\n var _videoCodec;\n const attributes = levelParsed.attrs;\n let {\n audioCodec,\n videoCodec\n } = levelParsed;\n if (audioCodec) {\n // Returns empty and set to undefined for 'mp4a.40.34' with fallback to 'audio/mpeg' SourceBuffer\n levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource) || undefined;\n }\n if (((_videoCodec = videoCodec) == null ? void 0 : _videoCodec.indexOf('avc1')) === 0) {\n videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);\n }\n\n // only keep levels with supported audio/video codecs\n const {\n width,\n height,\n unknownCodecs\n } = levelParsed;\n let unknownUnsupportedCodecCount = unknownCodecs ? unknownCodecs.length : 0;\n if (unknownCodecs) {\n // Treat unknown codec as audio or video codec based on passing `isTypeSupported` check\n // (allows for playback of any supported codec even if not indexed in utils/codecs)\n for (let i = unknownUnsupportedCodecCount; i--;) {\n const unknownCodec = unknownCodecs[i];\n if (this.isAudioSupported(unknownCodec)) {\n levelParsed.audioCodec = audioCodec = audioCodec ? `${audioCodec},${unknownCodec}` : unknownCodec;\n unknownUnsupportedCodecCount--;\n sampleEntryCodesISO.audio[audioCodec.substring(0, 4)] = 2;\n } else if (this.isVideoSupported(unknownCodec)) {\n levelParsed.videoCodec = videoCodec = videoCodec ? `${videoCodec},${unknownCodec}` : unknownCodec;\n unknownUnsupportedCodecCount--;\n sampleEntryCodesISO.video[videoCodec.substring(0, 4)] = 2;\n }\n }\n }\n resolutionFound || (resolutionFound = !!(width && height));\n videoCodecFound || (videoCodecFound = !!videoCodec);\n audioCodecFound || (audioCodecFound = !!audioCodec);\n if (unknownUnsupportedCodecCount || audioCodec && !this.isAudioSupported(audioCodec) || videoCodec && !this.isVideoSupported(videoCodec)) {\n this.log(`Some or all CODECS not supported \"${attributes.CODECS}\"`);\n return;\n }\n const {\n CODECS,\n 'FRAME-RATE': FRAMERATE,\n 'HDCP-LEVEL': HDCP,\n 'PATHWAY-ID': PATHWAY,\n RESOLUTION,\n 'VIDEO-RANGE': VIDEO_RANGE\n } = attributes;\n const contentSteeringPrefix = `${PATHWAY || '.'}-`;\n const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}-${VIDEO_RANGE}-${HDCP}`;\n if (!redundantSet[levelKey]) {\n const level = this.createLevel(levelParsed);\n redundantSet[levelKey] = level;\n generatePathwaySet[levelKey] = 1;\n levels.push(level);\n } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs['PATHWAY-ID']) {\n // Assign Pathway IDs to Redundant Streams (default Pathways is \".\". Redundant Streams \"..\", \"...\", and so on.)\n // Content Steering controller to handles Pathway fallback on error\n const pathwayCount = generatePathwaySet[levelKey] += 1;\n levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');\n const level = this.createLevel(levelParsed);\n redundantSet[levelKey] = level;\n levels.push(level);\n } else {\n redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);\n redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);\n }\n });\n this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);\n }\n createLevel(levelParsed) {\n const level = new Level(levelParsed);\n const supplemental = levelParsed.supplemental;\n if (supplemental != null && supplemental.videoCodec && !this.isVideoSupported(supplemental.videoCodec)) {\n const error = new Error(`SUPPLEMENTAL-CODECS not supported \"${supplemental.videoCodec}\"`);\n this.log(error.message);\n level.supportedResult = getUnsupportedResult(error, []);\n }\n return level;\n }\n isAudioSupported(codec) {\n return areCodecsMediaSourceSupported(codec, 'audio', this.hls.config.preferManagedMediaSource);\n }\n isVideoSupported(codec) {\n return areCodecsMediaSourceSupported(codec, 'video', this.hls.config.preferManagedMediaSource);\n }\n filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {\n let audioTracks = [];\n let subtitleTracks = [];\n let levels = filteredLevels;\n\n // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled\n if ((resolutionFound || videoCodecFound) && audioCodecFound) {\n levels = levels.filter(({\n videoCodec,\n videoRange,\n width,\n height\n }) => (!!videoCodec || !!(width && height)) && isVideoRange(videoRange));\n }\n if (levels.length === 0) {\n // Dispatch error after MANIFEST_LOADED is done propagating\n Promise.resolve().then(() => {\n if (this.hls) {\n let message = 'no level with compatible codecs found in manifest';\n let reason = message;\n if (data.levels.length) {\n reason = `one or more CODECS in variant not supported: ${stringify(data.levels.map(level => level.attrs.CODECS).filter((value, index, array) => array.indexOf(value) === index))}`;\n this.warn(reason);\n message += ` (${reason})`;\n }\n const error = new Error(message);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n url: data.url,\n error,\n reason\n });\n }\n });\n return;\n }\n if (data.audioTracks) {\n audioTracks = data.audioTracks.filter(track => !track.audioCodec || this.isAudioSupported(track.audioCodec));\n // Assign ids after filtering as array indices by group-id\n assignTrackIdsByGroup(audioTracks);\n }\n if (data.subtitles) {\n subtitleTracks = data.subtitles;\n assignTrackIdsByGroup(subtitleTracks);\n }\n // start bitrate is the first bitrate of the manifest\n const unsortedLevels = levels.slice(0);\n // sort levels from lowest to highest\n levels.sort((a, b) => {\n if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {\n return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '') ? 1 : -1;\n }\n // sort on height before bitrate for cap-level-controller\n if (resolutionFound && a.height !== b.height) {\n return a.height - b.height;\n }\n if (a.frameRate !== b.frameRate) {\n return a.frameRate - b.frameRate;\n }\n if (a.videoRange !== b.videoRange) {\n return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);\n }\n if (a.videoCodec !== b.videoCodec) {\n const valueA = videoCodecPreferenceValue(a.videoCodec);\n const valueB = videoCodecPreferenceValue(b.videoCodec);\n if (valueA !== valueB) {\n return valueB - valueA;\n }\n }\n if (a.uri === b.uri && a.codecSet !== b.codecSet) {\n const valueA = codecsSetSelectionPreferenceValue(a.codecSet);\n const valueB = codecsSetSelectionPreferenceValue(b.codecSet);\n if (valueA !== valueB) {\n return valueB - valueA;\n }\n }\n if (a.averageBitrate !== b.averageBitrate) {\n return a.averageBitrate - b.averageBitrate;\n }\n return 0;\n });\n let firstLevelInPlaylist = unsortedLevels[0];\n if (this.steering) {\n levels = this.steering.filterParsedLevels(levels);\n if (levels.length !== unsortedLevels.length) {\n for (let i = 0; i < unsortedLevels.length; i++) {\n if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {\n firstLevelInPlaylist = unsortedLevels[i];\n break;\n }\n }\n }\n }\n this._levels = levels;\n\n // find index of first level in sorted levels\n for (let i = 0; i < levels.length; i++) {\n if (levels[i] === firstLevelInPlaylist) {\n var _this$hls$userConfig;\n this._firstLevel = i;\n const firstLevelBitrate = firstLevelInPlaylist.bitrate;\n const bandwidthEstimate = this.hls.bandwidthEstimate;\n this.log(`manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelBitrate}`);\n // Update default bwe to first variant bitrate as long it has not been configured or set\n if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === undefined) {\n const startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);\n if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === this.hls.abrEwmaDefaultEstimate) {\n this.hls.bandwidthEstimate = startingBwEstimate;\n }\n }\n break;\n }\n }\n\n // Audio is only alternate if manifest include a URI along with the audio group tag,\n // and this is not an audio-only stream where levels contain audio-only\n const audioOnly = audioCodecFound && !videoCodecFound;\n const config = this.hls.config;\n const altAudioEnabled = !!(config.audioStreamController && config.audioTrackController);\n const edata = {\n levels,\n audioTracks,\n subtitleTracks,\n sessionData: data.sessionData,\n sessionKeys: data.sessionKeys,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: altAudioEnabled && !audioOnly && audioTracks.some(t => !!t.url)\n };\n this.hls.trigger(Events.MANIFEST_PARSED, edata);\n }\n get levels() {\n if (this._levels.length === 0) {\n return null;\n }\n return this._levels;\n }\n get loadLevelObj() {\n return this.currentLevel;\n }\n get level() {\n return this.currentLevelIndex;\n }\n set level(newLevel) {\n const levels = this._levels;\n if (levels.length === 0) {\n return;\n }\n // check if level idx is valid\n if (newLevel < 0 || newLevel >= levels.length) {\n // invalid level id given, trigger error\n const error = new Error('invalid level idx');\n const fatal = newLevel < 0;\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal,\n error,\n reason: error.message\n });\n if (fatal) {\n return;\n }\n newLevel = Math.min(newLevel, levels.length - 1);\n }\n const lastLevelIndex = this.currentLevelIndex;\n const lastLevel = this.currentLevel;\n const lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;\n const level = levels[newLevel];\n const pathwayId = level.attrs['PATHWAY-ID'];\n this.currentLevelIndex = newLevel;\n this.currentLevel = level;\n if (lastLevelIndex === newLevel && lastLevel && lastPathwayId === pathwayId) {\n return;\n }\n this.log(`Switching to level ${newLevel} (${level.height ? level.height + 'p ' : ''}${level.videoRange ? level.videoRange + ' ' : ''}${level.codecSet ? level.codecSet + ' ' : ''}@${level.bitrate})${pathwayId ? ' with Pathway ' + pathwayId : ''} from level ${lastLevelIndex}${lastPathwayId ? ' with Pathway ' + lastPathwayId : ''}`);\n const levelSwitchingData = {\n level: newLevel,\n attrs: level.attrs,\n details: level.details,\n bitrate: level.bitrate,\n averageBitrate: level.averageBitrate,\n maxBitrate: level.maxBitrate,\n realBitrate: level.realBitrate,\n width: level.width,\n height: level.height,\n codecSet: level.codecSet,\n audioCodec: level.audioCodec,\n videoCodec: level.videoCodec,\n audioGroups: level.audioGroups,\n subtitleGroups: level.subtitleGroups,\n loaded: level.loaded,\n loadError: level.loadError,\n fragmentError: level.fragmentError,\n name: level.name,\n id: level.id,\n uri: level.uri,\n url: level.url,\n urlId: 0,\n audioGroupIds: level.audioGroupIds,\n textGroupIds: level.textGroupIds\n };\n this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);\n // check if we need to load playlist for this level\n const levelDetails = level.details;\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n const hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);\n this.loadPlaylist(hlsUrlParameters);\n }\n }\n get manualLevel() {\n return this.manualLevelIndex;\n }\n set manualLevel(newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n get firstLevel() {\n return this._firstLevel;\n }\n set firstLevel(newLevel) {\n this._firstLevel = newLevel;\n }\n get startLevel() {\n // Setting hls.startLevel (this._startLevel) overrides config.startLevel\n if (this._startLevel === undefined) {\n const configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n }\n return this.hls.firstAutoLevel;\n }\n return this._startLevel;\n }\n set startLevel(newLevel) {\n this._startLevel = newLevel;\n }\n get pathways() {\n if (this.steering) {\n return this.steering.pathways();\n }\n return [];\n }\n get pathwayPriority() {\n if (this.steering) {\n return this.steering.pathwayPriority;\n }\n return null;\n }\n set pathwayPriority(pathwayPriority) {\n if (this.steering) {\n const pathwaysList = this.steering.pathways();\n const filteredPathwayPriority = pathwayPriority.filter(pathwayId => {\n return pathwaysList.indexOf(pathwayId) !== -1;\n });\n if (pathwayPriority.length < 1) {\n this.warn(`pathwayPriority ${pathwayPriority} should contain at least one pathway from list: ${pathwaysList}`);\n return;\n }\n this.steering.pathwayPriority = filteredPathwayPriority;\n }\n }\n onError(event, data) {\n if (data.fatal || !data.context) {\n return;\n }\n if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {\n this.checkRetry(data);\n }\n }\n\n // reset errors on the successful load of a fragment\n onFragBuffered(event, {\n frag\n }) {\n if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {\n const el = frag.elementaryStreams;\n if (!Object.keys(el).some(type => !!el[type])) {\n return;\n }\n const level = this._levels[frag.level];\n if (level != null && level.loadError) {\n this.log(`Resetting level error count of ${level.loadError} on frag buffered`);\n level.loadError = 0;\n }\n }\n }\n onLevelLoaded(event, data) {\n var _data$deliveryDirecti2;\n const {\n level,\n details\n } = data;\n const curLevel = data.levelInfo;\n if (!curLevel) {\n var _data$deliveryDirecti;\n this.warn(`Invalid level index ${level}`);\n if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {\n details.deltaUpdateFailed = true;\n }\n return;\n }\n\n // only process level loaded events matching with expected level or prior to switch when media playlist is loaded directly\n if (curLevel === this.currentLevel || data.withoutMultiVariant) {\n // reset level load error counter on successful level loaded only if there is no issues with fragments\n if (curLevel.fragmentError === 0) {\n curLevel.loadError = 0;\n }\n // Ignore matching details populated by loading a Media Playlist directly\n let previousDetails = curLevel.details;\n if (previousDetails === data.details && previousDetails.advanced) {\n previousDetails = undefined;\n }\n this.playlistLoaded(level, data, previousDetails);\n } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {\n // received a delta playlist update that cannot be merged\n details.deltaUpdateFailed = true;\n }\n }\n loadPlaylist(hlsUrlParameters) {\n super.loadPlaylist();\n if (this.shouldLoadPlaylist(this.currentLevel)) {\n this.scheduleLoading(this.currentLevel, hlsUrlParameters);\n }\n }\n loadingPlaylist(currentLevel, hlsUrlParameters) {\n super.loadingPlaylist(currentLevel, hlsUrlParameters);\n const url = this.getUrlWithDirectives(currentLevel.uri, hlsUrlParameters);\n const currentLevelIndex = this.currentLevelIndex;\n const pathwayId = currentLevel.attrs['PATHWAY-ID'];\n const details = currentLevel.details;\n const age = details == null ? void 0 : details.age;\n this.log(`Loading level index ${currentLevelIndex}${(hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : ''}${pathwayId ? ' Pathway ' + pathwayId : ''}${age && details.live ? ' age ' + age.toFixed(1) + (details.type ? ' ' + details.type || '' : '') : ''} ${url}`);\n this.hls.trigger(Events.LEVEL_LOADING, {\n url,\n level: currentLevelIndex,\n levelInfo: currentLevel,\n pathwayId: currentLevel.attrs['PATHWAY-ID'],\n id: 0,\n // Deprecated Level urlId\n deliveryDirectives: hlsUrlParameters || null\n });\n }\n get nextLoadLevel() {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n set nextLoadLevel(nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n removeLevel(levelIndex) {\n var _this$currentLevel;\n if (this._levels.length === 1) {\n return;\n }\n const levels = this._levels.filter((level, index) => {\n if (index !== levelIndex) {\n return true;\n }\n if (this.steering) {\n this.steering.removeLevel(level);\n }\n if (level === this.currentLevel) {\n this.currentLevel = null;\n this.currentLevelIndex = -1;\n if (level.details) {\n level.details.fragments.forEach(f => f.level = -1);\n }\n }\n return false;\n });\n reassignFragmentLevelIndexes(levels);\n this._levels = levels;\n if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {\n this.currentLevelIndex = this.currentLevel.details.fragments[0].level;\n }\n if (this.manualLevelIndex > -1) {\n this.manualLevelIndex = this.currentLevelIndex;\n }\n const maxLevel = levels.length - 1;\n this._firstLevel = Math.min(this._firstLevel, maxLevel);\n if (this._startLevel) {\n this._startLevel = Math.min(this._startLevel, maxLevel);\n }\n this.hls.trigger(Events.LEVELS_UPDATED, {\n levels\n });\n }\n onLevelsUpdated(event, {\n levels\n }) {\n this._levels = levels;\n }\n checkMaxAutoUpdated() {\n const {\n autoLevelCapping,\n maxAutoLevel,\n maxHdcpLevel\n } = this.hls;\n if (this._maxAutoLevel !== maxAutoLevel) {\n this._maxAutoLevel = maxAutoLevel;\n this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {\n autoLevelCapping,\n levels: this.levels,\n maxAutoLevel,\n minAutoLevel: this.hls.minAutoLevel,\n maxHdcpLevel\n });\n }\n }\n}\nfunction assignTrackIdsByGroup(tracks) {\n const groups = {};\n tracks.forEach(track => {\n const groupId = track.groupId || '';\n track.id = groups[groupId] = groups[groupId] || 0;\n groups[groupId]++;\n });\n}\n\nfunction getSourceBuffer() {\n return self.SourceBuffer || self.WebKitSourceBuffer;\n}\nfunction isMSESupported() {\n const mediaSource = getMediaSource();\n if (!mediaSource) {\n return false;\n }\n\n // if SourceBuffer is exposed ensure its API is valid\n // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n const sourceBuffer = getSourceBuffer();\n return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';\n}\nfunction isSupported() {\n if (!isMSESupported()) {\n return false;\n }\n const mediaSource = getMediaSource();\n return typeof (mediaSource == null ? void 0 : mediaSource.isTypeSupported) === 'function' && (['avc1.42E01E,mp4a.40.2', 'av01.0.01M.08', 'vp09.00.50.08'].some(codecsForVideoContainer => mediaSource.isTypeSupported(mimeTypeForCodec(codecsForVideoContainer, 'video'))) || ['mp4a.40.2', 'fLaC'].some(codecForAudioContainer => mediaSource.isTypeSupported(mimeTypeForCodec(codecForAudioContainer, 'audio'))));\n}\nfunction changeTypeSupported() {\n var _sourceBuffer$prototy;\n const sourceBuffer = getSourceBuffer();\n return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === 'function';\n}\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\nclass StreamController extends BaseStreamController {\n constructor(hls, fragmentTracker, keyLoader) {\n super(hls, fragmentTracker, keyLoader, 'stream-controller', PlaylistLevelType.MAIN);\n this.audioCodecSwap = false;\n this.level = -1;\n this._forceStartLoad = false;\n this._hasEnoughToStart = false;\n this.altAudio = 0;\n this.audioOnly = false;\n this.fragPlaying = null;\n this.fragLastKbps = 0;\n this.couldBacktrack = false;\n this.backtrackFragment = null;\n this.audioCodecSwitch = false;\n this.videoBuffer = null;\n this.onMediaPlaying = () => {\n // tick to speed up FRAG_CHANGED triggering\n this.tick();\n };\n this.onMediaSeeked = () => {\n const media = this.media;\n const currentTime = media ? media.currentTime : null;\n if (currentTime === null || !isFiniteNumber(currentTime)) {\n return;\n }\n this.log(`Media seeked to ${currentTime.toFixed(3)}`);\n\n // If seeked was issued before buffer was appended do not tick immediately\n if (!this.getBufferedFrag(currentTime)) {\n return;\n }\n const bufferInfo = this.getFwdBufferInfoAtPos(media, currentTime, PlaylistLevelType.MAIN, 0);\n if (bufferInfo === null || bufferInfo.len === 0) {\n this.warn(`Main forward buffer length at ${currentTime} on \"seeked\" event ${bufferInfo ? bufferInfo.len : 'empty'})`);\n return;\n }\n\n // tick to speed up FRAG_CHANGED triggering\n this.tick();\n };\n this.registerListeners();\n }\n registerListeners() {\n super.registerListeners();\n const {\n hls\n } = this;\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);\n hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n unregisterListeners() {\n super.unregisterListeners();\n const {\n hls\n } = this;\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);\n hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n onHandlerDestroying() {\n // @ts-ignore\n this.onMediaPlaying = this.onMediaSeeked = null;\n this.unregisterListeners();\n super.onHandlerDestroying();\n }\n startLoad(startPosition, skipSeekToStartPosition) {\n if (this.levels) {\n const {\n lastCurrentTime,\n hls\n } = this;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n this.level = -1;\n if (!this.startFragRequested) {\n // determine load level\n let startLevel = hls.startLevel;\n if (startLevel === -1) {\n if (hls.config.testBandwidth && this.levels.length > 1) {\n // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n startLevel = 0;\n this.bitrateTest = true;\n } else {\n startLevel = hls.firstAutoLevel;\n }\n }\n // set new level to playlist loader : this will trigger start level load\n // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n hls.nextLoadLevel = startLevel;\n this.level = hls.loadLevel;\n this._hasEnoughToStart = !!skipSeekToStartPosition;\n }\n // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n if (lastCurrentTime > 0 && startPosition === -1 && !skipSeekToStartPosition) {\n this.log(`Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n startPosition = lastCurrentTime;\n }\n this.state = State.IDLE;\n this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;\n this.startPosition = skipSeekToStartPosition ? -1 : startPosition;\n this.tick();\n } else {\n this._forceStartLoad = true;\n this.state = State.STOPPED;\n }\n }\n stopLoad() {\n this._forceStartLoad = false;\n super.stopLoad();\n }\n doTick() {\n switch (this.state) {\n case State.WAITING_LEVEL:\n {\n const {\n levels,\n level\n } = this;\n const currentLevel = levels == null ? void 0 : levels[level];\n const details = currentLevel == null ? void 0 : currentLevel.details;\n if (details && (!details.live || this.levelLastLoaded === currentLevel && !this.waitForLive(currentLevel))) {\n if (this.waitForCdnTuneIn(details)) {\n break;\n }\n this.state = State.IDLE;\n break;\n } else if (this.hls.nextLoadLevel !== this.level) {\n this.state = State.IDLE;\n break;\n }\n break;\n }\n case State.FRAG_LOADING_WAITING_RETRY:\n {\n var _this$media;\n const now = self.performance.now();\n const retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {\n const {\n levels,\n level\n } = this;\n const currentLevel = levels == null ? void 0 : levels[level];\n this.resetStartWhenNotLoaded(currentLevel || null);\n this.state = State.IDLE;\n }\n }\n break;\n }\n if (this.state === State.IDLE) {\n this.doTickIdle();\n }\n this.onTickEnd();\n }\n onTickEnd() {\n var _this$media2;\n super.onTickEnd();\n if ((_this$media2 = this.media) != null && _this$media2.readyState && this.media.seeking === false) {\n this.lastCurrentTime = this.media.currentTime;\n }\n this.checkFragmentChanged();\n }\n doTickIdle() {\n const {\n hls,\n levelLastLoaded,\n levels,\n media\n } = this;\n\n // if start level not parsed yet OR\n // if video not attached AND start fragment already requested OR start frag prefetch not enabled\n // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment\n if (levelLastLoaded === null || !media && !this.primaryPrefetch && (this.startFragRequested || !hls.config.startFragPrefetch)) {\n return;\n }\n\n // If the \"main\" level is audio-only but we are loading an alternate track in the same group, do not load anything\n if (this.altAudio && this.audioOnly) {\n return;\n }\n const level = this.buffering ? hls.nextLoadLevel : hls.loadLevel;\n if (!(levels != null && levels[level])) {\n return;\n }\n const levelInfo = levels[level];\n\n // if buffer length is less than maxBufLen try to load a new fragment\n\n const bufferInfo = this.getMainFwdBufferInfo();\n if (bufferInfo === null) {\n return;\n }\n const lastDetails = this.getLevelDetails();\n if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {\n const data = {};\n if (this.altAudio === 2) {\n data.type = 'video';\n }\n this.hls.trigger(Events.BUFFER_EOS, data);\n this.state = State.ENDED;\n return;\n }\n if (!this.buffering) {\n return;\n }\n\n // set next load level : this will trigger a playlist load if needed\n if (hls.loadLevel !== level && hls.manualLevel === -1) {\n this.log(`Adapting to level ${level} from level ${this.level}`);\n }\n this.level = hls.nextLoadLevel = level;\n const levelDetails = levelInfo.details;\n // if level info not retrieved yet, switch state and wait for level retrieval\n // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n if (!levelDetails || this.state === State.WAITING_LEVEL || this.waitForLive(levelInfo)) {\n this.level = level;\n this.state = State.WAITING_LEVEL;\n this.startFragRequested = false;\n return;\n }\n const bufferLen = bufferInfo.len;\n\n // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s\n const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);\n\n // Stay idle if we are still with buffer margins\n if (bufferLen >= maxBufLen) {\n return;\n }\n if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {\n this.backtrackFragment = null;\n }\n const targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;\n let frag = this.getNextFragment(targetBufferTime, levelDetails);\n // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)\n if (this.couldBacktrack && !this.fragPrevious && frag && isMediaFragment(frag) && this.fragmentTracker.getState(frag) !== FragmentState.OK) {\n var _this$backtrackFragme;\n const backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;\n const fragIdx = backtrackSn - levelDetails.startSN;\n const backtrackFrag = levelDetails.fragments[fragIdx - 1];\n if (backtrackFrag && frag.cc === backtrackFrag.cc) {\n frag = backtrackFrag;\n this.fragmentTracker.removeFragment(backtrackFrag);\n }\n } else if (this.backtrackFragment && bufferInfo.len) {\n this.backtrackFragment = null;\n }\n // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags\n if (frag && this.isLoopLoading(frag, targetBufferTime)) {\n const gapStart = frag.gap;\n if (!gapStart) {\n // Cleanup the fragment tracker before trying to find the next unbuffered fragment\n const type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;\n const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;\n if (mediaBuffer) {\n this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);\n }\n }\n frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);\n }\n if (!frag) {\n return;\n }\n if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {\n frag = frag.initSegment;\n }\n this.loadFragment(frag, levelInfo, targetBufferTime);\n }\n loadFragment(frag, level, targetBufferTime) {\n // Check if fragment is not loaded\n const fragState = this.fragmentTracker.getState(frag);\n if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {\n if (!isMediaFragment(frag)) {\n this._loadInitSegment(frag, level);\n } else if (this.bitrateTest) {\n this.log(`Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`);\n this._loadBitrateTestFrag(frag, level);\n } else {\n super.loadFragment(frag, level, targetBufferTime);\n }\n } else {\n this.clearTrackerIfNeeded(frag);\n }\n }\n getBufferedFrag(position) {\n return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);\n }\n followingBufferedFrag(frag) {\n if (frag) {\n // try to get range of next fragment (500ms after this range)\n return this.getBufferedFrag(frag.end + 0.5);\n }\n return null;\n }\n\n /*\n on immediate level switch :\n - pause playback if playing\n - cancel any pending load request\n - and trigger a buffer flush\n */\n immediateLevelSwitch() {\n this.abortCurrentFrag();\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n\n /**\n * try to switch ASAP without breaking video playback:\n * in order to ensure smooth but quick level switching,\n * we need to find the next flushable buffer range\n * we should take into account new segment fetch time\n */\n nextLevelSwitch() {\n const {\n levels,\n media\n } = this;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media != null && media.readyState) {\n let fetchdelay;\n const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);\n if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {\n // flush buffer preceding current fragment (flush until current fragment start offset)\n // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...\n this.flushMainBuffer(0, fragPlayingCurrent.start - 1);\n }\n const levelDetails = this.getLevelDetails();\n if (levelDetails != null && levelDetails.live) {\n const bufferInfo = this.getMainFwdBufferInfo();\n // Do not flush in live stream with low buffer\n if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {\n return;\n }\n }\n if (!media.paused && levels) {\n // add a safety delay of 1s\n const nextLevelId = this.hls.nextLoadLevel;\n const nextLevel = levels[nextLevelId];\n const fragLastKbps = this.fragLastKbps;\n if (fragLastKbps && this.fragCurrent) {\n fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;\n } else {\n fetchdelay = 0;\n }\n } else {\n fetchdelay = 0;\n }\n // this.log('fetchdelay:'+fetchdelay);\n // find buffer range that will be reached once new fragment will be fetched\n const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (bufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);\n if (nextBufferedFrag) {\n // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n this.abortCurrentFrag();\n // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.\n const maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;\n const fragDuration = nextBufferedFrag.duration;\n const startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * (this.couldBacktrack ? 0.5 : 0.125)), fragDuration * (this.couldBacktrack ? 0.75 : 0.25)));\n this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);\n }\n }\n }\n }\n abortCurrentFrag() {\n const fragCurrent = this.fragCurrent;\n this.fragCurrent = null;\n this.backtrackFragment = null;\n if (fragCurrent) {\n fragCurrent.abortRequests();\n this.fragmentTracker.removeFragment(fragCurrent);\n }\n switch (this.state) {\n case State.KEY_LOADING:\n case State.FRAG_LOADING:\n case State.FRAG_LOADING_WAITING_RETRY:\n case State.PARSING:\n case State.PARSED:\n this.state = State.IDLE;\n break;\n }\n this.nextLoadPosition = this.getLoadPosition();\n }\n flushMainBuffer(startOffset, endOffset) {\n super.flushMainBuffer(startOffset, endOffset, this.altAudio === 2 ? 'video' : null);\n }\n onMediaAttached(event, data) {\n super.onMediaAttached(event, data);\n const media = data.media;\n addEventListener(media, 'playing', this.onMediaPlaying);\n addEventListener(media, 'seeked', this.onMediaSeeked);\n }\n onMediaDetaching(event, data) {\n const {\n media\n } = this;\n if (media) {\n removeEventListener(media, 'playing', this.onMediaPlaying);\n removeEventListener(media, 'seeked', this.onMediaSeeked);\n }\n this.videoBuffer = null;\n this.fragPlaying = null;\n super.onMediaDetaching(event, data);\n const transferringMedia = !!data.transferMedia;\n if (transferringMedia) {\n return;\n }\n this._hasEnoughToStart = false;\n }\n onManifestLoading() {\n super.onManifestLoading();\n // reset buffer on manifest loading\n this.log('Trigger BUFFER_RESET');\n this.hls.trigger(Events.BUFFER_RESET, undefined);\n this.couldBacktrack = false;\n this.fragLastKbps = 0;\n this.fragPlaying = this.backtrackFragment = null;\n this.altAudio = 0;\n this.audioOnly = false;\n }\n onManifestParsed(event, data) {\n // detect if we have different kind of audio codecs used amongst playlists\n let aac = false;\n let heaac = false;\n data.levels.forEach(level => {\n const codec = level.audioCodec;\n if (codec) {\n aac = aac || codec.indexOf('mp4a.40.2') !== -1;\n heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;\n }\n });\n this.audioCodecSwitch = aac && heaac && !changeTypeSupported();\n if (this.audioCodecSwitch) {\n this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');\n }\n this.levels = data.levels;\n this.startFragRequested = false;\n }\n onLevelLoading(event, data) {\n const {\n levels\n } = this;\n if (!levels || this.state !== State.IDLE) {\n return;\n }\n const level = data.levelInfo;\n if (!level.details || level.details.live && (this.levelLastLoaded !== level || level.details.expired) || this.waitForCdnTuneIn(level.details)) {\n this.state = State.WAITING_LEVEL;\n }\n }\n onLevelLoaded(event, data) {\n var _curLevel$details;\n const {\n levels,\n startFragRequested\n } = this;\n const newLevelId = data.level;\n const newDetails = data.details;\n const duration = newDetails.totalduration;\n if (!levels) {\n this.warn(`Levels were reset while loading level ${newLevelId}`);\n return;\n }\n this.log(`Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${newDetails.lastPartSn ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]` : ''}, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`);\n const curLevel = data.levelInfo;\n const fragCurrent = this.fragCurrent;\n if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {\n if (fragCurrent.level !== data.level && fragCurrent.loader) {\n this.abortCurrentFrag();\n }\n }\n let sliding = 0;\n if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {\n var _this$levelLastLoaded;\n this.checkLiveUpdate(newDetails);\n if (newDetails.deltaUpdateFailed) {\n return;\n }\n sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);\n }\n // override level info\n curLevel.details = newDetails;\n this.levelLastLoaded = curLevel;\n if (!startFragRequested) {\n this.setStartPosition(newDetails, sliding);\n }\n this.hls.trigger(Events.LEVEL_UPDATED, {\n details: newDetails,\n level: newLevelId\n });\n\n // only switch back to IDLE state if we were waiting for level to start downloading a new fragment\n if (this.state === State.WAITING_LEVEL) {\n if (this.waitForCdnTuneIn(newDetails)) {\n // Wait for Low-Latency CDN Tune-in\n return;\n }\n this.state = State.IDLE;\n }\n if (startFragRequested && newDetails.live) {\n this.synchronizeToLiveEdge(newDetails);\n }\n\n // trigger handler right now\n this.tick();\n }\n synchronizeToLiveEdge(levelDetails) {\n const {\n config,\n media\n } = this;\n if (!media) {\n return;\n }\n const liveSyncPosition = this.hls.liveSyncPosition;\n const currentTime = this.getLoadPosition();\n const start = levelDetails.fragmentStart;\n const end = levelDetails.edge;\n const withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;\n // Continue if we can seek forward to sync position or if current time is outside of sliding window\n if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {\n // Continue if buffer is starving or if current time is behind max latency\n const maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {\n if (!this._hasEnoughToStart) {\n this.nextLoadPosition = liveSyncPosition;\n }\n // Only seek if ready and there is not a significant forward buffer available for playback\n if (media.readyState) {\n this.warn(`Playback: ${currentTime.toFixed(3)} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);\n media.currentTime = liveSyncPosition;\n }\n }\n }\n }\n _handleFragmentLoadProgress(data) {\n var _frag$initSegment;\n const frag = data.frag;\n const {\n part,\n payload\n } = data;\n const {\n levels\n } = this;\n if (!levels) {\n this.warn(`Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`);\n return;\n }\n const currentLevel = levels[frag.level];\n if (!currentLevel) {\n this.warn(`Level ${frag.level} not found on progress`);\n return;\n }\n const details = currentLevel.details;\n if (!details) {\n this.warn(`Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`);\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n const videoCodec = currentLevel.videoCodec;\n\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n const accurateTimeOffset = details.PTSKnown || !details.live;\n const initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;\n const audioCodec = this._getAudioCodec(currentLevel);\n\n // transmux the MPEG-TS data to ISO-BMFF segments\n // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);\n const transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));\n const partIndex = part ? part.index : -1;\n const partial = partIndex !== -1;\n const chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);\n const initPTS = this.initPTS[frag.cc];\n transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);\n }\n onAudioTrackSwitching(event, data) {\n const hls = this.hls;\n // if any URL found on new audio track, it is an alternate audio track\n const fromAltAudio = this.altAudio === 2;\n const altAudio = useAlternateAudio(data.url, hls);\n // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered\n // don't do anything if we switch to alt audio: audio stream controller is handling it.\n // we will just have to change buffer scheduling on audioTrackSwitched\n if (!altAudio) {\n if (this.mediaBuffer !== this.media) {\n this.log('Switching on main audio, use media.buffered to schedule main fragment loading');\n this.mediaBuffer = this.media;\n const fragCurrent = this.fragCurrent;\n // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch\n if (fragCurrent) {\n this.log('Switching to main audio track, cancel main fragment load');\n fragCurrent.abortRequests();\n this.fragmentTracker.removeFragment(fragCurrent);\n }\n // destroy transmuxer to force init segment generation (following audio switch)\n this.resetTransmuxer();\n // switch to IDLE state to load new fragment\n this.resetLoadingState();\n } else if (this.audioOnly) {\n // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off\n this.resetTransmuxer();\n }\n // If switching from alt to main audio, flush all audio and trigger track switched\n if (fromAltAudio) {\n this.fragmentTracker.removeAllFragments();\n hls.once(Events.BUFFER_FLUSHED, () => {\n var _this$hls;\n (_this$hls = this.hls) == null ? void 0 : _this$hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);\n });\n hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: Number.POSITIVE_INFINITY,\n type: null\n });\n return;\n }\n hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);\n } else {\n this.altAudio = 1;\n }\n }\n onAudioTrackSwitched(event, data) {\n const altAudio = useAlternateAudio(data.url, this.hls);\n if (altAudio) {\n const videoBuffer = this.videoBuffer;\n // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered\n if (videoBuffer && this.mediaBuffer !== videoBuffer) {\n this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');\n this.mediaBuffer = videoBuffer;\n }\n }\n this.altAudio = altAudio ? 2 : 0;\n this.tick();\n }\n onBufferCreated(event, data) {\n const tracks = data.tracks;\n let mediaTrack;\n let name;\n let alternate = false;\n for (const type in tracks) {\n const track = tracks[type];\n if (track.id === 'main') {\n name = type;\n mediaTrack = track;\n // keep video source buffer reference\n if (type === 'video') {\n const videoTrack = tracks[type];\n if (videoTrack) {\n this.videoBuffer = videoTrack.buffer;\n }\n }\n } else {\n alternate = true;\n }\n }\n if (alternate && mediaTrack) {\n this.log(`Alternate track found, use ${name}.buffered to schedule main fragment loading`);\n this.mediaBuffer = mediaTrack.buffer;\n } else {\n this.mediaBuffer = this.media;\n }\n }\n onFragBuffered(event, data) {\n const {\n frag,\n part\n } = data;\n const bufferedMainFragment = frag.type === PlaylistLevelType.MAIN;\n if (bufferedMainFragment) {\n if (this.fragContextChanged(frag)) {\n // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion\n // Avoid setting state back to IDLE, since that will interfere with a level switch\n this.warn(`Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${frag.level} finished buffering, but was aborted. state: ${this.state}`);\n if (this.state === State.PARSED) {\n this.state = State.IDLE;\n }\n return;\n }\n const stats = part ? part.stats : frag.stats;\n this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));\n if (isMediaFragment(frag)) {\n this.fragPrevious = frag;\n }\n this.fragBufferedComplete(frag, part);\n }\n const media = this.media;\n if (!media) {\n return;\n }\n if (!this._hasEnoughToStart && BufferHelper.getBuffered(media).length) {\n this._hasEnoughToStart = true;\n this.seekToStartPos();\n }\n if (bufferedMainFragment) {\n this.tick();\n }\n }\n get hasEnoughToStart() {\n return this._hasEnoughToStart;\n }\n onError(event, data) {\n var _data$context;\n if (data.fatal) {\n this.state = State.ERROR;\n return;\n }\n switch (data.details) {\n case ErrorDetails.FRAG_GAP:\n case ErrorDetails.FRAG_PARSING_ERROR:\n case ErrorDetails.FRAG_DECRYPT_ERROR:\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n case ErrorDetails.LEVEL_PARSING_ERROR:\n // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE\n if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {\n this.state = State.IDLE;\n }\n break;\n case ErrorDetails.BUFFER_ADD_CODEC_ERROR:\n case ErrorDetails.BUFFER_APPEND_ERROR:\n if (data.parent !== 'main') {\n return;\n }\n this.resetLoadingState();\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n if (data.parent !== 'main') {\n return;\n }\n if (this.reduceLengthAndFlushBuffer(data)) {\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n break;\n case ErrorDetails.INTERNAL_EXCEPTION:\n this.recoverWorkerError(data);\n break;\n }\n }\n onFragLoadEmergencyAborted() {\n this.state = State.IDLE;\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this._hasEnoughToStart) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.lastCurrentTime;\n }\n this.tickImmediate();\n }\n onBufferFlushed(event, {\n type\n }) {\n if (type !== ElementaryStreamTypes.AUDIO || !this.altAudio) {\n const mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;\n if (mediaBuffer) {\n this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);\n this.tick();\n }\n }\n }\n onLevelsUpdated(event, data) {\n if (this.level > -1 && this.fragCurrent) {\n this.level = this.fragCurrent.level;\n if (this.level === -1) {\n this.resetWhenMissingContext(this.fragCurrent);\n }\n }\n this.levels = data.levels;\n }\n swapAudioCodec() {\n this.audioCodecSwap = !this.audioCodecSwap;\n }\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n */\n seekToStartPos() {\n const {\n media\n } = this;\n if (!media) {\n return;\n }\n const currentTime = media.currentTime;\n let startPosition = this.startPosition;\n // only adjust currentTime if different from startPosition or if startPosition not buffered\n // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n if (startPosition >= 0 && currentTime < startPosition) {\n if (media.seeking) {\n this.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);\n return;\n }\n\n // Offset start position by timeline offset\n const timelineOffset = this.timelineOffset;\n if (timelineOffset && startPosition) {\n startPosition += timelineOffset;\n }\n const details = this.getLevelDetails();\n const buffered = BufferHelper.getBuffered(media);\n const bufferStart = buffered.length ? buffered.start(0) : 0;\n const delta = bufferStart - startPosition;\n const skipTolerance = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);\n if (delta > 0 && (delta < skipTolerance || this.loadingParts && delta < 2 * ((details == null ? void 0 : details.partTarget) || 0))) {\n this.log(`adjusting start position by ${delta} to match buffer start`);\n startPosition += delta;\n this.startPosition = startPosition;\n }\n if (currentTime < startPosition) {\n this.log(`seek to target start position ${startPosition} from current time ${currentTime} buffer start ${bufferStart}`);\n media.currentTime = startPosition;\n }\n }\n }\n _getAudioCodec(currentLevel) {\n let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if (this.audioCodecSwap && audioCodec) {\n this.log('Swapping audio codec');\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n return audioCodec;\n }\n _loadBitrateTestFrag(fragment, level) {\n fragment.bitrateTest = true;\n this._doFragLoad(fragment, level).then(data => {\n const {\n hls\n } = this;\n const frag = data == null ? void 0 : data.frag;\n if (!frag || this.fragContextChanged(frag)) {\n return;\n }\n level.fragmentError = 0;\n this.state = State.IDLE;\n this.startFragRequested = false;\n this.bitrateTest = false;\n const stats = frag.stats;\n // Bitrate tests fragments are neither parsed nor buffered\n stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();\n hls.trigger(Events.FRAG_LOADED, data);\n frag.bitrateTest = false;\n });\n }\n _handleTransmuxComplete(transmuxResult) {\n var _id3$samples;\n const id = this.playlistType;\n const {\n hls\n } = this;\n const {\n remuxResult,\n chunkMeta\n } = transmuxResult;\n const context = this.getCurrentContext(chunkMeta);\n if (!context) {\n this.resetWhenMissingContext(chunkMeta);\n return;\n }\n const {\n frag,\n part,\n level\n } = context;\n const {\n video,\n text,\n id3,\n initSegment\n } = remuxResult;\n const {\n details\n } = level;\n // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track\n const audio = this.altAudio ? undefined : remuxResult.audio;\n\n // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.\n // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.\n if (this.fragContextChanged(frag)) {\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n this.state = State.PARSING;\n if (initSegment) {\n if (initSegment != null && initSegment.tracks) {\n const mapFragment = frag.initSegment || frag;\n this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);\n hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {\n frag: mapFragment,\n id,\n tracks: initSegment.tracks\n });\n }\n\n // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038\n const initPTS = initSegment.initPTS;\n const timescale = initSegment.timescale;\n if (isFiniteNumber(initPTS)) {\n this.initPTS[frag.cc] = {\n baseTime: initPTS,\n timescale\n };\n hls.trigger(Events.INIT_PTS_FOUND, {\n frag,\n id,\n initPTS,\n timescale\n });\n }\n }\n\n // Avoid buffering if backtracking this fragment\n if (video && details) {\n if (audio && video.type === 'audiovideo') {\n this.logMuxedErr(frag);\n }\n const prevFrag = details.fragments[frag.sn - 1 - details.startSN];\n const isFirstFragment = frag.sn === details.startSN;\n const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;\n if (remuxResult.independent !== false) {\n const {\n startPTS,\n endPTS,\n startDTS,\n endDTS\n } = video;\n if (part) {\n part.elementaryStreams[video.type] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS\n };\n } else {\n if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {\n this.couldBacktrack = true;\n }\n if (video.dropped && video.independent) {\n // Backtrack if dropped frames create a gap after currentTime\n\n const bufferInfo = this.getMainFwdBufferInfo();\n const targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;\n const startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;\n if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {\n this.backtrack(frag);\n return;\n } else if (isFirstInDiscontinuity) {\n // Mark segment with a gap to avoid loop loading\n frag.gap = true;\n }\n // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial\n frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);\n } else if (isFirstFragment && startPTS - (details.appliedTimelineOffset || 0) > MAX_START_GAP_JUMP) {\n // Mark segment with a gap to skip large start gap\n frag.gap = true;\n }\n }\n frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);\n if (this.backtrackFragment) {\n this.backtrackFragment = frag;\n }\n this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);\n } else if (isFirstFragment || isFirstInDiscontinuity) {\n // Mark segment with a gap to avoid loop loading\n frag.gap = true;\n } else {\n this.backtrack(frag);\n return;\n }\n }\n if (audio) {\n const {\n startPTS,\n endPTS,\n startDTS,\n endDTS\n } = audio;\n if (part) {\n part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS\n };\n }\n frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);\n this.bufferFragmentData(audio, frag, part, chunkMeta);\n }\n if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {\n const emittedID3 = {\n id,\n frag,\n details,\n samples: id3.samples\n };\n hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);\n }\n if (details && text) {\n const emittedText = {\n id,\n frag,\n details,\n samples: text.samples\n };\n hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);\n }\n }\n logMuxedErr(frag) {\n this.warn(`${isMediaFragment(frag) ? 'Media' : 'Init'} segment with muxed audiovideo where only video expected: ${frag.url}`);\n }\n _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {\n if (this.state !== State.PARSING) {\n return;\n }\n this.audioOnly = !!tracks.audio && !tracks.video;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (this.altAudio && !this.audioOnly) {\n delete tracks.audio;\n if (tracks.audiovideo) {\n this.logMuxedErr(frag);\n }\n }\n // include levelCodec in audio and video tracks\n const {\n audio,\n video,\n audiovideo\n } = tracks;\n if (audio) {\n let audioCodec = pickMostCompleteCodecName(audio.codec, currentLevel.audioCodec);\n // Add level and profile to make up for passthrough-remuxer not being able to parse full codec\n // (logger warning \"Unhandled audio codec...\")\n if (audioCodec === 'mp4a') {\n audioCodec = 'mp4a.40.5';\n }\n // Handle `audioCodecSwitch`\n const ua = navigator.userAgent.toLowerCase();\n if (this.audioCodecSwitch) {\n if (audioCodec) {\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n // In the case that AAC and HE-AAC audio codecs are signalled in manifest,\n // force HE-AAC, as it seems that most browsers prefers it.\n // don't force HE-AAC if mono stream, or in Firefox\n const audioMetadata = audio.metadata;\n if (audioMetadata && 'channelCount' in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf('firefox') === -1) {\n audioCodec = 'mp4a.40.5';\n }\n }\n // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n if (audioCodec && audioCodec.indexOf('mp4a.40.5') !== -1 && ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {\n // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n this.log(`Android: force audio codec to ${audioCodec}`);\n }\n if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {\n this.log(`Swapping manifest audio codec \"${currentLevel.audioCodec}\" for \"${audioCodec}\"`);\n }\n audio.levelCodec = audioCodec;\n audio.id = PlaylistLevelType.MAIN;\n this.log(`Init audio buffer, container:${audio.container}, codecs[selected/level/parsed]=[${audioCodec || ''}/${currentLevel.audioCodec || ''}/${audio.codec}]`);\n delete tracks.audiovideo;\n }\n if (video) {\n video.levelCodec = currentLevel.videoCodec;\n video.id = PlaylistLevelType.MAIN;\n const parsedVideoCodec = video.codec;\n if ((parsedVideoCodec == null ? void 0 : parsedVideoCodec.length) === 4) {\n // Make up for passthrough-remuxer not being able to parse full codec\n // (logger warning \"Unhandled video codec...\")\n switch (parsedVideoCodec) {\n case 'hvc1':\n case 'hev1':\n video.codec = 'hvc1.1.6.L120.90';\n break;\n case 'av01':\n video.codec = 'av01.0.04M.08';\n break;\n case 'avc1':\n video.codec = 'avc1.42e01e';\n break;\n }\n }\n this.log(`Init video buffer, container:${video.container}, codecs[level/parsed]=[${currentLevel.videoCodec || ''}/${parsedVideoCodec}]${video.codec !== parsedVideoCodec ? ' parsed-corrected=' + video.codec : ''}${video.supplemental ? ' supplemental=' + video.supplemental : ''}`);\n delete tracks.audiovideo;\n }\n if (audiovideo) {\n this.log(`Init audiovideo buffer, container:${audiovideo.container}, codecs[level/parsed]=[${currentLevel.codecs}/${audiovideo.codec}]`);\n delete tracks.video;\n delete tracks.audio;\n }\n const trackTypes = Object.keys(tracks);\n if (trackTypes.length) {\n this.hls.trigger(Events.BUFFER_CODECS, tracks);\n if (!this.hls) {\n // Exit after fatal tracks error\n return;\n }\n // loop through tracks that are going to be provided to bufferController\n trackTypes.forEach(trackName => {\n const track = tracks[trackName];\n const initSegment = track.initSegment;\n if (initSegment != null && initSegment.byteLength) {\n this.hls.trigger(Events.BUFFER_APPENDING, {\n type: trackName,\n data: initSegment,\n frag,\n part: null,\n chunkMeta,\n parent: frag.type\n });\n }\n });\n }\n // trigger handler right now\n this.tickImmediate();\n }\n getMainFwdBufferInfo() {\n // Observe video SourceBuffer (this.mediaBuffer) only when alt-audio is used, otherwise observe combined media buffer\n const bufferOutput = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;\n return this.getFwdBufferInfo(bufferOutput, PlaylistLevelType.MAIN);\n }\n get maxBufferLength() {\n const {\n levels,\n level\n } = this;\n const levelInfo = levels == null ? void 0 : levels[level];\n if (!levelInfo) {\n return this.config.maxBufferLength;\n }\n return this.getMaxBufferLength(levelInfo.maxBitrate);\n }\n backtrack(frag) {\n this.couldBacktrack = true;\n // Causes findFragments to backtrack through fragments to find the keyframe\n this.backtrackFragment = frag;\n this.resetTransmuxer();\n this.flushBufferGap(frag);\n this.fragmentTracker.removeFragment(frag);\n this.fragPrevious = null;\n this.nextLoadPosition = frag.start;\n this.state = State.IDLE;\n }\n checkFragmentChanged() {\n const video = this.media;\n let fragPlayingCurrent = null;\n if (video && video.readyState > 1 && video.seeking === false) {\n const currentTime = video.currentTime;\n /* if video element is in seeked state, currentTime can only increase.\n (assuming that playback rate is positive ...)\n As sometimes currentTime jumps back to zero after a\n media decode error, check this, to avoid seeking back to\n wrong position after a media decode error\n */\n\n if (BufferHelper.isBuffered(video, currentTime)) {\n fragPlayingCurrent = this.getAppendedFrag(currentTime);\n } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {\n /* ensure that FRAG_CHANGED event is triggered at startup,\n when first video frame is displayed and playback is paused.\n add a tolerance of 100ms, in case current position is not buffered,\n check if current pos+100ms is buffered and use that buffer range\n for FRAG_CHANGED event reporting */\n fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);\n }\n if (fragPlayingCurrent) {\n this.backtrackFragment = null;\n const fragPlaying = this.fragPlaying;\n const fragCurrentLevel = fragPlayingCurrent.level;\n if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {\n this.fragPlaying = fragPlayingCurrent;\n this.hls.trigger(Events.FRAG_CHANGED, {\n frag: fragPlayingCurrent\n });\n if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {\n this.hls.trigger(Events.LEVEL_SWITCHED, {\n level: fragCurrentLevel\n });\n }\n }\n }\n }\n }\n get nextLevel() {\n const frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n }\n return -1;\n }\n get currentFrag() {\n var _this$media3;\n if (this.fragPlaying) {\n return this.fragPlaying;\n }\n const currentTime = ((_this$media3 = this.media) == null ? void 0 : _this$media3.currentTime) || this.lastCurrentTime;\n if (isFiniteNumber(currentTime)) {\n return this.getAppendedFrag(currentTime);\n }\n return null;\n }\n get currentProgramDateTime() {\n var _this$media4;\n const currentTime = ((_this$media4 = this.media) == null ? void 0 : _this$media4.currentTime) || this.lastCurrentTime;\n if (isFiniteNumber(currentTime)) {\n const details = this.getLevelDetails();\n const frag = this.currentFrag || (details ? findFragmentByPTS(null, details.fragments, currentTime) : null);\n if (frag) {\n const programDateTime = frag.programDateTime;\n if (programDateTime !== null) {\n const epocMs = programDateTime + (currentTime - frag.start) * 1000;\n return new Date(epocMs);\n }\n }\n }\n return null;\n }\n get currentLevel() {\n const frag = this.currentFrag;\n if (frag) {\n return frag.level;\n }\n return -1;\n }\n get nextBufferedFrag() {\n const frag = this.currentFrag;\n if (frag) {\n return this.followingBufferedFrag(frag);\n }\n return null;\n }\n get forceStartLoad() {\n return this._forceStartLoad;\n }\n}\n\nclass KeyLoader {\n constructor(config) {\n this.config = void 0;\n this.keyUriToKeyInfo = {};\n this.emeController = null;\n this.config = config;\n }\n abort(type) {\n for (const uri in this.keyUriToKeyInfo) {\n const loader = this.keyUriToKeyInfo[uri].loader;\n if (loader) {\n var _loader$context;\n if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {\n return;\n }\n loader.abort();\n }\n }\n }\n detach() {\n for (const uri in this.keyUriToKeyInfo) {\n const keyInfo = this.keyUriToKeyInfo[uri];\n // Remove cached EME keys on detach\n if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {\n delete this.keyUriToKeyInfo[uri];\n }\n }\n }\n destroy() {\n this.detach();\n for (const uri in this.keyUriToKeyInfo) {\n const loader = this.keyUriToKeyInfo[uri].loader;\n if (loader) {\n loader.destroy();\n }\n }\n this.keyUriToKeyInfo = {};\n }\n createKeyLoadError(frag, details = ErrorDetails.KEY_LOAD_ERROR, error, networkDetails, response) {\n return new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal: false,\n frag,\n response,\n error,\n networkDetails\n });\n }\n loadClear(loadingFrag, encryptedFragments) {\n if (this.emeController && this.config.emeEnabled) {\n // access key-system with nearest key on start (loaidng frag is unencrypted)\n const {\n sn,\n cc\n } = loadingFrag;\n for (let i = 0; i < encryptedFragments.length; i++) {\n const frag = encryptedFragments[i];\n if (cc <= frag.cc && (sn === 'initSegment' || frag.sn === 'initSegment' || sn < frag.sn)) {\n this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {\n frag.setKeyFormat(keySystemFormat);\n });\n break;\n }\n }\n }\n }\n load(frag) {\n if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) {\n // Multiple keys, but none selected, resolve in eme-controller\n return this.emeController.selectKeySystemFormat(frag).then(keySystemFormat => {\n return this.loadInternal(frag, keySystemFormat);\n });\n }\n return this.loadInternal(frag);\n }\n loadInternal(frag, keySystemFormat) {\n var _keyInfo, _keyInfo2;\n if (keySystemFormat) {\n frag.setKeyFormat(keySystemFormat);\n }\n const decryptdata = frag.decryptdata;\n if (!decryptdata) {\n const error = new Error(keySystemFormat ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}` : 'Missing decryption data on fragment in onKeyLoading');\n return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));\n }\n const uri = decryptdata.uri;\n if (!uri) {\n return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Invalid key URI: \"${uri}\"`)));\n }\n let keyInfo = this.keyUriToKeyInfo[uri];\n if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {\n decryptdata.key = keyInfo.decryptdata.key;\n return Promise.resolve({\n frag,\n keyInfo\n });\n }\n // Return key load promise as long as it does not have a mediakey session with an unusable key status\n if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {\n var _keyInfo$mediaKeySess;\n switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {\n case undefined:\n case 'status-pending':\n case 'usable':\n case 'usable-in-future':\n return keyInfo.keyLoadPromise.then(keyLoadedData => {\n // Return the correct fragment with updated decryptdata key and loaded keyInfo\n decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;\n return {\n frag,\n keyInfo\n };\n });\n }\n // If we have a key session and status and it is not pending or usable, continue\n // This will go back to the eme-controller for expired keys to get a new keyLoadPromise\n }\n\n // Load the key or return the loading promise\n keyInfo = this.keyUriToKeyInfo[uri] = {\n decryptdata,\n keyLoadPromise: null,\n loader: null,\n mediaKeySessionContext: null\n };\n switch (decryptdata.method) {\n case 'ISO-23001-7':\n case 'SAMPLE-AES':\n case 'SAMPLE-AES-CENC':\n case 'SAMPLE-AES-CTR':\n if (decryptdata.keyFormat === 'identity') {\n // loadKeyHTTP handles http(s) and data URLs\n return this.loadKeyHTTP(keyInfo, frag);\n }\n return this.loadKeyEME(keyInfo, frag);\n case 'AES-128':\n case 'AES-256':\n case 'AES-256-CTR':\n return this.loadKeyHTTP(keyInfo, frag);\n default:\n return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`Key supplied with unsupported METHOD: \"${decryptdata.method}\"`)));\n }\n }\n loadKeyEME(keyInfo, frag) {\n const keyLoadedData = {\n frag,\n keyInfo\n };\n if (this.emeController && this.config.emeEnabled) {\n const keySessionContextPromise = this.emeController.loadKey(keyLoadedData);\n if (keySessionContextPromise) {\n return (keyInfo.keyLoadPromise = keySessionContextPromise.then(keySessionContext => {\n keyInfo.mediaKeySessionContext = keySessionContext;\n return keyLoadedData;\n })).catch(error => {\n // Remove promise for license renewal or retry\n keyInfo.keyLoadPromise = null;\n throw error;\n });\n }\n }\n return Promise.resolve(keyLoadedData);\n }\n loadKeyHTTP(keyInfo, frag) {\n const config = this.config;\n const Loader = config.loader;\n const keyLoader = new Loader(config);\n frag.keyLoader = keyInfo.loader = keyLoader;\n return keyInfo.keyLoadPromise = new Promise((resolve, reject) => {\n const loaderContext = {\n keyInfo,\n frag,\n responseType: 'arraybuffer',\n url: keyInfo.decryptdata.uri\n };\n\n // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,\n // key-loader will trigger an error and rely on stream-controller to handle retry logic.\n // this will also align retry logic with fragment-loader\n const loadPolicy = config.keyLoadPolicy.default;\n const loaderConfig = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0\n };\n const loaderCallbacks = {\n onSuccess: (response, stats, context, networkDetails) => {\n const {\n frag,\n keyInfo,\n url: uri\n } = context;\n if (!frag.decryptdata || keyInfo !== this.keyUriToKeyInfo[uri]) {\n return reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error('after key load, decryptdata unset or changed'), networkDetails));\n }\n keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(response.data);\n\n // detach fragment key loader on load success\n frag.keyLoader = null;\n keyInfo.loader = null;\n resolve({\n frag,\n keyInfo\n });\n },\n onError: (response, context, networkDetails, stats) => {\n this.resetLoader(context);\n reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error(`HTTP Error ${response.code} loading key ${response.text}`), networkDetails, _objectSpread2({\n url: loaderContext.url,\n data: undefined\n }, response)));\n },\n onTimeout: (stats, context, networkDetails) => {\n this.resetLoader(context);\n reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error('key loading timed out'), networkDetails));\n },\n onAbort: (stats, context, networkDetails) => {\n this.resetLoader(context);\n reject(this.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error('key loading aborted'), networkDetails));\n }\n };\n keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);\n });\n }\n resetLoader(context) {\n const {\n frag,\n keyInfo,\n url: uri\n } = context;\n const loader = keyInfo.loader;\n if (frag.keyLoader === loader) {\n frag.keyLoader = null;\n keyInfo.loader = null;\n }\n delete this.keyUriToKeyInfo[uri];\n if (loader) {\n loader.destroy();\n }\n }\n}\n\nfunction mapContextToLevelType(context) {\n const {\n type\n } = context;\n switch (type) {\n case PlaylistContextType.AUDIO_TRACK:\n return PlaylistLevelType.AUDIO;\n case PlaylistContextType.SUBTITLE_TRACK:\n return PlaylistLevelType.SUBTITLE;\n default:\n return PlaylistLevelType.MAIN;\n }\n}\nfunction getResponseUrl(response, context) {\n let url = response.url;\n // responseURL not supported on some browsers (it is used to detect URL redirection)\n // data-uri mode also not supported (but no need to detect redirection)\n if (url === undefined || url.indexOf('data:') === 0) {\n // fallback to initial URL\n url = context.url;\n }\n return url;\n}\nclass PlaylistLoader {\n constructor(hls) {\n this.hls = void 0;\n this.loaders = Object.create(null);\n this.variableList = null;\n this.onManifestLoaded = this.checkAutostartLoad;\n this.hls = hls;\n this.registerListeners();\n }\n startLoad(startPosition) {}\n stopLoad() {\n this.destroyInternalLoaders();\n }\n registerListeners() {\n const {\n hls\n } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);\n hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n }\n unregisterListeners() {\n const {\n hls\n } = this;\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);\n hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n }\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n */\n createInternalLoader(context) {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n const InternalLoader = PLoader || Loader;\n const loader = new InternalLoader(config);\n this.loaders[context.type] = loader;\n return loader;\n }\n getInternalLoader(context) {\n return this.loaders[context.type];\n }\n resetInternalLoader(contextType) {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n }\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n destroyInternalLoaders() {\n for (const contextType in this.loaders) {\n const loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n this.resetInternalLoader(contextType);\n }\n }\n destroy() {\n this.variableList = null;\n this.unregisterListeners();\n this.destroyInternalLoaders();\n }\n onManifestLoading(event, data) {\n const {\n url\n } = data;\n this.variableList = null;\n this.load({\n id: null,\n level: 0,\n responseType: 'text',\n type: PlaylistContextType.MANIFEST,\n url,\n deliveryDirectives: null,\n levelOrTrack: null\n });\n }\n onLevelLoading(event, data) {\n const {\n id,\n level,\n pathwayId,\n url,\n deliveryDirectives,\n levelInfo\n } = data;\n this.load({\n id,\n level,\n pathwayId,\n responseType: 'text',\n type: PlaylistContextType.LEVEL,\n url,\n deliveryDirectives,\n levelOrTrack: levelInfo\n });\n }\n onAudioTrackLoading(event, data) {\n const {\n id,\n groupId,\n url,\n deliveryDirectives,\n track\n } = data;\n this.load({\n id,\n groupId,\n level: null,\n responseType: 'text',\n type: PlaylistContextType.AUDIO_TRACK,\n url,\n deliveryDirectives,\n levelOrTrack: track\n });\n }\n onSubtitleTrackLoading(event, data) {\n const {\n id,\n groupId,\n url,\n deliveryDirectives,\n track\n } = data;\n this.load({\n id,\n groupId,\n level: null,\n responseType: 'text',\n type: PlaylistContextType.SUBTITLE_TRACK,\n url,\n deliveryDirectives,\n levelOrTrack: track\n });\n }\n onLevelsUpdated(event, data) {\n // abort and delete loader of removed levels\n const loader = this.loaders[PlaylistContextType.LEVEL];\n if (loader) {\n const context = loader.context;\n if (context && !data.levels.some(lvl => lvl === context.levelOrTrack)) {\n loader.abort();\n delete this.loaders[PlaylistContextType.LEVEL];\n }\n }\n }\n load(context) {\n var _context$deliveryDire;\n const config = this.hls.config;\n\n // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const logger = this.hls.logger;\n const loaderContext = loader.context;\n if (loaderContext && loaderContext.levelOrTrack === context.levelOrTrack && (loaderContext.url === context.url || loaderContext.deliveryDirectives && !context.deliveryDirectives)) {\n // same URL can't overlap, or wait for blocking request\n if (loaderContext.url === context.url) {\n logger.log(`[playlist-loader]: ignore ${context.url} ongoing request`);\n } else {\n logger.log(`[playlist-loader]: ignore ${context.url} in favor of ${loaderContext.url}`);\n }\n return;\n }\n logger.log(`[playlist-loader]: aborting previous loader for type: ${context.type}`);\n loader.abort();\n }\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n let loadPolicy;\n if (context.type === PlaylistContextType.MANIFEST) {\n loadPolicy = config.manifestLoadPolicy.default;\n } else {\n loadPolicy = _extends({}, config.playlistLoadPolicy.default, {\n timeoutRetry: null,\n errorRetry: null\n });\n }\n loader = this.createInternalLoader(context);\n\n // Override level/track timeout for LL-HLS requests\n // (the default of 10000ms is counter productive to blocking playlist reload requests)\n if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {\n let levelDetails;\n if (context.type === PlaylistContextType.LEVEL && context.level !== null) {\n levelDetails = this.hls.levels[context.level].details;\n } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {\n levelDetails = this.hls.audioTracks[context.id].details;\n } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {\n levelDetails = this.hls.subtitleTracks[context.id].details;\n }\n if (levelDetails) {\n const partTarget = levelDetails.partTarget;\n const targetDuration = levelDetails.targetduration;\n if (partTarget && targetDuration) {\n const maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1000;\n loadPolicy = _extends({}, loadPolicy, {\n maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),\n maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)\n });\n }\n }\n }\n const legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};\n const loaderConfig = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: legacyRetryCompatibility.maxNumRetry || 0,\n retryDelay: legacyRetryCompatibility.retryDelayMs || 0,\n maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0\n };\n const loaderCallbacks = {\n onSuccess: (response, stats, context, networkDetails) => {\n const loader = this.getInternalLoader(context);\n this.resetInternalLoader(context.type);\n const string = response.data;\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this.handleManifestParsingError(response, context, new Error('no EXTM3U delimiter'), networkDetails || null, stats);\n return;\n }\n stats.parsing.start = performance.now();\n if (M3U8Parser.isMediaPlaylist(string) || context.type !== PlaylistContextType.MANIFEST) {\n this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails || null, loader);\n } else {\n this.handleMasterPlaylist(response, stats, context, networkDetails);\n }\n },\n onError: (response, context, networkDetails, stats) => {\n this.handleNetworkError(context, networkDetails, false, response, stats);\n },\n onTimeout: (stats, context, networkDetails) => {\n this.handleNetworkError(context, networkDetails, true, undefined, stats);\n }\n };\n\n // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);\n\n loader.load(context, loaderConfig, loaderCallbacks);\n }\n checkAutostartLoad() {\n if (!this.hls) {\n return;\n }\n const {\n config: {\n autoStartLoad,\n startPosition\n },\n forceStartLoad\n } = this.hls;\n if (autoStartLoad || forceStartLoad) {\n this.hls.logger.log(`${autoStartLoad ? 'auto' : 'force'} startLoad with configured startPosition ${startPosition}`);\n this.hls.startLoad(startPosition);\n }\n }\n handleMasterPlaylist(response, stats, context, networkDetails) {\n const hls = this.hls;\n const string = response.data;\n const url = getResponseUrl(response, context);\n const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);\n if (parsedResult.playlistParsingError) {\n this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);\n return;\n }\n const {\n contentSteering,\n levels,\n sessionData,\n sessionKeys,\n startTimeOffset,\n variableList\n } = parsedResult;\n this.variableList = variableList;\n const {\n AUDIO: audioTracks = [],\n SUBTITLES: subtitles,\n 'CLOSED-CAPTIONS': captions\n } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);\n if (audioTracks.length) {\n // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n const embeddedAudioFound = audioTracks.some(audioTrack => !audioTrack.url);\n\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // contains both audio+video. but with mixed audio track not signaled\n if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {\n this.hls.logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');\n audioTracks.unshift({\n type: 'main',\n name: 'main',\n groupId: 'main',\n default: false,\n autoselect: false,\n forced: false,\n id: -1,\n attrs: new AttrList({}),\n bitrate: 0,\n url: ''\n });\n }\n }\n hls.trigger(Events.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n captions,\n contentSteering,\n url,\n stats,\n networkDetails,\n sessionData,\n sessionKeys,\n startTimeOffset,\n variableList\n });\n }\n handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {\n const hls = this.hls;\n const {\n id,\n level,\n type\n } = context;\n const url = getResponseUrl(response, context);\n const levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;\n const levelType = mapContextToLevelType(context);\n const levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, 0, this.variableList);\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === PlaylistContextType.MANIFEST) {\n const singleLevel = {\n attrs: new AttrList({}),\n bitrate: 0,\n details: levelDetails,\n name: '',\n url\n };\n levelDetails.requestScheduled = stats.loading.start + computeReloadInterval(levelDetails, 0);\n hls.trigger(Events.MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url,\n stats,\n networkDetails,\n sessionData: null,\n sessionKeys: null,\n contentSteering: null,\n startTimeOffset: null,\n variableList: null\n });\n }\n\n // save parsing time\n stats.parsing.end = performance.now();\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);\n }\n handleManifestParsingError(response, context, error, networkDetails, stats) {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.MANIFEST_PARSING_ERROR,\n fatal: context.type === PlaylistContextType.MANIFEST,\n url: response.url,\n err: error,\n error,\n reason: error.message,\n response,\n context,\n networkDetails,\n stats\n });\n }\n handleNetworkError(context, networkDetails, timeout = false, response, stats) {\n let message = `A network ${timeout ? 'timeout' : 'error' + (response ? ' (status ' + response.code + ')' : '')} occurred while loading ${context.type}`;\n if (context.type === PlaylistContextType.LEVEL) {\n message += `: ${context.level} id: ${context.id}`;\n } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {\n message += ` id: ${context.id} group-id: \"${context.groupId}\"`;\n }\n const error = new Error(message);\n this.hls.logger.warn(`[playlist-loader]: ${message}`);\n let details = ErrorDetails.UNKNOWN;\n let fatal = false;\n const loader = this.getInternalLoader(context);\n switch (context.type) {\n case PlaylistContextType.MANIFEST:\n details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;\n fatal = true;\n break;\n case PlaylistContextType.LEVEL:\n details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;\n fatal = false;\n break;\n case PlaylistContextType.AUDIO_TRACK:\n details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;\n fatal = false;\n break;\n case PlaylistContextType.SUBTITLE_TRACK:\n details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;\n fatal = false;\n break;\n }\n if (loader) {\n this.resetInternalLoader(context.type);\n }\n const errorData = {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: context.url,\n loader,\n context,\n error,\n networkDetails,\n stats\n };\n if (response) {\n const url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;\n errorData.response = _objectSpread2({\n url,\n data: undefined\n }, response);\n }\n this.hls.trigger(Events.ERROR, errorData);\n }\n handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {\n const hls = this.hls;\n const {\n type,\n level,\n id,\n groupId,\n deliveryDirectives\n } = context;\n const url = getResponseUrl(response, context);\n const parent = mapContextToLevelType(context);\n const levelIndex = typeof context.level === 'number' && parent === PlaylistLevelType.MAIN ? level : undefined;\n if (!levelDetails.fragments.length) {\n const _error = levelDetails.playlistParsingError = new Error('No Segments found in Playlist');\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_EMPTY_ERROR,\n fatal: false,\n url,\n error: _error,\n reason: _error.message,\n response,\n context,\n level: levelIndex,\n parent,\n networkDetails,\n stats\n });\n return;\n }\n if (!levelDetails.targetduration) {\n levelDetails.playlistParsingError = new Error('Missing Target Duration');\n }\n const error = levelDetails.playlistParsingError;\n if (error) {\n this.hls.logger.warn(error);\n if (!hls.config.ignorePlaylistParsingErrors) {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_PARSING_ERROR,\n fatal: false,\n url,\n error,\n reason: error.message,\n response,\n context,\n level: levelIndex,\n parent,\n networkDetails,\n stats\n });\n return;\n }\n levelDetails.playlistParsingError = null;\n }\n if (levelDetails.live && loader) {\n if (loader.getCacheAge) {\n levelDetails.ageHeader = loader.getCacheAge() || 0;\n }\n if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {\n levelDetails.ageHeader = 0;\n }\n }\n switch (type) {\n case PlaylistContextType.MANIFEST:\n case PlaylistContextType.LEVEL:\n hls.trigger(Events.LEVEL_LOADED, {\n details: levelDetails,\n levelInfo: context.levelOrTrack || hls.levels[0],\n level: levelIndex || 0,\n id: id || 0,\n stats,\n networkDetails,\n deliveryDirectives,\n withoutMultiVariant: type === PlaylistContextType.MANIFEST\n });\n break;\n case PlaylistContextType.AUDIO_TRACK:\n hls.trigger(Events.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n track: context.levelOrTrack,\n id: id || 0,\n groupId: groupId || '',\n stats,\n networkDetails,\n deliveryDirectives\n });\n break;\n case PlaylistContextType.SUBTITLE_TRACK:\n hls.trigger(Events.SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n track: context.levelOrTrack,\n id: id || 0,\n groupId: groupId || '',\n stats,\n networkDetails,\n deliveryDirectives\n });\n break;\n }\n }\n}\n\n/**\n * The `Hls` class is the core of the HLS.js library used to instantiate player instances.\n * @public\n */\nclass Hls {\n /**\n * Get the video-dev/hls.js package version.\n */\n static get version() {\n return version;\n }\n\n /**\n * Check if the required MediaSource Extensions are available.\n */\n static isMSESupported() {\n return isMSESupported();\n }\n\n /**\n * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.\n */\n static isSupported() {\n return isSupported();\n }\n\n /**\n * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).\n */\n static getMediaSource() {\n return getMediaSource();\n }\n static get Events() {\n return Events;\n }\n static get MetadataSchema() {\n return MetadataSchema;\n }\n static get ErrorTypes() {\n return ErrorTypes;\n }\n static get ErrorDetails() {\n return ErrorDetails;\n }\n\n /**\n * Get the default configuration applied to new instances.\n */\n static get DefaultConfig() {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n return Hls.defaultConfig;\n }\n\n /**\n * Replace the default configuration applied to new instances.\n */\n static set DefaultConfig(defaultConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n * @param userConfig - Configuration options applied over `Hls.DefaultConfig`\n */\n constructor(userConfig = {}) {\n /**\n * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.\n */\n this.config = void 0;\n /**\n * The configuration object provided on player instantiation.\n */\n this.userConfig = void 0;\n /**\n * The logger functions used by this player instance, configured on player instantiation.\n */\n this.logger = void 0;\n this.coreComponents = void 0;\n this.networkControllers = void 0;\n this._emitter = new EventEmitter();\n this._autoLevelCapping = -1;\n this._maxHdcpLevel = null;\n this.abrController = void 0;\n this.bufferController = void 0;\n this.capLevelController = void 0;\n this.latencyController = void 0;\n this.levelController = void 0;\n this.streamController = void 0;\n this.audioStreamController = void 0;\n this.subtititleStreamController = void 0;\n this.audioTrackController = void 0;\n this.subtitleTrackController = void 0;\n this.interstitialsController = void 0;\n this.gapController = void 0;\n this.emeController = void 0;\n this.cmcdController = void 0;\n this._media = null;\n this._url = null;\n this._sessionId = void 0;\n this.triggeringException = void 0;\n this.started = false;\n const logger = this.logger = enableLogs(userConfig.debug || false, 'Hls instance', userConfig.assetPlayerId);\n const config = this.config = mergeConfig(Hls.DefaultConfig, userConfig, logger);\n this.userConfig = userConfig;\n if (config.progressive) {\n enableStreamingMode(config, logger);\n }\n\n // core controllers and network loaders\n const {\n abrController: _AbrController,\n bufferController: _BufferController,\n capLevelController: _CapLevelController,\n errorController: _ErrorController,\n fpsController: _FpsController\n } = config;\n const errorController = new _ErrorController(this);\n const abrController = this.abrController = new _AbrController(this);\n // FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n const _InterstitialsController = config.interstitialsController;\n const interstitialsController = _InterstitialsController ? this.interstitialsController = new _InterstitialsController(this, Hls) : null;\n const bufferController = this.bufferController = new _BufferController(this, fragmentTracker);\n const capLevelController = this.capLevelController = new _CapLevelController(this);\n const fpsController = new _FpsController(this);\n const playListLoader = new PlaylistLoader(this);\n const _ContentSteeringController = config.contentSteeringController;\n // Instantiate ConentSteeringController before LevelController to receive Multivariant Playlist events first\n const contentSteering = _ContentSteeringController ? new _ContentSteeringController(this) : null;\n const levelController = this.levelController = new LevelController(this, contentSteering);\n const id3TrackController = new ID3TrackController(this);\n const keyLoader = new KeyLoader(this.config);\n const streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);\n const gapController = this.gapController = new GapController(this, fragmentTracker);\n\n // Cap level controller uses streamController to flush the buffer\n capLevelController.setStreamController(streamController);\n // fpsController uses streamController to switch when frames are being dropped\n fpsController.setStreamController(streamController);\n const networkControllers = [playListLoader, levelController, streamController];\n if (interstitialsController) {\n networkControllers.splice(1, 0, interstitialsController);\n }\n if (contentSteering) {\n networkControllers.splice(1, 0, contentSteering);\n }\n this.networkControllers = networkControllers;\n const coreComponents = [abrController, bufferController, gapController, capLevelController, fpsController, id3TrackController, fragmentTracker];\n this.audioTrackController = this.createController(config.audioTrackController, networkControllers);\n const AudioStreamControllerClass = config.audioStreamController;\n if (AudioStreamControllerClass) {\n networkControllers.push(this.audioStreamController = new AudioStreamControllerClass(this, fragmentTracker, keyLoader));\n }\n // Instantiate subtitleTrackController before SubtitleStreamController to receive level events first\n this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);\n const SubtitleStreamControllerClass = config.subtitleStreamController;\n if (SubtitleStreamControllerClass) {\n networkControllers.push(this.subtititleStreamController = new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));\n }\n this.createController(config.timelineController, coreComponents);\n keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);\n this.cmcdController = this.createController(config.cmcdController, coreComponents);\n this.latencyController = this.createController(LatencyController, coreComponents);\n this.coreComponents = coreComponents;\n\n // Error controller handles errors before and after all other controllers\n // This listener will be invoked after all other controllers error listeners\n networkControllers.push(errorController);\n const onErrorOut = errorController.onErrorOut;\n if (typeof onErrorOut === 'function') {\n this.on(Events.ERROR, onErrorOut, errorController);\n }\n // Autostart load handler\n this.on(Events.MANIFEST_LOADED, playListLoader.onManifestLoaded, playListLoader);\n }\n createController(ControllerClass, components) {\n if (ControllerClass) {\n const controllerInstance = new ControllerClass(this);\n if (components) {\n components.push(controllerInstance);\n }\n return controllerInstance;\n }\n return null;\n }\n\n // Delegate the EventEmitter through the public API of Hls.js\n on(event, listener, context = this) {\n this._emitter.on(event, listener, context);\n }\n once(event, listener, context = this) {\n this._emitter.once(event, listener, context);\n }\n removeAllListeners(event) {\n this._emitter.removeAllListeners(event);\n }\n off(event, listener, context = this, once) {\n this._emitter.off(event, listener, context, once);\n }\n listeners(event) {\n return this._emitter.listeners(event);\n }\n emit(event, name, eventObject) {\n return this._emitter.emit(event, name, eventObject);\n }\n trigger(event, eventObject) {\n if (this.config.debug) {\n return this.emit(event, event, eventObject);\n } else {\n try {\n return this.emit(event, event, eventObject);\n } catch (error) {\n this.logger.error('An internal error happened while handling event ' + event + '. Error message: \"' + error.message + '\". Here is a stacktrace:', error);\n // Prevent recursion in error event handlers that throw #5497\n if (!this.triggeringException) {\n this.triggeringException = true;\n const fatal = event === Events.ERROR;\n this.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n fatal,\n event,\n error\n });\n this.triggeringException = false;\n }\n }\n }\n return false;\n }\n listenerCount(event) {\n return this._emitter.listenerCount(event);\n }\n\n /**\n * Dispose of the instance\n */\n destroy() {\n this.logger.log('destroy');\n this.trigger(Events.DESTROYING, undefined);\n this.detachMedia();\n this.removeAllListeners();\n this._autoLevelCapping = -1;\n this._url = null;\n this.networkControllers.forEach(component => component.destroy());\n this.networkControllers.length = 0;\n this.coreComponents.forEach(component => component.destroy());\n this.coreComponents.length = 0;\n // Remove any references that could be held in config options or callbacks\n const config = this.config;\n config.xhrSetup = config.fetchSetup = undefined;\n // @ts-ignore\n this.userConfig = null;\n }\n\n /**\n * Attaches Hls.js to a media element\n */\n attachMedia(data) {\n if (!data || 'media' in data && !data.media) {\n const error = new Error(`attachMedia failed: invalid argument (${data})`);\n this.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.ATTACH_MEDIA_ERROR,\n fatal: true,\n error\n });\n return;\n }\n this.logger.log(`attachMedia`);\n if (this._media) {\n this.logger.warn(`media must be detached before attaching`);\n this.detachMedia();\n }\n const attachMediaSource = 'media' in data;\n const media = attachMediaSource ? data.media : data;\n const attachingData = attachMediaSource ? data : {\n media\n };\n this._media = media;\n this.trigger(Events.MEDIA_ATTACHING, attachingData);\n }\n\n /**\n * Detach Hls.js from the media\n */\n detachMedia() {\n this.logger.log('detachMedia');\n this.trigger(Events.MEDIA_DETACHING, {});\n this._media = null;\n }\n\n /**\n * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance\n */\n transferMedia() {\n this._media = null;\n const transferMedia = this.bufferController.transferMedia();\n this.trigger(Events.MEDIA_DETACHING, {\n transferMedia\n });\n return transferMedia;\n }\n\n /**\n * Set the source URL. Can be relative or absolute.\n */\n loadSource(url) {\n this.stopLoad();\n const media = this.media;\n const loadedSource = this._url;\n const loadingSource = this._url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {\n alwaysNormalize: true\n });\n this._autoLevelCapping = -1;\n this._maxHdcpLevel = null;\n this.logger.log(`loadSource:${loadingSource}`);\n if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {\n // Remove and re-create MediaSource\n this.detachMedia();\n this.attachMedia(media);\n }\n // when attaching to a source URL, trigger a playlist load\n this.trigger(Events.MANIFEST_LOADING, {\n url: url\n });\n }\n\n /**\n * Gets the currently loaded URL\n */\n get url() {\n return this._url;\n }\n\n /**\n * Whether or not enough has been buffered to seek to start position or use `media.currentTime` to determine next load position\n */\n get hasEnoughToStart() {\n return this.streamController.hasEnoughToStart;\n }\n\n /**\n * Get the startPosition set on startLoad(position) or on autostart with config.startPosition\n */\n get startPosition() {\n return this.streamController.startPositionValue;\n }\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param startPosition - Set the start position to stream from.\n * Defaults to -1 (None: starts from earliest point)\n */\n startLoad(startPosition = -1, skipSeekToStartPosition) {\n this.logger.log(`startLoad(${startPosition + (skipSeekToStartPosition ? ', <skip seek to start>' : '')})`);\n this.started = true;\n this.resumeBuffering();\n for (let i = 0; i < this.networkControllers.length; i++) {\n this.networkControllers[i].startLoad(startPosition, skipSeekToStartPosition);\n if (!this.started || !this.networkControllers) {\n break;\n }\n }\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad() {\n this.logger.log('stopLoad');\n this.started = false;\n for (let i = 0; i < this.networkControllers.length; i++) {\n this.networkControllers[i].stopLoad();\n if (this.started || !this.networkControllers) {\n break;\n }\n }\n }\n\n /**\n * Returns whether loading, toggled with `startLoad()` and `stopLoad()`, is active or not`.\n */\n get loadingEnabled() {\n return this.started;\n }\n\n /**\n * Returns state of fragment loading toggled by calling `pauseBuffering()` and `resumeBuffering()`.\n */\n get bufferingEnabled() {\n return this.streamController.bufferingEnabled;\n }\n\n /**\n * Resumes stream controller segment loading after `pauseBuffering` has been called.\n */\n resumeBuffering() {\n if (!this.bufferingEnabled) {\n this.logger.log(`resume buffering`);\n this.networkControllers.forEach(controller => {\n if (controller.resumeBuffering) {\n controller.resumeBuffering();\n }\n });\n }\n }\n\n /**\n * Prevents stream controller from loading new segments until `resumeBuffering` is called.\n * This allows for media buffering to be paused without interupting playlist loading.\n */\n pauseBuffering() {\n if (this.bufferingEnabled) {\n this.logger.log(`pause buffering`);\n this.networkControllers.forEach(controller => {\n if (controller.pauseBuffering) {\n controller.pauseBuffering();\n }\n });\n }\n }\n get inFlightFragments() {\n const inFlightData = {\n [PlaylistLevelType.MAIN]: this.streamController.inFlightFrag\n };\n if (this.audioStreamController) {\n inFlightData[PlaylistLevelType.AUDIO] = this.audioStreamController.inFlightFrag;\n }\n if (this.subtititleStreamController) {\n inFlightData[PlaylistLevelType.SUBTITLE] = this.subtititleStreamController.inFlightFrag;\n }\n return inFlightData;\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec() {\n this.logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError() {\n this.logger.log('recoverMediaError');\n const media = this._media;\n const time = media == null ? void 0 : media.currentTime;\n this.detachMedia();\n if (media) {\n this.attachMedia(media);\n if (time) {\n this.startLoad(time);\n }\n }\n }\n removeLevel(levelIndex) {\n this.levelController.removeLevel(levelIndex);\n }\n\n /**\n * @returns a UUID for this player instance\n */\n get sessionId() {\n let _sessionId = this._sessionId;\n if (!_sessionId) {\n _sessionId = this._sessionId = uuid();\n }\n return _sessionId;\n }\n\n /**\n * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH\n */\n get levels() {\n const levels = this.levelController.levels;\n return levels ? levels : [];\n }\n\n /**\n * @returns LevelDetails of last loaded level (variant) or `null` prior to loading a media playlist.\n */\n get latestLevelDetails() {\n return this.streamController.getLevelDetails() || null;\n }\n\n /**\n * @returns Level object of selected level (variant) or `null` prior to selecting a level or once the level is removed.\n */\n get loadLevelObj() {\n return this.levelController.loadLevelObj;\n }\n\n /**\n * Index of quality level (variant) currently played\n */\n get currentLevel() {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately. This will flush the current buffer to replace the quality asap. That means playback will interrupt at least shortly to re-buffer and re-sync eventually. Set to -1 for automatic level selection.\n */\n set currentLevel(newLevel) {\n this.logger.log(`set currentLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n */\n get nextLevel() {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @param newLevel - Pass -1 for automatic level selection\n */\n set nextLevel(newLevel) {\n this.logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n */\n get loadLevel() {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @param newLevel - Pass -1 for automatic level selection\n */\n set loadLevel(newLevel) {\n this.logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n */\n get nextLoadLevel() {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n */\n set nextLoadLevel(level) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n */\n get firstLevel() {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n */\n set firstLevel(newLevel) {\n this.logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\n\n /**\n * Return the desired start level for the first fragment that will be loaded.\n * The default value of -1 indicates automatic start level selection.\n * Setting hls.nextAutoLevel without setting a startLevel will result in\n * the nextAutoLevel value being used for one fragment load.\n */\n get startLevel() {\n const startLevel = this.levelController.startLevel;\n if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {\n return this.abrController.forcedAutoLevel;\n }\n return startLevel;\n }\n\n /**\n * set start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n */\n set startLevel(newLevel) {\n this.logger.log(`set startLevel:${newLevel}`);\n // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel\n if (newLevel !== -1) {\n newLevel = Math.max(newLevel, this.minAutoLevel);\n }\n this.levelController.startLevel = newLevel;\n }\n\n /**\n * Whether level capping is enabled.\n * Default value is set via `config.capLevelToPlayerSize`.\n */\n get capLevelToPlayerSize() {\n return this.config.capLevelToPlayerSize;\n }\n\n /**\n * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.\n */\n set capLevelToPlayerSize(shouldStartCapping) {\n const newCapLevelToPlayerSize = !!shouldStartCapping;\n if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {\n if (newCapLevelToPlayerSize) {\n this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.\n } else {\n this.capLevelController.stopCapping();\n this.autoLevelCapping = -1;\n this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.\n }\n this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;\n }\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n */\n get autoLevelCapping() {\n return this._autoLevelCapping;\n }\n\n /**\n * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.\n */\n get bandwidthEstimate() {\n const {\n bwEstimator\n } = this.abrController;\n if (!bwEstimator) {\n return NaN;\n }\n return bwEstimator.getEstimate();\n }\n set bandwidthEstimate(abrEwmaDefaultEstimate) {\n this.abrController.resetEstimator(abrEwmaDefaultEstimate);\n }\n get abrEwmaDefaultEstimate() {\n const {\n bwEstimator\n } = this.abrController;\n if (!bwEstimator) {\n return NaN;\n }\n return bwEstimator.defaultEstimate;\n }\n\n /**\n * get time to first byte estimate\n * @type {number}\n */\n get ttfbEstimate() {\n const {\n bwEstimator\n } = this.abrController;\n if (!bwEstimator) {\n return NaN;\n }\n return bwEstimator.getEstimateTTFB();\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n */\n set autoLevelCapping(newLevel) {\n if (this._autoLevelCapping !== newLevel) {\n this.logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n this.levelController.checkMaxAutoUpdated();\n }\n }\n get maxHdcpLevel() {\n return this._maxHdcpLevel;\n }\n set maxHdcpLevel(value) {\n if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {\n this._maxHdcpLevel = value;\n this.levelController.checkMaxAutoUpdated();\n }\n }\n\n /**\n * True when automatic level selection enabled\n */\n get autoLevelEnabled() {\n return this.levelController.manualLevel === -1;\n }\n\n /**\n * Level set manually (if any)\n */\n get manualLevel() {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n */\n get minAutoLevel() {\n const {\n levels,\n config: {\n minAutoBitrate\n }\n } = this;\n if (!levels) return 0;\n const len = levels.length;\n for (let i = 0; i < len; i++) {\n if (levels[i].maxBitrate >= minAutoBitrate) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n * max level selectable in auto mode according to autoLevelCapping\n */\n get maxAutoLevel() {\n const {\n levels,\n autoLevelCapping,\n maxHdcpLevel\n } = this;\n let maxAutoLevel;\n if (autoLevelCapping === -1 && levels != null && levels.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n if (maxHdcpLevel) {\n for (let i = maxAutoLevel; i--;) {\n const hdcpLevel = levels[i].attrs['HDCP-LEVEL'];\n if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {\n return i;\n }\n }\n }\n return maxAutoLevel;\n }\n get firstAutoLevel() {\n return this.abrController.firstAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n */\n get nextAutoLevel() {\n return this.abrController.nextAutoLevel;\n }\n\n /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)\n * forced value is valid for one fragment. upon successful frag loading at forced level,\n * this value will be resetted to -1 by ABR controller.\n */\n set nextAutoLevel(nextLevel) {\n this.abrController.nextAutoLevel = nextLevel;\n }\n\n /**\n * get the datetime value relative to media.currentTime for the active level Program Date Time if present\n */\n get playingDate() {\n return this.streamController.currentProgramDateTime;\n }\n get mainForwardBufferInfo() {\n return this.streamController.getMainFwdBufferInfo();\n }\n get maxBufferLength() {\n return this.streamController.maxBufferLength;\n }\n\n /**\n * Find and select the best matching audio track, making a level switch when a Group change is necessary.\n * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.\n */\n setAudioOption(audioOption) {\n var _this$audioTrackContr;\n return ((_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption)) || null;\n }\n /**\n * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.\n * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.\n */\n setSubtitleOption(subtitleOption) {\n var _this$subtitleTrackCo;\n return ((_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption)) || null;\n }\n\n /**\n * Get the complete list of audio tracks across all media groups\n */\n get allAudioTracks() {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.allAudioTracks : [];\n }\n\n /**\n * Get the list of selectable audio tracks\n */\n get audioTracks() {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n */\n get audioTrack() {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n */\n set audioTrack(audioTrackId) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * get the complete list of subtitle tracks across all media groups\n */\n get allSubtitleTracks() {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n */\n get subtitleTracks() {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n */\n get subtitleTrack() {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n get media() {\n return this._media;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n */\n set subtitleTrack(subtitleTrackId) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * Whether subtitle display is enabled or not\n */\n get subtitleDisplay() {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n */\n set subtitleDisplay(value) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleDisplay = value;\n }\n }\n\n /**\n * get mode for Low-Latency HLS loading\n */\n get lowLatencyMode() {\n return this.config.lowLatencyMode;\n }\n\n /**\n * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.\n */\n set lowLatencyMode(mode) {\n this.config.lowLatencyMode = mode;\n }\n\n /**\n * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)\n * @returns null prior to loading live Playlist\n */\n get liveSyncPosition() {\n return this.latencyController.liveSyncPosition;\n }\n\n /**\n * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)\n * @returns 0 before first playlist is loaded\n */\n get latency() {\n return this.latencyController.latency;\n }\n\n /**\n * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```\n * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```\n * @returns 0 before first playlist is loaded\n */\n get maxLatency() {\n return this.latencyController.maxLatency;\n }\n\n /**\n * target distance from the edge as calculated by the latency controller\n */\n get targetLatency() {\n return this.latencyController.targetLatency;\n }\n set targetLatency(latency) {\n this.latencyController.targetLatency = latency;\n }\n\n /**\n * the rate at which the edge of the current live playlist is advancing or 1 if there is none\n */\n get drift() {\n return this.latencyController.drift;\n }\n\n /**\n * set to true when startLoad is called before MANIFEST_PARSED event\n */\n get forceStartLoad() {\n return this.streamController.forceStartLoad;\n }\n\n /**\n * ContentSteering pathways getter\n */\n get pathways() {\n return this.levelController.pathways;\n }\n\n /**\n * ContentSteering pathwayPriority getter/setter\n */\n get pathwayPriority() {\n return this.levelController.pathwayPriority;\n }\n set pathwayPriority(pathwayPriority) {\n this.levelController.pathwayPriority = pathwayPriority;\n }\n\n /**\n * returns true when all SourceBuffers are buffered to the end\n */\n get bufferedToEnd() {\n var _this$bufferControlle;\n return !!((_this$bufferControlle = this.bufferController) != null && _this$bufferControlle.bufferedToEnd);\n }\n\n /**\n * returns Interstitials Program Manager\n */\n get interstitialsManager() {\n var _this$interstitialsCo;\n return ((_this$interstitialsCo = this.interstitialsController) == null ? void 0 : _this$interstitialsCo.interstitialsManager) || null;\n }\n\n /**\n * returns mediaCapabilities.decodingInfo for a variant/rendition\n */\n getMediaDecodingInfo(level, audioTracks = this.allAudioTracks) {\n const audioTracksByGroup = getAudioTracksByGroup(audioTracks);\n return getMediaDecodingInfoPromise(level, audioTracksByGroup, navigator.mediaCapabilities);\n }\n}\nHls.defaultConfig = void 0;\n\nexport { AbrController, AttrList, AudioStreamController, AudioTrackController, BasePlaylistController, BaseSegment, BaseStreamController, BufferController, CMCDController, CapLevelController, ChunkMetadata, ContentSteeringController, Cues, DateRange, EMEController, ErrorActionFlags, ErrorController, ErrorDetails, ErrorTypes, Events, FPSController, FetchLoader, Fragment, Hls, HlsSkip, HlsUrlParameters, KeySystemFormats, KeySystems, Level, LevelDetails, LevelKey, LoadStats, M3U8Parser, MetadataSchema, NetworkErrorAction, Part, PlaylistLevelType, SubtitleStreamController, SubtitleTrackController, TimelineController, XhrLoader, Hls as default, fetchSupported, getMediaSource, isMSESupported, isSupported, requestMediaKeySystemAccess };\n//# sourceMappingURL=hls.mjs.map\n"],"names":[],"sourceRoot":""}