@maveio/components 0.0.172 → 0.0.174

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 (193) hide show
  1. package/dist/chunk-3FKZJPP6.cjs +2 -0
  2. package/dist/chunk-HDVI5ING.js +2583 -0
  3. package/dist/chunk-KCEF7VQS.cjs +2583 -0
  4. package/dist/chunk-SWNRHAZK.js +2 -0
  5. package/dist/config.cjs +1 -1
  6. package/dist/config.d.cts +9 -3
  7. package/dist/config.d.ts +9 -3
  8. package/dist/config.js +1 -1
  9. package/dist/de-4HGSV4NX.cjs +1 -0
  10. package/dist/de-AM53RBF2.js +1 -0
  11. package/dist/{themes/default.cjs → default-LFHA4VXP.cjs} +3 -3
  12. package/dist/{themes/default.js → default-OIQBJJAX.js} +3 -3
  13. package/dist/{themes/dolphin.cjs → dolphin-B2Z26DWX.cjs} +2 -2
  14. package/dist/{themes/dolphin.js → dolphin-JJOJS5EI.js} +2 -2
  15. package/dist/en-H7UBETC6.js +1 -0
  16. package/dist/en-M6OWHDJ2.cjs +1 -0
  17. package/dist/fr-2IL2CZKO.js +1 -0
  18. package/dist/fr-OXQSVAX4.cjs +1 -0
  19. package/dist/index.cjs +1 -1
  20. package/dist/index.d.cts +470 -16
  21. package/dist/index.d.ts +470 -16
  22. package/dist/index.js +1 -1
  23. package/dist/nl-CPFN66G7.js +1 -0
  24. package/dist/nl-YHUQM5IK.cjs +1 -0
  25. package/dist/react.cjs +1 -1
  26. package/dist/react.d.cts +2 -11
  27. package/dist/react.d.ts +2 -11
  28. package/dist/react.js +1 -1
  29. package/dist/{themes/synthwave.cjs → synthwave-JAIVYLQN.cjs} +2 -2
  30. package/dist/{themes/synthwave.js → synthwave-X45G4Z3J.js} +2 -2
  31. package/dist/vue.cjs +1 -1
  32. package/dist/vue.d.cts +1 -0
  33. package/dist/vue.d.ts +1 -0
  34. package/dist/vue.js +1 -1
  35. package/package.json +7 -2
  36. package/dist/chunk-2E5GLLOS.cjs +0 -19
  37. package/dist/chunk-2FUCHY2J.cjs +0 -35
  38. package/dist/chunk-2JCNQPEK.js +0 -1
  39. package/dist/chunk-3BAQWQNY.cjs +0 -25
  40. package/dist/chunk-3UQNIS3L.js +0 -194
  41. package/dist/chunk-474VILDO.cjs +0 -194
  42. package/dist/chunk-5NKBIUPL.cjs +0 -1
  43. package/dist/chunk-5PIHL662.js +0 -19
  44. package/dist/chunk-5ZZKAVXJ.js +0 -38
  45. package/dist/chunk-6DDQAAOQ.cjs +0 -211
  46. package/dist/chunk-AOBEOJ2U.cjs +0 -10
  47. package/dist/chunk-B5K5JDPC.cjs +0 -7
  48. package/dist/chunk-B6P2GJBQ.js +0 -9
  49. package/dist/chunk-BL5IEXIA.cjs +0 -1
  50. package/dist/chunk-BTCK3T4L.cjs +0 -24
  51. package/dist/chunk-CNPQ5Q2M.js +0 -1
  52. package/dist/chunk-CVXHA76S.js +0 -3
  53. package/dist/chunk-CWZPXTU2.cjs +0 -154
  54. package/dist/chunk-DL4BV5IH.cjs +0 -24
  55. package/dist/chunk-DXS4BF7U.js +0 -33
  56. package/dist/chunk-EVKPEPYP.cjs +0 -2
  57. package/dist/chunk-FAONFKQ2.cjs +0 -9
  58. package/dist/chunk-GXOLIMQT.js +0 -1
  59. package/dist/chunk-HMVS6DJE.js +0 -186
  60. package/dist/chunk-IBQULJZC.cjs +0 -3
  61. package/dist/chunk-J7OISSKU.cjs +0 -1
  62. package/dist/chunk-JN3JQJEF.js +0 -1639
  63. package/dist/chunk-K5Z7QHTN.cjs +0 -1
  64. package/dist/chunk-KHVG2CY5.js +0 -7
  65. package/dist/chunk-KNLOZXCA.cjs +0 -33
  66. package/dist/chunk-KO3CETGD.js +0 -25
  67. package/dist/chunk-KZGLJUFY.cjs +0 -38
  68. package/dist/chunk-LVGLIRQU.cjs +0 -186
  69. package/dist/chunk-MK4VIJT3.js +0 -1
  70. package/dist/chunk-MMHEOMF5.js +0 -9
  71. package/dist/chunk-NDPOBFNC.js +0 -20
  72. package/dist/chunk-NPP5B5PV.cjs +0 -16
  73. package/dist/chunk-OX42Y2HR.js +0 -1
  74. package/dist/chunk-P6SBZPDR.js +0 -1
  75. package/dist/chunk-PTN427IG.js +0 -24
  76. package/dist/chunk-QFF6OUH6.js +0 -9
  77. package/dist/chunk-QOM4AP6R.cjs +0 -9
  78. package/dist/chunk-QQDH35OW.cjs +0 -9
  79. package/dist/chunk-R3SDTEHC.js +0 -9
  80. package/dist/chunk-RHTBV6KZ.js +0 -24
  81. package/dist/chunk-RKL7JR7S.js +0 -211
  82. package/dist/chunk-RQN3DXJB.cjs +0 -1
  83. package/dist/chunk-RRCW5BBR.cjs +0 -9
  84. package/dist/chunk-S3D62CAG.js +0 -154
  85. package/dist/chunk-SDKTBB4N.cjs +0 -1
  86. package/dist/chunk-SWRFZ3FV.js +0 -1
  87. package/dist/chunk-TAKTIPT7.cjs +0 -1639
  88. package/dist/chunk-TH3DUBVR.js +0 -35
  89. package/dist/chunk-TJ5F2FGY.cjs +0 -20
  90. package/dist/chunk-TKJYRGEU.cjs +0 -1
  91. package/dist/chunk-WE5NUDRY.js +0 -0
  92. package/dist/chunk-WOXKZOJ3.js +0 -10
  93. package/dist/chunk-X7OGQ4KH.cjs +0 -1
  94. package/dist/chunk-YPCQNE3R.js +0 -16
  95. package/dist/chunk-ZTDQPDC6.js +0 -2
  96. package/dist/components/audio-track-menu.cjs +0 -1
  97. package/dist/components/audio-track-menu.d.cts +0 -27
  98. package/dist/components/audio-track-menu.d.ts +0 -27
  99. package/dist/components/audio-track-menu.js +0 -1
  100. package/dist/components/captions-menu-button.cjs +0 -1
  101. package/dist/components/captions-menu-button.d.cts +0 -10
  102. package/dist/components/captions-menu-button.d.ts +0 -10
  103. package/dist/components/captions-menu-button.js +0 -1
  104. package/dist/components/clip.cjs +0 -1
  105. package/dist/components/clip.d.cts +0 -55
  106. package/dist/components/clip.d.ts +0 -55
  107. package/dist/components/clip.js +0 -1
  108. package/dist/components/files.cjs +0 -1
  109. package/dist/components/files.d.cts +0 -22
  110. package/dist/components/files.d.ts +0 -22
  111. package/dist/components/files.js +0 -1
  112. package/dist/components/img.cjs +0 -1
  113. package/dist/components/img.d.cts +0 -16
  114. package/dist/components/img.d.ts +0 -16
  115. package/dist/components/img.js +0 -1
  116. package/dist/components/list.cjs +0 -1
  117. package/dist/components/list.d.cts +0 -29
  118. package/dist/components/list.d.ts +0 -29
  119. package/dist/components/list.js +0 -1
  120. package/dist/components/player.cjs +0 -1
  121. package/dist/components/player.d.cts +0 -104
  122. package/dist/components/player.d.ts +0 -104
  123. package/dist/components/player.js +0 -1
  124. package/dist/components/pop.cjs +0 -1
  125. package/dist/components/pop.d.cts +0 -37
  126. package/dist/components/pop.d.ts +0 -37
  127. package/dist/components/pop.js +0 -1
  128. package/dist/components/text.cjs +0 -1
  129. package/dist/components/text.d.cts +0 -55
  130. package/dist/components/text.d.ts +0 -55
  131. package/dist/components/text.js +0 -1
  132. package/dist/components/upload.cjs +0 -1
  133. package/dist/components/upload.d.cts +0 -94
  134. package/dist/components/upload.d.ts +0 -94
  135. package/dist/components/upload.js +0 -1
  136. package/dist/embed/api.cjs +0 -1
  137. package/dist/embed/api.d.cts +0 -112
  138. package/dist/embed/api.d.ts +0 -112
  139. package/dist/embed/api.js +0 -1
  140. package/dist/embed/caption.cjs +0 -1
  141. package/dist/embed/caption.d.cts +0 -24
  142. package/dist/embed/caption.d.ts +0 -24
  143. package/dist/embed/caption.js +0 -1
  144. package/dist/embed/controller.cjs +0 -1
  145. package/dist/embed/controller.d.cts +0 -34
  146. package/dist/embed/controller.d.ts +0 -34
  147. package/dist/embed/controller.js +0 -1
  148. package/dist/embed/socket.cjs +0 -1
  149. package/dist/embed/socket.d.cts +0 -14
  150. package/dist/embed/socket.d.ts +0 -14
  151. package/dist/embed/socket.js +0 -1
  152. package/dist/generated/locales/de.cjs +0 -1
  153. package/dist/generated/locales/de.d.cts +0 -17
  154. package/dist/generated/locales/de.d.ts +0 -17
  155. package/dist/generated/locales/de.js +0 -1
  156. package/dist/generated/locales/en.cjs +0 -1
  157. package/dist/generated/locales/en.d.cts +0 -17
  158. package/dist/generated/locales/en.d.ts +0 -17
  159. package/dist/generated/locales/en.js +0 -1
  160. package/dist/generated/locales/fr.cjs +0 -1
  161. package/dist/generated/locales/fr.d.cts +0 -17
  162. package/dist/generated/locales/fr.d.ts +0 -17
  163. package/dist/generated/locales/fr.js +0 -1
  164. package/dist/generated/locales/nl.cjs +0 -1
  165. package/dist/generated/locales/nl.d.cts +0 -17
  166. package/dist/generated/locales/nl.d.ts +0 -17
  167. package/dist/generated/locales/nl.js +0 -1
  168. package/dist/themes/default.d.cts +0 -3
  169. package/dist/themes/default.d.ts +0 -3
  170. package/dist/themes/dolphin.d.cts +0 -3
  171. package/dist/themes/dolphin.d.ts +0 -3
  172. package/dist/themes/loader.cjs +0 -1
  173. package/dist/themes/loader.d.cts +0 -11
  174. package/dist/themes/loader.d.ts +0 -11
  175. package/dist/themes/loader.js +0 -1
  176. package/dist/themes/synthwave.d.cts +0 -3
  177. package/dist/themes/synthwave.d.ts +0 -3
  178. package/dist/utils/localization.cjs +0 -1
  179. package/dist/utils/localization.d.cts +0 -24
  180. package/dist/utils/localization.d.ts +0 -24
  181. package/dist/utils/localization.js +0 -1
  182. package/dist/utils/mave_element.cjs +0 -1
  183. package/dist/utils/mave_element.d.cts +0 -19
  184. package/dist/utils/mave_element.d.ts +0 -19
  185. package/dist/utils/mave_element.js +0 -1
  186. package/dist/utils/origin.cjs +0 -1
  187. package/dist/utils/origin.d.cts +0 -3
  188. package/dist/utils/origin.d.ts +0 -3
  189. package/dist/utils/origin.js +0 -1
  190. package/dist/utils/video_events.cjs +0 -1
  191. package/dist/utils/video_events.d.cts +0 -3
  192. package/dist/utils/video_events.d.ts +0 -3
  193. package/dist/utils/video_events.js +0 -1
@@ -0,0 +1,2583 @@
1
+ import {a as a$1}from'./chunk-SWNRHAZK.js';import {a,c,b as b$1,e,g,d,f}from'./chunk-KA24PL7V.js';var bA=a((A5,yA)=>{yA.exports=function(e,t){if(t=t.split(":")[0],e=+e,!e)return false;switch(t){case "http":case "ws":return e!==80;case "https":case "wss":return e!==443;case "ftp":return e!==21;case "gopher":return e!==70;case "file":return false}return e!==0};});var SA=a(G0=>{var M1=Object.prototype.hasOwnProperty,P1;function _A(s){try{return decodeURIComponent(s.replace(/\+/g," "))}catch{return null}}function TA(s){try{return encodeURIComponent(s)}catch{return null}}function O1(s){for(var e=/([^=?#&]+)=?([^&]*)/g,t={},i;i=e.exec(s);){var r=_A(i[1]),n=_A(i[2]);r===null||n===null||r in t||(t[r]=n);}return t}function U1(s,e){e=e||"";var t=[],i,r;typeof e!="string"&&(e="?");for(r in s)if(M1.call(s,r)){if(i=s[r],!i&&(i===null||i===P1||isNaN(i))&&(i=""),r=TA(r),i=TA(i),r===null||i===null)continue;t.push(r+"="+i);}return t.length?e+t.join("&"):""}G0.stringify=U1;G0.parse=O1;});var CA=a((x5,wA)=>{var IA=bA(),Nh=SA(),N1=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,xA=/[\n\r\t]/g,F1=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,LA=/:\d+$/,$1=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,B1=/^[a-zA-Z]:/;function V0(s){return (s||"").toString().replace(N1,"")}var K0=[["#","hash"],["?","query"],function(e,t){return cs(t.protocol)?e.replace(/\\/g,"/"):e},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],AA={hash:1,query:1};function RA(s){var e;typeof window<"u"?e=window:typeof global<"u"?e=global:typeof self<"u"?e=self:e={};var t=e.location||{};s=s||t;var i={},r=typeof s,n;if(s.protocol==="blob:")i=new us(unescape(s.pathname),{});else if(r==="string"){i=new us(s,{});for(n in AA)delete i[n];}else if(r==="object"){for(n in s)n in AA||(i[n]=s[n]);i.slashes===void 0&&(i.slashes=F1.test(s.href));}return i}function cs(s){return s==="file:"||s==="ftp:"||s==="http:"||s==="https:"||s==="ws:"||s==="wss:"}function kA(s,e){s=V0(s),s=s.replace(xA,""),e=e||{};var t=$1.exec(s),i=t[1]?t[1].toLowerCase():"",r=!!t[2],n=!!t[3],o=0,a;return r?n?(a=t[2]+t[3]+t[4],o=t[2].length+t[3].length):(a=t[2]+t[4],o=t[2].length):n?(a=t[3]+t[4],o=t[3].length):a=t[4],i==="file:"?o>=2&&(a=a.slice(2)):cs(i)?a=t[4]:i?r&&(a=a.slice(2)):o>=2&&cs(e.protocol)&&(a=t[4]),{protocol:i,slashes:r||cs(i),slashesCount:o,rest:a}}function H1(s,e){if(s==="")return e;for(var t=(e||"/").split("/").slice(0,-1).concat(s.split("/")),i=t.length,r=t[i-1],n=false,o=0;i--;)t[i]==="."?t.splice(i,1):t[i]===".."?(t.splice(i,1),o++):o&&(i===0&&(n=true),t.splice(i,1),o--);return n&&t.unshift(""),(r==="."||r==="..")&&t.push(""),t.join("/")}function us(s,e,t){if(s=V0(s),s=s.replace(xA,""),!(this instanceof us))return new us(s,e,t);var i,r,n,o,a,l,d=K0.slice(),c=typeof e,u=this,h=0;for(c!=="object"&&c!=="string"&&(t=e,e=null),t&&typeof t!="function"&&(t=Nh.parse),e=RA(e),r=kA(s||"",e),i=!r.protocol&&!r.slashes,u.slashes=r.slashes||i&&e.slashes,u.protocol=r.protocol||e.protocol||"",s=r.rest,(r.protocol==="file:"&&(r.slashesCount!==2||B1.test(s))||!r.slashes&&(r.protocol||r.slashesCount<2||!cs(u.protocol)))&&(d[3]=[/(.*)/,"pathname"]);h<d.length;h++){if(o=d[h],typeof o=="function"){s=o(s,u);continue}n=o[0],l=o[1],n!==n?u[l]=s:typeof n=="string"?(a=n==="@"?s.lastIndexOf(n):s.indexOf(n),~a&&(typeof o[2]=="number"?(u[l]=s.slice(0,a),s=s.slice(a+o[2])):(u[l]=s.slice(a),s=s.slice(0,a)))):(a=n.exec(s))&&(u[l]=a[1],s=s.slice(0,a.index)),u[l]=u[l]||i&&o[3]&&e[l]||"",o[4]&&(u[l]=u[l].toLowerCase());}t&&(u.query=t(u.query)),i&&e.slashes&&u.pathname.charAt(0)!=="/"&&(u.pathname!==""||e.pathname!=="")&&(u.pathname=H1(u.pathname,e.pathname)),u.pathname.charAt(0)!=="/"&&cs(u.protocol)&&(u.pathname="/"+u.pathname),IA(u.port,u.protocol)||(u.host=u.hostname,u.port=""),u.username=u.password="",u.auth&&(a=u.auth.indexOf(":"),~a?(u.username=u.auth.slice(0,a),u.username=encodeURIComponent(decodeURIComponent(u.username)),u.password=u.auth.slice(a+1),u.password=encodeURIComponent(decodeURIComponent(u.password))):u.username=encodeURIComponent(decodeURIComponent(u.auth)),u.auth=u.password?u.username+":"+u.password:u.username),u.origin=u.protocol!=="file:"&&cs(u.protocol)&&u.host?u.protocol+"//"+u.host:"null",u.href=u.toString();}function G1(s,e,t){var i=this;switch(s){case "query":typeof e=="string"&&e.length&&(e=(t||Nh.parse)(e)),i[s]=e;break;case "port":i[s]=e,IA(e,i.protocol)?e&&(i.host=i.hostname+":"+e):(i.host=i.hostname,i[s]="");break;case "hostname":i[s]=e,i.port&&(e+=":"+i.port),i.host=e;break;case "host":i[s]=e,LA.test(e)?(e=e.split(":"),i.port=e.pop(),i.hostname=e.join(":")):(i.hostname=e,i.port="");break;case "protocol":i.protocol=e.toLowerCase(),i.slashes=!t;break;case "pathname":case "hash":if(e){var r=s==="pathname"?"/":"#";i[s]=e.charAt(0)!==r?r+e:e;}else i[s]=e;break;case "username":case "password":i[s]=encodeURIComponent(e);break;case "auth":var n=e.indexOf(":");~n?(i.username=e.slice(0,n),i.username=encodeURIComponent(decodeURIComponent(i.username)),i.password=e.slice(n+1),i.password=encodeURIComponent(decodeURIComponent(i.password))):i.username=encodeURIComponent(decodeURIComponent(e));}for(var o=0;o<K0.length;o++){var a=K0[o];a[4]&&(i[a[1]]=i[a[1]].toLowerCase());}return i.auth=i.password?i.username+":"+i.password:i.username,i.origin=i.protocol!=="file:"&&cs(i.protocol)&&i.host?i.protocol+"//"+i.host:"null",i.href=i.toString(),i}function K1(s){(!s||typeof s!="function")&&(s=Nh.stringify);var e,t=this,i=t.host,r=t.protocol;r&&r.charAt(r.length-1)!==":"&&(r+=":");var n=r+(t.protocol&&t.slashes||cs(t.protocol)?"//":"");return t.username?(n+=t.username,t.password&&(n+=":"+t.password),n+="@"):t.password?(n+=":"+t.password,n+="@"):t.protocol!=="file:"&&cs(t.protocol)&&!i&&t.pathname!=="/"&&(n+="@"),(i[i.length-1]===":"||LA.test(t.hostname)&&!t.port)&&(i+=":"),n+=i+t.pathname,e=typeof t.query=="object"?s(t.query):t.query,e&&(n+=e.charAt(0)!=="?"?"?"+e:e),t.hash&&(n+=t.hash),n}us.prototype={set:G1,toString:K1};us.extractProtocol=kA;us.location=RA;us.trimLeft=V0;us.qs=Nh;wA.exports=us;});var ln=class{constructor(e,{target:t,config:i,callback:r,skipInitial:n}){this.t=new Set,this.o=false,this.i=false,this.h=e,t!==null&&this.t.add(t??e),this.o=n??this.o,this.callback=r,window.IntersectionObserver?(this.u=new IntersectionObserver(o=>{let a=this.i;this.i=false,this.o&&a||(this.handleChanges(o),this.h.requestUpdate());},i),e.addController(this)):console.warn("IntersectionController error: browser does not support IntersectionObserver.");}handleChanges(e){this.value=this.callback?.(e,this.u);}hostConnected(){for(let e of this.t)this.observe(e);}hostDisconnected(){this.disconnect();}async hostUpdated(){let e=this.u.takeRecords();e.length&&this.handleChanges(e);}observe(e){this.t.add(e),this.u.observe(e),this.i=true;}unobserve(e){this.t.delete(e),this.u.unobserve(e);}disconnect(){this.u.disconnect();}};var ov=s=>{throw TypeError(s)},Xh=(s,e,t)=>e.has(s)||ov("Cannot "+t),N=(s,e,t)=>(Xh(s,e,"read from private field"),t?t.call(s):e.get(s)),Me=(s,e,t)=>e.has(s)?ov("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),ee=(s,e,t,i)=>(Xh(s,e,"write to private field"),e.set(s,t),t),he=(s,e,t)=>(Xh(s,e,"access private method"),t),Zl,av=class Yl{static setDebug(e){ee(Yl,Zl,e);}static debugEnabled(){if(N(Yl,Zl))return true;try{let e=globalThis;if(e.__MAVE_DATA_DEBUG__===!0||e.localStorage?.getItem("MAVE_DATA_DEBUG")==="1")return !0}catch{}return false}static log(e){console.log(`[mave_data]: ${e}`);}static error(e,t){typeof t>"u"?console.error(`[mave_data]: ${e}`):console.error(`[mave_data]: ${e}`,t);}static debug(e,t){Yl.debugEnabled()&&(typeof t>"u"?console.debug(`[mave_data]: ${e}`):console.debug(`[mave_data]: ${e}`,t));}};Zl=new WeakMap;Me(av,Zl,false);var rt=av,Jl,wt,ur,lr,Zh,td,id,hr,mt,lv,dv,Os,Jh,cv,uv,hv,fv,mv,pv,gI=class zt{constructor(){if(Me(this,mt),Me(this,Jl,{apiEndpoint:""}),Me(this,wt,[]),Me(this,ur,null),Me(this,lr,null),Me(this,Zh,5e3),Me(this,td,50),Me(this,id,48*1024),Me(this,hr,null),typeof window<"u"){let e=he(this,mt,pv).bind(this);ee(this,lr,e),document.addEventListener("visibilitychange",e),window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e);}}static get instance_(){return zt.instance||(zt.instance=new zt),zt.instance}static set config(e){ee(zt.instance_,Jl,e),typeof e.debug=="boolean"&&rt.setDebug(e.debug);}static push(e){var t;he(t=zt.instance_,mt,lv).call(t,e);}static flush(){var e;he(e=zt.instance_,mt,Os).call(e);}static flushAsync(){var e;return he(e=zt.instance_,mt,dv).call(e)}static flushOnExit(){var e;he(e=zt.instance_,mt,Os).call(e,{keepalive:true,preferBeacon:true});}static __resetForTests(){var e;zt.instance&&he(e=zt.instance,mt,cv).call(e),zt.instance=void 0;}};Jl=new WeakMap;wt=new WeakMap;ur=new WeakMap;lr=new WeakMap;Zh=new WeakMap;td=new WeakMap;id=new WeakMap;hr=new WeakMap;mt=new WeakSet;lv=function(s){let e={name:s.name||"unknown",timestamp:s.timestamp||Date.now(),session_id:s.session_id||"",...s};N(this,wt).push(e),rt.debug("Data.push",{name:e.name,session_id:e.session_id,embed_id:e.embed_id,video_time:e.video_time,buffer_size:N(this,wt).length}),!N(this,ur)&&typeof globalThis.setInterval=="function"&&ee(this,ur,globalThis.setInterval(()=>he(this,mt,Os).call(this),N(this,Zh))),N(this,wt).length>=N(this,td)&&he(this,mt,Os).call(this);};dv=function(s){return he(this,mt,Os).call(this,s),N(this,hr)??Promise.resolve(true)};Os=function(s){if(N(this,wt).length===0||N(this,hr))return;let e=[...N(this,wt)];ee(this,wt,[]);let t=N(this,Jl).apiEndpoint||"https://metrics.video-dns.com/v1/events",i=s?.keepalive??(typeof document<"u"&&document.visibilityState==="hidden"),r=s?.preferBeacon??false,n=he(this,mt,uv).call(this,e);rt.debug("Data.flush.start",{url:t,buffered:e.length,batches:n.map(a=>a.length),keepalive:i,preferBeacon:r});let o=false;ee(this,hr,(async()=>{for(let a of n){let l={events:a};if(rt.debug("Data.flush.batch",{size:a.length,first:a[0]?.name,last:a[a.length-1]?.name}),!await he(this,mt,fv).call(this,t,l,i,r))return ee(this,wt,[...a,...N(this,wt)]),false}return true})().catch(a=>(rt.error("Failed to send metrics",a),ee(this,wt,[...e,...N(this,wt)]),false)).then(a=>(rt.debug("Data.flush.done",{ok:a,remaining_buffer:N(this,wt).length}),a&&N(this,wt).length>0&&(o=true),a)).finally(()=>{ee(this,hr,null),N(this,wt).length===0&&he(this,mt,Jh).call(this),o&&he(this,mt,Os).call(this);}));};Jh=function(){N(this,ur)!=null&&(typeof globalThis.clearInterval=="function"&&globalThis.clearInterval(N(this,ur)),ee(this,ur,null));};cv=function(){typeof window<"u"&&N(this,lr)&&(document.removeEventListener("visibilitychange",N(this,lr)),window.removeEventListener("pagehide",N(this,lr)),window.removeEventListener("beforeunload",N(this,lr))),he(this,mt,Jh).call(this),ee(this,wt,[]),ee(this,hr,null);};uv=function(s){let e=[],t=[],i=0;for(let r of s){let n=he(this,mt,hv).call(this,r),o=i+n>N(this,id),a=t.length>=N(this,td);t.length>0&&(o||a)&&(e.push(t),t=[],i=0),t.push(r),i+=n;}return t.length>0&&e.push(t),e};hv=function(s){try{return JSON.stringify(s).length}catch{return 1024}};fv=async function(s,e,t,i){if(i&&t&&he(this,mt,mv).call(this,s,e))return rt.debug("Data.send.beacon",{url:s,bytes:JSON.stringify(e).length}),true;try{let r=await fetch(s,{method:"POST",keepalive:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return rt.debug("Data.send.fetch",{url:s,ok:r.ok,status:r.status}),r.ok}catch(r){return rt.error("Failed to send metrics",r),rt.debug("Data.send.fetch.error",r),false}};mv=function(s,e){try{if(typeof navigator>"u"||typeof navigator.sendBeacon!="function")return !1;let t=JSON.stringify(e);if(t.length>N(this,id))return !1;let i=new Blob([t],{type:"application/json"});return navigator.sendBeacon(s,i)}catch{return false}};pv=function(s){let e=s?.type==="pagehide"||s?.type==="beforeunload",t=document.visibilityState==="hidden";(e||t)&&(rt.debug(`Data.handleVisibilityChange (${s?.type||"visibility"})`,{state:document.visibilityState}),he(this,mt,Os).call(this,{keepalive:true,preferBeacon:true}));};var tt=gI;function vI(){let s=globalThis.crypto;if(s?.randomUUID)return s.randomUUID();if(s?.getRandomValues)return "10000000-1000-4000-8000-100000000000".replace(/[018]/g,i=>{let r=s.getRandomValues(new Uint8Array(1))[0]??0;return (Number(i)^(r&15)>>Number(i)/4).toString(16)});let e=Math.random().toString(16).slice(2).padEnd(12,"0"),t=Date.now().toString(16).padStart(12,"0");return `${t.slice(0,8)}-${t.slice(8,12)}-4000-8000-${e.slice(0,12)}`}var ef=(s=>(s.PLAYING="playing",s.ENDED="ended",s.PAUSE="pause",s))(ef||{}),ce,He,ai,ki,fr,ms,No,dr,wi,cr,Ut,Ci,tf,sf,rf,Ps,sd,ke,zl,rd,nd,Ql,Xl,mr,gv,vv,Ev,ed,Qh,yv,bv,_v,Uo,Ms,Tv,Us=class{constructor(...s){if(Me(this,ke),this.VERSION="0.1.1",Me(this,ce),Me(this,He,null),Me(this,ai,false),Me(this,ki,false),Me(this,fr,null),Me(this,ms,false),Me(this,No,0),Me(this,dr,0),Me(this,wi,null),Me(this,cr,null),Me(this,Ut,null),Me(this,Ci,null),Me(this,tf,750),Me(this,sf,1),Me(this,rf,300),Me(this,Ps,false),Me(this,sd,e=>he(this,ke,Tv).call(this,e)),Me(this,rd,()=>{if(!N(this,ai)||!N(this,ce))return;he(this,ke,zl).call(this),rt.debug("Metrics.native.seeking",{currentTime:N(this,ce).currentTime,lastObservedVideoTime:N(this,dr),paused:N(this,ce).paused,seeking:N(this,ce).seeking,lastEventType:N(this,He)});let e=N(this,He)==="play"||!N(this,ce).paused&&!N(this,ce).ended;if(e&&N(this,He)!=="pause"){ee(this,ki,true),ee(this,ms,false),he(this,ke,ed).call(this),he(this,ke,Ms).call(this);let t=N(this,dr)||N(this,ce).currentTime||0,i=he(this,ke,mr).call(this,"pause");tt.push({...i,name:"pause",video_time:t}),ee(this,He,"pause"),tt.flush(),rt.debug("Metrics.scrub.pause_sent",{pauseTime:t,currentTime:N(this,ce).currentTime});}else rt.debug("Metrics.scrub.pause_not_sent",{wasPlaying:e,lastEventType:N(this,He)});}),Me(this,nd,()=>{N(this,ai)&&N(this,ce)&&(rt.debug("Metrics.native.seeked",{currentTime:N(this,ce).currentTime,paused:N(this,ce).paused,seeking:N(this,ce).seeking,wasPlayingBeforeSeek:N(this,ki),lastEventType:N(this,He)}),N(this,ki)&&(he(this,ke,zl).call(this),ee(this,fr,window.setTimeout(()=>{if(ee(this,fr,null),!!N(this,ai)&&N(this,ce)){if(N(this,He)==="play"){ee(this,ki,false),ee(this,ms,false);return}if(!N(this,ce).seeking&&!N(this,ce).paused&&!N(this,ce).ended){let e=he(this,ke,mr).call(this,"play");tt.push({...e,name:"play"}),ee(this,He,"play"),ee(this,cr,Date.now()),ee(this,Ps,true),ee(this,No,Date.now()+1500),he(this,ke,Uo).call(this),ee(this,ms,false),tt.flush(),ee(this,ki,false);}else ee(this,ms,true),ee(this,ki,false);}},200))));}),Me(this,Ql,()=>{N(this,ai)&&document.visibilityState==="hidden"&&tt.flush();}),Me(this,Xl,e=>{if(N(this,ai)){if(e.persisted){tt.flush();return}he(this,ke,Qh).call(this),he(this,ke,Ev).call(this),tt.flushOnExit();}}),this.sessionId=vI(),s.length<2)rt.error("Metrics requires two arguments: a querySelectorable, hls instance or HTMLMediaElement/HTMLVideoElement and a unique embedId for your video.");else if(typeof s[0]=="string"&&(this.querySelectorable=s[0],this.embedId=s[1]),s[0]instanceof HTMLVideoElement||s[0]instanceof HTMLMediaElement?ee(this,ce,s[0]):typeof s[0]=="object"&&(this.hls=s[0]),this.embedId=s[1],s[2]){let e=s[2];this.component=e.component;}}static set config(s){tt.config=s,typeof s.debug=="boolean"&&rt.setDebug(s.debug);}monitor(){let s=this.querySelectorable?document.querySelector(this.querySelectorable):this.hls?.media;return N(this,ai)?this:(s||N(this,ce)?(N(this,ce)||ee(this,ce,s),rt.debug("Metrics.monitor",{embed_id:this.embedId,session_id:this.sessionId,currentTime:N(this,ce).currentTime,paused:N(this,ce).paused,seeking:N(this,ce).seeking,readyState:N(this,ce).readyState}),he(this,ke,bv).call(this),ee(this,dr,N(this,ce).currentTime||0),window.addEventListener("visibilitychange",N(this,Ql)),window.addEventListener("pagehide",N(this,Xl)),ee(this,ai,true)):rt.error(`${this.querySelectorable} is not a valid reference to a HTMLVideoElement.`),this)}demonitor(){N(this,ai)&&(he(this,ke,Qh).call(this),he(this,ke,gv).call(this),he(this,ke,zl).call(this),he(this,ke,Ms).call(this),he(this,ke,_v).call(this),window.removeEventListener("visibilitychange",N(this,Ql)),window.removeEventListener("pagehide",N(this,Xl)),ee(this,ai,false));}};ce=new WeakMap;He=new WeakMap;ai=new WeakMap;ki=new WeakMap;fr=new WeakMap;ms=new WeakMap;No=new WeakMap;dr=new WeakMap;wi=new WeakMap;cr=new WeakMap;Ut=new WeakMap;Ci=new WeakMap;tf=new WeakMap;sf=new WeakMap;rf=new WeakMap;Ps=new WeakMap;sd=new WeakMap;ke=new WeakSet;zl=function(){N(this,fr)!=null&&(window.clearTimeout(N(this,fr)),ee(this,fr,null));};rd=new WeakMap;nd=new WeakMap;Ql=new WeakMap;Xl=new WeakMap;mr=function(s){return {name:s,duration:N(this,ce)?.duration,video_time:N(this,ce)?.currentTime,session_id:this.sessionId,embed_id:this.embedId||"unknown",component:this.component,source_url:window.location.href,timestamp:Date.now()}};gv=function(){N(this,ce)&&(N(this,ce).paused||N(this,He)!=="pause"&&(N(this,Ut)||(he(this,ke,vv).call(this),tt.flush())));};vv=function(){N(this,ce)&&N(this,He)!=="pause"&&(N(this,Ut)||(tt.push(he(this,ke,mr).call(this,"pause")),ee(this,He,"pause")));};Ev=function(){N(this,ce)&&N(this,He)==="play"&&(N(this,Ut)||(tt.push(he(this,ke,mr).call(this,"pause")),ee(this,He,"pause")));};ed=function(){N(this,Ut)&&(window.clearTimeout(N(this,Ut)),ee(this,Ut,null)),ee(this,Ci,null);};Qh=function(){if(!N(this,Ut)||!N(this,Ci))return;window.clearTimeout(N(this,Ut));let s=N(this,Ci);ee(this,Ut,null),ee(this,Ci,null),tt.push(s),ee(this,He,"pause"),ee(this,Ps,false),tt.flush();};yv=function(s){N(this,Ut)||(ee(this,Ci,s),ee(this,Ut,window.setTimeout(()=>{if(!N(this,Ci)){ee(this,Ut,null);return}let e=N(this,Ci);ee(this,Ci,null),ee(this,Ut,null),tt.push(e),ee(this,He,"pause"),tt.flush();},N(this,rf))));};bv=function(){rt.debug("Metrics.listeners.attach",{embed_id:this.embedId,session_id:this.sessionId});for(let s of Object.values(ef))N(this,ce).addEventListener(s,N(this,sd));N(this,ce).addEventListener("seeking",N(this,rd)),N(this,ce).addEventListener("seeked",N(this,nd));};_v=function(){for(let s of Object.values(ef))N(this,ce).removeEventListener(s,N(this,sd));N(this,ce).removeEventListener("seeking",N(this,rd)),N(this,ce).removeEventListener("seeked",N(this,nd));};Uo=function(){if(!N(this,ce)||N(this,wi)!=null)return;let s=()=>{if(!N(this,ce)){ee(this,wi,null);return}ee(this,dr,N(this,ce).currentTime||N(this,dr)),N(this,ai)&&!N(this,ce).paused&&!N(this,ce).ended?ee(this,wi,window.requestAnimationFrame(s)):ee(this,wi,null);};ee(this,wi,window.requestAnimationFrame(s));};Ms=function(){N(this,wi)!=null&&(window.cancelAnimationFrame(N(this,wi)),ee(this,wi,null));};Tv=function(s){let e=he(this,ke,mr).call(this,s.type);switch(rt.debug("Metrics.native.event",{type:s.type,currentTime:N(this,ce)?.currentTime,paused:N(this,ce)?.paused,seeking:N(this,ce)?.seeking,readyState:N(this,ce)?.readyState,lastEventType:N(this,He),wasPlayingBeforeSeek:N(this,ki),awaitingSeekResumePlay:N(this,ms)}),s.type){case "playing":if(he(this,ke,ed).call(this),N(this,ms)){if(N(this,He)!=="play"){let r=he(this,ke,mr).call(this,"play");tt.push({...r,name:"play"}),ee(this,He,"play"),ee(this,cr,Date.now()),ee(this,Ps,true),ee(this,No,Date.now()+1500),he(this,ke,Uo).call(this),tt.flush();}ee(this,ms,false);break}if(N(this,ce)?.seeking||N(this,ki))break;if(Date.now()<N(this,No)){ee(this,He,"play"),he(this,ke,Uo).call(this);break}if(N(this,He)==="play")break;tt.push({...e,name:"play"}),ee(this,He,"play"),ee(this,cr,Date.now()),ee(this,Ps,false),he(this,ke,Uo).call(this);break;case "pause":if(N(this,ce)?.seeking){he(this,ke,Ms).call(this);break}if(N(this,He)==="pause"){he(this,ke,Ms).call(this);break}let t=N(this,cr)==null?Number.POSITIVE_INFINITY:Date.now()-N(this,cr),i=N(this,ce)?.currentTime??0;if(t<=N(this,tf)&&(i<=N(this,sf)||N(this,Ps))){he(this,ke,yv).call(this,{...e,name:"pause"}),he(this,ke,Ms).call(this);break}tt.push({...e,name:"pause"}),ee(this,He,"pause"),ee(this,Ps,false),he(this,ke,Ms).call(this),tt.flush();break;case "ended":he(this,ke,ed).call(this),he(this,ke,Ms).call(this),N(this,He)!=="pause"&&(tt.push({...e,name:"pause"}),ee(this,He,"pause"),tt.flush());break;}};var od=globalThis,ad=od.ShadowRoot&&(od.ShadyCSS===void 0||od.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,nf=Symbol(),Sv=new WeakMap,Fo=class{constructor(e,t,i){if(this._$cssResult$=true,i!==nf)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t;}get styleSheet(){let e=this.o,t=this.t;if(ad&&e===void 0){let i=t!==void 0&&t.length===1;i&&(e=Sv.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&Sv.set(t,e));}return e}toString(){return this.cssText}},Av=s=>new Fo(typeof s=="string"?s:s+"",void 0,nf),it=(s,...e)=>{let t=s.length===1?s[0]:e.reduce((i,r,n)=>i+(o=>{if(o._$cssResult$===true)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+s[n+1],s[0]);return new Fo(t,s,nf)},Iv=(s,e)=>{if(ad)s.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let i=document.createElement("style"),r=od.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=t.cssText,s.appendChild(i);}},of=ad?s=>s:s=>s instanceof CSSStyleSheet?(e=>{let t="";for(let i of e.cssRules)t+=i.cssText;return Av(t)})(s):s;var{is:EI,defineProperty:yI,getOwnPropertyDescriptor:bI,getOwnPropertyNames:_I,getOwnPropertySymbols:TI,getPrototypeOf:SI}=Object,Ns=globalThis,xv=Ns.trustedTypes,AI=xv?xv.emptyScript:"",II=Ns.reactiveElementPolyfillSupport,$o=(s,e)=>s,Bo={toAttribute(s,e){switch(e){case Boolean:s=s?AI:null;break;case Object:case Array:s=s==null?s:JSON.stringify(s);}return s},fromAttribute(s,e){let t=s;switch(e){case Boolean:t=s!==null;break;case Number:t=s===null?null:Number(s);break;case Object:case Array:try{t=JSON.parse(s);}catch{t=null;}}return t}},dn=(s,e)=>!EI(s,e),Lv={attribute:true,type:String,converter:Bo,reflect:false,useDefault:false,hasChanged:dn};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ns.litPropertyMetadata??(Ns.litPropertyMetadata=new WeakMap);var ps=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e);}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Lv){if(t.state&&(t.attribute=false),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=true),this.elementProperties.set(e,t),!t.noAccessor){let i=Symbol(),r=this.getPropertyDescriptor(e,i,t);r!==void 0&&yI(this.prototype,e,r);}}static getPropertyDescriptor(e,t,i){let{get:r,set:n}=bI(this.prototype,e)??{get(){return this[t]},set(o){this[t]=o;}};return {get:r,set(o){let a=r?.call(this);n?.call(this,o),this.requestUpdate(e,a,i);},configurable:true,enumerable:true}}static getPropertyOptions(e){return this.elementProperties.get(e)??Lv}static _$Ei(){if(this.hasOwnProperty($o("elementProperties")))return;let e=SI(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties);}static finalize(){if(this.hasOwnProperty($o("finalized")))return;if(this.finalized=true,this._$Ei(),this.hasOwnProperty($o("properties"))){let t=this.properties,i=[..._I(t),...TI(t)];for(let r of i)this.createProperty(r,t[r]);}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[i,r]of t)this.elementProperties.set(i,r);}this._$Eh=new Map;for(let[t,i]of this.elementProperties){let r=this._$Eu(t,i);r!==void 0&&this._$Eh.set(r,t);}this.elementStyles=this.finalizeStyles(this.styles);}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let i=new Set(e.flat(1/0).reverse());for(let r of i)t.unshift(of(r));}else e!==void 0&&t.push(of(e));return t}static _$Eu(e,t){let i=t.attribute;return i===false?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=false,this.hasUpdated=false,this._$Em=null,this._$Ev();}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this));}addController(e){(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.();}removeController(e){this._$EO?.delete(e);}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e);}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Iv(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(true),this._$EO?.forEach(e=>e.hostConnected?.());}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.());}attributeChangedCallback(e,t,i){this._$AK(e,i);}_$ET(e,t){let i=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,i);if(r!==void 0&&i.reflect===true){let n=(i.converter?.toAttribute!==void 0?i.converter:Bo).toAttribute(t,i.type);this._$Em=e,n==null?this.removeAttribute(r):this.setAttribute(r,n),this._$Em=null;}}_$AK(e,t){let i=this.constructor,r=i._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let n=i.getPropertyOptions(r),o=typeof n.converter=="function"?{fromAttribute:n.converter}:n.converter?.fromAttribute!==void 0?n.converter:Bo;this._$Em=r;let a=o.fromAttribute(t,n.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null;}}requestUpdate(e,t,i,r=false,n){if(e!==void 0){let o=this.constructor;if(r===false&&(n=this[e]),i??(i=o.getPropertyOptions(e)),!((i.hasChanged??dn)(n,t)||i.useDefault&&i.reflect&&n===this._$Ej?.get(e)&&!this.hasAttribute(o._$Eu(e,i))))return;this.C(e,t,i);}this.isUpdatePending===false&&(this._$ES=this._$EP());}C(e,t,{useDefault:i,reflect:r,wrapped:n},o){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,o??t??this[e]),n!==true||o!==void 0)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),r===true&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e));}async _$EP(){this.isUpdatePending=true;try{await this._$ES;}catch(t){Promise.reject(t);}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[r,n]of this._$Ep)this[r]=n;this._$Ep=void 0;}let i=this.constructor.elementProperties;if(i.size>0)for(let[r,n]of i){let{wrapped:o}=n,a=this[r];o!==true||this._$AL.has(r)||a===void 0||this.C(r,void 0,n,a);}}let e=false,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(i=>i.hostUpdate?.()),this.update(t)):this._$EM();}catch(i){throw e=false,this._$EM(),i}e&&this._$AE(t);}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=true,this.firstUpdated(e)),this.updated(e);}_$EM(){this._$AL=new Map,this.isUpdatePending=false;}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return true}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach(t=>this._$ET(t,this[t]))),this._$EM();}updated(e){}firstUpdated(e){}};ps.elementStyles=[],ps.shadowRootOptions={mode:"open"},ps[$o("elementProperties")]=new Map,ps[$o("finalized")]=new Map,II?.({ReactiveElement:ps}),(Ns.reactiveElementVersions??(Ns.reactiveElementVersions=[])).push("2.1.2");var Go=globalThis,Rv=s=>s,ld=Go.trustedTypes,kv=ld?ld.createPolicy("lit-html",{createHTML:s=>s}):void 0,lf="$lit$",gs=`lit$${Math.random().toFixed(9).slice(2)}$`,df="?"+gs,xI=`<${df}>`,vr=document,Ko=()=>vr.createComment(""),Vo=s=>s===null||typeof s!="object"&&typeof s!="function",cf=Array.isArray,Ov=s=>cf(s)||typeof s?.[Symbol.iterator]=="function",af=`[
2
+ \f\r]`,Ho=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,wv=/-->/g,Cv=/>/g,pr=RegExp(`>|${af}(?:([^\\s"'>=/]+)(${af}*=${af}*(?:[^
3
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Dv=/'/g,Mv=/"/g,Uv=/^(?:script|style|textarea|title)$/i,uf=s=>(e,...t)=>({_$litType$:s,strings:e,values:t}),ne=uf(1),vs=Symbol.for("lit-noChange"),Ce=Symbol.for("lit-nothing"),Pv=new WeakMap,gr=vr.createTreeWalker(vr,129);function $v(s,e){if(!cf(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return kv!==void 0?kv.createHTML(e):e}var Bv=(s,e)=>{let t=s.length-1,i=[],r,n=e===2?"<svg>":e===3?"<math>":"",o=Ho;for(let a=0;a<t;a++){let l=s[a],d,c,u=-1,h=0;for(;h<l.length&&(o.lastIndex=h,c=o.exec(l),c!==null);)h=o.lastIndex,o===Ho?c[1]==="!--"?o=wv:c[1]!==void 0?o=Cv:c[2]!==void 0?(Uv.test(c[2])&&(r=RegExp("</"+c[2],"g")),o=pr):c[3]!==void 0&&(o=pr):o===pr?c[0]===">"?(o=r??Ho,u=-1):c[1]===void 0?u=-2:(u=o.lastIndex-c[2].length,d=c[1],o=c[3]===void 0?pr:c[3]==='"'?Mv:Dv):o===Mv||o===Dv?o=pr:o===wv||o===Cv?o=Ho:(o=pr,r=void 0);let f=o===pr&&s[a+1].startsWith("/>")?" ":"";n+=o===Ho?l+xI:u>=0?(i.push(d),l.slice(0,u)+lf+l.slice(u)+gs+f):l+gs+(u===-2?a:f);}return [$v(s,n+(s[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]},Wo=class s{constructor({strings:e,_$litType$:t},i){let r;this.parts=[];let n=0,o=0,a=e.length-1,l=this.parts,[d,c]=Bv(e,t);if(this.el=s.createElement(d,i),gr.currentNode=this.el.content,t===2||t===3){let u=this.el.content.firstChild;u.replaceWith(...u.childNodes);}for(;(r=gr.nextNode())!==null&&l.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(let u of r.getAttributeNames())if(u.endsWith(lf)){let h=c[o++],f=r.getAttribute(u).split(gs),m=/([.?@])?(.*)/.exec(h);l.push({type:1,index:n,name:m[2],strings:f,ctor:m[1]==="."?cd:m[1]==="?"?ud:m[1]==="@"?hd:yr}),r.removeAttribute(u);}else u.startsWith(gs)&&(l.push({type:6,index:n}),r.removeAttribute(u));if(Uv.test(r.tagName)){let u=r.textContent.split(gs),h=u.length-1;if(h>0){r.textContent=ld?ld.emptyScript:"";for(let f=0;f<h;f++)r.append(u[f],Ko()),gr.nextNode(),l.push({type:2,index:++n});r.append(u[h],Ko());}}}else if(r.nodeType===8)if(r.data===df)l.push({type:2,index:n});else {let u=-1;for(;(u=r.data.indexOf(gs,u+1))!==-1;)l.push({type:7,index:n}),u+=gs.length-1;}n++;}}static createElement(e,t){let i=vr.createElement("template");return i.innerHTML=e,i}};function Er(s,e,t=s,i){if(e===vs)return e;let r=i!==void 0?t._$Co?.[i]:t._$Cl,n=Vo(e)?void 0:e._$litDirective$;return r?.constructor!==n&&(r?._$AO?.(false),n===void 0?r=void 0:(r=new n(s),r._$AT(s,t,i)),i!==void 0?(t._$Co??(t._$Co=[]))[i]=r:t._$Cl=r),r!==void 0&&(e=Er(s,r._$AS(s,e.values),r,i)),e}var dd=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t;}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:i}=this._$AD,r=(e?.creationScope??vr).importNode(t,true);gr.currentNode=r;let n=gr.nextNode(),o=0,a=0,l=i[0];for(;l!==void 0;){if(o===l.index){let d;l.type===2?d=new cn(n,n.nextSibling,this,e):l.type===1?d=new l.ctor(n,l.name,l.strings,this,e):l.type===6&&(d=new fd(n,this,e)),this._$AV.push(d),l=i[++a];}o!==l?.index&&(n=gr.nextNode(),o++);}return gr.currentNode=vr,r}p(e){let t=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++;}},cn=class s{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,i,r){this.type=2,this._$AH=Ce,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=r,this._$Cv=r?.isConnected??true;}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Er(this,e,t),Vo(e)?e===Ce||e==null||e===""?(this._$AH!==Ce&&this._$AR(),this._$AH=Ce):e!==this._$AH&&e!==vs&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Ov(e)?this.k(e):this._(e);}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e));}_(e){this._$AH!==Ce&&Vo(this._$AH)?this._$AA.nextSibling.data=e:this.T(vr.createTextNode(e)),this._$AH=e;}$(e){let{values:t,_$litType$:i}=e,r=typeof i=="number"?this._$AC(e):(i.el===void 0&&(i.el=Wo.createElement($v(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===r)this._$AH.p(t);else {let n=new dd(r,this),o=n.u(this.options);n.p(t),this.T(o),this._$AH=n;}}_$AC(e){let t=Pv.get(e.strings);return t===void 0&&Pv.set(e.strings,t=new Wo(e)),t}k(e){cf(this._$AH)||(this._$AH=[],this._$AR());let t=this._$AH,i,r=0;for(let n of e)r===t.length?t.push(i=new s(this.O(Ko()),this.O(Ko()),this,this.options)):i=t[r],i._$AI(n),r++;r<t.length&&(this._$AR(i&&i._$AB.nextSibling,r),t.length=r);}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(false,true,t);e!==this._$AB;){let i=Rv(e).nextSibling;Rv(e).remove(),e=i;}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e));}},yr=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,r,n){this.type=1,this._$AH=Ce,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=n,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Ce;}_$AI(e,t=this,i,r){let n=this.strings,o=false;if(n===void 0)e=Er(this,e,t,0),o=!Vo(e)||e!==this._$AH&&e!==vs,o&&(this._$AH=e);else {let a=e,l,d;for(e=n[0],l=0;l<n.length-1;l++)d=Er(this,a[i+l],t,l),d===vs&&(d=this._$AH[l]),o||(o=!Vo(d)||d!==this._$AH[l]),d===Ce?e=Ce:e!==Ce&&(e+=(d??"")+n[l+1]),this._$AH[l]=d;}o&&!r&&this.j(e);}j(e){e===Ce?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"");}},cd=class extends yr{constructor(){super(...arguments),this.type=3;}j(e){this.element[this.name]=e===Ce?void 0:e;}},ud=class extends yr{constructor(){super(...arguments),this.type=4;}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Ce);}},hd=class extends yr{constructor(e,t,i,r,n){super(e,t,i,r,n),this.type=5;}_$AI(e,t=this){if((e=Er(this,e,t,0)??Ce)===vs)return;let i=this._$AH,r=e===Ce&&i!==Ce||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,n=e!==Ce&&(i===Ce||r);r&&this.element.removeEventListener(this.name,this,i),n&&this.element.addEventListener(this.name,this,e),this._$AH=e;}handleEvent(e){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e);}},fd=class{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i;}get _$AU(){return this._$AM._$AU}_$AI(e){Er(this,e);}},LI=Go.litHtmlPolyfillSupport;LI?.(Wo,cn),(Go.litHtmlVersions??(Go.litHtmlVersions=[])).push("3.3.2");var Gv=(s,e,t)=>{let i=t?.renderBefore??e,r=i._$litPart$;if(r===void 0){let n=t?.renderBefore??null;i._$litPart$=r=new cn(e.insertBefore(Ko(),n),n,void 0,t??{});}return r._$AI(s),r};var qo=globalThis,nt=class extends ps{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0;}createRenderRoot(){var t;let e=super.createRenderRoot();return (t=this.renderOptions).renderBefore??(t.renderBefore=e.firstChild),e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Gv(t,this.renderRoot,this.renderOptions);}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(true);}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(false);}render(){return vs}};nt._$litElement$=true,nt.finalized=true,qo.litElementHydrateSupport?.({LitElement:nt});var RI=qo.litElementPolyfillSupport;RI?.({LitElement:nt});(qo.litElementVersions??(qo.litElementVersions=[])).push("4.2.2");var kI={attribute:true,type:String,converter:Bo,reflect:false,hasChanged:dn},wI=(s=kI,e,t)=>{let{kind:i,metadata:r}=t,n=globalThis.litPropertyMetadata.get(r);if(n===void 0&&globalThis.litPropertyMetadata.set(r,n=new Map),i==="setter"&&((s=Object.create(s)).wrapped=true),n.set(t.name,s),i==="accessor"){let{name:o}=t;return {set(a){let l=e.get.call(this);e.set.call(this,a),this.requestUpdate(o,l,s,true,a);},init(a){return a!==void 0&&this.C(o,void 0,s,a),a}}}if(i==="setter"){let{name:o}=t;return function(a){let l=this[o];e.call(this,a),this.requestUpdate(o,l,s,true,a);}}throw Error("Unsupported decorator location: "+i)};function oe(s){return (e,t)=>typeof t=="object"?wI(s,e,t):((i,r,n)=>{let o=r.hasOwnProperty(n);return r.constructor.createProperty(n,i),o?Object.getOwnPropertyDescriptor(r,n):void 0})(s,e,t)}function Ct(s){return oe({...s,state:true,attribute:false})}var br=(s,e,t)=>(t.configurable=true,t.enumerable=true,Reflect.decorate&&typeof e!="object"&&Object.defineProperty(s,e,t),t);function Di(s,e){return (t,i,r)=>{let n=o=>o.renderRoot?.querySelector(s)??null;return br(t,i,{get(){return n(this)}})}}var _r=s=>s??Ce;var Kv=s=>s.strings===void 0;var md={ATTRIBUTE:1,CHILD:2},jo=s=>(...e)=>({_$litDirective$:s,values:e}),un=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i;}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}};var Yo=(s,e)=>{let t=s._$AN;if(t===void 0)return false;for(let i of t)i._$AO?.(e,false),Yo(i,e);return true},pd=s=>{let e,t;do{if((e=s._$AM)===void 0)break;t=e._$AN,t.delete(s),s=e;}while(t?.size===0)},Vv=s=>{for(let e;e=s._$AM;s=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(s))break;t.add(s),MI(e);}};function CI(s){this._$AN!==void 0?(pd(this),this._$AM=s,Vv(this)):this._$AM=s;}function DI(s,e=false,t=0){let i=this._$AH,r=this._$AN;if(r!==void 0&&r.size!==0)if(e)if(Array.isArray(i))for(let n=t;n<i.length;n++)Yo(i[n],false),pd(i[n]);else i!=null&&(Yo(i,false),pd(i));else Yo(this,s);}var MI=s=>{s.type==md.CHILD&&(s._$AP??(s._$AP=DI),s._$AQ??(s._$AQ=CI));},gd=class extends un{constructor(){super(...arguments),this._$AN=void 0;}_$AT(e,t,i){super._$AT(e,t,i),Vv(this),this.isConnected=e._$AU;}_$AO(e,t=true){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(Yo(this,e),pd(this));}setValue(e){if(Kv(this._$Ct))this._$Ct._$AI(e,this);else {let t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0);}}disconnected(){}reconnected(){}};var hf=new WeakMap,vd=jo(class extends gd{render(s){return Ce}update(s,[e]){let t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=s.options?.host,this.rt(this.ct=s.element)),Ce}rt(s){if(this.isConnected||(s=void 0),typeof this.G=="function"){let e=this.ht??globalThis,t=hf.get(e);t===void 0&&(t=new WeakMap,hf.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,s),s!==void 0&&this.G.call(this.ht,s);}else this.G.value=s;}get lt(){return typeof this.G=="function"?hf.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0);}reconnected(){this.rt(this.ct);}});var Wv=Symbol(),Tr=class{get taskComplete(){return this.t||(this.i===1?this.t=new Promise(((e,t)=>{this.o=e,this.h=t;})):this.i===3?this.t=Promise.reject(this.l):this.t=Promise.resolve(this.u)),this.t}constructor(e,t,i){this.p=0,this.i=0,(this._=e).addController(this);let r=typeof t=="object"?t:{task:t,args:i};this.v=r.task,this.j=r.args,this.m=r.argsEqual??qv,this.k=r.onComplete,this.A=r.onError,this.autoRun=r.autoRun??true,"initialValue"in r&&(this.u=r.initialValue,this.i=2,this.O=this.T?.());}hostUpdate(){this.autoRun===true&&this.S();}hostUpdated(){this.autoRun==="afterUpdate"&&this.S();}T(){if(this.j===void 0)return;let e=this.j();if(!Array.isArray(e))throw Error("The args function must return an array");return e}async S(){let e=this.T(),t=this.O;this.O=e,e===t||e===void 0||t!==void 0&&this.m(t,e)||await this.run(e);}async run(e){let t,i;e??(e=this.T()),this.O=e,this.i===1?this.q?.abort():(this.t=void 0,this.o=void 0,this.h=void 0),this.i=1,this.autoRun==="afterUpdate"?queueMicrotask((()=>this._.requestUpdate())):this._.requestUpdate();let r=++this.p;this.q=new AbortController;let n=false;try{t=await this.v(e,{signal:this.q.signal});}catch(o){n=true,i=o;}if(this.p===r){if(t===Wv)this.i=0;else {if(n===false){try{this.k?.(t);}catch{}this.i=2,this.o?.(t);}else {try{this.A?.(i);}catch{}this.i=3,this.h?.(i);}this.u=t,this.l=i;}this._.requestUpdate();}}abort(e){this.i===1&&this.q?.abort(e);}get value(){return this.u}get error(){return this.l}get status(){return this.i}render(e){switch(this.i){case 0:return e.initial?.();case 1:return e.pending?.();case 2:return e.complete?.(this.value);case 3:return e.error?.(this.error);default:throw Error("Unexpected status: "+this.i)}}},qv=(s,e)=>s===e||s.length===e.length&&s.every(((t,i)=>!dn(t,e[i])));function jv(){return a$1.api.endpoint}var Mi=class{constructor(e,t=1){this.caching=true;this.loading=true;this.host=e,this.type=t,this.loading=true,this.task=new Tr(this.host,async()=>{try{if(this.type==1&&!this.embed)return;if(this.type==0&&!this.token){console.warn("No token attr provided for mave-list");return}let r=await(await fetch(this.manifest_url)).json();return this.loading=!1,this.type==1?(this._embedData=r,this.version=this._embedData.video?.version||0,this._embedData):r}catch(i){throw console.log(i),new Error(`Failed to fetch "${this.embed}"`)}},()=>[this.embed]);}get manifest_url(){if(this.type==1)return this.embedFile("manifest.json");{let e=new URL(`${jv()}/collection/${this.token}`);return this.embed&&this.embed?.length>1&&e.searchParams.append("embed",this.embed),e.toString()}}set embed(e){this._embed!=e&&(this._embed=e,this.loading=true,this.host.requestUpdate());}get embed(){return this._embed}set token(e){this._token!=e&&(this._token=e,this.host.requestUpdate());}get token(){return this._token}get spaceId(){return this.embed?.substring(0,5)}get embedId(){return this.embed?.substring(5,this.embed?.length)}get version(){return this._version?`/v${this._version}/`:"/"}set version(e){this._version!=e&&(this._version=e,this.host.requestUpdate());}get cdnRoot(){return a$1.cdn.endpoint.replace("${this.spaceId}",this.spaceId)}refresh(){return this.loading=true,this.task?.run()}embedFile(e,t=new URLSearchParams){let i=new URL(`${this.cdnRoot}/${this.embedId}${e=="manifest.json"?"/":this.version}${e}`);if(e.includes("?")){let[r,n]=e.split("?");new URLSearchParams(n).forEach((a,l)=>{t.append(l,a);});}return this.token&&t.append("token",this.token),e=="manifest.json"&&(t.has("e")&&t.delete("e"),t.append("e",new Date().getTime().toString())),e!=="manifest.json"&&!this.caching&&(t.has("e")||t.append("e",new Date().getTime().toString())),i.search=t.toString(),i.toString()}render(e){return this.task?.render(e)}};var Ed=["audioprocess","canplay","canplaythrough","complete","duration_change","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting"];var _e,yd,Es,zo,ff,Yv,Qo,zv,Qv,Xv,Zv,li=class extends nt{constructor(){super(...arguments);e(this,_e);this.autoplay="lazy";this.quality="auto";this.fallback="placeholder";this._queue=[];this._failedPlay=false;this._intersectionObserver=new ln(this,{callback:g(this,_e,Qv).bind(this)});this.embedController=new Mi(this);}get embed(){return this._embedId}set embed(t){this._embedId!=t&&(this._embedId=t,this.requestUpdate("embed"),this.embedController.embed=this.embed);}set loop(t){this._loop=t===""||t=="true"||t==true;}get loop(){return this._loop??false}get poster(){return this.embedController.embedFile(`${this.fallback}.jpg`)}set poster(t){if(t){let i=this._poster;this._poster=t,this.requestUpdate("poster",i);}}get token(){return this._token}set token(t){this._token!=t&&(this._token=t,this.requestUpdate("token"),this.embedController.token=this._token);}get sources(){let t=this.autoplay==="scroll"?["clip_keyframes"]:["video","clip"],i=this._embed.video.renditions.filter(n=>(this.quality=="auto"?n.size!=="uhd":d(this,_e,Es).indexOf(n.size)<=d(this,_e,Es).indexOf(this.quality))&&n.container==="mp4"&&d(this,_e,zo).includes(n.codec)&&(!n.type||t.includes(n.type))).sort((n,o)=>n.size===o.size?d(this,_e,zo).indexOf(n.codec)-d(this,_e,zo).indexOf(o.codec):d(this,_e,Es).indexOf(o.size)-d(this,_e,Es).indexOf(n.size)).map(n=>{let o=d(this,_e,Yv).find(l=>l.size===n.size)?.media,a=`${n.codec}_${n.size}${n.type&&n.type!="video"?`_${n.type}`:""}.mp4`;return {media:o,src:this.embedController.embedFile(a),codec:d(this,_e,ff)[n.codec]??n.codec}}),r=this._embed.video.renditions.filter(n=>d(this,_e,Es).indexOf(n.size)<=d(this,_e,Es).indexOf("fhd")&&n.container==="mp4"&&d(this,_e,zo).includes(n.codec)&&(!n.type||t.includes(n.type))).sort((n,o)=>d(this,_e,Es).indexOf(o.size)-d(this,_e,Es).indexOf(n.size));if(r.length>0){let n=r[0],o=`${n.codec}_${n.size}${n.type&&n.type!="video"?`_${n.type}`:""}.mp4`,a={media:void 0,src:this.embedController.embedFile(o),codec:d(this,_e,ff)[n.codec]??n.codec};i.push(a);}return i}connectedCallback(){super.connectedCallback(),typeof document<"u"&&this.autoplay==="scroll"&&document.addEventListener("scroll",g(this,_e,yd).bind(this));}disconnectedCallback(){super.disconnectedCallback(),typeof document<"u"&&this.autoplay==="scroll"&&document.removeEventListener("scroll",g(this,_e,yd).bind(this)),this._metricsInstance?.demonitor();}set muted(t){this._videoElement?this._videoElement.muted=t:this._queue.push(()=>this._videoElement.muted=t);}get muted(){return this._videoElement?.muted||false}get paused(){return this._videoElement?.paused??true}get duration(){return new Promise((t,i)=>{if(this._videoElement&&!isNaN(this._videoElement.duration))return t(this._videoElement.duration);let r=()=>{this._videoElement?.addEventListener("loadedmetadata",()=>{this._videoElement&&t(this._videoElement.duration);}),this._videoElement?.addEventListener("error",n=>{i(new Error("Failed to load video metadata."));});};this._videoElement?r():this.addEventListener("mave:video_element_ready",()=>{r();});})}set currentTime(t){this._videoElement?this._videoElement.currentTime=t:this._queue.push(()=>this._videoElement.currentTime=t);}get currentTime(){return this._videoElement?this._videoElement?.currentTime:0}play(){this._videoElement?g(this,_e,Qo).call(this):this._queue.push(()=>g(this,_e,Qo).call(this));}pause(){this._videoElement?this._videoElement.pause():this._queue.push(()=>this._videoElement?.pause());}render(){return ne`
4
+ ${this.embedController.render({complete:t=>{if(this._embed=t,!!t)return ne`
5
+ <video
6
+ @click=${g(this,_e,Xv)}
7
+ preload="metadata"
8
+ style=${_r(this._failedPlay||this.autoplay==="off"?"cursor: pointer":void 0)}
9
+ muted
10
+ playsinline
11
+ poster=${_r(this._failedPlay?this.poster:void 0)}
12
+ ${vd(g(this,_e,zv))}
13
+ ?autoplay=${this.autoplay==="always"}
14
+ ?loop=${d(this,_e,Zv)}
15
+ >
16
+ ${this.sources.map(i=>ne`
17
+ <source
18
+ media=${_r(i.media?`(min-width: ${i.media}px)`:void 0)}
19
+ src=${i.src}
20
+ type=${`video/mp4; ${i.codec}`}
21
+ />
22
+ `)}
23
+ </video>
24
+ `}})}
25
+ `}};_e=new WeakSet,yd=function(){if(typeof window>"u")return;let{height:t,top:i,bottom:r}=this.getBoundingClientRect(),n=window.innerHeight;if(this._videoElement){this._videoElement.duration||this._videoElement.load();let o=0;if(i<n&&r>0){let a=t+n;o=(n-i)/a*this._videoElement.duration;}o>=0&&o<=this._videoElement.duration&&(this._videoElement.currentTime=o);}},Es=function(){return ["sd","hd","fhd","qhd","uhd"]},zo=function(){let t=navigator.userAgent,i=/Edg/.test(t)&&/Mac OS/.test(t),r=/Safari/.test(t)&&!/Chrome/.test(t),n=/Mac OS/.test(t),o=/iPhone|iPad/.test(t);return n&&(r||i)||o?["hevc","h264"]:["av1","h264"]},ff=function(){return {av1:"av01.0.08M.08.0.110.01.01.01.0,opus",hevc:"hevc.01.00.78,mp4a.40.2",h264:"avc1.64.00.28,mp4a.40.2"}},Yv=function(){return [{size:"qhd",media:1280},{size:"fhd",media:1080},{size:"hd",media:720},{size:"sd",media:640}]},Qo=function(){this._metricsInstance?.monitor(),this._videoElement&&(this._videoElement.muted=true,this._videoElement.play().catch(t=>{this._failedPlay=true;}));},zv=function(t){if(this._videoElement||(this._videoElement=t,this.dispatchEvent(new CustomEvent("mave:video_element_ready",{detail:this._videoElement,bubbles:true,composed:true}))),this._intersectionObserver.observe(this._videoElement),this._videoElement&&this._embed){Ed.forEach(r=>{this._videoElement?.addEventListener(r,n=>{!this._canPlay&&this.autoplay==="scroll"&&r==="canplay"&&(this._canPlay=true,g(this,_e,yd).call(this)),this.dispatchEvent(new CustomEvent(r,{detail:n,bubbles:true,composed:true}));});});({video_id:this._embed.video.id,space_id:this._embed.space_id});Us.config={apiEndpoint:a$1.metrics.endpoint},a$1.metrics.enabled&&(this._metricsInstance=new Us(this._videoElement,this.embed,{component:"clip"}));}this._queue.length&&(this._queue.forEach(i=>i()),this._queue=[]);},Qv=function(t){for(let{isIntersecting:i}of t){if(this.autoplay==="always")return;i&&(this.autoplay==="lazy"||this.autoplay==="true")?this._videoElement?.paused&&g(this,_e,Qo).call(this):this._videoElement?.paused||this._videoElement?.pause();}},Xv=function(){(this.autoplay==="off"||this._failedPlay)&&(this._videoElement?.paused?g(this,_e,Qo).call(this):this._videoElement?.pause());},Zv=function(){return this._loop!==void 0?this._loop:this.autoplay!=="off"},li.styles=it`
26
+ :host {
27
+ display: block;
28
+ position: relative;
29
+ overflow: hidden;
30
+ }
31
+
32
+ video {
33
+ all: initial;
34
+ display: block;
35
+ width: 100%;
36
+ height: 100%;
37
+ object-fit: var(--clip-fit, cover);
38
+ object-position: var(--clip-position, 50% 50%);
39
+ }
40
+ `,c([oe()],li.prototype,"embed",1),c([oe()],li.prototype,"autoplay",2),c([oe()],li.prototype,"quality",2),c([oe()],li.prototype,"fallback",2),c([oe()],li.prototype,"loop",1),c([oe()],li.prototype,"poster",1),c([oe()],li.prototype,"token",1),c([Ct()],li.prototype,"_failedPlay",2);typeof window<"u"&&window.customElements&&(window.customElements.get("mave-clip")||window.customElements.define("mave-clip",li));var Ei=class extends nt{constructor(){super(...arguments);this.EVENT_TYPES={CLICK:"user_click"};}get embed(){return this._embed}set embed(t){this._embed=t;}get embedId(){return this._embed?.substring(5,this._embed?.length)}get spaceId(){return this.embed?.substring(0,5)}get cdn_root(){return a$1.cdn.endpoint.replace("${this.spaceId}",this.spaceId)}get _stylesheets(){if(typeof document>"u")return ne``;let t=document.querySelectorAll('style, link[rel="stylesheet"]');return ne`${Array.from(t).map(i=>i.cloneNode(true))}`}durationToTime(t){let i=Math.floor(t),r=Math.floor(i/3600),n=Math.floor(i%3600/60),o=i%60;return r>0?`${r}:${n.toString().padStart(2,"0")}:${o.toString().padStart(2,"0")}`:`${n}:${o.toString().padStart(2,"0")}`}emit(t,i){this.dispatchEvent(new CustomEvent(`mave:${t}`,{detail:{...i,eventType:t}})),this.dispatchEvent(new CustomEvent("mave:*",{detail:{...i,eventType:t}}));}};c([oe({type:String})],Ei.prototype,"embed",1);var Re,Fs,Jv,eE,bd,mf,pf,tE,iE,sE,rE,gf,Xo=class extends Ei{constructor(){super(...arguments);e(this,Re);this.embedController=new Mi(this);}get embed(){return this._embed}set embed(t){this._embed!==t&&(this._embed=t,this.requestUpdate("embed"),this.embedController.embed=this.embed);}get _slottedChildren(){return this.shadowRoot?.querySelector("slot")?.assignedElements({flatten:true})||[]}render(){return ne`
41
+ ${this.embedController.render({pending:this.renderPending,complete:t=>{if(this._data=t,!t)return;let i=g(this,Re,sE).call(this),r=g(this,Re,rE).call(this),n=this._slottedChildren.map(o=>{function a(){let d;return o.nodeName==="TEMPLATE"?d=o.content.cloneNode(true):d=o.cloneNode(true),d}if(o.getAttribute("name")=="mave-files-video"){if(!i)return;let d=a(),c=Number(this._data.created_at),u=c&&c<1e12?c*1e3:c;Number.isFinite(u)&&g(this,Re,Fs).call(this,d,"date",new Date(u).toLocaleDateString().replaceAll("/","-"));let h=this._data.video.duration;h&&g(this,Re,Fs).call(this,d,"duration",this.durationToTime(h));let f=this._data.video.filetype;f&&g(this,Re,Fs).call(this,d,"filetype",f);let m=i.file_size||this._data.video.size;m&&g(this,Re,Fs).call(this,d,"size",g(this,Re,mf).call(this,m));let p=g(this,Re,tE).call(this,i),g$1=i.container||"mp4",E=g(this,Re,bd).call(this,p,`${this._data.name}.${g$1}`);return E.setAttribute("aria-label","Download video"),E.appendChild(d),ne`${E}`}if(r&&o.getAttribute("name")=="mave-files-audio"){let d=a(),c=r.codec||g(this,Re,gf).call(this,r.filename)||"mp3";g(this,Re,Fs).call(this,d,"filetype",c);let u=r.file_size;u&&g(this,Re,Fs).call(this,d,"size",g(this,Re,mf).call(this,u));let h=g(this,Re,iE).call(this,r),f=g(this,Re,bd).call(this,h,r.filename||`${this._data.name}.${c}`);return f.setAttribute("aria-label","Download audio"),f.appendChild(d),ne`${f}`}let l=this._data.subtitles.find(d=>d.language==this._data.video.language);if(l&&o.getAttribute("name")=="mave-files-subtitles"){let d=a();g(this,Re,Fs).call(this,d,"filetype","vtt");let c=g(this,Re,bd).call(this,l.path,`${this._data.name}.vtt`);return c.setAttribute("aria-label","Download subtitles"),c.appendChild(d),ne`${c}`}});return ne`${this._stylesheets} ${n}`}})}
42
+ `}renderPending(){return ne`<slot style="display: none"></slot>`}};Re=new WeakSet,Fs=function(t,i,r){let n=t.querySelector(`[slot="${i}"], [data-slot="${i}"]`);n&&(n.textContent=r,n.removeAttribute("slot"),n.removeAttribute("data-slot"));},Jv=function(t,i){let r=window.URL.createObjectURL(t),n=document.createElement("a");n.style.display="none",n.href=r,n.download=i,this.appendChild(n),n.click(),window.URL.revokeObjectURL(r),this.removeChild(n);},eE=function(t,i){return fetch(t).then(r=>{if(!r.ok)throw new Error("Network response was not ok");return r.blob()}).then(r=>g(this,Re,Jv).call(this,r,i)).catch(r=>console.error("Something went wrong:",r))},bd=function(t,i){let r=document.createElement("a");r.classList.add("link"),r.setAttribute("href",t),r.setAttribute("download",i),r.setAttribute("target","new");let n=false;return r.addEventListener("click",o=>{o.preventDefault(),!n&&(n=true,r.style.cursor="wait",r.style.opacity="0.5",g(this,Re,eE).call(this,t,i).then(()=>{n=false,r.style.cursor="pointer",r.style.opacity="1";}));}),r},mf=function(t){let i=t/1e6;if(i<10)return `${i.toFixed(1)} MB`;let r=i%1!==0;return `${i.toFixed(r?1:0)} MB`},pf=function(t){let i=this._data?.video?.version&&this._data.video.version>0?`v${this._data.video.version}/`:"";return `${this.cdn_root}/${this.embedId}/${i}${t}`},tE=function(t){let i=t?.codec||"h264",r=t?.size||"hd",n=t?.container||"mp4";return g(this,Re,pf).call(this,`${i}_${r}.${n}`)},iE=function(t){if(t?.path)return t.path;let i=t?.codec||g(this,Re,gf).call(this,t?.filename||"")||"mp3";return g(this,Re,pf).call(this,`audio.${i}`)},sE=function(){let t=this._data?.video?.renditions||[];if(!t.length)return;let i=t.filter(n=>n.container==="mp4"&&n.codec==="h264"&&(!n.type||n.type==="video")),r=["hd","fhd","sd","qhd","uhd"];for(let n of r){let o=i.find(a=>a.size===n);if(o)return o}return i[0]||t.find(n=>n.type==="video")},rE=function(){let t=this._data?.audio_tracks||[];if(t.length)return t.find(i=>i.default)||t[0]},gf=function(t){if(!t)return;let i=t.split(".");return i.length>1?i.pop():void 0},Xo.styles=it`
43
+ :host {
44
+ display: block;
45
+ --link-color: #006fc6;
46
+ --link-decoration: underline;
47
+ --link-decoration-thickness: 1px;
48
+ --link-decoration-offset: 1px;
49
+ --link-cursor: pointer;
50
+ }
51
+
52
+ a {
53
+ text-decoration: var(--link-decoration);
54
+ text-decoration-thickness: var(--link-decoration-thickness);
55
+ text-underline-offset: var(--link-decoration-thickness);
56
+ color: var(--link-color);
57
+ cursor: var(--link-cursor);
58
+ }
59
+ `,c([oe({type:String})],Xo.prototype,"embed",1);typeof window<"u"&&window.customElements&&(window.customElements.get("mave-files")||window.customElements.define("mave-files",Xo));var _d=class extends Ei{get poster(){return `${this.cdn_root}/${this.embedId}/poster.webp`}render(){return ne`<img src=${this.poster} />`}};_d.styles=it`
60
+ :host {
61
+ display: block;
62
+ }
63
+
64
+ img {
65
+ width: 100%;
66
+ max-height: 100vh;
67
+ }
68
+ `;typeof window<"u"&&window.customElements&&(window.customElements.get("mave-img")||window.customElements.define("mave-img",_d));var V={MEDIA_PLAY_REQUEST:"mediaplayrequest",MEDIA_PAUSE_REQUEST:"mediapauserequest",MEDIA_MUTE_REQUEST:"mediamuterequest",MEDIA_UNMUTE_REQUEST:"mediaunmuterequest",MEDIA_LOOP_REQUEST:"medialooprequest",MEDIA_VOLUME_REQUEST:"mediavolumerequest",MEDIA_SEEK_REQUEST:"mediaseekrequest",MEDIA_AIRPLAY_REQUEST:"mediaairplayrequest",MEDIA_ENTER_FULLSCREEN_REQUEST:"mediaenterfullscreenrequest",MEDIA_EXIT_FULLSCREEN_REQUEST:"mediaexitfullscreenrequest",MEDIA_PREVIEW_REQUEST:"mediapreviewrequest",MEDIA_ENTER_PIP_REQUEST:"mediaenterpiprequest",MEDIA_EXIT_PIP_REQUEST:"mediaexitpiprequest",MEDIA_ENTER_CAST_REQUEST:"mediaentercastrequest",MEDIA_EXIT_CAST_REQUEST:"mediaexitcastrequest",MEDIA_SHOW_TEXT_TRACKS_REQUEST:"mediashowtexttracksrequest",MEDIA_HIDE_TEXT_TRACKS_REQUEST:"mediahidetexttracksrequest",MEDIA_SHOW_SUBTITLES_REQUEST:"mediashowsubtitlesrequest",MEDIA_DISABLE_SUBTITLES_REQUEST:"mediadisablesubtitlesrequest",MEDIA_TOGGLE_SUBTITLES_REQUEST:"mediatogglesubtitlesrequest",MEDIA_PLAYBACK_RATE_REQUEST:"mediaplaybackraterequest",MEDIA_RENDITION_REQUEST:"mediarenditionrequest",MEDIA_AUDIO_TRACK_REQUEST:"mediaaudiotrackrequest",MEDIA_SEEK_TO_LIVE_REQUEST:"mediaseektoliverequest",REGISTER_MEDIA_STATE_RECEIVER:"registermediastatereceiver",UNREGISTER_MEDIA_STATE_RECEIVER:"unregistermediastatereceiver"},ve={MEDIA_CHROME_ATTRIBUTES:"mediachromeattributes",MEDIA_CONTROLLER:"mediacontroller"},vf={MEDIA_AIRPLAY_UNAVAILABLE:"mediaAirplayUnavailable",MEDIA_AUDIO_TRACK_ENABLED:"mediaAudioTrackEnabled",MEDIA_AUDIO_TRACK_LIST:"mediaAudioTrackList",MEDIA_AUDIO_TRACK_UNAVAILABLE:"mediaAudioTrackUnavailable",MEDIA_BUFFERED:"mediaBuffered",MEDIA_CAST_UNAVAILABLE:"mediaCastUnavailable",MEDIA_CHAPTERS_CUES:"mediaChaptersCues",MEDIA_CURRENT_TIME:"mediaCurrentTime",MEDIA_DURATION:"mediaDuration",MEDIA_ENDED:"mediaEnded",MEDIA_ERROR:"mediaError",MEDIA_ERROR_CODE:"mediaErrorCode",MEDIA_ERROR_MESSAGE:"mediaErrorMessage",MEDIA_FULLSCREEN_UNAVAILABLE:"mediaFullscreenUnavailable",MEDIA_HAS_PLAYED:"mediaHasPlayed",MEDIA_HEIGHT:"mediaHeight",MEDIA_IS_AIRPLAYING:"mediaIsAirplaying",MEDIA_IS_CASTING:"mediaIsCasting",MEDIA_IS_FULLSCREEN:"mediaIsFullscreen",MEDIA_IS_PIP:"mediaIsPip",MEDIA_LOADING:"mediaLoading",MEDIA_MUTED:"mediaMuted",MEDIA_LOOP:"mediaLoop",MEDIA_PAUSED:"mediaPaused",MEDIA_PIP_UNAVAILABLE:"mediaPipUnavailable",MEDIA_PLAYBACK_RATE:"mediaPlaybackRate",MEDIA_PREVIEW_CHAPTER:"mediaPreviewChapter",MEDIA_PREVIEW_COORDS:"mediaPreviewCoords",MEDIA_PREVIEW_IMAGE:"mediaPreviewImage",MEDIA_PREVIEW_TIME:"mediaPreviewTime",MEDIA_RENDITION_LIST:"mediaRenditionList",MEDIA_RENDITION_SELECTED:"mediaRenditionSelected",MEDIA_RENDITION_UNAVAILABLE:"mediaRenditionUnavailable",MEDIA_SEEKABLE:"mediaSeekable",MEDIA_STREAM_TYPE:"mediaStreamType",MEDIA_SUBTITLES_LIST:"mediaSubtitlesList",MEDIA_SUBTITLES_SHOWING:"mediaSubtitlesShowing",MEDIA_TARGET_LIVE_WINDOW:"mediaTargetLiveWindow",MEDIA_TIME_IS_LIVE:"mediaTimeIsLive",MEDIA_VOLUME:"mediaVolume",MEDIA_VOLUME_LEVEL:"mediaVolumeLevel",MEDIA_VOLUME_UNAVAILABLE:"mediaVolumeUnavailable",MEDIA_LANG:"mediaLang",MEDIA_WIDTH:"mediaWidth"},nE=Object.entries(vf),b=nE.reduce((s,[e,t])=>(s[e]=t.toLowerCase(),s),{}),OI={USER_INACTIVE_CHANGE:"userinactivechange",BREAKPOINTS_CHANGE:"breakpointchange",BREAKPOINTS_COMPUTED:"breakpointscomputed"},Sr=nE.reduce((s,[e,t])=>(s[e]=t.toLowerCase(),s),{...OI});Object.entries(Sr).reduce((s,[e,t])=>{let i=b[e];return i&&(s[t]=i),s},{userinactivechange:"userinactive"});var oE=Object.entries(b).reduce((s,[e,t])=>{let i=Sr[e];return i&&(s[t]=i),s},{userinactive:"userinactivechange"}),Bt={SUBTITLES:"subtitles",CAPTIONS:"captions",CHAPTERS:"chapters",METADATA:"metadata"},$s={DISABLED:"disabled",SHOWING:"showing"};var Td={MOUSE:"mouse",PEN:"pen",TOUCH:"touch"},Ht={UNAVAILABLE:"unavailable",UNSUPPORTED:"unsupported"},yi={LIVE:"live",ON_DEMAND:"on-demand",UNKNOWN:"unknown"};var aE={FULLSCREEN:"fullscreen"};function lE(s){return s?.map(NI).join(" ")}function dE(s){return s?.split(/\s+/).map(FI)}function NI(s){if(s){let{id:e,width:t,height:i}=s;return [e,t,i].filter(r=>r!=null).join(":")}}function FI(s){if(s){let[e,t,i]=s.split(":");return {id:e,width:+t,height:+i}}}function cE(s){return s?.map($I).join(" ")}function uE(s){return s?.split(/\s+/).map(BI)}function $I(s){if(s){let{id:e,kind:t,language:i,label:r}=s;return [e,t,i,r].filter(n=>n!=null).join(":")}}function BI(s){if(s){let[e,t,i,r]=s.split(":");return {id:e,kind:t,language:i,label:r}}}function hn(s){return typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s)}var Sd=s=>new Promise(e=>setTimeout(e,s));var hE=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],HI=(s,e)=>{let t=s===1?hE[e].singular:hE[e].plural;return `${s} ${t}`},Ar=s=>{if(!hn(s))return "";let e=Math.abs(s),t=e!==s,i=new Date(0,0,0,0,0,e,0);return `${[i.getHours(),i.getMinutes(),i.getSeconds()].map((a,l)=>a&&HI(a,l)).filter(a=>a).join(", ")}${t?" remaining":""}`};function bi(s,e){let t=false;s<0&&(t=true,s=0-s),s=s<0?0:s;let i=Math.floor(s%60),r=Math.floor(s/60%60),n=Math.floor(s/3600),o=Math.floor(e/60%60),a=Math.floor(e/3600);return (isNaN(s)||s===1/0)&&(n=r=i="0"),n=n>0||a>0?n+":":"",r=((n||o>=10)&&r<10?"0"+r:r)+":",i=i<10?"0"+i:i,(t?"-":"")+n+r+i}var fE={"Start airplay":"Start airplay","Stop airplay":"Stop airplay",Audio:"Audio",Captions:"Captions","Enable captions":"Enable captions","Disable captions":"Disable captions","Start casting":"Start casting","Stop casting":"Stop casting","Enter fullscreen mode":"Enter fullscreen mode","Exit fullscreen mode":"Exit fullscreen mode",Mute:"Mute",Unmute:"Unmute",Loop:"Loop","Enter picture in picture mode":"Enter picture in picture mode","Exit picture in picture mode":"Exit picture in picture mode",Play:"Play",Pause:"Pause","Playback rate":"Playback rate","Playback rate {playbackRate}":"Playback rate {playbackRate}",Quality:"Quality","Seek backward":"Seek backward","Seek forward":"Seek forward",Settings:"Settings",Auto:"Auto","audio player":"audio player","video player":"video player",volume:"volume",seek:"seek","closed captions":"closed captions","current playback rate":"current playback rate","playback time":"playback time","media loading":"media loading",settings:"settings","audio tracks":"audio tracks",quality:"quality",play:"play",pause:"pause",mute:"mute",unmute:"unmute","chapter: {chapterName}":"chapter: {chapterName}",live:"live",Off:"Off","start airplay":"start airplay","stop airplay":"stop airplay","start casting":"start casting","stop casting":"stop casting","enter fullscreen mode":"enter fullscreen mode","exit fullscreen mode":"exit fullscreen mode","enter picture in picture mode":"enter picture in picture mode","exit picture in picture mode":"exit picture in picture mode","seek to live":"seek to live","playing live":"playing live","seek back {seekOffset} seconds":"seek back {seekOffset} seconds","seek forward {seekOffset} seconds":"seek forward {seekOffset} seconds","Network Error":"Network Error","Decode Error":"Decode Error","Source Not Supported":"Source Not Supported","Encryption Error":"Encryption Error","A network error caused the media download to fail.":"A network error caused the media download to fail.","A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.":"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.","An unsupported error occurred. The server or network failed, or your browser does not support this format.":"An unsupported error occurred. The server or network failed, or your browser does not support this format.","The media is encrypted and there are no keys to decrypt it.":"The media is encrypted and there are no keys to decrypt it."};var mE,Ef={en:fE},yf=((mE=globalThis.navigator)==null?void 0:mE.language)||"en",pE=s=>{yf=s;};var KI=s=>{var e,t,i;let[r]=yf.split("-");return ((e=Ef[yf])==null?void 0:e[s])||((t=Ef[r])==null?void 0:t[s])||((i=Ef.en)==null?void 0:i[s])||s},K=(s,e={})=>KI(s).replace(/\{(\w+)\}/g,(t,i)=>i in e?String(e[i]):`{${i}}`);var Ad=class{addEventListener(){}removeEventListener(){}dispatchEvent(){return true}},Id=class extends Ad{},xd=class extends Id{constructor(){super(...arguments),this.role=null;}},bf=class{observe(){}unobserve(){}disconnect(){}},gE={createElement:function(){return new Zo.HTMLElement},createElementNS:function(){return new Zo.HTMLElement},addEventListener(){},removeEventListener(){},dispatchEvent(s){return false}},Zo={ResizeObserver:bf,document:gE,Node:Id,Element:xd,HTMLElement:class extends xd{constructor(){super(...arguments),this.innerHTML="";}get content(){return new Zo.DocumentFragment}},DocumentFragment:class extends Ad{},customElements:{get:function(){},define:function(){},whenDefined:function(){}},localStorage:{getItem(s){return null},setItem(s,e){},removeItem(s){}},CustomEvent:function(){},getComputedStyle:function(){},navigator:{languages:[],get userAgent(){return ""}},matchMedia(s){return {matches:false,media:s}},DOMParser:class{parseFromString(e,t){return {body:{textContent:e}}}}},vE="global"in globalThis&&globalThis?.global===globalThis||typeof window>"u"||typeof window.customElements>"u",EE=Object.keys(Zo).every(s=>s in globalThis),A=vE&&!EE?Zo:globalThis,je=vE&&!EE?gE:globalThis.document;var yE=new WeakMap,_f=s=>{let e=yE.get(s);return e||yE.set(s,e=new Set),e},bE=new A.ResizeObserver(s=>{for(let e of s)for(let t of _f(e.target))t(e);});function ys(s,e){_f(s).add(e),bE.observe(s);}function bs(s,e){let t=_f(s);t.delete(e),t.size||bE.unobserve(s);}function qe(s){let e={};for(let t of s)e[t.name]=t.value;return e}function Ge(s){var e;return (e=Ld(s))!=null?e:Pi(s,"media-controller")}function Ld(s){var e;let{MEDIA_CONTROLLER:t}=ve,i=s.getAttribute(t);if(i)return (e=Ir(s))==null?void 0:e.getElementById(i)}var Rd=(s,e,t=".value")=>{let i=s.querySelector(t);i&&(i.textContent=e);},VI=(s,e)=>{let t=`slot[name="${e}"]`,i=s.shadowRoot.querySelector(t);return i?i.children:[]},kd=(s,e)=>VI(s,e)[0],Nt=(s,e)=>!s||!e?false:s?.contains(e)?true:Nt(s,e.getRootNode().host),Pi=(s,e)=>{if(!s)return null;let t=s.closest(e);return t||Pi(s.getRootNode().host,e)};function Jo(s=document){var e;let t=s?.activeElement;return t?(e=Jo(t.shadowRoot))!=null?e:t:null}function Ir(s){var e;let t=(e=s?.getRootNode)==null?void 0:e.call(s);return t instanceof ShadowRoot||t instanceof Document?t:null}function wd(s,{depth:e=3,checkOpacity:t=true,checkVisibilityCSS:i=true}={}){if(s.checkVisibility)return s.checkVisibility({checkOpacity:t,checkVisibilityCSS:i});let r=s;for(;r&&e>0;){let n=getComputedStyle(r);if(t&&n.opacity==="0"||i&&n.visibility==="hidden"||n.display==="none")return false;r=r.parentElement,e--;}return true}function _E(s,e,t,i){let r=i.x-t.x,n=i.y-t.y,o=r*r+n*n;if(o===0)return 0;let a=((s-t.x)*r+(e-t.y)*n)/o;return Math.max(0,Math.min(1,a))}function Ke(s,e){let t=WI(s,i=>i===e);return t||ea(s,e)}function WI(s,e){var t,i;let r;for(r of (t=s.querySelectorAll("style:not([media])"))!=null?t:[]){let n;try{n=(i=r.sheet)==null?void 0:i.cssRules;}catch{continue}for(let o of n??[])if(e(o.selectorText))return o}}function ea(s,e){var t,i;let r=(t=s.querySelectorAll("style:not([media])"))!=null?t:[],n=r?.[r.length-1];return n?.sheet?(n?.sheet.insertRule(`${e}{}`,n.sheet.cssRules.length),(i=n.sheet.cssRules)==null?void 0:i[n.sheet.cssRules.length-1]):(console.warn("Media Chrome: No style sheet found on style tag of",s),{style:{setProperty:()=>{},removeProperty:()=>"",getPropertyValue:()=>""}})}function ye(s,e,t=Number.NaN){let i=s.getAttribute(e);return i!=null?+i:t}function Ae(s,e,t){let i=+t;if(t==null||Number.isNaN(i)){s.hasAttribute(e)&&s.removeAttribute(e);return}ye(s,e,void 0)!==i&&s.setAttribute(e,`${i}`);}function ae(s,e){return s.hasAttribute(e)}function le(s,e,t){if(t==null){s.hasAttribute(e)&&s.removeAttribute(e);return}ae(s,e)!=t&&s.toggleAttribute(e,t);}function me(s,e,t=null){var i;return (i=s.getAttribute(e))!=null?i:t}function pe(s,e,t){if(t==null){s.hasAttribute(e)&&s.removeAttribute(e);return}let i=`${t}`;me(s,e,void 0)!==i&&s.setAttribute(e,i);}var TE=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Bs=(s,e,t)=>(TE(s,e,"read from private field"),t?t.call(s):e.get(s)),qI=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Cd=(s,e,t,i)=>(TE(s,e,"write to private field"),e.set(s,t),t),Gt;function jI(s){return `
69
+ <style>
70
+ :host {
71
+ display: var(--media-control-display, var(--media-gesture-receiver-display, inline-block));
72
+ box-sizing: border-box;
73
+ }
74
+ </style>
75
+ `}var fn=class extends A.HTMLElement{constructor(){if(super(),qI(this,Gt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [ve.MEDIA_CONTROLLER,b.MEDIA_PAUSED]}attributeChangedCallback(e,t,i){var r,n,o,a,l;e===ve.MEDIA_CONTROLLER&&(t&&((n=(r=Bs(this,Gt))==null?void 0:r.unassociateElement)==null||n.call(r,this),Cd(this,Gt,null)),i&&this.isConnected&&(Cd(this,Gt,(o=this.getRootNode())==null?void 0:o.getElementById(i)),(l=(a=Bs(this,Gt))==null?void 0:a.associateElement)==null||l.call(a,this)));}connectedCallback(){var e,t,i,r;this.tabIndex=-1,this.setAttribute("aria-hidden","true"),Cd(this,Gt,YI(this)),this.getAttribute(ve.MEDIA_CONTROLLER)&&((t=(e=Bs(this,Gt))==null?void 0:e.associateElement)==null||t.call(e,this)),(i=Bs(this,Gt))==null||i.addEventListener("pointerdown",this),(r=Bs(this,Gt))==null||r.addEventListener("click",this);}disconnectedCallback(){var e,t,i,r;this.getAttribute(ve.MEDIA_CONTROLLER)&&((t=(e=Bs(this,Gt))==null?void 0:e.unassociateElement)==null||t.call(e,this)),(i=Bs(this,Gt))==null||i.removeEventListener("pointerdown",this),(r=Bs(this,Gt))==null||r.removeEventListener("click",this),Cd(this,Gt,null);}handleEvent(e){var t;let i=(t=e.composedPath())==null?void 0:t[0];if(["video","media-controller"].includes(i?.localName)){if(e.type==="pointerdown")this._pointerType=e.pointerType;else if(e.type==="click"){let{clientX:n,clientY:o}=e,{left:a,top:l,width:d,height:c}=this.getBoundingClientRect(),u=n-a,h=o-l;if(u<0||h<0||u>d||h>c||d===0&&c===0)return;let f=this._pointerType||"mouse";if(this._pointerType=void 0,f===Td.TOUCH){this.handleTap(e);return}else if(f===Td.MOUSE||f===Td.PEN){this.handleMouseClick(e);return}}}}get mediaPaused(){return ae(this,b.MEDIA_PAUSED)}set mediaPaused(e){le(this,b.MEDIA_PAUSED,e);}handleTap(e){}handleMouseClick(e){let t=this.mediaPaused?V.MEDIA_PLAY_REQUEST:V.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new A.CustomEvent(t,{composed:true,bubbles:true}));}};Gt=new WeakMap;fn.shadowRootOptions={mode:"open"};fn.getTemplateHTML=jI;function YI(s){var e;let t=s.getAttribute(ve.MEDIA_CONTROLLER);return t?(e=s.getRootNode())==null?void 0:e.getElementById(t):Pi(s,"media-controller")}A.customElements.get("media-gesture-receiver")||A.customElements.define("media-gesture-receiver",fn);var Dd=fn;var If=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Xt=(s,e,t)=>(If(s,e,"read from private field"),t?t.call(s):e.get(s)),Qt=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},xr=(s,e,t,i)=>(If(s,e,"write to private field"),e.set(s,t),t),di=(s,e,t)=>(If(s,e,"access private method"),t),Od,mn,ia,pn,Md,Tf,SE,ta,Pd,Sf,AE,Af,IE,sa,Ud,Nd,xf,gn,ra,ue={AUDIO:"audio",AUTOHIDE:"autohide",BREAKPOINTS:"breakpoints",GESTURES_DISABLED:"gesturesdisabled",KEYBOARD_CONTROL:"keyboardcontrol",NO_AUTOHIDE:"noautohide",USER_INACTIVE:"userinactive",AUTOHIDE_OVER_CONTROLS:"autohideovercontrols"};function zI(s){return `
76
+ <style>
77
+
78
+ :host([${b.MEDIA_IS_FULLSCREEN}]) ::slotted([slot=media]) {
79
+ outline: none;
80
+ }
81
+
82
+ :host {
83
+ box-sizing: border-box;
84
+ position: relative;
85
+ display: inline-block;
86
+ line-height: 0;
87
+ background-color: var(--media-background-color, #000);
88
+ overflow: hidden;
89
+ }
90
+
91
+ :host(:not([${ue.AUDIO}])) [part~=layer]:not([part~=media-layer]) {
92
+ position: absolute;
93
+ top: 0;
94
+ left: 0;
95
+ bottom: 0;
96
+ right: 0;
97
+ display: flex;
98
+ flex-flow: column nowrap;
99
+ align-items: start;
100
+ pointer-events: none;
101
+ background: none;
102
+ }
103
+
104
+ slot[name=media] {
105
+ display: var(--media-slot-display, contents);
106
+ }
107
+
108
+
109
+ :host([${ue.AUDIO}]) slot[name=media] {
110
+ display: var(--media-slot-display, none);
111
+ }
112
+
113
+
114
+ :host([${ue.AUDIO}]) [part~=layer][part~=gesture-layer] {
115
+ height: 0;
116
+ display: block;
117
+ }
118
+
119
+
120
+ :host(:not([${ue.AUDIO}])[${ue.GESTURES_DISABLED}]) ::slotted([slot=gestures-chrome]),
121
+ :host(:not([${ue.AUDIO}])[${ue.GESTURES_DISABLED}]) media-gesture-receiver[slot=gestures-chrome] {
122
+ display: none;
123
+ }
124
+
125
+
126
+ ::slotted(:not([slot=media]):not([slot=poster]):not(media-loading-indicator):not([role=dialog]):not([hidden])) {
127
+ pointer-events: auto;
128
+ }
129
+
130
+ :host(:not([${ue.AUDIO}])) *[part~=layer][part~=centered-layer] {
131
+ align-items: center;
132
+ justify-content: center;
133
+ }
134
+
135
+ :host(:not([${ue.AUDIO}])) ::slotted(media-gesture-receiver[slot=gestures-chrome]),
136
+ :host(:not([${ue.AUDIO}])) media-gesture-receiver[slot=gestures-chrome] {
137
+ align-self: stretch;
138
+ flex-grow: 1;
139
+ }
140
+
141
+ slot[name=middle-chrome] {
142
+ display: inline;
143
+ flex-grow: 1;
144
+ pointer-events: none;
145
+ background: none;
146
+ }
147
+
148
+
149
+ ::slotted([slot=media]),
150
+ ::slotted([slot=poster]) {
151
+ width: 100%;
152
+ height: 100%;
153
+ }
154
+
155
+
156
+ :host(:not([${ue.AUDIO}])) .spacer {
157
+ flex-grow: 1;
158
+ }
159
+
160
+
161
+ :host(:-webkit-full-screen) {
162
+
163
+ width: 100% !important;
164
+ height: 100% !important;
165
+ }
166
+
167
+
168
+ ::slotted(:not([slot=media]):not([slot=poster]):not([${ue.NO_AUTOHIDE}]):not([hidden]):not([role=dialog])) {
169
+ opacity: 1;
170
+ transition: var(--media-control-transition-in, opacity 0.25s);
171
+ }
172
+
173
+
174
+ :host([${ue.USER_INACTIVE}]:not([${b.MEDIA_PAUSED}]):not([${b.MEDIA_IS_AIRPLAYING}]):not([${b.MEDIA_IS_CASTING}]):not([${ue.AUDIO}])) ::slotted(:not([slot=media]):not([slot=poster]):not([${ue.NO_AUTOHIDE}]):not([role=dialog])) {
175
+ opacity: 0;
176
+ transition: var(--media-control-transition-out, opacity 1s);
177
+ }
178
+
179
+ :host([${ue.USER_INACTIVE}]:not([${ue.NO_AUTOHIDE}]):not([${b.MEDIA_PAUSED}]):not([${b.MEDIA_IS_CASTING}]):not([${ue.AUDIO}])) ::slotted([slot=media]) {
180
+ cursor: none;
181
+ }
182
+
183
+ :host([${ue.USER_INACTIVE}][${ue.AUTOHIDE_OVER_CONTROLS}]:not([${ue.NO_AUTOHIDE}]):not([${b.MEDIA_PAUSED}]):not([${b.MEDIA_IS_CASTING}]):not([${ue.AUDIO}])) * {
184
+ --media-cursor: none;
185
+ cursor: none;
186
+ }
187
+
188
+
189
+ ::slotted(media-control-bar) {
190
+ align-self: stretch;
191
+ }
192
+
193
+
194
+ :host(:not([${ue.AUDIO}])[${b.MEDIA_HAS_PLAYED}]) slot[name=poster] {
195
+ display: none;
196
+ }
197
+
198
+ ::slotted([role=dialog]) {
199
+ width: 100%;
200
+ height: 100%;
201
+ align-self: center;
202
+ }
203
+
204
+ ::slotted([role=menu]) {
205
+ align-self: end;
206
+ }
207
+ </style>
208
+
209
+ <slot name="media" part="layer media-layer"></slot>
210
+ <slot name="poster" part="layer poster-layer"></slot>
211
+ <slot name="gestures-chrome" part="layer gesture-layer">
212
+ <media-gesture-receiver slot="gestures-chrome">
213
+ <template shadowrootmode="${Dd.shadowRootOptions.mode}">
214
+ ${Dd.getTemplateHTML({})}
215
+ </template>
216
+ </media-gesture-receiver>
217
+ </slot>
218
+ <span part="layer vertical-layer">
219
+ <slot name="top-chrome" part="top chrome"></slot>
220
+ <slot name="middle-chrome" part="middle chrome"></slot>
221
+ <slot name="centered-chrome" part="layer centered-layer center centered chrome"></slot>
222
+
223
+ <slot part="bottom chrome"></slot>
224
+ </span>
225
+ <slot name="dialog" part="layer dialog-layer"></slot>
226
+ `}var QI=Object.values(b),XI="sm:384 md:576 lg:768 xl:960";function ZI(s){xE(s.target,s.contentRect.width);}function xE(s,e){var t;if(!s.isConnected)return;let i=(t=s.getAttribute(ue.BREAKPOINTS))!=null?t:XI,r=JI(i),n=ex(r,e),o=false;if(Object.keys(r).forEach(a=>{if(n.includes(a)){s.hasAttribute(`breakpoint${a}`)||(s.setAttribute(`breakpoint${a}`,""),o=true);return}s.hasAttribute(`breakpoint${a}`)&&(s.removeAttribute(`breakpoint${a}`),o=true);}),o){let a=new CustomEvent(Sr.BREAKPOINTS_CHANGE,{detail:n});s.dispatchEvent(a);}s.breakpointsComputed||(s.breakpointsComputed=true,s.dispatchEvent(new CustomEvent(Sr.BREAKPOINTS_COMPUTED,{bubbles:true,composed:true})));}function JI(s){let e=s.split(/\s+/);return Object.fromEntries(e.map(t=>t.split(":")))}function ex(s,e){return Object.keys(s).filter(t=>e>=parseInt(s[t]))}var Lr=class extends A.HTMLElement{constructor(){if(super(),Qt(this,Tf),Qt(this,Sf),Qt(this,Af),Qt(this,sa),Qt(this,Nd),Qt(this,gn),Qt(this,Od,0),Qt(this,mn,null),Qt(this,ia,null),Qt(this,pn,void 0),this.breakpointsComputed=false,Qt(this,Md,new MutationObserver(di(this,Tf,SE).bind(this))),Qt(this,ta,false),Qt(this,Pd,t=>{Xt(this,ta)||(setTimeout(()=>{ZI(t),xr(this,ta,false);},0),xr(this,ta,true));}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let t=qe(this.attributes),i=this.constructor.getTemplateHTML(t);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(i):this.shadowRoot.innerHTML=i;}let e=this.querySelector(":scope > slot[slot=media]");e&&e.addEventListener("slotchange",()=>{if(!e.assignedElements({flatten:true}).length){Xt(this,mn)&&this.mediaUnsetCallback(Xt(this,mn));return}this.handleMediaUpdated(this.media);});}static get observedAttributes(){return [ue.AUTOHIDE,ue.GESTURES_DISABLED].concat(QI).filter(e=>![b.MEDIA_RENDITION_LIST,b.MEDIA_AUDIO_TRACK_LIST,b.MEDIA_CHAPTERS_CUES,b.MEDIA_WIDTH,b.MEDIA_HEIGHT,b.MEDIA_ERROR,b.MEDIA_ERROR_MESSAGE].includes(e))}attributeChangedCallback(e,t,i){e.toLowerCase()==ue.AUTOHIDE&&(this.autohide=i);}get media(){let e=this.querySelector(":scope > [slot=media]");return e?.nodeName=="SLOT"&&(e=e.assignedElements({flatten:true})[0]),e}async handleMediaUpdated(e){e&&(xr(this,mn,e),e.localName.includes("-")&&await A.customElements.whenDefined(e.localName),this.mediaSetCallback(e));}connectedCallback(){var e;Xt(this,Md).observe(this,{childList:true,subtree:true}),ys(this,Xt(this,Pd));let i=this.getAttribute(ue.AUDIO)!=null?K("audio player"):K("video player");this.setAttribute("role","region"),this.setAttribute("aria-label",i),this.handleMediaUpdated(this.media),this.setAttribute(ue.USER_INACTIVE,""),xE(this,this.getBoundingClientRect().width),this.addEventListener("pointerdown",this),this.addEventListener("pointermove",this),this.addEventListener("pointerup",this),this.addEventListener("mouseleave",this),this.addEventListener("keyup",this),(e=A.window)==null||e.addEventListener("mouseup",this);}disconnectedCallback(){var e;Xt(this,Md).disconnect(),bs(this,Xt(this,Pd)),this.media&&this.mediaUnsetCallback(this.media),(e=A.window)==null||e.removeEventListener("mouseup",this);}mediaSetCallback(e){}mediaUnsetCallback(e){xr(this,mn,null);}handleEvent(e){switch(e.type){case "pointerdown":xr(this,Od,e.timeStamp);break;case "pointermove":di(this,Sf,AE).call(this,e);break;case "pointerup":di(this,Af,IE).call(this,e);break;case "mouseleave":di(this,sa,Ud).call(this);break;case "mouseup":this.removeAttribute(ue.KEYBOARD_CONTROL);break;case "keyup":di(this,gn,ra).call(this),this.setAttribute(ue.KEYBOARD_CONTROL,"");break}}set autohide(e){let t=Number(e);xr(this,pn,isNaN(t)?0:t);}get autohide(){return (Xt(this,pn)===void 0?2:Xt(this,pn)).toString()}get breakpoints(){return me(this,ue.BREAKPOINTS)}set breakpoints(e){pe(this,ue.BREAKPOINTS,e);}get audio(){return ae(this,ue.AUDIO)}set audio(e){le(this,ue.AUDIO,e);}get gesturesDisabled(){return ae(this,ue.GESTURES_DISABLED)}set gesturesDisabled(e){le(this,ue.GESTURES_DISABLED,e);}get keyboardControl(){return ae(this,ue.KEYBOARD_CONTROL)}set keyboardControl(e){le(this,ue.KEYBOARD_CONTROL,e);}get noAutohide(){return ae(this,ue.NO_AUTOHIDE)}set noAutohide(e){le(this,ue.NO_AUTOHIDE,e);}get autohideOverControls(){return ae(this,ue.AUTOHIDE_OVER_CONTROLS)}set autohideOverControls(e){le(this,ue.AUTOHIDE_OVER_CONTROLS,e);}get userInteractive(){return ae(this,ue.USER_INACTIVE)}set userInteractive(e){le(this,ue.USER_INACTIVE,e);}};Od=new WeakMap;mn=new WeakMap;ia=new WeakMap;pn=new WeakMap;Md=new WeakMap;Tf=new WeakSet;SE=function(s){let e=this.media;for(let t of s){if(t.type!=="childList")continue;let i=t.removedNodes;for(let r of i){if(r.slot!="media"||t.target!=this)continue;let n=t.previousSibling&&t.previousSibling.previousElementSibling;if(!n||!e)this.mediaUnsetCallback(r);else {let o=n.slot!=="media";for(;(n=n.previousSibling)!==null;)n.slot=="media"&&(o=false);o&&this.mediaUnsetCallback(r);}}if(e)for(let r of t.addedNodes)r===e&&this.handleMediaUpdated(e);}};ta=new WeakMap;Pd=new WeakMap;Sf=new WeakSet;AE=function(s){if(s.pointerType!=="mouse"&&s.timeStamp-Xt(this,Od)<250)return;di(this,Nd,xf).call(this),clearTimeout(Xt(this,ia));let e=this.hasAttribute(ue.AUTOHIDE_OVER_CONTROLS);([this,this.media].includes(s.target)||e)&&di(this,gn,ra).call(this);};Af=new WeakSet;IE=function(s){if(s.pointerType==="touch"){let e=!this.hasAttribute(ue.USER_INACTIVE);[this,this.media].includes(s.target)&&e?di(this,sa,Ud).call(this):di(this,gn,ra).call(this);}else s.composedPath().some(e=>["media-play-button","media-fullscreen-button"].includes(e?.localName))&&di(this,gn,ra).call(this);};sa=new WeakSet;Ud=function(){if(Xt(this,pn)<0||this.hasAttribute(ue.USER_INACTIVE))return;this.setAttribute(ue.USER_INACTIVE,"");let s=new A.CustomEvent(Sr.USER_INACTIVE_CHANGE,{composed:true,bubbles:true,detail:true});this.dispatchEvent(s);};Nd=new WeakSet;xf=function(){if(!this.hasAttribute(ue.USER_INACTIVE))return;this.removeAttribute(ue.USER_INACTIVE);let s=new A.CustomEvent(Sr.USER_INACTIVE_CHANGE,{composed:true,bubbles:true,detail:false});this.dispatchEvent(s);};gn=new WeakSet;ra=function(){di(this,Nd,xf).call(this),clearTimeout(Xt(this,ia));let s=parseInt(this.autohide);s<0||xr(this,ia,setTimeout(()=>{di(this,sa,Ud).call(this);},s*1e3));};Lr.shadowRootOptions={mode:"open"};Lr.getTemplateHTML=zI;A.customElements.get("media-container")||A.customElements.define("media-container",Lr);var LE=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},bt=(s,e,t)=>(LE(s,e,"read from private field"),t?t.call(s):e.get(s)),na=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Fd=(s,e,t,i)=>(LE(s,e,"write to private field"),e.set(s,t),t),vn,En,$d,Rr,_s,Hs,Gs=class{constructor(e,t,{defaultValue:i}={defaultValue:void 0}){na(this,_s),na(this,vn,void 0),na(this,En,void 0),na(this,$d,void 0),na(this,Rr,new Set),Fd(this,vn,e),Fd(this,En,t),Fd(this,$d,new Set(i));}[Symbol.iterator](){return bt(this,_s,Hs).values()}get length(){return bt(this,_s,Hs).size}get value(){var e;return (e=[...bt(this,_s,Hs)].join(" "))!=null?e:""}set value(e){var t;e!==this.value&&(Fd(this,Rr,new Set),this.add(...(t=e?.split(" "))!=null?t:[]));}toString(){return this.value}item(e){return [...bt(this,_s,Hs)][e]}values(){return bt(this,_s,Hs).values()}forEach(e,t){bt(this,_s,Hs).forEach(e,t);}add(...e){var t,i;e.forEach(r=>bt(this,Rr).add(r)),!(this.value===""&&!((t=bt(this,vn))!=null&&t.hasAttribute(`${bt(this,En)}`)))&&((i=bt(this,vn))==null||i.setAttribute(`${bt(this,En)}`,`${this.value}`));}remove(...e){var t;e.forEach(i=>bt(this,Rr).delete(i)),(t=bt(this,vn))==null||t.setAttribute(`${bt(this,En)}`,`${this.value}`);}contains(e){return bt(this,_s,Hs).has(e)}toggle(e,t){return typeof t<"u"?t?(this.add(e),true):(this.remove(e),false):this.contains(e)?(this.remove(e),false):(this.add(e),true)}replace(e,t){return this.remove(e),this.add(t),e===t}};vn=new WeakMap;En=new WeakMap;$d=new WeakMap;Rr=new WeakMap;_s=new WeakSet;Hs=function(){return bt(this,Rr).size?bt(this,Rr):bt(this,$d)};var tx=(s="")=>s.split(/\s+/),RE=(s="")=>{let[e,t,i]=s.split(":"),r=i?decodeURIComponent(i):void 0;return {kind:e==="cc"?Bt.CAPTIONS:Bt.SUBTITLES,language:t,label:r}},kr=(s="",e={})=>tx(s).map(t=>{let i=RE(t);return {...e,...i}}),Lf=s=>s?Array.isArray(s)?s.map(e=>typeof e=="string"?RE(e):e):typeof s=="string"?kr(s):[s]:[],Bd=({kind:s,label:e,language:t}={kind:"subtitles"})=>e?`${s==="captions"?"cc":"sb"}:${t}:${encodeURIComponent(e)}`:t,Ts=(s=[])=>Array.prototype.map.call(s,Bd).join(" "),ix=(s,e)=>t=>t[s]===e,kE=s=>{let e=Object.entries(s).map(([t,i])=>ix(t,i));return t=>e.every(i=>i(t))},wr=(s,e=[],t=[])=>{let i=Lf(t).map(kE),r=n=>i.some(o=>o(n));Array.from(e).filter(r).forEach(n=>{n.mode=s;});},Cr=(s,e=()=>true)=>{if(!s?.textTracks)return [];let t=typeof e=="function"?e:kE(e);return Array.from(s.textTracks).filter(t)},Hd=s=>{var e;return !!((e=s.mediaSubtitlesShowing)!=null&&e.length)||s.hasAttribute(b.MEDIA_SUBTITLES_SHOWING)};var CE=s=>{var e;let{media:t,fullscreenElement:i}=s;try{let r=i&&"requestFullscreen"in i?"requestFullscreen":i&&"webkitRequestFullScreen"in i?"webkitRequestFullScreen":void 0;if(r){let n=(e=i[r])==null?void 0:e.call(i);if(n instanceof Promise)return n.catch(()=>{})}else t?.webkitEnterFullscreen?t.webkitEnterFullscreen():t?.requestFullscreen&&t.requestFullscreen();}catch(r){console.error(r);}},wE="exitFullscreen"in je?"exitFullscreen":"webkitExitFullscreen"in je?"webkitExitFullscreen":"webkitCancelFullScreen"in je?"webkitCancelFullScreen":void 0,DE=s=>{var e;let{documentElement:t}=s;if(wE){let i=(e=t?.[wE])==null?void 0:e.call(t);if(i instanceof Promise)return i.catch(()=>{})}},oa="fullscreenElement"in je?"fullscreenElement":"webkitFullscreenElement"in je?"webkitFullscreenElement":void 0,sx=s=>{let{documentElement:e,media:t}=s,i=e?.[oa];return !i&&"webkitDisplayingFullscreen"in t&&"webkitPresentationMode"in t&&t.webkitDisplayingFullscreen&&t.webkitPresentationMode===aE.FULLSCREEN?t:i},ME=s=>{var e;let{media:t,documentElement:i,fullscreenElement:r=t}=s;if(!t||!i)return false;let n=sx(s);if(!n)return false;if(n===r||n===t)return true;if(n.localName.includes("-")){let o=n.shadowRoot;if(!(oa in o))return Nt(n,r);for(;o?.[oa];){if(o[oa]===r)return true;o=(e=o[oa])==null?void 0:e.shadowRoot;}}return false},rx="fullscreenEnabled"in je?"fullscreenEnabled":"webkitFullscreenEnabled"in je?"webkitFullscreenEnabled":void 0,PE=s=>{let{documentElement:e,media:t}=s;return !!e?.[rx]||t&&"webkitSupportsFullscreen"in t};var Gd,Rf=()=>{var s,e;return Gd||(Gd=(e=(s=je)==null?void 0:s.createElement)==null?void 0:e.call(s,"video"),Gd)},OE=async(s=Rf())=>{if(!s)return false;let e=s.volume;s.volume=e/2+.1;let t=new AbortController,i=await Promise.race([nx(s,t.signal),ox(s,e)]);return t.abort(),i},nx=(s,e)=>new Promise(t=>{s.addEventListener("volumechange",()=>t(true),{signal:e});}),ox=async(s,e)=>{for(let t=0;t<10;t++){if(s.volume===e)return false;await Sd(10);}return s.volume!==e},ax=/.*Version\/.*Safari\/.*/.test(A.navigator.userAgent),kf=(s=Rf())=>A.matchMedia("(display-mode: standalone)").matches&&ax?false:typeof s?.requestPictureInPicture=="function",wf=(s=Rf())=>PE({documentElement:je,media:s}),UE=wf(),NE=kf(),FE=!!A.WebKitPlaybackTargetAvailabilityEvent,$E=!!A.chrome;var yn=s=>Cr(s.media,e=>[Bt.SUBTITLES,Bt.CAPTIONS].includes(e.kind)).sort((e,t)=>e.kind>=t.kind?1:-1),Cf=s=>Cr(s.media,e=>e.mode===$s.SHOWING&&[Bt.SUBTITLES,Bt.CAPTIONS].includes(e.kind)),Kd=(s,e)=>{let t=yn(s),i=Cf(s),r=!!i.length;if(t.length){if(e===false||r&&e!==true)wr($s.DISABLED,t,i);else if(e===true||!r&&e!==false){let n=t[0],{options:o}=s;if(!o?.noSubtitlesLangPref){let c=globalThis.localStorage.getItem("media-chrome-pref-subtitles-lang"),u=c?[c,...globalThis.navigator.languages]:globalThis.navigator.languages,h=t.filter(f=>u.some(m=>f.language.toLowerCase().startsWith(m.split("-")[0]))).sort((f,m)=>{let p=u.findIndex(E=>f.language.toLowerCase().startsWith(E.split("-")[0])),g=u.findIndex(E=>m.language.toLowerCase().startsWith(E.split("-")[0]));return p-g});h[0]&&(n=h[0]);}let{language:a,label:l,kind:d}=n;wr($s.DISABLED,t,i),wr($s.SHOWING,t,[{language:a,label:l,kind:d}]);}}},Vd=(s,e)=>s===e?true:s==null||e==null||typeof s!=typeof e?false:typeof s=="number"&&Number.isNaN(s)&&Number.isNaN(e)?true:typeof s!="object"?false:Array.isArray(s)?lx(s,e):Object.entries(s).every(([t,i])=>t in e&&Vd(i,e[t])),lx=(s,e)=>{let t=Array.isArray(s),i=Array.isArray(e);return t!==i?false:t||i?s.length!==e.length?false:s.every((r,n)=>Vd(r,e[n])):true};var dx=Object.values(yi),Wd,cx=OE().then(s=>(Wd=s,Wd)),BE=async(...s)=>{await Promise.all(s.filter(e=>e).map(async e=>{if(!("localName"in e&&e instanceof A.HTMLElement))return;let t=e.localName;if(!t.includes("-"))return;let i=A.customElements.get(t);i&&e instanceof i||(await A.customElements.whenDefined(t),A.customElements.upgrade(e));}));},ux=new A.DOMParser,hx=s=>s&&(ux.parseFromString(s,"text/html").body.textContent||s),bn={mediaError:{get(s,e){let{media:t}=s;if(e?.type!=="playing")return t?.error},mediaEvents:["emptied","error","playing"]},mediaErrorCode:{get(s,e){var t;let{media:i}=s;if(e?.type!=="playing")return (t=i?.error)==null?void 0:t.code},mediaEvents:["emptied","error","playing"]},mediaErrorMessage:{get(s,e){var t,i;let{media:r}=s;if(e?.type!=="playing")return (i=(t=r?.error)==null?void 0:t.message)!=null?i:""},mediaEvents:["emptied","error","playing"]},mediaWidth:{get(s){var e;let{media:t}=s;return (e=t?.videoWidth)!=null?e:0},mediaEvents:["resize"]},mediaHeight:{get(s){var e;let{media:t}=s;return (e=t?.videoHeight)!=null?e:0},mediaEvents:["resize"]},mediaPaused:{get(s){var e;let{media:t}=s;return (e=t?.paused)!=null?e:true},set(s,e){var t;let{media:i}=e;i&&(s?i.pause():(t=i.play())==null||t.catch(()=>{}));},mediaEvents:["play","playing","pause","emptied"]},mediaHasPlayed:{get(s,e){let{media:t}=s;return t?e?e.type==="playing":!t.paused:false},mediaEvents:["playing","emptied"]},mediaEnded:{get(s){var e;let{media:t}=s;return (e=t?.ended)!=null?e:false},mediaEvents:["seeked","ended","emptied"]},mediaPlaybackRate:{get(s){var e;let{media:t}=s;return (e=t?.playbackRate)!=null?e:1},set(s,e){let{media:t}=e;t&&Number.isFinite(+s)&&(t.playbackRate=+s);},mediaEvents:["ratechange","loadstart"]},mediaMuted:{get(s){var e;let{media:t}=s;return (e=t?.muted)!=null?e:false},set(s,e){let{media:t,options:{noMutedPref:i}={}}=e;if(t){t.muted=s;try{let r=A.localStorage.getItem("media-chrome-pref-muted")!==null,n=t.hasAttribute("muted");if(i){r&&A.localStorage.removeItem("media-chrome-pref-muted");return}if(n&&!r)return;A.localStorage.setItem("media-chrome-pref-muted",s?"true":"false");}catch(r){console.debug("Error setting muted pref",r);}}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(s,e)=>{let{options:{noMutedPref:t}}=e,{media:i}=e;if(!(!i||i.muted||t))try{let r=A.localStorage.getItem("media-chrome-pref-muted")==="true";bn.mediaMuted.set(r,e),s(r);}catch(r){console.debug("Error getting muted pref",r);}}]},mediaLoop:{get(s){let{media:e}=s;return e?.loop},set(s,e){let{media:t}=e;t&&(t.loop=s);},mediaEvents:["medialooprequest"]},mediaVolume:{get(s){var e;let{media:t}=s;return (e=t?.volume)!=null?e:1},set(s,e){let{media:t,options:{noVolumePref:i}={}}=e;if(t){try{s==null?A.localStorage.removeItem("media-chrome-pref-volume"):!t.hasAttribute("muted")&&!i&&A.localStorage.setItem("media-chrome-pref-volume",s.toString());}catch(r){console.debug("Error setting volume pref",r);}Number.isFinite(+s)&&(t.volume=+s);}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(s,e)=>{let{options:{noVolumePref:t}}=e;if(!t)try{let{media:i}=e;if(!i)return;let r=A.localStorage.getItem("media-chrome-pref-volume");if(r==null)return;bn.mediaVolume.set(+r,e),s(+r);}catch(i){console.debug("Error getting volume pref",i);}}]},mediaVolumeLevel:{get(s){let{media:e}=s;return typeof e?.volume>"u"?"high":e.muted||e.volume===0?"off":e.volume<.5?"low":e.volume<.75?"medium":"high"},mediaEvents:["volumechange"]},mediaCurrentTime:{get(s){var e;let{media:t}=s;return (e=t?.currentTime)!=null?e:0},set(s,e){let{media:t}=e;!t||!hn(s)||(t.currentTime=s);},mediaEvents:["timeupdate","loadedmetadata"]},mediaDuration:{get(s){let{media:e,options:{defaultDuration:t}={}}=s;return t&&(!e||!e.duration||Number.isNaN(e.duration)||!Number.isFinite(e.duration))?t:Number.isFinite(e?.duration)?e.duration:Number.NaN},mediaEvents:["durationchange","loadedmetadata","emptied"]},mediaLoading:{get(s){let{media:e}=s;return e?.readyState<3},mediaEvents:["waiting","playing","emptied"]},mediaSeekable:{get(s){var e;let{media:t}=s;if(!((e=t?.seekable)!=null&&e.length))return;let i=t.seekable.start(0),r=t.seekable.end(t.seekable.length-1);if(!(!i&&!r))return [Number(i.toFixed(3)),Number(r.toFixed(3))]},mediaEvents:["loadedmetadata","emptied","progress","seekablechange"]},mediaBuffered:{get(s){var e;let{media:t}=s,i=(e=t?.buffered)!=null?e:[];return Array.from(i).map((r,n)=>[Number(i.start(n).toFixed(3)),Number(i.end(n).toFixed(3))])},mediaEvents:["progress","emptied"]},mediaStreamType:{get(s){let{media:e,options:{defaultStreamType:t}={}}=s,i=[yi.LIVE,yi.ON_DEMAND].includes(t)?t:void 0;if(!e)return i;let{streamType:r}=e;if(dx.includes(r))return r===yi.UNKNOWN?i:r;let n=e.duration;return n===1/0?yi.LIVE:Number.isFinite(n)?yi.ON_DEMAND:i},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange"]},mediaTargetLiveWindow:{get(s){let{media:e}=s;if(!e)return Number.NaN;let{targetLiveWindow:t}=e,i=bn.mediaStreamType.get(s);return (t==null||Number.isNaN(t))&&i===yi.LIVE?0:t},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange","targetlivewindowchange"]},mediaTimeIsLive:{get(s){let{media:e,options:{liveEdgeOffset:t=10}={}}=s;if(!e)return false;if(typeof e.liveEdgeStart=="number")return Number.isNaN(e.liveEdgeStart)?false:e.currentTime>=e.liveEdgeStart;if(!(bn.mediaStreamType.get(s)===yi.LIVE))return false;let r=e.seekable;if(!r)return true;if(!r.length)return false;let n=r.end(r.length-1)-t;return e.currentTime>=n},mediaEvents:["playing","timeupdate","progress","waiting","emptied"]},mediaSubtitlesList:{get(s){return yn(s).map(({kind:e,label:t,language:i})=>({kind:e,label:t,language:i}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack"]},mediaSubtitlesShowing:{get(s){return Cf(s).map(({kind:e,label:t,language:i})=>({kind:e,label:t,language:i}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(s,e)=>{var t,i;let{media:r,options:n}=e;if(!r)return;let o=a=>{var l;!n.defaultSubtitles||a&&![Bt.CAPTIONS,Bt.SUBTITLES].includes((l=a?.track)==null?void 0:l.kind)||Kd(e,true);};return r.addEventListener("loadstart",o),(t=r.textTracks)==null||t.addEventListener("addtrack",o),(i=r.textTracks)==null||i.addEventListener("removetrack",o),()=>{var a,l;r.removeEventListener("loadstart",o),(a=r.textTracks)==null||a.removeEventListener("addtrack",o),(l=r.textTracks)==null||l.removeEventListener("removetrack",o);}}]},mediaChaptersCues:{get(s){var e;let{media:t}=s;if(!t)return [];let[i]=Cr(t,{kind:Bt.CHAPTERS});return Array.from((e=i?.cues)!=null?e:[]).map(({text:r,startTime:n,endTime:o})=>({text:hx(r),startTime:n,endTime:o}))},mediaEvents:["loadstart","loadedmetadata"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(s,e)=>{var t;let{media:i}=e;if(!i)return;let r=i.querySelector('track[kind="chapters"][default][src]'),n=(t=i.shadowRoot)==null?void 0:t.querySelector(':is(video,audio) > track[kind="chapters"][default][src]');return r?.addEventListener("load",s),n?.addEventListener("load",s),()=>{r?.removeEventListener("load",s),n?.removeEventListener("load",s);}}]},mediaIsPip:{get(s){var e,t;let{media:i,documentElement:r}=s;if(!i||!r||!r.pictureInPictureElement)return false;if(r.pictureInPictureElement===i)return true;if(r.pictureInPictureElement instanceof HTMLMediaElement)return (e=i.localName)!=null&&e.includes("-")?Nt(i,r.pictureInPictureElement):false;if(r.pictureInPictureElement.localName.includes("-")){let n=r.pictureInPictureElement.shadowRoot;for(;n?.pictureInPictureElement;){if(n.pictureInPictureElement===i)return true;n=(t=n.pictureInPictureElement)==null?void 0:t.shadowRoot;}}return false},set(s,e){let{media:t}=e;if(t)if(s){if(!je.pictureInPictureEnabled){console.warn("MediaChrome: Picture-in-picture is not enabled");return}if(!t.requestPictureInPicture){console.warn("MediaChrome: The current media does not support picture-in-picture");return}let i=()=>{console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a readyState > 0.");};t.requestPictureInPicture().catch(r=>{if(r.code===11){if(!t.src){console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a src set.");return}if(t.readyState===0&&t.preload==="none"){let n=()=>{t.removeEventListener("loadedmetadata",o),t.preload="none";},o=()=>{t.requestPictureInPicture().catch(i),n();};t.addEventListener("loadedmetadata",o),t.preload="metadata",setTimeout(()=>{t.readyState===0&&i(),n();},1e3);}else throw r}else throw r});}else je.pictureInPictureElement&&je.exitPictureInPicture();},mediaEvents:["enterpictureinpicture","leavepictureinpicture"]},mediaRenditionList:{get(s){var e;let{media:t}=s;return [...(e=t?.videoRenditions)!=null?e:[]].map(i=>({...i}))},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaRenditionSelected:{get(s){var e,t,i;let{media:r}=s;return (i=(t=r?.videoRenditions)==null?void 0:t[(e=r.videoRenditions)==null?void 0:e.selectedIndex])==null?void 0:i.id},set(s,e){let{media:t}=e;if(!t?.videoRenditions){console.warn("MediaController: Rendition selection not supported by this media.");return}let i=s,r=Array.prototype.findIndex.call(t.videoRenditions,n=>n.id==i);t.videoRenditions.selectedIndex!=r&&(t.videoRenditions.selectedIndex=r);},mediaEvents:["emptied"],videoRenditionsEvents:["addrendition","removerendition","change"]},mediaAudioTrackList:{get(s){var e;let{media:t}=s;return [...(e=t?.audioTracks)!=null?e:[]]},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaAudioTrackEnabled:{get(s){var e,t;let{media:i}=s;return (t=[...(e=i?.audioTracks)!=null?e:[]].find(r=>r.enabled))==null?void 0:t.id},set(s,e){let{media:t}=e;if(!t?.audioTracks){console.warn("MediaChrome: Audio track selection not supported by this media.");return}let i=s;for(let r of t.audioTracks)r.enabled=i==r.id;},mediaEvents:["emptied"],audioTracksEvents:["addtrack","removetrack","change"]},mediaIsFullscreen:{get(s){return ME(s)},set(s,e,t){var i;s?(CE(e),t.detail&&((i=e.media)==null||i.focus())):DE(e);},rootEvents:["fullscreenchange","webkitfullscreenchange"],mediaEvents:["webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"]},mediaIsCasting:{get(s){var e;let{media:t}=s;return !t?.remote||((e=t.remote)==null?void 0:e.state)==="disconnected"?false:!!t.remote.state},set(s,e){var t,i;let{media:r}=e;if(r&&!(s&&((t=r.remote)==null?void 0:t.state)!=="disconnected")&&!(!s&&((i=r.remote)==null?void 0:i.state)!=="connected")){if(typeof r.remote.prompt!="function"){console.warn("MediaChrome: Casting is not supported in this environment");return}r.remote.prompt().catch(()=>{});}},remoteEvents:["connect","connecting","disconnect"]},mediaIsAirplaying:{get(){return false},set(s,e){let{media:t}=e;if(t){if(!(t.webkitShowPlaybackTargetPicker&&A.WebKitPlaybackTargetAvailabilityEvent)){console.error("MediaChrome: received a request to select AirPlay but AirPlay is not supported in this environment");return}t.webkitShowPlaybackTargetPicker();}},mediaEvents:["webkitcurrentplaybacktargetiswirelesschanged"]},mediaFullscreenUnavailable:{get(s){let{media:e}=s;if(!UE||!wf(e))return Ht.UNSUPPORTED}},mediaPipUnavailable:{get(s){let{media:e}=s;if(!NE||!kf(e))return Ht.UNSUPPORTED;if(e?.disablePictureInPicture)return Ht.UNAVAILABLE}},mediaVolumeUnavailable:{get(s){let{media:e}=s;if(Wd===false||e?.volume==null)return Ht.UNSUPPORTED},stateOwnersUpdateHandlers:[s=>{Wd==null&&cx.then(e=>s(e?void 0:Ht.UNSUPPORTED));}]},mediaCastUnavailable:{get(s,{availability:e="not-available"}={}){var t;let{media:i}=s;if(!$E||!((t=i?.remote)!=null&&t.state))return Ht.UNSUPPORTED;if(!(e==null||e==="available"))return Ht.UNAVAILABLE},stateOwnersUpdateHandlers:[(s,e)=>{var t;let{media:i}=e;return i?(i.disableRemotePlayback||i.hasAttribute("disableremoteplayback")||(t=i?.remote)==null||t.watchAvailability(n=>{s({availability:n?"available":"not-available"});}).catch(n=>{n.name==="NotSupportedError"?s({availability:null}):s({availability:"not-available"});}),()=>{var n;(n=i?.remote)==null||n.cancelWatchAvailability().catch(()=>{});}):void 0}]},mediaAirplayUnavailable:{get(s,e){if(!FE)return Ht.UNSUPPORTED;if(e?.availability==="not-available")return Ht.UNAVAILABLE},mediaEvents:["webkitplaybacktargetavailabilitychanged"],stateOwnersUpdateHandlers:[(s,e)=>{var t;let{media:i}=e;return i?(i.disableRemotePlayback||i.hasAttribute("disableremoteplayback")||(t=i?.remote)==null||t.watchAvailability(n=>{s({availability:n?"available":"not-available"});}).catch(n=>{n.name==="NotSupportedError"?s({availability:null}):s({availability:"not-available"});}),()=>{var n;(n=i?.remote)==null||n.cancelWatchAvailability().catch(()=>{});}):void 0}]},mediaRenditionUnavailable:{get(s){var e;let{media:t}=s;if(!t?.videoRenditions)return Ht.UNSUPPORTED;if(!((e=t.videoRenditions)!=null&&e.length))return Ht.UNAVAILABLE},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaAudioTrackUnavailable:{get(s){var e,t;let{media:i}=s;if(!i?.audioTracks)return Ht.UNSUPPORTED;if(((t=(e=i.audioTracks)==null?void 0:e.length)!=null?t:0)<=1)return Ht.UNAVAILABLE},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaLang:{get(s){let{options:{mediaLang:e}={}}=s;return e??"en"}}};var HE={[V.MEDIA_PREVIEW_REQUEST](s,e,{detail:t}){var i,r,n;let{media:o}=e,a=t??void 0,l,d;if(o&&a!=null){let[f]=Cr(o,{kind:Bt.METADATA,label:"thumbnails"}),m=Array.prototype.find.call((i=f?.cues)!=null?i:[],(p,g,E)=>g===0?p.endTime>a:g===E.length-1?p.startTime<=a:p.startTime<=a&&p.endTime>a);if(m){let p=/'^(?:[a-z]+:)?\/\//i.test(m.text)||(r=o?.querySelector('track[label="thumbnails"]'))==null?void 0:r.src,g=new URL(m.text,p);d=new URLSearchParams(g.hash).get("#xywh").split(",").map(y=>+y),l=g.href;}}let c=s.mediaDuration.get(e),h=(n=s.mediaChaptersCues.get(e).find((f,m,p)=>m===p.length-1&&c===f.endTime?f.startTime<=a&&f.endTime>=a:f.startTime<=a&&f.endTime>a))==null?void 0:n.text;return t!=null&&h==null&&(h=""),{mediaPreviewTime:a,mediaPreviewImage:l,mediaPreviewCoords:d,mediaPreviewChapter:h}},[V.MEDIA_PAUSE_REQUEST](s,e){s["mediaPaused"].set(true,e);},[V.MEDIA_PLAY_REQUEST](s,e){var t,i,r,n;let o="mediaPaused",l=s.mediaStreamType.get(e)===yi.LIVE,d=!((t=e.options)!=null&&t.noAutoSeekToLive),c=s.mediaTargetLiveWindow.get(e)>0;if(l&&d&&!c){let u=(i=s.mediaSeekable.get(e))==null?void 0:i[1];if(u){let h=(n=(r=e.options)==null?void 0:r.seekToLiveOffset)!=null?n:0,f=u-h;s.mediaCurrentTime.set(f,e);}}s[o].set(false,e);},[V.MEDIA_PLAYBACK_RATE_REQUEST](s,e,{detail:t}){let i="mediaPlaybackRate",r=t;s[i].set(r,e);},[V.MEDIA_MUTE_REQUEST](s,e){s["mediaMuted"].set(true,e);},[V.MEDIA_UNMUTE_REQUEST](s,e){let t="mediaMuted";s.mediaVolume.get(e)||s.mediaVolume.set(.25,e),s[t].set(false,e);},[V.MEDIA_LOOP_REQUEST](s,e,{detail:t}){let i="mediaLoop",r=!!t;return s[i].set(r,e),{mediaLoop:r}},[V.MEDIA_VOLUME_REQUEST](s,e,{detail:t}){let i="mediaVolume",r=t;r&&s.mediaMuted.get(e)&&s.mediaMuted.set(false,e),s[i].set(r,e);},[V.MEDIA_SEEK_REQUEST](s,e,{detail:t}){let i="mediaCurrentTime",r=t;s[i].set(r,e);},[V.MEDIA_SEEK_TO_LIVE_REQUEST](s,e){var t,i,r;let n="mediaCurrentTime",o=(t=s.mediaSeekable.get(e))==null?void 0:t[1];if(Number.isNaN(Number(o)))return;let a=(r=(i=e.options)==null?void 0:i.seekToLiveOffset)!=null?r:0,l=o-a;s[n].set(l,e);},[V.MEDIA_SHOW_SUBTITLES_REQUEST](s,e,{detail:t}){var i;let{options:r}=e,n=yn(e),o=Lf(t),a=(i=o[0])==null?void 0:i.language;a&&!r.noSubtitlesLangPref&&A.localStorage.setItem("media-chrome-pref-subtitles-lang",a),wr($s.SHOWING,n,o);},[V.MEDIA_DISABLE_SUBTITLES_REQUEST](s,e,{detail:t}){let i=yn(e),r=t??[];wr($s.DISABLED,i,r);},[V.MEDIA_TOGGLE_SUBTITLES_REQUEST](s,e,{detail:t}){Kd(e,t);},[V.MEDIA_RENDITION_REQUEST](s,e,{detail:t}){let i="mediaRenditionSelected",r=t;s[i].set(r,e);},[V.MEDIA_AUDIO_TRACK_REQUEST](s,e,{detail:t}){let i="mediaAudioTrackEnabled",r=t;s[i].set(r,e);},[V.MEDIA_ENTER_PIP_REQUEST](s,e){let t="mediaIsPip";s.mediaIsFullscreen.get(e)&&s.mediaIsFullscreen.set(false,e),s[t].set(true,e);},[V.MEDIA_EXIT_PIP_REQUEST](s,e){s["mediaIsPip"].set(false,e);},[V.MEDIA_ENTER_FULLSCREEN_REQUEST](s,e,t){let i="mediaIsFullscreen";s.mediaIsPip.get(e)&&s.mediaIsPip.set(false,e),s[i].set(true,e,t);},[V.MEDIA_EXIT_FULLSCREEN_REQUEST](s,e){s["mediaIsFullscreen"].set(false,e);},[V.MEDIA_ENTER_CAST_REQUEST](s,e){let t="mediaIsCasting";s.mediaIsFullscreen.get(e)&&s.mediaIsFullscreen.set(false,e),s[t].set(true,e);},[V.MEDIA_EXIT_CAST_REQUEST](s,e){s["mediaIsCasting"].set(false,e);},[V.MEDIA_AIRPLAY_REQUEST](s,e){s["mediaIsAirplaying"].set(true,e);}};var GE=({media:s,fullscreenElement:e,documentElement:t,stateMediator:i=bn,requestMap:r=HE,options:n={},monitorStateOwnersOnlyWithSubscriptions:o=true})=>{let a=[],l={options:{...n}},d=Object.freeze({mediaPreviewTime:void 0,mediaPreviewImage:void 0,mediaPreviewCoords:void 0,mediaPreviewChapter:void 0}),c=p=>{p!=null&&(Vd(p,d)||(d=Object.freeze({...d,...p}),a.forEach(g=>g(d))));},u=()=>{let p=Object.entries(i).reduce((g,[E,{get:y}])=>(g[E]=y(l),g),{});c(p);},h={},f,m=async(p,g)=>{var E,y,_,S,L,O,R,D,C,k,H,q,j,X,Y,x;let T=!!f;if(f={...l,...f??{},...p},T)return;await BE(...Object.values(p));let I=a.length>0&&g===0&&o,P=l.media!==f.media,U=((E=l.media)==null?void 0:E.textTracks)!==((y=f.media)==null?void 0:y.textTracks),w=((_=l.media)==null?void 0:_.videoRenditions)!==((S=f.media)==null?void 0:S.videoRenditions),B=((L=l.media)==null?void 0:L.audioTracks)!==((O=f.media)==null?void 0:O.audioTracks),z=((R=l.media)==null?void 0:R.remote)!==((D=f.media)==null?void 0:D.remote),te=l.documentElement!==f.documentElement,se=!!l.media&&(P||I),re=!!((C=l.media)!=null&&C.textTracks)&&(U||I),Ie=!!((k=l.media)!=null&&k.videoRenditions)&&(w||I),dt=!!((H=l.media)!=null&&H.audioTracks)&&(B||I),Pt=!!((q=l.media)!=null&&q.remote)&&(z||I),jt=!!l.documentElement&&(te||I),gi=se||re||Ie||dt||Pt||jt,Ds=a.length===0&&g===1&&o,nn=!!f.media&&(P||Ds),on=!!((j=f.media)!=null&&j.textTracks)&&(U||Ds),jh=!!((X=f.media)!=null&&X.videoRenditions)&&(w||Ds),xe=!!((Y=f.media)!=null&&Y.audioTracks)&&(B||Ds),ft=!!((x=f.media)!=null&&x.remote)&&(z||Ds),Ot=!!f.documentElement&&(te||Ds),Ri=nn||on||jh||xe||ft||Ot;if(!(gi||Ri)){Object.entries(f).forEach(([Le,Yt])=>{l[Le]=Yt;}),u(),f=void 0;return}Object.entries(i).forEach(([Le,{get:Yt,mediaEvents:Kl=[],textTracksEvents:an=[],videoRenditionsEvents:Vl=[],audioTracksEvents:ar=[],remoteEvents:Wl=[],rootEvents:Yh=[],stateOwnersUpdateHandlers:ql=[]}])=>{h[Le]||(h[Le]={});let kt=Qe=>{let ct=Yt(l,Qe);c({[Le]:ct});},ze;ze=h[Le].mediaEvents,Kl.forEach(Qe=>{ze&&se&&(l.media.removeEventListener(Qe,ze),h[Le].mediaEvents=void 0),nn&&(f.media.addEventListener(Qe,kt),h[Le].mediaEvents=kt);}),ze=h[Le].textTracksEvents,an.forEach(Qe=>{var ct,vi;ze&&re&&((ct=l.media.textTracks)==null||ct.removeEventListener(Qe,ze),h[Le].textTracksEvents=void 0),on&&((vi=f.media.textTracks)==null||vi.addEventListener(Qe,kt),h[Le].textTracksEvents=kt);}),ze=h[Le].videoRenditionsEvents,Vl.forEach(Qe=>{var ct,vi;ze&&Ie&&((ct=l.media.videoRenditions)==null||ct.removeEventListener(Qe,ze),h[Le].videoRenditionsEvents=void 0),jh&&((vi=f.media.videoRenditions)==null||vi.addEventListener(Qe,kt),h[Le].videoRenditionsEvents=kt);}),ze=h[Le].audioTracksEvents,ar.forEach(Qe=>{var ct,vi;ze&&dt&&((ct=l.media.audioTracks)==null||ct.removeEventListener(Qe,ze),h[Le].audioTracksEvents=void 0),xe&&((vi=f.media.audioTracks)==null||vi.addEventListener(Qe,kt),h[Le].audioTracksEvents=kt);}),ze=h[Le].remoteEvents,Wl.forEach(Qe=>{var ct,vi;ze&&Pt&&((ct=l.media.remote)==null||ct.removeEventListener(Qe,ze),h[Le].remoteEvents=void 0),ft&&((vi=f.media.remote)==null||vi.addEventListener(Qe,kt),h[Le].remoteEvents=kt);}),ze=h[Le].rootEvents,Yh.forEach(Qe=>{ze&&jt&&(l.documentElement.removeEventListener(Qe,ze),h[Le].rootEvents=void 0),Ot&&(f.documentElement.addEventListener(Qe,kt),h[Le].rootEvents=kt);});let jl=h[Le].stateOwnersUpdateHandlers;if(jl&&gi&&(Array.isArray(jl)?jl:[jl]).forEach(ct=>{typeof ct=="function"&&ct();}),Ri){let Qe=ql.map(ct=>ct(kt,f)).filter(ct=>typeof ct=="function");h[Le].stateOwnersUpdateHandlers=Qe.length===1?Qe[0]:Qe;}else gi&&(h[Le].stateOwnersUpdateHandlers=void 0);}),Object.entries(f).forEach(([Le,Yt])=>{l[Le]=Yt;}),u(),f=void 0;};return m({media:s,fullscreenElement:e,documentElement:t,options:n}),{dispatch(p){let{type:g,detail:E}=p;if(r[g]&&d.mediaErrorCode==null){c(r[g](i,l,p));return}g==="mediaelementchangerequest"?m({media:E}):g==="fullscreenelementchangerequest"?m({fullscreenElement:E}):g==="documentelementchangerequest"?m({documentElement:E}):g==="optionschangerequest"&&(Object.entries(E??{}).forEach(([y,_])=>{l.options[y]=_;}),u());},getState(){return d},subscribe(p){return m({},a.length+1),a.push(p),p(d),()=>{let g=a.indexOf(p);g>=0&&(m({},a.length-1),a.splice(g,1));}}}};var Nf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},de=(s,e,t)=>(Nf(s,e,"read from private field"),t?t.call(s):e.get(s)),ci=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Oi=(s,e,t,i)=>(Nf(s,e,"write to private field"),e.set(s,t),t),Ni=(s,e,t)=>(Nf(s,e,"access private method"),t),Ks,aa,we,Mr,la,Ui,qd,da,jd,Df,Pr,_n,Yd,Mf,Pf,zE,QE=["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Enter"," ","f","m","k","c","l","j",">","<","p"],KE=10,VE=.025,WE=.25,fx=.25,mx=2,W={DEFAULT_SUBTITLES:"defaultsubtitles",DEFAULT_STREAM_TYPE:"defaultstreamtype",DEFAULT_DURATION:"defaultduration",FULLSCREEN_ELEMENT:"fullscreenelement",HOTKEYS:"hotkeys",KEYBOARD_BACKWARD_SEEK_OFFSET:"keyboardbackwardseekoffset",KEYBOARD_FORWARD_SEEK_OFFSET:"keyboardforwardseekoffset",KEYBOARD_DOWN_VOLUME_STEP:"keyboarddownvolumestep",KEYBOARD_UP_VOLUME_STEP:"keyboardupvolumestep",KEYS_USED:"keysused",LANG:"lang",LOOP:"loop",LIVE_EDGE_OFFSET:"liveedgeoffset",NO_AUTO_SEEK_TO_LIVE:"noautoseektolive",NO_DEFAULT_STORE:"nodefaultstore",NO_HOTKEYS:"nohotkeys",NO_MUTED_PREF:"nomutedpref",NO_SUBTITLES_LANG_PREF:"nosubtitleslangpref",NO_VOLUME_PREF:"novolumepref",SEEK_TO_LIVE_OFFSET:"seektoliveoffset"},Of=class extends Lr{constructor(){super(),ci(this,jd),ci(this,Pr),ci(this,Yd),ci(this,Pf),this.mediaStateReceivers=[],this.associatedElementSubscriptions=new Map,ci(this,Ks,new Gs(this,W.HOTKEYS)),ci(this,aa,void 0),ci(this,we,void 0),ci(this,Mr,null),ci(this,la,void 0),ci(this,Ui,void 0),ci(this,qd,t=>{var i;(i=de(this,we))==null||i.dispatch(t);}),ci(this,da,void 0),this.associateElement(this);let e={};Oi(this,la,t=>{Object.entries(t).forEach(([i,r])=>{if(i in e&&e[i]===r)return;this.propagateMediaState(i,r);let n=i.toLowerCase(),o=new A.CustomEvent(oE[n],{composed:true,detail:r});this.dispatchEvent(o);}),e=t;}),this.hasAttribute(W.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys();}static get observedAttributes(){return super.observedAttributes.concat(W.NO_HOTKEYS,W.HOTKEYS,W.DEFAULT_STREAM_TYPE,W.DEFAULT_SUBTITLES,W.DEFAULT_DURATION,W.NO_MUTED_PREF,W.NO_VOLUME_PREF,W.LANG,W.LOOP)}get mediaStore(){return de(this,we)}set mediaStore(e){var t,i;if(de(this,we)&&((t=de(this,Ui))==null||t.call(this),Oi(this,Ui,void 0)),Oi(this,we,e),!de(this,we)&&!this.hasAttribute(W.NO_DEFAULT_STORE)){Ni(this,jd,Df).call(this);return}Oi(this,Ui,(i=de(this,we))==null?void 0:i.subscribe(de(this,la)));}get fullscreenElement(){var e;return (e=de(this,aa))!=null?e:this}set fullscreenElement(e){var t;this.hasAttribute(W.FULLSCREEN_ELEMENT)&&this.removeAttribute(W.FULLSCREEN_ELEMENT),Oi(this,aa,e),(t=de(this,we))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement});}get defaultSubtitles(){return ae(this,W.DEFAULT_SUBTITLES)}set defaultSubtitles(e){le(this,W.DEFAULT_SUBTITLES,e);}get defaultStreamType(){return me(this,W.DEFAULT_STREAM_TYPE)}set defaultStreamType(e){pe(this,W.DEFAULT_STREAM_TYPE,e);}get defaultDuration(){return ye(this,W.DEFAULT_DURATION)}set defaultDuration(e){Ae(this,W.DEFAULT_DURATION,e);}get noHotkeys(){return ae(this,W.NO_HOTKEYS)}set noHotkeys(e){le(this,W.NO_HOTKEYS,e);}get keysUsed(){return me(this,W.KEYS_USED)}set keysUsed(e){pe(this,W.KEYS_USED,e);}get liveEdgeOffset(){return ye(this,W.LIVE_EDGE_OFFSET)}set liveEdgeOffset(e){Ae(this,W.LIVE_EDGE_OFFSET,e);}get noAutoSeekToLive(){return ae(this,W.NO_AUTO_SEEK_TO_LIVE)}set noAutoSeekToLive(e){le(this,W.NO_AUTO_SEEK_TO_LIVE,e);}get noVolumePref(){return ae(this,W.NO_VOLUME_PREF)}set noVolumePref(e){le(this,W.NO_VOLUME_PREF,e);}get noMutedPref(){return ae(this,W.NO_MUTED_PREF)}set noMutedPref(e){le(this,W.NO_MUTED_PREF,e);}get noSubtitlesLangPref(){return ae(this,W.NO_SUBTITLES_LANG_PREF)}set noSubtitlesLangPref(e){le(this,W.NO_SUBTITLES_LANG_PREF,e);}get noDefaultStore(){return ae(this,W.NO_DEFAULT_STORE)}set noDefaultStore(e){le(this,W.NO_DEFAULT_STORE,e);}attributeChangedCallback(e,t,i){var r,n,o,a,l,d,c,u,h,f,m,p;if(super.attributeChangedCallback(e,t,i),e===W.NO_HOTKEYS)i!==t&&i===""?(this.hasAttribute(W.HOTKEYS)&&console.warn("Media Chrome: Both `hotkeys` and `nohotkeys` have been set. All hotkeys will be disabled."),this.disableHotkeys()):i!==t&&i===null&&this.enableHotkeys();else if(e===W.HOTKEYS)de(this,Ks).value=i;else if(e===W.DEFAULT_SUBTITLES&&i!==t)(r=de(this,we))==null||r.dispatch({type:"optionschangerequest",detail:{defaultSubtitles:this.hasAttribute(W.DEFAULT_SUBTITLES)}});else if(e===W.DEFAULT_STREAM_TYPE)(o=de(this,we))==null||o.dispatch({type:"optionschangerequest",detail:{defaultStreamType:(n=this.getAttribute(W.DEFAULT_STREAM_TYPE))!=null?n:void 0}});else if(e===W.LIVE_EDGE_OFFSET)(a=de(this,we))==null||a.dispatch({type:"optionschangerequest",detail:{liveEdgeOffset:this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(W.SEEK_TO_LIVE_OFFSET)?void 0:+this.getAttribute(W.LIVE_EDGE_OFFSET)}});else if(e===W.SEEK_TO_LIVE_OFFSET)(l=de(this,we))==null||l.dispatch({type:"optionschangerequest",detail:{seekToLiveOffset:this.hasAttribute(W.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(W.SEEK_TO_LIVE_OFFSET):void 0}});else if(e===W.NO_AUTO_SEEK_TO_LIVE)(d=de(this,we))==null||d.dispatch({type:"optionschangerequest",detail:{noAutoSeekToLive:this.hasAttribute(W.NO_AUTO_SEEK_TO_LIVE)}});else if(e===W.FULLSCREEN_ELEMENT){let g=i?(c=this.getRootNode())==null?void 0:c.getElementById(i):void 0;Oi(this,aa,g),(u=de(this,we))==null||u.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement});}else e===W.LANG&&i!==t?(pE(i),(h=de(this,we))==null||h.dispatch({type:"optionschangerequest",detail:{mediaLang:i}})):e===W.LOOP&&i!==t?(f=de(this,we))==null||f.dispatch({type:V.MEDIA_LOOP_REQUEST,detail:i!=null}):e===W.NO_VOLUME_PREF&&i!==t?(m=de(this,we))==null||m.dispatch({type:"optionschangerequest",detail:{noVolumePref:this.hasAttribute(W.NO_VOLUME_PREF)}}):e===W.NO_MUTED_PREF&&i!==t&&((p=de(this,we))==null||p.dispatch({type:"optionschangerequest",detail:{noMutedPref:this.hasAttribute(W.NO_MUTED_PREF)}}));}connectedCallback(){var e,t;!de(this,we)&&!this.hasAttribute(W.NO_DEFAULT_STORE)&&Ni(this,jd,Df).call(this),(e=de(this,we))==null||e.dispatch({type:"documentelementchangerequest",detail:je}),super.connectedCallback(),de(this,we)&&!de(this,Ui)&&Oi(this,Ui,(t=de(this,we))==null?void 0:t.subscribe(de(this,la))),de(this,da)!==void 0&&de(this,we)&&this.media&&setTimeout(()=>{var i,r,n;(r=(i=this.media)==null?void 0:i.textTracks)!=null&&r.length&&((n=de(this,we))==null||n.dispatch({type:V.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:de(this,da)}));},0),this.hasAttribute(W.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys();}disconnectedCallback(){var e,t,i,r,n;if((e=super.disconnectedCallback)==null||e.call(this),de(this,we)){let o=de(this,we).getState();Oi(this,da,!!((t=o.mediaSubtitlesShowing)!=null&&t.length)),(i=de(this,we))==null||i.dispatch({type:"documentelementchangerequest",detail:void 0}),(r=de(this,we))==null||r.dispatch({type:V.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:false});}de(this,Ui)&&((n=de(this,Ui))==null||n.call(this),Oi(this,Ui,void 0));}mediaSetCallback(e){var t;super.mediaSetCallback(e),(t=de(this,we))==null||t.dispatch({type:"mediaelementchangerequest",detail:e}),e.hasAttribute("tabindex")||(e.tabIndex=-1);}mediaUnsetCallback(e){var t;super.mediaUnsetCallback(e),(t=de(this,we))==null||t.dispatch({type:"mediaelementchangerequest",detail:void 0});}propagateMediaState(e,t){YE(this.mediaStateReceivers,e,t);}associateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(t.has(e))return;let i=this.registerMediaStateReceiver.bind(this),r=this.unregisterMediaStateReceiver.bind(this),n=bx(e,i,r);Object.values(V).forEach(o=>{e.addEventListener(o,de(this,qd));}),t.set(e,n);}unassociateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(!t.has(e))return;t.get(e)(),t.delete(e),Object.values(V).forEach(r=>{e.removeEventListener(r,de(this,qd));});}registerMediaStateReceiver(e){if(!e)return;let t=this.mediaStateReceivers;t.indexOf(e)>-1||(t.push(e),de(this,we)&&Object.entries(de(this,we).getState()).forEach(([r,n])=>{YE([e],r,n);}));}unregisterMediaStateReceiver(e){let t=this.mediaStateReceivers,i=t.indexOf(e);i<0||t.splice(i,1);}enableHotkeys(){this.addEventListener("keydown",Ni(this,Yd,Mf));}disableHotkeys(){this.removeEventListener("keydown",Ni(this,Yd,Mf)),this.removeEventListener("keyup",Ni(this,Pr,_n));}get hotkeys(){return me(this,W.HOTKEYS)}set hotkeys(e){pe(this,W.HOTKEYS,e);}keyboardShortcutHandler(e){var t,i,r,n,o,a,l,d,c;let u=e.target;if(((r=(i=(t=u.getAttribute(W.KEYS_USED))==null?void 0:t.split(" "))!=null?i:u?.keysUsed)!=null?r:[]).map(E=>E==="Space"?" ":E).filter(Boolean).includes(e.key))return;let f,m,p;if(!(de(this,Ks).contains(`no${e.key.toLowerCase()}`)||e.key===" "&&de(this,Ks).contains("nospace")||e.shiftKey&&(e.key==="/"||e.key==="?")&&de(this,Ks).contains("noshift+/")))switch(e.key){case " ":case "k":f=de(this,we).getState().mediaPaused?V.MEDIA_PLAY_REQUEST:V.MEDIA_PAUSE_REQUEST,this.dispatchEvent(new A.CustomEvent(f,{composed:true,bubbles:true}));break;case "m":f=this.mediaStore.getState().mediaVolumeLevel==="off"?V.MEDIA_UNMUTE_REQUEST:V.MEDIA_MUTE_REQUEST,this.dispatchEvent(new A.CustomEvent(f,{composed:true,bubbles:true}));break;case "f":f=this.mediaStore.getState().mediaIsFullscreen?V.MEDIA_EXIT_FULLSCREEN_REQUEST:V.MEDIA_ENTER_FULLSCREEN_REQUEST,this.dispatchEvent(new A.CustomEvent(f,{composed:true,bubbles:true}));break;case "c":this.dispatchEvent(new A.CustomEvent(V.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:true,bubbles:true}));break;case "ArrowLeft":case "j":{let E=this.hasAttribute(W.KEYBOARD_BACKWARD_SEEK_OFFSET)?+this.getAttribute(W.KEYBOARD_BACKWARD_SEEK_OFFSET):KE;m=Math.max(((n=this.mediaStore.getState().mediaCurrentTime)!=null?n:0)-E,0),p=new A.CustomEvent(V.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:m}),this.dispatchEvent(p);break}case "ArrowRight":case "l":{let E=this.hasAttribute(W.KEYBOARD_FORWARD_SEEK_OFFSET)?+this.getAttribute(W.KEYBOARD_FORWARD_SEEK_OFFSET):KE;m=Math.max(((o=this.mediaStore.getState().mediaCurrentTime)!=null?o:0)+E,0),p=new A.CustomEvent(V.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:m}),this.dispatchEvent(p);break}case "ArrowUp":{let E=this.hasAttribute(W.KEYBOARD_UP_VOLUME_STEP)?+this.getAttribute(W.KEYBOARD_UP_VOLUME_STEP):VE;m=Math.min(((a=this.mediaStore.getState().mediaVolume)!=null?a:1)+E,1),p=new A.CustomEvent(V.MEDIA_VOLUME_REQUEST,{composed:true,bubbles:true,detail:m}),this.dispatchEvent(p);break}case "ArrowDown":{let E=this.hasAttribute(W.KEYBOARD_DOWN_VOLUME_STEP)?+this.getAttribute(W.KEYBOARD_DOWN_VOLUME_STEP):VE;m=Math.max(((l=this.mediaStore.getState().mediaVolume)!=null?l:1)-E,0),p=new A.CustomEvent(V.MEDIA_VOLUME_REQUEST,{composed:true,bubbles:true,detail:m}),this.dispatchEvent(p);break}case "<":{let E=(d=this.mediaStore.getState().mediaPlaybackRate)!=null?d:1;m=Math.max(E-WE,fx).toFixed(2),p=new A.CustomEvent(V.MEDIA_PLAYBACK_RATE_REQUEST,{composed:true,bubbles:true,detail:m}),this.dispatchEvent(p);break}case ">":{let E=(c=this.mediaStore.getState().mediaPlaybackRate)!=null?c:1;m=Math.min(E+WE,mx).toFixed(2),p=new A.CustomEvent(V.MEDIA_PLAYBACK_RATE_REQUEST,{composed:true,bubbles:true,detail:m}),this.dispatchEvent(p);break}case "/":case "?":{e.shiftKey&&Ni(this,Pf,zE).call(this);break}case "p":{f=this.mediaStore.getState().mediaIsPip?V.MEDIA_EXIT_PIP_REQUEST:V.MEDIA_ENTER_PIP_REQUEST,p=new A.CustomEvent(f,{composed:true,bubbles:true}),this.dispatchEvent(p);break}}}};Ks=new WeakMap;aa=new WeakMap;we=new WeakMap;Mr=new WeakMap;la=new WeakMap;Ui=new WeakMap;qd=new WeakMap;da=new WeakMap;jd=new WeakSet;Df=function(){var s;this.mediaStore=GE({media:this.media,fullscreenElement:this.fullscreenElement,options:{defaultSubtitles:this.hasAttribute(W.DEFAULT_SUBTITLES),defaultDuration:this.hasAttribute(W.DEFAULT_DURATION)?+this.getAttribute(W.DEFAULT_DURATION):void 0,defaultStreamType:(s=this.getAttribute(W.DEFAULT_STREAM_TYPE))!=null?s:void 0,liveEdgeOffset:this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(W.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(W.SEEK_TO_LIVE_OFFSET):this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0,noAutoSeekToLive:this.hasAttribute(W.NO_AUTO_SEEK_TO_LIVE),noVolumePref:this.hasAttribute(W.NO_VOLUME_PREF),noMutedPref:this.hasAttribute(W.NO_MUTED_PREF),noSubtitlesLangPref:this.hasAttribute(W.NO_SUBTITLES_LANG_PREF)}});};Pr=new WeakSet;_n=function(s){let{key:e,shiftKey:t}=s;if(!(t&&(e==="/"||e==="?")||QE.includes(e))){this.removeEventListener("keyup",Ni(this,Pr,_n));return}this.keyboardShortcutHandler(s);};Yd=new WeakSet;Mf=function(s){var e;let{metaKey:t,altKey:i,key:r,shiftKey:n}=s,o=n&&(r==="/"||r==="?");if(o&&((e=de(this,Mr))!=null&&e.open)){this.removeEventListener("keyup",Ni(this,Pr,_n));return}if(t||i||!o&&!QE.includes(r)){this.removeEventListener("keyup",Ni(this,Pr,_n));return}let a=s.target,l=a instanceof HTMLElement&&(a.tagName.toLowerCase()==="media-volume-range"||a.tagName.toLowerCase()==="media-time-range");[" ","ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(r)&&!(de(this,Ks).contains(`no${r.toLowerCase()}`)||r===" "&&de(this,Ks).contains("nospace"))&&!l&&s.preventDefault(),this.addEventListener("keyup",Ni(this,Pr,_n),{once:true});};Pf=new WeakSet;zE=function(){de(this,Mr)||(Oi(this,Mr,je.createElement("media-keyboard-shortcuts-dialog")),this.appendChild(de(this,Mr))),de(this,Mr).open=true;};var px=Object.values(b),gx=Object.values(vf),XE=s=>{var e,t,i,r;let{observedAttributes:n}=s.constructor;!n&&((e=s.nodeName)!=null&&e.includes("-"))&&(A.customElements.upgrade(s),{observedAttributes:n}=s.constructor);let o=(r=(i=(t=s?.getAttribute)==null?void 0:t.call(s,ve.MEDIA_CHROME_ATTRIBUTES))==null?void 0:i.split)==null?void 0:r.call(i,/\s+/);return Array.isArray(n||o)?(n||o).filter(a=>px.includes(a)):[]},vx=s=>{var e,t;return (e=s.nodeName)!=null&&e.includes("-")&&A.customElements.get((t=s.nodeName)==null?void 0:t.toLowerCase())&&!(s instanceof A.customElements.get(s.nodeName.toLowerCase()))&&A.customElements.upgrade(s),gx.some(i=>i in s)},Uf=s=>vx(s)||!!XE(s).length,qE=s=>{var e;return (e=s?.join)==null?void 0:e.call(s,":")},jE={[b.MEDIA_SUBTITLES_LIST]:Ts,[b.MEDIA_SUBTITLES_SHOWING]:Ts,[b.MEDIA_SEEKABLE]:qE,[b.MEDIA_BUFFERED]:s=>s?.map(qE).join(" "),[b.MEDIA_PREVIEW_COORDS]:s=>s?.join(" "),[b.MEDIA_RENDITION_LIST]:lE,[b.MEDIA_AUDIO_TRACK_LIST]:cE},Ex=async(s,e,t)=>{var i,r;if(s.isConnected||await Sd(0),typeof t=="boolean"||t==null)return le(s,e,t);if(typeof t=="number")return Ae(s,e,t);if(typeof t=="string")return pe(s,e,t);if(Array.isArray(t)&&!t.length)return s.removeAttribute(e);let n=(r=(i=jE[e])==null?void 0:i.call(jE,t))!=null?r:t;return s.setAttribute(e,n)},yx=s=>{var e;return !!((e=s.closest)!=null&&e.call(s,'*[slot="media"]'))},Dr=(s,e)=>{if(yx(s))return;let t=(r,n)=>{var o,a;Uf(r)&&n(r);let{children:l=[]}=r??{},d=(a=(o=r?.shadowRoot)==null?void 0:o.children)!=null?a:[];[...l,...d].forEach(u=>Dr(u,n));},i=s?.nodeName.toLowerCase();if(i.includes("-")&&!Uf(s)){A.customElements.whenDefined(i).then(()=>{t(s,e);});return}t(s,e);},YE=(s,e,t)=>{s.forEach(i=>{if(e in i){i[e]=t;return}let r=XE(i),n=e.toLowerCase();r.includes(n)&&Ex(i,n,t);});},bx=(s,e,t)=>{Dr(s,e);let i=c=>{var u;let h=(u=c?.composedPath()[0])!=null?u:c.target;e(h);},r=c=>{var u;let h=(u=c?.composedPath()[0])!=null?u:c.target;t(h);};s.addEventListener(V.REGISTER_MEDIA_STATE_RECEIVER,i),s.addEventListener(V.UNREGISTER_MEDIA_STATE_RECEIVER,r);let n=c=>{c.forEach(u=>{let{addedNodes:h=[],removedNodes:f=[],type:m,target:p,attributeName:g}=u;m==="childList"?(Array.prototype.forEach.call(h,E=>Dr(E,e)),Array.prototype.forEach.call(f,E=>Dr(E,t))):m==="attributes"&&g===ve.MEDIA_CHROME_ATTRIBUTES&&(Uf(p)?e(p):t(p));});},o=[],a=c=>{let u=c.target;u.name!=="media"&&(o.forEach(h=>Dr(h,t)),o=[...u.assignedElements({flatten:true})],o.forEach(h=>Dr(h,e)));};s.addEventListener("slotchange",a);let l=new MutationObserver(n);return l.observe(s,{childList:true,attributes:true,subtree:true}),()=>{Dr(s,t),s.removeEventListener("slotchange",a),l.disconnect(),s.removeEventListener(V.REGISTER_MEDIA_STATE_RECEIVER,i),s.removeEventListener(V.UNREGISTER_MEDIA_STATE_RECEIVER,r);}};A.customElements.get("media-controller")||A.customElements.define("media-controller",Of);var Tn={PLACEMENT:"placement",BOUNDS:"bounds"};function _x(s){return `
227
+ <style>
228
+ :host {
229
+ --_tooltip-background-color: var(--media-tooltip-background-color, var(--media-secondary-color, rgba(20, 20, 30, .7)));
230
+ --_tooltip-background: var(--media-tooltip-background, var(--_tooltip-background-color));
231
+ --_tooltip-arrow-half-width: calc(var(--media-tooltip-arrow-width, 12px) / 2);
232
+ --_tooltip-arrow-height: var(--media-tooltip-arrow-height, 5px);
233
+ --_tooltip-arrow-background: var(--media-tooltip-arrow-color, var(--_tooltip-background-color));
234
+ position: relative;
235
+ pointer-events: none;
236
+ display: var(--media-tooltip-display, inline-flex);
237
+ justify-content: center;
238
+ align-items: center;
239
+ box-sizing: border-box;
240
+ z-index: var(--media-tooltip-z-index, 1);
241
+ background: var(--_tooltip-background);
242
+ color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238)));
243
+ font: var(--media-font,
244
+ var(--media-font-weight, 400)
245
+ var(--media-font-size, 13px) /
246
+ var(--media-text-content-height, var(--media-control-height, 18px))
247
+ var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif));
248
+ padding: var(--media-tooltip-padding, .35em .7em);
249
+ border: var(--media-tooltip-border, none);
250
+ border-radius: var(--media-tooltip-border-radius, 5px);
251
+ filter: var(--media-tooltip-filter, drop-shadow(0 0 4px rgba(0, 0, 0, .2)));
252
+ white-space: var(--media-tooltip-white-space, nowrap);
253
+ }
254
+
255
+ :host([hidden]) {
256
+ display: none;
257
+ }
258
+
259
+ img, svg {
260
+ display: inline-block;
261
+ }
262
+
263
+ #arrow {
264
+ position: absolute;
265
+ width: 0px;
266
+ height: 0px;
267
+ border-style: solid;
268
+ display: var(--media-tooltip-arrow-display, block);
269
+ }
270
+
271
+ :host(:not([placement])),
272
+ :host([placement="top"]) {
273
+ position: absolute;
274
+ bottom: calc(100% + var(--media-tooltip-distance, 12px));
275
+ left: 50%;
276
+ transform: translate(calc(-50% - var(--media-tooltip-offset-x, 0px)), 0);
277
+ }
278
+ :host(:not([placement])) #arrow,
279
+ :host([placement="top"]) #arrow {
280
+ top: 100%;
281
+ left: 50%;
282
+ border-width: var(--_tooltip-arrow-height) var(--_tooltip-arrow-half-width) 0 var(--_tooltip-arrow-half-width);
283
+ border-color: var(--_tooltip-arrow-background) transparent transparent transparent;
284
+ transform: translate(calc(-50% + var(--media-tooltip-offset-x, 0px)), 0);
285
+ }
286
+
287
+ :host([placement="right"]) {
288
+ position: absolute;
289
+ left: calc(100% + var(--media-tooltip-distance, 12px));
290
+ top: 50%;
291
+ transform: translate(0, -50%);
292
+ }
293
+ :host([placement="right"]) #arrow {
294
+ top: 50%;
295
+ right: 100%;
296
+ border-width: var(--_tooltip-arrow-half-width) var(--_tooltip-arrow-height) var(--_tooltip-arrow-half-width) 0;
297
+ border-color: transparent var(--_tooltip-arrow-background) transparent transparent;
298
+ transform: translate(0, -50%);
299
+ }
300
+
301
+ :host([placement="bottom"]) {
302
+ position: absolute;
303
+ top: calc(100% + var(--media-tooltip-distance, 12px));
304
+ left: 50%;
305
+ transform: translate(calc(-50% - var(--media-tooltip-offset-x, 0px)), 0);
306
+ }
307
+ :host([placement="bottom"]) #arrow {
308
+ bottom: 100%;
309
+ left: 50%;
310
+ border-width: 0 var(--_tooltip-arrow-half-width) var(--_tooltip-arrow-height) var(--_tooltip-arrow-half-width);
311
+ border-color: transparent transparent var(--_tooltip-arrow-background) transparent;
312
+ transform: translate(calc(-50% + var(--media-tooltip-offset-x, 0px)), 0);
313
+ }
314
+
315
+ :host([placement="left"]) {
316
+ position: absolute;
317
+ right: calc(100% + var(--media-tooltip-distance, 12px));
318
+ top: 50%;
319
+ transform: translate(0, -50%);
320
+ }
321
+ :host([placement="left"]) #arrow {
322
+ top: 50%;
323
+ left: 100%;
324
+ border-width: var(--_tooltip-arrow-half-width) 0 var(--_tooltip-arrow-half-width) var(--_tooltip-arrow-height);
325
+ border-color: transparent transparent transparent var(--_tooltip-arrow-background);
326
+ transform: translate(0, -50%);
327
+ }
328
+
329
+ :host([placement="none"]) #arrow {
330
+ display: none;
331
+ }
332
+ </style>
333
+ <slot></slot>
334
+ <div id="arrow"></div>
335
+ `}var Sn=class extends A.HTMLElement{constructor(){if(super(),this.updateXOffset=()=>{var e;if(!wd(this,{checkOpacity:false,checkVisibilityCSS:false}))return;let t=this.placement;if(t==="left"||t==="right"){this.style.removeProperty("--media-tooltip-offset-x");return}let i=getComputedStyle(this),r=(e=Pi(this,"#"+this.bounds))!=null?e:Ge(this);if(!r)return;let{x:n,width:o}=r.getBoundingClientRect(),{x:a,width:l}=this.getBoundingClientRect(),d=a+l,c=n+o,u=i.getPropertyValue("--media-tooltip-offset-x"),h=u?parseFloat(u.replace("px","")):0,f=i.getPropertyValue("--media-tooltip-container-margin"),m=f?parseFloat(f.replace("px","")):0,p=a-n+h-m,g=d-c+h+m;if(p<0){this.style.setProperty("--media-tooltip-offset-x",`${p}px`);return}if(g>0){this.style.setProperty("--media-tooltip-offset-x",`${g}px`);return}this.style.removeProperty("--media-tooltip-offset-x");},!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}if(this.arrowEl=this.shadowRoot.querySelector("#arrow"),Object.prototype.hasOwnProperty.call(this,"placement")){let e=this.placement;delete this.placement,this.placement=e;}}static get observedAttributes(){return [Tn.PLACEMENT,Tn.BOUNDS]}get placement(){return me(this,Tn.PLACEMENT)}set placement(e){pe(this,Tn.PLACEMENT,e);}get bounds(){return me(this,Tn.BOUNDS)}set bounds(e){pe(this,Tn.BOUNDS,e);}};Sn.shadowRootOptions={mode:"open"};Sn.getTemplateHTML=_x;A.customElements.get("media-tooltip")||A.customElements.define("media-tooltip",Sn);var zd=Sn;var $f=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},ht=(s,e,t)=>($f(s,e,"read from private field"),t?t.call(s):e.get(s)),An=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Qd=(s,e,t,i)=>($f(s,e,"write to private field"),e.set(s,t),t),Tx=(s,e,t)=>($f(s,e,"access private method"),t),Fi,xn,Ws,In,Xd,Ff,ZE,Vs={TOOLTIP_PLACEMENT:"tooltipplacement",DISABLED:"disabled",NO_TOOLTIP:"notooltip"};function Sx(s,e={}){return `
336
+ <style>
337
+ :host {
338
+ position: relative;
339
+ font: var(--media-font,
340
+ var(--media-font-weight, bold)
341
+ var(--media-font-size, 14px) /
342
+ var(--media-text-content-height, var(--media-control-height, 24px))
343
+ var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif));
344
+ color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238)));
345
+ background: var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7)));
346
+ padding: var(--media-button-padding, var(--media-control-padding, 10px));
347
+ justify-content: var(--media-button-justify-content, center);
348
+ display: inline-flex;
349
+ align-items: center;
350
+ vertical-align: middle;
351
+ box-sizing: border-box;
352
+ transition: background .15s linear;
353
+ pointer-events: auto;
354
+ cursor: var(--media-cursor, pointer);
355
+ -webkit-tap-highlight-color: transparent;
356
+ }
357
+
358
+
359
+ :host(:focus-visible) {
360
+ box-shadow: var(--media-focus-box-shadow, inset 0 0 0 2px rgb(27 127 204 / .9));
361
+ outline: 0;
362
+ }
363
+
364
+ :host(:where(:focus)) {
365
+ box-shadow: none;
366
+ outline: 0;
367
+ }
368
+
369
+ :host(:hover) {
370
+ background: var(--media-control-hover-background, rgba(50 50 70 / .7));
371
+ }
372
+
373
+ svg, img, ::slotted(svg), ::slotted(img) {
374
+ width: var(--media-button-icon-width);
375
+ height: var(--media-button-icon-height, var(--media-control-height, 24px));
376
+ transform: var(--media-button-icon-transform);
377
+ transition: var(--media-button-icon-transition);
378
+ fill: var(--media-icon-color, var(--media-primary-color, rgb(238 238 238)));
379
+ vertical-align: middle;
380
+ max-width: 100%;
381
+ max-height: 100%;
382
+ min-width: 100%;
383
+ }
384
+
385
+ media-tooltip {
386
+
387
+ max-width: 0;
388
+ overflow-x: clip;
389
+ opacity: 0;
390
+ transition: opacity .3s, max-width 0s 9s;
391
+ }
392
+
393
+ :host(:hover) media-tooltip,
394
+ :host(:focus-visible) media-tooltip {
395
+ max-width: 100vw;
396
+ opacity: 1;
397
+ transition: opacity .3s;
398
+ }
399
+
400
+ :host([notooltip]) slot[name="tooltip"] {
401
+ display: none;
402
+ }
403
+ </style>
404
+
405
+ ${this.getSlotTemplateHTML(s,e)}
406
+
407
+ <slot name="tooltip">
408
+ <media-tooltip part="tooltip" aria-hidden="true">
409
+ <template shadowrootmode="${zd.shadowRootOptions.mode}">
410
+ ${zd.getTemplateHTML({})}
411
+ </template>
412
+ <slot name="tooltip-content">
413
+ ${this.getTooltipContentHTML(s)}
414
+ </slot>
415
+ </media-tooltip>
416
+ </slot>
417
+ `}function Ax(s,e){return `
418
+ <slot></slot>
419
+ `}function Ix(){return ""}var De=class extends A.HTMLElement{constructor(){if(super(),An(this,Ff),An(this,Fi,void 0),this.preventClick=false,this.tooltipEl=null,An(this,xn,e=>{this.preventClick||this.handleClick(e),setTimeout(ht(this,Ws),0);}),An(this,Ws,()=>{var e,t;(t=(e=this.tooltipEl)==null?void 0:e.updateXOffset)==null||t.call(e);}),An(this,In,e=>{let{key:t}=e;if(!this.keysUsed.includes(t)){this.removeEventListener("keyup",ht(this,In));return}this.preventClick||this.handleClick(e);}),An(this,Xd,e=>{let{metaKey:t,altKey:i,key:r}=e;if(t||i||!this.keysUsed.includes(r)){this.removeEventListener("keyup",ht(this,In));return}this.addEventListener("keyup",ht(this,In),{once:true});}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=qe(this.attributes),t=this.constructor.getTemplateHTML(e);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(t):this.shadowRoot.innerHTML=t;}this.tooltipEl=this.shadowRoot.querySelector("media-tooltip");}static get observedAttributes(){return ["disabled",Vs.TOOLTIP_PLACEMENT,ve.MEDIA_CONTROLLER,b.MEDIA_LANG]}enable(){this.addEventListener("click",ht(this,xn)),this.addEventListener("keydown",ht(this,Xd)),this.tabIndex=0;}disable(){this.removeEventListener("click",ht(this,xn)),this.removeEventListener("keydown",ht(this,Xd)),this.removeEventListener("keyup",ht(this,In)),this.tabIndex=-1;}attributeChangedCallback(e,t,i){var r,n,o,a,l;e===ve.MEDIA_CONTROLLER?(t&&((n=(r=ht(this,Fi))==null?void 0:r.unassociateElement)==null||n.call(r,this),Qd(this,Fi,null)),i&&this.isConnected&&(Qd(this,Fi,(o=this.getRootNode())==null?void 0:o.getElementById(i)),(l=(a=ht(this,Fi))==null?void 0:a.associateElement)==null||l.call(a,this))):e==="disabled"&&i!==t?i==null?this.enable():this.disable():e===Vs.TOOLTIP_PLACEMENT&&this.tooltipEl&&i!==t?this.tooltipEl.placement=i:e===b.MEDIA_LANG&&(this.shadowRoot.querySelector('slot[name="tooltip-content"]').innerHTML=this.constructor.getTooltipContentHTML()),ht(this,Ws).call(this);}connectedCallback(){var e,t,i;let{style:r}=Ke(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`),this.hasAttribute("disabled")?this.disable():this.enable(),this.setAttribute("role","button");let n=this.getAttribute(ve.MEDIA_CONTROLLER);n&&(Qd(this,Fi,(e=this.getRootNode())==null?void 0:e.getElementById(n)),(i=(t=ht(this,Fi))==null?void 0:t.associateElement)==null||i.call(t,this)),A.customElements.whenDefined("media-tooltip").then(()=>Tx(this,Ff,ZE).call(this));}disconnectedCallback(){var e,t;this.disable(),(t=(e=ht(this,Fi))==null?void 0:e.unassociateElement)==null||t.call(e,this),Qd(this,Fi,null),this.removeEventListener("mouseenter",ht(this,Ws)),this.removeEventListener("focus",ht(this,Ws)),this.removeEventListener("click",ht(this,xn));}get keysUsed(){return ["Enter"," "]}get tooltipPlacement(){return me(this,Vs.TOOLTIP_PLACEMENT)}set tooltipPlacement(e){pe(this,Vs.TOOLTIP_PLACEMENT,e);}get mediaController(){return me(this,ve.MEDIA_CONTROLLER)}set mediaController(e){pe(this,ve.MEDIA_CONTROLLER,e);}get disabled(){return ae(this,Vs.DISABLED)}set disabled(e){le(this,Vs.DISABLED,e);}get noTooltip(){return ae(this,Vs.NO_TOOLTIP)}set noTooltip(e){le(this,Vs.NO_TOOLTIP,e);}handleClick(e){}};Fi=new WeakMap;xn=new WeakMap;Ws=new WeakMap;In=new WeakMap;Xd=new WeakMap;Ff=new WeakSet;ZE=function(){this.addEventListener("mouseenter",ht(this,Ws)),this.addEventListener("focus",ht(this,Ws)),this.addEventListener("click",ht(this,xn));let s=this.tooltipPlacement;s&&this.tooltipEl&&(this.tooltipEl.placement=s);};De.shadowRootOptions={mode:"open"};De.getTemplateHTML=Sx;De.getSlotTemplateHTML=Ax;De.getTooltipContentHTML=Ix;A.customElements.get("media-chrome-button")||A.customElements.define("media-chrome-button",De);var JE=`<svg aria-hidden="true" viewBox="0 0 26 24">
420
+ <path d="M22.13 3H3.87a.87.87 0 0 0-.87.87v13.26a.87.87 0 0 0 .87.87h3.4L9 16H5V5h16v11h-4l1.72 2h3.4a.87.87 0 0 0 .87-.87V3.87a.87.87 0 0 0-.86-.87Zm-8.75 11.44a.5.5 0 0 0-.76 0l-4.91 5.73a.5.5 0 0 0 .38.83h9.82a.501.501 0 0 0 .38-.83l-4.91-5.73Z"/>
421
+ </svg>
422
+ `;function xx(s){return `
423
+ <style>
424
+ :host([${b.MEDIA_IS_AIRPLAYING}]) slot[name=icon] slot:not([name=exit]) {
425
+ display: none !important;
426
+ }
427
+
428
+
429
+ :host(:not([${b.MEDIA_IS_AIRPLAYING}])) slot[name=icon] slot:not([name=enter]) {
430
+ display: none !important;
431
+ }
432
+
433
+ :host([${b.MEDIA_IS_AIRPLAYING}]) slot[name=tooltip-enter],
434
+ :host(:not([${b.MEDIA_IS_AIRPLAYING}])) slot[name=tooltip-exit] {
435
+ display: none;
436
+ }
437
+ </style>
438
+
439
+ <slot name="icon">
440
+ <slot name="enter">${JE}</slot>
441
+ <slot name="exit">${JE}</slot>
442
+ </slot>
443
+ `}function Lx(){return `
444
+ <slot name="tooltip-enter">${K("start airplay")}</slot>
445
+ <slot name="tooltip-exit">${K("stop airplay")}</slot>
446
+ `}var ey=s=>{let e=s.mediaIsAirplaying?K("stop airplay"):K("start airplay");s.setAttribute("aria-label",e);},ca=class extends De{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_IS_AIRPLAYING,b.MEDIA_AIRPLAY_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),ey(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_IS_AIRPLAYING&&ey(this);}get mediaIsAirplaying(){return ae(this,b.MEDIA_IS_AIRPLAYING)}set mediaIsAirplaying(e){le(this,b.MEDIA_IS_AIRPLAYING,e);}get mediaAirplayUnavailable(){return me(this,b.MEDIA_AIRPLAY_UNAVAILABLE)}set mediaAirplayUnavailable(e){pe(this,b.MEDIA_AIRPLAY_UNAVAILABLE,e);}handleClick(){let e=new A.CustomEvent(V.MEDIA_AIRPLAY_REQUEST,{composed:true,bubbles:true});this.dispatchEvent(e);}};ca.getSlotTemplateHTML=xx;ca.getTooltipContentHTML=Lx;A.customElements.get("media-airplay-button")||A.customElements.define("media-airplay-button",ca);var Rx=`<svg aria-hidden="true" viewBox="0 0 26 24">
447
+ <path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/>
448
+ </svg>`,kx=`<svg aria-hidden="true" viewBox="0 0 26 24">
449
+ <path d="M17.73 14.09a1.4 1.4 0 0 1-1 .37 1.579 1.579 0 0 1-1.27-.58A3 3 0 0 1 15 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34A2.89 2.89 0 0 0 19 9.07a3 3 0 0 0-2.14-.78 3.14 3.14 0 0 0-2.42 1 3.91 3.91 0 0 0-.93 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.17 3.17 0 0 0 1.07-1.74l-1.4-.45c-.083.43-.3.822-.62 1.12Zm-7.22 0a1.43 1.43 0 0 1-1 .37 1.58 1.58 0 0 1-1.27-.58A3 3 0 0 1 7.76 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34a2.81 2.81 0 0 0-.74-1.32 2.94 2.94 0 0 0-2.13-.78 3.18 3.18 0 0 0-2.43 1 4 4 0 0 0-.92 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.23 3.23 0 0 0 1.07-1.74l-1.4-.45a2.06 2.06 0 0 1-.6 1.07Zm12.32-8.41a2.59 2.59 0 0 0-2.3-2.51C18.72 3.05 15.86 3 13 3c-2.86 0-5.72.05-7.53.17a2.59 2.59 0 0 0-2.3 2.51c-.23 4.207-.23 8.423 0 12.63a2.57 2.57 0 0 0 2.3 2.5c1.81.13 4.67.19 7.53.19 2.86 0 5.72-.06 7.53-.19a2.57 2.57 0 0 0 2.3-2.5c.23-4.207.23-8.423 0-12.63Zm-1.49 12.53a1.11 1.11 0 0 1-.91 1.11c-1.67.11-4.45.18-7.43.18-2.98 0-5.76-.07-7.43-.18a1.11 1.11 0 0 1-.91-1.11c-.21-4.14-.21-8.29 0-12.43a1.11 1.11 0 0 1 .91-1.11C7.24 4.56 10 4.49 13 4.49s5.76.07 7.43.18a1.11 1.11 0 0 1 .91 1.11c.21 4.14.21 8.29 0 12.43Z"/>
450
+ </svg>`;function wx(s){return `
451
+ <style>
452
+ :host([aria-checked="true"]) slot[name=off] {
453
+ display: none !important;
454
+ }
455
+
456
+
457
+ :host(:not([aria-checked="true"])) slot[name=on] {
458
+ display: none !important;
459
+ }
460
+
461
+ :host([aria-checked="true"]) slot[name=tooltip-enable],
462
+ :host(:not([aria-checked="true"])) slot[name=tooltip-disable] {
463
+ display: none;
464
+ }
465
+ </style>
466
+
467
+ <slot name="icon">
468
+ <slot name="on">${Rx}</slot>
469
+ <slot name="off">${kx}</slot>
470
+ </slot>
471
+ `}function Cx(){return `
472
+ <slot name="tooltip-enable">${K("Enable captions")}</slot>
473
+ <slot name="tooltip-disable">${K("Disable captions")}</slot>
474
+ `}var ty=s=>{s.setAttribute("aria-checked",Hd(s).toString());},ua=class extends De{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_SUBTITLES_LIST,b.MEDIA_SUBTITLES_SHOWING]}connectedCallback(){super.connectedCallback(),this.setAttribute("role","switch"),this.setAttribute("aria-label",K("closed captions")),ty(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_SUBTITLES_SHOWING&&ty(this);}get mediaSubtitlesList(){return iy(this,b.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){sy(this,b.MEDIA_SUBTITLES_LIST,e);}get mediaSubtitlesShowing(){return iy(this,b.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){sy(this,b.MEDIA_SUBTITLES_SHOWING,e);}handleClick(){this.dispatchEvent(new A.CustomEvent(V.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:true,bubbles:true}));}};ua.getSlotTemplateHTML=wx;ua.getTooltipContentHTML=Cx;var iy=(s,e)=>{let t=s.getAttribute(e);return t?kr(t):[]},sy=(s,e,t)=>{if(!t?.length){s.removeAttribute(e);return}let i=Ts(t);s.getAttribute(e)!==i&&s.setAttribute(e,i);};A.customElements.get("media-captions-button")||A.customElements.define("media-captions-button",ua);var Dx='<svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/></g></svg>',Mx='<svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/><path class="cast_caf_icon_boxfill" d="M5,7 L5,8.63 C8,8.6 13.37,14 13.37,17 L19,17 L19,7 Z"/></g></svg>';function Px(s){return `
475
+ <style>
476
+ :host([${b.MEDIA_IS_CASTING}]) slot[name=icon] slot:not([name=exit]) {
477
+ display: none !important;
478
+ }
479
+
480
+
481
+ :host(:not([${b.MEDIA_IS_CASTING}])) slot[name=icon] slot:not([name=enter]) {
482
+ display: none !important;
483
+ }
484
+
485
+ :host([${b.MEDIA_IS_CASTING}]) slot[name=tooltip-enter],
486
+ :host(:not([${b.MEDIA_IS_CASTING}])) slot[name=tooltip-exit] {
487
+ display: none;
488
+ }
489
+ </style>
490
+
491
+ <slot name="icon">
492
+ <slot name="enter">${Dx}</slot>
493
+ <slot name="exit">${Mx}</slot>
494
+ </slot>
495
+ `}function Ox(){return `
496
+ <slot name="tooltip-enter">${K("Start casting")}</slot>
497
+ <slot name="tooltip-exit">${K("Stop casting")}</slot>
498
+ `}var ry=s=>{let e=s.mediaIsCasting?K("stop casting"):K("start casting");s.setAttribute("aria-label",e);},ha=class extends De{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_IS_CASTING,b.MEDIA_CAST_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),ry(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_IS_CASTING&&ry(this);}get mediaIsCasting(){return ae(this,b.MEDIA_IS_CASTING)}set mediaIsCasting(e){le(this,b.MEDIA_IS_CASTING,e);}get mediaCastUnavailable(){return me(this,b.MEDIA_CAST_UNAVAILABLE)}set mediaCastUnavailable(e){pe(this,b.MEDIA_CAST_UNAVAILABLE,e);}handleClick(){let e=this.mediaIsCasting?V.MEDIA_EXIT_CAST_REQUEST:V.MEDIA_ENTER_CAST_REQUEST;this.dispatchEvent(new A.CustomEvent(e,{composed:true,bubbles:true}));}};ha.getSlotTemplateHTML=Px;ha.getTooltipContentHTML=Ox;A.customElements.get("media-cast-button")||A.customElements.define("media-cast-button",ha);var qf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Ur=(s,e,t)=>(qf(s,e,"read from private field"),e.get(s)),Ss=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},jf=(s,e,t,i)=>(qf(s,e,"write to private field"),e.set(s,t),t),Or=(s,e,t)=>(qf(s,e,"access private method"),t),Jd,ma,Nr,Zd,Bf,Hf,ny,Gf,oy,Kf,ay,Vf,ly,Wf,dy;function Ux(s){return `
499
+ <style>
500
+ :host {
501
+ font: var(--media-font,
502
+ var(--media-font-weight, normal)
503
+ var(--media-font-size, 14px) /
504
+ var(--media-text-content-height, var(--media-control-height, 24px))
505
+ var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif));
506
+ color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238)));
507
+ display: var(--media-dialog-display, inline-flex);
508
+ justify-content: center;
509
+ align-items: center;
510
+
511
+ transition-behavior: allow-discrete;
512
+ visibility: hidden;
513
+ opacity: 0;
514
+ transform: translateY(2px) scale(.99);
515
+ pointer-events: none;
516
+ }
517
+
518
+ :host([open]) {
519
+ transition: display .2s, visibility 0s, opacity .2s ease-out, transform .15s ease-out;
520
+ visibility: visible;
521
+ opacity: 1;
522
+ transform: translateY(0) scale(1);
523
+ pointer-events: auto;
524
+ }
525
+
526
+ #content {
527
+ display: flex;
528
+ position: relative;
529
+ box-sizing: border-box;
530
+ width: min(320px, 100%);
531
+ word-wrap: break-word;
532
+ max-height: 100%;
533
+ overflow: auto;
534
+ text-align: center;
535
+ line-height: 1.4;
536
+ }
537
+ </style>
538
+ ${this.getSlotTemplateHTML(s)}
539
+ `}function Nx(s){return `
540
+ <slot id="content"></slot>
541
+ `}var fa={OPEN:"open",ANCHOR:"anchor"},$i=class extends A.HTMLElement{constructor(){super(),Ss(this,Zd),Ss(this,Hf),Ss(this,Gf),Ss(this,Kf),Ss(this,Vf),Ss(this,Wf),Ss(this,Jd,false),Ss(this,ma,null),Ss(this,Nr,null),this.addEventListener("invoke",this),this.addEventListener("focusout",this),this.addEventListener("keydown",this);}static get observedAttributes(){return [fa.OPEN,fa.ANCHOR]}get open(){return ae(this,fa.OPEN)}set open(e){le(this,fa.OPEN,e);}handleEvent(e){switch(e.type){case "invoke":Or(this,Kf,ay).call(this,e);break;case "focusout":Or(this,Vf,ly).call(this,e);break;case "keydown":Or(this,Wf,dy).call(this,e);break}}connectedCallback(){Or(this,Zd,Bf).call(this),this.role||(this.role="dialog");}attributeChangedCallback(e,t,i){Or(this,Zd,Bf).call(this),e===fa.OPEN&&i!==t&&(this.open?Or(this,Hf,ny).call(this):Or(this,Gf,oy).call(this));}focus(){jf(this,ma,Jo());let e=!this.dispatchEvent(new Event("focus",{composed:true,cancelable:true})),t=!this.dispatchEvent(new Event("focusin",{composed:true,bubbles:true,cancelable:true}));if(e||t)return;let i=this.querySelector('[autofocus], [tabindex]:not([tabindex="-1"]), [role="menu"]');i?.focus();}get keysUsed(){return ["Escape","Tab"]}};Jd=new WeakMap;ma=new WeakMap;Nr=new WeakMap;Zd=new WeakSet;Bf=function(){if(!Ur(this,Jd)&&(jf(this,Jd,true),!this.shadowRoot)){this.attachShadow(this.constructor.shadowRootOptions);let s=qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(s),queueMicrotask(()=>{let{style:e}=Ke(this.shadowRoot,":host");e.setProperty("transition","display .15s, visibility .15s, opacity .15s ease-in, transform .15s ease-in");});}};Hf=new WeakSet;ny=function(){var s;(s=Ur(this,Nr))==null||s.setAttribute("aria-expanded","true"),this.dispatchEvent(new Event("open",{composed:true,bubbles:true})),this.addEventListener("transitionend",()=>this.focus(),{once:true});};Gf=new WeakSet;oy=function(){var s;(s=Ur(this,Nr))==null||s.setAttribute("aria-expanded","false"),this.dispatchEvent(new Event("close",{composed:true,bubbles:true}));};Kf=new WeakSet;ay=function(s){jf(this,Nr,s.relatedTarget),Nt(this,s.relatedTarget)||(this.open=!this.open);};Vf=new WeakSet;ly=function(s){var e;Nt(this,s.relatedTarget)||((e=Ur(this,ma))==null||e.focus(),Ur(this,Nr)&&Ur(this,Nr)!==s.relatedTarget&&this.open&&(this.open=false));};Wf=new WeakSet;dy=function(s){var e,t,i,r,n;let{key:o,ctrlKey:a,altKey:l,metaKey:d}=s;a||l||d||this.keysUsed.includes(o)&&(s.preventDefault(),s.stopPropagation(),o==="Tab"?(s.shiftKey?(t=(e=this.previousElementSibling)==null?void 0:e.focus)==null||t.call(e):(r=(i=this.nextElementSibling)==null?void 0:i.focus)==null||r.call(i),this.blur()):o==="Escape"&&((n=Ur(this,ma))==null||n.focus(),this.open=false));};$i.shadowRootOptions={mode:"open"};$i.getTemplateHTML=Ux;$i.getSlotTemplateHTML=Nx;A.customElements.get("media-chrome-dialog")||A.customElements.define("media-chrome-dialog",$i);var em=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Xe=(s,e,t)=>(em(s,e,"read from private field"),t?t.call(s):e.get(s)),At=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},qs=(s,e,t,i)=>(em(s,e,"write to private field"),e.set(s,t),t),_i=(s,e,t)=>(em(s,e,"access private method"),t),Bi,dc,ec,tc,Ti,ac,ic,sc,rc,tm,cy,nc,Yf,oc,zf,lc,im,Qf,uy,Xf,hy,Zf,fy,Jf,my;function Fx(s){return `
542
+ <style>
543
+ :host {
544
+ --_focus-box-shadow: var(--media-focus-box-shadow, inset 0 0 0 2px rgb(27 127 204 / .9));
545
+ --_media-range-padding: var(--media-range-padding, var(--media-control-padding, 10px));
546
+
547
+ box-shadow: var(--_focus-visible-box-shadow, none);
548
+ background: var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7)));
549
+ height: calc(var(--media-control-height, 24px) + 2 * var(--_media-range-padding));
550
+ display: inline-flex;
551
+ align-items: center;
552
+
553
+ vertical-align: middle;
554
+ box-sizing: border-box;
555
+ position: relative;
556
+ width: 100px;
557
+ transition: background .15s linear;
558
+ cursor: var(--media-cursor, pointer);
559
+ pointer-events: auto;
560
+ touch-action: none;
561
+ }
562
+
563
+
564
+ input[type=range]:focus {
565
+ outline: 0;
566
+ }
567
+ input[type=range]:focus::-webkit-slider-runnable-track {
568
+ outline: 0;
569
+ }
570
+
571
+ :host(:hover) {
572
+ background: var(--media-control-hover-background, rgb(50 50 70 / .7));
573
+ }
574
+
575
+ #leftgap {
576
+ padding-left: var(--media-range-padding-left, var(--_media-range-padding));
577
+ }
578
+
579
+ #rightgap {
580
+ padding-right: var(--media-range-padding-right, var(--_media-range-padding));
581
+ }
582
+
583
+ #startpoint,
584
+ #endpoint {
585
+ position: absolute;
586
+ }
587
+
588
+ #endpoint {
589
+ right: 0;
590
+ }
591
+
592
+ #container {
593
+
594
+ width: var(--media-range-track-width, 100%);
595
+ transform: translate(var(--media-range-track-translate-x, 0px), var(--media-range-track-translate-y, 0px));
596
+ position: relative;
597
+ height: 100%;
598
+ display: flex;
599
+ align-items: center;
600
+ min-width: 40px;
601
+ }
602
+
603
+ #range {
604
+
605
+ display: var(--media-time-range-hover-display, block);
606
+ bottom: var(--media-time-range-hover-bottom, -7px);
607
+ height: var(--media-time-range-hover-height, max(100% + 7px, 25px));
608
+ width: 100%;
609
+ position: absolute;
610
+ cursor: var(--media-cursor, pointer);
611
+
612
+ -webkit-appearance: none;
613
+ -webkit-tap-highlight-color: transparent;
614
+ background: transparent;
615
+ margin: 0;
616
+ z-index: 1;
617
+ }
618
+
619
+ @media (hover: hover) {
620
+ #range {
621
+ bottom: var(--media-time-range-hover-bottom, -5px);
622
+ height: var(--media-time-range-hover-height, max(100% + 5px, 20px));
623
+ }
624
+ }
625
+
626
+
627
+
628
+ #range::-webkit-slider-thumb {
629
+ -webkit-appearance: none;
630
+ background: transparent;
631
+ width: .1px;
632
+ height: .1px;
633
+ }
634
+
635
+
636
+ #range::-moz-range-thumb {
637
+ background: transparent;
638
+ border: transparent;
639
+ width: .1px;
640
+ height: .1px;
641
+ }
642
+
643
+ #appearance {
644
+ height: var(--media-range-track-height, 4px);
645
+ display: flex;
646
+ flex-direction: column;
647
+ justify-content: center;
648
+ width: 100%;
649
+ position: absolute;
650
+
651
+ will-change: transform;
652
+ }
653
+
654
+ #track {
655
+ background: var(--media-range-track-background, rgb(255 255 255 / .2));
656
+ border-radius: var(--media-range-track-border-radius, 1px);
657
+ border: var(--media-range-track-border, none);
658
+ outline: var(--media-range-track-outline);
659
+ outline-offset: var(--media-range-track-outline-offset);
660
+ backdrop-filter: var(--media-range-track-backdrop-filter);
661
+ -webkit-backdrop-filter: var(--media-range-track-backdrop-filter);
662
+ box-shadow: var(--media-range-track-box-shadow, none);
663
+ position: absolute;
664
+ width: 100%;
665
+ height: 100%;
666
+ overflow: hidden;
667
+ }
668
+
669
+ #progress,
670
+ #pointer {
671
+ position: absolute;
672
+ height: 100%;
673
+ will-change: width;
674
+ }
675
+
676
+ #progress {
677
+ background: var(--media-range-bar-color, var(--media-primary-color, rgb(238 238 238)));
678
+ transition: var(--media-range-track-transition);
679
+ }
680
+
681
+ #pointer {
682
+ background: var(--media-range-track-pointer-background);
683
+ border-right: var(--media-range-track-pointer-border-right);
684
+ transition: visibility .25s, opacity .25s;
685
+ visibility: hidden;
686
+ opacity: 0;
687
+ }
688
+
689
+ @media (hover: hover) {
690
+ :host(:hover) #pointer {
691
+ transition: visibility .5s, opacity .5s;
692
+ visibility: visible;
693
+ opacity: 1;
694
+ }
695
+ }
696
+
697
+ #thumb,
698
+ ::slotted([slot=thumb]) {
699
+ width: var(--media-range-thumb-width, 10px);
700
+ height: var(--media-range-thumb-height, 10px);
701
+ transition: var(--media-range-thumb-transition);
702
+ transform: var(--media-range-thumb-transform, none);
703
+ opacity: var(--media-range-thumb-opacity, 1);
704
+ translate: -50%;
705
+ position: absolute;
706
+ left: 0;
707
+ cursor: var(--media-cursor, pointer);
708
+ }
709
+
710
+ #thumb {
711
+ border-radius: var(--media-range-thumb-border-radius, 10px);
712
+ background: var(--media-range-thumb-background, var(--media-primary-color, rgb(238 238 238)));
713
+ box-shadow: var(--media-range-thumb-box-shadow, 1px 1px 1px transparent);
714
+ border: var(--media-range-thumb-border, none);
715
+ }
716
+
717
+ :host([disabled]) #thumb {
718
+ background-color: #777;
719
+ }
720
+
721
+ .segments #appearance {
722
+ height: var(--media-range-segment-hover-height, 7px);
723
+ }
724
+
725
+ #track {
726
+ clip-path: url(#segments-clipping);
727
+ }
728
+
729
+ #segments {
730
+ --segments-gap: var(--media-range-segments-gap, 2px);
731
+ position: absolute;
732
+ width: 100%;
733
+ height: 100%;
734
+ }
735
+
736
+ #segments-clipping {
737
+ transform: translateX(calc(var(--segments-gap) / 2));
738
+ }
739
+
740
+ #segments-clipping:empty {
741
+ display: none;
742
+ }
743
+
744
+ #segments-clipping rect {
745
+ height: var(--media-range-track-height, 4px);
746
+ y: calc((var(--media-range-segment-hover-height, 7px) - var(--media-range-track-height, 4px)) / 2);
747
+ transition: var(--media-range-segment-transition, transform .1s ease-in-out);
748
+ transform: var(--media-range-segment-transform, scaleY(1));
749
+ transform-origin: center;
750
+ }
751
+ </style>
752
+ <div id="leftgap"></div>
753
+ <div id="container">
754
+ <div id="startpoint"></div>
755
+ <div id="endpoint"></div>
756
+ <div id="appearance">
757
+ <div id="track" part="track">
758
+ <div id="pointer"></div>
759
+ <div id="progress" part="progress"></div>
760
+ </div>
761
+ <slot name="thumb">
762
+ <div id="thumb" part="thumb"></div>
763
+ </slot>
764
+ <svg id="segments"><clipPath id="segments-clipping"></clipPath></svg>
765
+ </div>
766
+ <input id="range" type="range" min="0" max="1" step="any" value="0">
767
+
768
+ ${this.getContainerTemplateHTML(s)}
769
+ </div>
770
+ <div id="rightgap"></div>
771
+ `}function $x(s){return ""}var Hi=class extends A.HTMLElement{constructor(){if(super(),At(this,tm),At(this,nc),At(this,oc),At(this,lc),At(this,Qf),At(this,Xf),At(this,Zf),At(this,Jf),At(this,Bi,void 0),At(this,dc,void 0),At(this,ec,void 0),At(this,tc,void 0),At(this,Ti,{}),At(this,ac,[]),At(this,ic,()=>{if(this.range.matches(":focus-visible")){let{style:e}=Ke(this.shadowRoot,":host");e.setProperty("--_focus-visible-box-shadow","var(--_focus-box-shadow)");}}),At(this,sc,()=>{let{style:e}=Ke(this.shadowRoot,":host");e.removeProperty("--_focus-visible-box-shadow");}),At(this,rc,()=>{let e=this.shadowRoot.querySelector("#segments-clipping");e&&e.parentNode.append(e);}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=qe(this.attributes),t=this.constructor.getTemplateHTML(e);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(t):this.shadowRoot.innerHTML=t;}this.container=this.shadowRoot.querySelector("#container"),qs(this,ec,this.shadowRoot.querySelector("#startpoint")),qs(this,tc,this.shadowRoot.querySelector("#endpoint")),this.range=this.shadowRoot.querySelector("#range"),this.appearance=this.shadowRoot.querySelector("#appearance");}static get observedAttributes(){return ["disabled","aria-disabled",ve.MEDIA_CONTROLLER]}attributeChangedCallback(e,t,i){var r,n,o,a,l;e===ve.MEDIA_CONTROLLER?(t&&((n=(r=Xe(this,Bi))==null?void 0:r.unassociateElement)==null||n.call(r,this),qs(this,Bi,null)),i&&this.isConnected&&(qs(this,Bi,(o=this.getRootNode())==null?void 0:o.getElementById(i)),(l=(a=Xe(this,Bi))==null?void 0:a.associateElement)==null||l.call(a,this))):(e==="disabled"||e==="aria-disabled"&&t!==i)&&(i==null?(this.range.removeAttribute(e),_i(this,nc,Yf).call(this)):(this.range.setAttribute(e,i),_i(this,oc,zf).call(this)));}connectedCallback(){var e,t,i;let{style:r}=Ke(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`),Xe(this,Ti).pointer=Ke(this.shadowRoot,"#pointer"),Xe(this,Ti).progress=Ke(this.shadowRoot,"#progress"),Xe(this,Ti).thumb=Ke(this.shadowRoot,'#thumb, ::slotted([slot="thumb"])'),Xe(this,Ti).activeSegment=Ke(this.shadowRoot,"#segments-clipping rect:nth-child(0)");let n=this.getAttribute(ve.MEDIA_CONTROLLER);n&&(qs(this,Bi,(e=this.getRootNode())==null?void 0:e.getElementById(n)),(i=(t=Xe(this,Bi))==null?void 0:t.associateElement)==null||i.call(t,this)),this.updateBar(),this.shadowRoot.addEventListener("focusin",Xe(this,ic)),this.shadowRoot.addEventListener("focusout",Xe(this,sc)),_i(this,nc,Yf).call(this),ys(this.container,Xe(this,rc));}disconnectedCallback(){var e,t;_i(this,oc,zf).call(this),(t=(e=Xe(this,Bi))==null?void 0:e.unassociateElement)==null||t.call(e,this),qs(this,Bi,null),this.shadowRoot.removeEventListener("focusin",Xe(this,ic)),this.shadowRoot.removeEventListener("focusout",Xe(this,sc)),bs(this.container,Xe(this,rc));}updatePointerBar(e){var t;(t=Xe(this,Ti).pointer)==null||t.style.setProperty("width",`${this.getPointerRatio(e)*100}%`);}updateBar(){var e,t;let i=this.range.valueAsNumber*100;(e=Xe(this,Ti).progress)==null||e.style.setProperty("width",`${i}%`),(t=Xe(this,Ti).thumb)==null||t.style.setProperty("left",`${i}%`);}updateSegments(e){let t=this.shadowRoot.querySelector("#segments-clipping");if(t.textContent="",this.container.classList.toggle("segments",!!e?.length),!e?.length)return;let i=[...new Set([+this.range.min,...e.flatMap(n=>[n.start,n.end]),+this.range.max])];qs(this,ac,[...i]);let r=i.pop();for(let[n,o]of i.entries()){let[a,l]=[n===0,n===i.length-1],d=a?"calc(var(--segments-gap) / -1)":`${o*100}%`,u=`calc(${((l?r:i[n+1])-o)*100}%${a||l?"":" - var(--segments-gap)"})`,h=je.createElementNS("http://www.w3.org/2000/svg","rect"),f=ea(this.shadowRoot,`#segments-clipping rect:nth-child(${n+1})`);f.style.setProperty("x",d),f.style.setProperty("width",u),t.append(h);}}getPointerRatio(e){return _E(e.clientX,e.clientY,Xe(this,ec).getBoundingClientRect(),Xe(this,tc).getBoundingClientRect())}get dragging(){return this.hasAttribute("dragging")}handleEvent(e){switch(e.type){case "pointermove":_i(this,Jf,my).call(this,e);break;case "input":this.updateBar();break;case "pointerenter":_i(this,Qf,uy).call(this,e);break;case "pointerdown":_i(this,lc,im).call(this,e);break;case "pointerup":_i(this,Xf,hy).call(this);break;case "pointerleave":_i(this,Zf,fy).call(this);break}}get keysUsed(){return ["ArrowUp","ArrowRight","ArrowDown","ArrowLeft"]}};Bi=new WeakMap;dc=new WeakMap;ec=new WeakMap;tc=new WeakMap;Ti=new WeakMap;ac=new WeakMap;ic=new WeakMap;sc=new WeakMap;rc=new WeakMap;tm=new WeakSet;cy=function(s){let e=Xe(this,Ti).activeSegment;if(!e)return;let t=this.getPointerRatio(s),r=`#segments-clipping rect:nth-child(${Xe(this,ac).findIndex((n,o,a)=>{let l=a[o+1];return l!=null&&t>=n&&t<=l})+1})`;(e.selectorText!=r||!e.style.transform)&&(e.selectorText=r,e.style.setProperty("transform","var(--media-range-segment-hover-transform, scaleY(2))"));};nc=new WeakSet;Yf=function(){this.hasAttribute("disabled")||(this.addEventListener("input",this),this.addEventListener("pointerdown",this),this.addEventListener("pointerenter",this));};oc=new WeakSet;zf=function(){var s,e;this.removeEventListener("input",this),this.removeEventListener("pointerdown",this),this.removeEventListener("pointerenter",this),(s=A.window)==null||s.removeEventListener("pointerup",this),(e=A.window)==null||e.removeEventListener("pointermove",this);};lc=new WeakSet;im=function(s){var e;qs(this,dc,s.composedPath().includes(this.range)),(e=A.window)==null||e.addEventListener("pointerup",this);};Qf=new WeakSet;uy=function(s){var e;s.pointerType!=="mouse"&&_i(this,lc,im).call(this,s),this.addEventListener("pointerleave",this),(e=A.window)==null||e.addEventListener("pointermove",this);};Xf=new WeakSet;hy=function(){var s;(s=A.window)==null||s.removeEventListener("pointerup",this),this.toggleAttribute("dragging",false),this.range.disabled=this.hasAttribute("disabled");};Zf=new WeakSet;fy=function(){var s,e;this.removeEventListener("pointerleave",this),(s=A.window)==null||s.removeEventListener("pointermove",this),this.toggleAttribute("dragging",false),this.range.disabled=this.hasAttribute("disabled"),(e=Xe(this,Ti).activeSegment)==null||e.style.removeProperty("transform");};Jf=new WeakSet;my=function(s){s.pointerType==="pen"&&s.buttons===0||(this.toggleAttribute("dragging",s.buttons===1||s.pointerType!=="mouse"),this.updatePointerBar(s),_i(this,tm,cy).call(this,s),this.dragging&&(s.pointerType!=="mouse"||!Xe(this,dc))&&(this.range.disabled=true,this.range.valueAsNumber=this.getPointerRatio(s),this.range.dispatchEvent(new Event("input",{bubbles:true,composed:true}))));};Hi.shadowRootOptions={mode:"open"};Hi.getTemplateHTML=Fx;Hi.getContainerTemplateHTML=$x;A.customElements.get("media-chrome-range")||A.customElements.define("media-chrome-range",Hi);var py=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},cc=(s,e,t)=>(py(s,e,"read from private field"),t?t.call(s):e.get(s)),Bx=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},uc=(s,e,t,i)=>(py(s,e,"write to private field"),e.set(s,t),t),Gi;function Hx(s){return `
772
+ <style>
773
+ :host {
774
+
775
+ box-sizing: border-box;
776
+ display: var(--media-control-display, var(--media-control-bar-display, inline-flex));
777
+ color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238)));
778
+ --media-loading-indicator-icon-height: 44px;
779
+ }
780
+
781
+ ::slotted(media-time-range),
782
+ ::slotted(media-volume-range) {
783
+ min-height: 100%;
784
+ }
785
+
786
+ ::slotted(media-time-range),
787
+ ::slotted(media-clip-selector) {
788
+ flex-grow: 1;
789
+ }
790
+
791
+ ::slotted([role="menu"]) {
792
+ position: absolute;
793
+ }
794
+ </style>
795
+
796
+ <slot></slot>
797
+ `}var pa=class extends A.HTMLElement{constructor(){if(super(),Bx(this,Gi,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [ve.MEDIA_CONTROLLER]}attributeChangedCallback(e,t,i){var r,n,o,a,l;e===ve.MEDIA_CONTROLLER&&(t&&((n=(r=cc(this,Gi))==null?void 0:r.unassociateElement)==null||n.call(r,this),uc(this,Gi,null)),i&&this.isConnected&&(uc(this,Gi,(o=this.getRootNode())==null?void 0:o.getElementById(i)),(l=(a=cc(this,Gi))==null?void 0:a.associateElement)==null||l.call(a,this)));}connectedCallback(){var e,t,i;let r=this.getAttribute(ve.MEDIA_CONTROLLER);r&&(uc(this,Gi,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(i=(t=cc(this,Gi))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=cc(this,Gi))==null?void 0:e.unassociateElement)==null||t.call(e,this),uc(this,Gi,null);}};Gi=new WeakMap;pa.shadowRootOptions={mode:"open"};pa.getTemplateHTML=Hx;A.customElements.get("media-control-bar")||A.customElements.define("media-control-bar",pa);var gy=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},hc=(s,e,t)=>(gy(s,e,"read from private field"),t?t.call(s):e.get(s)),Gx=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},fc=(s,e,t,i)=>(gy(s,e,"write to private field"),e.set(s,t),t),Ki;function Kx(s,e={}){return `
798
+ <style>
799
+ :host {
800
+ font: var(--media-font,
801
+ var(--media-font-weight, normal)
802
+ var(--media-font-size, 14px) /
803
+ var(--media-text-content-height, var(--media-control-height, 24px))
804
+ var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif));
805
+ color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238)));
806
+ background: var(--media-text-background, var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7))));
807
+ padding: var(--media-control-padding, 10px);
808
+ display: inline-flex;
809
+ justify-content: center;
810
+ align-items: center;
811
+ vertical-align: middle;
812
+ box-sizing: border-box;
813
+ text-align: center;
814
+ pointer-events: auto;
815
+ }
816
+
817
+
818
+ :host(:focus-visible) {
819
+ box-shadow: inset 0 0 0 2px rgb(27 127 204 / .9);
820
+ outline: 0;
821
+ }
822
+
823
+
824
+ :host(:where(:focus)) {
825
+ box-shadow: none;
826
+ outline: 0;
827
+ }
828
+ </style>
829
+
830
+ ${this.getSlotTemplateHTML(s,e)}
831
+ `}function Vx(s,e){return `
832
+ <slot></slot>
833
+ `}var Kt=class extends A.HTMLElement{constructor(){if(super(),Gx(this,Ki,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [ve.MEDIA_CONTROLLER]}attributeChangedCallback(e,t,i){var r,n,o,a,l;e===ve.MEDIA_CONTROLLER&&(t&&((n=(r=hc(this,Ki))==null?void 0:r.unassociateElement)==null||n.call(r,this),fc(this,Ki,null)),i&&this.isConnected&&(fc(this,Ki,(o=this.getRootNode())==null?void 0:o.getElementById(i)),(l=(a=hc(this,Ki))==null?void 0:a.associateElement)==null||l.call(a,this)));}connectedCallback(){var e,t,i;let{style:r}=Ke(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`);let n=this.getAttribute(ve.MEDIA_CONTROLLER);n&&(fc(this,Ki,(e=this.getRootNode())==null?void 0:e.getElementById(n)),(i=(t=hc(this,Ki))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=hc(this,Ki))==null?void 0:e.unassociateElement)==null||t.call(e,this),fc(this,Ki,null);}};Ki=new WeakMap;Kt.shadowRootOptions={mode:"open"};Kt.getTemplateHTML=Kx;Kt.getSlotTemplateHTML=Vx;A.customElements.get("media-text-display")||A.customElements.define("media-text-display",Kt);var Ey=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},vy=(s,e,t)=>(Ey(s,e,"read from private field"),t?t.call(s):e.get(s)),Wx=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},qx=(s,e,t,i)=>(Ey(s,e,"write to private field"),e.set(s,t),t),ga;function jx(s,e){return `
834
+ <slot>${bi(e.mediaDuration)}</slot>
835
+ `}var mc=class extends Kt{constructor(){var e;super(),Wx(this,ga,void 0),qx(this,ga,this.shadowRoot.querySelector("slot")),vy(this,ga).textContent=bi((e=this.mediaDuration)!=null?e:0);}static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_DURATION]}attributeChangedCallback(e,t,i){e===b.MEDIA_DURATION&&(vy(this,ga).textContent=bi(+i)),super.attributeChangedCallback(e,t,i);}get mediaDuration(){return ye(this,b.MEDIA_DURATION)}set mediaDuration(e){Ae(this,b.MEDIA_DURATION,e);}};ga=new WeakMap;mc.getSlotTemplateHTML=jx;A.customElements.get("media-duration-display")||A.customElements.define("media-duration-display",mc);var Yx={2:K("Network Error"),3:K("Decode Error"),4:K("Source Not Supported"),5:K("Encryption Error")},zx={2:K("A network error caused the media download to fail."),3:K("A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format."),4:K("An unsupported error occurred. The server or network failed, or your browser does not support this format."),5:K("The media is encrypted and there are no keys to decrypt it.")},sm=s=>{var e,t;return s.code===1?null:{title:(e=Yx[s.code])!=null?e:`Error ${s.code}`,message:(t=zx[s.code])!=null?t:s.message}};var by=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Qx=(s,e,t)=>(by(s,e,"read from private field"),t?t.call(s):e.get(s)),Xx=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Zx=(s,e,t,i)=>(by(s,e,"write to private field"),e.set(s,t),t),pc;function Jx(s){return `
836
+ <style>
837
+ :host {
838
+ background: rgb(20 20 30 / .8);
839
+ }
840
+
841
+ #content {
842
+ display: block;
843
+ padding: 1.2em 1.5em;
844
+ }
845
+
846
+ h3,
847
+ p {
848
+ margin-block: 0 .3em;
849
+ }
850
+ </style>
851
+ <slot name="error-${s.mediaerrorcode}" id="content">
852
+ ${_y({code:+s.mediaerrorcode,message:s.mediaerrormessage})}
853
+ </slot>
854
+ `}function eL(s){return s.code&&sm(s)!==null}function _y(s){var e;let{title:t,message:i}=(e=sm(s))!=null?e:{},r="";return t&&(r+=`<slot name="error-${s.code}-title"><h3>${t}</h3></slot>`),i&&(r+=`<slot name="error-${s.code}-message"><p>${i}</p></slot>`),r}var yy=[b.MEDIA_ERROR_CODE,b.MEDIA_ERROR_MESSAGE],va=class extends $i{constructor(){super(...arguments),Xx(this,pc,null);}static get observedAttributes(){return [...super.observedAttributes,...yy]}formatErrorMessage(e){return this.constructor.formatErrorMessage(e)}attributeChangedCallback(e,t,i){var r;if(super.attributeChangedCallback(e,t,i),!yy.includes(e))return;let n=(r=this.mediaError)!=null?r:{code:this.mediaErrorCode,message:this.mediaErrorMessage};this.open=eL(n),this.open&&(this.shadowRoot.querySelector("slot").name=`error-${this.mediaErrorCode}`,this.shadowRoot.querySelector("#content").innerHTML=this.formatErrorMessage(n));}get mediaError(){return Qx(this,pc)}set mediaError(e){Zx(this,pc,e);}get mediaErrorCode(){return ye(this,"mediaerrorcode")}set mediaErrorCode(e){Ae(this,"mediaerrorcode",e);}get mediaErrorMessage(){return me(this,"mediaerrormessage")}set mediaErrorMessage(e){pe(this,"mediaerrormessage",e);}};pc=new WeakMap;va.getSlotTemplateHTML=Jx;va.formatErrorMessage=_y;A.customElements.get("media-error-dialog")||A.customElements.define("media-error-dialog",va);var tL=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},js=(s,e,t)=>(tL(s,e,"read from private field"),t?t.call(s):e.get(s)),Ty=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Ln,Rn;function iL(s){return `
855
+ <style>
856
+ :host {
857
+ position: fixed;
858
+ top: 0;
859
+ left: 0;
860
+ z-index: 9999;
861
+ background: rgb(20 20 30 / .8);
862
+ backdrop-filter: blur(10px);
863
+ }
864
+
865
+ #content {
866
+ display: block;
867
+ width: clamp(400px, 40vw, 700px);
868
+ max-width: 90vw;
869
+ text-align: left;
870
+ }
871
+
872
+ h2 {
873
+ margin: 0 0 1.5rem 0;
874
+ font-size: 1.5rem;
875
+ font-weight: 500;
876
+ text-align: center;
877
+ }
878
+
879
+ .shortcuts-table {
880
+ width: 100%;
881
+ border-collapse: collapse;
882
+ }
883
+
884
+ .shortcuts-table tr {
885
+ border-bottom: 1px solid rgba(255, 255, 255, 0.1);
886
+ }
887
+
888
+ .shortcuts-table tr:last-child {
889
+ border-bottom: none;
890
+ }
891
+
892
+ .shortcuts-table td {
893
+ padding: 0.75rem 0.5rem;
894
+ }
895
+
896
+ .shortcuts-table td:first-child {
897
+ text-align: right;
898
+ padding-right: 1rem;
899
+ width: 40%;
900
+ min-width: 120px;
901
+ }
902
+
903
+ .shortcuts-table td:last-child {
904
+ padding-left: 1rem;
905
+ }
906
+
907
+ .key {
908
+ display: inline-block;
909
+ background: rgba(255, 255, 255, 0.15);
910
+ border: 1px solid rgba(255, 255, 255, 0.2);
911
+ border-radius: 4px;
912
+ padding: 0.25rem 0.5rem;
913
+ font-family: 'Courier New', monospace;
914
+ font-size: 0.9rem;
915
+ font-weight: 500;
916
+ min-width: 1.5rem;
917
+ text-align: center;
918
+ margin: 0 0.2rem;
919
+ }
920
+
921
+ .description {
922
+ color: rgba(255, 255, 255, 0.9);
923
+ font-size: 0.95rem;
924
+ }
925
+
926
+ .key-combo {
927
+ display: flex;
928
+ align-items: center;
929
+ justify-content: flex-end;
930
+ gap: 0.3rem;
931
+ }
932
+
933
+ .key-separator {
934
+ color: rgba(255, 255, 255, 0.5);
935
+ font-size: 0.9rem;
936
+ }
937
+ </style>
938
+ <slot id="content">
939
+ ${sL()}
940
+ </slot>
941
+ `}function sL(){return `
942
+ <h2>Keyboard Shortcuts</h2>
943
+ <table class="shortcuts-table">${[{keys:["Space","k"],description:"Toggle Playback"},{keys:["m"],description:"Toggle mute"},{keys:["f"],description:"Toggle fullscreen"},{keys:["c"],description:"Toggle captions or subtitles, if available"},{keys:["p"],description:"Toggle Picture in Picture"},{keys:["\u2190","j"],description:"Seek back 10s"},{keys:["\u2192","l"],description:"Seek forward 10s"},{keys:["\u2191"],description:"Turn volume up"},{keys:["\u2193"],description:"Turn volume down"},{keys:["< (SHIFT+,)"],description:"Decrease playback rate"},{keys:["> (SHIFT+.)"],description:"Increase playback rate"}].map(({keys:t,description:i})=>`
944
+ <tr>
945
+ <td>
946
+ <div class="key-combo">${t.map((n,o)=>o>0?`<span class="key-separator">or</span><span class="key">${n}</span>`:`<span class="key">${n}</span>`).join("")}</div>
947
+ </td>
948
+ <td class="description">${i}</td>
949
+ </tr>
950
+ `).join("")}</table>
951
+ `}var gc=class extends $i{constructor(){super(...arguments),Ty(this,Ln,e=>{var t;if(!this.open)return;let i=(t=this.shadowRoot)==null?void 0:t.querySelector("#content");if(!i)return;let r=e.composedPath(),n=r[0]===this||r.includes(this),o=r.includes(i);n&&!o&&(this.open=false);}),Ty(this,Rn,e=>{if(!this.open)return;let t=e.shiftKey&&(e.key==="/"||e.key==="?");(e.key==="Escape"||t)&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&(this.open=false,e.preventDefault(),e.stopPropagation());});}connectedCallback(){super.connectedCallback(),this.open&&(this.addEventListener("click",js(this,Ln)),document.addEventListener("keydown",js(this,Rn)));}disconnectedCallback(){this.removeEventListener("click",js(this,Ln)),document.removeEventListener("keydown",js(this,Rn));}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e==="open"&&(this.open?(this.addEventListener("click",js(this,Ln)),document.addEventListener("keydown",js(this,Rn))):(this.removeEventListener("click",js(this,Ln)),document.removeEventListener("keydown",js(this,Rn))));}};Ln=new WeakMap;Rn=new WeakMap;gc.getSlotTemplateHTML=iL;A.customElements.get("media-keyboard-shortcuts-dialog")||A.customElements.define("media-keyboard-shortcuts-dialog",gc);var Ay=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},rL=(s,e,t)=>(Ay(s,e,"read from private field"),e.get(s)),nL=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},oL=(s,e,t,i)=>(Ay(s,e,"write to private field"),e.set(s,t),t),vc,aL=`<svg aria-hidden="true" viewBox="0 0 26 24">
952
+ <path d="M16 3v2.5h3.5V9H22V3h-6ZM4 9h2.5V5.5H10V3H4v6Zm15.5 9.5H16V21h6v-6h-2.5v3.5ZM6.5 15H4v6h6v-2.5H6.5V15Z"/>
953
+ </svg>`,lL=`<svg aria-hidden="true" viewBox="0 0 26 24">
954
+ <path d="M18.5 6.5V3H16v6h6V6.5h-3.5ZM16 21h2.5v-3.5H22V15h-6v6ZM4 17.5h3.5V21H10v-6H4v2.5Zm3.5-11H4V9h6V3H7.5v3.5Z"/>
955
+ </svg>`;function dL(s){return `
956
+ <style>
957
+ :host([${b.MEDIA_IS_FULLSCREEN}]) slot[name=icon] slot:not([name=exit]) {
958
+ display: none !important;
959
+ }
960
+
961
+
962
+ :host(:not([${b.MEDIA_IS_FULLSCREEN}])) slot[name=icon] slot:not([name=enter]) {
963
+ display: none !important;
964
+ }
965
+
966
+ :host([${b.MEDIA_IS_FULLSCREEN}]) slot[name=tooltip-enter],
967
+ :host(:not([${b.MEDIA_IS_FULLSCREEN}])) slot[name=tooltip-exit] {
968
+ display: none;
969
+ }
970
+ </style>
971
+
972
+ <slot name="icon">
973
+ <slot name="enter">${aL}</slot>
974
+ <slot name="exit">${lL}</slot>
975
+ </slot>
976
+ `}function cL(){return `
977
+ <slot name="tooltip-enter">${K("Enter fullscreen mode")}</slot>
978
+ <slot name="tooltip-exit">${K("Exit fullscreen mode")}</slot>
979
+ `}var Sy=s=>{let e=s.mediaIsFullscreen?K("exit fullscreen mode"):K("enter fullscreen mode");s.setAttribute("aria-label",e);},Ea=class extends De{constructor(){super(...arguments),nL(this,vc,null);}static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_IS_FULLSCREEN,b.MEDIA_FULLSCREEN_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),Sy(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_IS_FULLSCREEN&&Sy(this);}get mediaFullscreenUnavailable(){return me(this,b.MEDIA_FULLSCREEN_UNAVAILABLE)}set mediaFullscreenUnavailable(e){pe(this,b.MEDIA_FULLSCREEN_UNAVAILABLE,e);}get mediaIsFullscreen(){return ae(this,b.MEDIA_IS_FULLSCREEN)}set mediaIsFullscreen(e){le(this,b.MEDIA_IS_FULLSCREEN,e);}handleClick(e){oL(this,vc,e);let t=rL(this,vc)instanceof PointerEvent,i=this.mediaIsFullscreen?new A.CustomEvent(V.MEDIA_EXIT_FULLSCREEN_REQUEST,{composed:true,bubbles:true}):new A.CustomEvent(V.MEDIA_ENTER_FULLSCREEN_REQUEST,{composed:true,bubbles:true,detail:t});this.dispatchEvent(i);}};vc=new WeakMap;Ea.getSlotTemplateHTML=dL;Ea.getTooltipContentHTML=cL;A.customElements.get("media-fullscreen-button")||A.customElements.define("media-fullscreen-button",Ea);var{MEDIA_TIME_IS_LIVE:Ec,MEDIA_PAUSED:ya}=b,{MEDIA_SEEK_TO_LIVE_REQUEST:uL,MEDIA_PLAY_REQUEST:hL}=V,fL='<svg viewBox="0 0 6 12"><circle cx="3" cy="6" r="2"></circle></svg>';function mL(s){return `
980
+ <style>
981
+ :host { --media-tooltip-display: none; }
982
+
983
+ slot[name=indicator] > *,
984
+ :host ::slotted([slot=indicator]) {
985
+
986
+ min-width: auto;
987
+ fill: var(--media-live-button-icon-color, rgb(140, 140, 140));
988
+ color: var(--media-live-button-icon-color, rgb(140, 140, 140));
989
+ }
990
+
991
+ :host([${Ec}]:not([${ya}])) slot[name=indicator] > *,
992
+ :host([${Ec}]:not([${ya}])) ::slotted([slot=indicator]) {
993
+ fill: var(--media-live-button-indicator-color, rgb(255, 0, 0));
994
+ color: var(--media-live-button-indicator-color, rgb(255, 0, 0));
995
+ }
996
+
997
+ :host([${Ec}]:not([${ya}])) {
998
+ cursor: var(--media-cursor, not-allowed);
999
+ }
1000
+
1001
+ slot[name=text]{
1002
+ text-transform: uppercase;
1003
+ }
1004
+
1005
+ </style>
1006
+
1007
+ <slot name="indicator">${fL}</slot>
1008
+
1009
+ <slot name="spacer">&nbsp;</slot><slot name="text">${K("live")}</slot>
1010
+ `}var Iy=s=>{var e;let t=s.mediaPaused||!s.mediaTimeIsLive,i=t?K("seek to live"):K("playing live");s.setAttribute("aria-label",i);let r=(e=s.shadowRoot)==null?void 0:e.querySelector('slot[name="text"]');r&&(r.textContent=K("live")),t?s.removeAttribute("aria-disabled"):s.setAttribute("aria-disabled","true");},yc=class extends De{static get observedAttributes(){return [...super.observedAttributes,Ec,ya]}connectedCallback(){super.connectedCallback(),Iy(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),Iy(this);}get mediaPaused(){return ae(this,b.MEDIA_PAUSED)}set mediaPaused(e){le(this,b.MEDIA_PAUSED,e);}get mediaTimeIsLive(){return ae(this,b.MEDIA_TIME_IS_LIVE)}set mediaTimeIsLive(e){le(this,b.MEDIA_TIME_IS_LIVE,e);}handleClick(){!this.mediaPaused&&this.mediaTimeIsLive||(this.dispatchEvent(new A.CustomEvent(uL,{composed:true,bubbles:true})),this.hasAttribute(ya)&&this.dispatchEvent(new A.CustomEvent(hL,{composed:true,bubbles:true})));}};yc.getSlotTemplateHTML=mL;A.customElements.get("media-live-button")||A.customElements.define("media-live-button",yc);var Ly=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},ba=(s,e,t)=>(Ly(s,e,"read from private field"),t?t.call(s):e.get(s)),xy=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},_a=(s,e,t,i)=>(Ly(s,e,"write to private field"),e.set(s,t),t),Vi,_c,bc={LOADING_DELAY:"loadingdelay",NO_AUTOHIDE:"noautohide"},Ry=500,pL=`
1011
+ <svg aria-hidden="true" viewBox="0 0 100 100">
1012
+ <path d="M73,50c0-12.7-10.3-23-23-23S27,37.3,27,50 M30.9,50c0-10.5,8.5-19.1,19.1-19.1S69.1,39.5,69.1,50">
1013
+ <animateTransform
1014
+ attributeName="transform"
1015
+ attributeType="XML"
1016
+ type="rotate"
1017
+ dur="1s"
1018
+ from="0 50 50"
1019
+ to="360 50 50"
1020
+ repeatCount="indefinite" />
1021
+ </path>
1022
+ </svg>
1023
+ `;function gL(s){return `
1024
+ <style>
1025
+ :host {
1026
+ display: var(--media-control-display, var(--media-loading-indicator-display, inline-block));
1027
+ vertical-align: middle;
1028
+ box-sizing: border-box;
1029
+ --_loading-indicator-delay: var(--media-loading-indicator-transition-delay, ${Ry}ms);
1030
+ }
1031
+
1032
+ #status {
1033
+ color: rgba(0,0,0,0);
1034
+ width: 0px;
1035
+ height: 0px;
1036
+ }
1037
+
1038
+ :host slot[name=icon] > *,
1039
+ :host ::slotted([slot=icon]) {
1040
+ opacity: var(--media-loading-indicator-opacity, 0);
1041
+ transition: opacity 0.15s;
1042
+ }
1043
+
1044
+ :host([${b.MEDIA_LOADING}]:not([${b.MEDIA_PAUSED}])) slot[name=icon] > *,
1045
+ :host([${b.MEDIA_LOADING}]:not([${b.MEDIA_PAUSED}])) ::slotted([slot=icon]) {
1046
+ opacity: var(--media-loading-indicator-opacity, 1);
1047
+ transition: opacity 0.15s var(--_loading-indicator-delay);
1048
+ }
1049
+
1050
+ :host #status {
1051
+ visibility: var(--media-loading-indicator-opacity, hidden);
1052
+ transition: visibility 0.15s;
1053
+ }
1054
+
1055
+ :host([${b.MEDIA_LOADING}]:not([${b.MEDIA_PAUSED}])) #status {
1056
+ visibility: var(--media-loading-indicator-opacity, visible);
1057
+ transition: visibility 0.15s var(--_loading-indicator-delay);
1058
+ }
1059
+
1060
+ svg, img, ::slotted(svg), ::slotted(img) {
1061
+ width: var(--media-loading-indicator-icon-width);
1062
+ height: var(--media-loading-indicator-icon-height, 100px);
1063
+ fill: var(--media-icon-color, var(--media-primary-color, rgb(238 238 238)));
1064
+ vertical-align: middle;
1065
+ }
1066
+ </style>
1067
+
1068
+ <slot name="icon">${pL}</slot>
1069
+ <div id="status" role="status" aria-live="polite">${K("media loading")}</div>
1070
+ `}var Ta=class extends A.HTMLElement{constructor(){if(super(),xy(this,Vi,void 0),xy(this,_c,Ry),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [ve.MEDIA_CONTROLLER,b.MEDIA_PAUSED,b.MEDIA_LOADING,bc.LOADING_DELAY]}attributeChangedCallback(e,t,i){var r,n,o,a,l;e===bc.LOADING_DELAY&&t!==i?this.loadingDelay=Number(i):e===ve.MEDIA_CONTROLLER&&(t&&((n=(r=ba(this,Vi))==null?void 0:r.unassociateElement)==null||n.call(r,this),_a(this,Vi,null)),i&&this.isConnected&&(_a(this,Vi,(o=this.getRootNode())==null?void 0:o.getElementById(i)),(l=(a=ba(this,Vi))==null?void 0:a.associateElement)==null||l.call(a,this)));}connectedCallback(){var e,t,i;let r=this.getAttribute(ve.MEDIA_CONTROLLER);r&&(_a(this,Vi,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(i=(t=ba(this,Vi))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=ba(this,Vi))==null?void 0:e.unassociateElement)==null||t.call(e,this),_a(this,Vi,null);}get loadingDelay(){return ba(this,_c)}set loadingDelay(e){_a(this,_c,e);let{style:t}=Ke(this.shadowRoot,":host");t.setProperty("--_loading-indicator-delay",`var(--media-loading-indicator-transition-delay, ${e}ms)`);}get mediaPaused(){return ae(this,b.MEDIA_PAUSED)}set mediaPaused(e){le(this,b.MEDIA_PAUSED,e);}get mediaLoading(){return ae(this,b.MEDIA_LOADING)}set mediaLoading(e){le(this,b.MEDIA_LOADING,e);}get mediaController(){return me(this,ve.MEDIA_CONTROLLER)}set mediaController(e){pe(this,ve.MEDIA_CONTROLLER,e);}get noAutohide(){return ae(this,bc.NO_AUTOHIDE)}set noAutohide(e){le(this,bc.NO_AUTOHIDE,e);}};Vi=new WeakMap;_c=new WeakMap;Ta.shadowRootOptions={mode:"open"};Ta.getTemplateHTML=gL;A.customElements.get("media-loading-indicator")||A.customElements.define("media-loading-indicator",Ta);var vL=`<svg aria-hidden="true" viewBox="0 0 24 24">
1071
+ <path d="M16.5 12A4.5 4.5 0 0 0 14 8v2.18l2.45 2.45a4.22 4.22 0 0 0 .05-.63Zm2.5 0a6.84 6.84 0 0 1-.54 2.64L20 16.15A8.8 8.8 0 0 0 21 12a9 9 0 0 0-7-8.77v2.06A7 7 0 0 1 19 12ZM4.27 3 3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25A6.92 6.92 0 0 1 14 18.7v2.06A9 9 0 0 0 17.69 19l2 2.05L21 19.73l-9-9L4.27 3ZM12 4 9.91 6.09 12 8.18V4Z"/>
1072
+ </svg>`,ky=`<svg aria-hidden="true" viewBox="0 0 24 24">
1073
+ <path d="M3 9v6h4l5 5V4L7 9H3Zm13.5 3A4.5 4.5 0 0 0 14 8v8a4.47 4.47 0 0 0 2.5-4Z"/>
1074
+ </svg>`,EL=`<svg aria-hidden="true" viewBox="0 0 24 24">
1075
+ <path d="M3 9v6h4l5 5V4L7 9H3Zm13.5 3A4.5 4.5 0 0 0 14 8v8a4.47 4.47 0 0 0 2.5-4ZM14 3.23v2.06a7 7 0 0 1 0 13.42v2.06a9 9 0 0 0 0-17.54Z"/>
1076
+ </svg>`;function yL(s){return `
1077
+ <style>
1078
+ :host(:not([${b.MEDIA_VOLUME_LEVEL}])) slot[name=icon] slot:not([name=high]),
1079
+ :host([${b.MEDIA_VOLUME_LEVEL}=high]) slot[name=icon] slot:not([name=high]) {
1080
+ display: none !important;
1081
+ }
1082
+
1083
+ :host([${b.MEDIA_VOLUME_LEVEL}=off]) slot[name=icon] slot:not([name=off]) {
1084
+ display: none !important;
1085
+ }
1086
+
1087
+ :host([${b.MEDIA_VOLUME_LEVEL}=low]) slot[name=icon] slot:not([name=low]) {
1088
+ display: none !important;
1089
+ }
1090
+
1091
+ :host([${b.MEDIA_VOLUME_LEVEL}=medium]) slot[name=icon] slot:not([name=medium]) {
1092
+ display: none !important;
1093
+ }
1094
+
1095
+ :host(:not([${b.MEDIA_VOLUME_LEVEL}=off])) slot[name=tooltip-unmute],
1096
+ :host([${b.MEDIA_VOLUME_LEVEL}=off]) slot[name=tooltip-mute] {
1097
+ display: none;
1098
+ }
1099
+ </style>
1100
+
1101
+ <slot name="icon">
1102
+ <slot name="off">${vL}</slot>
1103
+ <slot name="low">${ky}</slot>
1104
+ <slot name="medium">${ky}</slot>
1105
+ <slot name="high">${EL}</slot>
1106
+ </slot>
1107
+ `}function bL(){return `
1108
+ <slot name="tooltip-mute">${K("Mute")}</slot>
1109
+ <slot name="tooltip-unmute">${K("Unmute")}</slot>
1110
+ `}var wy=s=>{let t=s.mediaVolumeLevel==="off"?K("unmute"):K("mute");s.setAttribute("aria-label",t);},Sa=class extends De{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_VOLUME_LEVEL]}connectedCallback(){super.connectedCallback(),wy(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_VOLUME_LEVEL&&wy(this);}get mediaVolumeLevel(){return me(this,b.MEDIA_VOLUME_LEVEL)}set mediaVolumeLevel(e){pe(this,b.MEDIA_VOLUME_LEVEL,e);}handleClick(){let e=this.mediaVolumeLevel==="off"?V.MEDIA_UNMUTE_REQUEST:V.MEDIA_MUTE_REQUEST;this.dispatchEvent(new A.CustomEvent(e,{composed:true,bubbles:true}));}};Sa.getSlotTemplateHTML=yL;Sa.getTooltipContentHTML=bL;A.customElements.get("media-mute-button")||A.customElements.define("media-mute-button",Sa);var Cy=`<svg aria-hidden="true" viewBox="0 0 28 24">
1111
+ <path d="M24 3H4a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h20a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1Zm-1 16H5V5h18v14Zm-3-8h-7v5h7v-5Z"/>
1112
+ </svg>`;function _L(s){return `
1113
+ <style>
1114
+ :host([${b.MEDIA_IS_PIP}]) slot[name=icon] slot:not([name=exit]) {
1115
+ display: none !important;
1116
+ }
1117
+
1118
+ :host(:not([${b.MEDIA_IS_PIP}])) slot[name=icon] slot:not([name=enter]) {
1119
+ display: none !important;
1120
+ }
1121
+
1122
+ :host([${b.MEDIA_IS_PIP}]) slot[name=tooltip-enter],
1123
+ :host(:not([${b.MEDIA_IS_PIP}])) slot[name=tooltip-exit] {
1124
+ display: none;
1125
+ }
1126
+ </style>
1127
+
1128
+ <slot name="icon">
1129
+ <slot name="enter">${Cy}</slot>
1130
+ <slot name="exit">${Cy}</slot>
1131
+ </slot>
1132
+ `}function TL(){return `
1133
+ <slot name="tooltip-enter">${K("Enter picture in picture mode")}</slot>
1134
+ <slot name="tooltip-exit">${K("Exit picture in picture mode")}</slot>
1135
+ `}var Dy=s=>{let e=s.mediaIsPip?K("exit picture in picture mode"):K("enter picture in picture mode");s.setAttribute("aria-label",e);},Aa=class extends De{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_IS_PIP,b.MEDIA_PIP_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),Dy(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_IS_PIP&&Dy(this);}get mediaPipUnavailable(){return me(this,b.MEDIA_PIP_UNAVAILABLE)}set mediaPipUnavailable(e){pe(this,b.MEDIA_PIP_UNAVAILABLE,e);}get mediaIsPip(){return ae(this,b.MEDIA_IS_PIP)}set mediaIsPip(e){le(this,b.MEDIA_IS_PIP,e);}handleClick(){let e=this.mediaIsPip?V.MEDIA_EXIT_PIP_REQUEST:V.MEDIA_ENTER_PIP_REQUEST;this.dispatchEvent(new A.CustomEvent(e,{composed:true,bubbles:true}));}};Aa.getSlotTemplateHTML=_L;Aa.getTooltipContentHTML=TL;A.customElements.get("media-pip-button")||A.customElements.define("media-pip-button",Aa);var SL=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},kn=(s,e,t)=>(SL(s,e,"read from private field"),t?t.call(s):e.get(s)),AL=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Ys,rm={RATES:"rates"},nm=[1,1.2,1.5,1.7,2],Fr=1;function IL(s){return `
1136
+ <style>
1137
+ :host {
1138
+ min-width: 5ch;
1139
+ padding: var(--media-button-padding, var(--media-control-padding, 10px 5px));
1140
+ }
1141
+ </style>
1142
+ <slot name="icon">${s.mediaplaybackrate||Fr}x</slot>
1143
+ `}function xL(){return K("Playback rate")}var Ia=class extends De{constructor(){var e;super(),AL(this,Ys,new Gs(this,rm.RATES,{defaultValue:nm})),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:Fr}x`;}static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_PLAYBACK_RATE,rm.RATES]}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),e===rm.RATES&&(kn(this,Ys).value=i),e===b.MEDIA_PLAYBACK_RATE){let r=i?+i:Number.NaN,n=Number.isNaN(r)?Fr:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",K("Playback rate {playbackRate}",{playbackRate:n}));}}get rates(){return kn(this,Ys)}set rates(e){e?Array.isArray(e)?kn(this,Ys).value=e.join(" "):typeof e=="string"&&(kn(this,Ys).value=e):kn(this,Ys).value="";}get mediaPlaybackRate(){return ye(this,b.MEDIA_PLAYBACK_RATE,Fr)}set mediaPlaybackRate(e){Ae(this,b.MEDIA_PLAYBACK_RATE,e);}handleClick(){var e,t;let i=Array.from(kn(this,Ys).values(),o=>+o).sort((o,a)=>o-a),r=(t=(e=i.find(o=>o>this.mediaPlaybackRate))!=null?e:i[0])!=null?t:Fr,n=new A.CustomEvent(V.MEDIA_PLAYBACK_RATE_REQUEST,{composed:true,bubbles:true,detail:r});this.dispatchEvent(n);}};Ys=new WeakMap;Ia.getSlotTemplateHTML=IL;Ia.getTooltipContentHTML=xL;A.customElements.get("media-playback-rate-button")||A.customElements.define("media-playback-rate-button",Ia);var LL=`<svg aria-hidden="true" viewBox="0 0 24 24">
1144
+ <path d="m6 21 15-9L6 3v18Z"/>
1145
+ </svg>`,RL=`<svg aria-hidden="true" viewBox="0 0 24 24">
1146
+ <path d="M6 20h4V4H6v16Zm8-16v16h4V4h-4Z"/>
1147
+ </svg>`;function kL(s){return `
1148
+ <style>
1149
+ :host([${b.MEDIA_PAUSED}]) slot[name=pause],
1150
+ :host(:not([${b.MEDIA_PAUSED}])) slot[name=play] {
1151
+ display: none !important;
1152
+ }
1153
+
1154
+ :host([${b.MEDIA_PAUSED}]) slot[name=tooltip-pause],
1155
+ :host(:not([${b.MEDIA_PAUSED}])) slot[name=tooltip-play] {
1156
+ display: none;
1157
+ }
1158
+ </style>
1159
+
1160
+ <slot name="icon">
1161
+ <slot name="play">${LL}</slot>
1162
+ <slot name="pause">${RL}</slot>
1163
+ </slot>
1164
+ `}function wL(){return `
1165
+ <slot name="tooltip-play">${K("Play")}</slot>
1166
+ <slot name="tooltip-pause">${K("Pause")}</slot>
1167
+ `}var My=s=>{let e=s.mediaPaused?K("play"):K("pause");s.setAttribute("aria-label",e);},xa=class extends De{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_PAUSED,b.MEDIA_ENDED]}connectedCallback(){super.connectedCallback(),My(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),(e===b.MEDIA_PAUSED||e===b.MEDIA_LANG)&&My(this);}get mediaPaused(){return ae(this,b.MEDIA_PAUSED)}set mediaPaused(e){le(this,b.MEDIA_PAUSED,e);}handleClick(){let e=this.mediaPaused?V.MEDIA_PLAY_REQUEST:V.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new A.CustomEvent(e,{composed:true,bubbles:true}));}};xa.getSlotTemplateHTML=kL;xa.getTooltipContentHTML=wL;A.customElements.get("media-play-button")||A.customElements.define("media-play-button",xa);var Wi={PLACEHOLDER_SRC:"placeholdersrc",SRC:"src"};function CL(s){return `
1168
+ <style>
1169
+ :host {
1170
+ pointer-events: none;
1171
+ display: var(--media-poster-image-display, inline-block);
1172
+ box-sizing: border-box;
1173
+ }
1174
+
1175
+ img {
1176
+ max-width: 100%;
1177
+ max-height: 100%;
1178
+ min-width: 100%;
1179
+ min-height: 100%;
1180
+ background-repeat: no-repeat;
1181
+ background-position: var(--media-poster-image-background-position, var(--media-object-position, center));
1182
+ background-size: var(--media-poster-image-background-size, var(--media-object-fit, contain));
1183
+ object-fit: var(--media-object-fit, contain);
1184
+ object-position: var(--media-object-position, center);
1185
+ }
1186
+ </style>
1187
+
1188
+ <img part="poster img" aria-hidden="true" id="image"/>
1189
+ `}var DL=s=>{s.style.removeProperty("background-image");},ML=(s,e)=>{s.style["background-image"]=`url('${e}')`;},La=class extends A.HTMLElement{static get observedAttributes(){return [Wi.PLACEHOLDER_SRC,Wi.SRC]}constructor(){if(super(),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}this.image=this.shadowRoot.querySelector("#image");}attributeChangedCallback(e,t,i){e===Wi.SRC&&(i==null?this.image.removeAttribute(Wi.SRC):this.image.setAttribute(Wi.SRC,i)),e===Wi.PLACEHOLDER_SRC&&(i==null?DL(this.image):ML(this.image,i));}get placeholderSrc(){return me(this,Wi.PLACEHOLDER_SRC)}set placeholderSrc(e){pe(this,Wi.SRC,e);}get src(){return me(this,Wi.SRC)}set src(e){pe(this,Wi.SRC,e);}};La.shadowRootOptions={mode:"open"};La.getTemplateHTML=CL;A.customElements.get("media-poster-image")||A.customElements.define("media-poster-image",La);var Py=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},PL=(s,e,t)=>(Py(s,e,"read from private field"),t?t.call(s):e.get(s)),OL=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},UL=(s,e,t,i)=>(Py(s,e,"write to private field"),e.set(s,t),t),Tc,om=class extends Kt{constructor(){super(),OL(this,Tc,void 0),UL(this,Tc,this.shadowRoot.querySelector("slot"));}static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_PREVIEW_CHAPTER,b.MEDIA_LANG]}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),(e===b.MEDIA_PREVIEW_CHAPTER||e===b.MEDIA_LANG)&&i!==t&&i!=null)if(PL(this,Tc).textContent=i,i!==""){let r=K("chapter: {chapterName}",{chapterName:i});this.setAttribute("aria-valuetext",r);}else this.removeAttribute("aria-valuetext");}get mediaPreviewChapter(){return me(this,b.MEDIA_PREVIEW_CHAPTER)}set mediaPreviewChapter(e){pe(this,b.MEDIA_PREVIEW_CHAPTER,e);}};Tc=new WeakMap;A.customElements.get("media-preview-chapter-display")||A.customElements.define("media-preview-chapter-display",om);var Oy=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Sc=(s,e,t)=>(Oy(s,e,"read from private field"),t?t.call(s):e.get(s)),NL=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Ac=(s,e,t,i)=>(Oy(s,e,"write to private field"),e.set(s,t),t),qi;function FL(s){return `
1190
+ <style>
1191
+ :host {
1192
+ box-sizing: border-box;
1193
+ display: var(--media-control-display, var(--media-preview-thumbnail-display, inline-block));
1194
+ overflow: hidden;
1195
+ }
1196
+
1197
+ img {
1198
+ display: none;
1199
+ position: relative;
1200
+ }
1201
+ </style>
1202
+ <img crossorigin loading="eager" decoding="async">
1203
+ `}var wn=class extends A.HTMLElement{constructor(){if(super(),NL(this,qi,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [ve.MEDIA_CONTROLLER,b.MEDIA_PREVIEW_IMAGE,b.MEDIA_PREVIEW_COORDS]}connectedCallback(){var e,t,i;let r=this.getAttribute(ve.MEDIA_CONTROLLER);r&&(Ac(this,qi,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(i=(t=Sc(this,qi))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=Sc(this,qi))==null?void 0:e.unassociateElement)==null||t.call(e,this),Ac(this,qi,null);}attributeChangedCallback(e,t,i){var r,n,o,a,l;[b.MEDIA_PREVIEW_IMAGE,b.MEDIA_PREVIEW_COORDS].includes(e)&&this.update(),e===ve.MEDIA_CONTROLLER&&(t&&((n=(r=Sc(this,qi))==null?void 0:r.unassociateElement)==null||n.call(r,this),Ac(this,qi,null)),i&&this.isConnected&&(Ac(this,qi,(o=this.getRootNode())==null?void 0:o.getElementById(i)),(l=(a=Sc(this,qi))==null?void 0:a.associateElement)==null||l.call(a,this)));}get mediaPreviewImage(){return me(this,b.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){pe(this,b.MEDIA_PREVIEW_IMAGE,e);}get mediaPreviewCoords(){let e=this.getAttribute(b.MEDIA_PREVIEW_COORDS);if(e)return e.split(/\s+/).map(t=>+t)}set mediaPreviewCoords(e){if(!e){this.removeAttribute(b.MEDIA_PREVIEW_COORDS);return}this.setAttribute(b.MEDIA_PREVIEW_COORDS,e.join(" "));}update(){let e=this.mediaPreviewCoords,t=this.mediaPreviewImage;if(!(e&&t))return;let[i,r,n,o]=e,a=t.split("#")[0],l=getComputedStyle(this),{maxWidth:d,maxHeight:c,minWidth:u,minHeight:h}=l,f=Math.min(parseInt(d)/n,parseInt(c)/o),m=Math.max(parseInt(u)/n,parseInt(h)/o),p=f<1,g=p?f:m>1?m:1,{style:E}=Ke(this.shadowRoot,":host"),y=Ke(this.shadowRoot,"img").style,_=this.shadowRoot.querySelector("img"),S=p?"min":"max";E.setProperty(`${S}-width`,"initial","important"),E.setProperty(`${S}-height`,"initial","important"),E.width=`${n*g}px`,E.height=`${o*g}px`;let L=()=>{y.width=`${this.imgWidth*g}px`,y.height=`${this.imgHeight*g}px`,y.display="block";};_.src!==a&&(_.onload=()=>{this.imgWidth=_.naturalWidth,this.imgHeight=_.naturalHeight,L();},_.src=a,L()),L(),y.transform=`translate(-${i*g}px, -${r*g}px)`;}};qi=new WeakMap;wn.shadowRootOptions={mode:"open"};wn.getTemplateHTML=FL;A.customElements.get("media-preview-thumbnail")||A.customElements.define("media-preview-thumbnail",wn);var Ic=wn;var Ny=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Uy=(s,e,t)=>(Ny(s,e,"read from private field"),t?t.call(s):e.get(s)),$L=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},BL=(s,e,t,i)=>(Ny(s,e,"write to private field"),e.set(s,t),t),Ra,am=class extends Kt{constructor(){super(),$L(this,Ra,void 0),BL(this,Ra,this.shadowRoot.querySelector("slot")),Uy(this,Ra).textContent=bi(0);}static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_PREVIEW_TIME]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_PREVIEW_TIME&&i!=null&&(Uy(this,Ra).textContent=bi(parseFloat(i)));}get mediaPreviewTime(){return ye(this,b.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){Ae(this,b.MEDIA_PREVIEW_TIME,e);}};Ra=new WeakMap;A.customElements.get("media-preview-time-display")||A.customElements.define("media-preview-time-display",am);var Cn={SEEK_OFFSET:"seekoffset"},lm=30,HL=s=>`
1204
+ <svg aria-hidden="true" viewBox="0 0 20 24">
1205
+ <defs>
1206
+ <style>.text{font-size:8px;font-family:Arial-BoldMT, Arial;font-weight:700;}</style>
1207
+ </defs>
1208
+ <text class="text value" transform="translate(2.18 19.87)">${s}</text>
1209
+ <path d="M10 6V3L4.37 7 10 10.94V8a5.54 5.54 0 0 1 1.9 10.48v2.12A7.5 7.5 0 0 0 10 6Z"/>
1210
+ </svg>`;function GL(s,e){return `
1211
+ <slot name="icon">${HL(e.seekOffset)}</slot>
1212
+ `}function KL(){return K("Seek backward")}var VL=0,ka=class extends De{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_CURRENT_TIME,Cn.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=ye(this,Cn.SEEK_OFFSET,lm);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===Cn.SEEK_OFFSET&&(this.seekOffset=ye(this,Cn.SEEK_OFFSET,lm));}get seekOffset(){return ye(this,Cn.SEEK_OFFSET,lm)}set seekOffset(e){Ae(this,Cn.SEEK_OFFSET,e),this.setAttribute("aria-label",K("seek back {seekOffset} seconds",{seekOffset:this.seekOffset})),Rd(kd(this,"icon"),this.seekOffset);}get mediaCurrentTime(){return ye(this,b.MEDIA_CURRENT_TIME,VL)}set mediaCurrentTime(e){Ae(this,b.MEDIA_CURRENT_TIME,e);}handleClick(){let e=Math.max(this.mediaCurrentTime-this.seekOffset,0),t=new A.CustomEvent(V.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:e});this.dispatchEvent(t);}};ka.getSlotTemplateHTML=GL;ka.getTooltipContentHTML=KL;A.customElements.get("media-seek-backward-button")||A.customElements.define("media-seek-backward-button",ka);var Dn={SEEK_OFFSET:"seekoffset"},dm=30,WL=s=>`
1213
+ <svg aria-hidden="true" viewBox="0 0 20 24">
1214
+ <defs>
1215
+ <style>.text{font-size:8px;font-family:Arial-BoldMT, Arial;font-weight:700;}</style>
1216
+ </defs>
1217
+ <text class="text value" transform="translate(8.9 19.87)">${s}</text>
1218
+ <path d="M10 6V3l5.61 4L10 10.94V8a5.54 5.54 0 0 0-1.9 10.48v2.12A7.5 7.5 0 0 1 10 6Z"/>
1219
+ </svg>`;function qL(s,e){return `
1220
+ <slot name="icon">${WL(e.seekOffset)}</slot>
1221
+ `}function jL(){return K("Seek forward")}var YL=0,wa=class extends De{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_CURRENT_TIME,Dn.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=ye(this,Dn.SEEK_OFFSET,dm);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===Dn.SEEK_OFFSET&&(this.seekOffset=ye(this,Dn.SEEK_OFFSET,dm));}get seekOffset(){return ye(this,Dn.SEEK_OFFSET,dm)}set seekOffset(e){Ae(this,Dn.SEEK_OFFSET,e),this.setAttribute("aria-label",K("seek forward {seekOffset} seconds",{seekOffset:this.seekOffset})),Rd(kd(this,"icon"),this.seekOffset);}get mediaCurrentTime(){return ye(this,b.MEDIA_CURRENT_TIME,YL)}set mediaCurrentTime(e){Ae(this,b.MEDIA_CURRENT_TIME,e);}handleClick(){let e=this.mediaCurrentTime+this.seekOffset,t=new A.CustomEvent(V.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:e});this.dispatchEvent(t);}};wa.getSlotTemplateHTML=qL;wa.getTooltipContentHTML=jL;A.customElements.get("media-seek-forward-button")||A.customElements.define("media-seek-forward-button",wa);var By=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},cm=(s,e,t)=>(By(s,e,"read from private field"),t?t.call(s):e.get(s)),zL=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},QL=(s,e,t,i)=>(By(s,e,"write to private field"),e.set(s,t),t),Mn,$r={REMAINING:"remaining",SHOW_DURATION:"showduration",NO_TOGGLE:"notoggle"},Fy=[...Object.values($r),b.MEDIA_CURRENT_TIME,b.MEDIA_DURATION,b.MEDIA_SEEKABLE],$y=["Enter"," "],XL="&nbsp;/&nbsp;",um=(s,{timesSep:e=XL}={})=>{var t,i;let r=(t=s.mediaCurrentTime)!=null?t:0,[,n]=(i=s.mediaSeekable)!=null?i:[],o=0;Number.isFinite(s.mediaDuration)?o=s.mediaDuration:Number.isFinite(n)&&(o=n);let a=s.remaining?bi(0-(o-r)):bi(r);return s.showDuration?`${a}${e}${bi(o)}`:a},ZL="video not loaded, unknown time.",JL=s=>{var e;let t=s.mediaCurrentTime,[,i]=(e=s.mediaSeekable)!=null?e:[],r=null;if(Number.isFinite(s.mediaDuration)?r=s.mediaDuration:Number.isFinite(i)&&(r=i),t==null||r===null){s.setAttribute("aria-valuetext",ZL);return}let n=s.remaining?Ar(0-(r-t)):Ar(t);if(!s.showDuration){s.setAttribute("aria-valuetext",n);return}let o=Ar(r),a=`${n} of ${o}`;s.setAttribute("aria-valuetext",a);};function eR(s,e){return `
1222
+ <slot>${um(e)}</slot>
1223
+ `}var xc=class extends Kt{constructor(){super(),zL(this,Mn,void 0),QL(this,Mn,this.shadowRoot.querySelector("slot")),cm(this,Mn).innerHTML=`${um(this)}`;}static get observedAttributes(){return [...super.observedAttributes,...Fy,"disabled"]}connectedCallback(){let{style:e}=Ke(this.shadowRoot,":host(:hover:not([notoggle]))");e.setProperty("cursor","var(--media-cursor, pointer)"),e.setProperty("background","var(--media-control-hover-background, rgba(50 50 70 / .7))"),this.hasAttribute("disabled")||this.enable(),this.setAttribute("role","progressbar"),this.setAttribute("aria-label",K("playback time"));let t=i=>{let{key:r}=i;if(!$y.includes(r)){this.removeEventListener("keyup",t);return}this.toggleTimeDisplay();};this.addEventListener("keydown",i=>{let{metaKey:r,altKey:n,key:o}=i;if(r||n||!$y.includes(o)){this.removeEventListener("keyup",t);return}this.addEventListener("keyup",t);}),this.addEventListener("click",this.toggleTimeDisplay),super.connectedCallback();}toggleTimeDisplay(){this.noToggle||(this.hasAttribute("remaining")?this.removeAttribute("remaining"):this.setAttribute("remaining",""));}disconnectedCallback(){this.disable(),super.disconnectedCallback();}attributeChangedCallback(e,t,i){Fy.includes(e)?this.update():e==="disabled"&&i!==t&&(i==null?this.enable():this.disable()),super.attributeChangedCallback(e,t,i);}enable(){this.tabIndex=0;}disable(){this.tabIndex=-1;}get remaining(){return ae(this,$r.REMAINING)}set remaining(e){le(this,$r.REMAINING,e);}get showDuration(){return ae(this,$r.SHOW_DURATION)}set showDuration(e){le(this,$r.SHOW_DURATION,e);}get noToggle(){return ae(this,$r.NO_TOGGLE)}set noToggle(e){le(this,$r.NO_TOGGLE,e);}get mediaDuration(){return ye(this,b.MEDIA_DURATION)}set mediaDuration(e){Ae(this,b.MEDIA_DURATION,e);}get mediaCurrentTime(){return ye(this,b.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){Ae(this,b.MEDIA_CURRENT_TIME,e);}get mediaSeekable(){let e=this.getAttribute(b.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(b.MEDIA_SEEKABLE);return}this.setAttribute(b.MEDIA_SEEKABLE,e.join(":"));}update(){let e=um(this);JL(this),e!==cm(this,Mn).innerHTML&&(cm(this,Mn).innerHTML=e);}};Mn=new WeakMap;xc.getSlotTemplateHTML=eR;A.customElements.get("media-time-display")||A.customElements.define("media-time-display",xc);var Hy=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},_t=(s,e,t)=>(Hy(s,e,"read from private field"),e.get(s)),ji=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Zt=(s,e,t,i)=>(Hy(s,e,"write to private field"),e.set(s,t),t),tR=(s,e,t,i)=>({set _(r){Zt(s,e,r);},get _(){return _t(s,e)}}),Pn,Lc,On,Ca,Rc,kc,wc,Un,Br,Cc,Dc=class{constructor(e,t,i){ji(this,Pn,void 0),ji(this,Lc,void 0),ji(this,On,void 0),ji(this,Ca,void 0),ji(this,Rc,void 0),ji(this,kc,void 0),ji(this,wc,void 0),ji(this,Un,void 0),ji(this,Br,0),ji(this,Cc,(r=performance.now())=>{Zt(this,Br,requestAnimationFrame(_t(this,Cc))),Zt(this,Ca,performance.now()-_t(this,On));let n=1e3/this.fps;if(_t(this,Ca)>n){Zt(this,On,r-_t(this,Ca)%n);let o=1e3/((r-_t(this,Lc))/++tR(this,Rc)._),a=(r-_t(this,kc))/1e3/this.duration,l=_t(this,wc)+a*this.playbackRate;l-_t(this,Pn).valueAsNumber>0?Zt(this,Un,this.playbackRate/this.duration/o):(Zt(this,Un,.995*_t(this,Un)),l=_t(this,Pn).valueAsNumber+_t(this,Un)),this.callback(l);}}),Zt(this,Pn,e),this.callback=t,this.fps=i;}start(){_t(this,Br)===0&&(Zt(this,On,performance.now()),Zt(this,Lc,_t(this,On)),Zt(this,Rc,0),_t(this,Cc).call(this));}stop(){_t(this,Br)!==0&&(cancelAnimationFrame(_t(this,Br)),Zt(this,Br,0));}update({start:e,duration:t,playbackRate:i}){let r=e-_t(this,Pn).valueAsNumber,n=Math.abs(t-this.duration);(r>0||r<-0.03||n>=.5)&&this.callback(e),Zt(this,wc,e),Zt(this,kc,performance.now()),this.duration=t,this.playbackRate=i;}};Pn=new WeakMap;Lc=new WeakMap;On=new WeakMap;Ca=new WeakMap;Rc=new WeakMap;kc=new WeakMap;wc=new WeakMap;Un=new WeakMap;Br=new WeakMap;Cc=new WeakMap;var pm=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},ot=(s,e,t)=>(pm(s,e,"read from private field"),t?t.call(s):e.get(s)),pt=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},ui=(s,e,t,i)=>(pm(s,e,"write to private field"),e.set(s,t),t),Dt=(s,e,t)=>(pm(s,e,"access private method"),t),Nn,Hr,Oc,Ma,Uc,Pc,Pa,Oa,Fn,$n,Bn,Da,gm,Gy,hm,Nc,vm,Fc,Em,$c,ym,fm,Ky,Ua,Bc,mm,Vy,iR="video not loaded, unknown time.",sR=s=>{let e=s.range,t=Ar(+Wy(s)),i=Ar(+s.mediaSeekableEnd),r=t&&i?`${t} of ${i}`:iR;e.setAttribute("aria-valuetext",r);};function rR(s){return `
1224
+ <style>
1225
+ :host {
1226
+ --media-box-border-radius: 4px;
1227
+ --media-box-padding-left: 10px;
1228
+ --media-box-padding-right: 10px;
1229
+ --media-preview-border-radius: var(--media-box-border-radius);
1230
+ --media-box-arrow-offset: var(--media-box-border-radius);
1231
+ --_control-background: var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7)));
1232
+ --_preview-background: var(--media-preview-background, var(--_control-background));
1233
+
1234
+
1235
+ contain: layout;
1236
+ }
1237
+
1238
+ #buffered {
1239
+ background: var(--media-time-range-buffered-color, rgb(255 255 255 / .4));
1240
+ position: absolute;
1241
+ height: 100%;
1242
+ will-change: width;
1243
+ }
1244
+
1245
+ #preview-rail,
1246
+ #current-rail {
1247
+ width: 100%;
1248
+ position: absolute;
1249
+ left: 0;
1250
+ bottom: 100%;
1251
+ pointer-events: none;
1252
+ will-change: transform;
1253
+ }
1254
+
1255
+ [part~="box"] {
1256
+ width: min-content;
1257
+
1258
+ position: absolute;
1259
+ bottom: 100%;
1260
+ flex-direction: column;
1261
+ align-items: center;
1262
+ transform: translateX(-50%);
1263
+ }
1264
+
1265
+ [part~="current-box"] {
1266
+ display: var(--media-current-box-display, var(--media-box-display, flex));
1267
+ margin: var(--media-current-box-margin, var(--media-box-margin, 0 0 5px));
1268
+ visibility: hidden;
1269
+ }
1270
+
1271
+ [part~="preview-box"] {
1272
+ display: var(--media-preview-box-display, var(--media-box-display, flex));
1273
+ margin: var(--media-preview-box-margin, var(--media-box-margin, 0 0 5px));
1274
+ transition-property: var(--media-preview-transition-property, visibility, opacity);
1275
+ transition-duration: var(--media-preview-transition-duration-out, .25s);
1276
+ transition-delay: var(--media-preview-transition-delay-out, 0s);
1277
+ visibility: hidden;
1278
+ opacity: 0;
1279
+ }
1280
+
1281
+ :host(:is([${b.MEDIA_PREVIEW_IMAGE}], [${b.MEDIA_PREVIEW_TIME}])[dragging]) [part~="preview-box"] {
1282
+ transition-duration: var(--media-preview-transition-duration-in, .5s);
1283
+ transition-delay: var(--media-preview-transition-delay-in, .25s);
1284
+ visibility: visible;
1285
+ opacity: 1;
1286
+ }
1287
+
1288
+ @media (hover: hover) {
1289
+ :host(:is([${b.MEDIA_PREVIEW_IMAGE}], [${b.MEDIA_PREVIEW_TIME}]):hover) [part~="preview-box"] {
1290
+ transition-duration: var(--media-preview-transition-duration-in, .5s);
1291
+ transition-delay: var(--media-preview-transition-delay-in, .25s);
1292
+ visibility: visible;
1293
+ opacity: 1;
1294
+ }
1295
+ }
1296
+
1297
+ media-preview-thumbnail,
1298
+ ::slotted(media-preview-thumbnail) {
1299
+ visibility: hidden;
1300
+
1301
+ transition: visibility 0s .25s;
1302
+ transition-delay: calc(var(--media-preview-transition-delay-out, 0s) + var(--media-preview-transition-duration-out, .25s));
1303
+ background: var(--media-preview-thumbnail-background, var(--_preview-background));
1304
+ box-shadow: var(--media-preview-thumbnail-box-shadow, 0 0 4px rgb(0 0 0 / .2));
1305
+ max-width: var(--media-preview-thumbnail-max-width, 180px);
1306
+ max-height: var(--media-preview-thumbnail-max-height, 160px);
1307
+ min-width: var(--media-preview-thumbnail-min-width, 120px);
1308
+ min-height: var(--media-preview-thumbnail-min-height, 80px);
1309
+ border: var(--media-preview-thumbnail-border);
1310
+ border-radius: var(--media-preview-thumbnail-border-radius,
1311
+ var(--media-preview-border-radius) var(--media-preview-border-radius) 0 0);
1312
+ }
1313
+
1314
+ :host([${b.MEDIA_PREVIEW_IMAGE}][dragging]) media-preview-thumbnail,
1315
+ :host([${b.MEDIA_PREVIEW_IMAGE}][dragging]) ::slotted(media-preview-thumbnail) {
1316
+ transition-delay: var(--media-preview-transition-delay-in, .25s);
1317
+ visibility: visible;
1318
+ }
1319
+
1320
+ @media (hover: hover) {
1321
+ :host([${b.MEDIA_PREVIEW_IMAGE}]:hover) media-preview-thumbnail,
1322
+ :host([${b.MEDIA_PREVIEW_IMAGE}]:hover) ::slotted(media-preview-thumbnail) {
1323
+ transition-delay: var(--media-preview-transition-delay-in, .25s);
1324
+ visibility: visible;
1325
+ }
1326
+
1327
+ :host([${b.MEDIA_PREVIEW_TIME}]:hover) {
1328
+ --media-time-range-hover-display: block;
1329
+ }
1330
+ }
1331
+
1332
+ media-preview-chapter-display,
1333
+ ::slotted(media-preview-chapter-display) {
1334
+ font-size: var(--media-font-size, 13px);
1335
+ line-height: 17px;
1336
+ min-width: 0;
1337
+ visibility: hidden;
1338
+
1339
+ transition: min-width 0s, border-radius 0s, margin 0s, padding 0s, visibility 0s;
1340
+ transition-delay: calc(var(--media-preview-transition-delay-out, 0s) + var(--media-preview-transition-duration-out, .25s));
1341
+ background: var(--media-preview-chapter-background, var(--_preview-background));
1342
+ border-radius: var(--media-preview-chapter-border-radius,
1343
+ var(--media-preview-border-radius) var(--media-preview-border-radius)
1344
+ var(--media-preview-border-radius) var(--media-preview-border-radius));
1345
+ padding: var(--media-preview-chapter-padding, 3.5px 9px);
1346
+ margin: var(--media-preview-chapter-margin, 0 0 5px);
1347
+ text-shadow: var(--media-preview-chapter-text-shadow, 0 0 4px rgb(0 0 0 / .75));
1348
+ }
1349
+
1350
+ :host([${b.MEDIA_PREVIEW_IMAGE}]) media-preview-chapter-display,
1351
+ :host([${b.MEDIA_PREVIEW_IMAGE}]) ::slotted(media-preview-chapter-display) {
1352
+ transition-delay: var(--media-preview-transition-delay-in, .25s);
1353
+ border-radius: var(--media-preview-chapter-border-radius, 0);
1354
+ padding: var(--media-preview-chapter-padding, 3.5px 9px 0);
1355
+ margin: var(--media-preview-chapter-margin, 0);
1356
+ min-width: 100%;
1357
+ }
1358
+
1359
+ media-preview-chapter-display[${b.MEDIA_PREVIEW_CHAPTER}],
1360
+ ::slotted(media-preview-chapter-display[${b.MEDIA_PREVIEW_CHAPTER}]) {
1361
+ visibility: visible;
1362
+ }
1363
+
1364
+ media-preview-chapter-display:not([aria-valuetext]),
1365
+ ::slotted(media-preview-chapter-display:not([aria-valuetext])) {
1366
+ display: none;
1367
+ }
1368
+
1369
+ media-preview-time-display,
1370
+ ::slotted(media-preview-time-display),
1371
+ media-time-display,
1372
+ ::slotted(media-time-display) {
1373
+ font-size: var(--media-font-size, 13px);
1374
+ line-height: 17px;
1375
+ min-width: 0;
1376
+
1377
+ transition: min-width 0s, border-radius 0s;
1378
+ transition-delay: calc(var(--media-preview-transition-delay-out, 0s) + var(--media-preview-transition-duration-out, .25s));
1379
+ background: var(--media-preview-time-background, var(--_preview-background));
1380
+ border-radius: var(--media-preview-time-border-radius,
1381
+ var(--media-preview-border-radius) var(--media-preview-border-radius)
1382
+ var(--media-preview-border-radius) var(--media-preview-border-radius));
1383
+ padding: var(--media-preview-time-padding, 3.5px 9px);
1384
+ margin: var(--media-preview-time-margin, 0);
1385
+ text-shadow: var(--media-preview-time-text-shadow, 0 0 4px rgb(0 0 0 / .75));
1386
+ transform: translateX(min(
1387
+ max(calc(50% - var(--_box-width) / 2),
1388
+ calc(var(--_box-shift, 0))),
1389
+ calc(var(--_box-width) / 2 - 50%)
1390
+ ));
1391
+ }
1392
+
1393
+ :host([${b.MEDIA_PREVIEW_IMAGE}]) media-preview-time-display,
1394
+ :host([${b.MEDIA_PREVIEW_IMAGE}]) ::slotted(media-preview-time-display) {
1395
+ transition-delay: var(--media-preview-transition-delay-in, .25s);
1396
+ border-radius: var(--media-preview-time-border-radius,
1397
+ 0 0 var(--media-preview-border-radius) var(--media-preview-border-radius));
1398
+ min-width: 100%;
1399
+ }
1400
+
1401
+ :host([${b.MEDIA_PREVIEW_TIME}]:hover) {
1402
+ --media-time-range-hover-display: block;
1403
+ }
1404
+
1405
+ [part~="arrow"],
1406
+ ::slotted([part~="arrow"]) {
1407
+ display: var(--media-box-arrow-display, inline-block);
1408
+ transform: translateX(min(
1409
+ max(calc(50% - var(--_box-width) / 2 + var(--media-box-arrow-offset)),
1410
+ calc(var(--_box-shift, 0))),
1411
+ calc(var(--_box-width) / 2 - 50% - var(--media-box-arrow-offset))
1412
+ ));
1413
+
1414
+ border-color: transparent;
1415
+ border-top-color: var(--media-box-arrow-background, var(--_control-background));
1416
+ border-width: var(--media-box-arrow-border-width,
1417
+ var(--media-box-arrow-height, 5px) var(--media-box-arrow-width, 6px) 0);
1418
+ border-style: solid;
1419
+ justify-content: center;
1420
+ height: 0;
1421
+ }
1422
+ </style>
1423
+ <div id="preview-rail">
1424
+ <slot name="preview" part="box preview-box">
1425
+ <media-preview-thumbnail>
1426
+ <template shadowrootmode="${Ic.shadowRootOptions.mode}">
1427
+ ${Ic.getTemplateHTML({})}
1428
+ </template>
1429
+ </media-preview-thumbnail>
1430
+ <media-preview-chapter-display></media-preview-chapter-display>
1431
+ <media-preview-time-display></media-preview-time-display>
1432
+ <slot name="preview-arrow"><div part="arrow"></div></slot>
1433
+ </slot>
1434
+ </div>
1435
+ <div id="current-rail">
1436
+ <slot name="current" part="box current-box">
1437
+
1438
+ </slot>
1439
+ </div>
1440
+ `}var Mc=(s,e=s.mediaCurrentTime)=>{let t=Number.isFinite(s.mediaSeekableStart)?s.mediaSeekableStart:0,i=Number.isFinite(s.mediaDuration)?s.mediaDuration:s.mediaSeekableEnd;if(Number.isNaN(i))return 0;let r=(e-t)/(i-t);return Math.max(0,Math.min(r,1))},Wy=(s,e=s.range.valueAsNumber)=>{let t=Number.isFinite(s.mediaSeekableStart)?s.mediaSeekableStart:0,i=Number.isFinite(s.mediaDuration)?s.mediaDuration:s.mediaSeekableEnd;return Number.isNaN(i)?0:e*(i-t)+t},Na=class extends Hi{constructor(){super(),pt(this,Bn),pt(this,gm),pt(this,Nc),pt(this,Fc),pt(this,$c),pt(this,fm),pt(this,Ua),pt(this,mm),pt(this,Nn,void 0),pt(this,Hr,void 0),pt(this,Oc,void 0),pt(this,Ma,void 0),pt(this,Uc,void 0),pt(this,Pc,void 0),pt(this,Pa,void 0),pt(this,Oa,void 0),pt(this,Fn,void 0),pt(this,$n,void 0),pt(this,hm,i=>{this.dragging||(hn(i)&&(this.range.valueAsNumber=i),ot(this,$n)||this.updateBar());}),this.shadowRoot.querySelector("#track").insertAdjacentHTML("afterbegin",'<div id="buffered" part="buffered"></div>'),ui(this,Oc,this.shadowRoot.querySelectorAll('[part~="box"]')),ui(this,Uc,this.shadowRoot.querySelector('[part~="preview-box"]')),ui(this,Pc,this.shadowRoot.querySelector('[part~="current-box"]'));let t=getComputedStyle(this);ui(this,Pa,parseInt(t.getPropertyValue("--media-box-padding-left"))),ui(this,Oa,parseInt(t.getPropertyValue("--media-box-padding-right"))),ui(this,Hr,new Dc(this.range,ot(this,hm),60));}static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_PAUSED,b.MEDIA_DURATION,b.MEDIA_SEEKABLE,b.MEDIA_CURRENT_TIME,b.MEDIA_PREVIEW_IMAGE,b.MEDIA_PREVIEW_TIME,b.MEDIA_PREVIEW_CHAPTER,b.MEDIA_BUFFERED,b.MEDIA_PLAYBACK_RATE,b.MEDIA_LOADING,b.MEDIA_ENDED]}connectedCallback(){var e;super.connectedCallback(),this.range.setAttribute("aria-label",K("seek")),Dt(this,Bn,Da).call(this),ui(this,Nn,this.getRootNode()),(e=ot(this,Nn))==null||e.addEventListener("transitionstart",this);}disconnectedCallback(){var e;super.disconnectedCallback(),Dt(this,Bn,Da).call(this),(e=ot(this,Nn))==null||e.removeEventListener("transitionstart",this),ui(this,Nn,null);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),t!=i&&(e===b.MEDIA_CURRENT_TIME||e===b.MEDIA_PAUSED||e===b.MEDIA_ENDED||e===b.MEDIA_LOADING||e===b.MEDIA_DURATION||e===b.MEDIA_SEEKABLE?(ot(this,Hr).update({start:Mc(this),duration:this.mediaSeekableEnd-this.mediaSeekableStart,playbackRate:this.mediaPlaybackRate}),Dt(this,Bn,Da).call(this),sR(this)):e===b.MEDIA_BUFFERED&&this.updateBufferedBar(),(e===b.MEDIA_DURATION||e===b.MEDIA_SEEKABLE)&&(this.mediaChaptersCues=ot(this,Fn),this.updateBar()));}get mediaChaptersCues(){return ot(this,Fn)}set mediaChaptersCues(e){var t;ui(this,Fn,e),this.updateSegments((t=ot(this,Fn))==null?void 0:t.map(i=>({start:Mc(this,i.startTime),end:Mc(this,i.endTime)})));}get mediaPaused(){return ae(this,b.MEDIA_PAUSED)}set mediaPaused(e){le(this,b.MEDIA_PAUSED,e);}get mediaLoading(){return ae(this,b.MEDIA_LOADING)}set mediaLoading(e){le(this,b.MEDIA_LOADING,e);}get mediaDuration(){return ye(this,b.MEDIA_DURATION)}set mediaDuration(e){Ae(this,b.MEDIA_DURATION,e);}get mediaCurrentTime(){return ye(this,b.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){Ae(this,b.MEDIA_CURRENT_TIME,e);}get mediaPlaybackRate(){return ye(this,b.MEDIA_PLAYBACK_RATE,1)}set mediaPlaybackRate(e){Ae(this,b.MEDIA_PLAYBACK_RATE,e);}get mediaBuffered(){let e=this.getAttribute(b.MEDIA_BUFFERED);return e?e.split(" ").map(t=>t.split(":").map(i=>+i)):[]}set mediaBuffered(e){if(!e){this.removeAttribute(b.MEDIA_BUFFERED);return}let t=e.map(i=>i.join(":")).join(" ");this.setAttribute(b.MEDIA_BUFFERED,t);}get mediaSeekable(){let e=this.getAttribute(b.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(b.MEDIA_SEEKABLE);return}this.setAttribute(b.MEDIA_SEEKABLE,e.join(":"));}get mediaSeekableEnd(){var e;let[,t=this.mediaDuration]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaSeekableStart(){var e;let[t=0]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaPreviewImage(){return me(this,b.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){pe(this,b.MEDIA_PREVIEW_IMAGE,e);}get mediaPreviewTime(){return ye(this,b.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){Ae(this,b.MEDIA_PREVIEW_TIME,e);}get mediaEnded(){return ae(this,b.MEDIA_ENDED)}set mediaEnded(e){le(this,b.MEDIA_ENDED,e);}updateBar(){super.updateBar(),this.updateBufferedBar(),this.updateCurrentBox();}updateBufferedBar(){var e;let t=this.mediaBuffered;if(!t.length)return;let i;if(this.mediaEnded)i=1;else {let n=this.mediaCurrentTime,[,o=this.mediaSeekableStart]=(e=t.find(([a,l])=>a<=n&&n<=l))!=null?e:[];i=Mc(this,o);}let{style:r}=Ke(this.shadowRoot,"#buffered");r.setProperty("width",`${i*100}%`);}updateCurrentBox(){if(!this.shadowRoot.querySelector('slot[name="current"]').assignedElements().length)return;let t=Ke(this.shadowRoot,"#current-rail"),i=Ke(this.shadowRoot,'[part~="current-box"]'),r=Dt(this,Nc,vm).call(this,ot(this,Pc)),n=Dt(this,Fc,Em).call(this,r,this.range.valueAsNumber),o=Dt(this,$c,ym).call(this,r,this.range.valueAsNumber);t.style.transform=`translateX(${n})`,t.style.setProperty("--_range-width",`${r.range.width}`),i.style.setProperty("--_box-shift",`${o}`),i.style.setProperty("--_box-width",`${r.box.width}px`),i.style.setProperty("visibility","initial");}handleEvent(e){switch(super.handleEvent(e),e.type){case "input":Dt(this,mm,Vy).call(this);break;case "pointermove":Dt(this,fm,Ky).call(this,e);break;case "pointerup":ot(this,$n)&&ui(this,$n,false);break;case "pointerdown":ui(this,$n,true);break;case "pointerleave":Dt(this,Ua,Bc).call(this,null);break;case "transitionstart":Nt(e.target,this)&&setTimeout(()=>Dt(this,Bn,Da).call(this),0);break}}};Nn=new WeakMap;Hr=new WeakMap;Oc=new WeakMap;Ma=new WeakMap;Uc=new WeakMap;Pc=new WeakMap;Pa=new WeakMap;Oa=new WeakMap;Fn=new WeakMap;$n=new WeakMap;Bn=new WeakSet;Da=function(){Dt(this,gm,Gy).call(this)?ot(this,Hr).start():ot(this,Hr).stop();};gm=new WeakSet;Gy=function(){return this.isConnected&&!this.mediaPaused&&!this.mediaLoading&&!this.mediaEnded&&this.mediaSeekableEnd>0&&wd(this)};hm=new WeakMap;Nc=new WeakSet;vm=function(s){var e;let i=((e=this.getAttribute("bounds")?Pi(this,`#${this.getAttribute("bounds")}`):this.parentElement)!=null?e:this).getBoundingClientRect(),r=this.range.getBoundingClientRect(),n=s.offsetWidth,o=-(r.left-i.left-n/2),a=i.right-r.left-n/2;return {box:{width:n,min:o,max:a},bounds:i,range:r}};Fc=new WeakSet;Em=function(s,e){let t=`${e*100}%`,{width:i,min:r,max:n}=s.box;if(!i)return t;if(Number.isNaN(r)||(t=`max(${`calc(1 / var(--_range-width) * 100 * ${r}% + var(--media-box-padding-left))`}, ${t})`),!Number.isNaN(n)){let a=`calc(1 / var(--_range-width) * 100 * ${n}% - var(--media-box-padding-right))`;t=`min(${t}, ${a})`;}return t};$c=new WeakSet;ym=function(s,e){let{width:t,min:i,max:r}=s.box,n=e*s.range.width;if(n<i+ot(this,Pa)){let o=s.range.left-s.bounds.left-ot(this,Pa);return `${n-t/2+o}px`}if(n>r-ot(this,Oa)){let o=s.bounds.right-s.range.right-ot(this,Oa);return `${n+t/2-o-s.range.width}px`}return 0};fm=new WeakSet;Ky=function(s){let e=[...ot(this,Oc)].some(c=>s.composedPath().includes(c));if(!this.dragging&&(e||!s.composedPath().includes(this))){Dt(this,Ua,Bc).call(this,null);return}let t=this.mediaSeekableEnd;if(!t)return;let i=Ke(this.shadowRoot,"#preview-rail"),r=Ke(this.shadowRoot,'[part~="preview-box"]'),n=Dt(this,Nc,vm).call(this,ot(this,Uc)),o=(s.clientX-n.range.left)/n.range.width;o=Math.max(0,Math.min(1,o));let a=Dt(this,Fc,Em).call(this,n,o),l=Dt(this,$c,ym).call(this,n,o);i.style.transform=`translateX(${a})`,i.style.setProperty("--_range-width",`${n.range.width}`),r.style.setProperty("--_box-shift",`${l}`),r.style.setProperty("--_box-width",`${n.box.width}px`);let d=Math.round(ot(this,Ma))-Math.round(o*t);Math.abs(d)<1&&o>.01&&o<.99||(ui(this,Ma,o*t),Dt(this,Ua,Bc).call(this,ot(this,Ma)));};Ua=new WeakSet;Bc=function(s){this.dispatchEvent(new A.CustomEvent(V.MEDIA_PREVIEW_REQUEST,{composed:true,bubbles:true,detail:s}));};mm=new WeakSet;Vy=function(){ot(this,Hr).stop();let s=Wy(this);this.dispatchEvent(new A.CustomEvent(V.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:s}));};Na.shadowRootOptions={mode:"open"};Na.getContainerTemplateHTML=rR;A.customElements.get("media-time-range")||A.customElements.define("media-time-range",Na);var nR=1,oR=s=>s.mediaMuted?0:s.mediaVolume,aR=s=>`${Math.round(s*100)}%`,bm=class extends Hi{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_VOLUME,b.MEDIA_MUTED,b.MEDIA_VOLUME_UNAVAILABLE]}constructor(){super(),this.range.addEventListener("input",()=>{let e=this.range.value,t=new A.CustomEvent(V.MEDIA_VOLUME_REQUEST,{composed:true,bubbles:true,detail:e});this.dispatchEvent(t);});}connectedCallback(){super.connectedCallback(),this.range.setAttribute("aria-label",K("volume"));}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),(e===b.MEDIA_VOLUME||e===b.MEDIA_MUTED)&&(this.range.valueAsNumber=oR(this),this.range.setAttribute("aria-valuetext",aR(this.range.valueAsNumber)),this.updateBar());}get mediaVolume(){return ye(this,b.MEDIA_VOLUME,nR)}set mediaVolume(e){Ae(this,b.MEDIA_VOLUME,e);}get mediaMuted(){return ae(this,b.MEDIA_MUTED)}set mediaMuted(e){le(this,b.MEDIA_MUTED,e);}get mediaVolumeUnavailable(){return me(this,b.MEDIA_VOLUME_UNAVAILABLE)}set mediaVolumeUnavailable(e){pe(this,b.MEDIA_VOLUME_UNAVAILABLE,e);}};A.customElements.get("media-volume-range")||A.customElements.define("media-volume-range",bm);function lR(s){return `
1441
+ <style>
1442
+ :host {
1443
+ min-width: 4ch;
1444
+ padding: var(--media-button-padding, var(--media-control-padding, 10px 5px));
1445
+ width: 100%;
1446
+ display: grid;
1447
+ grid-template-columns: 1fr auto;
1448
+ gap: 1rem;
1449
+ font-weight: var(--media-button-font-weight, normal);
1450
+ }
1451
+
1452
+ #checked-indicator {
1453
+ display: none;
1454
+ }
1455
+
1456
+ :host([${b.MEDIA_LOOP}]) #checked-indicator {
1457
+ display: block;
1458
+ }
1459
+ </style>
1460
+
1461
+ <span id="icon">
1462
+ </span>
1463
+
1464
+ <div id="checked-indicator">
1465
+ <svg aria-hidden="true" viewBox="0 1 24 24" part="checked-indicator indicator">
1466
+ <path d="m10 15.17 9.193-9.191 1.414 1.414-10.606 10.606-6.364-6.364 1.414-1.414 4.95 4.95Z"/>
1467
+ </svg>
1468
+ </div>
1469
+ `}function dR(){return K("Loop")}var Fa=class extends De{constructor(){super(...arguments),this.container=null;}static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_LOOP]}connectedCallback(){var e;super.connectedCallback(),this.container=((e=this.shadowRoot)==null?void 0:e.querySelector("#icon"))||null,this.container&&(this.container.textContent=K("Loop"));}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_LOOP&&this.container&&this.setAttribute("aria-checked",this.mediaLoop?"true":"false");}get mediaLoop(){return ae(this,b.MEDIA_LOOP)}set mediaLoop(e){le(this,b.MEDIA_LOOP,e);}handleClick(){let e=!this.mediaLoop,t=new A.CustomEvent(V.MEDIA_LOOP_REQUEST,{composed:true,bubbles:true,detail:e});this.dispatchEvent(t);}};Fa.getSlotTemplateHTML=lR;Fa.getTooltipContentHTML=dR;A.customElements.get("media-loop-button")||A.customElements.define("media-loop-button",Fa);function qy({anchor:s,floating:e,placement:t}){let i=cR({anchor:s,floating:e}),{x:r,y:n}=hR(i,t);return {x:r,y:n}}function cR({anchor:s,floating:e}){return {anchor:uR(s,e.offsetParent),floating:{x:0,y:0,width:e.offsetWidth,height:e.offsetHeight}}}function uR(s,e){var t;let i=s.getBoundingClientRect(),r=(t=e?.getBoundingClientRect())!=null?t:{x:0,y:0};return {x:i.x-r.x,y:i.y-r.y,width:i.width,height:i.height}}function hR({anchor:s,floating:e},t){let i=fR(t)==="x"?"y":"x",r=i==="y"?"height":"width",n=jy(t),o=s.x+s.width/2-e.width/2,a=s.y+s.height/2-e.height/2,l=s[r]/2-e[r]/2,d;switch(n){case "top":d={x:o,y:s.y-e.height};break;case "bottom":d={x:o,y:s.y+s.height};break;case "right":d={x:s.x+s.width,y:a};break;case "left":d={x:s.x-e.width,y:a};break;default:d={x:s.x,y:s.y};}switch(t.split("-")[1]){case "start":d[i]-=l;break;case "end":d[i]+=l;break}return d}function jy(s){return s.split("-")[0]}function fR(s){return ["top","bottom"].includes(jy(s))?"y":"x"}var zs=class extends Event{constructor({action:e="auto",relatedTarget:t,...i}){super("invoke",i),this.action=e,this.relatedTarget=t;}},Hc=class extends Event{constructor({newState:e,oldState:t,...i}){super("toggle",i),this.newState=e,this.oldState=t;}};var Dm=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Pe=(s,e,t)=>(Dm(s,e,"read from private field"),t?t.call(s):e.get(s)),Fe=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Yi=(s,e,t,i)=>(Dm(s,e,"write to private field"),e.set(s,t),t),$e=(s,e,t)=>(Dm(s,e,"access private method"),t),zi,Kr,Qs,Gc,Kc,Vr,Ha,_m,Yy,qc,Mm,jc,Vc,Tm,Sm,zy,Am,Qy,Im,Xy,Hn,Gn,Kn,Ga,Yc,Pm,xm,Zy,Om,Jy,Lm,eb,Um,tb,Rm,ib,km,sb,$a,zc,wm,rb,Ba,Qc,Wc,Cm;function hi({type:s,text:e,value:t,checked:i}){let r=je.createElement("media-chrome-menu-item");r.type=s,r.part.add("menu-item"),r.part.add(s),r.value=t,r.checked=i;let n=je.createElement("span");return n.textContent=e,r.append(n),r}function Jt(s,e){let t=s.querySelector(`:scope > [slot="${e}"]`);if(t?.nodeName=="SLOT"&&(t=t.assignedElements({flatten:true})[0]),t)return t=t.cloneNode(true),t;let i=s.shadowRoot.querySelector(`[name="${e}"] > svg`);return i?i.cloneNode(true):""}function mR(s){return `
1470
+ <style>
1471
+ :host {
1472
+ font: var(--media-font,
1473
+ var(--media-font-weight, normal)
1474
+ var(--media-font-size, 14px) /
1475
+ var(--media-text-content-height, var(--media-control-height, 24px))
1476
+ var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif));
1477
+ color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238)));
1478
+ --_menu-bg: rgb(20 20 30 / .8);
1479
+ background: var(--media-menu-background, var(--media-control-background, var(--media-secondary-color, var(--_menu-bg))));
1480
+ border-radius: var(--media-menu-border-radius);
1481
+ border: var(--media-menu-border, none);
1482
+ display: var(--media-menu-display, inline-flex) !important;
1483
+
1484
+ transition: var(--media-menu-transition-in,
1485
+ visibility 0s,
1486
+ opacity .2s ease-out,
1487
+ transform .15s ease-out,
1488
+ left .2s ease-in-out,
1489
+ min-width .2s ease-in-out,
1490
+ min-height .2s ease-in-out
1491
+ ) !important;
1492
+
1493
+ visibility: var(--media-menu-visibility, visible);
1494
+ opacity: var(--media-menu-opacity, 1);
1495
+ max-height: var(--media-menu-max-height, var(--_menu-max-height, 300px));
1496
+ transform: var(--media-menu-transform-in, translateY(0) scale(1));
1497
+ flex-direction: column;
1498
+
1499
+ min-height: 0;
1500
+ position: relative;
1501
+ bottom: var(--_menu-bottom);
1502
+ box-sizing: border-box;
1503
+ }
1504
+
1505
+ @-moz-document url-prefix() {
1506
+ :host{
1507
+ --_menu-bg: rgb(20 20 30);
1508
+ }
1509
+ }
1510
+
1511
+ :host([hidden]) {
1512
+ transition: var(--media-menu-transition-out,
1513
+ visibility .15s ease-in,
1514
+ opacity .15s ease-in,
1515
+ transform .15s ease-in
1516
+ ) !important;
1517
+ visibility: var(--media-menu-hidden-visibility, hidden);
1518
+ opacity: var(--media-menu-hidden-opacity, 0);
1519
+ max-height: var(--media-menu-hidden-max-height,
1520
+ var(--media-menu-max-height, var(--_menu-max-height, 300px)));
1521
+ transform: var(--media-menu-transform-out, translateY(2px) scale(.99));
1522
+ pointer-events: none;
1523
+ }
1524
+
1525
+ :host([slot="submenu"]) {
1526
+ background: none;
1527
+ width: 100%;
1528
+ min-height: 100%;
1529
+ position: absolute;
1530
+ bottom: 0;
1531
+ right: -100%;
1532
+ }
1533
+
1534
+ #container {
1535
+ display: flex;
1536
+ flex-direction: column;
1537
+ min-height: 0;
1538
+ transition: transform .2s ease-out;
1539
+ transform: translate(0, 0);
1540
+ }
1541
+
1542
+ #container.has-expanded {
1543
+ transition: transform .2s ease-in;
1544
+ transform: translate(-100%, 0);
1545
+ }
1546
+
1547
+ button {
1548
+ background: none;
1549
+ color: inherit;
1550
+ border: none;
1551
+ padding: 0;
1552
+ font: inherit;
1553
+ outline: inherit;
1554
+ display: inline-flex;
1555
+ align-items: center;
1556
+ }
1557
+
1558
+ slot[name="header"][hidden] {
1559
+ display: none;
1560
+ }
1561
+
1562
+ slot[name="header"] > *,
1563
+ slot[name="header"]::slotted(*) {
1564
+ padding: .4em .7em;
1565
+ border-bottom: 1px solid rgb(255 255 255 / .25);
1566
+ cursor: var(--media-cursor, default);
1567
+ }
1568
+
1569
+ slot[name="header"] > button[part~="back"],
1570
+ slot[name="header"]::slotted(button[part~="back"]) {
1571
+ cursor: var(--media-cursor, pointer);
1572
+ }
1573
+
1574
+ svg[part~="back"] {
1575
+ height: var(--media-menu-icon-height, var(--media-control-height, 24px));
1576
+ fill: var(--media-icon-color, var(--media-primary-color, rgb(238 238 238)));
1577
+ display: block;
1578
+ margin-right: .5ch;
1579
+ }
1580
+
1581
+ slot:not([name]) {
1582
+ gap: var(--media-menu-gap);
1583
+ flex-direction: var(--media-menu-flex-direction, column);
1584
+ overflow: var(--media-menu-overflow, hidden auto);
1585
+ display: flex;
1586
+ min-height: 0;
1587
+ }
1588
+
1589
+ :host([role="menu"]) slot:not([name]) {
1590
+ padding-block: .4em;
1591
+ }
1592
+
1593
+ slot:not([name])::slotted([role="menu"]) {
1594
+ background: none;
1595
+ }
1596
+
1597
+ media-chrome-menu-item > span {
1598
+ margin-right: .5ch;
1599
+ max-width: var(--media-menu-item-max-width);
1600
+ text-overflow: ellipsis;
1601
+ overflow: hidden;
1602
+ }
1603
+ </style>
1604
+ <style id="layout-row" media="width:0">
1605
+
1606
+ slot[name="header"] > *,
1607
+ slot[name="header"]::slotted(*) {
1608
+ padding: .4em .5em;
1609
+ }
1610
+
1611
+ slot:not([name]) {
1612
+ gap: var(--media-menu-gap, .25em);
1613
+ flex-direction: var(--media-menu-flex-direction, row);
1614
+ padding-inline: .5em;
1615
+ }
1616
+
1617
+ media-chrome-menu-item {
1618
+ padding: .3em .5em;
1619
+ }
1620
+
1621
+ media-chrome-menu-item[aria-checked="true"] {
1622
+ background: var(--media-menu-item-checked-background, rgb(255 255 255 / .2));
1623
+ }
1624
+
1625
+
1626
+ media-chrome-menu-item::part(checked-indicator) {
1627
+ display: var(--media-menu-item-checked-indicator-display, none);
1628
+ }
1629
+ </style>
1630
+ <div id="container" part="container">
1631
+ <slot name="header" hidden>
1632
+ <button part="back button" aria-label="Back to previous menu">
1633
+ <slot name="back-icon">
1634
+ <svg aria-hidden="true" viewBox="0 0 20 24" part="back indicator">
1635
+ <path d="m11.88 17.585.742-.669-4.2-4.665 4.2-4.666-.743-.669-4.803 5.335 4.803 5.334Z"/>
1636
+ </svg>
1637
+ </slot>
1638
+ <slot name="title"></slot>
1639
+ </button>
1640
+ </slot>
1641
+ <slot></slot>
1642
+ </div>
1643
+ <slot name="checked-indicator" hidden></slot>
1644
+ `}var Gr={STYLE:"style",HIDDEN:"hidden",DISABLED:"disabled",ANCHOR:"anchor"},Ze=class extends A.HTMLElement{constructor(){if(super(),Fe(this,_m),Fe(this,qc),Fe(this,Vc),Fe(this,Sm),Fe(this,Am),Fe(this,Im),Fe(this,Kn),Fe(this,Yc),Fe(this,xm),Fe(this,Om),Fe(this,Lm),Fe(this,Um),Fe(this,Rm),Fe(this,km),Fe(this,$a),Fe(this,wm),Fe(this,Ba),Fe(this,Wc),Fe(this,zi,null),Fe(this,Kr,null),Fe(this,Qs,null),Fe(this,Gc,new Set),Fe(this,Kc,void 0),Fe(this,Vr,false),Fe(this,Ha,null),Fe(this,jc,()=>{let e=Pe(this,Gc),t=new Set(this.items);for(let i of e)t.has(i)||this.dispatchEvent(new CustomEvent("removemenuitem",{detail:i}));for(let i of t)e.has(i)||this.dispatchEvent(new CustomEvent("addmenuitem",{detail:i}));Yi(this,Gc,t);}),Fe(this,Hn,()=>{$e(this,Kn,Ga).call(this),$e(this,Yc,Pm).call(this,false);}),Fe(this,Gn,()=>{$e(this,Kn,Ga).call(this);}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}this.container=this.shadowRoot.querySelector("#container"),this.defaultSlot=this.shadowRoot.querySelector("slot:not([name])"),this.shadowRoot.addEventListener("slotchange",this),Yi(this,Kc,new MutationObserver(Pe(this,jc))),Pe(this,Kc).observe(this.defaultSlot,{childList:true});}static get observedAttributes(){return [Gr.DISABLED,Gr.HIDDEN,Gr.STYLE,Gr.ANCHOR,ve.MEDIA_CONTROLLER]}static formatMenuItemText(e,t){return e}enable(){this.addEventListener("click",this),this.addEventListener("focusout",this),this.addEventListener("keydown",this),this.addEventListener("invoke",this),this.addEventListener("toggle",this);}disable(){this.removeEventListener("click",this),this.removeEventListener("focusout",this),this.removeEventListener("keyup",this),this.removeEventListener("invoke",this),this.removeEventListener("toggle",this);}handleEvent(e){switch(e.type){case "slotchange":$e(this,_m,Yy).call(this,e);break;case "invoke":$e(this,Sm,zy).call(this,e);break;case "click":$e(this,xm,Zy).call(this,e);break;case "toggle":$e(this,Lm,eb).call(this,e);break;case "focusout":$e(this,Rm,ib).call(this,e);break;case "keydown":$e(this,km,sb).call(this,e);break}}connectedCallback(){var e,t;Yi(this,Ha,ea(this.shadowRoot,":host")),$e(this,Vc,Tm).call(this),this.hasAttribute("disabled")||this.enable(),this.role||(this.role="menu"),Yi(this,zi,Ld(this)),(t=(e=Pe(this,zi))==null?void 0:e.associateElement)==null||t.call(e,this),this.hidden||(ys(Ka(this),Pe(this,Hn)),ys(this,Pe(this,Gn))),$e(this,qc,Mm).call(this);}disconnectedCallback(){var e,t;bs(Ka(this),Pe(this,Hn)),bs(this,Pe(this,Gn)),this.disable(),(t=(e=Pe(this,zi))==null?void 0:e.unassociateElement)==null||t.call(e,this),Yi(this,zi,null);}attributeChangedCallback(e,t,i){var r,n,o,a;e===Gr.HIDDEN&&i!==t?(Pe(this,Vr)||Yi(this,Vr,true),this.hidden?$e(this,Im,Xy).call(this):$e(this,Am,Qy).call(this),this.dispatchEvent(new Hc({oldState:this.hidden?"open":"closed",newState:this.hidden?"closed":"open",bubbles:true}))):e===ve.MEDIA_CONTROLLER?(t&&((n=(r=Pe(this,zi))==null?void 0:r.unassociateElement)==null||n.call(r,this),Yi(this,zi,null)),i&&this.isConnected&&(Yi(this,zi,Ld(this)),(a=(o=Pe(this,zi))==null?void 0:o.associateElement)==null||a.call(o,this))):e===Gr.DISABLED&&i!==t?i==null?this.enable():this.disable():e===Gr.STYLE&&i!==t&&$e(this,Vc,Tm).call(this);}formatMenuItemText(e,t){return this.constructor.formatMenuItemText(e,t)}get anchor(){return this.getAttribute("anchor")}set anchor(e){this.setAttribute("anchor",`${e}`);}get anchorElement(){var e;return this.anchor?(e=Ir(this))==null?void 0:e.querySelector(`#${this.anchor}`):null}get items(){return this.defaultSlot.assignedElements({flatten:true}).filter(pR)}get radioGroupItems(){return this.items.filter(e=>e.role==="menuitemradio")}get checkedItems(){return this.items.filter(e=>e.checked)}get value(){var e,t;return (t=(e=this.checkedItems[0])==null?void 0:e.value)!=null?t:""}set value(e){let t=this.items.find(i=>i.value===e);t&&$e(this,Wc,Cm).call(this,t);}focus(){if(Yi(this,Kr,Jo()),this.items.length){$e(this,Ba,Qc).call(this,this.items[0]),this.items[0].focus();return}let e=this.querySelector('[autofocus], [tabindex]:not([tabindex="-1"]), [role="menu"]');e?.focus();}handleSelect(e){var t;let i=$e(this,$a,zc).call(this,e);i&&($e(this,Wc,Cm).call(this,i,i.type==="checkbox"),Pe(this,Qs)&&!this.hidden&&((t=Pe(this,Kr))==null||t.focus(),this.hidden=true));}get keysUsed(){return ["Enter","Escape","Tab"," ","ArrowDown","ArrowUp","Home","End"]}handleMove(e){var t,i;let{key:r}=e,n=this.items,o=(i=(t=$e(this,$a,zc).call(this,e))!=null?t:$e(this,wm,rb).call(this))!=null?i:n[0],a=n.indexOf(o),l=Math.max(0,a);r==="ArrowDown"?l++:r==="ArrowUp"?l--:e.key==="Home"?l=0:e.key==="End"&&(l=n.length-1),l<0&&(l=n.length-1),l>n.length-1&&(l=0),$e(this,Ba,Qc).call(this,n[l]),n[l].focus();}};zi=new WeakMap;Kr=new WeakMap;Qs=new WeakMap;Gc=new WeakMap;Kc=new WeakMap;Vr=new WeakMap;Ha=new WeakMap;_m=new WeakSet;Yy=function(s){let e=s.target;for(let t of e.assignedNodes({flatten:true}))t.nodeType===3&&t.textContent.trim()===""&&t.remove();["header","title"].includes(e.name)&&$e(this,qc,Mm).call(this),e.name||Pe(this,jc).call(this);};qc=new WeakSet;Mm=function(){let s=this.shadowRoot.querySelector('slot[name="header"]'),e=this.shadowRoot.querySelector('slot[name="title"]');s.hidden=e.assignedNodes().length===0&&s.assignedNodes().length===0;};jc=new WeakMap;Vc=new WeakSet;Tm=function(){var s;let e=this.shadowRoot.querySelector("#layout-row"),t=(s=getComputedStyle(this).getPropertyValue("--media-menu-layout"))==null?void 0:s.trim();e.setAttribute("media",t==="row"?"":"width:0");};Sm=new WeakSet;zy=function(s){Yi(this,Qs,s.relatedTarget),Nt(this,s.relatedTarget)||(this.hidden=!this.hidden);};Am=new WeakSet;Qy=function(){var s;(s=Pe(this,Qs))==null||s.setAttribute("aria-expanded","true"),this.addEventListener("transitionend",()=>this.focus(),{once:true}),ys(Ka(this),Pe(this,Hn)),ys(this,Pe(this,Gn));};Im=new WeakSet;Xy=function(){var s;(s=Pe(this,Qs))==null||s.setAttribute("aria-expanded","false"),bs(Ka(this),Pe(this,Hn)),bs(this,Pe(this,Gn));};Hn=new WeakMap;Gn=new WeakMap;Kn=new WeakSet;Ga=function(s){if(this.hasAttribute("mediacontroller")&&!this.anchor||this.hidden||!this.anchorElement)return;let{x:e,y:t}=qy({anchor:this.anchorElement,floating:this,placement:"top-start"});s??(s=this.offsetWidth);let r=Ka(this).getBoundingClientRect(),n=r.width-e-s,o=r.height-t-this.offsetHeight,{style:a}=Pe(this,Ha);a.setProperty("position","absolute"),a.setProperty("right",`${Math.max(0,n)}px`),a.setProperty("--_menu-bottom",`${o}px`);let l=getComputedStyle(this),c=a.getPropertyValue("--_menu-bottom")===l.bottom?o:parseFloat(l.bottom),u=r.height-c-parseFloat(l.marginBottom);this.style.setProperty("--_menu-max-height",`${u}px`);};Yc=new WeakSet;Pm=function(s){let e=this.querySelector('[role="menuitem"][aria-haspopup][aria-expanded="true"]'),t=e?.querySelector('[role="menu"]'),{style:i}=Pe(this,Ha);if(s||i.setProperty("--media-menu-transition-in","none"),t){let r=t.offsetHeight,n=Math.max(t.offsetWidth,e.offsetWidth);this.style.setProperty("min-width",`${n}px`),this.style.setProperty("min-height",`${r}px`),$e(this,Kn,Ga).call(this,n);}else this.style.removeProperty("min-width"),this.style.removeProperty("min-height"),$e(this,Kn,Ga).call(this);i.removeProperty("--media-menu-transition-in");};xm=new WeakSet;Zy=function(s){var e;if(s.stopPropagation(),s.composedPath().includes(Pe(this,Om,Jy))){(e=Pe(this,Kr))==null||e.focus(),this.hidden=true;return}let t=$e(this,$a,zc).call(this,s);!t||t.hasAttribute("disabled")||($e(this,Ba,Qc).call(this,t),this.handleSelect(s));};Om=new WeakSet;Jy=function(){var s;return (s=this.shadowRoot.querySelector('slot[name="header"]').assignedElements({flatten:true}))==null?void 0:s.find(t=>t.matches('button[part~="back"]'))};Lm=new WeakSet;eb=function(s){if(s.target===this)return;$e(this,Um,tb).call(this);let e=Array.from(this.querySelectorAll('[role="menuitem"][aria-haspopup]'));for(let t of e)t.invokeTargetElement!=s.target&&s.newState=="open"&&t.getAttribute("aria-expanded")=="true"&&!t.invokeTargetElement.hidden&&t.invokeTargetElement.dispatchEvent(new zs({relatedTarget:t}));for(let t of e)t.setAttribute("aria-expanded",`${!t.submenuElement.hidden}`);$e(this,Yc,Pm).call(this,true);};Um=new WeakSet;tb=function(){let e=this.querySelector('[role="menuitem"] > [role="menu"]:not([hidden])');this.container.classList.toggle("has-expanded",!!e);};Rm=new WeakSet;ib=function(s){var e;Nt(this,s.relatedTarget)||(Pe(this,Vr)&&((e=Pe(this,Kr))==null||e.focus()),Pe(this,Qs)&&Pe(this,Qs)!==s.relatedTarget&&!this.hidden&&(this.hidden=true));};km=new WeakSet;sb=function(s){var e,t,i,r,n;let{key:o,ctrlKey:a,altKey:l,metaKey:d}=s;if(!(a||l||d)&&this.keysUsed.includes(o))if(s.preventDefault(),s.stopPropagation(),o==="Tab"){if(Pe(this,Vr)){this.hidden=true;return}s.shiftKey?(t=(e=this.previousElementSibling)==null?void 0:e.focus)==null||t.call(e):(r=(i=this.nextElementSibling)==null?void 0:i.focus)==null||r.call(i),this.blur();}else o==="Escape"?((n=Pe(this,Kr))==null||n.focus(),Pe(this,Vr)&&(this.hidden=true)):o==="Enter"||o===" "?this.handleSelect(s):this.handleMove(s);};$a=new WeakSet;zc=function(s){return s.composedPath().find(e=>["menuitemradio","menuitemcheckbox"].includes(e.role))};wm=new WeakSet;rb=function(){return this.items.find(s=>s.tabIndex===0)};Ba=new WeakSet;Qc=function(s){for(let e of this.items)e.tabIndex=e===s?0:-1;};Wc=new WeakSet;Cm=function(s,e){let t=[...this.checkedItems];s.type==="radio"&&this.radioGroupItems.forEach(i=>i.checked=false),e?s.checked=!s.checked:s.checked=true,this.checkedItems.some((i,r)=>i!=t[r])&&this.dispatchEvent(new Event("change",{bubbles:true,composed:true}));};Ze.shadowRootOptions={mode:"open"};Ze.getTemplateHTML=mR;function pR(s){return ["menuitem","menuitemradio","menuitemcheckbox"].includes(s?.role)}function Ka(s){var e;return (e=s.getAttribute("bounds")?Pi(s,`#${s.getAttribute("bounds")}`):Ge(s)||s.parentElement)!=null?e:s}A.customElements.get("media-chrome-menu")||A.customElements.define("media-chrome-menu",Ze);var Gm=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Qi=(s,e,t)=>(Gm(s,e,"read from private field"),t?t.call(s):e.get(s)),As=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Nm=(s,e,t,i)=>(Gm(s,e,"write to private field"),e.set(s,t),t),Si=(s,e,t)=>(Gm(s,e,"access private method"),t),Xc,Wa,Fm,nb,Jc,Km,Vm,ob,Xi,Vn,qa,$m,ab,Zc,Bm;function gR(s){return `
1645
+ <style>
1646
+ :host {
1647
+ transition: var(--media-menu-item-transition,
1648
+ background .15s linear,
1649
+ opacity .2s ease-in-out
1650
+ );
1651
+ outline: var(--media-menu-item-outline, 0);
1652
+ outline-offset: var(--media-menu-item-outline-offset, -1px);
1653
+ cursor: var(--media-cursor, pointer);
1654
+ display: flex;
1655
+ align-items: center;
1656
+ align-self: stretch;
1657
+ justify-self: stretch;
1658
+ white-space: nowrap;
1659
+ white-space-collapse: collapse;
1660
+ text-wrap: nowrap;
1661
+ padding: .4em .8em .4em 1em;
1662
+ }
1663
+
1664
+ :host(:focus-visible) {
1665
+ box-shadow: var(--media-menu-item-focus-shadow, inset 0 0 0 2px rgb(27 127 204 / .9));
1666
+ outline: var(--media-menu-item-hover-outline, 0);
1667
+ outline-offset: var(--media-menu-item-hover-outline-offset, var(--media-menu-item-outline-offset, -1px));
1668
+ }
1669
+
1670
+ :host(:hover) {
1671
+ cursor: var(--media-cursor, pointer);
1672
+ background: var(--media-menu-item-hover-background, rgb(92 92 102 / .5));
1673
+ outline: var(--media-menu-item-hover-outline);
1674
+ outline-offset: var(--media-menu-item-hover-outline-offset, var(--media-menu-item-outline-offset, -1px));
1675
+ }
1676
+
1677
+ :host([aria-checked="true"]) {
1678
+ background: var(--media-menu-item-checked-background);
1679
+ }
1680
+
1681
+ :host([hidden]) {
1682
+ display: none;
1683
+ }
1684
+
1685
+ :host([disabled]) {
1686
+ pointer-events: none;
1687
+ color: rgba(255, 255, 255, .3);
1688
+ }
1689
+
1690
+ slot:not([name]) {
1691
+ width: 100%;
1692
+ }
1693
+
1694
+ slot:not([name="submenu"]) {
1695
+ display: inline-flex;
1696
+ align-items: center;
1697
+ transition: inherit;
1698
+ opacity: var(--media-menu-item-opacity, 1);
1699
+ }
1700
+
1701
+ slot[name="description"] {
1702
+ justify-content: end;
1703
+ }
1704
+
1705
+ slot[name="description"] > span {
1706
+ display: inline-block;
1707
+ margin-inline: 1em .2em;
1708
+ max-width: var(--media-menu-item-description-max-width, 100px);
1709
+ text-overflow: ellipsis;
1710
+ overflow: hidden;
1711
+ font-size: .8em;
1712
+ font-weight: 400;
1713
+ text-align: right;
1714
+ position: relative;
1715
+ top: .04em;
1716
+ }
1717
+
1718
+ slot[name="checked-indicator"] {
1719
+ display: none;
1720
+ }
1721
+
1722
+ :host(:is([role="menuitemradio"],[role="menuitemcheckbox"])) slot[name="checked-indicator"] {
1723
+ display: var(--media-menu-item-checked-indicator-display, inline-block);
1724
+ }
1725
+
1726
+
1727
+ svg, img, ::slotted(svg), ::slotted(img) {
1728
+ height: var(--media-menu-item-icon-height, var(--media-control-height, 24px));
1729
+ fill: var(--media-icon-color, var(--media-primary-color, rgb(238 238 238)));
1730
+ display: block;
1731
+ }
1732
+
1733
+
1734
+ [part~="indicator"],
1735
+ ::slotted([part~="indicator"]) {
1736
+ fill: var(--media-menu-item-indicator-fill,
1737
+ var(--media-icon-color, var(--media-primary-color, rgb(238 238 238))));
1738
+ height: var(--media-menu-item-indicator-height, 1.25em);
1739
+ margin-right: .5ch;
1740
+ }
1741
+
1742
+ [part~="checked-indicator"] {
1743
+ visibility: hidden;
1744
+ }
1745
+
1746
+ :host([aria-checked="true"]) [part~="checked-indicator"] {
1747
+ visibility: visible;
1748
+ }
1749
+ </style>
1750
+ <slot name="checked-indicator">
1751
+ <svg aria-hidden="true" viewBox="0 1 24 24" part="checked-indicator indicator">
1752
+ <path d="m10 15.17 9.193-9.191 1.414 1.414-10.606 10.606-6.364-6.364 1.414-1.414 4.95 4.95Z"/>
1753
+ </svg>
1754
+ </slot>
1755
+ <slot name="prefix"></slot>
1756
+ <slot></slot>
1757
+ <slot name="description"></slot>
1758
+ <slot name="suffix">
1759
+ ${this.getSuffixSlotInnerHTML(s)}
1760
+ </slot>
1761
+ <slot name="submenu"></slot>
1762
+ `}function vR(s){return ""}var fi={TYPE:"type",VALUE:"value",CHECKED:"checked",DISABLED:"disabled"},ei=class extends A.HTMLElement{constructor(){if(super(),As(this,Fm),As(this,Jc),As(this,Vm),As(this,Vn),As(this,$m),As(this,Zc),As(this,Xc,false),As(this,Wa,void 0),As(this,Xi,()=>{var e,t;this.submenuElement.items&&this.setAttribute("submenusize",`${this.submenuElement.items.length}`);let i=this.shadowRoot.querySelector('slot[name="description"]'),r=(e=this.submenuElement.checkedItems)==null?void 0:e[0],n=(t=r?.dataset.description)!=null?t:r?.text,o=je.createElement("span");o.textContent=n??"",i.replaceChildren(o);}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}this.shadowRoot.addEventListener("slotchange",this);}static get observedAttributes(){return [fi.TYPE,fi.DISABLED,fi.CHECKED,fi.VALUE]}enable(){this.hasAttribute("tabindex")||this.setAttribute("tabindex","-1"),Va(this)&&!this.hasAttribute("aria-checked")&&this.setAttribute("aria-checked","false"),this.addEventListener("click",this),this.addEventListener("keydown",this);}disable(){this.removeAttribute("tabindex"),this.removeEventListener("click",this),this.removeEventListener("keydown",this),this.removeEventListener("keyup",this);}handleEvent(e){switch(e.type){case "slotchange":Si(this,Fm,nb).call(this,e);break;case "click":this.handleClick(e);break;case "keydown":Si(this,$m,ab).call(this,e);break;case "keyup":Si(this,Vn,qa).call(this,e);break}}attributeChangedCallback(e,t,i){e===fi.CHECKED&&Va(this)&&!Qi(this,Xc)?this.setAttribute("aria-checked",i!=null?"true":"false"):e===fi.TYPE&&i!==t?this.role="menuitem"+i:e===fi.DISABLED&&i!==t&&(i==null?this.enable():this.disable());}connectedCallback(){this.hasAttribute(fi.DISABLED)||this.enable(),this.role="menuitem"+this.type,Nm(this,Wa,Hm(this,this.parentNode)),Si(this,Zc,Bm).call(this),this.submenuElement&&Si(this,Jc,Km).call(this);}disconnectedCallback(){this.disable(),Si(this,Zc,Bm).call(this),Nm(this,Wa,null);}get invokeTarget(){return this.getAttribute("invoketarget")}set invokeTarget(e){this.setAttribute("invoketarget",`${e}`);}get invokeTargetElement(){var e;return this.invokeTarget?(e=Ir(this))==null?void 0:e.querySelector(`#${this.invokeTarget}`):this.submenuElement}get submenuElement(){return this.shadowRoot.querySelector('slot[name="submenu"]').assignedElements({flatten:true})[0]}get type(){var e;return (e=this.getAttribute(fi.TYPE))!=null?e:""}set type(e){this.setAttribute(fi.TYPE,`${e}`);}get value(){var e;return (e=this.getAttribute(fi.VALUE))!=null?e:this.text}set value(e){this.setAttribute(fi.VALUE,e);}get text(){var e;return ((e=this.textContent)!=null?e:"").trim()}get checked(){if(Va(this))return this.getAttribute("aria-checked")==="true"}set checked(e){Va(this)&&(Nm(this,Xc,true),this.setAttribute("aria-checked",e?"true":"false"),e?this.part.add("checked"):this.part.remove("checked"));}handleClick(e){Va(this)||this.invokeTargetElement&&Nt(this,e.target)&&this.invokeTargetElement.dispatchEvent(new zs({relatedTarget:this}));}get keysUsed(){return ["Enter"," "]}};Xc=new WeakMap;Wa=new WeakMap;Fm=new WeakSet;nb=function(s){let e=s.target;if(!e?.name)for(let i of e.assignedNodes({flatten:true}))i instanceof Text&&i.textContent.trim()===""&&i.remove();e.name==="submenu"&&(this.submenuElement?Si(this,Jc,Km).call(this):Si(this,Vm,ob).call(this));};Jc=new WeakSet;Km=async function(){this.setAttribute("aria-haspopup","menu"),this.setAttribute("aria-expanded",`${!this.submenuElement.hidden}`),this.submenuElement.addEventListener("change",Qi(this,Xi)),this.submenuElement.addEventListener("addmenuitem",Qi(this,Xi)),this.submenuElement.addEventListener("removemenuitem",Qi(this,Xi)),Qi(this,Xi).call(this);};Vm=new WeakSet;ob=function(){this.removeAttribute("aria-haspopup"),this.removeAttribute("aria-expanded"),this.submenuElement.removeEventListener("change",Qi(this,Xi)),this.submenuElement.removeEventListener("addmenuitem",Qi(this,Xi)),this.submenuElement.removeEventListener("removemenuitem",Qi(this,Xi)),Qi(this,Xi).call(this);};Xi=new WeakMap;Vn=new WeakSet;qa=function(s){let{key:e}=s;if(!this.keysUsed.includes(e)){this.removeEventListener("keyup",Si(this,Vn,qa));return}this.handleClick(s);};$m=new WeakSet;ab=function(s){let{metaKey:e,altKey:t,key:i}=s;if(e||t||!this.keysUsed.includes(i)){this.removeEventListener("keyup",Si(this,Vn,qa));return}this.addEventListener("keyup",Si(this,Vn,qa),{once:true});};Zc=new WeakSet;Bm=function(){var s;let e=(s=Qi(this,Wa))==null?void 0:s.radioGroupItems;if(!e)return;let t=e.filter(i=>i.getAttribute("aria-checked")==="true").pop();t||(t=e[0]);for(let i of e)i.setAttribute("aria-checked","false");t?.setAttribute("aria-checked","true");};ei.shadowRootOptions={mode:"open"};ei.getTemplateHTML=gR;ei.getSuffixSlotInnerHTML=vR;function Va(s){return s.type==="radio"||s.type==="checkbox"}function Hm(s,e){if(!s)return null;let{host:t}=s.getRootNode();return !e&&t?Hm(s,t):e?.items?e:Hm(e,e?.parentNode)}A.customElements.get("media-chrome-menu-item")||A.customElements.define("media-chrome-menu-item",ei);function ER(s){return `
1763
+ ${Ze.getTemplateHTML(s)}
1764
+ <style>
1765
+ :host {
1766
+ --_menu-bg: rgb(20 20 30 / .8);
1767
+ background: var(--media-settings-menu-background,
1768
+ var(--media-menu-background,
1769
+ var(--media-control-background,
1770
+ var(--media-secondary-color, var(--_menu-bg)))));
1771
+ min-width: var(--media-settings-menu-min-width, 170px);
1772
+ border-radius: 2px 2px 0 0;
1773
+ overflow: hidden;
1774
+ }
1775
+
1776
+ @-moz-document url-prefix() {
1777
+ :host{
1778
+ --_menu-bg: rgb(20 20 30);
1779
+ }
1780
+ }
1781
+
1782
+ :host([role="menu"]) {
1783
+
1784
+ justify-content: end;
1785
+ }
1786
+
1787
+ slot:not([name]) {
1788
+ justify-content: var(--media-settings-menu-justify-content);
1789
+ flex-direction: var(--media-settings-menu-flex-direction, column);
1790
+ overflow: visible;
1791
+ }
1792
+
1793
+ #container.has-expanded {
1794
+ --media-settings-menu-item-opacity: 0;
1795
+ }
1796
+ </style>
1797
+ `}var ja=class extends Ze{get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ge(this).querySelector("media-settings-menu-button")}};ja.getTemplateHTML=ER;A.customElements.get("media-settings-menu")||A.customElements.define("media-settings-menu",ja);function yR(s){return `
1798
+ ${ei.getTemplateHTML.call(this,s)}
1799
+ <style>
1800
+ slot:not([name="submenu"]) {
1801
+ opacity: var(--media-settings-menu-item-opacity, var(--media-menu-item-opacity));
1802
+ }
1803
+
1804
+ :host([aria-expanded="true"]:hover) {
1805
+ background: transparent;
1806
+ }
1807
+ </style>
1808
+ `}function bR(s){return `
1809
+ <svg aria-hidden="true" viewBox="0 0 20 24">
1810
+ <path d="m8.12 17.585-.742-.669 4.2-4.665-4.2-4.666.743-.669 4.803 5.335-4.803 5.334Z"/>
1811
+ </svg>
1812
+ `}var Wr=class extends ei{};Wr.shadowRootOptions={mode:"open"};Wr.getTemplateHTML=yR;Wr.getSuffixSlotInnerHTML=bR;A.customElements.get("media-settings-menu-item")||A.customElements.define("media-settings-menu-item",Wr);var Mt=class extends De{connectedCallback(){super.connectedCallback(),this.invokeTargetElement&&this.setAttribute("aria-haspopup","menu");}get invokeTarget(){return this.getAttribute("invoketarget")}set invokeTarget(e){this.setAttribute("invoketarget",`${e}`);}get invokeTargetElement(){var e;return this.invokeTarget?(e=Ir(this))==null?void 0:e.querySelector(`#${this.invokeTarget}`):null}handleClick(){var e;(e=this.invokeTargetElement)==null||e.dispatchEvent(new zs({relatedTarget:this}));}};A.customElements.get("media-chrome-menu-button")||A.customElements.define("media-chrome-menu-button",Mt);function _R(){return `
1813
+ <style>
1814
+ :host([aria-expanded="true"]) slot[name=tooltip] {
1815
+ display: none;
1816
+ }
1817
+ </style>
1818
+ <slot name="icon">
1819
+ <svg aria-hidden="true" viewBox="0 0 24 24">
1820
+ <path d="M4.5 14.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Zm7.5 0a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Zm7.5 0a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z"/>
1821
+ </svg>
1822
+ </slot>
1823
+ `}function TR(){return K("Settings")}var Wn=class extends Mt{static get observedAttributes(){return [...super.observedAttributes,"target"]}connectedCallback(){super.connectedCallback(),this.setAttribute("aria-label",K("settings"));}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:Ge(this).querySelector("media-settings-menu")}};Wn.getSlotTemplateHTML=_R;Wn.getTooltipContentHTML=TR;A.customElements.get("media-settings-menu-button")||A.customElements.define("media-settings-menu-button",Wn);var Ym=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},lb=(s,e,t)=>(Ym(s,e,"read from private field"),t?t.call(s):e.get(s)),eu=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Wm=(s,e,t,i)=>(Ym(s,e,"write to private field"),e.set(s,t),t),tu=(s,e,t)=>(Ym(s,e,"access private method"),t),Ya,ru,iu,qm,su,jm,nu=class extends Ze{constructor(){super(...arguments),eu(this,iu),eu(this,su),eu(this,Ya,[]),eu(this,ru,void 0);}static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_AUDIO_TRACK_LIST,b.MEDIA_AUDIO_TRACK_ENABLED,b.MEDIA_AUDIO_TRACK_UNAVAILABLE]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_AUDIO_TRACK_ENABLED&&t!==i?this.value=i:e===b.MEDIA_AUDIO_TRACK_LIST&&t!==i&&(Wm(this,Ya,uE(i??"")),tu(this,iu,qm).call(this));}connectedCallback(){super.connectedCallback(),this.addEventListener("change",tu(this,su,jm));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",tu(this,su,jm));}get anchorElement(){var e;return this.anchor!=="auto"?super.anchorElement:(e=Ge(this))==null?void 0:e.querySelector("media-audio-track-menu-button")}get mediaAudioTrackList(){return lb(this,Ya)}set mediaAudioTrackList(e){Wm(this,Ya,e),tu(this,iu,qm).call(this);}get mediaAudioTrackEnabled(){var e;return (e=me(this,b.MEDIA_AUDIO_TRACK_ENABLED))!=null?e:""}set mediaAudioTrackEnabled(e){pe(this,b.MEDIA_AUDIO_TRACK_ENABLED,e);}};Ya=new WeakMap;ru=new WeakMap;iu=new WeakSet;qm=function(){if(lb(this,ru)===JSON.stringify(this.mediaAudioTrackList))return;Wm(this,ru,JSON.stringify(this.mediaAudioTrackList));let s=this.mediaAudioTrackList;this.defaultSlot.textContent="",s.sort((e,t)=>e.id.localeCompare(t.id,void 0,{numeric:true}));for(let e of s){let t=this.formatMenuItemText(e.label,e),i=hi({type:"radio",text:t,value:`${e.id}`,checked:e.enabled});i.prepend(Jt(this,"checked-indicator")),this.defaultSlot.append(i);}};su=new WeakSet;jm=function(){if(this.value==null)return;let s=new A.CustomEvent(V.MEDIA_AUDIO_TRACK_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(s);};A.customElements.get("media-audio-track-menu")||A.customElements.define("media-audio-track-menu",nu);var SR=`<svg aria-hidden="true" viewBox="0 0 24 24">
1824
+ <path d="M11 17H9.5V7H11v10Zm-3-3H6.5v-4H8v4Zm6-5h-1.5v6H14V9Zm3 7h-1.5V8H17v8Z"/>
1825
+ <path d="M22 12c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2s10 4.477 10 10Zm-2 0a8 8 0 1 0-16 0 8 8 0 0 0 16 0Z"/>
1826
+ </svg>`;function AR(){return `
1827
+ <style>
1828
+ :host([aria-expanded="true"]) slot[name=tooltip] {
1829
+ display: none;
1830
+ }
1831
+ </style>
1832
+ <slot name="icon">${SR}</slot>
1833
+ `}function IR(){return K("Audio")}var db=s=>{let e=K("Audio");s.setAttribute("aria-label",e);},qn=class extends Mt{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_AUDIO_TRACK_ENABLED,b.MEDIA_AUDIO_TRACK_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),db(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_LANG&&db(this);}get invokeTargetElement(){var e;return this.invokeTarget!=null?super.invokeTargetElement:(e=Ge(this))==null?void 0:e.querySelector("media-audio-track-menu")}get mediaAudioTrackEnabled(){var e;return (e=me(this,b.MEDIA_AUDIO_TRACK_ENABLED))!=null?e:""}set mediaAudioTrackEnabled(e){pe(this,b.MEDIA_AUDIO_TRACK_ENABLED,e);}};qn.getSlotTemplateHTML=AR;qn.getTooltipContentHTML=IR;A.customElements.get("media-audio-track-menu-button")||A.customElements.define("media-audio-track-menu-button",qn);var Zm=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},xR=(s,e,t)=>(Zm(s,e,"read from private field"),e.get(s)),zm=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},LR=(s,e,t,i)=>(Zm(s,e,"write to private field"),e.set(s,t),t),ou=(s,e,t)=>(Zm(s,e,"access private method"),t),du,au,Qm,lu,Xm,RR=`
1834
+ <svg aria-hidden="true" viewBox="0 0 26 24" part="captions-indicator indicator">
1835
+ <path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/>
1836
+ </svg>`;function kR(s){return `
1837
+ ${Ze.getTemplateHTML(s)}
1838
+ <slot name="captions-indicator" hidden>${RR}</slot>
1839
+ `}var za=class extends Ze{constructor(){super(...arguments),zm(this,au),zm(this,lu),zm(this,du,void 0);}static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_SUBTITLES_LIST,b.MEDIA_SUBTITLES_SHOWING]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_SUBTITLES_LIST&&t!==i?ou(this,au,Qm).call(this):e===b.MEDIA_SUBTITLES_SHOWING&&t!==i&&(this.value=i||"",ou(this,au,Qm).call(this));}connectedCallback(){super.connectedCallback(),this.addEventListener("change",ou(this,lu,Xm));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",ou(this,lu,Xm));}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ge(this).querySelector("media-captions-menu-button")}get mediaSubtitlesList(){return cb(this,b.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){ub(this,b.MEDIA_SUBTITLES_LIST,e);}get mediaSubtitlesShowing(){return cb(this,b.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){ub(this,b.MEDIA_SUBTITLES_SHOWING,e);}};du=new WeakMap;au=new WeakSet;Qm=function(){var s;let e=xR(this,du)!==JSON.stringify(this.mediaSubtitlesList),t=this.value!==this.getAttribute(b.MEDIA_SUBTITLES_SHOWING);if(!e&&!t)return;LR(this,du,JSON.stringify(this.mediaSubtitlesList)),this.defaultSlot.textContent="";let i=!this.value,r=hi({type:"radio",text:this.formatMenuItemText(K("Off")),value:"off",checked:i});r.prepend(Jt(this,"checked-indicator")),this.defaultSlot.append(r);let n=this.mediaSubtitlesList;for(let o of n){let a=hi({type:"radio",text:this.formatMenuItemText(o.label,o),value:Bd(o),checked:this.value==Bd(o)});a.prepend(Jt(this,"checked-indicator")),((s=o.kind)!=null?s:"subs")==="captions"&&a.append(Jt(this,"captions-indicator")),this.defaultSlot.append(a);}};lu=new WeakSet;Xm=function(){let s=this.mediaSubtitlesShowing,e=this.getAttribute(b.MEDIA_SUBTITLES_SHOWING),t=this.value!==e;if(s?.length&&t&&this.dispatchEvent(new A.CustomEvent(V.MEDIA_DISABLE_SUBTITLES_REQUEST,{composed:true,bubbles:true,detail:s})),!this.value||!t)return;let i=new A.CustomEvent(V.MEDIA_SHOW_SUBTITLES_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(i);};za.getTemplateHTML=kR;var cb=(s,e)=>{let t=s.getAttribute(e);return t?kr(t):[]},ub=(s,e,t)=>{if(!t?.length){s.removeAttribute(e);return}let i=Ts(t);s.getAttribute(e)!==i&&s.setAttribute(e,i);};A.customElements.get("media-captions-menu")||A.customElements.define("media-captions-menu",za);var wR=`<svg aria-hidden="true" viewBox="0 0 26 24">
1840
+ <path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/>
1841
+ </svg>`,CR=`<svg aria-hidden="true" viewBox="0 0 26 24">
1842
+ <path d="M17.73 14.09a1.4 1.4 0 0 1-1 .37 1.579 1.579 0 0 1-1.27-.58A3 3 0 0 1 15 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34A2.89 2.89 0 0 0 19 9.07a3 3 0 0 0-2.14-.78 3.14 3.14 0 0 0-2.42 1 3.91 3.91 0 0 0-.93 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.17 3.17 0 0 0 1.07-1.74l-1.4-.45c-.083.43-.3.822-.62 1.12Zm-7.22 0a1.43 1.43 0 0 1-1 .37 1.58 1.58 0 0 1-1.27-.58A3 3 0 0 1 7.76 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34a2.81 2.81 0 0 0-.74-1.32 2.94 2.94 0 0 0-2.13-.78 3.18 3.18 0 0 0-2.43 1 4 4 0 0 0-.92 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.23 3.23 0 0 0 1.07-1.74l-1.4-.45a2.06 2.06 0 0 1-.6 1.07Zm12.32-8.41a2.59 2.59 0 0 0-2.3-2.51C18.72 3.05 15.86 3 13 3c-2.86 0-5.72.05-7.53.17a2.59 2.59 0 0 0-2.3 2.51c-.23 4.207-.23 8.423 0 12.63a2.57 2.57 0 0 0 2.3 2.5c1.81.13 4.67.19 7.53.19 2.86 0 5.72-.06 7.53-.19a2.57 2.57 0 0 0 2.3-2.5c.23-4.207.23-8.423 0-12.63Zm-1.49 12.53a1.11 1.11 0 0 1-.91 1.11c-1.67.11-4.45.18-7.43.18-2.98 0-5.76-.07-7.43-.18a1.11 1.11 0 0 1-.91-1.11c-.21-4.14-.21-8.29 0-12.43a1.11 1.11 0 0 1 .91-1.11C7.24 4.56 10 4.49 13 4.49s5.76.07 7.43.18a1.11 1.11 0 0 1 .91 1.11c.21 4.14.21 8.29 0 12.43Z"/>
1843
+ </svg>`;function DR(){return `
1844
+ <style>
1845
+ :host([data-captions-enabled="true"]) slot[name=off] {
1846
+ display: none !important;
1847
+ }
1848
+
1849
+
1850
+ :host(:not([data-captions-enabled="true"])) slot[name=on] {
1851
+ display: none !important;
1852
+ }
1853
+
1854
+ :host([aria-expanded="true"]) slot[name=tooltip] {
1855
+ display: none;
1856
+ }
1857
+ </style>
1858
+
1859
+ <slot name="icon">
1860
+ <slot name="on">${wR}</slot>
1861
+ <slot name="off">${CR}</slot>
1862
+ </slot>
1863
+ `}function MR(){return K("Captions")}var hb=s=>{s.setAttribute("data-captions-enabled",Hd(s).toString());},fb=s=>{s.setAttribute("aria-label",K("closed captions"));},Xs=class extends Mt{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_SUBTITLES_LIST,b.MEDIA_SUBTITLES_SHOWING,b.MEDIA_LANG]}connectedCallback(){super.connectedCallback(),fb(this),hb(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_SUBTITLES_SHOWING?hb(this):e===b.MEDIA_LANG&&fb(this);}get invokeTargetElement(){var e;return this.invokeTarget!=null?super.invokeTargetElement:(e=Ge(this))==null?void 0:e.querySelector("media-captions-menu")}get mediaSubtitlesList(){return mb(this,b.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){pb(this,b.MEDIA_SUBTITLES_LIST,e);}get mediaSubtitlesShowing(){return mb(this,b.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){pb(this,b.MEDIA_SUBTITLES_SHOWING,e);}};Xs.getSlotTemplateHTML=DR;Xs.getTooltipContentHTML=MR;var mb=(s,e)=>{let t=s.getAttribute(e);return t?kr(t):[]},pb=(s,e,t)=>{if(!t?.length){s.removeAttribute(e);return}let i=Ts(t);s.getAttribute(e)!==i&&s.setAttribute(e,i);};A.customElements.get("media-captions-menu-button")||A.customElements.define("media-captions-menu-button",Xs);var gb=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Yn=(s,e,t)=>(gb(s,e,"read from private field"),t?t.call(s):e.get(s)),Jm=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},jn=(s,e,t)=>(gb(s,e,"access private method"),t),Zs,zn,Qa,cu,tp,ep={RATES:"rates"},uu=class extends Ze{constructor(){super(),Jm(this,zn),Jm(this,cu),Jm(this,Zs,new Gs(this,ep.RATES,{defaultValue:nm})),jn(this,zn,Qa).call(this);}static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_PLAYBACK_RATE,ep.RATES]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_PLAYBACK_RATE&&t!=i?(this.value=i,jn(this,zn,Qa).call(this)):e===ep.RATES&&t!=i&&(Yn(this,Zs).value=i,jn(this,zn,Qa).call(this));}connectedCallback(){super.connectedCallback(),this.addEventListener("change",jn(this,cu,tp));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",jn(this,cu,tp));}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ge(this).querySelector("media-playback-rate-menu-button")}get rates(){return Yn(this,Zs)}set rates(e){e?Array.isArray(e)?Yn(this,Zs).value=e.join(" "):typeof e=="string"&&(Yn(this,Zs).value=e):Yn(this,Zs).value="",jn(this,zn,Qa).call(this);}get mediaPlaybackRate(){return ye(this,b.MEDIA_PLAYBACK_RATE,Fr)}set mediaPlaybackRate(e){Ae(this,b.MEDIA_PLAYBACK_RATE,e);}};Zs=new WeakMap;zn=new WeakSet;Qa=function(){this.defaultSlot.textContent="";let s=this.mediaPlaybackRate,e=new Set(Array.from(Yn(this,Zs)).map(i=>Number(i)));s>0&&!e.has(s)&&e.add(s);let t=Array.from(e).sort((i,r)=>i-r);for(let i of t){let r=hi({type:"radio",text:this.formatMenuItemText(`${i}x`,i),value:i.toString(),checked:s===i});r.prepend(Jt(this,"checked-indicator")),this.defaultSlot.append(r);}};cu=new WeakSet;tp=function(){if(!this.value)return;let s=new A.CustomEvent(V.MEDIA_PLAYBACK_RATE_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(s);};A.customElements.get("media-playback-rate-menu")||A.customElements.define("media-playback-rate-menu",uu);var hu=1;function PR(s){return `
1864
+ <style>
1865
+ :host {
1866
+ min-width: 5ch;
1867
+ padding: var(--media-button-padding, var(--media-control-padding, 10px 5px));
1868
+ }
1869
+
1870
+ :host([aria-expanded="true"]) slot {
1871
+ display: block;
1872
+ }
1873
+
1874
+ :host([aria-expanded="true"]) slot[name=tooltip] {
1875
+ display: none;
1876
+ }
1877
+ </style>
1878
+ <slot name="icon">${s.mediaplaybackrate||hu}x</slot>
1879
+ `}function OR(){return K("Playback rate")}var Qn=class extends Mt{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_PLAYBACK_RATE]}constructor(){var e;super(),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:hu}x`;}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),e===b.MEDIA_PLAYBACK_RATE){let r=i?+i:Number.NaN,n=Number.isNaN(r)?hu:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",K("Playback rate {playbackRate}",{playbackRate:n}));}}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:Ge(this).querySelector("media-playback-rate-menu")}get mediaPlaybackRate(){return ye(this,b.MEDIA_PLAYBACK_RATE,hu)}set mediaPlaybackRate(e){Ae(this,b.MEDIA_PLAYBACK_RATE,e);}};Qn.getSlotTemplateHTML=PR;Qn.getTooltipContentHTML=OR;A.customElements.get("media-playback-rate-menu-button")||A.customElements.define("media-playback-rate-menu-button",Qn);var sp=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Xa=(s,e,t)=>(sp(s,e,"read from private field"),t?t.call(s):e.get(s)),fu=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},vb=(s,e,t,i)=>(sp(s,e,"write to private field"),e.set(s,t),t),Xn=(s,e,t)=>(sp(s,e,"access private method"),t),Za,Jn,Zn,Ja,mu,ip,pu=class extends Ze{constructor(){super(...arguments),fu(this,Zn),fu(this,mu),fu(this,Za,[]),fu(this,Jn,{});}static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_RENDITION_LIST,b.MEDIA_RENDITION_SELECTED,b.MEDIA_RENDITION_UNAVAILABLE,b.MEDIA_HEIGHT]}static formatMenuItemText(e,t){return super.formatMenuItemText(e,t)}static formatRendition(e,{showBitrate:t=false}={}){let i=`${Math.min(e.width,e.height)}p`;if(t&&e.bitrate){let r=e.bitrate/1e6,n=`${r.toFixed(r<1?1:0)} Mbps`;return `${i} (${n})`}return this.formatMenuItemText(i,e)}static compareRendition(e,t){var i,r;return t.height===e.height?((i=t.bitrate)!=null?i:0)-((r=e.bitrate)!=null?r:0):t.height-e.height}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===b.MEDIA_RENDITION_SELECTED&&t!==i?(this.value=i??"auto",Xn(this,Zn,Ja).call(this)):e===b.MEDIA_RENDITION_LIST&&t!==i?(vb(this,Za,dE(i)),Xn(this,Zn,Ja).call(this)):e===b.MEDIA_HEIGHT&&t!==i&&Xn(this,Zn,Ja).call(this);}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Xn(this,mu,ip));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Xn(this,mu,ip));}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ge(this).querySelector("media-rendition-menu-button")}get mediaRenditionList(){return Xa(this,Za)}set mediaRenditionList(e){vb(this,Za,e),Xn(this,Zn,Ja).call(this);}get mediaRenditionSelected(){return me(this,b.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){pe(this,b.MEDIA_RENDITION_SELECTED,e);}get mediaHeight(){return ye(this,b.MEDIA_HEIGHT)}set mediaHeight(e){Ae(this,b.MEDIA_HEIGHT,e);}compareRendition(e,t){return this.constructor.compareRendition(e,t)}formatMenuItemText(e,t){return this.constructor.formatMenuItemText(e,t)}formatRendition(e,t){return this.constructor.formatRendition(e,t)}showRenditionBitrate(e){return this.mediaRenditionList.some(t=>t!==e&&t.height===e.height&&t.bitrate!==e.bitrate)}};Za=new WeakMap;Jn=new WeakMap;Zn=new WeakSet;Ja=function(){if(Xa(this,Jn).mediaRenditionList===JSON.stringify(this.mediaRenditionList)&&Xa(this,Jn).mediaHeight===this.mediaHeight)return;Xa(this,Jn).mediaRenditionList=JSON.stringify(this.mediaRenditionList),Xa(this,Jn).mediaHeight=this.mediaHeight;let s=this.mediaRenditionList.sort(this.compareRendition.bind(this)),e=s.find(o=>o.id===this.mediaRenditionSelected);for(let o of s)o.selected=o===e;this.defaultSlot.textContent="";let t=!this.mediaRenditionSelected;for(let o of s){let a=this.formatRendition(o,{showBitrate:this.showRenditionBitrate(o)}),l=hi({type:"radio",text:a,value:`${o.id}`,checked:o.selected&&!t});l.prepend(Jt(this,"checked-indicator")),this.defaultSlot.append(l);}let i=e&&this.showRenditionBitrate(e),r=t?e?this.formatMenuItemText(`${K("Auto")} \u2022 ${this.formatRendition(e,{showBitrate:i})}`,e):this.formatMenuItemText(`${K("Auto")} (${this.mediaHeight}p)`):this.formatMenuItemText(K("Auto")),n=hi({type:"radio",text:r,value:"auto",checked:t});n.dataset.description=r,n.prepend(Jt(this,"checked-indicator")),this.defaultSlot.append(n);};mu=new WeakSet;ip=function(){if(this.value==null)return;let s=new A.CustomEvent(V.MEDIA_RENDITION_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(s);};A.customElements.get("media-rendition-menu")||A.customElements.define("media-rendition-menu",pu);var UR=`<svg aria-hidden="true" viewBox="0 0 24 24">
1880
+ <path d="M13.5 2.5h2v6h-2v-2h-11v-2h11v-2Zm4 2h4v2h-4v-2Zm-12 4h2v6h-2v-2h-3v-2h3v-2Zm4 2h12v2h-12v-2Zm1 4h2v6h-2v-2h-8v-2h8v-2Zm4 2h7v2h-7v-2Z" />
1881
+ </svg>`;function NR(){return `
1882
+ <style>
1883
+ :host([aria-expanded="true"]) slot[name=tooltip] {
1884
+ display: none;
1885
+ }
1886
+ </style>
1887
+ <slot name="icon">${UR}</slot>
1888
+ `}function FR(){return K("Quality")}var eo=class extends Mt{static get observedAttributes(){return [...super.observedAttributes,b.MEDIA_RENDITION_SELECTED,b.MEDIA_RENDITION_UNAVAILABLE,b.MEDIA_HEIGHT]}connectedCallback(){super.connectedCallback(),this.setAttribute("aria-label",K("quality"));}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:Ge(this).querySelector("media-rendition-menu")}get mediaRenditionSelected(){return me(this,b.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){pe(this,b.MEDIA_RENDITION_SELECTED,e);}get mediaHeight(){return ye(this,b.MEDIA_HEIGHT)}set mediaHeight(e){Ae(this,b.MEDIA_HEIGHT,e);}};eo.getSlotTemplateHTML=NR;eo.getTooltipContentHTML=FR;A.customElements.get("media-rendition-menu-button")||A.customElements.define("media-rendition-menu-button",eo);var op=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Ji=(s,e,t)=>(op(s,e,"read from private field"),t?t.call(s):e.get(s)),Zi=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Eb=(s,e,t,i)=>(op(s,e,"write to private field"),e.set(s,t),t),mi=(s,e,t)=>(op(s,e,"access private method"),t),io,el,_u,qr,to,ap,yb,gu,rp,vu,np,bb,yu,bu,Eu;function $R(s){return `
1889
+ ${Ze.getTemplateHTML(s)}
1890
+ <style>
1891
+ :host {
1892
+ --_menu-bg: rgb(20 20 30 / .8);
1893
+ background: var(--media-settings-menu-background,
1894
+ var(--media-menu-background,
1895
+ var(--media-control-background,
1896
+ var(--media-secondary-color, var(--_menu-bg)))));
1897
+ min-width: var(--media-settings-menu-min-width, 170px);
1898
+ border-radius: 2px;
1899
+ overflow: hidden;
1900
+ }
1901
+ </style>
1902
+ `}var tl=class extends Ze{constructor(){super(),Zi(this,el),Zi(this,qr),Zi(this,ap),Zi(this,gu),Zi(this,np),Zi(this,io,false),Zi(this,vu,e=>{let t=e.target,i=t?.nodeName==="VIDEO",r=mi(this,gu,rp).call(this,t);(i||r)&&(Ji(this,io)?mi(this,qr,to).call(this):mi(this,np,bb).call(this,e));}),Zi(this,yu,e=>{let t=e.target,i=this.contains(t),r=e.button===2,n=t?.nodeName==="VIDEO",o=mi(this,gu,rp).call(this,t);i||r&&(n||o)||mi(this,qr,to).call(this);}),Zi(this,bu,e=>{e.key==="Escape"&&mi(this,qr,to).call(this);}),Zi(this,Eu,e=>{var t,i;let r=e.target;if((t=r.matches)!=null&&t.call(r,'button[invoke="copy"]')){let n=(i=r.closest("media-context-menu-item"))==null?void 0:i.querySelector('input[slot="copy"]');n&&navigator.clipboard.writeText(n.value);}mi(this,qr,to).call(this);}),this.setAttribute("noautohide",""),mi(this,el,_u).call(this);}connectedCallback(){super.connectedCallback(),Ge(this).addEventListener("contextmenu",Ji(this,vu)),this.addEventListener("click",Ji(this,Eu));}disconnectedCallback(){super.disconnectedCallback(),Ge(this).removeEventListener("contextmenu",Ji(this,vu)),this.removeEventListener("click",Ji(this,Eu)),document.removeEventListener("mousedown",Ji(this,yu)),document.removeEventListener("keydown",Ji(this,bu));}};io=new WeakMap;el=new WeakSet;_u=function(){this.hidden=!Ji(this,io);};qr=new WeakSet;to=function(){Eb(this,io,false),mi(this,el,_u).call(this);};ap=new WeakSet;yb=function(){document.querySelectorAll("media-context-menu").forEach(e=>{var t;e!==this&&mi(t=e,qr,to).call(t);});};gu=new WeakSet;rp=function(s){return s?s.hasAttribute("slot")&&s.getAttribute("slot")==="media"?true:s.nodeName.includes("-")&&s.tagName.includes("-")?s.hasAttribute("src")||s.hasAttribute("poster")||s.hasAttribute("preload")||s.hasAttribute("playsinline"):false:false};vu=new WeakMap;np=new WeakSet;bb=function(s){s.preventDefault(),mi(this,ap,yb).call(this),Eb(this,io,true),this.style.position="fixed",this.style.left=`${s.clientX}px`,this.style.top=`${s.clientY}px`,mi(this,el,_u).call(this),document.addEventListener("mousedown",Ji(this,yu),{once:true}),document.addEventListener("keydown",Ji(this,bu),{once:true});};yu=new WeakMap;bu=new WeakMap;Eu=new WeakMap;tl.getTemplateHTML=$R;A.customElements.get("media-context-menu")||A.customElements.define("media-context-menu",tl);function BR(s){return `
1903
+ ${ei.getTemplateHTML.call(this,s)}
1904
+ <style>
1905
+ ::slotted(*) {
1906
+ color: var(--media-text-color, white);
1907
+ text-decoration: none;
1908
+ border: none;
1909
+ background: none;
1910
+ cursor: pointer;
1911
+ padding: 0;
1912
+ min-height: var(--media-control-height, 24px);
1913
+ }
1914
+ </style>
1915
+ `}var so=class extends ei{};so.shadowRootOptions={mode:"open"};so.getTemplateHTML=BR;A.customElements.get("media-context-menu-item")||A.customElements.define("media-context-menu-item",so);var HR=`<svg aria-hidden="true" viewBox="0 0 24 24">
1916
+ <path d="M11 17H9.5V7H11v10Zm-3-3H6.5v-4H8v4Zm6-5h-1.5v6H14V9Zm3 7h-1.5V8H17v8Z"/>
1917
+ <path d="M22 12c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2s10 4.477 10 10Zm-2 0a8 8 0 1 0-16 0 8 8 0 0 0 16 0Z"/>
1918
+ </svg>`,Is,es,ts,dp,il,rl,lp=class extends Ze{constructor(){super(...arguments);e(this,ts);e(this,Is,[]);e(this,es);e(this,rl,()=>{let t=this.value??d(this,es);t!=null&&(f(this,es,String(t)),this.dispatchEvent(new A.CustomEvent(V.MEDIA_AUDIO_TRACK_REQUEST,{detail:d(this,es),composed:true,bubbles:true})),g(this,ts,il).call(this));});}get tracks(){return d(this,Is)}set tracks(t){f(this,Is,[...t??[]]),g(this,ts,dp).call(this);}get selected(){return d(this,es)}set selected(t){f(this,es,t??void 0),g(this,ts,il).call(this);}connectedCallback(){super.connectedCallback(),this.addEventListener("change",d(this,rl)),g(this,ts,dp).call(this),g(this,ts,il).call(this);}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",d(this,rl));}};Is=new WeakMap,es=new WeakMap,ts=new WeakSet,dp=function(){let t=this.defaultSlot;if(t){t.textContent="";for(let i of d(this,Is)){let r=hi({type:"radio",text:i.label??i.language??"",value:i.id,checked:!!i.enabled});r.prepend(Jt(this,"checked-indicator")),t.append(r);}g(this,ts,il).call(this);}},il=function(){let t=d(this,Is).find(o=>o.enabled)??(d(this,Is).length?d(this,Is)[0]:void 0),i=d(this,es)??t?.id;f(this,es,i);let n=this.defaultSlot?.querySelectorAll("media-chrome-menu-item")??this.querySelectorAll("media-chrome-menu-item");for(let o of Array.from(n))"checked"in o&&"value"in o&&(o.checked=o.value===i);i!=null?this.value=i:(this.value="",this.removeAttribute("value"));},rl=new WeakMap;var Tu,_b,sl=class extends Mt{constructor(){super(...arguments);e(this,Tu);}connectedCallback(){super.connectedCallback(),g(this,Tu,_b).call(this);}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:this.closest("media-controller, mave-player")?.querySelector("mave-audio-track-menu")??null}};Tu=new WeakSet,_b=function(){let t=K("audio tracks");this.setAttribute("aria-label",t);},sl.getSlotTemplateHTML=()=>`
1919
+ <style>
1920
+ :host([aria-expanded="true"]) slot[name='tooltip'] {
1921
+ display: none;
1922
+ }
1923
+ </style>
1924
+ <slot name="icon">${HR}</slot>
1925
+ `,sl.getTooltipContentHTML=()=>K("audio tracks");A.customElements.get("mave-audio-track-menu")||A.customElements.define("mave-audio-track-menu",lp);A.customElements.get("mave-audio-track-menu-button")||A.customElements.define("mave-audio-track-menu-button",sl);var nl,cp,Su=class extends Xs{constructor(){super(...arguments);e(this,nl);}connectedCallback(){super.connectedCallback(),g(this,nl,cp).call(this);}attributeChangedCallback(t,i,r){super.attributeChangedCallback(t,i,r),g(this,nl,cp).call(this);}};nl=new WeakSet,cp=function(){this.setAttribute("aria-label",K("Captions"));},Su.getTooltipContentHTML=()=>K("Captions");A.customElements.get("mave-captions-menu-button")||A.customElements.define("mave-captions-menu-button",Su);var Q=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},GR=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=KR},KR=Number.MAX_SAFE_INTEGER||9007199254740991,ie=(function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s})({}),M=(function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s})({}),v=(function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s})({}),Te={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},J={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},tr=class{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i;}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e;}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},Mp=class{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new tr(e),this.fast_=new tr(t),this.defaultTTFB_=r,this.ttfb_=new tr(e);}update(e,t){let{slow_:i,fast_:r,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new tr(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new tr(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new tr(e,n.getEstimate(),n.getTotalWeight()));}sample(e,t){e=Math.max(e,this.minDelayMs_);let i=8*t,r=e/1e3,n=i/r;this.fast_.sample(r,n),this.slow_.sample(r,n);}sampleTTFB(e){let t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5));}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function VR(s,e,t){return (e=qR(e))in s?Object.defineProperty(s,e,{value:t,enumerable:true,configurable:true,writable:true}):s[e]=t,s}function Be(){return Be=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(s[i]=t[i]);}return s},Be.apply(null,arguments)}function Tb(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i);}return t}function Oe(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Tb(Object(t),true).forEach(function(i){VR(s,i,t[i]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):Tb(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i));});}return s}function WR(s,e){if(typeof s!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(s)}function qR(s){var e=WR(s,"string");return typeof e=="symbol"?e:e+""}var qt=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i=`[${e}]:`;this.trace=ir,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i);}},ir=function(){},jR={trace:ir,debug:ir,log:ir,warn:ir,info:ir,error:ir};function Pp(){return Be({},jR)}function YR(s,e){let t=self.console[s];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${s}] >`):ir}function Sb(s,e,t){return e[s]?e[s].bind(e):YR(s,t)}var Op=Pp();function zR(s,e,t){let i=Pp();if(typeof console=="object"&&s===true||typeof s=="object"){let r=["debug","log","info","warn","error"];r.forEach(n=>{i[n]=Sb(n,s,t);});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`);}catch{return Pp()}r.forEach(n=>{Op[n]=Sb(n,s);});}else Be(Op,i);return i}var Ue=Op;function sr(s=true){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function QR(s){return typeof self<"u"&&s===self.ManagedMediaSource}function P_(s,e){let t=Object.keys(s),i=Object.keys(e),r=t.length,n=i.length;return !r||!n||r===n&&!t.some(o=>i.indexOf(o)===-1)}function ri(s,e=false){if(typeof TextDecoder<"u"){let d=new TextDecoder("utf-8").decode(s);if(e){let c=d.indexOf("\0");return c!==-1?d.substring(0,c):d}return d.replace(/\0/g,"")}let t=s.length,i,r,n,o="",a=0;for(;a<t;){if(i=s[a++],i===0&&e)return o;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:r=s[a++],o+=String.fromCharCode((i&31)<<6|r&63);break;case 14:r=s[a++],n=s[a++],o+=String.fromCharCode((i&15)<<12|(r&63)<<6|(n&63)<<0);break}}return o}function It(s){let e="";for(let t=0;t<s.length;t++){let i=s[t].toString(16);i.length<2&&(i="0"+i),e+=i;}return e}function O_(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function XR(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var up={exports:{}},Ab;function ZR(){return Ab||(Ab=1,(function(s,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(l,d,c){if(c=c||{},l=l.trim(),d=d.trim(),!d){if(!c.alwaysNormalize)return l;var u=a.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=a.normalizePath(u.path),a.buildURLFromParts(u)}var h=a.parseURL(d);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return c.alwaysNormalize?(h.path=a.normalizePath(h.path),a.buildURLFromParts(h)):d;var f=a.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2];}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(p.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)p.path=f.path,h.params||(p.params=f.params,h.query||(p.query=f.query));else {var g=f.path,E=g.substring(0,g.lastIndexOf("/")+1)+h.path;p.path=a.normalizePath(E);}return p.path===null&&(p.path=c.alwaysNormalize?a.normalizePath(h.path):h.path),a.buildURLFromParts(p)},parseURL:function(l){var d=i.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(o,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};s.exports=a;})();})(up)),up.exports}var Zg=ZR(),hl=class{constructor(){this.aborted=false,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0};}},Ve={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Wu=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,JR(this,"stats");}setByteRange(e,t){let i=e.split("@",2),r;i.length===1?r=t?.byteRangeEndOffset||0:r=parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r];}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[Ve.AUDIO]:null,[Ve.VIDEO]:null,[Ve.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e;}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new hl),this._stats}set stats(e){this._stats=e;}get url(){return !this._url&&this.baseurl&&this.relurl&&(this._url=Zg.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:true})),this._url||""}set url(e){this._url=e;}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[Ve.AUDIO]=null,e[Ve.VIDEO]=null,e[Ve.AUDIOVIDEO]=null;}};function at(s){return s.sn!=="initSegment"}var ll=class extends Wu{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=false,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e;}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(Q(e)&&Q(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e;}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){let i=Object.keys(t);if(i.length===1){let r=this._decryptdata=t[i[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t));}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=Q(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return true;if(this.levelkeys){var t;let i=Object.keys(this.levelkeys),r=i.length;if(r>1||r===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return true}return false}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!Q(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e;}get ref(){return at(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e);}setStart(e){this.start=e,this._ref&&(this._ref.start=e);}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e);}setKeyFormat(e){let t=this.levelkeys;if(t){var i;let r=t[e];r&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t));}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort();}setElementaryStreamInfo(e,t,i,r,n,o=false){let{elementaryStreams:a}=this,l=a[e];if(!l){a[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:o};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n);}},Up=class extends Wu{constructor(e,t,i,r,n){super(i),this.fragOffset=0,this.duration=0,this.gap=false,this.independent=false,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;let o=e.enumeratedString("BYTERANGE");o&&this.setByteRange(o,n),n&&(this.fragOffset=n.fragOffset+n.duration);}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return !!(e.audio||e.video||e.audiovideo)}};function U_(s,e){let t=Object.getPrototypeOf(s);if(t){let i=Object.getOwnPropertyDescriptor(t,e);return i||U_(t,e)}}function JR(s,e){let t=U_(s,e);t&&(t.enumerable=true,Object.defineProperty(s,e,t));}var Ib=Math.pow(2,32)-1,ek=[].push,N_={video:1,audio:2,id3:3,text:4};function gt(s){return String.fromCharCode.apply(null,s)}function F_(s,e){let t=s[e]<<8|s[e+1];return t<0?65536+t:t}function fe(s,e){let t=$_(s,e);return t<0?4294967296+t:t}function xb(s,e){let t=fe(s,e);return t*=Math.pow(2,32),t+=fe(s,e+4),t}function $_(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function tk(s){let e=s.byteLength;for(let t=0;t<e;){let i=fe(s,t);if(i>8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return true;t=i>1?t+i:e;}return false}function be(s,e){let t=[];if(!e.length)return t;let i=s.byteLength;for(let r=0;r<i;){let n=fe(s,r),o=gt(s.subarray(r+4,r+8)),a=n>1?r+n:i;if(o===e[0])if(e.length===1)t.push(s.subarray(r+8,a));else {let l=be(s.subarray(r+8,a),e.slice(1));l.length&&ek.apply(t,l);}r=a;}return t}function ik(s){let e=[],t=s[0],i=8,r=fe(s,i);i+=4;let n=0,o=0;t===0?(n=fe(s,i),o=fe(s,i+4),i+=8):(n=xb(s,i),o=xb(s,i+8),i+=16),i+=2;let a=s.length+o,l=F_(s,i);i+=2;for(let d=0;d<l;d++){let c=i,u=fe(s,c);c+=4;let h=u&2147483647;if((u&2147483648)>>>31===1)return Ue.warn("SIDX has hierarchical references (not supported)"),null;let m=fe(s,c);c+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:a,end:a+h-1}}),a+=h,c+=4,i=c;}return {earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function B_(s){let e=[],t=be(s,["moov","trak"]);for(let r=0;r<t.length;r++){let n=t[r],o=be(n,["tkhd"])[0];if(o){let a=o[0],l=fe(o,a===0?12:20),d=be(n,["mdia","mdhd"])[0];if(d){a=d[0];let c=fe(d,a===0?12:20),u=be(n,["mdia","hdlr"])[0];if(u){let h=gt(u.subarray(8,12)),f={soun:Ve.AUDIO,vide:Ve.VIDEO}[h],m=be(n,["mdia","minf","stbl","stsd"])[0],p=sk(m);f?(e[l]={timescale:c,type:f,stsd:p},e[f]=Oe({timescale:c,id:l},p)):e[l]={timescale:c,type:h,stsd:p};}}}}return be(s,["moov","mvex","trex"]).forEach(r=>{let n=fe(r,4),o=e[n];o&&(o.default={duration:fe(r,12),flags:fe(r,20)});}),e}function sk(s){let e=s.subarray(8),t=e.subarray(86),i=gt(e.subarray(4,8)),r=i,n,o=i==="enca"||i==="encv";if(o){let d=be(e,[i])[0].subarray(i==="enca"?28:78);be(d,["sinf"]).forEach(u=>{let h=be(u,["schm"])[0];if(h){let f=gt(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){let m=be(u,["frma"])[0];m&&(r=gt(m));}}});}let a=r;switch(r){case "avc1":case "avc2":case "avc3":case "avc4":{let l=be(t,["avcC"])[0];l&&l.length>3&&(r+="."+Iu(l[1])+Iu(l[2])+Iu(l[3]),n=Au(a==="avc1"?"dva1":"dvav",t));break}case "mp4a":{let l=be(e,[i])[0],d=be(l.subarray(28),["esds"])[0];if(d&&d.length>7){let c=4;if(d[c++]!==3)break;c=hp(d,c),c+=2;let u=d[c++];if(u&128&&(c+=2),u&64&&(c+=d[c++]),d[c++]!==4)break;c=hp(d,c);let h=d[c++];if(h===64)r+="."+Iu(h);else break;if(c+=12,d[c++]!==5)break;c=hp(d,c);let f=d[c++],m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((d[c]&224)>>5)),r+="."+m;}break}case "hvc1":case "hev1":{let l=be(t,["hvcC"])[0];if(l&&l.length>12){let d=l[1],c=["","A","B","C"][d>>6],u=d&31,h=fe(l,2),f=(d&32)>>5?"H":"L",m=l[12],p=l.subarray(6,12);r+="."+c+u,r+="."+rk(h).toString(16).toUpperCase(),r+="."+f+m;let g="";for(let E=p.length;E--;){let y=p[E];(y||g)&&(g="."+y.toString(16).toUpperCase()+g);}r+=g;}n=Au(a=="hev1"?"dvhe":"dvh1",t);break}case "dvh1":case "dvhe":case "dvav":case "dva1":case "dav1":{r=Au(r,t)||r;break}case "vp09":{let l=be(t,["vpcC"])[0];if(l&&l.length>6){let d=l[4],c=l[5],u=l[6]>>4&15;r+="."+rs(d)+"."+rs(c)+"."+rs(u);}break}case "av01":{let l=be(t,["av1C"])[0];if(l&&l.length>2){let d=l[1]>>>5,c=l[1]&31,u=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,m=d===2&&h?f?12:10:h?10:8,p=(l[2]&16)>>4,g=(l[2]&8)>>3,E=(l[2]&4)>>2,y=l[2]&3;r+="."+d+"."+rs(c)+u+"."+rs(m)+"."+p+"."+g+E+y+"."+rs(1)+"."+rs(1)+"."+rs(1)+"."+0,n=Au("dav1",t);}break}}return {codec:r,encrypted:o,supplemental:n}}function Au(s,e){let t=be(e,["dvvC"]),i=t.length?t[0]:be(e,["dvcC"])[0];if(i){let r=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return s+"."+rs(r)+"."+rs(n)}}function rk(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function hp(s,e){let t=e+5;for(;s[e++]&128&&e<t;);return e}function Iu(s){return ("0"+s.toString(16).toUpperCase()).slice(-2)}function rs(s){return (s<10?"0":"")+s}function nk(s,e){if(!s||!e)return;let t=e.keyId;t&&e.isCommonEncryption&&H_(s,(i,r)=>{let n=i.subarray(8,24);n.some(o=>o!==0)||(Ue.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${It(n)} -> ${It(t)}`),i.set(t,8));});}function ok(s){let e=[];return H_(s,t=>e.push(t.subarray(8,24))),e}function H_(s,e){be(s,["moov","trak"]).forEach(i=>{let r=be(i,["mdia","minf","stbl","stsd"])[0];if(!r)return;let n=r.subarray(8),o=be(n,["enca"]),a=o.length>0;a||(o=be(n,["encv"])),o.forEach(l=>{let d=a?l.subarray(28):l.subarray(78);be(d,["sinf"]).forEach(u=>{let h=G_(u);h&&e(h,a);});});});}function G_(s){let e=be(s,["schm"])[0];if(e){let t=gt(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let i=be(s,["schi","tenc"])[0];if(i)return i}}}function ak(s,e,t){let i={},r=be(s,["moof","traf"]);for(let n=0;n<r.length;n++){let o=r[n],a=be(o,["tfhd"])[0],l=fe(a,4),d=e[l];if(!d)continue;i[l]||(i[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});let c=i[l],u=be(o,["tfdt"])[0];if(u){let _=u[0],S=fe(u,4);_===1&&(S===Ib?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=Ib+1,S+=fe(u,8))),Q(S)&&(!Q(c.start)||S<c.start)&&(c.start=S);}let h=d.default,f=fe(a,0)|h?.flags,m=h?.duration||0;f&8&&(f&2?m=fe(a,12):m=fe(a,8));let p=be(o,["trun"]),g=c.start||0,E=0,y=m;for(let _=0;_<p.length;_++){let S=p[_],L=fe(S,4),O=c.sampleCount;c.sampleCount+=L;let R=S[3]&1,D=S[3]&4,C=S[2]&1,k=S[2]&2,H=S[2]&4,q=S[2]&8,j=8,X=L;for(R&&(j+=4),D&&L&&(!(S[j+1]&1)&&c.keyFrameIndex===void 0&&(c.keyFrameIndex=O),j+=4,C?(y=fe(S,j),j+=4):y=m,k&&(j+=4),q&&(j+=4),g+=y,E+=y,X--);X--;)C?(y=fe(S,j),j+=4):y=m,k&&(j+=4),H&&(S[j+1]&1||c.keyFrameIndex===void 0&&(c.keyFrameIndex=c.sampleCount-(X+1),c.keyFrameStart=g),j+=4),q&&(j+=4),g+=y,E+=y;!E&&m&&(E+=m*L);}c.duration+=E;}if(!Object.keys(i).some(n=>i[n].duration)){let n=1/0,o=0,a=be(s,["sidx"]);for(let l=0;l<a.length;l++){let d=ik(a[l]);if(d!=null&&d.references){n=Math.min(n,d.earliestPresentationTime/d.timescale);let c=d.references.reduce((u,h)=>u+h.info.duration||0,0);o=Math.max(o,c+d.earliestPresentationTime/d.timescale);}}o&&Q(o)&&Object.keys(i).forEach(l=>{i[l].duration||(i[l].duration=o*i[l].timescale-i[l].start);});}return i}function lk(s){let e={valid:null,remainder:null},t=be(s,["moof"]);if(t.length<2)return e.remainder=s,e;let i=t[t.length-1];return e.valid=s.slice(0,i.byteOffset-8),e.remainder=s.slice(i.byteOffset-8),e}function pi(s,e){let t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function Lb(s,e){let t=[],i=e.samples,r=e.timescale,n=e.id,o=false;return be(i,["moof"]).map(l=>{let d=l.byteOffset-8;be(l,["traf"]).map(u=>{let h=be(u,["tfdt"]).map(f=>{let m=f[0],p=fe(f,4);return m===1&&(p*=Math.pow(2,32),p+=fe(f,8)),p/r})[0];return h!==void 0&&(s=h),be(u,["tfhd"]).map(f=>{let m=fe(f,4),p=fe(f,0)&16777215,g=(p&1)!==0,E=(p&2)!==0,y=(p&8)!==0,_=0,S=(p&16)!==0,L=0,O=(p&32)!==0,R=8;m===n&&(g&&(R+=8),E&&(R+=4),y&&(_=fe(f,R),R+=4),S&&(L=fe(f,R),R+=4),O&&(R+=4),e.type==="video"&&(o=vh(e.codec)),be(u,["trun"]).map(D=>{let C=D[0],k=fe(D,0)&16777215,H=(k&1)!==0,q=0,j=(k&4)!==0,X=(k&256)!==0,Y=0,x=(k&512)!==0,T=0,I=(k&1024)!==0,P=(k&2048)!==0,U=0,w=fe(D,4),B=8;H&&(q=fe(D,B),B+=4),j&&(B+=4);let z=q+d;for(let te=0;te<w;te++){if(X?(Y=fe(D,B),B+=4):Y=_,x?(T=fe(D,B),B+=4):T=L,I&&(B+=4),P&&(C===0?U=fe(D,B):U=$_(D,B),B+=4),e.type===Ve.VIDEO){let se=0;for(;se<T;){let re=fe(i,z);if(z+=4,dk(o,i[z])){let Ie=i.subarray(z,z+re);Jg(Ie,o?2:1,s+U/r,t);}z+=re,se+=re+4;}}s+=Y/r;}}));})});}),t}function vh(s){if(!s)return false;let e=s.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function dk(s,e){if(s){let t=e>>1&63;return t===39||t===40}else return (e&31)===6}function Jg(s,e,t,i){let r=K_(s),n=0;n+=e;let o=0,a=0,l=0;for(;n<r.length;){o=0;do{if(n>=r.length)break;l=r[n++],o+=l;}while(l===255);a=0;do{if(n>=r.length)break;l=r[n++],a+=l;}while(l===255);let d=r.length-n,c=n;if(a<d)n+=a;else if(a>d){Ue.error(`Malformed SEI payload. ${a} is too small, only ${d} bytes left to parse.`);break}if(o===4){if(r[c++]===181){let h=F_(r,c);if(c+=2,h===49){let f=fe(r,c);if(c+=4,f===1195456820){let m=r[c++];if(m===3){let p=r[c++],g=31&p,E=64&p,y=E?2+g*3:0,_=new Uint8Array(y);if(E){_[0]=p;for(let S=1;S<y;S++)_[S]=r[c++];}i.push({type:m,payloadType:o,pts:t,bytes:_});}}}}}else if(o===5&&a>16){let u=[];for(let m=0;m<16;m++){let p=r[c++].toString(16);u.push(p.length==1?"0"+p:p),(m===3||m===5||m===7||m===9)&&u.push("-");}let h=a-16,f=new Uint8Array(h);for(let m=0;m<h;m++)f[m]=r[c++];i.push({payloadType:o,pts:t,uuid:u.join(""),userData:ri(f),userDataBytes:f});}}}function K_(s){let e=s.byteLength,t=[],i=1;for(;i<e-2;)s[i]===0&&s[i+1]===0&&s[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return s;let r=e-t.length,n=new Uint8Array(r),o=0;for(i=0;i<r;o++,i++)o===t[0]&&(o++,t.shift()),n[i]=s[o];return n}function ck(s){let e=s[0],t="",i="",r=0,n=0,o=0,a=0,l=0,d=0;if(e===0){for(;gt(s.subarray(d,d+1))!=="\0";)t+=gt(s.subarray(d,d+1)),d+=1;for(t+=gt(s.subarray(d,d+1)),d+=1;gt(s.subarray(d,d+1))!=="\0";)i+=gt(s.subarray(d,d+1)),d+=1;i+=gt(s.subarray(d,d+1)),d+=1,r=fe(s,12),n=fe(s,16),a=fe(s,20),l=fe(s,24),d=28;}else if(e===1){d+=4,r=fe(s,d),d+=4;let u=fe(s,d);d+=4;let h=fe(s,d);for(d+=4,o=2**32*u+h,GR(o)||(o=Number.MAX_SAFE_INTEGER,Ue.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),a=fe(s,d),d+=4,l=fe(s,d),d+=4;gt(s.subarray(d,d+1))!=="\0";)t+=gt(s.subarray(d,d+1)),d+=1;for(t+=gt(s.subarray(d,d+1)),d+=1;gt(s.subarray(d,d+1))!=="\0";)i+=gt(s.subarray(d,d+1)),d+=1;i+=gt(s.subarray(d,d+1)),d+=1;}let c=s.subarray(d,s.byteLength);return {schemeIdUri:t,value:i,timeScale:r,presentationTime:o,presentationTimeDelta:n,eventDuration:a,id:l,payload:c}}function uk(s,...e){let t=e.length,i=8,r=t;for(;r--;)i+=e[r].byteLength;let n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(s,4),r=0,i=8;r<t;r++)n.set(e[r],i),i+=e[r].byteLength;return n}function hk(s,e,t){if(s.byteLength!==16)throw new RangeError("Invalid system id");let i,r;i=0,r=new Uint8Array;let n;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,false)):n=new Uint8Array;let o=new Uint8Array(4);return t.byteLength>0&&new DataView(o.buffer).setUint32(0,t.byteLength,false),uk([112,115,115,104],new Uint8Array([i,0,0,0]),s,n,r,o,t)}function fk(s){let e=[];if(s instanceof ArrayBuffer){let t=s.byteLength,i=0;for(;i+32<t;){let r=new DataView(s,i),n=mk(r);e.push(n),i+=n.size;}}return e}function mk(s){let e=s.getUint32(0),t=s.byteOffset,i=s.byteLength;if(i<e)return {offset:t,size:i};if(s.getUint32(4)!==1886614376)return {offset:t,size:e};let n=s.getUint32(8)>>>24;if(n!==0&&n!==1)return {offset:t,size:e};let o=s.buffer,a=It(new Uint8Array(o,t+12,16)),l=null,d=null,c=0;if(n===0)c=28;else {let h=s.getUint32(28);if(!h||i<32+h*16)return {offset:t,size:e};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(o,t+32+f*16,16));c=32+h*16;}if(!c)return {offset:t,size:e};let u=s.getUint32(c);return e-32<u?{offset:t,size:e}:(d=new Uint8Array(o,t+c+4,u),{version:n,systemId:a,kids:l,data:d,offset:t,size:e})}var V_=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),go={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function e0(s,e){let t=go[e];return !!t&&!!t[s.slice(0,4)]}function fl(s,e,t=true){return !s.split(",").some(i=>!t0(i,e,t))}function t0(s,e,t=true){var i;let r=sr(t);return (i=r?.isTypeSupported(ml(s,e)))!=null?i:false}function ml(s,e){return `${e}/mp4;codecs=${s}`}function Rb(s){if(s){let e=s.substring(0,4);return go.video[e]}return 2}function qu(s){let e=V_();return s.split(",").reduce((t,i)=>{let n=e&&vh(i)?9:go.video[i];return n?(n*2+t)/(t?3:2):(go.audio[i]+t)/(t?2:1)},0)}var fp={};function pk(s,e=true){if(fp[s])return fp[s];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let r=0;r<t.length;r++){var i;if(t0(t[r],"audio",e))return fp[s]=t[r],t[r];if(t[r]==="mp3"&&(i=sr(e))!=null&&i.isTypeSupported("audio/mpeg"))return ""}return s}var gk=/flac|opus|mp4a\.40\.34/i;function ju(s,e=true){return s.replace(gk,t=>pk(t.toLowerCase(),e))}function vk(s,e){let t=[];if(s){let i=s.split(",");for(let r=0;r<i.length;r++)e0(i[r],"video")||t.push(i[r]);}return e&&t.push(e),t.join(",")}function Fu(s,e){if(s&&(s.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(kb(s,"audio")||kb(s,"video")))return s;if(e){let t=e.split(",");if(t.length>1){if(s){for(let i=t.length;i--;)if(t[i].substring(0,4)===s.substring(0,4))return t[i]}return t[0]}}return e||s}function kb(s,e){return e0(s,e)&&t0(s,e)}function Ek(s){let e=s.split(",");for(let t=0;t<e.length;t++){let i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`);}return e.join(",")}function yk(s){if(s.startsWith("av01.")){let e=s.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return s}function wb(s){let e=sr(s)||{isTypeSupported:()=>false};return {mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Np(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var bk={supported:true,powerEfficient:true,smooth:true},_k={supported:false,smooth:false,powerEfficient:false},W_={supported:true,configurations:[],decodingInfoResults:[bk]};function q_(s,e){return {supported:false,configurations:e,decodingInfoResults:[_k],error:s}}function Tk(s,e,t,i,r,n){let o=s.videoCodec,a=s.audioCodec?s.audioGroups:null,l=n?.audioCodec,d=n?.channels,c=d?parseInt(d):l?1/0:2,u=null;if(a!=null&&a.length)try{a.length===1&&a[0]?u=e.groups[a[0]].channels:u=a.reduce((h,f)=>{if(f){let m=e.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(p=>{h[p]=(h[p]||0)+m.channels[p];});}return h},{2:0});}catch{return true}return o!==void 0&&(o.split(",").some(h=>vh(h))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(r,8e6))||!!u&&Q(c)&&Object.keys(u).some(h=>parseInt(h)>c)}function j_(s,e,t,i={}){let r=s.videoCodec;if(!r&&!s.audioCodec||!t)return Promise.resolve(W_);let n=[],o=Sk(s),a=o.length,l=Ak(s,e,a>0),d=l.length;for(let c=a||1*d||1;c--;){let u={type:"media-source"};if(a&&(u.video=o[c%a]),d){u.audio=l[c%d];let h=u.audio.bitrate;u.video&&h&&(u.video.bitrate-=h);}n.push(u);}if(r){let c=navigator.userAgent;if(r.split(",").some(u=>vh(u))&&V_())return Promise.resolve(q_(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${c})`),n))}return Promise.all(n.map(c=>{let u=xk(c);return i[u]||(i[u]=t.decodingInfo(c))})).then(c=>({supported:!c.some(u=>!u.supported),configurations:n,decodingInfoResults:c})).catch(c=>({supported:false,configurations:n,decodingInfoResults:[],error:c}))}function Sk(s){var e;let t=(e=s.videoCodec)==null?void 0:e.split(","),i=Y_(s),r=s.width||640,n=s.height||480,o=s.frameRate||30,a=s.videoRange.toLowerCase();return t?t.map(l=>{let d={contentType:ml(yk(l),"video"),width:r,height:n,bitrate:i,framerate:o};return a!=="sdr"&&(d.transferFunction=a),d}):[]}function Ak(s,e,t){var i;let r=(i=s.audioCodec)==null?void 0:i.split(","),n=Y_(s);return r&&s.audioGroups?s.audioGroups.reduce((o,a)=>{var l;let d=a?(l=e.groups[a])==null?void 0:l.tracks:null;return d?d.reduce((c,u)=>{if(u.groupId===a){let h=parseFloat(u.channels||"");r.forEach(f=>{let m={contentType:ml(f,"audio"),bitrate:t?Ik(f,n):n};h&&(m.channels=""+h),c.push(m);});}return c},o):o},[]):[]}function Ik(s,e){if(e<=1)return 1;let t=128e3;return s==="ec-3"?t=768e3:s==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Y_(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function xk(s){let e="",{audio:t,video:i}=s;if(i){let r=Np(i.contentType);e+=`${r}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`;}if(t){let r=Np(t.contentType);e+=`${i?"_":""}${r}_c${t.channels}`;}return e}var Fp=["NONE","TYPE-0","TYPE-1",null];function Lk(s){return Fp.indexOf(s)>-1}var Yu=["SDR","PQ","HLG"];function Rk(s){return !!s&&Yu.indexOf(s)>-1}var $u={No:"",Yes:"YES",v2:"v2"};function Cb(s){let{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,r=i<e/2;return e&&r?t?$u.v2:$u.Yes:$u.No}var zu=class{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i;}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},Jr=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`);}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES);}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Db(this._audioGroups,e)}hasSubtitleGroup(e){return Db(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t);}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t);}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return (e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return (e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function Db(s,e){return !e||!s?false:s.indexOf(e)!==-1}function kk(){if(typeof matchMedia=="function"){let s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===true}return false}function wk(s,e){let t=false,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||Yu.slice(0);let r=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&kk(),t||(i=["SDR"]);}return {preferHDR:t,allowedVideoRanges:i}}var Ck=s=>{let e=new WeakSet;return (t,i)=>{if(s&&(i=s(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i);}return i}},We=(s,e)=>JSON.stringify(s,Ck(e));function Dk(s,e,t,i,r){let n=Object.keys(s),o=i?.channels,a=i?.audioCodec,l=r?.videoCodec,d=o&&parseInt(o)===2,c=false,u=false,h=1/0,f=1/0,m=1/0,p=1/0,g=0,E=[],{preferHDR:y,allowedVideoRanges:_}=wk(e,r);for(let D=n.length;D--;){let C=s[n[D]];c||(c=C.channels[2]>0),h=Math.min(h,C.minHeight),f=Math.min(f,C.minFramerate),m=Math.min(m,C.minBitrate),_.filter(H=>C.videoRanges[H]>0).length>0&&(u=true);}h=Q(h)?h:0,f=Q(f)?f:0;let S=Math.max(1080,h),L=Math.max(30,f);m=Q(m)?m:t,t=Math.max(m,t),u||(e=void 0);let O=n.length>1;return {codecSet:n.reduce((D,C)=>{let k=s[C];if(C===D)return D;if(E=u?_.filter(H=>k.videoRanges[H]>0):[],O){if(k.minBitrate>t)return is(C,`min bitrate of ${k.minBitrate} > current estimate of ${t}`),D;if(!k.hasDefaultAudio)return is(C,"no renditions with default or auto-select sound found"),D;if(a&&C.indexOf(a.substring(0,4))%5!==0)return is(C,`audio codec preference "${a}" not found`),D;if(o&&!d){if(!k.channels[o])return is(C,`no renditions with ${o} channel sound found (channels options: ${Object.keys(k.channels)})`),D}else if((!a||d)&&c&&k.channels[2]===0)return is(C,"no renditions with stereo sound found"),D;if(k.minHeight>S)return is(C,`min resolution of ${k.minHeight} > maximum of ${S}`),D;if(k.minFramerate>L)return is(C,`min framerate of ${k.minFramerate} > maximum of ${L}`),D;if(!E.some(H=>k.videoRanges[H]>0))return is(C,`no variants with VIDEO-RANGE of ${We(E)} found`),D;if(l&&C.indexOf(l.substring(0,4))%5!==0)return is(C,`video codec preference "${l}" not found`),D;if(k.maxScore<g)return is(C,`max score of ${k.maxScore} < selected max of ${g}`),D}return D&&(qu(C)>=qu(D)||k.fragmentError>s[D].fragmentError)?D:(p=k.minIndex,g=k.maxScore,C)},void 0),videoRanges:E,preferHDR:y,minFramerate:f,minBitrate:m,minIndex:p}}function is(s,e){Ue.log(`[abr] start candidates with "${s}" ignored because ${e}`);}function z_(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:false,hasAutoSelect:false}),i.tracks.push(t);let r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=true),i.hasAutoSelect&&(e.hasAutoSelectAudio=true),e},{hasDefaultAudio:false,hasAutoSelectAudio:false,groups:{}})}function Mk(s,e,t,i){return s.slice(t,i+1).reduce((r,n,o)=>{if(!n.codecSet)return r;let a=n.audioGroups,l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:o,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);let d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,o),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,a&&a.forEach(c=>{if(!c)return;let u=e.groups[c];u&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(h=>{l.channels[h]=(l.channels[h]||0)+u.channels[h];}));}),r},{})}function Mb(s){if(!s)return s;let{lang:e,assocLang:t,characteristics:i,channels:r,audioCodec:n}=s;return {lang:e,assocLang:t,characteristics:i,channels:r,audioCodec:n}}function os(s,e,t){if("attrs"in s){let i=e.indexOf(s);if(i!==-1)return i}for(let i=0;i<e.length;i++){let r=e[i];if(Xr(s,r,t))return i}return -1}function Xr(s,e,t){let{groupId:i,name:r,lang:n,assocLang:o,default:a}=s,l=s.forced;return (i===void 0||e.groupId===i)&&(r===void 0||e.name===r)&&(n===void 0||Pk(n,e.lang))&&(n===void 0||e.assocLang===o)&&(a===void 0||e.default===a)&&(l===void 0||e.forced===l)&&(!("characteristics"in s)||Ok(s.characteristics||"",e.characteristics))&&(t===void 0||t(s,e))}function Pk(s,e="--"){return s.length===e.length?s===e:s.startsWith(e)||e.startsWith(s)}function Ok(s,e=""){let t=s.split(","),i=e.split(",");return t.length===i.length&&!t.some(r=>i.indexOf(r)===-1)}function zr(s,e){let{audioCodec:t,channels:i}=s;return (t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function Uk(s,e,t,i,r){let n=e[i],a=e.reduce((h,f,m)=>{let p=f.uri;return (h[p]||(h[p]=[])).push(m),h},{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));let l=n.videoRange,d=n.frameRate,c=n.codecSet.substring(0,4),u=Pb(e,i,h=>{if(h.videoRange!==l||h.frameRate!==d||h.codecSet.substring(0,4)!==c)return false;let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return os(s,m,r)>-1});return u>-1?u:Pb(e,i,h=>{let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return os(s,m,r)>-1})}function Pb(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i<s.length;i++)if(t(s[i]))return i;return -1}function Qu(s,e){var t;return !!s&&s!==((t=e.loadLevelObj)==null?void 0:t.uri)}var $p=class extends qt{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;let{fragCurrent:r,partCurrent:n,hls:o}=this,{autoLevelEnabled:a,media:l}=o;if(!r||!l)return;let d=performance.now(),c=n?n.stats:r.stats,u=n?n.duration:r.duration,h=d-c.loading.start,f=o.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||m<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!a)return;let g=p>-1&&p!==m,E=!!t||g;if(!E&&(l.paused||!l.playbackRate||!l.readyState))return;let y=o.mainForwardBufferInfo;if(!E&&y===null)return;let _=this.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(h<=Math.max(_,1e3*(u/(S*2))))return;let L=y?y.len/S:0,O=c.loading.first?c.loading.first-c.loading.start:-1,R=c.loaded&&O>-1,D=this.getBwEstimate(),C=o.levels,k=C[m],H=Math.max(c.loaded,Math.round(u*(r.bitrate||k.averageBitrate)/8)),q=R?h-O:h;q<1&&R&&(q=Math.min(h,c.loaded*8/D));let j=R?c.loaded*1e3/q:0,X=_/1e3,Y=j?(H-c.loaded)/j:H*8/D+X;if(Y<=L)return;let x=j?j*8:D,T=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===true,I=this.hls.config.abrBandWidthUpFactor,P=Number.POSITIVE_INFINITY,U;for(U=m-1;U>f;U--){let te=C[U].maxBitrate,se=!C[U].details||T;if(P=this.getTimeToLoadFrag(X,x,u*te,se),P<Math.min(L,u+X))break}if(P>=Y||P>u*10)return;R?this.bwEstimator.sample(h-Math.min(_,O),c.loaded):this.bwEstimator.sampleTTFB(h);let w=C[U].maxBitrate;this.getBwEstimate()*I>w&&this.resetEstimator(w);let B=this.findBestLevel(w,f,U,0,L,1,1);B>-1&&(U=B),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${m} is loading too slowly;
1926
+ Fragment duration: ${r.duration.toFixed(3)}
1927
+ Time to underbuffer: ${L.toFixed(3)} s
1928
+ Estimated load time for current fragment: ${Y.toFixed(3)} s
1929
+ Estimated load time for down switch fragment: ${P.toFixed(3)} s
1930
+ TTFB estimate: ${O|0} ms
1931
+ Current BW estimate: ${Q(D)?D|0:"Unknown"} bps
1932
+ New BW estimate: ${this.getBwEstimate()|0} bps
1933
+ Switching to level ${U} @ ${w|0} bps`),o.nextLoadLevel=o.nextAutoLevel=U,this.clearTimer();let z=()=>{if(this.clearTimer(),this.fragCurrent===r&&this.hls.loadLevel===U&&U>0){let te=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${U>0?"and switching down":""}
1934
+ Fragment duration: ${r.duration.toFixed(3)} s
1935
+ Time to underbuffer: ${te.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,U>f){let se=this.findBestLevel(this.hls.levels[f].bitrate,f,U,0,te,1,1);se===-1&&(se=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=se,this.resetEstimator(this.hls.levels[se].bitrate);}}};g||Y>P*2?z():this.timer=self.setInterval(z,P*1e3),o.trigger(v.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:c});},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners();}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator();}initEstimator(){let e=this.hls.config;return new Mp(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.FRAG_LOADING,this.onFragLoading,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this),e.on(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(v.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e&&(e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.FRAG_LOADING,this.onFragLoading,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this),e.off(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(v.ERROR,this.onError,this));}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null;}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer();}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null;}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey="";}onFragLoading(e,t){let i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=(r=t.part)!=null?r:null;}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100);}}onLevelSwitching(e,t){this.clearTimer();}onError(e,t){if(!t.fatal)switch(t.details){case M.BUFFER_ADD_CODEC_ERROR:case M.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case M.FRAG_LOAD_TIMEOUT:{let i=t.frag,{fragCurrent:r,partCurrent:n}=this;if(i&&r&&i.sn===r.sn&&i.level===r.level){let o=performance.now(),a=n?n.stats:i.stats,l=o-a.loading.start,d=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&d>-1){let u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,d),a.loaded);}else this.bwEstimator.sampleTTFB(l);}break}}}getTimeToLoadFrag(e,t,i,r){let n=e+i/t,o=r?e+this.lastLevelLoadSec:0;return n+o}onLevelLoaded(e,t){let i=this.hls.config,{loading:r}=t.stats,n=r.end-r.first;Q(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo);}onFragLoaded(e,{frag:t,part:i}){let r=i?i.stats:t.stats;if(t.type===J.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let n=i?i.duration:t.duration,o=this.hls.levels[t.level],a=(o.loaded?o.loaded.bytes:0)+r.loaded,l=(o.loaded?o.loaded.duration:0)+n;o.loaded={bytes:a,duration:l},o.realBitrate=Math.round(8*a/l);}if(t.bitrateTest){let n={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(v.FRAG_BUFFERED,n),t.bitrateTest=false;}else this.lastLoadedFragLevel=t.level;}}onFragBuffered(e,t){let{frag:i,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;let o=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=o/1e3:this.bitrateTestDelay=0;}ignoreFragment(e){return e.type!==J.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1);}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,t,e,0,r,1,1);if(n>-1)return n;let o=this.hls.firstLevel,a=Math.min(Math.max(o,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=i&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let o=this.hls.levels;if(o.length>Math.max(e,n)&&o[e].loadError<=o[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:r,config:n,minAutoLevel:o}=i,a=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay(),c=n.abrBandWidthFactor,u=n.abrBandWidthUpFactor;if(d){let g=this.findBestLevel(l,o,r,d,0,c,u);if(g>=0)return this.rebufferNotice=-1,g}let h=a?Math.min(a,n.maxStarvationDelay):n.maxStarvationDelay;if(!d){let g=this.bitrateTestDelay;g&&(h=(a?Math.min(a,n.maxLoadingDelay):n.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),c=u=1);}let f=this.findBestLevel(l,o,r,d,h,c,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let m=i.levels[o],p=i.loadLevelObj;return p&&m?.bitrate<p.bitrate?o:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return (r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,n,o,a){var l;let d=r+n,c=this.lastLoadedFragLevel,u=c===-1?this.hls.firstLevel:c,{fragCurrent:h,partCurrent:f}=this,{levels:m,allAudioTracks:p,loadLevel:g,config:E}=this.hls;if(m.length===1)return 0;let y=m[u],_=!!((l=this.hls.latestLevelDetails)!=null&&l.live),S=g===-1||c===-1,L,O="SDR",R=y?.frameRate||0,{audioPreference:D,videoPreference:C}=E,k=this.audioTracksByGroup||(this.audioTracksByGroup=z_(p)),H=-1;if(S){if(this.firstSelection!==-1)return this.firstSelection;let x=this.codecTiers||(this.codecTiers=Mk(m,k,t,i)),T=Dk(x,O,e,D,C),{codecSet:I,videoRanges:P,minFramerate:U,minBitrate:w,minIndex:B,preferHDR:z}=T;H=B,L=I,O=z?P[P.length-1]:P[0],R=U,e=Math.max(e,w),this.log(`picked start tier ${We(T)}`);}else L=y?.codecSet,O=y?.videoRange;let q=f?f.duration:h?h.duration:0,j=this.bwEstimator.getEstimateTTFB()/1e3,X=[];for(let x=i;x>=t;x--){var Y;let T=m[x],I=x>u;if(!T)continue;if(E.useMediaCapabilities&&!T.supportedResult&&!T.supportedPromise){let se=navigator.mediaCapabilities;typeof se?.decodingInfo=="function"&&Tk(T,k,O,R,e,D)?(T.supportedPromise=j_(T,k,se,this.supportedCache),T.supportedPromise.then(re=>{if(!this.hls)return;T.supportedResult=re;let Ie=this.hls.levels,dt=Ie.indexOf(T);re.error?this.warn(`MediaCapabilities decodingInfo error: "${re.error}" for level ${dt} ${We(re)}`):re.supported?re.decodingInfoResults.some(Pt=>Pt.smooth===false||Pt.powerEfficient===false)&&this.log(`MediaCapabilities decodingInfo for level ${dt} not smooth or powerEfficient: ${We(re)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${dt} ${We(re)}`),dt>-1&&Ie.length>1&&(this.log(`Removing unsupported level ${dt}`),this.hls.removeLevel(dt),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)));}).catch(re=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${re}`);})):T.supportedResult=W_;}if((L&&T.codecSet!==L||O&&T.videoRange!==O||I&&R>T.frameRate||!I&&R>0&&R<T.frameRate||(Y=T.supportedResult)!=null&&(Y=Y.decodingInfoResults)!=null&&Y.some(se=>se.smooth===false))&&(!S||x!==H)){X.push(x);continue}let P=T.details,U=(f?P?.partTarget:P?.averagetargetduration)||q,w;I?w=a*e:w=o*e;let B=q&&r>=q*2&&n===0?T.averageBitrate:T.maxBitrate,z=this.getTimeToLoadFrag(j,w,B*U,P===void 0);if(w>=B&&(x===c||T.loadError===0&&T.fragmentError===0)&&(z<=j||!Q(z)||_&&!this.bitrateTestDelay||z<d)){let se=this.forcedAutoLevel;return x!==g&&(se===-1||se!==g)&&(X.length&&this.trace(`Skipped level(s) ${X.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${m[X[0]].codecs}" ${m[X[0]].videoRange}; not compatible with "${L}" ${O}`),this.info(`switch candidate:${u}->${x} adjustedbw(${Math.round(w)})-bitrate=${Math.round(w-B)} ttfb:${j.toFixed(1)} avgDuration:${U.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${z.toFixed(1)} firstSelection:${S} codecSet:${T.codecSet} videoRange:${T.videoRange} hls.loadLevel:${g}`)),S&&(this.firstSelection=x),x}}return -1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t);}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},Q_={search:function(s,e){let t=0,i=s.length-1,r=null,n=null;for(;t<=i;){r=(t+i)/2|0,n=s[r];let o=e(n);if(o>0)t=r+1;else if(o<0)i=r-1;else return n}return null}};function Nk(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!Q(e))return null;let i=s[0].programDateTime;if(e<(i||0))return null;let r=s[s.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<s.length;++n){let o=s[n];if($k(e,t,o))return o}return null}function en(s,e,t=0,i=0,r=.005){let n=null;if(s){n=e[1+s.sn-e[0].sn]||null;let a=s.endDTS-t;a>0&&a<15e-7&&(t+=15e-7),n&&s.level!==n.level&&n.end<=s.end&&(n=e[2+s.sn-e[0].sn]||null);}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!s||s.level===n.level)&&Ob(t,i,n)===0||Fk(n,s,Math.min(r,i))))return n;let o=Q_.search(e,Ob.bind(null,t,i));return o&&(o!==s||!n)?o:n}function Fk(s,e,t){if(e&&e.start===0&&e.level<s.level&&(e.endPTS||0)>0){let i=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return s.start<=i}return false}function Ob(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function $k(s,e,t){let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return (t.endProgramDateTime||0)-i>s}function X_(s,e,t){if(s&&s.startCC<=e&&s.endCC>=e){let i=s.fragments,{fragmentHint:r}=s;r&&(i=i.concat(r));let n;return Q_.search(i,o=>o.cc<e?1:o.cc>e?-1:(n=o,o.end<=t?1:o.start>t?-1:0)),n||null}return null}function Xu(s){switch(s.details){case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_TIMEOUT:case M.LEVEL_LOAD_TIMEOUT:case M.MANIFEST_LOAD_TIMEOUT:return true}return false}function Z_(s){return s.details.startsWith("key")}function J_(s){return Z_(s)&&!!s.frag&&!s.frag.decryptdata}function Ub(s,e){let t=Xu(e);return s.default[`${t?"timeout":"error"}Retry`]}function i0(s,e){let t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function Nb(s){return Oe(Oe({},s),{errorRetry:null,timeoutRetry:null})}function Zu(s,e,t,i){if(!s)return false;let r=i?.code,n=e<s.maxNumRetry&&(Bk(r)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,i,n):n}function Bk(s){return Bp(s)||!!s&&(s<400||s>499)}function Bp(s){return s===0&&navigator.onLine===false}var St={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},ti={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4},Hp=class extends qt{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners();}registerListeners(){let e=this.hls;e.on(v.ERROR,this.onError,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this);}unregisterListeners(){let e=this.hls;e&&(e.off(v.ERROR,this.onError,this),e.off(v.ERROR,this.onErrorOut,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this));}destroy(){this.unregisterListeners(),this.hls=null;}startLoad(e){}stopLoad(){this.playlistError=0;}getVariantLevelIndex(e){return e?.type===J.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;return (e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return true;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(o=>r.indexOf(o.groupId)>=0).some(o=>{var a;return (a=o.details)==null?void 0:a.hasKey(t)})}return false}onManifestLoading(){this.playlistError=0;}onLevelUpdated(){this.playlistError=0;}onError(e,t){var i;if(t.fatal)return;let r=this.hls,n=t.context;switch(t.details){case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case M.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=ho();return}case M.FRAG_GAP:case M.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=St.SendAlternateToPenaltyBox;return}case M.LEVEL_EMPTY_ERROR:case M.LEVEL_PARSING_ERROR:{var o;let l=t.parent===J.MAIN?t.level:r.loadLevel;t.details===M.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(o=o.levelDetails)!=null&&o.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=false,t.errorAction=this.getLevelSwitchAction(t,l));}return;case M.LEVEL_LOAD_ERROR:case M.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case M.AUDIO_TRACK_LOAD_ERROR:case M.AUDIO_TRACK_LOAD_TIMEOUT:case M.SUBTITLE_LOAD_ERROR:case M.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let l=r.loadLevelObj;if(l&&(n.type===Te.AUDIO_TRACK&&l.hasAudioGroup(n.groupId)||n.type===Te.SUBTITLE_TRACK&&l.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=St.SendAlternateToPenaltyBox,t.errorAction.flags=ti.MoveAllAlternatesMatchingHost;return}}return;case M.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:St.SendAlternateToPenaltyBox,flags:ti.MoveAllAlternatesMatchingHDCP};return;case M.KEY_SYSTEM_SESSION_UPDATE_FAILED:case M.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case M.KEY_SYSTEM_NO_SESSION:t.errorAction={action:St.SendAlternateToPenaltyBox,flags:ti.MoveAllAlternatesMatchingKey};return;case M.BUFFER_ADD_CODEC_ERROR:case M.REMUX_ALLOC_ERROR:case M.BUFFER_APPEND_ERROR:if(!t.errorAction){var a;t.errorAction=this.getLevelSwitchAction(t,(a=t.level)!=null?a:r.loadLevel);}return;case M.INTERNAL_EXCEPTION:case M.BUFFER_APPENDING_ERROR:case M.BUFFER_FULL_ERROR:case M.LEVEL_SWITCH_ERROR:case M.BUFFER_STALLED_ERROR:case M.BUFFER_SEEK_OVER_HOLE:case M.BUFFER_NUDGE_ON_STALL:t.errorAction=ho();return}t.type===ie.KEY_SYSTEM_ERROR&&(t.levelRetry=false,t.errorAction=ho());}getPlaylistRetryOrSwitchAction(e,t){let i=this.hls,r=Ub(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(Zu(r,n,Xu(e),e.response))return {action:St.RetryRequest,flags:ti.None,retryConfig:r,retryCount:n};let a=this.getLevelSwitchAction(e,t);return r&&(a.retryConfig=r,a.retryCount=n),a}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:o}=t.config,a=Ub(Z_(e)?o:n,e),l=t.levels.reduce((c,u)=>c+u.fragmentError,0);if(r&&(e.details!==M.FRAG_GAP&&r.fragmentError++,!J_(e)&&Zu(a,l,Xu(e),e.response)))return {action:St.RetryRequest,flags:ti.None,retryConfig:a,retryCount:l};let d=this.getLevelSwitchAction(e,i);return a&&(d.retryConfig=a,d.retryCount=l),d}getLevelSwitchAction(e,t){let i=this.hls;t==null&&(t=i.loadLevel);let r=this.hls.levels[t];if(r){var n,o;let d=e.details;r.loadError++,d===M.BUFFER_APPEND_ERROR&&r.fragmentError++;let c=-1,{levels:u,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);let p=(n=e.frag)==null?void 0:n.type,E=(p===J.AUDIO&&d===M.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===M.BUFFER_ADD_CODEC_ERROR||d===M.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:O})=>r.audioCodec!==O),_=e.sourceBufferName==="video"&&(d===M.BUFFER_ADD_CODEC_ERROR||d===M.BUFFER_APPEND_ERROR)&&u.some(({codecSet:O,audioCodec:R})=>r.codecSet!==O&&r.audioCodec===R),{type:S,groupId:L}=(o=e.context)!=null?o:{};for(let O=u.length;O--;){let R=(O+h)%u.length;if(R!==h&&R>=f&&R<=m&&u[R].loadError===0){var a,l;let D=u[R];if(d===M.FRAG_GAP&&p===J.MAIN&&e.frag){let C=u[R].details;if(C){let k=en(e.frag,C.fragments,e.frag.start);if(k!=null&&k.gap)continue}}else {if(S===Te.AUDIO_TRACK&&D.hasAudioGroup(L)||S===Te.SUBTITLE_TRACK&&D.hasSubtitleGroup(L))continue;if(p===J.AUDIO&&(a=r.audioGroups)!=null&&a.some(C=>D.hasAudioGroup(C))||p===J.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(C=>D.hasSubtitleGroup(C))||E&&r.audioCodec===D.audioCodec||_&&r.codecSet===D.codecSet||!E&&r.codecSet!==D.codecSet)continue}c=R;break}}if(c>-1&&i.loadLevel!==c)return e.levelRetry=true,this.playlistError=0,{action:St.SendAlternateToPenaltyBox,flags:ti.None,nextAutoLevel:c}}return {action:St.SendAlternateToPenaltyBox,flags:ti.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case St.DoNothing:break;case St.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==M.FRAG_GAP?t.fatal=true:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:r}=i,n=i.nextAutoLevel;switch(r){case ti.None:this.switchLevel(e,n);break;case ti.MoveAllAlternatesMatchingHDCP:{let l=this.getVariantLevelIndex(e.frag),d=t.levels[l],c=d?.attrs["HDCP-LEVEL"];if(i.hdcpLevel=c,c==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(c){t.maxHdcpLevel=Fp[Fp.indexOf(c)-1],i.resolved=true,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case ti.MoveAllAlternatesMatchingKey:{let l=e.decryptdata;if(l){let d=this.hls.levels,c=d.length;for(let h=c;h--;)if(this.variantHasKey(d[h],l)){var o,a;this.log(`Banned key found in level ${h} (${d[h].bitrate}bps) or audio group "${(o=d[h].audioGroups)==null?void 0:o.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${It(l.keyId||[])}`),d[h].fragmentError++,d[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h);}let u=e.frag;if(this.hls.levels.length<c)i.resolved=true;else if(u&&u.type!==J.MAIN){let h=u.decryptdata;h&&!l.matches(h)&&(i.resolved=true);}}break}}i.resolved||this.switchLevel(e,n);}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=true,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===M.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let i=Np(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${n} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(n));}}};function ho(s){let e={action:St.DoNothing,flags:ti.None};return s&&(e.resolved=true),e}var vt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Gp=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=false,this.hls=e,this._registerListeners();}_registerListeners(){let{hls:e}=this;e&&(e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.BUFFER_APPENDED,this.onBufferAppended,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this));}_unregisterListeners(){let{hls:e}=this;e&&(e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.BUFFER_APPENDED,this.onBufferAppended,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this));}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null;}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let r=i.length;r--;){let n=i[r];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,true)}getFragAtPos(e,t,i){let{fragments:r}=this,n=Object.keys(r);for(let o=n.length;o--;){let a=r[n[o]];if(a?.body.type===t&&(!i||a.buffered)){let l=a.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,r,n){this.timeRanges&&(this.timeRanges[e]=t);let o=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(a=>{let l=this.fragments[a];if(!l||o>=l.body.sn)return;if(!l.buffered&&(!l.loaded||n)){l.body.type===i&&this.removeFragment(l.body);return}let d=l.range[e];if(d){if(d.time.length===0){this.removeFragment(l.body);return}d.time.some(c=>{let u=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return u&&this.removeFragment(l.body),u});}});}detectPartialFragments(e){let t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;let i=e.frag,r=ro(i),n=this.fragments[r];if(!n||n.buffered&&i.gap)return;let o=!i.relurl;Object.keys(t).forEach(a=>{let l=i.elementaryStreams[a];if(!l)return;let d=t[a],c=o||l.partial===true;n.range[a]=this.getBufferedTimes(i,e.part,c,d);}),n.loaded=null,Object.keys(n.range).length?(this.bufferedEnd(n,i),xu(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body);}bufferedEnd(e,t){e.buffered=true,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e);}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=Fb(i,r=>r.fragment.sn>=e));}fragBuffered(e,t){let i=ro(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:false,range:Object.create(null)},e.gap&&(this.hasGaps=true)),r&&(r.loaded=null,this.bufferedEnd(r,e));}getBufferedTimes(e,t,i,r){let n={time:[],partial:i},o=e.start,a=e.end,l=e.minEndPTS||a,d=e.maxStartPTS||o;for(let c=0;c<r.length;c++){let u=r.start(c)-this.bufferPadding,h=r.end(c)+this.bufferPadding;if(d>=u&&l<=h){n.time.push({startPTS:Math.max(o,r.start(c)),endPTS:Math.min(a,r.end(c))});break}else if(o<h&&a>u){let f=Math.max(o,r.start(c)),m=Math.min(a,r.end(c));m>f&&(n.partial=true,n.time.push({startPTS:f,endPTS:m}));}else if(a<=u)break}return n}getPartialFragment(e){let t=null,i,r,n,o=0,{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach(d=>{let c=l[d];c&&xu(c)&&(r=c.body.start-a,n=c.body.end+a,e>=r&&e<=n&&(i=Math.min(e-r,n-e),o<=i&&(t=c.body,o=i)));}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||xu(t))}getState(e){let t=ro(e),i=this.fragments[t];return i?i.buffered?xu(i)?vt.PARTIAL:vt.OK:vt.APPENDING:vt.NOT_LOADED}isTimeBuffered(e,t,i){let r,n;for(let o=0;o<i.length;o++){if(r=i.start(o)-this.bufferPadding,n=i.end(o)+this.bufferPadding,e>=r&&t<=n)return true;if(t<=r)return false}return false}onManifestLoading(){this.removeAllFragments();}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;let i=t.frag,r=t.part?null:t,n=ro(i);this.fragments[n]={body:i,appendedPTS:null,loaded:r,buffered:false,range:Object.create(null)};}onBufferAppended(e,t){let{frag:i,part:r,timeRanges:n,type:o}=t;if(i.sn==="initSegment")return;let a=i.type;if(r){let d=this.activePartLists[a];d||(this.activePartLists[a]=d=[]),d.push(r);}this.timeRanges=n;let l=n[o];this.detectEvictedFragments(o,l,a,r);}onFragBuffered(e,t){this.detectPartialFragments(t);}hasFragment(e){let t=ro(e);return !!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let r=i.length;r--;){let n=t[i[r]];if(n?.body.type===e)return true}return false}hasParts(e){var t;return !!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(o=>{let a=this.fragments[o];if(!a)return;let l=a.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(a.buffered||n)&&this.removeFragment(l);});}removeFragment(e){let t=ro(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let r=e.sn;this.activePartLists[e.type]=Fb(i,n=>n.fragment.sn!==r);}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type];}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=false;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo());}};function xu(s){var e,t,i;return s.buffered&&!!(s.body.gap||(e=s.range.video)!=null&&e.partial||(t=s.range.audio)!=null&&t.partial||(i=s.range.audiovideo)!=null&&i.partial)}function ro(s){return `${s.type}_${s.level}_${s.sn}`}function Fb(s,e){return s.filter(t=>{let i=e(t);return i||t.clearElementaryStreamInfo(),i})}var rr={cbc:0,ctr:1},Kp=class{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i;}decrypt(e,t){switch(this.aesMode){case rr.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case rr.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function Hk(s){let e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}var Vp=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable();}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let r=0;r<4;r++)i[r]=t.getUint32(r*4);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],o=i[2],a=i[3],l=this.invSubMix,d=l[0],c=l[1],u=l[2],h=l[3],f=new Uint32Array(256),m=0,p=0,g=0;for(g=0;g<256;g++)g<128?f[g]=g<<1:f[g]=g<<1^283;for(g=0;g<256;g++){let E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^E&255^99,e[m]=E,t[E]=m;let y=f[m],_=f[y],S=f[_],L=f[E]*257^E*16843008;r[m]=L<<24|L>>>8,n[m]=L<<16|L>>>16,o[m]=L<<8|L>>>24,a[m]=L,L=S*16843009^_*65537^y*257^m*16843008,d[E]=L<<24|L>>>8,c[E]=L<<16|L>>>16,u[E]=L<<8|L>>>24,h[E]=L,m?(m=y^f[f[f[S^y]]],p^=f[f[p]]):m=p=1;}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),i=true,r=0;for(;r<t.length&&i;)i=t[r]===this.key[r],r++;if(i)return;this.key=t;let n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);let o=this.ksRows=(n+6+1)*4,a,l,d=this.keySchedule=new Uint32Array(o),c=this.invKeySchedule=new Uint32Array(o),u=this.sBox,h=this.rcon,f=this.invSubMix,m=f[0],p=f[1],g=f[2],E=f[3],y,_;for(a=0;a<o;a++){if(a<n){y=d[a]=t[a];continue}_=y,a%n===0?(_=_<<8|_>>>24,_=u[_>>>24]<<24|u[_>>>16&255]<<16|u[_>>>8&255]<<8|u[_&255],_^=h[a/n|0]<<24):n>6&&a%n===4&&(_=u[_>>>24]<<24|u[_>>>16&255]<<16|u[_>>>8&255]<<8|u[_&255]),d[a]=y=(d[a-n]^_)>>>0;}for(l=0;l<o;l++)a=o-l,l&3?_=d[a]:_=d[a-4],l<4||a<=4?c[l]=_:c[l]=m[u[_>>>24]]^p[u[_>>>16&255]]^g[u[_>>>8&255]]^E[u[_&255]],c[l]=c[l]>>>0;}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){let r=this.keySize+6,n=this.invKeySchedule,o=this.invSBox,a=this.invSubMix,l=a[0],d=a[1],c=a[2],u=a[3],h=this.uint8ArrayToUint32Array_(i),f=h[0],m=h[1],p=h[2],g=h[3],E=new Int32Array(e),y=new Int32Array(E.length),_,S,L,O,R,D,C,k,H,q,j,X,Y,x,T=this.networkToHostOrderSwap;for(;t<E.length;){for(H=T(E[t]),q=T(E[t+1]),j=T(E[t+2]),X=T(E[t+3]),R=H^n[0],D=X^n[1],C=j^n[2],k=q^n[3],Y=4,x=1;x<r;x++)_=l[R>>>24]^d[D>>16&255]^c[C>>8&255]^u[k&255]^n[Y],S=l[D>>>24]^d[C>>16&255]^c[k>>8&255]^u[R&255]^n[Y+1],L=l[C>>>24]^d[k>>16&255]^c[R>>8&255]^u[D&255]^n[Y+2],O=l[k>>>24]^d[R>>16&255]^c[D>>8&255]^u[C&255]^n[Y+3],R=_,D=S,C=L,k=O,Y=Y+4;_=o[R>>>24]<<24^o[D>>16&255]<<16^o[C>>8&255]<<8^o[k&255]^n[Y],S=o[D>>>24]<<24^o[C>>16&255]<<16^o[k>>8&255]<<8^o[R&255]^n[Y+1],L=o[C>>>24]<<24^o[k>>16&255]<<16^o[R>>8&255]<<8^o[D&255]^n[Y+2],O=o[k>>>24]<<24^o[R>>16&255]<<16^o[D>>8&255]<<8^o[C&255]^n[Y+3],y[t]=T(_^f),y[t+1]=T(O^m),y[t+2]=T(L^p),y[t+3]=T(S^g),f=H,m=q,p=j,g=X,t=t+4;}return y.buffer}},Wp=class{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i;}expandKey(){let e=Gk(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},false,["encrypt","decrypt"])}};function Gk(s){switch(s){case rr.cbc:return "AES-CBC";case rr.ctr:return "AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${s}`)}}var Kk=16,pl=class{constructor(e,{removePKCS7Padding:t=true}={}){if(this.logEnabled=true,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle);}catch{}this.useSoftware=!this.subtle;}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null;}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Hk(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null);}decrypt(e,t,i,r){return this.useSoftware?new Promise((n,o)=>{let a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,i,r);let l=this.flush();l?n(l.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"));}):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)}softwareDecrypt(e,t,i,r){let{currentIV:n,currentResult:o,remainderData:a}=this;if(r!==rr.cbc||t.byteLength!==16)return Ue.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=pi(a,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;n&&(i=n);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new Vp),d.expandKey(t);let c=o;return this.currentResult=d.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,c||null}webCryptoDecrypt(e,t,i,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Wp(this.subtle,t,r);}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Kp(this.subtle,new Uint8Array(i),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(Ue.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,r)))}onWebCryptoError(e,t,i,r){let n=this.enableSoftwareAES;if(n){this.useSoftware=true,this.logEnabled=true,this.softwareDecrypt(e,t,i,r);let o=this.flush();if(o)return o.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%Kk;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Ue.log(`[decrypter]: ${e}`),this.logEnabled=false);}},$b=Math.pow(2,17),qp=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e;}destroy(){this.loader&&(this.loader.destroy(),this.loader=null);}abort(){this.loader&&this.loader.abort();}load(e,t){let i=e.url;if(!i)return Promise.reject(new xi({type:ie.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:false,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();let r=this.config,n=r.fLoader,o=r.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){l(Hb(e));return}else e.gap=false;let d=this.loader=n?new n(r):new o(r),c=Bb(e);e.loader=d;let u=Nb(r.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:$b};e.stats=d.stats;let f={onSuccess:(m,p,g,E)=>{this.resetLoader(e,d);let y=m.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(y.slice(0,16)),y=y.slice(16)),a({frag:e,part:null,payload:y,networkDetails:E});},onError:(m,p,g,E)=>{this.resetLoader(e,d),l(new xi({type:ie.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:false,frag:e,response:Oe({url:i,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:g,stats:E}));},onAbort:(m,p,g)=>{this.resetLoader(e,d),l(new xi({type:ie.NETWORK_ERROR,details:M.INTERNAL_ABORTED,fatal:false,frag:e,error:new Error("Aborted"),networkDetails:g,stats:m}));},onTimeout:(m,p,g)=>{this.resetLoader(e,d),l(new xi({type:ie.NETWORK_ERROR,details:M.FRAG_LOAD_TIMEOUT,fatal:false,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:m}));}};t&&(f.onProgress=(m,p,g,E)=>t({frag:e,part:null,payload:g,networkDetails:E})),d.load(c,h,f);})}loadPart(e,t,i){this.abort();let r=this.config,n=r.fLoader,o=r.loader;return new Promise((a,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Hb(e,t));return}let d=this.loader=n?new n(r):new o(r),c=Bb(e,t);e.loader=d;let u=Nb(r.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:$b};t.stats=d.stats,d.load(c,h,{onSuccess:(f,m,p,g)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);let E={frag:e,part:t,payload:f.data,networkDetails:g};i(E),a(E);},onError:(f,m,p,g)=>{this.resetLoader(e,d),l(new xi({type:ie.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:false,frag:e,part:t,response:Oe({url:c.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:g}));},onAbort:(f,m,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),l(new xi({type:ie.NETWORK_ERROR,details:M.INTERNAL_ABORTED,fatal:false,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}));},onTimeout:(f,m,p)=>{this.resetLoader(e,d),l(new xi({type:ie.NETWORK_ERROR,details:M.FRAG_LOAD_TIMEOUT,fatal:false,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}));}});})}updateStatsFromPart(e,t){let i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){let l=Math.round(e.duration/t.duration),d=Math.min(Math.round(i.loaded/n),l),u=(l-d)*Math.round(i.loaded/d);i.total=i.loaded+u;}else i.total=Math.max(i.loaded,i.total);let o=i.loading,a=r.loading;o.start?o.first+=a.first-a.start:(o.start=a.start,o.first=a.first),o.end=a.end;}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy();}};function Bb(s,e=null){let t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(Q(r)&&Q(n)){var o;let a=r,l=n;if(s.sn==="initSegment"&&Vk((o=s.decryptdata)==null?void 0:o.method)){let d=n-r;d%16&&(l=n+(16-d%16)),r!==0&&(i.resetIV=true,a=r-16);}i.rangeStart=a,i.rangeEnd=l;}return i}function Hb(s,e){let t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:ie.MEDIA_ERROR,details:M.FRAG_GAP,fatal:false,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=true,new xi(i)}function Vk(s){return s==="AES-128"||s==="AES-256"}var xi=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e;}},Ju=class extends qt{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this);}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed();}onHandlerDestroying(){this.clearNextTick(),this.clearInterval();}onHandlerDestroyed(){}hasInterval(){return !!this._tickInterval}hasNextTick(){return !!this._tickTimer}setInterval(e){return this._tickInterval?false:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),true)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,true):false}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,true):false}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0);}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0);}doTick(){}},gl=class{constructor(e,t,i,r=0,n=-1,o=false){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Lu(),this.buffering={audio:Lu(),video:Lu(),audiovideo:Lu()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=n,this.partial=o;}};function Lu(){return {start:0,executeStart:0,executeEnd:0,end:0}}var Gb={length:0,start:()=>0,end:()=>0},Ee=class s{static isBuffered(e,t){if(e){let i=s.getBuffered(e);for(let r=i.length;r--;)if(t>=i.start(r)&&t<=i.end(r))return true}return false}static bufferedRanges(e){if(e){let t=s.getBuffered(e);return s.timeRangesToArray(t)}return []}static timeRangesToArray(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){let r=s.bufferedRanges(e);if(r.length)return s.bufferedInfo(r,t,i)}return {len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((c,u)=>c.start-u.start||u.end-c.end);let r=-1,n=[];if(i)for(let c=0;c<e.length;c++){t>=e[c].start&&t<=e[c].end&&(r=c);let u=n.length;if(u){let h=n[u-1].end;e[c].start-h<i?e[c].end>h&&(n[u-1].end=e[c].end):n.push(e[c]);}else n.push(e[c]);}else n=e;let o=0,a,l=t,d=t;for(let c=0;c<n.length;c++){let u=n[c].start,h=n[c].end;if(r===-1&&t>=u&&t<=h&&(r=c),t+i>=u&&t<h)l=u,d=h,o=d-t;else if(t+i<u){a=u;break}}return {len:o,start:l||0,end:d||0,nextStart:a,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||Gb}catch(t){return Ue.log("failed to get media.buffered",t),Gb}}},eT=/\{\$([a-zA-Z0-9-_]+)\}/g;function Kb(s){return eT.test(s)}function jp(s,e){if(s.variableList!==null||s.hasVariableRefs){let t=s.variableList;return e.replace(eT,i=>{let r=i.substring(2,i.length-1),n=t?.[r];return n===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),i):n})}return e}function Vb(s,e,t){let i=s.variableList;i||(s.variableList=i={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{let o=new self.URL(t).searchParams;if(o.has(r))n=o.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(o){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${o.message}`));}}else r=e.NAME,n=e.VALUE;r in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):i[r]=n||"";}function Wk(s,e,t){let i=e.IMPORT;if(t&&i in t){let r=s.variableList;r||(s.variableList=r={}),r[i]=t[i];}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`));}var qk=/^(\d+)x(\d+)$/,Wb=/(.+?)=(".*?"|.*?)(?:,|$)/g,Je=class s{constructor(e,t){typeof e=="string"&&(e=s.parseAttrList(e,t)),Be(this,e);}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;let i=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return (i?i.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=true,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=qk.exec(this[e]);if(t!==null)return {width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,r={};for(Wb.lastIndex=0;(i=Wb.exec(e))!==null;){let o=i[1].trim(),a=i[2],l=a.indexOf('"')===0&&a.lastIndexOf('"')===a.length-1,d=false;if(l)a=a.slice(1,-1);else switch(o){case "IV":case "SCTE35-CMD":case "SCTE35-IN":case "SCTE35-OUT":d=true;}if(t&&(l||d))a=jp(t,a);else if(!d&&!l)switch(o){case "CLOSED-CAPTIONS":if(a==="NONE")break;case "ALLOWED-CPC":case "CLASS":case "ASSOC-LANGUAGE":case "AUDIO":case "BYTERANGE":case "CHANNELS":case "CHARACTERISTICS":case "CODECS":case "DATA-ID":case "END-DATE":case "GROUP-ID":case "ID":case "IMPORT":case "INSTREAM-ID":case "KEYFORMAT":case "KEYFORMATVERSIONS":case "LANGUAGE":case "NAME":case "PATHWAY-ID":case "QUERYPARAM":case "RECENTLY-REMOVED-DATERANGES":case "SERVER-URI":case "STABLE-RENDITION-ID":case "STABLE-VARIANT-ID":case "START-DATE":case "SUBTITLES":case "SUPPLEMENTAL-CODECS":case "URI":case "VALUE":case "VIDEO":case "X-ASSET-LIST":case "X-ASSET-URI":Ue.warn(`${e}: attribute ${o} is missing quotes`);}r[o]=a;}return r}},jk="com.apple.hls.interstitial";function Yk(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function zk(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}var eh=class{constructor(e,t,i=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(r=t?.tagOrder)!=null?r:i,t){let n=t.attr;for(let o in n)if(Object.prototype.hasOwnProperty.call(e,o)&&e[o]!==n[o]){Ue.warn(`DATERANGE tag attribute: "${o}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=o;break}e=Be(new Je({}),n,e);}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){let n=t?.endDate||new Date(this.attr["END-DATE"]);Q(n.getTime())&&(this._endDate=n);}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:false,post:false,once:false}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Ue.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(Q(e))return e}else if(this._endDate)return (this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return "PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===jk}get isValid(){return !!this.id&&!this._badValueForSameId&&Q(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)}},Qk=10,Yp=class{constructor(e){this.PTSKnown=false,this.alignedSliding=false,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=true,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=true,this.advanced=true,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=false,this.canSkipUntil=0,this.canSkipDateRanges=false,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=false,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e;}reloaded(e){if(!e){this.advanced=true,this.updated=true;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1;}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?Q(this.fragments[this.fragments.length-1].programDateTime):false}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Qk}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return (e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return (e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return (e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return false}};function th(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):false}function qb(s,e){return !s&&!e?true:!s||!e?false:th(s,e)}function fo(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function s0(s){switch(s){case "AES-128":case "AES-256":return rr.cbc;case "AES-256-CTR":return rr.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function r0(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function zp(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function Xk(s){let e=zp(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function tT(s){let e=function(i,r,n){let o=i[r];i[r]=i[n],i[n]=o;};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7);}function iT(s){let e=s.split(":"),t=null;if(e[0]==="data"&&e.length===2){let i=e[1].split(";"),r=i[i.length-1].split(",");if(r.length===2){let n=r[0]==="base64",o=r[1];n?(i.splice(-1,1),t=r0(o)):t=Xk(o);}}return t}var ih=typeof self<"u"?self:void 0,et={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},xt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Bu(s){switch(s){case xt.FAIRPLAY:return et.FAIRPLAY;case xt.PLAYREADY:return et.PLAYREADY;case xt.WIDEVINE:return et.WIDEVINE;case xt.CLEARKEY:return et.CLEARKEY}}function mp(s){switch(s){case et.FAIRPLAY:return xt.FAIRPLAY;case et.PLAYREADY:return xt.PLAYREADY;case et.WIDEVINE:return xt.WIDEVINE;case et.CLEARKEY:return xt.CLEARKEY}}function al(s){let{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[et.FAIRPLAY,et.WIDEVINE,et.PLAYREADY,et.CLEARKEY].filter(r=>!!e[r]):[];return !i[et.WIDEVINE]&&t&&i.push(et.WIDEVINE),i}var sT=(function(s){return ih!=null&&(s=ih.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function Zk(s,e,t,i){let r;switch(s){case et.FAIRPLAY:r=["cenc","sinf"];break;case et.WIDEVINE:case et.PLAYREADY:r=["cenc"];break;case et.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return Jk(r,e,t,i)}function Jk(s,e,t,i){return [{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function ew(s){var e;return !!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function rT(s){let e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),o=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(o){let a=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(a){let l=r0(a).subarray(0,16);return tT(l),l}}return null}var no={},vo=class s{static clearKeyUriToKeyIdMap(){no={};}static setKeyIdForUri(e,t){no[e]=t;}static addKeyIdForUri(e){let t=Object.keys(no).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),no[e]=i,i}constructor(e,t,i,r=[1],n=null,o){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":false,this.isCommonEncryption=this.encrypted&&!fo(e),o!=null&&o.startsWith("0x")&&(this.keyId=new Uint8Array(O_(o)));}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&th(e.keyFormatVersions,this.keyFormatVersions)&&qb(e.iv,this.iv)&&qb(e.keyId,this.keyId)}isSupported(){if(this.method){if(fo(this.method)||this.method==="NONE")return true;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case xt.FAIRPLAY:case xt.WIDEVINE:case xt.PLAYREADY:case xt.CLEARKEY:return ["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return false}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(fo(this.method)){let n=this.iv;return n||(typeof e!="number"&&(Ue.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=iw(e)),new s(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){let n=no[this.uri];if(n&&!th(this.keyId,n)&&s.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let i=iT(this.uri);if(i)switch(this.keyFormat){case xt.WIDEVINE:if(this.pssh=i,!this.keyId){let n=fk(i.buffer);if(n.length){var r;let o=n[0];this.keyId=(r=o.kids)!=null&&r.length?o.kids[0]:null;}}this.keyId||(this.keyId=jb(t));break;case xt.PLAYREADY:{let n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=hk(n,null,i),this.keyId=rT(i);break}default:{let n=i.subarray(0,16);if(n.length!==16){let o=new Uint8Array(16);o.set(n,16-n.length),n=o;}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=tw(t),n||(n=jb(t),n||(n=no[this.uri])),n&&(this.keyId=n,s.setKeyIdForUri(this.uri,n));}return this}};function tw(s){let e=s?.[xt.WIDEVINE];return e?e.keyId:null}function jb(s){let e=s?.[xt.PLAYREADY];if(e){let t=iT(e.uri);if(t)return rT(t)}return null}function iw(s){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}var Yb=/#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,zb=/#EXT-X-MEDIA:(.*)/g,sw=/^#EXT(?:INF|-X-TARGETDURATION):/m,pp=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),rw=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("|")),Qr=class s{static findGroup(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r.id===t)return r}}static resolve(e,t){return Zg.buildAbsoluteURL(t,e,{alwaysNormalize:true})}static isMediaPlaylist(e){return sw.test(e)}static parseMasterPlaylist(e,t){let i=Kb(e),r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];if(Yb.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let o;for(;(o=Yb.exec(e))!=null;)if(o[1]){var a;let d=new Je(o[1],r),c=jp(r,o[2]),u={attrs:d,bitrate:d.decimalInteger("BANDWIDTH")||d.decimalInteger("AVERAGE-BANDWIDTH"),name:d.NAME,url:s.resolve(c,t)},h=d.decimalResolution("RESOLUTION");h&&(u.width=h.width,u.height=h.height),Zb(d.CODECS,u);let f=d["SUPPLEMENTAL-CODECS"];f&&(u.supplemental={},Zb(f,u.supplemental)),(a=u.unknownCodecs)!=null&&a.length||n.push(u),r.levels.push(u);}else if(o[3]){let d=o[3],c=o[4];switch(d){case "SESSION-DATA":{let u=new Je(c,r),h=u["DATA-ID"];h&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[h]=u);break}case "SESSION-KEY":{let u=Qb(c,t,r);u.encrypted&&u.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(u)):Ue.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case "DEFINE":{{let u=new Je(c,r);Vb(r,u,t);}break}case "CONTENT-STEERING":{let u=new Je(c,r);r.contentSteering={uri:s.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case "START":{r.startTimeOffset=Xb(c);break}}}let l=n.length>0&&n.length<r.levels.length;return r.levels=l?n:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,i){let r,n={},o=i.levels,a={AUDIO:o.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:o.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(zb.lastIndex=0;(r=zb.exec(e))!==null;){let d=new Je(r[1],i),c=d.TYPE;if(c){let u=a[c],h=n[c]||[];n[c]=h;let f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],p=d.CHANNELS,g=d.CHARACTERISTICS,E=d["INSTREAM-ID"],y={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:c,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?s.resolve(d.URI,t):""};if(m&&(y.assocLang=m),p&&(y.channels=p),g&&(y.characteristics=g),E&&(y.instreamId=E),u!=null&&u.length){let _=s.findGroup(u,y.groupId)||u[0];Jb(y,_,"audioCodec"),Jb(y,_,"textCodec");}h.push(y);}}return n}static parseLevelPlaylist(e,t,i,r,n,o){var a;let l={url:t},d=new Yp(t),c=d.fragments,u=[],h=null,f=0,m=0,p=0,g=0,E=0,y=null,_=new ll(r,l),S,L,O,R=-1,D=false,C=null,k;if(pp.lastIndex=0,d.m3u8=e,d.hasVariableRefs=Kb(e),((a=pp.exec(e))==null?void 0:a[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(S=pp.exec(e))!==null;){D&&(D=false,_=new ll(r,l),_.playlistOffset=p,_.setStart(p),_.sn=f,_.cc=g,E&&(_.bitrate=E),_.level=i,h&&(_.initSegment=h,h.rawProgramDateTime&&(_.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),C&&(_.setByteRange(C),C=null)));let X=S[1];if(X){_.duration=parseFloat(X);let Y=(" "+S[2]).slice(1);_.title=Y||null,_.tagList.push(Y?["INF",X,Y]:["INF",X]);}else if(S[3]){if(Q(_.duration)){_.playlistOffset=p,_.setStart(p),O&&t_(_,O,d),_.sn=f,_.level=i,_.cc=g,c.push(_);let Y=(" "+S[3]).slice(1);_.relurl=jp(d,Y),Qp(_,y,u),y=_,p+=_.duration,f++,m=0,D=true;}}else {if(S=S[0].match(rw),!S){Ue.warn("No matches on slow regex match for level playlist!");continue}for(L=1;L<S.length&&S[L]===void 0;L++);let Y=(" "+S[L]).slice(1),x=(" "+S[L+1]).slice(1),T=S[L+2]?(" "+S[L+2]).slice(1):null;switch(Y){case "BYTERANGE":y?_.setByteRange(x,y):_.setByteRange(x);break;case "PROGRAM-DATE-TIME":_.rawProgramDateTime=x,_.tagList.push(["PROGRAM-DATE-TIME",x]),R===-1&&(R=c.length);break;case "PLAYLIST-TYPE":d.type&&xs(d,Y,S),d.type=x.toUpperCase();break;case "MEDIA-SEQUENCE":d.startSN!==0?xs(d,Y,S):c.length>0&&i_(d,Y,S),f=d.startSN=parseInt(x);break;case "SKIP":{d.skippedSegments&&xs(d,Y,S);let I=new Je(x,d),P=I.decimalInteger("SKIPPED-SEGMENTS");if(Q(P)){d.skippedSegments+=P;for(let w=P;w--;)c.push(null);f+=P;}let U=I.enumeratedString("RECENTLY-REMOVED-DATERANGES");U&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(U.split(" ")));break}case "TARGETDURATION":d.targetduration!==0&&xs(d,Y,S),d.targetduration=Math.max(parseInt(x),1);break;case "VERSION":d.version!==null&&xs(d,Y,S),d.version=parseInt(x);break;case "INDEPENDENT-SEGMENTS":break;case "ENDLIST":d.live||xs(d,Y,S),d.live=false;break;case "#":(x||T)&&_.tagList.push(T?[x,T]:[x]);break;case "DISCONTINUITY":g++,_.tagList.push(["DIS"]);break;case "GAP":_.gap=true,_.tagList.push([Y]);break;case "BITRATE":_.tagList.push([Y,x]),E=parseInt(x)*1e3,Q(E)?_.bitrate=E:E=0;break;case "DATERANGE":{let I=new Je(x,d),P=new eh(I,d.dateRanges[I.ID],d.dateRangeTagCount);d.dateRangeTagCount++,P.isValid||d.skippedSegments?d.dateRanges[P.id]=P:Ue.warn(`Ignoring invalid DATERANGE tag: "${x}"`),_.tagList.push(["EXT-X-DATERANGE",x]);break}case "DEFINE":{{let I=new Je(x,d);"IMPORT"in I?Wk(d,I,o):Vb(d,I,t);}break}case "DISCONTINUITY-SEQUENCE":d.startCC!==0?xs(d,Y,S):c.length>0&&i_(d,Y,S),d.startCC=g=parseInt(x);break;case "KEY":{let I=Qb(x,t,d);if(I.isSupported()){if(I.method==="NONE"){O=void 0;break}O||(O={});let P=O[I.keyFormat];P!=null&&P.matches(I)||(P&&(O=Be({},O)),O[I.keyFormat]=I);}else Ue.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${x}"`);break}case "START":d.startTimeOffset=Xb(x);break;case "MAP":{let I=new Je(x,d);if(_.duration){let P=new ll(r,l);e_(P,I,i,O),h=P,_.initSegment=h,h.rawProgramDateTime&&!_.rawProgramDateTime&&(_.rawProgramDateTime=h.rawProgramDateTime);}else {let P=_.byteRangeEndOffset;if(P){let U=_.byteRangeStartOffset;C=`${P-U}@${U}`;}else C=null;e_(_,I,i,O),h=_,D=true;}h.cc=g;break}case "SERVER-CONTROL":{k&&xs(d,Y,S),k=new Je(x),d.canBlockReload=k.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=k.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&k.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=k.optionalFloat("PART-HOLD-BACK",0),d.holdBack=k.optionalFloat("HOLD-BACK",0);break}case "PART-INF":{d.partTarget&&xs(d,Y,S);let I=new Je(x);d.partTarget=I.decimalFloatingPoint("PART-TARGET");break}case "PART":{let I=d.partList;I||(I=d.partList=[]);let P=m>0?I[I.length-1]:void 0,U=m++,w=new Je(x,d),B=new Up(w,_,l,U,P);I.push(B),_.duration+=B.duration;break}case "PRELOAD-HINT":{let I=new Je(x,d);d.preloadHint=I;break}case "RENDITION-REPORT":{let I=new Je(x,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(I);break}default:Ue.warn(`line parsed but not handled: ${S}`);break}}}y&&!y.relurl?(c.pop(),p-=y.duration,d.partList&&(d.fragmentHint=y)):d.partList&&(Qp(_,y,u),_.cc=g,d.fragmentHint=_,O&&t_(_,O,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));let H=c.length,q=c[0],j=c[H-1];if(p+=d.skippedSegments*d.targetduration,p>0&&H&&j){d.averagetargetduration=p/H;let X=j.sn;d.endSN=X!=="initSegment"?X:0,d.live||(j.endList=true),R>0&&(ow(c,R),q&&u.unshift(q));}return d.fragmentHint&&(p+=d.fragmentHint.duration),d.totalduration=p,u.length&&d.dateRangeTagCount&&q&&nT(u,d),d.endCC=g,d}};function nT(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){let a=e.fragments[e.fragments.length-1];s.push(a),t++;}else return;let i=s[t-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let a=n.length;a--;){let l=e.dateRanges[n[a]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let c=t;c--;){var o;if(((o=s[c])==null?void 0:o.sn)<e.startSN)break;let u=nw(e,d,s,c,r);if(u!==-1){l.tagAnchor=e.fragments[u].ref;break}}}}function nw(s,e,t,i,r){let n=t[i];if(n){let a=n.programDateTime;if(e>=a||i===0){var o;let l=(((o=t[i+1])==null?void 0:o.start)||r)-n.start;if(e<=a+l*1e3){let d=t[i].sn-s.startSN;if(d<0)return -1;let c=s.fragments;if(c.length>t.length){let h=(t[i+1]||c[c.length-1]).sn-s.startSN;for(let f=h;f>d;f--){let m=c[f].programDateTime;if(e>=m&&e<m+c[f].duration*1e3)return f}}return d}}}return -1}function Qb(s,e,t){var i,r;let n=new Je(s,t),o=(i=n.METHOD)!=null?i:"",a=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=(r=n.KEYFORMAT)!=null?r:"identity";a&&n.IV&&!l&&Ue.error(`Invalid IV: ${n.IV}`);let u=a?Qr.resolve(a,e):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new vo(o,u,c,h,l,n.KEYID)}function Xb(s){let t=new Je(s).decimalFloatingPoint("TIME-OFFSET");return Q(t)?t:null}function Zb(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{let r=t.filter(n=>e0(n,i));r.length&&(e[`${i}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1));}),e.unknownCodecs=t;}function Jb(s,e,t){let i=e[t];i&&(s[t]=i);}function ow(s,e){let t=s[e];for(let i=e;i--;){let r=s[i];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r;}}function Qp(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime);}function e_(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null;}function t_(s,e,t){s.levelkeys=e;let{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&i.push(s);}function xs(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`);}function i_(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`);}function gp(s,e){let t=e.startPTS;if(Q(t)){let i=0,r;e.sn>s.sn?(i=t-s.start,r=s):(i=s.start-t,r=e),r.duration!==i&&r.setDuration(i);}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.setStart(s.start+(s.minEndPTS-s.start)):e.setStart(s.start+s.duration):e.setStart(Math.max(s.start-e.duration,0));}function oT(s,e,t,i,r,n,o){i-t<=0&&(o.warn("Fragment should have a positive duration",e),i=t+e.duration,n=r+e.duration);let l=t,d=i,c=e.startPTS,u=e.endPTS;if(Q(c)){let E=Math.abs(c-t);s&&E>s.totalduration?o.warn(`media timestamps and playlist times differ by ${E}s for level ${e.level} ${s.url}`):Q(e.deltaPTS)?e.deltaPTS=Math.max(E,e.deltaPTS):e.deltaPTS=E,l=Math.max(t,c),t=Math.min(t,c),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,d=Math.min(i,u),i=Math.max(i,u),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n;}let h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=r,e.endPTS=i,e.minEndPTS=d,e.endDTS=n;let f=e.sn;if(!s||f<s.startSN||f>s.endSN)return 0;let m,p=f-s.startSN,g=s.fragments;for(g[p]=e,m=p;m>0;m--)gp(g[m],g[m-1]);for(m=p;m<g.length-1;m++)gp(g[m],g[m+1]);return s.fragmentHint&&gp(g[g.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=true,h}function aw(s,e,t){if(s===e)return;let i=null,r=s.fragments;for(let c=r.length-1;c>=0;c--){let u=r[c].initSegment;if(u){i=u;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let n;cw(s,e,(c,u,h,f)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==c.cc){let m=c.cc-u.cc;for(let p=h;p<f.length;p++)f[p].cc+=m;e.endCC=f[f.length-1].cc;}Q(c.startPTS)&&Q(c.endPTS)&&(u.setStart(u.startPTS=c.startPTS),u.startDTS=c.startDTS,u.maxStartPTS=c.maxStartPTS,u.endPTS=c.endPTS,u.endDTS=c.endDTS,u.minEndPTS=c.minEndPTS,u.setDuration(c.endPTS-c.startPTS),u.duration&&(n=u),e.PTSKnown=e.alignedSliding=true),c.hasStreams&&(u.elementaryStreams=c.elementaryStreams),u.loader=c.loader,c.hasStats&&(u.stats=c.stats),c.initSegment&&(u.initSegment=c.initSegment,i=c.initSegment);});let o=e.fragments,a=e.fragmentHint?o.concat(e.fragmentHint):o;if(i&&a.forEach(c=>{var u;c&&(!c.initSegment||c.initSegment.relurl===((u=i)==null?void 0:u.relurl))&&(c.initSegment=i);}),e.skippedSegments){if(e.deltaUpdateFailed=o.some(c=>!c),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=e.skippedSegments;c--;)o.shift();e.startSN=o[0].sn;}else {e.canSkipDateRanges&&(e.dateRanges=lw(s.dateRanges,e,t));let c=s.fragments.filter(u=>u.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<a.length;u++)a[u].programDateTime===null&&Qp(a[u],a[u-1],c);nT(c,e);}e.endCC=o[o.length-1].cc;}if(!e.startCC){var l;let c=dT(s,e.startSN-1);e.startCC=(l=c?.cc)!=null?l:o[0].cc;}dw(s.partList,e.partList,(c,u)=>{u.elementaryStreams=c.elementaryStreams,u.stats=c.stats;}),n?oT(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):aT(s,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;let d=e.advancedDateTime;if(e.advanced&&d){let c=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=c),e.driftEndTime=d,e.driftEnd=c;}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled);}function lw(s,e,t){let{dateRanges:i,recentlyRemovedDateranges:r}=e,n=Be({},s);r&&r.forEach(l=>{delete n[l];});let a=Object.keys(n).length;return a?(Object.keys(i).forEach(l=>{let d=n[l],c=new eh(i[l].attr,d);c.isValid?(n[l]=c,d||(c.tagOrder+=a)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${We(i[l].attr)}"`);}),n):i}function dw(s,e,t){if(s&&e){let i=0;for(let r=0,n=s.length;r<=n;r++){let o=s[r],a=e[r+i];o&&a&&o.index===a.index&&o.fragment.sn===a.fragment.sn?t(o,a):i--;}}}function cw(s,e,t){let i=e.skippedSegments,r=Math.max(s.startSN,e.startSN)-e.startSN,n=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,o=e.startSN-s.startSN,a=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=r;d<=n;d++){let c=l[o+d],u=a[d];if(i&&!u&&c&&(u=e.fragments[d]=c),c&&u){t(c,u,d,a);let h=c.relurl,f=u.relurl;if(h&&uw(h,f)){e.playlistParsingError=s_(`media sequence mismatch ${u.sn}:`,s,e,c,u);return}else if(c.cc!==u.cc){e.playlistParsingError=s_(`discontinuity sequence mismatch (${c.cc}!=${u.cc})`,s,e,c,u);return}}}}function s_(s,e,t,i,r){return new Error(`${s} ${r.url}
1936
+ Playlist starting @${e.startSN}
1937
+ ${e.m3u8}
1938
+
1939
+ Playlist starting @${t.startSN}
1940
+ ${t.m3u8}`)}function aT(s,e,t=true){let i=e.startSN+e.skippedSegments-s.startSN,r=s.fragments,n=i>=0,o=0;if(n&&i<r.length)o=r[i].start;else if(n&&e.startSN===s.endSN+1)o=s.fragmentEnd;else if(n&&t)o=s.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=s.fragmentStart;else return;Xp(e,o);}function Xp(s,e){if(e){let t=s.fragments;for(let i=s.skippedSegments;i<t.length;i++)t[i].addStart(e);s.fragmentHint&&s.fragmentHint.addStart(e);}}function lT(s,e=1/0){let t=1e3*s.targetduration;if(s.updated){let i=s.fragments;if(i.length&&t*4>e){let n=i[i.length-1].duration*1e3;n<t&&(t=n);}}else t/=2;return Math.round(t)}function dT(s,e,t){if(!s)return null;let i=s.fragments[e-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===e)?i:e<s.startSN&&t&&t.sn===e?t:null}function r_(s,e,t){return s?cT(s.partList,e,t):null}function cT(s,e,t){if(s)for(let i=s.length;i--;){let r=s[i];if(r.index===t&&r.fragment.sn===e)return r}return null}function uT(s){s.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t);});});}function uw(s,e){return s!==e&&e?n_(s)!==n_(e):false}function n_(s){return s.replace(/\?[^?]*$/,"")}function dl(s,e){for(let i=0,r=s.length;i<r;i++){var t;if(((t=s[i])==null?void 0:t.cc)===e)return s[i]}return null}function hw(s,e){return !!(s&&e.startCC<s.endCC&&e.endCC>s.startCC)}function o_(s,e){let t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration;}function hT(s,e){let t=e.fragments;for(let i=0,r=t.length;i<r;i++)o_(t[i],s);e.fragmentHint&&o_(e.fragmentHint,s),e.alignedSliding=true;}function fw(s,e){s&&(fT(e,s),e.alignedSliding||sh(e,s),!e.alignedSliding&&!e.skippedSegments&&aT(s,e,false));}function fT(s,e){if(!hw(e,s))return;let t=Math.min(e.endCC,s.endCC),i=dl(e.fragments,t),r=dl(s.fragments,t);if(!i||!r)return;Ue.log(`Aligning playlist at start of dicontinuity sequence ${t}`);let n=i.start-r.start;hT(n,s);}function sh(s,e){if(!s.hasProgramDateTime||!e.hasProgramDateTime)return;let t=s.fragments,i=e.fragments;if(!t.length||!i.length)return;let r,n,o=Math.min(e.endCC,s.endCC);e.startCC<o&&s.startCC<o&&(r=dl(i,o),n=dl(t,o)),(!r||!n)&&(r=i[Math.floor(i.length/2)],n=dl(t,r.cc)||t[Math.floor(t.length/2)]);let a=r.programDateTime,l=n.programDateTime;if(!a||!l)return;let d=(l-a)/1e3-(n.start-r.start);hT(d,s);}function $t(s,e,t){Wt(s,e,t),s.addEventListener(e,t);}function Wt(s,e,t){s.removeEventListener(e,t);}var mw={toString:function(s){let e="",t=s.length;for(let i=0;i<t;i++)e+=`[${s.start(i).toFixed(3)}-${s.end(i).toFixed(3)}]`;return e}},G={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},vl=class extends Ju{constructor(e,t,i,r,n){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=G.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=false,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=false,this.decrypter=void 0,this.initPTS=[],this.buffering=true,this.loadingParts=false,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:o,fragCurrent:a,media:l,mediaBuffer:d,state:c}=this,u=l?l.currentTime:0,h=Ee.bufferInfo(d||l,u,o.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${Q(u)?u.toFixed(3):u}, state: ${c}, ${f?"out of":"in"} buffer`),this.state===G.ENDED)this.resetLoadingState();else if(a){let m=o.maxFragLookUpTolerance,p=a.start-m,g=a.start+a.duration+m;if(f||g<h.start||p>h.end){let E=u>g;(u<p||E)&&(E&&a.loader&&(this.log(`Cancelling fragment load for seek (sn: ${a.sn})`),a.abortRequests(),this.resetLoadingState()),this.fragPrevious=null);}}if(l){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,true);let m=this.lastCurrentTime;if(u>m&&(this.lastCurrentTime=u),!this.loadingParts){let p=Math.max(h.end,u),g=this.shouldLoadParts(this.getLevelDetails(),p);g&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=g);}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,f&&(this.startPosition=u)),f&&this.state===G.IDLE&&this.tickImmediate();},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0;},this.playlistType=n,this.hls=e,this.fragmentLoader=new qp(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new pl(e.config);}registerListeners(){let{hls:e}=this;e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.ERROR,this.onError,this);}doTick(){this.onTickEnd();}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===G.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=G.STOPPED;}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=false;}resumeBuffering(){this.buffering=true;}get inFlightFrag(){return {frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return false;let i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return false;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=Ee.bufferedInfo(n,e.start,0));let o=e.nextStart;if(o&&o>r&&o<t.edge||this.media.currentTime<e.start)return false;let l=t.partList;if(l!=null&&l.length){let c=l[l.length-1];return Ee.isBuffered(this.media,c.start+c.duration/2)}let d=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(d)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return ((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;$t(i,"seeking",this.onMediaSeeking),$t(i,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===G.STOPPED&&this.startLoad(r.startPosition);}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Wt(r,"seeking",this.onMediaSeeking),Wt(r,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=false,this.fragmentTracker.removeAllFragments(),this.stopLoad();}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=false;}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset;}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null;}onHandlerDestroyed(){this.state=G.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed();}loadFragment(e,t,i){this.startFragRequested=true,this._loadFragForPlayback(e,t,i);}_loadFragForPlayback(e,t,i){let r=n=>{let o=n.frag;if(this.fragContextChanged(o)){this.warn(`${o.type} sn: ${o.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(o,false,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(o);return}o.stats.chunkCount++,this._handleFragmentLoadProgress(n);};this._doFragLoad(e,t,i,r).then(n=>{if(!n)return;let o=this.state,a=n.frag;if(this.fragContextChanged(a)){(o===G.FRAG_LOADING||!this.fragCurrent&&o===G.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=G.IDLE);return}"payload"in n&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(v.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n);}).catch(n=>{this.state===G.STOPPED||this.state===G.ERROR||(this.warn(`Frag error: ${n?.message||n}`),this.resetFragmentLoading(e));});}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===vt.APPENDING){let n=e.type,o=this.getFwdBufferInfo(this.mediaBuffer,n),a=Math.max(e.duration,o?o.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&i.removeFragment(e);}else ((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===vt.PARTIAL&&i.removeFragment(e));}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type});}e.fragments[0]||(e.deltaUpdateFailed=true);}waitForLive(e){let t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:i};this.hls.trigger(v.BUFFER_FLUSHING,r);}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{let r=i?.frag;if(!r||this.fragContextChanged(r)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{let{hls:r}=this,{frag:n,payload:o}=i,a=n.decryptdata;if(o&&o.byteLength>0&&a!=null&&a.key&&a.iv&&fo(a.method)){let l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(o),a.key.buffer,a.iv.buffer,s0(a.method)).catch(d=>{throw r.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.FRAG_DECRYPT_ERROR,fatal:false,error:d,reason:d.message,frag:n}),d}).then(d=>{let c=self.performance.now();return r.trigger(v.FRAG_DECRYPTED,{frag:n,payload:d,stats:{tstart:l,tdecrypt:c}}),i.payload=d,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===G.STOPPED||this.state===G.ERROR||(this.warn(i),this.resetFragmentLoading(e));});}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");let i=e.frag.stats;this.state!==G.STOPPED&&(this.state=G.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick();}unhandledEncryptionError(e,t){var i,r;let n=e.tracks;if(n&&!t.encrypted&&((i=n.audio)!=null&&i.encrypted||(r=n.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let o=this.media,a=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${o?"attached mediaKeys: "+o.mediaKeys:"detached"})`);return this.warn(a.message),!o||o.mediaKeys?false:(this.hls.trigger(v.ERROR,{type:ie.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_KEYS,fatal:false,error:a,frag:t}),this.resetTransmuxer(),true)}return false}fragContextChanged(e){let{fragCurrent:t}=this;return !e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,false,t)} > buffer:${i?mw.toString(Ee.getBuffered(i)):"(detached)"})`),at(e)){var r;if(e.type!==J.SUBTITLE){let o=e.elementaryStreams;if(!Object.keys(o).some(a=>!!o[a])){this.state=G.IDLE;return}}let n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0);}this.state=G.IDLE;}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:i,part:r,partsLoaded:n}=e,o=!n||n.length===0||n.some(l=>!l),a=new gl(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!o);t.flush(a);}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var n;this.fragCurrent=e;let o=t.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let a=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${o.startSN}-${o.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=G.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(v.KEY_LOADED,h),this.state===G.KEY_LOADING&&(this.state=G.IDLE),h}),this.hls.trigger(v.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(a=this.keyLoader.loadClear(e,o.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));let l=this.fragPrevious;if(at(e)&&(!l||e.sn!==l.sn)){let h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${l?.sn}->${e.sn}`),this.loadingParts=h);}if(i=Math.max(e.start,i||0),this.loadingParts&&at(e)){let h=o.partList;if(h&&r){i>o.fragmentEnd&&o.fragmentHint&&(e=o.fragmentHint);let f=this.getNextPart(h,e,i);if(f>-1){let m=h[f];e=this.fragCurrent=m.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${f}/${h.length-1}) of ${this.fragInfo(e,false,m)}) cc: ${e.cc} [${o.startSN}-${o.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=m.start+m.duration,this.state=G.FRAG_LOADING;let p;return a?p=a.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,m,t,r)).catch(g=>this.handleFragLoadError(g)):p=this.doFragPartsLoad(e,m,t,r).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(v.FRAG_LOADING,{frag:e,part:m,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(h,i))return Promise.resolve(null)}}if(at(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=o.partList)==null?void 0:d.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=false;}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,false)}) cc: ${e.cc} ${"["+o.startSN+"-"+o.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),Q(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=G.FRAG_LOADING;let c=this.config.progressive&&e.type!==J.SUBTITLE,u;return c&&a?u=a.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,r)).catch(h=>this.handleFragLoadError(h)):u=Promise.all([this.fragmentLoader.load(e,c?r:void 0),a]).then(([h])=>(!c&&r&&r(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(v.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,i,r){return new Promise((n,o)=>{var a;let l=[],d=(a=i.details)==null?void 0:a.partList,c=u=>{this.fragmentLoader.loadPart(e,u,r).then(h=>{l[u.index]=h;let f=h.part;this.hls.trigger(v.FRAG_LOADED,h);let m=r_(i.details,e.sn,u.index+1)||cT(d,e.sn,u.index+1);if(m)c(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(o);};c(t);})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===M.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===ie.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(v.ERROR,t);}else this.hls.trigger(v.ERROR,{type:ie.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,err:e,error:e,fatal:true});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==G.PARSING){!this.fragCurrent&&this.state!==G.STOPPED&&this.state!==G.ERROR&&(this.state=G.IDLE);return}let{frag:i,part:r,level:n}=t,o=self.performance.now();i.stats.parsing.end=o,r&&(r.stats.parsing.end=o);let a=this.getLevelDetails(),d=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(i,r,n,e.partial);}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;let n=e.partList[0];if(n.fragment.type===J.SUBTITLE)return false;let o=n.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=o){var r;if((this.hls.hasEnoughToStart?((r=this.media)==null?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return true}}}return false}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:r,sn:n,part:o}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let a=t[r],l=a.details,d=o>-1?r_(l,n,o):null,c=d?d.fragment:dT(l,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:d,level:a}):null}bufferFragmentData(e,t,i,r,n){if(this.state!==G.PARSING)return;let{data1:o,data2:a}=e,l=o;if(a&&(l=pi(o,a)),!l.length)return;let d=this.initPTS[t.cc],c=d?-d.baseTime/d.timescale:void 0,u={type:e.type,frag:t,part:i,chunkMeta:r,offset:c,parent:t.type,data:l};if(this.hls.trigger(v.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t);}}flushBufferGap(e){let t=this.media;if(!t)return;if(!Ee.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let i=t.currentTime,r=Ee.bufferInfo(t,i,0),n=e.duration,o=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),a=Math.max(Math.min(e.start-o,r.end-o),i+o);e.start-a>o&&this.flushMainBuffer(a,e.start);}getFwdBufferInfo(e,t){var i;let r=this.getLoadPosition();if(!Q(r))return null;let o=this.lastCurrentTime>r||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,o)}getFwdBufferInfoAtPos(e,t,i,r){let n=Ee.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){let o=this.fragmentTracker.getBufferedFrag(t,i);if(o&&(n.nextStart<=o.end||o.gap)){let a=Math.max(Math.min(n.nextStart,o.end)-t,r);return Ee.bufferInfo(e,t,a)}}return n}getMaxBufferLength(e){let{config:t}=this,i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){let i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-t*3,i.maxMaxBufferLength/2,r);return n>=r?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),true):false}getAppendedFrag(e,t=J.MAIN){let i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i=t.fragments,r=i.length;if(!r)return null;let{config:n}=this,o=i[0].start,a=n.lowLatencyMode&&!!t.partList,l=null;if(t.live){let u=n.initialLiveManifestSize;if(r<u)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<o){var d;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=true),l=this.getInitialLiveFragment(t);let h=this.hls.startPosition,f=this.hls.liveSyncPosition,m=l?(h!==-1&&h>=o?h:f)||l.start:e;this.log(`Setting startPosition to ${m} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${f} frag.start: ${(d=l)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=m;}}else e<=o&&(l=i[0]);if(!l){let u=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,u,t);}let c=this.filterReplacedPrimary(l,t);if(!c&&l){let u=l.sn-t.startSN;c=this.filterReplacedPrimary(i[u+1]||null,t);}return this.mapToInitFragWhenRequired(c)}isLoopLoading(e,t){let i=this.fragmentTracker.getState(e);return (i===vt.OK||i===vt.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,r,n){let o=null;if(e.gap&&(o=this.getNextFragment(this.nextLoadPosition,t),o&&!o.gap&&i.nextStart)){let a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(a!==null&&i.len+a.len>=n){let l=o.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,o}get primaryPrefetch(){if(a_(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return true}return false}filterReplacedPrimary(e,t){if(!e)return e;if(a_(this.config)&&e.type!==J.SUBTITLE){let i=this.hls.interstitialsManager,r=i?.bufferingItem;if(r){let o=r.event;if(o){if(o.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&t?.live===false||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}let n=i?.playerQueue;if(n)for(let o=n.length;o--;){let a=n[o].interstitial;if(a.appendInPlace&&e.start>=a.startTime&&e.end<=a.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let r=-1,n=false,o=true;for(let a=0,l=e.length;a<l;a++){let d=e[a];if(o=o&&!d.independent,r>-1&&i<d.start)break;let c=d.loaded;c?r=-1:(n||(d.independent||o)&&d.fragment===t)&&(d.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${d.start}`),r=a),n=c;}return r}loadedEndOfParts(e,t){let i;for(let r=e.length;r--;){if(i=e[r],!i.loaded)return false;if(t>i.start)return true}return false}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=Nk(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){let o=t[n-e.startSN];i.cc===o.cc&&(r=o,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`));}r||(r=X_(e,i.cc,i.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`));}}else {let n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e));}return r}getFragmentAtPosition(e,t,i){let{config:r}=this,{fragPrevious:n}=this,{fragments:o,endSN:a}=i,{fragmentHint:l}=i,{maxFragLookUpTolerance:d}=r,c=i.partList,u=!!(this.loadingParts&&c!=null&&c.length&&l);u&&!this.bitrateTest&&c[c.length-1].fragment.sn===l.sn&&(o=o.concat(l),a=l.sn);let h;if(e<t){var f;let p=e<this.lastCurrentTime||e>t-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;h=en(n,o,e,p);}else h=o[o.length-1];if(h){let m=h.sn-i.startSN,p=this.fragmentTracker.getState(h);if((p===vt.OK||p===vt.PARTIAL&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!u||c[0].fragment.sn>h.sn||!i.live)&&h.level===n.level){let E=o[m+1];h.sn<a&&this.fragmentTracker.getState(E)!==vt.OK?h=E:h=null;}}return h}alignPlaylists(e,t,i){let r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;let n=e.fragmentStart,o=!t,a=e.alignedSliding&&Q(n);if(o||!a&&!n){fw(i,e);let l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),l}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);let r=this.timelineOffset;if(i===-1){let n=this.startTimeOffset!==null,o=n?this.startTimeOffset:e.startTimeOffset;o!==null&&Q(o)?(i=t+o,o<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${o} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r;}this.nextLoadPosition=i+r;}getLoadPosition(){var e;let{media:t}=this,i=0;return (e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&at(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e));}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==G.FRAG_LOADING_WAITING_RETRY)&&(this.state=G.IDLE);}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){let E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag);}let r=t.frag;if(!r||r.type!==e||!this.levels)return;if(this.fragContextChanged(r)){var n;this.warn(`Frag load error must match current frag to retry ${r.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}let o=t.details===M.FRAG_GAP;o&&this.fragmentTracker.fragBuffered(r,true);let a=t.errorAction;if(!a){this.state=G.ERROR;return}let{action:l,flags:d,retryCount:c=0,retryConfig:u}=a,h=!!u,f=h&&l===St.RetryRequest,m=h&&!a.resolved&&d===ti.MoveAllAlternatesMatchingHost,p=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!f&&m&&at(r)&&!r.endList&&p&&!J_(t))this.resetFragmentErrors(e),this.treatAsGap(r),a.resolved=true;else if((f||m)&&c<u.maxNumRetry){var g;let E=Bp((g=t.response)==null?void 0:g.code),y=i0(u,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+y,this.state=G.FRAG_LOADING_WAITING_RETRY,a.resolved=true,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${c+1}/${u.maxNumRetry} in ${y}ms`);}else if(u)if(this.resetFragmentErrors(e),c<u.maxNumRetry)!o&&l!==St.RemoveAlternatePermanently&&(a.resolved=true);else {this.warn(`${t.details} reached or exceeded max retry (${c})`);return}else l===St.SendAlternateToPenaltyBox?this.state=G.WAITING_LEVEL:this.state=G.ERROR;this.tickImmediate();}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!Bp(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=G.IDLE);}reduceLengthAndFlushBuffer(e){if(this.state===G.PARSING||this.state===G.PARSED){let t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,t?.duration||10);let o=!n;return o&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),o}return false}resetFragmentErrors(e){e===J.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=false),this.state!==G.STOPPED&&(this.state=G.IDLE);}afterBufferFlushed(e,t,i){if(!e)return;let r=Ee.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===G.ENDED&&this.resetLoadingState();}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==G.STOPPED&&(this.state=G.IDLE);}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=false;let e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition;}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState();}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,false,true);}updateLevelTiming(e,t,i,r){let n=i.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,d)=>{let c=e.elementaryStreams[d];if(c){let u=c.endPTS-c.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${u})`),l||false;let h=r?0:oT(n,e,c.startPTS,c.endPTS,c.startDTS,c.endDTS,this);return this.hls.trigger(v.LEVEL_PTS_UPDATED,{details:n,level:i,drift:h,type:d,frag:e,start:c.startPTS,end:c.endPTS}),true}return l},false)){var a;let l=((a=this.transmuxer)==null?void 0:a.error)===null;if((i.fragmentError===0||l&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),l){let d=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:false,error:d,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer();}}this.state=G.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,false,t)})`),this.hls.trigger(v.FRAG_PARSED,{frag:e,part:t});}playlistLabel(){return this.playlistType===J.MAIN?"level":"track"}fragInfo(e,t=true,i){var r,n;return `${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((r=t&&!i?e.startPTS:(i||e).start)!=null?r:NaN).toFixed(3)}-${((n=t&&!i?e.endPTS:(i||e).end)!=null?n:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=true,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,true);}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset();}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState());}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`));}get state(){return this._state}};function a_(s){return !!s.interstitialsController&&s.enableInterstitialPlayback!==false}var rh=class{constructor(){this.chunks=[],this.dataLength=0;}push(e){this.chunks.push(e),this.dataLength+=e.length;}flush(){let{chunks:e,dataLength:t}=this,i;if(e.length)e.length===1?i=e[0]:i=pw(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0;}};function pw(s,e){let t=new Uint8Array(e),i=0;for(let r=0;r<s.length;r++){let n=s[r];t.set(n,i),i+=n.length;}return t}var vp={exports:{}},l_;function gw(){return l_||(l_=1,(function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=false));function r(l,d,c){this.fn=l,this.context=d,this.once=c||false;}function n(l,d,c,u,h){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new r(c,u||l,h),m=t?t+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function o(l,d){--l._eventsCount===0?l._events=new i:delete l._events[d];}function a(){this._events=new i,this._eventsCount=0;}a.prototype.eventNames=function(){var d=[],c,u;if(this._eventsCount===0)return d;for(u in c=this._events)e.call(c,u)&&d.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},a.prototype.listeners=function(d){var c=t?t+d:d,u=this._events[c];if(!u)return [];if(u.fn)return [u.fn];for(var h=0,f=u.length,m=new Array(f);h<f;h++)m[h]=u[h].fn;return m},a.prototype.listenerCount=function(d){var c=t?t+d:d,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(d,c,u,h,f,m){var p=t?t+d:d;if(!this._events[p])return false;var g=this._events[p],E=arguments.length,y,_;if(g.fn){switch(g.once&&this.removeListener(d,g.fn,void 0,true),E){case 1:return g.fn.call(g.context),true;case 2:return g.fn.call(g.context,c),true;case 3:return g.fn.call(g.context,c,u),true;case 4:return g.fn.call(g.context,c,u,h),true;case 5:return g.fn.call(g.context,c,u,h,f),true;case 6:return g.fn.call(g.context,c,u,h,f,m),true}for(_=1,y=new Array(E-1);_<E;_++)y[_-1]=arguments[_];g.fn.apply(g.context,y);}else {var S=g.length,L;for(_=0;_<S;_++)switch(g[_].once&&this.removeListener(d,g[_].fn,void 0,true),E){case 1:g[_].fn.call(g[_].context);break;case 2:g[_].fn.call(g[_].context,c);break;case 3:g[_].fn.call(g[_].context,c,u);break;case 4:g[_].fn.call(g[_].context,c,u,h);break;default:if(!y)for(L=1,y=new Array(E-1);L<E;L++)y[L-1]=arguments[L];g[_].fn.apply(g[_].context,y);}}return true},a.prototype.on=function(d,c,u){return n(this,d,c,u,false)},a.prototype.once=function(d,c,u){return n(this,d,c,u,true)},a.prototype.removeListener=function(d,c,u,h){var f=t?t+d:d;if(!this._events[f])return this;if(!c)return o(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!h||m.once)&&(!u||m.context===u)&&o(this,f);else {for(var p=0,g=[],E=m.length;p<E;p++)(m[p].fn!==c||h&&!m[p].once||u&&m[p].context!==u)&&g.push(m[p]);g.length?this._events[f]=g.length===1?g[0]:g:o(this,f);}return this},a.prototype.removeAllListeners=function(d){var c;return d?(c=t?t+d:d,this._events[c]&&o(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,s.exports=a;})(vp)),vp.exports}var vw=gw(),n0=XR(vw),El="1.6.15",Eo={};function Ew(){return typeof __HLS_WORKER_BUNDLE__=="function"}function yw(){let s=Eo[El];if(s)return s.clientCount++,s;let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),r={worker:new self.Worker(t),objectURL:t,clientCount:1};return Eo[El]=r,r}function bw(s){let e=Eo[s];if(e)return e.clientCount++,e;let t=new self.URL(s,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Eo[s]=r,r}function _w(s){let e=Eo[s||El];if(e&&e.clientCount--===1){let{worker:i,objectURL:r}=e;delete Eo[s||El],r&&self.URL.revokeObjectURL(r),i.terminate();}}function mT(s,e){return e+10<=s.length&&s[e]===51&&s[e+1]===68&&s[e+2]===73&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function o0(s,e){return e+10<=s.length&&s[e]===73&&s[e+1]===68&&s[e+2]===51&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function Eh(s,e){let t=0;return t=(s[e]&127)<<21,t|=(s[e+1]&127)<<14,t|=(s[e+2]&127)<<7,t|=s[e+3]&127,t}function yl(s,e){let t=e,i=0;for(;o0(s,e);){i+=10;let r=Eh(s,e+6);i+=r,mT(s,e+10)&&(i+=10),e+=i;}if(i>0)return s.subarray(t,t+i)}function Tw(s,e,t,i){let r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],o=n>>2&15;if(o>12){let f=new Error(`invalid ADTS sampling index:${o}`);s.emit(v.ERROR,v.ERROR,{type:ie.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:true,error:f,reason:f.message});return}let a=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,d="mp4a.40."+a,c=r[o],u=o;(a===5||a===29)&&(u-=3);let h=[a<<3|(u&14)>>1,(u&1)<<7|l<<3];return Ue.log(`manifest codec:${i}, parsed codec:${d}, channels:${l}, rate:${c} (ADTS object type:${a} sampling index:${o})`),{config:h,samplerate:c,channelCount:l,codec:d,parsedCodec:d,manifestCodec:i}}function pT(s,e){return s[e]===255&&(s[e+1]&246)===240}function gT(s,e){return s[e+1]&1?7:9}function a0(s,e){return (s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function Sw(s,e){return e+5<s.length}function nh(s,e){return e+1<s.length&&pT(s,e)}function Aw(s,e){return Sw(s,e)&&pT(s,e)&&a0(s,e)<=s.length-e}function Iw(s,e){if(nh(s,e)){let t=gT(s,e);if(e+t>=s.length)return false;let i=a0(s,e);if(i<=t)return false;let r=e+i;return r===s.length||nh(s,r)}return false}function vT(s,e,t,i,r){if(!s.samplerate){let n=Tw(e,t,i,r);if(!n)return;Be(s,n);}}function ET(s){return 1024*9e4/s}function xw(s,e){let t=gT(s,e);if(e+t<=s.length){let i=a0(s,e)-t;if(i>0)return {headerLength:t,frameLength:i}}}function yT(s,e,t,i,r){let n=ET(s.samplerate),o=i+r*n,a=xw(e,t),l;if(a){let{frameLength:u,headerLength:h}=a,f=h+u,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+f);let p={unit:l,pts:o};return m||s.samples.push(p),{sample:p,length:f,missing:m}}let d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:o},length:d,missing:-1}}function Lw(s,e){return o0(s,e)&&Eh(s,e+6)+10<=s.length-e}function Rw(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function Ep(s,e=0,t=1/0){return kw(s,e,t,Uint8Array)}function kw(s,e,t,i){let r=ww(s),n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);let o=Cw(s)?s.byteOffset:0,a=(o+s.byteLength)/n,l=(o+e)/n,d=Math.floor(Math.max(0,Math.min(l,a))),c=Math.floor(Math.min(d+Math.max(t,0),a));return new i(r,d,c-d)}function ww(s){return s instanceof ArrayBuffer?s:s.buffer}function Cw(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function Dw(s){let e={key:s.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(s.size<2)return;if(s.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let i=s.data.subarray(1).indexOf(0);if(i===-1)return;let r=ri(Ep(s.data,1,i)),n=s.data[2+i],o=s.data.subarray(3+i).indexOf(0);if(o===-1)return;let a=ri(Ep(s.data,3+i,o)),l;return r==="-->"?l=ri(Ep(s.data,4+i+o)):l=Rw(s.data.subarray(4+i+o)),e.mimeType=r,e.pictureType=n,e.description=a,e.data=l,e}function Mw(s){if(s.size<2)return;let e=ri(s.data,true),t=new Uint8Array(s.data.subarray(e.length+1));return {key:s.type,info:e,data:t.buffer}}function Pw(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1,i=ri(s.data.subarray(t),true);t+=i.length+1;let r=ri(s.data.subarray(t));return {key:s.type,info:i,data:r}}let e=ri(s.data.subarray(1));return {key:s.type,info:"",data:e}}function Ow(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1,i=ri(s.data.subarray(t),true);t+=i.length+1;let r=ri(s.data.subarray(t));return {key:s.type,info:i,data:r}}let e=ri(s.data);return {key:s.type,info:"",data:e}}function Uw(s){return s.type==="PRIV"?Mw(s):s.type[0]==="W"?Ow(s):s.type==="APIC"?Dw(s):Pw(s)}function Nw(s){let e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=Eh(s,4),i=10;return {type:e,size:t,data:s.subarray(i,i+t)}}var Ru=10,Fw=10;function bT(s){let e=0,t=[];for(;o0(s,e);){let i=Eh(s,e+6);s[e+5]>>6&1&&(e+=Ru),e+=Ru;let r=e+i;for(;e+Fw<r;){let n=Nw(s.subarray(e)),o=Uw(n);o&&t.push(o),e+=n.size+Ru;}mT(s,e)&&(e+=Ru);}return t}function _T(s){return s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp"}function $w(s){if(s.data.byteLength===8){let e=new Uint8Array(s.data),t=e[3]&1,i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function l0(s){let e=bT(s);for(let t=0;t<e.length;t++){let i=e[t];if(_T(i))return $w(i)}}var si=(function(s){return s.audioId3="org.id3",s.dateRange="com.apple.quicktime.HLS",s.emsg="https://aomedia.org/emsg/ID3",s.misbklv="urn:misb:KLV:bin:1910.1",s})({});function ns(s="",e=9e4){return {type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var bl=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null;}resetInitSegment(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0};}resetTimeStamp(e){this.initPTS=e,this.resetContiguity();}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0;}canParse(e,t){return false}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=pi(this.cachedData,e),this.cachedData=null);let i=yl(e,0),r=i?i.length:0,n,o=this._audioTrack,a=this._id3Track,l=i?l0(i):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&Q(l))&&(this.basePTS=Bw(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:si.audioId3,duration:Number.POSITIVE_INFINITY});r<d;){if(this.canParse(e,r)){let c=this.appendFrame(o,e,r);c?(this.frameIndex++,this.lastPTS=c.sample.pts,r+=c.length,n=r):r=d;}else Lw(e,r)?(i=yl(e,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:si.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,n=r):r++;if(r===d&&n!==d){let c=e.slice(n);this.cachedData?this.cachedData=pi(this.cachedData,c):this.cachedData=c;}}return {audioTrack:o,videoTrack:ns(),id3Track:a,textTrack:ns()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:ns(),id3Track:this._id3Track,textTrack:ns()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0;}},Bw=(s,e,t)=>{if(Q(s))return s*90;let i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i},ku=null,Hw=[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],Gw=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Kw=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Vw=[0,1,1,4];function TT(s,e,t,i,r){if(t+24>e.length)return;let n=ST(e,t);if(n&&t+n.frameLength<=e.length){let o=n.samplesPerFrame*9e4/n.sampleRate,a=i+r*o,l={unit:e.subarray(t,t+n.frameLength),pts:a,dts:a};return s.config=[],s.channelCount=n.channelCount,s.samplerate=n.sampleRate,s.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function ST(s,e){let t=s[e+1]>>3&3,i=s[e+1]>>1&3,r=s[e+2]>>4&15,n=s[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){let o=s[e+2]>>1&1,a=s[e+3]>>6,l=t===3?3-i:i===3?3:4,d=Hw[l*14+r-1]*1e3,u=Gw[(t===3?0:t===2?1:2)*3+n],h=a===3?1:2,f=Kw[t][i],m=Vw[i],p=f*8*m,g=Math.floor(f*d/u+o)*m;if(ku===null){let _=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ku=_?parseInt(_[1]):0;}return ku&&ku<=87&&i===2&&d>=224e3&&a===0&&(s[e+3]=s[e+3]|128),{sampleRate:u,channelCount:h,frameLength:g,samplesPerFrame:p}}}function d0(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function AT(s,e){return e+1<s.length&&d0(s,e)}function Ww(s,e){return d0(s,e)&&4<=s.length-e}function IT(s,e){if(e+1<s.length&&d0(s,e)){let i=ST(s,e),r=4;i!=null&&i.frameLength&&(r=i.frameLength);let n=e+r;return n===s.length||AT(s,n)}return false}var Zp=class extends bl{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t;}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0};}static probe(e,t){if(!e)return false;let i=yl(e,0),r=i?.length||0;if(IT(e,r))return false;for(let n=e.length;r<n;r++)if(Iw(e,r))return t.log("ADTS sync word found !"),true;return false}canParse(e,t){return Aw(e,t)}appendFrame(e,t,i){vT(e,this.observer,t,i,e.manifestCodec);let r=yT(e,t,i,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}},xT=(s,e)=>{let t=0,i=5;e+=i;let r=new Uint32Array(1),n=new Uint32Array(1),o=new Uint8Array(1);for(;i>0;){o[0]=s[e];let a=Math.min(i,8),l=8-a;n[0]=4278190080>>>24+l<<l,r[0]=(o[0]&n[0])>>l,t=t?t<<a|r[0]:r[0],e+=1,i-=a;}return t},Jp=class extends bl{constructor(e){super(),this.observer=void 0,this.observer=e;}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0};}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let r=LT(e,t,i,this.basePTS,this.frameIndex);if(r!==-1)return {sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return false;let t=yl(e,0);if(!t)return false;let i=t.length;return e[i]===11&&e[i+1]===119&&l0(t)!==void 0&&xT(e,i)<16}};function LT(s,e,t,i,r){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return -1;let n=e[t+4]>>6;if(n>=3)return -1;let a=[48e3,44100,32e3][n],l=e[t+4]&63,c=[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][l*3+n]*2;if(t+c>e.length)return -1;let u=e[t+6]>>5,h=0;u===2?h+=2:(u&1&&u!==1&&(h+=2),u&4&&(h+=2));let f=(e[t+6]<<8|e[t+7])>>12-h&1,p=[2,1,2,3,3,4,4,5][u]+f,g=e[t+5]>>3,E=e[t+5]&7,y=new Uint8Array([n<<6|g<<1|E>>2,(E&3)<<6|u<<3|f<<2|l>>4,l<<4&224]),_=1536/a*9e4,S=i+r*_,L=e.subarray(t,t+c);return s.config=y,s.channelCount=p,s.samplerate=a,s.samples.push({unit:L,pts:S}),c}var eg=class extends bl{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0};}static probe(e){if(!e)return false;let t=yl(e,0),i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&l0(t)!==void 0&&xT(e,i)<=16)return false;for(let r=e.length;i<r;i++)if(IT(e,i))return Ue.log("MPEG Audio sync word found !"),true;return false}canParse(e,t){return Ww(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return TT(e,t,i,this.basePTS,this.frameIndex)}},qw=/\/emsg[-/]ID3/i,tg=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t;}resetTimeStamp(){}resetInitSegment(e,t,i,r){let n=this.videoTrack=ns("video",1),o=this.audioTrack=ns("audio",1),a=this.txtTrack=ns("text",1);if(this.id3Track=ns("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=B_(e);if(l.video){let{id:d,timescale:c,codec:u,supplemental:h}=l.video;n.id=d,n.timescale=a.timescale=c,n.codec=u,n.supplemental=h;}if(l.audio){let{id:d,timescale:c,codec:u}=l.audio;o.id=d,o.timescale=c,o.codec=u;}a.id=N_.text,n.sampleDuration=0,n.duration=o.duration=r;}resetContiguity(){this.remainderData=null;}static probe(e){return tk(e)}demux(e,t){this.timeOffset=t;let i=e,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=pi(this.remainderData,e));let a=lk(i);this.remainderData=a.remainder,r.samples=a.valid||new Uint8Array;}else r.samples=i;let o=this.extractID3Track(r,t);return n.samples=Lb(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return i.samples=Lb(e,t),{videoTrack:t,audioTrack:ns(),id3Track:r,textTrack:ns()}}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let r=be(e.samples,["emsg"]);r&&r.forEach(n=>{let o=ck(n);if(qw.test(o.schemeIdUri)){let a=d_(o,t),l=o.eventDuration===4294967295?Number.POSITIVE_INFINITY:o.eventDuration/o.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let d=o.payload;i.samples.push({data:d,len:d.byteLength,dts:a,pts:a,type:si.emsg,duration:l});}else if(this.config.enableEmsgKLVMetadata&&o.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let a=d_(o,t);i.samples.push({data:o.payload,len:o.payload.byteLength,dts:a,pts:a,type:si.misbklv,duration:Number.POSITIVE_INFINITY});}});}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0;}};function d_(s,e){return Q(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}var ig=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new pl(t,{removePKCS7Padding:false});}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,rr.cbc)}decryptAacSample(e,t,i){let r=e[t].unit;if(r.length<=16)return;let n=r.subarray(16,r.length-r.length%16),o=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(o).then(a=>{let l=new Uint8Array(a);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i);}).catch(i);}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)i.set(e.subarray(n,n+16),r);return i}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(i.subarray(r,r+16),n);return e}decryptAvcSample(e,t,i,r,n){let o=K_(n.data),a=this.getAvcEncryptedData(o);this.decryptBuffer(a.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(o,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r);}).catch(r);}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){r();return}let n=e[t].units;for(;!(i>=n.length);i++){let o=n[i];if(!(o.data.length<=48||o.type!==1&&o.type!==5)&&(this.decryptAvcSample(e,t,i,r,o),!this.decrypter.isSync()))return}}}},oh=class{constructor(){this.VideoSample=null;}createVideoSample(e,t,i){return {key:e,frame:false,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,r;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){let n=i.units;r=n[n.length-1];}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let i=t.samples,r=i.length;if(r){let n=i[r-1];e.pts=n.pts,e.dts=n.dts;}else {t.dropped++;return}}t.samples.push(e);}}parseNALu(e,t,i){let r=t.byteLength,n=e.naluState||0,o=n,a=[],l=0,d,c,u,h=-1,f=0;for(n===-1&&(h=0,f=this.getNALuType(t,0),n=0,l=1);l<r;){if(d=t[l++],!n){n=d?0:1;continue}if(n===1){n=d?0:2;continue}if(!d)n=3;else if(d===1){if(c=l-n-1,h>=0){let m={data:t.subarray(h,c),type:f};a.push(m);}else {let m=this.getLastNalUnit(e.samples);m&&(o&&l<=4-o&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-o)),c>0&&(m.data=pi(m.data,t.subarray(0,c)),m.state=0));}l<r?(u=this.getNALuType(t,l),h=l,f=u,n=0):n=-1;}else n=0;}if(h>=0&&n>=0){let m={data:t.subarray(h,r),type:f,state:n};a.push(m);}if(a.length===0){let m=this.getLastNalUnit(e.samples);m&&(m.data=pi(m.data,t));}return e.naluState=n,a}},Zr=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0;}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n;}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e);}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&Ue.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ());}skipEG(){this.skipBits(1+this.skipLZ());}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},sg=class extends oh{parsePES(e,t,i,r){let n=this.parseNALu(e,i.data,r),o=this.VideoSample,a,l=false;i.data=null,o&&n.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(false,i.pts,i.dts)),n.forEach(d=>{var c,u;switch(d.type){case 1:{let p=false;a=true;let g=d.data;if(l&&g.length>4){let E=this.readSliceType(g);(E===2||E===4||E===7||E===9)&&(p=true);}if(p){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null);}o||(o=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),o.frame=true,o.key=p;break}case 5:a=true,(c=o)!=null&&c.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),o.key=true,o.frame=true;break;case 6:{a=true,Jg(d.data,1,i.pts,t.samples);break}case 7:{var f,m;a=true,l=true;let p=d.data,g=this.readSPS(p);if(!e.sps||e.width!==g.width||e.height!==g.height||((f=e.pixelRatio)==null?void 0:f[0])!==g.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[p];let E=p.subarray(1,4),y="avc1.";for(let _=0;_<3;_++){let S=E[_].toString(16);S.length<2&&(S="0"+S),y+=S;}e.codec=y;}break}case 8:a=true,e.pps=[d.data];break;case 9:a=true,e.audFound=true,(u=o)!=null&&u.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(false,i.pts,i.dts));break;case 12:a=true;break;default:a=false;break}o&&a&&o.units.push(d);}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null);}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new Zr(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,r=8,n;for(let o=0;o<e;o++)r!==0&&(n=t.readEG(),r=(i+n+256)%256),i=r===0?i:r;}readSPS(e){let t=new Zr(e),i=0,r=0,n=0,o=0,a,l,d,c=t.readUByte.bind(t),u=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),m=t.skipBits.bind(t),p=t.skipEG.bind(t),g=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);c();let y=c();if(u(5),m(3),c(),g(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){let D=h();if(D===3&&m(1),g(),g(),m(1),f())for(l=D!==3?8:12,d=0;d<l;d++)f()&&(d<6?E(16,t):E(64,t));}g();let _=h();if(_===0)h();else if(_===1)for(m(1),p(),p(),a=h(),d=0;d<a;d++)p();g(),m(1);let S=h(),L=h(),O=u(1);O===0&&m(1),m(1),f()&&(i=h(),r=h(),n=h(),o=h());let R=[1,1];if(f()&&f())switch(c()){case 1:R=[1,1];break;case 2:R=[12,11];break;case 3:R=[10,11];break;case 4:R=[16,11];break;case 5:R=[40,33];break;case 6:R=[24,11];break;case 7:R=[20,11];break;case 8:R=[32,11];break;case 9:R=[80,33];break;case 10:R=[18,11];break;case 11:R=[15,11];break;case 12:R=[64,33];break;case 13:R=[160,99];break;case 14:R=[4,3];break;case 15:R=[3,2];break;case 16:R=[2,1];break;case 255:{R=[c()<<8|c(),c()<<8|c()];break}}return {width:Math.ceil((S+1)*16-i*2-r*2),height:(2-O)*(L+1)*16-(O?2:4)*(n+o),pixelRatio:R}}},rg=class extends oh{constructor(...e){super(...e),this.initVPS=null;}parsePES(e,t,i,r){let n=this.parseNALu(e,i.data,r),o=this.VideoSample,a,l=false;i.data=null,o&&n.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(false,i.pts,i.dts)),n.forEach(d=>{var c,u;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(false,i.pts,i.dts)),o.frame=true,a=true;break;case 16:case 17:case 18:case 21:if(a=true,l){var h;(h=o)!=null&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null);}o||(o=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),o.key=true,o.frame=true;break;case 19:case 20:a=true,(c=o)!=null&&c.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),o.key=true,o.frame=true;break;case 39:a=true,Jg(d.data,2,i.pts,t.samples);break;case 32:a=true,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Be(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(a=true,l=true,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let f=this.readSPS(d.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let m in f.params)e.params[m]=f.params[m];}this.pushParameterSet(e.sps,d.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),o.key=true;break;case 34:if(a=true,typeof e.params=="object"){if(!e.pps){e.pps=[];let f=this.readPPS(d.data);for(let m in f)e.params[m]=f[m];}this.pushParameterSet(e.pps,d.data,e.vps);}break;case 35:a=true,e.audFound=true,(u=o)!=null&&u.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(false,i.pts,i.dts));break;default:a=false;break}o&&a&&o.units.push(d);}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null);}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t);}getNALuType(e,t){return (e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null);}readVPS(e){let t=new Zr(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let i=t.readBits(3),r=t.readBoolean();return {numTemporalLayers:i+1,temporalIdNested:r}}readSPS(e){let t=new Zr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let r=t.readBits(2),n=t.readBoolean(),o=t.readBits(5),a=t.readUByte(),l=t.readUByte(),d=t.readUByte(),c=t.readUByte(),u=t.readUByte(),h=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),g=t.readUByte(),E=t.readUByte(),y=[],_=[];for(let xe=0;xe<i;xe++)y.push(t.readBoolean()),_.push(t.readBoolean());if(i>0)for(let xe=i;xe<8;xe++)t.readBits(2);for(let xe=0;xe<i;xe++)y[xe]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),_[xe]&&t.readUByte();t.readUEG();let S=t.readUEG();S==3&&t.skipBits(1);let L=t.readUEG(),O=t.readUEG(),R=t.readBoolean(),D=0,C=0,k=0,H=0;R&&(D+=t.readUEG(),C+=t.readUEG(),k+=t.readUEG(),H+=t.readUEG());let q=t.readUEG(),j=t.readUEG(),X=t.readUEG(),Y=t.readBoolean();for(let xe=Y?0:i;xe<=i;xe++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let ft=0;ft<4;ft++)for(let Ot=0;Ot<(ft===3?2:6);Ot++)if(!t.readBoolean())t.readUEG();else {let oi=Math.min(64,1<<4+(ft<<1));ft>1&&t.readEG();for(let Le=0;Le<oi;Le++)t.readEG();}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let I=t.readUEG(),P=0;for(let xe=0;xe<I;xe++){let ft=false;if(xe!==0&&(ft=t.readBoolean()),ft){xe===I&&t.readUEG(),t.readBoolean(),t.readUEG();let Ot=0;for(let Ri=0;Ri<=P;Ri++){let oi=t.readBoolean(),Le=false;oi||(Le=t.readBoolean()),(oi||Le)&&Ot++;}P=Ot;}else {let Ot=t.readUEG(),Ri=t.readUEG();P=Ot+Ri;for(let oi=0;oi<Ot;oi++)t.readUEG(),t.readBoolean();for(let oi=0;oi<Ri;oi++)t.readUEG(),t.readBoolean();}}if(t.readBoolean()){let xe=t.readUEG();for(let ft=0;ft<xe;ft++){for(let Ot=0;Ot<X+4;Ot++)t.readBits(1);t.readBits(1);}}let w=0,B=1,z=1,te=true,se=1,re=0;t.readBoolean(),t.readBoolean();let Ie=false;if(t.readBoolean()){if(t.readBoolean()){let Yt=t.readUByte(),Kl=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],an=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Yt>0&&Yt<16?(B=Kl[Yt-1],z=an[Yt-1]):Yt===255&&(B=t.readBits(16),z=t.readBits(16));}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),Ie=t.readBoolean(),Ie&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(se=t.readBits(32),re=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let an=t.readBoolean(),Vl=t.readBoolean(),ar=false;(an||Vl)&&(ar=t.readBoolean(),ar&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ar&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Wl=0;Wl<=i;Wl++){te=t.readBoolean();let Yh=te||t.readBoolean(),ql=false;Yh?t.readEG():ql=t.readBoolean();let kt=ql?1:t.readUEG()+1;if(an)for(let ze=0;ze<kt;ze++)t.readUEG(),t.readUEG(),ar&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Vl)for(let ze=0;ze<kt;ze++)t.readUEG(),t.readUEG(),ar&&(t.readUEG(),t.readUEG()),t.skipBits(1);}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),w=t.readUEG());}let Pt=L,jt=O;if(R){let xe=1,ft=1;S===1?xe=ft=2:S==2&&(xe=2),Pt=L-xe*C-xe*D,jt=O-ft*H-ft*k;}let gi=r?["A","B","C"][r]:"",Ds=a<<24|l<<16|d<<8|c,nn=0;for(let xe=0;xe<32;xe++)nn=(nn|(Ds>>xe&1)<<31-xe)>>>0;let on=nn.toString(16);return o===1&&on==="2"&&(on="6"),{codecString:`hvc1.${gi}${o}.${on}.${n?"H":"L"}${E}.B0`,params:{general_tier_flag:n,general_profile_idc:o,general_profile_space:r,general_profile_compatibility_flags:[a,l,d,c],general_constraint_indicator_flags:[u,h,f,m,p,g],general_level_idc:E,bit_depth:q+8,bit_depth_luma_minus8:q,bit_depth_chroma_minus8:j,min_spatial_segmentation_idc:w,chroma_format_idc:S,frame_rate:{fixed:te,fps:re/se}},width:Pt,height:jt,pixelRatio:[B,z]}}readPPS(e){let t=new Zr(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let r=t.readBoolean(),n=t.readBoolean(),o=1;return n&&r?o=0:n?o=3:r&&(o=2),{parallelismType:o}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},Tt=188,ng=class s{constructor(e,t,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=false,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null;}static probe(e,t){let i=s.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){let t=e.length,i=Math.min(Tt*5,t-Tt)+1,r=0;for(;r<i;){let n=false,o=-1,a=0;for(let l=r;l<t;l+=Tt)if(e[l]===71&&(t-l===Tt||e[l+Tt]===71)){if(a++,o===-1&&(o=l,o!==0&&(i=Math.min(o+Tt*99,e.length-Tt)+1)),n||(n=og(e,l)===0),n&&a>1&&(o===0&&a>2||l+Tt>i))return o}else {if(a)return -1;break}r++;}return -1}static createTrack(e,t){return {container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:N_[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=false,this._pmtId=-1,this._videoTrack=s.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=s.createTrack("audio",r),this._id3Track=s.createTrack("id3"),this._txtTrack=s.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i;}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null;}demux(e,t,i=false,r=false){i||(this.sampleAes=null);let n,o=this._videoTrack,a=this._audioTrack,l=this._id3Track,d=this._txtTrack,c=o.pid,u=o.pesData,h=a.pid,f=l.pid,m=a.pesData,p=l.pesData,g=null,E=this.pmtParsed,y=this._pmtId,_=e.length;if(this.remainderData&&(e=pi(this.remainderData,e),_=e.length,this.remainderData=null),_<Tt&&!r)return this.remainderData=e,{audioTrack:a,videoTrack:o,id3Track:l,textTrack:d};let S=Math.max(0,s.syncOffset(e));_-=(_-S)%Tt,_<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,_,e.buffer.byteLength-_));let L=0;for(let R=S;R<_;R+=Tt)if(e[R]===71){let D=!!(e[R+1]&64),C=og(e,R),k=(e[R+3]&48)>>4,H;if(k>1){if(H=R+5+e[R+4],H===R+Tt)continue}else H=R+4;switch(C){case c:D&&(u&&(n=oo(u,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,d,n,false)),u={data:[],size:0}),u&&(u.data.push(e.subarray(H,R+Tt)),u.size+=R+Tt-H);break;case h:if(D){if(m&&(n=oo(m,this.logger)))switch(a.segmentCodec){case "aac":this.parseAACPES(a,n);break;case "mp3":this.parseMPEGPES(a,n);break;case "ac3":this.parseAC3PES(a,n);break}m={data:[],size:0};}m&&(m.data.push(e.subarray(H,R+Tt)),m.size+=R+Tt-H);break;case f:D&&(p&&(n=oo(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(H,R+Tt)),p.size+=R+Tt-H);break;case 0:D&&(H+=e[H]+1),y=this._pmtId=jw(e,H);break;case y:{D&&(H+=e[H]+1);let q=Yw(e,H,this.typeSupported,i,this.observer,this.logger);c=q.videoPid,c>0&&(o.pid=c,o.segmentCodec=q.segmentVideoCodec),h=q.audioPid,h>0&&(a.pid=h,a.segmentCodec=q.segmentAudioCodec),f=q.id3Pid,f>0&&(l.pid=f),g!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${R} after unknown PID '${g}'. Backtracking to sync byte @${S} to parse all TS packets.`),g=null,R=S-188),E=this.pmtParsed=true;break}case 17:case 8191:break;default:g=C;break}}else L++;L>0&&ag(this.observer,new Error(`Found ${L} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=u,a.pesData=m,l.pesData=p;let O={audioTrack:a,videoTrack:o,id3Track:l,textTrack:d};return r&&this.extractRemainingSamples(O),O}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,false,true):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:i,id3Track:r,textTrack:n}=e,o=i.pesData,a=t.pesData,l=r.pesData,d;if(o&&(d=oo(o,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,n,d,true),i.pesData=null)):i.pesData=o,a&&(d=oo(a,this.logger))){switch(t.segmentCodec){case "aac":this.parseAACPES(t,d);break;case "mp3":this.parseMPEGPES(t,d);break;case "ac3":this.parseAC3PES(t,d);break}t.pesData=null;}else a!=null&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;l&&(d=oo(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l;}demuxSampleAes(e,t,i){let r=this.demux(e,i,true,!this.config.progressive),n=this.sampleAes=new ig(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new sg:e==="hevc"&&(this.videoParser=new rg));}decrypt(e,t){return new Promise(i=>{let{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e);}):i(e);}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e);});})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0;}parseAACPES(e,t){let i=0,r=this.aacOverFlow,n=t.data;if(r){this.aacOverFlow=null;let u=r.missing,h=r.sample.unit.byteLength;if(u===-1)n=pi(r.sample.unit,n);else {let f=h-u;r.sample.unit.set(n.subarray(0,u),f),e.samples.push(r.sample),i=r.missing;}}let o,a;for(o=i,a=n.length;o<a-1&&!nh(n,o);o++);if(o!==i){let u,h=o<a-1;if(h?u=`AAC PES did not start with ADTS header,offset:${o}`:u="No ADTS header found in AAC PES",ag(this.observer,new Error(u),h,this.logger),!h)return}vT(e,this.observer,n,o,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(r){let u=ET(e.samplerate);l=r.sample.pts+u;}else {this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,c;for(;o<a;)if(c=yT(e,n,o,l,d),o+=c.length,c.missing){this.aacOverFlow=c;break}else for(d++;o<a-1&&!nh(n,o);o++);}parseMPEGPES(e,t){let i=t.data,r=i.length,n=0,o=0,a=t.pts;if(a===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;o<r;)if(AT(i,o)){let l=TT(e,i,o,a,n);if(l)o+=l.length,n++;else break}else o++;}parseAC3PES(e,t){{let i=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=i.length,o=0,a=0,l;for(;a<n&&(l=LT(e,i,a,r,o++))>0;)a+=l;}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=Be({},t,{type:this._videoTrack?si.emsg:si.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i);}};function og(s,e){return ((s[e+1]&31)<<8)+s[e+2]}function jw(s,e){return (s[e+10]&31)<<8|s[e+11]}function Yw(s,e,t,i,r,n){let o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(s[e+1]&15)<<8|s[e+2],l=e+3+a-4,d=(s[e+10]&15)<<8|s[e+11];for(e+=12+d;e<l;){let c=og(s,e),u=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!i){yp("ADTS AAC",n);break}case 15:o.audioPid===-1&&(o.audioPid=c);break;case 21:o.id3Pid===-1&&(o.id3Pid=c);break;case 219:if(!i){yp("H.264",n);break}case 27:o.videoPid===-1&&(o.videoPid=c);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):o.audioPid===-1&&(o.audioPid=c,o.segmentAudioCodec="mp3");break;case 193:if(!i){yp("AC-3",n);break}case 129:t.ac3?o.audioPid===-1&&(o.audioPid=c,o.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(o.audioPid===-1&&u>0){let h=e+5,f=u;for(;f>2;){s[h]===106&&(t.ac3!==true?n.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=c,o.segmentAudioCodec="ac3"));let p=s[h+1]+2;h+=p,f-=p;}}break;case 194:case 135:return ag(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),o;case 36:o.videoPid===-1&&(o.videoPid=c,o.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=u+5;}return o}function ag(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(v.ERROR,v.ERROR,{type:ie.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:false,levelRetry:t,error:e,reason:e.message});}function yp(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`);}function oo(s,e){let t=0,i,r,n,o,a,l=s.data;if(!s||s.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=pi(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(r=(i[4]<<8)+i[5],r&&r>s.size-6)return null;let c=i[7];c&192&&(o=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,c&64?(a=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,o-a>60*9e4&&(e.warn(`${Math.round((o-a)/9e4)}s delta between PTS and DTS, align them`),o=a)):a=o),n=i[8];let u=n+9;if(s.size<=u)return null;s.size-=u;let h=new Uint8Array(s.size);for(let f=0,m=l.length;f<m;f++){i=l[f];let p=i.byteLength;if(u)if(u>p){u-=p;continue}else i=i.subarray(u),p-=u,u=0;h.set(i,t),t+=p;}return r&&(r-=n+3),{data:h,pts:o,dts:a,len:r}}return null}var lg=class{static getSilentFrame(e,t){switch(e){case "mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},Js=Math.pow(2,32)-1,Et=class s{static init(){s.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in s.types)s.types.hasOwnProperty(e)&&(s.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);let t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);s.HDLR_TYPES={video:t,audio:i};let r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);s.STTS=s.STSC=s.STCO=n,s.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),s.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),s.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),s.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let o=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);s.FTYP=s.box(s.types.ftyp,o,l,o,a),s.DINF=s.box(s.types.dinf,s.box(s.types.dref,r));}static box(e,...t){let i=8,r=t.length,n=r;for(;r--;)i+=t[r].byteLength;let o=new Uint8Array(i);for(o[0]=i>>24&255,o[1]=i>>16&255,o[2]=i>>8&255,o[3]=i&255,o.set(e,4),r=0,i=8;r<n;r++)o.set(t[r],i),i+=t[r].byteLength;return o}static hdlr(e){return s.box(s.types.hdlr,s.HDLR_TYPES[e])}static mdat(e){return s.box(s.types.mdat,e)}static mdhd(e,t){t*=e;let i=Math.floor(t/(Js+1)),r=Math.floor(t%(Js+1));return s.box(s.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return s.box(s.types.mdia,s.mdhd(e.timescale||0,e.duration||0),s.hdlr(e.type),s.minf(e))}static mfhd(e){return s.box(s.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?s.box(s.types.minf,s.box(s.types.smhd,s.SMHD),s.DINF,s.stbl(e)):s.box(s.types.minf,s.box(s.types.vmhd,s.VMHD),s.DINF,s.stbl(e))}static moof(e,t,i){return s.box(s.types.moof,s.mfhd(e),s.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=s.trak(e[t]);return s.box.apply(null,[s.types.moov,s.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(s.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=s.trex(e[t]);return s.box.apply(null,[s.types.mvex,...i])}static mvhd(e,t){t*=e;let i=Math.floor(t/(Js+1)),r=Math.floor(t%(Js+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return s.box(s.types.mvhd,n)}static sdtp(e){let t=e.samples||[],i=new Uint8Array(4+t.length),r,n;for(r=0;r<t.length;r++)n=t[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return s.box(s.types.sdtp,i)}static stbl(e){return s.box(s.types.stbl,s.stsd(e),s.box(s.types.stts,s.STTS),s.box(s.types.stsc,s.STSC),s.box(s.types.stsz,s.STSZ),s.box(s.types.stco,s.STCO))}static avc1(e){let t=[],i=[],r,n,o;for(r=0;r<e.sps.length;r++)n=e.sps[r],o=n.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r<e.pps.length;r++)n=e.pps[r],o=n.byteLength,i.push(o>>>8&255),i.push(o&255),i=i.concat(Array.prototype.slice.call(n));let a=s.box(s.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,d=e.height,c=e.pixelRatio[0],u=e.pixelRatio[1];return s.box(s.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,s.box(s.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),s.box(s.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){let t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return s.box(s.types.mp4a,s.audioStsd(e),s.box(s.types.esds,s.esds(e)))}static mp3(e){return s.box(s.types[".mp3"],s.audioStsd(e))}static ac3(e){return s.box(s.types["ac-3"],s.audioStsd(e),s.box(s.types.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return s.box(s.types.stsd,s.STSD,s.mp4a(e));if(t==="ac3"&&e.config)return s.box(s.types.stsd,s.STSD,s.ac3(e));if(t==="mp3"&&e.codec==="mp3")return s.box(s.types.stsd,s.STSD,s.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return s.box(s.types.stsd,s.STSD,s.avc1(e));if(t==="hevc"&&e.vps)return s.box(s.types.stsd,s.STSD,s.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,o=Math.floor(i/(Js+1)),a=Math.floor(i%(Js+1));return s.box(s.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,a>>24,a>>16&255,a>>8&255,a&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let i=s.sdtp(e),r=e.id,n=Math.floor(t/(Js+1)),o=Math.floor(t%(Js+1));return s.box(s.types.traf,s.box(s.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),s.box(s.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&255])),s.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,s.box(s.types.trak,s.tkhd(e),s.mdia(e))}static trex(e){let t=e.id;return s.box(s.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i=e.samples||[],r=i.length,n=12+16*r,o=new Uint8Array(n),a,l,d,c,u,h;for(t+=8+n,o.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),a=0;a<r;a++)l=i[a],d=l.duration,c=l.size,u=l.flags,h=l.cts,o.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*a);return s.box(s.types.trun,o)}static initSegment(e){s.types||s.init();let t=s.moov(e);return pi(s.FTYP,t)}static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],r=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),r-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]),o=n.length;for(let m=0;m<i.length;m+=1){o+=3;for(let p=0;p<i[m].length;p+=1)o+=2+i[m][p].length;}let a=new Uint8Array(o);a.set(n,0),o=n.length;let l=i.length-1;for(let m=0;m<i.length;m+=1){a.set(new Uint8Array([32+m|(m===l?128:0),0,i[m].length]),o),o+=3;for(let p=0;p<i[m].length;p+=1)a.set(new Uint8Array([i[m][p].length>>8,i[m][p].length&255]),o),o+=2,a.set(i[m][p],o),o+=i[m][p].length;}let d=s.box(s.types.hvcC,a),c=e.width,u=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return s.box(s.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,s.box(s.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),s.box(s.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}};Et.types=void 0;Et.HDLR_TYPES=void 0;Et.STTS=void 0;Et.STSC=void 0;Et.STCO=void 0;Et.STSZ=void 0;Et.VMHD=void 0;Et.SMHD=void 0;Et.STSD=void 0;Et.FTYP=void 0;Et.DINF=void 0;var RT=9e4;function c0(s,e,t=1,i=false){let r=s*e*t;return i?Math.round(r):r}function zw(s,e,t=1,i=false){return c0(s,e,1/t,i)}function ol(s,e=false){return c0(s,1e3,1/RT,e)}function Qw(s,e=1){return c0(s,RT,1/e)}function c_(s){let{baseTime:e,timescale:t,trackId:i}=s;return `${e/t} (${e}/${t}) trackId: ${i}`}var Xw=10*1e3,Zw=1024,Jw=1152,eC=1536,ao=null,bp=null;function u_(s,e,t,i){return {duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}var mo=class extends qt{constructor(e,t,i,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=false,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=false,this.isVideoContiguous=false,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=false,ao===null){let o=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ao=o?parseInt(o[1]):0;}if(bp===null){let n=navigator.userAgent.match(/Safari\/(\d+)/i);bp=n?parseInt(n[1]):0;}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null;}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&c_(t)} > ${e&&c_(e)}`),this._initPTS=this._initDTS=e;}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=false,this.isAudioContiguous=false;}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=false,this.videoTrackConfig=void 0;}getVideoStartPts(e){let t=false,i=e[0].pts,r=e.reduce((n,o)=>{let a=o.pts,l=a-n;return l<-4294967296&&(t=true,a=ii(a,i),l=a-n),l>0?n:a},i);return t&&this.debug("PTS rollover detected"),r}remux(e,t,i,r,n,o,a,l){let d,c,u,h,f,m,p=n,g=n,E=e.pid>-1,y=t.pid>-1,_=t.samples.length,S=e.samples.length>0,L=a&&_>0||_>1;if((!E||S)&&(!y||L)||this.ISGenerated||a){if(this.ISGenerated){var R,D,C,k;let X=this.videoTrackConfig;(X&&(t.width!==X.width||t.height!==X.height||((R=t.pixelRatio)==null?void 0:R[0])!==((D=X.pixelRatio)==null?void 0:D[0])||((C=t.pixelRatio)==null?void 0:C[1])!==((k=X.pixelRatio)==null?void 0:k[1]))||!X&&L||this.nextAudioTs===null&&S)&&this.resetInitSegment();}this.ISGenerated||(u=this.generateIS(e,t,n,o));let H=this.isVideoContiguous,q=-1,j;if(L&&(q=tC(t.samples),!H&&this.config.forceKeyFrameOnDiscontinuity))if(m=true,q>0){this.warn(`Dropped ${q} out of ${_} video samples due to a missing keyframe`);let X=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(q),t.dropped+=q,g+=(t.samples[0].pts-X)/t.inputTimeScale,j=g;}else q===-1&&(this.warn(`No keyframe found out of ${_} video samples`),m=false);if(this.ISGenerated){if(S&&L){let X=this.getVideoStartPts(t.samples),x=(ii(e.samples[0].pts,X)-X)/t.inputTimeScale;p+=Math.max(0,x),g+=Math.max(0,-x);}if(S){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,n,o)),c=this.remuxAudio(e,p,this.isAudioContiguous,o,y||L||l===J.AUDIO?g:void 0),L){let X=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,n,o)),d=this.remuxVideo(t,g,H,X);}}else L&&(d=this.remuxVideo(t,g,H,0));d&&(d.firstKeyFrame=q,d.independent=q!==-1,d.firstKeyFramePTS=j);}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=kT(i,n,this._initPTS,this._initDTS)),r.samples.length&&(h=wT(r,n,this._initPTS))),{audio:c,video:d,initSegment:u,independent:m,text:h,id3:f}}computeInitPts(e,t,i,r){let n=Math.round(i*t),o=ii(e,n);if(o<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-o)/t} ${r}`);o<n+t;)o+=8589934592;return o-n}generateIS(e,t,i,r){let n=e.samples,o=t.samples,a=this.typeSupported,l={},d=this._initPTS,c=!d||r,u="audio/mp4",h,f,m,p=-1;if(c&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case "mp3":a.mpeg?(u="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case "ac3":e.codec="ac-3";break}l.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):Et.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(p=e.id,m=e.inputTimeScale,!d||m!==d.timescale?h=f=this.computeInitPts(n[0].pts,m,i,"audio"):c=false);}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Et.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(p=t.id,m=t.inputTimeScale,!d||m!==d.timescale){let g=this.getVideoStartPts(o),E=ii(o[0].dts,g),y=this.computeInitPts(E,m,i,"video"),_=this.computeInitPts(g,m,i,"video");f=Math.min(f,y),h=Math.min(h,_);}else c=false;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio};}if(Object.keys(l).length)return this.ISGenerated=true,c?(d&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${i} ${h/m} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${h/m} (${h}/${m}) trackId: ${p}`),this._initPTS={baseTime:h,timescale:m,trackId:p},this._initDTS={baseTime:f,timescale:m,trackId:p}):h=m=void 0,{tracks:l,initPTS:h,timescale:m,trackId:p}}remuxVideo(e,t,i,r){let n=e.inputTimeScale,o=e.samples,a=[],l=o.length,d=this._initPTS,c=d.baseTime*n/d.timescale,u=this.nextVideoTs,h=8,f=this.videoSampleDuration,m,p,g=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,y=false;if(!i||u===null){let w=c+t*n,B=o[0].pts-ii(o[0].dts,o[0].pts);ao&&u!==null&&Math.abs(w-B-(u+c))<15e3?i=true:u=w-B-c;}let _=u+c;for(let w=0;w<l;w++){let B=o[w];B.pts=ii(B.pts,_),B.dts=ii(B.dts,_),B.dts<o[w>0?w-1:w].dts&&(y=true);}y&&o.sort(function(w,B){let z=w.dts-B.dts,te=w.pts-B.pts;return z||te}),m=o[0].dts,p=o[o.length-1].dts;let S=p-m,L=S?Math.round(S/(l-1)):f||e.inputTimeScale/30;if(i){let w=m-_,B=w>L,z=w<-1;if((B||z)&&(B?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ol(w,true)} ms (${w}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ol(-w,true)} ms (${w}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!z||_>=o[0].pts||ao)){m=_;let te=o[0].pts-w;if(B)o[0].dts=m,o[0].pts=te;else {let se=true;for(let re=0;re<o.length&&!(o[re].dts>te&&se);re++){let Ie=o[re].pts;if(o[re].dts-=w,o[re].pts-=w,re<o.length-1){let dt=o[re+1].pts,Pt=o[re].pts,jt=dt<=Pt,gi=dt<=Ie;se=jt==gi;}}}this.log(`Video: Initial PTS/DTS adjusted: ${ol(te,true)}/${ol(m,true)}, delta: ${ol(w,true)} ms`);}}m=Math.max(0,m);let O=0,R=0,D=m;for(let w=0;w<l;w++){let B=o[w],z=B.units,te=z.length,se=0;for(let re=0;re<te;re++)se+=z[re].data.length;R+=se,O+=te,B.length=se,B.dts<D?(B.dts=D,D+=L/4|0||1):D=B.dts,g=Math.min(B.pts,g),E=Math.max(B.pts,E);}p=o[l-1].dts;let C=R+4*O+8,k;try{k=new Uint8Array(C);}catch(w){this.observer.emit(v.ERROR,v.ERROR,{type:ie.MUX_ERROR,details:M.REMUX_ALLOC_ERROR,fatal:false,error:w,bytes:C,reason:`fail allocating video mdat ${C}`});return}let H=new DataView(k.buffer);H.setUint32(0,C),k.set(Et.types.mdat,4);let q=false,j=Number.POSITIVE_INFINITY,X=Number.POSITIVE_INFINITY,Y=Number.NEGATIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(let w=0;w<l;w++){let B=o[w],z=B.units,te=0;for(let Ie=0,dt=z.length;Ie<dt;Ie++){let Pt=z[Ie],jt=Pt.data,gi=Pt.data.byteLength;H.setUint32(h,gi),h+=4,k.set(jt,h),h+=gi,te+=4+gi;}let se;if(w<l-1)f=o[w+1].dts-B.dts,se=o[w+1].pts-B.pts;else {let Ie=this.config,dt=w>0?B.dts-o[w-1].dts:L;if(se=w>0?B.pts-o[w-1].pts:L,Ie.stretchShortVideoTrack&&this.nextAudioTs!==null){let Pt=Math.floor(Ie.maxBufferHole*n),jt=(r?g+r*n:this.nextAudioTs+c)-B.pts;jt>Pt?(f=jt-dt,f<0?f=dt:q=true,this.log(`It is approximately ${jt/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=dt;}else f=dt;}let re=Math.round(B.pts-B.dts);j=Math.min(j,f),Y=Math.max(Y,f),X=Math.min(X,se),x=Math.max(x,se),a.push(u_(B.key,f,te,re));}if(a.length){if(ao){if(ao<70){let w=a[0].flags;w.dependsOn=2,w.isNonSync=0;}}else if(bp&&x-X<Y-j&&L/Y<.025&&a[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let w=m;for(let B=0,z=a.length;B<z;B++){let te=w+a[B].duration,se=w+a[B].cts;if(B<z-1){let re=te+a[B+1].cts;a[B].duration=re-se;}else a[B].duration=B?a[B-1].duration:L;a[B].cts=0,w=te;}}}f=q||!f?L:f;let T=p+f;this.nextVideoTs=u=T-c,this.videoSampleDuration=f,this.isVideoContiguous=true;let U={data1:Et.moof(e.sequenceNumber++,m,Be(e,{samples:a})),data2:k,startPTS:(g-c)/n,endPTS:(E+f-c)/n,startDTS:(m-c)/n,endDTS:u/n,type:"video",hasAudio:false,hasVideo:true,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,U}getSamplesPerFrame(e){switch(e.segmentCodec){case "mp3":return Jw;case "ac3":return eC;default:return Zw}}remuxAudio(e,t,i,r,n){let o=e.inputTimeScale,a=e.samplerate?e.samplerate:o,l=o/a,d=this.getSamplesPerFrame(e),c=d*l,u=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=n!==void 0,p=e.samples,g=h?0:8,E=this.nextAudioTs||-1,y=u.baseTime*o/u.timescale,_=y+t*o;if(this.isAudioContiguous=i=i||p.length&&E>0&&(r&&Math.abs(_-(E+y))<9e3||Math.abs(ii(p[0].pts,_)-(E+y))<20*c),p.forEach(function(x){x.pts=ii(x.pts,_);}),!i||E<0){let x=p.length;if(p=p.filter(T=>T.pts>=0),x!==p.length&&this.warn(`Removed ${p.length-x} of ${x} samples (initPTS ${y} / ${o})`),!p.length)return;n===0?E=0:r&&!m?E=Math.max(0,_-y):E=p[0].pts-y;}if(e.segmentCodec==="aac"){let x=this.config.maxAudioFramesDrift;for(let T=0,I=E+y;T<p.length;T++){let P=p[T],U=P.pts,w=U-I,B=Math.abs(1e3*w/o);if(w<=-x*c&&m)T===0&&(this.warn(`Audio frame @ ${(U/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*w/o)} ms.`),this.nextAudioTs=E=U-y,I=U);else if(w>=x*c&&B<Xw&&m){let z=Math.round(w/c);for(I=U-z*c;I<0&&z&&c;)z--,I+=c;T===0&&(this.nextAudioTs=E=I-y),this.warn(`Injecting ${z} audio frames @ ${((I-y)/o).toFixed(3)}s due to ${Math.round(1e3*w/o)} ms gap.`);for(let te=0;te<z;te++){let se=lg.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);se||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),se=P.unit.subarray()),p.splice(T,0,{unit:se,pts:I}),I+=c,T++;}}P.pts=I,I+=c;}}let S=null,L=null,O,R=0,D=p.length;for(;D--;)R+=p[D].unit.byteLength;for(let x=0,T=p.length;x<T;x++){let I=p[x],P=I.unit,U=I.pts;if(L!==null){let B=f[x-1];B.duration=Math.round((U-L)/l);}else if(i&&e.segmentCodec==="aac"&&(U=E+y),S=U,R>0){R+=g;try{O=new Uint8Array(R);}catch(B){this.observer.emit(v.ERROR,v.ERROR,{type:ie.MUX_ERROR,details:M.REMUX_ALLOC_ERROR,fatal:false,error:B,bytes:R,reason:`fail allocating audio mdat ${R}`});return}h||(new DataView(O.buffer).setUint32(0,R),O.set(Et.types.mdat,4));}else return;O.set(P,g);let w=P.byteLength;g+=w,f.push(u_(true,d,w,0)),L=U;}let C=f.length;if(!C)return;let k=f[f.length-1];E=L-y,this.nextAudioTs=E+l*k.duration;let H=h?new Uint8Array(0):Et.moof(e.sequenceNumber++,S/l,Be({},e,{samples:f}));e.samples=[];let q=(S-y)/o,j=this.nextAudioTs/o,Y={data1:H,data2:O,startPTS:q,endPTS:j,startDTS:q,endDTS:j,type:"audio",hasAudio:true,hasVideo:false,nb:C};return this.isAudioContiguous=true,Y}};function ii(s,e){let t;if(e===null)return s;for(e<s?t=-8589934592:t=8589934592;Math.abs(s-e)>4294967296;)s+=t;return s}function tC(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return -1}function kT(s,e,t,i){let r=s.samples.length;if(!r)return;let n=s.inputTimeScale;for(let a=0;a<r;a++){let l=s.samples[a];l.pts=ii(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=ii(l.dts-i.baseTime*n/i.timescale,e*n)/n;}let o=s.samples;return s.samples=[],{samples:o}}function wT(s,e,t){let i=s.samples.length;if(!i)return;let r=s.inputTimeScale;for(let o=0;o<i;o++){let a=s.samples[o];a.pts=ii(a.pts-t.baseTime*r/t.timescale,e*r)/r;}s.samples.sort((o,a)=>o.pts-a.pts);let n=s.samples;return s.samples=[],{samples:n}}var dg=class extends qt{constructor(e,t,i,r){super("passthrough-remuxer",r),this.emitInitSegment=false,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=false;}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e);}resetNextTimestamp(){this.isVideoContiguous=false,this.lastEndTime=null;}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,r),this.emitInitSegment=true;}generateInitSegment(e,t){let{audioCodec:i,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:n,video:o}=this.initData=B_(e);if(t)nk(e,t);else {let l=n||o;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`);}n&&(i=h_(n,Ve.AUDIO,this)),o&&(r=h_(o,Ve.VIDEO,this));let a={};n&&o?a.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:n?a.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:e,id:"audio"}:o?a.video={container:"video/mp4",codec:r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a;}remux(e,t,i,r,n,o){var a,l;let{initPTS:d,lastEndTime:c}=this,u={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};Q(c)||(c=this.lastEndTime=n||0);let h=t.samples;if(!h.length)return u;let f={initPTS:void 0,timescale:void 0,trackId:void 0},m=this.initData;if((a=m)!=null&&a.length||(this.generateInitSegment(h),m=this.initData),!((l=m)!=null&&l.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=false);let p=ak(h,m,this),g=m.audio?p[m.audio.id]:null,E=m.video?p[m.video.id]:null,y=wu(E,1/0),_=wu(g,1/0),S=wu(E,0,true),L=wu(g,0,true),O=n,R=0,D=g&&(!E||!d&&_<y||d&&d.trackId===m.audio.id),C=D?g:E;if(C){let I=C.timescale,P=C.start-n*I,U=D?m.audio.id:m.video.id;O=C.start/I,R=D?L-_:S-y,(o||!d)&&(iC(d,O,n,R)||I!==d.timescale)&&(d&&this.warn(`Timestamps at playlist time: ${o?"":"~"}${n} ${P/I} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${O-n} (${P}/${I}) trackId: ${U}`),d=null,f.initPTS=P,f.timescale=I,f.trackId=U);}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);d?(f.initPTS=d.baseTime,f.timescale=d.timescale,f.trackId=d.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=O,f.timescale=1,f.trackId=-1),this.initPTS=d={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let k=O-d.baseTime/d.timescale,H=k+R;R>0?this.lastEndTime=H:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let q=!!m.audio,j=!!m.video,X="";q&&(X+="audio"),j&&(X+="video");let Y=(m.audio?m.audio.encrypted:false)||(m.video?m.video.encrypted:false),x={data1:h,startPTS:k,startDTS:k,endPTS:H,endDTS:H,type:X,hasAudio:q,hasVideo:j,nb:1,dropped:0,encrypted:Y};u.audio=q&&!j?x:void 0,u.video=j?x:void 0;let T=E?.sampleCount;if(T){let I=E.keyFrameIndex,P=I!==-1;x.nb=T,x.dropped=I===0||this.isVideoContiguous?0:P?I:T,x.independent=P,x.firstKeyFrame=I,P&&E.keyFrameStart&&(x.firstKeyFramePTS=(E.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(u.independent=P),this.isVideoContiguous||(this.isVideoContiguous=P),x.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${I}/${T} dropped: ${x.dropped} start: ${x.firstKeyFramePTS||"NA"}`);}return u.initSegment=f,u.id3=kT(i,n,d,d),r.samples.length&&(u.text=wT(r,n,d)),u}};function wu(s,e,t=false){return s?.start!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function iC(s,e,t,i){if(s===null)return true;let r=Math.max(i,1),n=e-s.baseTime/s.timescale;return Math.abs(n-t)>r}function h_(s,e,t){let i=s.codec;return i&&i.length>4?i:e===Ve.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?ju(i,false):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}var Rs;try{Rs=self.performance.now.bind(self.performance);}catch{Rs=Date.now;}var Hu=[{demux:tg,remux:dg},{demux:ng,remux:mo},{demux:Zp,remux:mo},{demux:eg,remux:mo}];Hu.splice(2,0,{demux:Jp,remux:mo});var ah=class{constructor(e,t,i,r,n,o){this.asyncResult=false,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=o;}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset();}push(e,t,i,r){let n=i.transmuxing;n.executeStart=Rs();let o=new Uint8Array(e),{currentTransmuxState:a,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);let{contiguous:d,discontinuity:c,trackSwitch:u,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=r||a,{audioCodec:p,videoCodec:g,defaultInitPts:E,duration:y,initSegmentData:_}=l,S=sC(o,t);if(S&&fo(S.method)){let D=this.getDecrypter(),C=s0(S.method);if(D.isSync()){let k=D.softwareDecrypt(o,S.key.buffer,S.iv.buffer,C);if(i.part>-1){let q=D.flush();k=q&&q.buffer;}if(!k)return n.executeEnd=Rs(),_p(i);o=new Uint8Array(k);}else return this.asyncResult=true,this.decryptionPromise=D.webCryptoDecrypt(o,S.key.buffer,S.iv.buffer,C).then(k=>{let H=this.push(k,null,i);return this.decryptionPromise=null,H}),this.decryptionPromise}let L=this.needsProbing(c,u);if(L){let D=this.configureTransmuxer(o);if(D)return this.logger.warn(`[transmuxer] ${D.message}`),this.observer.emit(v.ERROR,v.ERROR,{type:ie.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:false,error:D,reason:D.message}),n.executeEnd=Rs(),_p(i)}(c||u||m||L)&&this.resetInitSegment(_,p,g,y,t),(c||m||L)&&this.resetInitialTimestamp(E),d||this.resetContiguity();let O=this.transmux(o,S,f,h,i);this.asyncResult=_l(O);let R=this.currentTransmuxState;return R.contiguous=true,R.discontinuity=false,R.trackSwitch=false,n.executeEnd=Rs(),O}flush(e){let t=e.transmuxing;t.executeStart=Rs();let{decrypter:i,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=true,n.then(()=>this.flush(e));let o=[],{timeOffset:a}=r;if(i){let u=i.flush();u&&o.push(this.push(u.buffer,null,e));}let{demuxer:l,remuxer:d}=this;if(!l||!d){t.executeEnd=Rs();let u=[_p(e)];return this.asyncResult?Promise.resolve(u):u}let c=l.flush(a);return _l(c)?(this.asyncResult=true,c.then(u=>(this.flushRemux(o,u,e),o))):(this.flushRemux(o,c,e),this.asyncResult?Promise.resolve(o):o)}flushRemux(e,t,i){let{audioTrack:r,videoTrack:n,id3Track:o,textTrack:a}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===J.MAIN?"level":"track"} ${i.level}`);let c=this.remuxer.remux(r,n,o,a,d,l,true,this.id);e.push({remuxResult:c,chunkMeta:i}),i.transmuxing.executeEnd=Rs();}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e));}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp());}resetInitSegment(e,t,i,r,n){let{demuxer:o,remuxer:a}=this;!o||!a||(o.resetInitSegment(e,t,i,r),a.resetInitSegment(e,t,i,n));}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0);}transmux(e,t,i,r,n){let o;return t&&t.method==="SAMPLE-AES"?o=this.transmuxSampleAes(e,t,i,r,n):o=this.transmuxUnencrypted(e,i,r,n),o}transmuxUnencrypted(e,t,i,r){let{audioTrack:n,videoTrack:o,id3Track:a,textTrack:l}=this.demuxer.demux(e,t,false,!this.config.progressive);return {remuxResult:this.remuxer.remux(n,o,a,l,t,i,false,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,n){return this.demuxer.demuxSampleAes(e,t,i).then(o=>({remuxResult:this.remuxer.remux(o.audioTrack,o.videoTrack,o.id3Track,o.textTrack,i,r,false,this.id),chunkMeta:n}))}configureTransmuxer(e){let{config:t,observer:i,typeSupported:r}=this,n;for(let u=0,h=Hu.length;u<h;u++){var o;if((o=Hu[u].demux)!=null&&o.probe(e,this.logger)){n=Hu[u];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");let a=this.demuxer,l=this.remuxer,d=n.remux,c=n.demux;(!l||!(l instanceof d))&&(this.remuxer=new d(i,t,r,this.logger)),(!a||!(a instanceof c))&&(this.demuxer=new c(i,t,r,this.logger),this.probe=c.probe);}needsProbing(e,t){return !this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new pl(this.config)),e}};function sC(s,e){let t=null;return s.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var _p=s=>({remuxResult:{},chunkMeta:s});function _l(s){return "then"in s&&s.then instanceof Function}var cg=class{constructor(e,t,i,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=n||null;}},ug=class{constructor(e,t,i,r,n,o){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=o;}},f_=0,lh=class{constructor(e,t,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=f_++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{let d=l.data,c=this.hls;if(!(!c||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case "init":{var u;let h=(u=this.workerContext)==null?void 0:u.objectURL;h&&self.URL.revokeObjectURL(h);break}case "transmuxComplete":{this.handleTransmuxComplete(d.data);break}case "flush":{this.onFlush(d.data);break}case "workerLog":{c.logger[d.data.logType]&&c.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,c.trigger(d.event,d.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let d=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=false,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(v.ERROR,{type:ie.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,fatal:false,event:"demuxerWorker",error:d});};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;let o=(l,d)=>{d=d||{},d.frag=this.frag||void 0,l===v.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(l,d);};this.observer=new n0,this.observer.on(v.FRAG_DECRYPTED,o),this.observer.on(v.ERROR,o);let a=wb(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let l=this.hls.logger;if(n.workerPath||Ew()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=bw(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=yw());let{worker:c}=this.workerContext;c.addEventListener("message",this.onWorkerMessage),c.addEventListener("error",this.onWorkerError),c.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:We(n)});}catch(c){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,c),this.terminateWorker(),this.error=null,this.transmuxer=new ah(this.observer,a,n,"",t,e.logger);}return}}this.transmuxer=new ah(this.observer,a,n,"",t,e.logger);}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=f_++;let t=this.hls.config,i=wb(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:We(t)});}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),_w(this.hls.config.workerPath);}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else {let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null);}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null;}push(e,t,i,r,n,o,a,l,d,c){var u,h;d.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:m}=this,p=o?o.start:n.start,g=n.decryptdata,E=this.frag,y=!(E&&n.cc===E.cc),_=!(E&&d.level===E.level),S=E?d.sn-E.sn:-1,L=this.part?d.part-this.part.index:-1,O=S===0&&d.id>1&&d.id===E?.stats.chunkCount,R=!_&&(S===1||S===0&&(L===1||O&&L<=0)),D=self.performance.now();(_||S||n.stats.parsing.start===0)&&(n.stats.parsing.start=D),o&&(L||!R)&&(o.stats.parsing.start=D);let C=!(E&&((u=n.initSegment)==null?void 0:u.url)===((h=E.initSegment)==null?void 0:h.url)),k=new ug(y,R,l,_,p,C);if(!R||y||C){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===J.MAIN?"level":"track"}: ${d.level} id: ${d.id}
1941
+ discontinuity: ${y}
1942
+ trackSwitch: ${_}
1943
+ contiguous: ${R}
1944
+ accurateTimeOffset: ${l}
1945
+ timeOffset: ${p}
1946
+ initSegmentChange: ${C}`);let H=new cg(i,r,t,a,c);this.configureTransmuxer(H);}if(this.frag=n,this.part=o,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:g,chunkMeta:d,state:k},e instanceof ArrayBuffer?[e]:[]);else if(m){let H=m.push(e,g,d,k);_l(H)?H.then(q=>{this.handleTransmuxComplete(q);}).catch(q=>{this.transmuxerError(q,d,"transmuxer-interface push error");}):this.handleTransmuxComplete(H);}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let r=i.flush(e);_l(r)?r.then(n=>{this.handleFlushResult(n,e);}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error");}):this.handleFlushResult(r,e);}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:false,error:e,err:e,reason:i}));}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i);}),this.onFlush(t);}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e);}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e);}},m_=100,hg=class extends vl{constructor(e,t,i){super(e,t,i,"audio-stream-controller",J.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=false,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=false,this.bufferFlushed=false,this.cachedTrackLoadedData=null,this.registerListeners();}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem();}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null;}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(v.BUFFER_RESET,this.onBufferReset,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(v.FRAG_LOADING,this.onFragLoading,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this);}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(v.BUFFER_RESET,this.onBufferReset,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(v.FRAG_LOADING,this.onFragLoading,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this));}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n,trackId:o}){if(i===J.MAIN){let a=t.cc,l=this.fragCurrent;if(this.initPTS[a]={baseTime:r,timescale:n,trackId:o},this.log(`InitPTS for cc: ${a} found from main: ${r/n} (${r}/${n}) trackId: ${o}`),this.mainAnchor=t,this.state===G.WAITING_INIT_PTS){let d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==a)&&this.syncWithAnchor(t,d?.frag);}else !this.hls.hasEnoughToStart&&l&&l.cc!==a?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===G.IDLE&&this.tick();}}getLoadPosition(){return !this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;let r=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&r?.cc===t.cc)return;let n=(r||e).cc,o=this.getLevelDetails(),a=this.getLoadPosition(),l=X_(o,n,a);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=false,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===G.IDLE&&this.doTickIdle());}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=G.STOPPED;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(m_),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=G.IDLE):this.state=G.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick();}doTick(){switch(this.state){case G.IDLE:this.doTickIdle();break;case G.WAITING_TRACK:{let{levels:e,trackId:t}=this,i=e?.[t],r=i?.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=G.WAITING_INIT_PTS;}break}case G.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case G.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:r,complete:n}=e,o=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=G.FRAG_LOADING;let a=r.flush().buffer,l={frag:t,part:i,payload:a,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l);}else o&&o.cc!==e.frag.cc&&this.syncWithAnchor(o,e.frag);}else this.state=G.IDLE;}}this.onTickEnd();}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState();}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime);}doTickIdle(){var e;let{hls:t,levels:i,media:r,trackId:n}=this,o=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!o.startFragPrefetch)||!(i!=null&&i[n]))return;let a=i[n],l=a.details;if(!l||this.waitForLive(a)||this.waitForCdnTuneIn(l)){this.state=G.WAITING_TRACK,this.startFragRequested=false;return}let d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=false,this.afterBufferFlushed(d,Ve.AUDIO,J.AUDIO));let c=this.getFwdBufferInfo(d,J.AUDIO);if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,l)){t.trigger(v.BUFFER_EOS,{type:"audio"}),this.state=G.ENDED;return}let u=c.len,h=t.maxBufferLength,f=l.fragments,m=f[0].start,p=this.getLoadPosition(),g=this.flushing?p:c.end;if(this.switchingTrack&&r){let _=p;l.PTSKnown&&_<m&&(c.end>m||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=m+.05);}if(u>=h&&!this.switchingTrack&&g<f[f.length-1].start)return;let E=this.getNextFragment(g,l);if(E&&this.isLoopLoading(E,g)&&(E=this.getNextFragmentLoopLoading(E,l,c,J.MAIN,h)),!E){this.bufferFlushed=true;return}let y=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&at(E)&&!E.endList&&(!l.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===vt.OK&&(this.mainFragLoading=y=null),y&&at(y))){if(E.start>y.end){let S=this.fragmentTracker.getFragAtPos(g,J.MAIN);S&&S.end>y.end&&(y=S,this.mainFragLoading={frag:S,targetBufferTime:null});}if(E.start>y.end)return}this.loadFragment(E,a,g);}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=false,super.onMediaDetaching(e,t);}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new Jr(i));}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==G.STOPPED&&(this.setInterval(m_),this.state=G.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval());}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=false,this.resetItem(),this.trackId=-1;}onLevelLoaded(e,t){this.mainDetails=t.details;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(v.AUDIO_TRACK_LOADED,i));}onAudioTrackLoaded(e,t){var i;let{levels:r}=this,{details:n,id:o,groupId:a,track:l}=t;if(!r){this.warn(`Audio tracks reset while loading track ${o} "${l.name}" of "${a}"`);return}let d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==G.STOPPED&&(this.state=G.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${o} "${l.name}" of "${a}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);let c=r[o],u=0;if(n.live||(i=c.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(c.details){var h;u=this.alignPlaylists(n,c.details,(h=this.levelLastLoaded)==null?void 0:h.details);}n.alignedSliding||(fT(n,d),n.alignedSliding||sh(n,d),u=n.fragmentStart);}c.details=n,this.levelLastLoaded=c,this.startFragRequested||this.setStartPosition(d,u),this.hls.trigger(v.AUDIO_TRACK_UPDATED,{details:n,id:o,groupId:t.groupId}),this.state===G.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=G.IDLE),this.tick();}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:n}=e,{config:o,trackId:a,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let d=l[a];if(!d){this.warn("Audio track is undefined on fragment load progress");return}let c=d.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let u=o.defaultAudioCodec||d.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new lh(this.hls,J.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],m=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){let g=r?r.index:-1,E=g!==-1,y=new gl(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,E);h.push(n,m,u,"",i,r,c.totalduration,false,y,f);}else {this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);let{cache:p}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new rh,complete:false};p.push(new Uint8Array(n)),this.state!==G.STOPPED&&(this.state=G.WAITING_INIT_PTS);}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=true;return}super._handleFragmentLoadComplete(e);}onBufferReset(){this.mediaBuffer=null;}onBufferCreated(e,t){this.bufferFlushed=this.flushing=false;let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null);}onFragLoading(e,t){!this.audioOnly&&t.frag.type===J.MAIN&&at(t.frag)&&(this.mainFragLoading=t,this.state===G.IDLE&&this.tick());}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i.type!==J.AUDIO){!this.audioOnly&&i.type===J.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=true,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(at(i)){this.fragPrevious=i;let n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(v.AUDIO_TRACK_SWITCHED,Oe({},n)));}this.fragBufferedComplete(i,r),this.media&&this.tick();}onError(e,t){var i;if(t.fatal){this.state=G.ERROR;return}switch(t.details){case M.FRAG_GAP:case M.FRAG_PARSING_ERROR:case M.FRAG_DECRYPT_ERROR:case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.AUDIO,t);break;case M.AUDIO_TRACK_LOAD_ERROR:case M.AUDIO_TRACK_LOAD_TIMEOUT:case M.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===G.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===Te.AUDIO_TRACK&&(this.state=G.IDLE);break;case M.BUFFER_ADD_CODEC_ERROR:case M.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case M.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case M.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Ve.VIDEO&&(this.flushing=true);}onBufferFlushed(e,{type:t}){if(t!==Ve.VIDEO){this.flushing=false,this.bufferFlushed=true,this.state===G.ENDED&&(this.state=G.IDLE);let i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,J.AUDIO),this.tick());}}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:n,chunkMeta:o}=e,a=this.getCurrentContext(o);if(!a){this.resetWhenMissingContext(o);return}let{frag:l,part:d,level:c}=a,{details:u}=c,{audio:h,text:f,id3:m,initSegment:p}=n;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l);return}if(this.state=G.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){let g=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(c,p.tracks,g,o),r.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:i,tracks:p.tracks});}if(h){let{startPTS:g,endPTS:E,startDTS:y,endDTS:_}=h;d&&(d.elementaryStreams[Ve.AUDIO]={startPTS:g,endPTS:E,startDTS:y,endDTS:_}),l.setElementaryStreamInfo(Ve.AUDIO,g,E,y,_),this.bufferFragmentData(h,l,d,o);}if(m!=null&&(t=m.samples)!=null&&t.length){let g=Be({id:i,frag:l,details:u},m);r.trigger(v.FRAG_PARSING_METADATA,g);}if(f){let g=Be({id:i,frag:l,details:u},f);r.trigger(v.FRAG_PARSING_USERDATA,g);}}_bufferInitSegment(e,t,i,r){if(this.state!==G.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=J.AUDIO;let o=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${o}/${n.codec}]`),o&&o.split(",").length===1&&(n.levelCodec=o),this.hls.trigger(v.BUFFER_CODECS,t);let a=n.initSegment;if(a!=null&&a.byteLength){let l={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(v.BUFFER_APPENDING,l);}this.tickImmediate();}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===vt.NOT_LOADED||r===vt.PARTIAL){var n;if(!at(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=G.WAITING_INIT_PTS;let o=this.mainDetails;o&&o.fragmentStart!==t.details.fragmentStart&&sh(t.details,o);}else super.loadFragment(e,t,i);}else this.clearTrackerIfNeeded(e);}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:a}=this.bufferedTrack;Xr({name:t,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:a},e,zr)||(Qu(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e);}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(v.AUDIO_TRACK_SWITCHED,Oe({},e));}},Tl=class extends qt{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=false,this.timer=-1,this.hls=e;}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null;}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1);}startLoad(){this.canLoad=true,this.loadPlaylist();}stopLoad(){this.canLoad=false,this.clearTimer();}switchParams(e,t,i){let r=t?.renditionReports;if(r){let n=-1;for(let o=0;o<r.length;o++){let a=r[o],l;try{l=new self.URL(a.URI,t.url).href;}catch(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),l=a.URI||"";}if(l===e){n=o;break}else l===e.substring(0,l.length)&&(n=o);}if(n!==-1){let o=r[n],a=parseInt(o["LAST-MSN"])||t.lastPartSn,l=parseInt(o["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let c=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&c>t.partTarget&&(l+=1);}let d=i&&Cb(i);return new zu(a,l>=0?l:void 0,d)}}}loadPlaylist(e){this.clearTimer();}loadingPlaylist(e,t){this.clearTimer();}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`);}return e}playlistLoaded(e,t,i){let{details:r,stats:n}=t,o=self.performance.now(),a=n.loading.first?Math.max(0,o-n.loading.first):0;r.advancedDateTime=Date.now()-a;let l=this.hls.config.timelineOffset;if(l!==r.appliedTimelineOffset){let c=Math.max(l||0,0);r.appliedTimelineOffset=c,r.fragments.forEach(u=>{u.setStart(u.playlistOffset+c);});}if(r.live||i!=null&&i.live){let c="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){aw(i,r,this);let y=r.playlistParsingError;if(y){this.warn(y);let _=this.hls;if(!_.config.ignorePlaylistParsingErrors){var d;let{networkDetails:S}=t;_.trigger(v.ERROR,{type:ie.NETWORK_ERROR,details:M.LEVEL_PARSING_ERROR,fatal:false,url:r.url,error:y,reason:y.message,level:t.level||void 0,parent:(d=r.fragments[0])==null?void 0:d.type,networkDetails:S,stats:n});return}r.playlistParsingError=null;}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);let u=this.hls.mainForwardBufferInfo,h=u?u.end-u.len:0,f=(r.edge-h)*1e3,m=lT(r,f);if(r.requestScheduled+m<o?r.requestScheduled=o:r.requestScheduled+=m,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let p,g,E;if(r.canBlockReload&&r.endSN&&r.advanced){let y=this.hls.config.lowLatencyMode,_=r.lastPartSn,S=r.endSN,L=r.lastPartIndex,O=L!==-1,R=_===S;O?R?(g=S+1,E=y?0:L):(g=_,E=y?L+1:r.maxPartIndex):g=S+1;let D=r.age,C=D+r.ageHeader,k=Math.min(C-r.partTarget,r.targetduration*1.5);if(k>0){if(C>r.targetduration*3)this.log(`Playlist last advanced ${D.toFixed(2)}s ago. Omitting segment and part directives.`),g=void 0,E=void 0;else if(i!=null&&i.tuneInGoal&&C-r.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${k} with playlist age: ${r.age}`),k=0;else {let H=Math.floor(k/r.targetduration);if(g+=H,E!==void 0){let q=Math.round(k%r.targetduration/r.partTarget);E+=q;}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${D.toFixed(2)}s goal: ${k} skip sn ${H} to part ${E}`);}r.tuneInGoal=k;}if(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,E),y||!R){r.requestScheduled=o,this.loadingPlaylist(c,p);return}}else (r.canBlockReload||r.canSkipUntil)&&(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,E));p&&g!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(m-a*2,m/2)),this.scheduleLoading(c,p,r);}else this.clearTimer();}scheduleLoading(e,t,i){let r=i||e.details;if(!r){this.loadingPlaylist(e,t);return}let n=self.performance.now(),o=r.requestScheduled;if(n>=o){this.loadingPlaylist(e,t);return}let a=o-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a);}getDeliveryDirectives(e,t,i,r){let n=Cb(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=$u.No),new zu(i,r,n)}checkRetry(e){let t=e.details,i=Xu(e),r=e.errorAction,{action:n,retryCount:o=0,retryConfig:a}=r||{},l=!!r&&!!a&&(n===St.RetryRequest||!r.resolved&&n===St.SendAlternateToPenaltyBox);if(l){var d;if(o>=a.maxNumRetry)return false;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else {let c=i0(a,o);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),c),this.warn(`Retrying playlist loading ${o+1}/${a.maxNumRetry} after "${t}" in ${c}ms`);}e.levelRetry=true,r.resolved=true;}return l}};function CT(s,e){if(s.length!==e.length)return false;for(let t=0;t<s.length;t++)if(!Sl(s[t].attrs,e[t].attrs))return false;return true}function Sl(s,e,t){let i=s["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>s[r]!==e[r])}function fg(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}var mg=class extends Tl{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true,this.registerListeners();}registerListeners(){let{hls:e}=this;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(v.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVEL_LOADING,this.onLevelLoading,this),e.off(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(v.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(v.ERROR,this.onError,this);}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy();}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=true;}onManifestParsed(e,t){this.tracks=t.audioTracks||[];}onAudioTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==r){this.warn(`Audio track with id:${i} and group:${r} not found in active group ${o?.groupId}`);return}let a=o.details;o.details=t.details,this.log(`Audio track ${i} "${o.name}" lang:${o.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a);}onLevelLoading(e,t){this.switchLevel(t.level);}onLevelSwitching(e,t){this.switchLevel(t.level);}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||r?.length!==i?.length||i!=null&&i.some(a=>r?.indexOf(a)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let a=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=false),a.forEach((h,f)=>{h.id=f;});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;let l=this.hls.config.audioPreference;if(!n&&l){let h=os(l,a,zr);if(h>-1)n=a[h];else {let f=os(l,this.tracks);n=this.tracks[f];}}let d=this.findTrackId(n);d===-1&&n&&(d=this.findTrackId(null));let c={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(v.AUDIO_TRACKS_UPDATED,c);let u=this.trackId;if(d!==-1&&u===-1)this.setAudioTrack(d);else if(a.length&&u===-1){var o;let h=new Error(`No audio track selected for current audio group-ID(s): ${(o=this.groupIds)==null?void 0:o.join(",")} track count: ${a.length}`);this.warn(h.message),this.hls.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.AUDIO_TRACK_LOAD_ERROR,fatal:true,error:h});}}}onError(e,t){t.fatal||!t.context||t.context.type===Te.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t);}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=false,this.setAudioTrack(e);}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let i=this.allAudioTracks;if(this.selectDefaultTrack=false,i.length){let r=this.currentTrack;if(r&&Xr(e,r,zr))return r;let n=os(e,this.tracksInGroup,zr);if(n>-1){let o=this.tracksInGroup[n];return this.setAudioTrack(n),o}else if(r){let o=t.loadLevel;o===-1&&(o=t.firstAutoLevel);let a=Uk(e,t.levels,i,o,zr);if(a===-1)return null;t.nextLoadLevel=a;}if(e.channels||e.audioCodec){let o=os(e,i);if(o>-1)return i[o]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=false;let i=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===i&&n||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(v.AUDIO_TRACK_SWITCHING,Oe({},r)),n))return;let o=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(o);}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if(!(this.selectDefaultTrack&&!r.default)&&(!e||Xr(e,r,zr)))return i}if(e){let{name:i,lang:r,assocLang:n,characteristics:o,audioCodec:a,channels:l}=e;for(let d=0;d<t.length;d++){let c=t[d];if(Xr({name:i,lang:r,assocLang:n,characteristics:o,audioCodec:a,channels:l},c,zr))return d}for(let d=0;d<t.length;d++){let c=t[d];if(Sl(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){let c=t[d];if(Sl(e.attrs,c.attrs,["LANGUAGE"]))return d}}return -1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&Qu(t.url,this.hls)&&this.scheduleLoading(t,e);}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),o=e.details,a=o?.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${n}`),this.hls.trigger(v.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null,track:e});}},pg=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e;}destroy(){this.tracks=this.queues=null;}append(e,t,i){if(this.queues===null||this.tracks===null)return;let r=this.queues[t];r.push(e),r.length===1&&!i&&this.executeNext(t);}appendBlocker(e){return new Promise(t=>{let i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e);})}prependBlocker(e){return new Promise(t=>{if(this.queues){let i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i);}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1));});}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio");}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let r=t[0];try{r.execute();}catch(n){var i;if(r.onError(n),this.queues===null||this.tracks===null)return;let o=(i=this.tracks[e])==null?void 0:i.buffer;o!=null&&o.updating||this.shiftAndExecuteNext(e);}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e));}current(e){var t;return ((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
1947
+ ${this.list("video")}
1948
+ ${this.list("audio")}
1949
+ ${this.list("audiovideo")}}`}list(e){var t,i;return (t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=(t=this.tracks)==null?void 0:t[e],r=i?.buffer;return r?`SourceBuffer${r.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return ((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}},p_=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,DT="HlsJsTrackRemovedError",gg=class extends Error{constructor(e){super(e),this.name=DT;}},vg=class extends qt{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var r;this.hls&&((r=this.mediaSource)==null?void 0:r.readyState)==="open"&&this.hls.pauseBuffering();},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering();},this._onMediaSourceOpen=i=>{let{media:r,mediaSource:n}=this;i&&this.log("Media source opened"),!(!r||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(v.MEDIA_ATTACHED,{media:r,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks());},this._onMediaSourceClose=()=>{this.log("Media source closed");},this._onMediaSourceEnded=()=>{this.log("Media source ended");},this._onMediaEmptied=()=>{let{mediaSrc:i,_objectUrl:r}=this;i!==r&&this.error(`Media element src was set while attaching MediaSource (${r} > ${i})`);},this.hls=e,this.fragmentTracker=t,this.appendSource=QR(sr(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners();}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null;}registerListeners(){let{hls:e}=this;e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.BUFFER_RESET,this.onBufferReset,this),e.on(v.BUFFER_APPENDING,this.onBufferAppending,this),e.on(v.BUFFER_CODECS,this.onBufferCodecs,this),e.on(v.BUFFER_EOS,this.onBufferEos,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(v.FRAG_PARSED,this.onFragParsed,this),e.on(v.FRAG_CHANGED,this.onFragChanged,this),e.on(v.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.BUFFER_RESET,this.onBufferReset,this),e.off(v.BUFFER_APPENDING,this.onBufferAppending,this),e.off(v.BUFFER_CODECS,this.onBufferCodecs,this),e.off(v.BUFFER_EOS,this.onBufferEos,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(v.FRAG_PARSED,this.onFragParsed,this),e.off(v.FRAG_CHANGED,this.onFragChanged,this),e.off(v.ERROR,this.onError,this);}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let n=this.isUpdating();n||this.operationQueue.removeBlockers();let o=this.isQueued();(n||o)&&this.warn(`Transfering MediaSource with${o?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy();}let r=this.transferData;return !this.sourceBufferCount&&r&&r.mediaSource===t?Be(i,r.tracks):this.sourceBuffers.forEach(n=>{let[o]=n;o&&(i[o]=Be({},this.tracks[o]),this.removeBuffer(o)),n[0]=n[1]=null;}),{media:e,mediaSource:t,tracks:i}}initTracks(){let e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0;}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null;}onManifestParsed(e,t){var i;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated();}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let r=sr(this.appendSource);if(r){let n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let o=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(o),n)this._objectUrl=i.src,this.attachTransferred();else {let a=this._objectUrl=self.URL.createObjectURL(o);if(this.appendSource)try{i.removeAttribute("src");let l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&o instanceof l,g_(i),rC(i,a),i.load();}catch{i.src=a;}else i.src=a;}i.addEventListener("emptied",this._onMediaEmptied);}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming));}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,r=t.tracks,n=r?Object.keys(r):null,o=n?n.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen();});};if(r&&n&&o){if(!this.tracksReady){this.hls.config.startFragPrefetch=true,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
1950
+ required tracks: ${We(i,(l,d)=>l==="initSegment"?void 0:d)};
1951
+ transfer tracks: ${We(r,(l,d)=>l==="initSegment"?void 0:d)}}`),!P_(r,i)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,d=this.details,c=Math.max(l,d?.fragments[0].start||0);if(c-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${c}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(i)}") start time: ${c} currentTime: ${l}`),this.onMediaDetaching(v.MEDIA_DETACHING,{}),this.onMediaAttaching(v.MEDIA_ATTACHING,t),e.currentTime=c;return}this.transferData=void 0,n.forEach(l=>{let d=l,c=r[d];if(c){let u=c.buffer;if(u){let h=this.fragmentTracker,f=c.id;if(h.hasFragments(f)||h.hasParts(f)){let g=Ee.getBuffered(u);h.detectEvictedFragments(d,g,f,null,true);}let m=Tp(d),p=[d,u];this.sourceBuffers[m]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,c);}}}),a(),this.bufferCreated();}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a();}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:n,_objectUrl:o}=this;if(n){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a);}),this.resetQueue();else {if(this.mediaSourceOpenOrEnded){let a=n.readyState==="open";try{let l=n.sourceBuffers;for(let d=l.length;d--;)a&&l[d].abort(),n.removeSourceBuffer(l[d]);a&&n.endOfStream();}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`);}}this.sourceBufferCount&&this.onBufferReset();}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null;}r&&(r.removeEventListener("emptied",this._onMediaEmptied),i||(o&&self.URL.revokeObjectURL(o),this.mediaSrc===o?(r.removeAttribute("src"),this.appendSource&&g_(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(v.MEDIA_DETACHED,t);}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e);}),this.initTracks();}resetBuffer(e){var t;let i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i);}catch(n){this.warn(`onBufferReset ${e}`,n);}delete this.tracks[e];}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Tp(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0);}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new pg(this.tracks);}onBufferCodecs(e,t){var i;let r=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);let o="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),a=!o&&this.sourceBufferCount&&this.media&&n.some(l=>!r[l]);if(o||a){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var d,c;let u=t[l],{id:h,codec:f,levelCodec:m,container:p,metadata:g,supplemental:E}=u,y=r[l],_=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[l],S=_!=null&&_.buffer?_:y,L=S?.pendingCodec||S?.codec,O=S?.levelCodec;y||(y=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:E,container:p,levelCodec:m,metadata:g,id:h});let R=Fu(L,O),D=R?.replace(p_,"$1"),C=Fu(f,m),k=(c=C)==null?void 0:c.replace(p_,"$1");C&&R&&D!==k&&(l.slice(0,5)==="audio"&&(C=ju(C,this.appendSource)),this.log(`switching codec ${L} to ${C}`),C!==(y.pendingCodec||y.codec)&&(y.pendingCodec=C),y.container=p,this.appendChangeType(l,p,C));}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks());}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let r=`${t};codecs=${i}`,n={label:`change-type=${r}`,execute:()=>{let o=this.tracks[e];if(o){let a=o.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),a.changeType(r),o.codec=i,o.container=t);}this.shiftAndExecuteNext(e);},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn(`Failed to change ${e} SourceBuffer type`,o);}};this.append(n,e,this.isPending(this.tracks[e]));}blockAudio(e){var t;let i=e.start,r=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,J.MAIN))==null?void 0:t.gap)===true)return;let o={label:"block-audio",execute:()=>{var a;let l=this.tracks.video;(this.lastVideoAppendEnd>r||l!=null&&l.buffer&&Ee.isBuffered(l.buffer,r)||((a=this.fragmentTracker.getAppendedFrag(r,J.MAIN))==null?void 0:a.gap)===true)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"));},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn("Error executing block-audio operation",a);}};this.blockedAudioAppend={op:o,frag:e},this.append(o,"audio",true);}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op));}onBufferAppending(e,t){let{tracks:i}=this,{data:r,type:n,parent:o,frag:a,part:l,chunkMeta:d,offset:c}=t,u=d.buffering[n],{sn:h,cc:f}=a,m=self.performance.now();u.start=m;let p=a.stats.buffering,g=l?l.stats.buffering:null;p.start===0&&(p.start=m),g&&g.start===0&&(g.start=m);let E=i.audio,y=false;n==="audio"&&E?.container==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);let _=i.video,S=_?.buffer;if(S&&h!=="initSegment"){let R=l||a,D=this.blockedAudioAppend;if(n==="audio"&&o!=="main"&&!this.blockedAudioAppend&&!(_.ending||_.ended)){let k=R.start+R.duration*.05,H=S.buffered,q=this.currentOp("video");!H.length&&!q?this.blockAudio(R):!q&&!Ee.isBuffered(S,k)&&this.lastVideoAppendEnd<k&&this.blockAudio(R);}else if(n==="video"){let C=R.end;if(D){let k=D.frag.start;(C>k||C<this.lastVideoAppendEnd||Ee.isBuffered(S,k))&&this.unblockAudio();}this.lastVideoAppendEnd=C;}}let L=(l||a).start,O={label:`append-${n}`,execute:()=>{var R;u.executeStart=self.performance.now();let D=(R=this.tracks[n])==null?void 0:R.buffer;D&&(y?this.updateTimestampOffset(D,L,.1,n,h,f):c!==void 0&&Q(c)&&this.updateTimestampOffset(D,c,1e-6,n,h,f)),this.appendExecutor(r,n);},onStart:()=>{},onComplete:()=>{let R=self.performance.now();u.executeEnd=u.end=R,p.first===0&&(p.first=R),g&&g.first===0&&(g.first=R);let D={};this.sourceBuffers.forEach(([C,k])=>{C&&(D[C]=Ee.getBuffered(k));}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(v.BUFFER_APPENDED,{type:n,frag:a,part:l,chunkMeta:d,parent:a.type,timeRanges:D});},onError:R=>{var D;let C={type:ie.MEDIA_ERROR,parent:a.type,details:M.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:a,part:l,chunkMeta:d,error:R,err:R,fatal:false},k=(D=this.media)==null?void 0:D.error;if(R.code===DOMException.QUOTA_EXCEEDED_ERR||R.name=="QuotaExceededError"||"quota"in R)C.details=M.BUFFER_FULL_ERROR;else if(R.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!k)C.errorAction=ho(true);else if(R.name===DT&&this.sourceBufferCount===0)C.errorAction=ho(true);else {let H=++this.appendErrors[n];this.warn(`Failed ${H}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${k||"no media error"})`),(H>=this.hls.config.appendErrorMaxRetry||k)&&(C.fatal=true);}this.hls.trigger(v.ERROR,C);}};this.log(`queuing "${n}" append sn: ${h}${l?" p: "+l.index:""} of ${a.type===J.MAIN?"level":"track"} ${a.level} cc: ${f}`),this.append(O,n,this.isPending(this.tracks[n]));}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i);},onStart:()=>{},onComplete:()=>{this.hls.trigger(v.BUFFER_FLUSHED,{type:e});},onError:r=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,r);}}}onBufferFlushing(e,t){let{type:i,startOffset:r,endOffset:n}=t;i?this.append(this.getFlushOp(i,r,n),i):this.sourceBuffers.forEach(([o])=>{o&&this.append(this.getFlushOp(o,r,n),o);});}onFragParsed(e,t){let{frag:i,part:r}=t,n=[],o=r?r.elementaryStreams:i.elementaryStreams;o[Ve.AUDIOVIDEO]?n.push("audiovideo"):(o[Ve.AUDIO]&&n.push("audio"),o[Ve.VIDEO]&&n.push("video"));let a=()=>{let l=self.performance.now();i.stats.buffering.end=l,r&&(r.stats.buffering.end=l);let d=r?r.stats:i.stats;this.hls.trigger(v.FRAG_BUFFERED,{frag:i,part:r,stats:d,id:i.type});};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(a,n).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes);});}onFragChanged(e,t){this.trimBuffers();}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return !t.ended||t.ending}return false})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([o])=>{if(o){let a=this.tracks[o];(!t.type||t.type===o)&&(a.ending=true,a.ended||(a.ended=true,this.log(`${o} buffer reached EOS`)));}});let r=((i=this.overrides)==null?void 0:i.endOfStream)!==false;this.sourceBufferCount>0&&!this.sourceBuffers.some(([o])=>{var a;return o&&!((a=this.tracks[o])!=null&&a.ended)})?r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:o}=this;if(!o||o.readyState!=="open"){o&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${o.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),o.endOfStream(),this.hls.trigger(v.BUFFERED_TO_END,void 0);})):(this.tracksEnded(),this.hls.trigger(v.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio();}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=false);}});}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration());}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e);});}onError(e,t){if(t.details===M.BUFFER_APPEND_ERROR&&t.frag){var i;let r=(i=t.errorAction)==null?void 0:i.nextAutoLevel;Q(r)&&r!==t.frag.level&&this.resetAppendErrors();}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0};}trimBuffers(){let{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;let r=e.config,n=i.currentTime,o=t.levelTargetDuration,a=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(Q(a)&&a>=0){let d=Math.max(a,o),c=Math.floor(n/o)*o-d;this.flushBackBuffer(n,o,c);}let l=r.frontBufferFlushThreshold;if(Q(l)&&l>0){let d=Math.max(r.maxBufferLength,l),c=Math.max(d,o),u=Math.floor(n/o)*o+c;this.flushFrontBuffer(n,o,u);}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([r,n])=>{if(n){let a=Ee.getBuffered(n);if(a.length>0&&i>a.start(0)){var o;this.hls.trigger(v.BACK_BUFFER_REACHED,{bufferEnd:i});let l=this.tracks[r];if((o=this.details)!=null&&o.live)this.hls.trigger(v.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l!=null&&l.ended){this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:r});}}});}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([r,n])=>{if(n){let o=Ee.getBuffered(n),a=o.length;if(a<2)return;let l=o.start(a-1),d=o.end(a-1);if(i>l||e>=l&&e<=d)return;this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r});}});}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;let r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let d=Math.max(0,t.fragmentStart),c=Math.max(d,r);return {duration:1/0,start:d,end:c}}return {duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return Q(n)?{duration:n}:null;let o=this.media.duration,a=Q(i.duration)?i.duration:0;return r>a&&r>o||!Q(o)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:i}){let r=this.mediaSource;!this.media||!r||r.readyState!=="open"||(r.duration!==e&&(Q(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${i}.`),r.setLiveSeekableRange(t,i)));}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${We(i)}`),this.tracksReady){var r;let n=(r=this.transferData)==null?void 0:r.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers();}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let r=this.tracks[t];e[t]={buffer:i,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata};}}),this.hls.trigger(v.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t);});}else {let e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:true,error:e,reason:e.message});}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(let n in e){let o=n,a=e[o];if(this.isPending(a)){let l=this.getTrackCodec(a,o),d=`${a.container};codecs=${l}`;a.codec=l,this.log(`creating sourceBuffer(${d})${this.currentOp(o)?" Queued":""} ${We(a)}`);try{let c=i.addSourceBuffer(d),u=Tp(o),h=[o,c];t[u]=h,a.buffer=c;}catch(c){var r;this.error(`error while trying to add sourceBuffer: ${c.message}`),this.shiftAndExecuteNext(o),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[o],this.hls.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.BUFFER_ADD_CODEC_ERROR,fatal:false,error:c,sourceBufferName:o,mimeType:d,parent:a.id});return}this.trackSourceBuffer(o,a);}}this.bufferCreated();}getTrackCodec(e,t){let i=e.supplemental,r=e.codec;i&&(t==="video"||t==="audiovideo")&&fl(i,"video")&&(r=vk(r,i));let n=Fu(r,e.levelCodec);return n?t.slice(0,5)==="audio"?ju(n,this.appendSource):n:""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,o)=>{let a=o.removedRanges;a!=null&&a.length&&this.hls.trigger(v.BUFFER_FLUSHED,{type:n});});}get mediaSrc(){var e,t;let i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart();}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e));}onSBUpdateError(e,t){var i;let r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:false});let n=this.currentOp(e);n&&n.onError(r);}updateTimestampOffset(e,t,i,r,n,o){let a=t-e.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${o})`),e.timestampOffset=t);}removeExecutor(e,t,i){let{media:r,mediaSource:n}=this,o=this.tracks[e],a=o?.buffer;if(!r||!n||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let l=Q(r.duration)?r.duration:1/0,d=Q(n.duration)?n.duration:1/0,c=Math.max(0,t),u=Math.min(i,l,d);u>c&&(!o.ending||o.ended)?(o.ended=false,this.log(`Removing [${c},${u}] from the ${e} SourceBuffer`),a.remove(c,u)):this.shiftAndExecuteNext(e);}appendExecutor(e,t){let i=this.tracks[t],r=i?.buffer;if(!r)throw new gg(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=false,i.ended=false,r.appendBuffer(e);}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes);});else try{e();}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`);}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return !!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:i}=this,r=t.map(o=>this.appendBlocker(o));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(o=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes));})}stepOperationQueue(e){e.forEach(t=>{var i;let r=(i=this.tracks[t])==null?void 0:i.buffer;!r||r.updating||this.shiftAndExecuteNext(t);});}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i);}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e);}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e);}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let r=this.tracks[e];if(!r)return;let n=r.buffer;if(!n)return;let o=i.bind(this,e);r.listeners.push({event:t,listener:o}),n.addEventListener(t,o);}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(r=>{i.removeEventListener(r.event,r.listener);}),t.listeners.length=0);}};function g_(s){let e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t);});}function rC(s,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t);}function Tp(s){return s==="audio"?1:0}var Eg=class s{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners();}setStreamController(e){this.streamController=e;}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null;}registerListeners(){let{hls:e}=this;e.on(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.BUFFER_CODECS,this.onBufferCodecs,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this);}unregisterListener(){let{hls:e}=this;e.off(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.BUFFER_CODECS,this.onBufferCodecs,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this);}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width});}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize();}onManifestParsed(e,t){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping();}onLevelsUpdated(e,t){this.timer&&Q(this.autoLevelCapping)&&this.detectPlayerSize();}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping();}onMediaDetaching(){this.stopCapping(),this.media=null;}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping;}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return -1;let i=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,s.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize());}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0);}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0);}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio;}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return !this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return -1;let r=(a,l)=>l?a.width!==l.width||a.height!==l.height:true,n=e.length-1,o=Math.max(t,i);for(let a=0;a<e.length;a+=1){let l=e[a];if((l.width>=o||l.height>=o)&&r(l,e[a+1])){n=a;break}}return n}},nC={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Vt=nC,oC={HLS:"h"},aC=oC,ks=class s{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof s?i:new s(i))),this.value=e,this.params=t;}},lC="Dict";function dC(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function cC(s,e,t,i){return new Error(`failed to ${s} "${dC(e)}" as ${t}`,{cause:i})}function as(s,e,t){return cC("serialize",s,e,t)}var dh=class{constructor(e){this.description=e;}},v_="Bare Item",uC="Boolean";function hC(s){if(typeof s!="boolean")throw as(s,uC);return s?"?1":"?0"}function fC(s){return btoa(String.fromCharCode(...s))}var mC="Byte Sequence";function pC(s){if(ArrayBuffer.isView(s)===false)throw as(s,mC);return `:${fC(s)}:`}var gC="Integer";function vC(s){return s<-999999999999999||999999999999999<s}function MT(s){if(vC(s))throw as(s,gC);return s.toString()}function EC(s){return `@${MT(s.getTime()/1e3)}`}function PT(s,e){if(s<0)return -PT(-s,e);let t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){let r=Math.floor(s*t);return (r%2===0?r:r+1)/t}else return Math.round(s*t)/t}var yC="Decimal";function bC(s){let e=PT(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw as(s,yC);let t=e.toString();return t.includes(".")?t:`${t}.0`}var _C="String",TC=/[\x00-\x1f\x7f]+/;function SC(s){if(TC.test(s))throw as(s,_C);return `"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function AC(s){return s.description||s.toString().slice(7,-1)}var IC="Token";function E_(s){let e=AC(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===false)throw as(e,IC);return e}function yg(s){switch(typeof s){case "number":if(!Q(s))throw as(s,v_);return Number.isInteger(s)?MT(s):bC(s);case "string":return SC(s);case "symbol":return E_(s);case "boolean":return hC(s);case "object":if(s instanceof Date)return EC(s);if(s instanceof Uint8Array)return pC(s);if(s instanceof dh)return E_(s);default:throw as(s,v_)}}var xC="Key";function bg(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===false)throw as(s,xC);return s}function u0(s){return s==null?"":Object.entries(s).map(([e,t])=>t===true?`;${bg(e)}`:`;${bg(e)}=${yg(t)}`).join("")}function OT(s){return s instanceof ks?`${yg(s.value)}${u0(s.params)}`:yg(s)}function LC(s){return `(${s.value.map(OT).join(" ")})${u0(s.params)}`}function RC(s,e={whitespace:true}){if(typeof s!="object"||s==null)throw as(s,lC);let t=s instanceof Map?s.entries():Object.entries(s),i=e?.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof ks||(n=new ks(n));let o=bg(r);return n.value===true?o+=u0(n.params):(o+="=",Array.isArray(n.value)?o+=LC(n):o+=OT(n)),o}).join(`,${i}`)}function UT(s,e){return RC(s,e)}var ss="CMCD-Object",st="CMCD-Request",jr="CMCD-Session",er="CMCD-Status",kC={br:ss,ab:ss,d:ss,ot:ss,tb:ss,tpb:ss,lb:ss,tab:ss,lab:ss,url:ss,pb:st,bl:st,tbl:st,dl:st,ltc:st,mtp:st,nor:st,nrr:st,rc:st,sn:st,sta:st,su:st,ttfb:st,ttfbb:st,ttlb:st,cmsdd:st,cmsds:st,smrt:st,df:st,cs:st,ts:st,cid:jr,pr:jr,sf:jr,sid:jr,st:jr,v:jr,msd:jr,bs:er,bsd:er,cdn:er,rtp:er,bg:er,pt:er,ec:er,e:er},wC={REQUEST:st};function CC(s){return Object.keys(s).reduce((e,t)=>{var i;return (i=s[t])===null||i===void 0||i.forEach(r=>e[r]=t),e},{})}function DC(s,e){let t={};if(!s)return t;let i=Object.keys(s),r=e?CC(e):{};return i.reduce((n,o)=>{var a;let l=kC[o]||r[o]||wC.REQUEST,d=(a=n[l])!==null&&a!==void 0?a:n[l]={};return d[o]=s[o],n},t)}function MC(s){return ["ot","sf","st","e","sta"].includes(s)}function PC(s){return typeof s=="number"?Q(s):s!=null&&s!==""&&s!==false}var NT="event";function OC(s,e){let t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;let r=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+t.search+t.hash}var Gu=s=>Math.round(s),_g=(s,e)=>Array.isArray(s)?s.map(t=>_g(t,e)):s instanceof ks&&typeof s.value=="string"?new ks(_g(s.value,e),s.params):(e.baseUrl&&(s=OC(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),Cu=s=>Gu(s/100)*100,UC=(s,e)=>{let t=s;return e.version>=2&&(s instanceof ks&&typeof s.value=="string"?t=new ks([s]):typeof s=="string"&&(t=[s])),_g(t,e)},NC={br:Gu,d:Gu,bl:Cu,dl:Cu,mtp:Cu,nor:UC,rtp:Cu,tb:Gu},FT="request",$T="response",h0=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],FC=["e"],$C=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function yh(s){return $C.test(s)}function BC(s){return h0.includes(s)||FC.includes(s)||yh(s)}var BT=["d","dl","nor","ot","rtp","su"];function HC(s){return h0.includes(s)||BT.includes(s)||yh(s)}var GC=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function KC(s){return h0.includes(s)||BT.includes(s)||GC.includes(s)||yh(s)}var VC=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function WC(s){return VC.includes(s)||yh(s)}var qC={[$T]:KC,[NT]:BC,[FT]:HC};function HT(s,e={}){let t={};if(s==null||typeof s!="object")return t;let i=e.version||s.v||1,r=e.reportingMode||FT,n=i===1?WC:qC[r],o=Object.keys(s).filter(n),a=e.filter;typeof a=="function"&&(o=o.filter(a));let l=r===$T||r===NT;l&&!o.includes("ts")&&o.push("ts"),i>1&&!o.includes("v")&&o.push("v");let d=Be({},NC,e.formatters),c={version:i,reportingMode:r,baseUrl:e.baseUrl};return o.sort().forEach(u=>{let h=s[u],f=d[u];if(typeof f=="function"&&(h=f(h,c)),u==="v"){if(i===1)return;h=i;}u=="pr"&&h===1||(l&&u==="ts"&&!Q(h)&&(h=Date.now()),PC(h)&&(MC(u)&&typeof h=="string"&&(h=new dh(h)),t[u]=h));}),t}function jC(s,e={}){let t={};if(!s)return t;let i=HT(s,e),r=DC(i,e?.customHeaderMap);return Object.entries(r).reduce((n,[o,a])=>{let l=UT(a,{whitespace:false});return l&&(n[o]=l),n},t)}function YC(s,e,t){return Be(s,jC(e,t))}var zC="CMCD";function QC(s,e={}){return s?UT(HT(s,e),{whitespace:false}):""}function XC(s,e={}){if(!s)return "";let t=QC(s,e);return encodeURIComponent(t)}function ZC(s,e={}){if(!s)return "";let t=XC(s,e);return `${zC}=${t}`}var y_=/CMCD=[^&#]+/;function JC(s,e,t){let i=ZC(e,t);if(!i)return s;if(y_.test(s))return s.replace(y_,i);let r=s.includes("?")?"&":"?";return `${s}${r}${i}`}var Tg=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=false,this.includeKeys=void 0,this.initialized=false,this.starved=false,this.buffering=true,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=true),this.buffering=true;},this.onPlaying=()=>{this.initialized||(this.initialized=true),this.buffering=false;},this.applyPlaylistData=r=>{try{this.apply(r,{ot:Vt.MANIFEST,su:!this.initialized});}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n);}},this.applyFragmentData=r=>{try{let{frag:n,part:o}=r,a=this.hls.levels[n.level],l=this.getObjectType(n),d={d:(o||n).duration*1e3,ot:l};(l===Vt.VIDEO||l===Vt.AUDIO||l==Vt.MUXED)&&(d.br=a.bitrate/1e3,d.tb=this.getTopBandwidth(l)/1e3,d.bl=this.getBufferLength(l));let c=o?this.getNextPart(o):this.getNextFrag(n);c!=null&&c.url&&c.url!==n.url&&(d.nor=c.url),this.apply(r,d);}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n);}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===true,this.includeKeys=i.includeKeys,this.registerListeners());}registerListeners(){let e=this.hls;e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHED,this.onMediaDetached,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this);}unregisterListeners(){let e=this.hls;e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHED,this.onMediaDetached,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this);}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null;}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying);}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null);}onBufferCreated(e,t){var i,r;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer;}createData(){var e;return {v:1,sf:aC.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Be(t,this.createData());let i=t.ot===Vt.INIT||t.ot===Vt.VIDEO||t.ot===Vt.MUXED;this.starved&&i&&(t.bs=true,t.su=true,this.starved=false),t.su==null&&(t.su=this.buffering);let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((o,a)=>(r.includes(a)&&(o[a]=t[a]),o),{}));let n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),YC(e.headers,t,n)):e.url=JC(e.url,t,n);}getNextFrag(e){var t;let i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){let r=e.sn-i.startSN;return i.fragments[r+1]}}getNextPart(e){var t;let{index:i,fragment:r}=e,n=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(n){let{sn:o}=r;for(let a=n.length-1;a>=0;a--){let l=n[a];if(l.index===i&&l.fragment.sn===o)return n[a+1]}}}getObjectType(e){let{type:t}=e;if(t==="subtitle")return Vt.TIMED_TEXT;if(e.sn==="initSegment")return Vt.INIT;if(t==="audio")return Vt.AUDIO;if(t==="main")return this.hls.audioTracks.length?Vt.VIDEO:Vt.MUXED}getTopBandwidth(e){let t=0,i,r=this.hls;if(e===Vt.AUDIO)i=r.audioTracks;else {let n=r.maxAutoLevel,o=n>-1?n+1:r.levels.length;i=r.levels.slice(0,o);}return i.forEach(n=>{n.bitrate>t&&(t=n.bitrate);}),t>0?t:NaN}getBufferLength(e){let t=this.media,i=e===Vt.AUDIO?this.audioBuffer:this.videoBuffer;return !i||!t?NaN:Ee.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,o,a){t(n),this.loader.load(n,o,a);}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,o,a){t(n),this.loader.load(n,o,a);}}}},eD=3e5,Sg=class extends qt{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=false,this.enabled=true,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners();}registerListeners(){let e=this.hls;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.ERROR,this.onError,this);}unregisterListeners(){let e=this.hls;e&&(e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.ERROR,this.onError,this));}pathways(){return (this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e);}startLoad(){if(this.started=true,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri);}}stopLoad(){this.started=false,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout();}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1);}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null;}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==e));}onManifestLoading(){this.stopLoad(),this.enabled=true,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null;}onManifestLoaded(e,t){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad());}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks;}onError(e,t){let{errorAction:i}=t;if(i?.action===St.SendAlternateToPenaltyBox&&i.flags===ti.MoveAllAlternatesMatchingHost){let r=this.levels,n=this._pathwayPriority,o=this.pathwayId;if(t.context){let{groupId:a,pathwayId:l,type:d}=t.context;a&&r?o=this.getPathwayForGroupId(a,d,o):l&&(o=l);}o in this.penalizedPathways||(this.penalizedPathways[o]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==o),t.details===M.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=true:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${o} levels: ${r&&r.length} priorities: ${We(n)} penalized: ${We(this.penalizedPathways)}`);}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i;}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>eD&&delete i[n];});for(let n=0;n<e.length;n++){let o=e[n];if(o in i)continue;if(o===this.pathwayId)return;let a=this.hls.nextLoadLevel,l=this.hls.levels[a];if(t=this.getLevelsForPathway(o),t.length>0){this.log(`Setting Pathway to "${o}"`),this.pathwayId=o,uT(t),this.hls.trigger(v.LEVELS_UPDATED,{levels:t});let d=this.hls.levels[a];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===Te.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===Te.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(n=>{let{ID:o,"BASE-ID":a,"URI-REPLACEMENT":l}=n;if(t.some(c=>c.pathwayId===o))return;let d=this.getLevelsForPathway(a).map(c=>{let u=new Je(c.attrs);u["PATHWAY-ID"]=o;let h=u.AUDIO&&`${u.AUDIO}_clone_${o}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${o}`;h&&(i[u.AUDIO]=h,u.AUDIO=h),f&&(r[u.SUBTITLES]=f,u.SUBTITLES=f);let m=GT(c.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new Jr({attrs:u,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:m,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let g=1;g<c.audioGroups.length;g++)p.addGroupId("audio",`${c.audioGroups[g]}_clone_${o}`);if(c.subtitleGroups)for(let g=1;g<c.subtitleGroups.length;g++)p.addGroupId("text",`${c.subtitleGroups[g]}_clone_${o}`);return p});t.push(...d),b_(this.audioTracks,i,l,o),b_(this.subtitleTracks,r,l,o);});}loadSteeringManifest(e){let t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let r;try{r=new self.URL(e);}catch{this.enabled=false,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){let c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+c);}let n={responseType:"json",url:r.href},o=t.steeringManifestLoadPolicy.default,a=o.errorRetry||o.timeoutRetry||{},l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},d={onSuccess:(c,u,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);let m=c.data;if(m?.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;let{"RELOAD-URI":p,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":E}=m;if(p)try{this.uri=new self.URL(p,r).href;}catch{this.enabled=false,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||h.url),g&&this.clonePathways(g);let y={steeringManifest:m,url:r.toString()};this.hls.trigger(v.STEERING_MANIFEST_LOADED,y),E&&this.updatePathwayPriority(E);},onError:(c,u,h,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${u.url})`),this.stopLoad(),c.code===410){this.enabled=false,this.log(`Steering manifest ${u.url} no longer available`);return}let m=this.timeToLoad*1e3;if(c.code===429){let p=this.loader;if(typeof p?.getResponseHeader=="function"){let g=p.getResponseHeader("Retry-After");g&&(m=parseFloat(g)*1e3);}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,m);},onTimeout:(c,u,h)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url);}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,d);}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let r=(i=this.hls)==null?void 0:i.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3);},t);}};function b_(s,e,t,i){s&&Object.keys(e).forEach(r=>{let n=s.filter(o=>o.groupId===r).map(o=>{let a=Be({},o);return a.details=void 0,a.attrs=new Je(a.attrs),a.url=a.attrs.URI=GT(o.url,o.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),a.groupId=a.attrs["GROUP-ID"]=e[r],a.attrs["PATHWAY-ID"]=i,a});s.push(...n);});}function GT(s,e,t,i){let{HOST:r,PARAMS:n,[t]:o}=i,a;e&&(a=o?.[e],a&&(s=a));let l=new self.URL(s);return r&&!a&&(l.host=r),n&&Object.keys(n).sort().forEach(d=>{d&&l.searchParams.set(d,n[d]);}),l.href}var ch=class s extends qt{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=s.CDMCleanupPromise?[s.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{let{initDataType:i,initData:r}=t,n=`"${t.type}" event: init data type: "${i}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=al(this.config));let a=o.map(mp).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(a);}this.keyFormatPromise.then(o=>{let a=Bu(o);if(i!=="sinf"||a!==et.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${a}`);return}let l;try{let f=gt(new Uint8Array(r)),m=r0(JSON.parse(f).sinf),p=G_(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24));}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}let d=It(l),{keyIdToKeySessionPromise:c,mediaKeySessions:u}=this,h=c[d];for(let f=0;f<u.length;f++){let m=u[f],p=m.decryptdata;if(!p.keyId)continue;let g=It(p.keyId);if(th(l,p.keyId)||p.uri.replace(/-/g,"").indexOf(d)!==-1){if(h=c[g],!h)continue;if(p.pssh)break;delete c[g],p.pssh=new Uint8Array(r),p.keyId=l,h=c[d]=h.then(()=>this.generateRequestWithPreferredKeySession(m,i,r,"encrypted-event-key-match")),h.catch(E=>this.handleError(E));break}}h||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${u.length}.`));}).catch(o=>this.handleError(o));}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`);},this.hls=e,this.config=e.config,this.registerListeners();}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null;}registerListeners(){this.hls.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(v.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(v.DESTROYING,this.onDestroying,this);}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(v.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(v.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(v.DESTROYING,this.onDestroying,this);}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t?.[e];if(r)return r.licenseUrl;if(e===et.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t?.[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`);}attemptKeySystemAccess(e){let t=this.hls.levels,i=(o,a,l)=>!!o&&l.indexOf(o)===a,r=t.map(o=>o.audioCodec).filter(i),n=t.map(o=>o.videoCodec).filter(i);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((o,a)=>{let l=d=>{let c=d.shift();this.getMediaKeysPromise(c,r,n).then(u=>o({keySystem:c,mediaKeys:u})).catch(u=>{d.length?l(d):u instanceof Ft?a(u):a(new Ft({type:ie.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_ACCESS,error:u,fatal:true},u.message));});};l(e);})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return sT===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return i(e,t)}getMediaKeysPromise(e,t,i){var r;let n=Zk(e,t,i,this.config.drmSystemOptions||{}),o=this.keySystemAccessPromises[e],a=(r=o)==null?void 0:r.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${We(n)}`),a=this.requestMediaKeySystemAccess(e,n);let l=o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`);}),a.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);let c=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let u=l.mediaKeys=d.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=true,c.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return u.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`);}),u})}return a.then(()=>o.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${It(e.keyId||[])} keyUri: ${e.uri}`);let r=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),r=Du(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,n,t.pssh.buffer,"expired");}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e);}updateKeySession(e,t){let i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${It(e.decryptdata.keyId||[])}
1952
+ } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>mp(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:r})=>{let n=mp(r);n?t(n):i(new Error(`Unable to find format for key-system "${r}"`));}).catch(i);})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=al(this.config),i=e.map(Bu).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(i)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){let r=tD(e,t[i]);if(r)return r}}loadKey(e){let t=e.keyInfo.decryptdata,i=Du(t),r=this.bannedKeyIds[i];if(r||this.getKeyStatus(t)==="internal-error"){let a=__(r||"internal-error",t);return this.handleError(a,e.frag),Promise.reject(a)}let n=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let o=this.keyIdToKeySessionPromise[i];if(!o){let a=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:d})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:d,decryptdata:t}))))).then(l=>{let d="cenc",c=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,d,c,"playlist-key")});return a.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[i]=a,a}return o.catch(a=>{if(a instanceof Ft){let l=Oe({},a.data);this.getKeyStatus(t)==="internal-error"&&(l.decryptdata=t);let d=new Ft(l,a.message);this.handleError(d,e.frag);}}),o}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Ft){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${It(i.keyId||[])})`:""}`),this.hls.trigger(v.ERROR,e.data);}else this.error(e.message),this.hls.trigger(v.ERROR,{type:ie.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_KEYS,error:e,fatal:true});}getKeySystemForKeyPromise(e){let t=Du(e),i=this.keyIdToKeySessionPromise[t];if(!i){let r=Bu(e.keyFormat),n=r?[r]:al(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=al(this.config)),e.length===0)throw new Ft({type:ie.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:true},`Missing key-system license configuration options ${We({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,o)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return o(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(o);};}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1);})}generateRequestWithPreferredKeySession(e,t,i,r){var n;let o=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(o)try{let m=o.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=m.initData?m.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null;}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let a=Du(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${a} URI: ${l} (init data type: ${t} length: ${i.byteLength})`);let d=new n0,c=e._onmessage=m=>{let p=e.mediaKeysSession;if(!p){d.emit("error",new Error("invalid state"));return}let{messageType:g,message:E}=m;this.log(`"${g}" message event for session "${p.sessionId}" message size: ${E.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,E).catch(y=>{d.eventNames().length?d.emit("error",y):this.handleError(y);}):g==="license-release"?e.keySystem===et.FAIRPLAY&&this.updateKeySession(e,zp("acknowledged")).then(()=>this.removeSession(e)).catch(y=>this.handleError(y)):this.warn(`unhandled media key message type "${g}"`);},u=(m,p)=>{p.keyStatus=m;let g;m.startsWith("usable")?d.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?g=__(m,p.decryptdata):m==="expired"?g=new Error(`key expired (keyId: ${a})`):m==="released"?g=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${a})`),g&&(d.eventNames().length?d.emit("error",g):this.handleError(g));},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}let g=this.getKeyStatuses(e);if(!Object.keys(g).some(S=>g[S]!=="status-pending"))return;if(g[a]==="expired"){this.log(`Expired key ${We(g)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let y=g[a];if(y)u(y,e);else {var _;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(_=e.keyStatusTimeouts)[a]||(_[a]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let L=this.getKeyStatus(e.decryptdata);if(L&&L!=="status-pending")return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${L} from other session.`),u(L,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),y="internal-error",u(y,e);},1e3)),this.log(`No status for keyId ${a} (${We(g)}).`);}};$t(e.mediaKeysSession,"message",c),$t(e.mediaKeysSession,"keystatuseschange",h);let f=new Promise((m,p)=>{d.on("error",p),d.on("resolved",m);});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${l}`);}).catch(m=>{throw new Ft({type:ie.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:e.decryptdata,fatal:false},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw m}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((i,r)=>{if(typeof r=="string"&&typeof i=="object"){let a=r;r=i,i=a;}let n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===et.PLAYREADY&&n.length===16){let a=It(n);t[a]=i,tT(n);}let o=It(n);i==="internal-error"&&(this.bannedKeyIds[o]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${o} key-session "${e.mediaKeysSession.sessionId}"`),t[o]=i;}),t}fetchServerCertificate(e){let t=this.config,i=t.loader,r=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((o,a)=>{let l={responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,m,p)=>{o(h.data);},onError:(h,f,m,p)=>{a(new Ft({type:ie.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:m,response:Oe({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`));},onTimeout:(h,f,m)=>{a(new Ft({type:ie.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`));},onAbort:(h,f,m)=>{a(new Error("aborted"));}};r.load(l,c,u);})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,n)=>{e.setServerCertificate(i).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),r(e);}).catch(o=>{n(new Ft({type:ie.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:true},o.message));});})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new Ft({type:ie.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:r,fatal:false},r.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let u=0,h=n.length;u<h;u++){var o,a;c=n[u];let f=(o=c.querySelector("name"))==null?void 0:o.textContent,m=(a=c.querySelector("value"))==null?void 0:a.textContent;f&&m&&e.setRequestHeader(f,m);}}let l=r.querySelector("Challenge"),d=l?.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return zp(atob(d))}setupLicenseXHR(e,t,i,r){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,r)}).catch(o=>{if(!i.decryptdata)throw o;return e.open("POST",t,true),n.call(this.hls,e,t,i,r)}).then(o=>(e.readyState||e.open("POST",t,true),{xhr:e,licenseChallenge:o||r})):(e.open("POST",t,true),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{let o=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${o}`);let a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(a.readyState===4)if(a.status===200){this._requestLicenseFailureCount=0;let l=a.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);let d=this.config.licenseResponseCallback;if(d)try{l=d.call(this.hls,a,o,e);}catch(c){this.error(c);}r(l);}else {let l=i.errorRetry,d=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||a.status>=400&&a.status<500)n(new Ft({type:ie.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:true,networkDetails:a,response:{url:o,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${o}). Status: ${a.status} (${a.statusText})`));else {let c=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} attempts left`),this.requestLicense(e,t).then(r,n);}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,o,e,t).then(({xhr:l,licenseChallenge:d})=>{e.keySystem==et.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(l,d)),l.send(d);}).catch(n);})}onDestroying(){this.unregisterListeners(),this._clear();}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,$t(i,"encrypted",this.onMediaEncrypted),$t(i,"waitingforkey",this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=i.mediaKeys;}onMediaDetached(){let e=this.media;e&&(Wt(e,"encrypted",this.onMediaEncrypted),Wt(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null);}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let i=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,vo.clearKeyUriToKeyIdMap();let n=r.length;s.CDMCleanupPromise=Promise.all(r.map(o=>this.removeSession(o)).concat((i==null||(e=i.setMediaKeys(null))==null?void 0:e.catch(o=>{this.log(`Could not clear media keys: ${o}`),this.hls&&this.hls.trigger(v.ERROR,{type:ie.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:false,error:new Error(`Could not clear media keys: ${o}`)});}))||Promise.resolve())).catch(o=>{this.log(`Could not close sessions and clear media keys: ${o}`),this.hls&&this.hls.trigger(v.ERROR,{type:ie.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:false,error:new Error(`Could not close sessions and clear media keys: ${o}`)});}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys");});}onManifestLoading(){this._clear();}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let i=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i);}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${It(r?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);let{keyStatusTimeouts:o}=e;o&&Object.keys(o).forEach(d=>self.clearTimeout(o[d]));let{drmSystemOptions:a}=this.config;return (ew(a)?new Promise((d,c)=>{self.setTimeout(()=>c(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(d).catch(c);}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(v.ERROR,{type:ie.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:false,error:new Error(`Could not remove session: ${d}`)});}).then(()=>t.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(v.ERROR,{type:ie.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:false,error:new Error(`Could not close session: ${d}`)});})}return Promise.resolve()}};ch.CDMCleanupPromise=void 0;function Du(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return It(s.keyId)}function tD(s,e){if(s.keyId&&e.mediaKeysSession.keyStatuses.has(s.keyId))return e.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(e.decryptdata))return e.keyStatus}var Ft=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error;}};function __(s,e){let t=s==="output-restricted",i=t?M.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:M.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ft({type:ie.KEY_SYSTEM_ERROR,details:i,fatal:false,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}var Ag=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=false,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners();}setStreamController(e){this.streamController=e;}registerListeners(){this.hls.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(v.MEDIA_DETACHING,this.onMediaDetaching,this);}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(v.MEDIA_DETACHING,this.onMediaDetaching,this);}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=false,this.media=null;}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=true),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod);}}onMediaDetaching(){this.media=null;}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let n=r-this.lastTime,o=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,l=1e3*o/n,d=this.hls;if(d.trigger(v.FPS_DROP,{currentDropped:o,currentDecoded:a,totalDroppedFrames:i}),l>0&&o>d.config.fpsDroppedMonitoringThreshold*a){let c=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=c)&&(c=c-1,d.trigger(v.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:d.currentLevel}),d.autoLevelCapping=c,this.streamController.nextLevelSwitch());}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t;}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames);}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount);}};function KT(s,e){let t;try{t=new Event("addtrack");}catch{t=document.createEvent("Event"),t.initEvent("addtrack",false,false);}t.track=s,e.dispatchEvent(t);}function VT(s,e){let t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){Ue.debug(`[texttrack-utils]: ${i}`);try{let r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,s.addCue(r);}catch(r){Ue.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`);}}t==="disabled"&&(s.mode=t);}function co(s,e){let t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues)for(let i=s.cues.length;i--;)e&&s.cues[i].removeEventListener("enter",e),s.removeCue(s.cues[i]);t==="disabled"&&(s.mode=t);}function Ig(s,e,t,i){let r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){let n=sD(s.cues,e,t);for(let o=0;o<n.length;o++)(!i||i(n[o]))&&s.removeCue(n[o]);}r==="disabled"&&(s.mode=r);}function iD(s,e){if(e<=s[0].startTime)return 0;let t=s.length-1;if(e>s[t].endTime)return -1;let i=0,r=t,n;for(;i<=r;)if(n=Math.floor((r+i)/2),e<s[n].startTime)r=n-1;else if(e>s[n].startTime&&i<t)i=n+1;else return n;return s[i].startTime-e<e-s[r].startTime?i:r}function sD(s,e,t){let i=[],r=iD(s,e);if(r>-1)for(let n=r,o=s.length;n<o;n++){let a=s[n];if(a.startTime>=e&&a.endTime<=t)i.push(a);else if(a.startTime>t)return i}return i}function Ku(s){let e=[];for(let t=0;t<s.length;t++){let i=s[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(s[t]);}return e}var xg=class extends Tl{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true,this.queuedDefaultTrack=-1,this.useTextTrackPolling=false,this.subtitlePollingInterval=-1,this._subtitleDisplay=true,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null,i=Ku(this.media.textTracks);for(let n=0;n<i.length;n++)if(i[n].mode==="hidden")t=i[n];else if(i[n].mode==="showing"){t=i[n];break}let r=this.findTrackForTextTrack(t);this.subtitleTrack!==r&&this.setSubtitleTrack(r);},this.registerListeners();}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy();}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes();}registerListeners(){let{hls:e}=this;e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(v.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVEL_LOADING,this.onLevelLoading,this),e.off(v.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(v.ERROR,this.onError,this);}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange));}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e);}onMediaDetaching(e,t){let i=this.media;if(!i)return;let r=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r)return;Ku(i.textTracks).forEach(o=>{co(o);});}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true;}onManifestParsed(e,t){this.tracks=t.subtitleTracks;}onSubtitleTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,o=this.tracksInGroup[i];if(!o||o.groupId!==r){this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${o?.groupId}`);return}let a=o.details;o.details=t.details,this.log(`Subtitle track ${i} "${o.name}" lang:${o.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a);}onLevelLoading(e,t){this.switchLevel(t.level);}onLevelSwitching(e,t){this.switchLevel(t.level);}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||r?.length!==i?.length||i!=null&&i.some(o=>r?.indexOf(o)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(c=>!i||i.indexOf(c.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(c=>c.default)&&(this.selectDefaultTrack=false),o.forEach((c,u)=>{c.id=u;});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let a=this.hls.config.subtitlePreference;if(!n&&a){this.selectDefaultTrack=false;let c=os(a,o);if(c>-1)n=o[c];else {let u=os(a,this.tracks);n=this.tracks[u];}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let d={subtitleTracks:o};this.log(`Updating subtitle tracks, ${o.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(v.SUBTITLE_TRACKS_UPDATED,d),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l);}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let n=t[r];if(!(i&&!n.default||!i&&!e)&&(!e||Xr(n,e)))return r}if(e){for(let r=0;r<t.length;r++){let n=t[r];if(Sl(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){let n=t[r];if(Sl(e.attrs,n.attrs,["LANGUAGE"]))return r}}return -1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if(fg(r,e))return i}}return -1}onError(e,t){t.fatal||!t.context||t.context.type===Te.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t);}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=false,this.setSubtitleTrack(e);}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=false,t.length){let i=this.currentTrack;if(i&&Xr(e,i))return i;let r=os(e,this.tracksInGroup);if(r>-1){let n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}else {if(i)return null;{let n=os(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e);}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),o=e.details,a=o?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${n}`),this.hls.trigger(v.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null,track:e});}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=Ku(e.textTracks),i=this.currentTrack,r;if(i&&(r=t.filter(n=>fg(i,n))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==r&&(n.mode="disabled");}),r){let n=this.subtitleDisplay?"showing":"hidden";r.mode!==n&&(r.mode=n);}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!Q(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=false;let i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(v.SUBTITLE_TRACK_SWITCH,{id:e});return}let n=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));let{id:o,groupId:a="",name:l,type:d,url:c}=r;this.hls.trigger(v.SUBTITLE_TRACK_SWITCH,{id:o,groupId:a,name:l,type:d,url:c});let u=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(u);}};function rD(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}function cl(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return (e>>>0).toString()}var po=.025,uh=(function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s})({});function nD(s,e,t){return `${s.identifier}-${t+1}-${cl(e)}`}var Lg=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=false,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:false,jump:false},this.snapOptions={out:false,in:false},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e);}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions);}reset(){var e;this.appendInPlaceStarted=false,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null);}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return true;let i=this.playoutLimit;return e<=0||isNaN(i)?false:i===0?true:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return Sp(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return true;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,i=Sp(t,e);return t-i<.1}return false}get resumptionOffset(){let e=this.resumeOffset,t=Q(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return Sp(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?true:this.appendInPlaceDisabled?false:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<po))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e;}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e;}get duration(){let e=this.playoutLimit,t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e;}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?uh.Range:uh.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return oD(this)}};function Sp(s,e){return s-e.start<e.duration/2&&!(Math.abs(s-(e.start+e.duration))<po)?e.start:e.start+e.duration}function WT(s,e,t){let i=new self.URL(s,t);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",e),i}function Ap(s,e){for(;(t=s.assetList[++e])!=null&&t.error;)var t;return e}function oD(s){return `["${s.identifier}" ${s.cue.pre?"<pre>":s.cue.post?"<post>":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function lo(s){let e=s.timelineStart,t=s.duration||0;return `["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var Rg=class{constructor(e,t,i,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=false,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(v.PLAYOUT_LIMIT_REACHED,{});};let n=this.hls=new e(t);this.interstitial=i,this.assetItem=r;let o=()=>{this.hasDetails=true;};n.once(v.LEVEL_LOADED,o),n.once(v.AUDIO_TRACK_LOADED,o),n.once(v.SUBTITLE_TRACK_LOADED,o),n.on(v.MEDIA_ATTACHING,(a,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(v.BUFFER_APPENDED,()=>{let c=this.bufferedEnd;this.reachedPlayout(c)&&(this._bufferedEosTime=c,n.trigger(v.BUFFERED_TO_END,void 0));}));});}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,true);else {let t=this.assetItem.uri;try{t=WT(t,e.config.primarySessionId||"").href;}catch{}e.loadSource(t);}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return false;if((t=this.hls)!=null&&t.bufferedToEnd)return true;if(!e)return false;let i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,n=Ee.bufferInfo(e,r,0);return this.getAssetTime(n.end)>=i-.02}reachedPlayout(e){let i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return !((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return ((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=Ee.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return ((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e;}}}getAssetTime(e){let t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout));}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd);}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null;}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e);}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia();}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering();}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering();}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=false;}}on(e,t,i){var r;(r=this.hls)==null||r.on(e,t);}once(e,t,i){var r;(r=this.hls)==null||r.once(e,t);}off(e,t,i){var r;(r=this.hls)==null||r.off(e,t);}toString(){var e;return `HlsAssetPlayer: ${lo(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},T_=.033,kg=class extends qt{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e;}destroy(){this.reset(),this.onScheduleUpdate=null;}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null;}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(n=r[i])!=null&&n.event;){var n;i--;}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let r=0;r<i.length;r++){let n=i[r];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return -1}findJumpRestrictedIndex(e,t){let i=this.items;if(i)for(let r=e;r<=t&&i[r];r++){let n=i[r].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return r}return -1}findEventIndex(e){let t=this.items;if(t)for(let r=t.length;r--;){var i;if(((i=t[r].event)==null?void 0:i.identifier)===e)return r}return -1}findAssetIndex(e,t){let i=e.assetList,r=i.length;if(r>1)for(let n=0;n<r;n++){let o=i[n];if(!o.error){let a=o.timelineStart;if(t===a||t>a&&(t<a+(o.duration||0)||n===r-1))return n}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let i=t.assetList,r=i[i.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){let i=e.main.details,{dateRanges:r}=i,n=this.events,o=this.parseDateRanges(r,{url:i.url},t),a=Object.keys(r),l=n?n.filter(d=>!a.includes(d.identifier)):[];o.length&&o.sort((d,c)=>{let u=d.cue.pre,h=d.cue.post,f=c.cue.pre,m=c.cue.post;if(u&&!f)return -1;if(f&&!u||h&&!m)return 1;if(m&&!h)return -1;if(!u&&!f&&!h&&!m){let p=d.startTime,g=c.startTime;if(p!==g)return p-g}return d.dateRange.tagOrder-c.dateRange.tagOrder}),this.events=o,l.forEach(d=>{this.removeEvent(d);}),this.updateSchedule(e,l);}updateSchedule(e,t=[],i=false){let r=this.events||[];if(r.length||t.length||this.length<2){let n=this.items,o=this.parseSchedule(r,e);(i||t.length||n?.length!==o.length||o.some((l,d)=>Math.abs(l.playout.start-n[d].playout.start)>.005||Math.abs(l.playout.end-n[d].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,n));}}parseDateRanges(e,t,i){let r=[],n=Object.keys(e);for(let o=0;o<n.length;o++){let a=n[o],l=e[a];if(l.isInterstitial){let d=this.eventMap[a];d?d.setDateRange(l):(d=new Lg(l,t),this.eventMap[a]=d,i===false&&(d.appendInPlace=i)),r.push(d);}}return r}parseSchedule(e,t){let i=[],r=t.main.details,n=r.live?1/0:r.edge,o=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,d=0;if(e.forEach((c,u)=>{let h=c.cue.pre,f=c.cue.post,m=e[u-1]||null,p=c.appendInPlace,g=f?n:c.startOffset,E=c.duration,y=c.timelineOccupancy===uh.Range?E:0,_=c.resumptionOffset,S=m?.startTime===g,L=g+c.cumulativeDuration,O=p?L+E:g+_;if(h||!f&&g<=0){let D=d;d+=y,c.timelineStart=L;let C=o;o+=E,i.push({event:c,start:L,end:O,playout:{start:C,end:o},integrated:{start:D,end:d}});}else if(g<=n){if(!S){let k=g-l;if(k>T_){let H=l,q=d;d+=k;let j=o;o+=k;let X={previousEvent:e[u-1]||null,nextEvent:c,start:H,end:H+k,playout:{start:j,end:o},integrated:{start:q,end:d}};i.push(X);}else k>0&&m&&(m.cumulativeDuration+=k,i[i.length-1].end=g);}f&&(O=L),c.timelineStart=L;let D=d;d+=y;let C=o;o+=E,i.push({event:c,start:L,end:O,playout:{start:C,end:o},integrated:{start:D,end:d}});}else return;let R=c.resumeTime;f||R>n?l=n:l=R;}),l<n){var a;let c=l,u=d,h=n-l;d+=h;let f=o;o+=h,i.push({previousEvent:((a=i[i.length-1])==null?void 0:a.event)||null,nextEvent:null,start:l,end:c+h,playout:{start:f,end:o},integrated:{start:u,end:d}});}this.setDurations(n,o,d);}else i.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i};}resolveOffsets(e,t){let i=t.main.details,r=i.live?1/0:i.edge,n=0,o=-1;e.forEach((a,l)=>{let d=a.cue.pre,c=a.cue.post,u=d?0:c?r:a.startTime;this.updateAssetDurations(a),o===u?a.cumulativeDuration=n:(n=0,o=u),!c&&a.snapOptions.in&&(a.resumeAnchor=en(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=false)),!a.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<T_&&(e[l+1].appendInPlace=false,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));let f=Q(a.resumeOffset)?a.resumeOffset:a.duration;n+=f;});}primaryCanResumeInPlaceAt(e,t){let i=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(i-r)>po?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${r}`),false):!Object.keys(t).some(o=>{let a=t[o].details,l=a.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${o} playlist end ${l}`),false;let d=en(null,a.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${o} playlist (${a.fragStart}-${a.fragmentEnd})`),true;let c=o==="audio"?.175:0;return Math.abs(d.start-i)<po+c||Math.abs(d.end-i)<po+c?false:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${o} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),true)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,i=0,r=false,n=false;for(let o=0;o<e.assetList.length;o++){let a=e.assetList[o],l=t+i;a.startOffset=i,a.timelineStart=l,r||(r=a.duration===null),n||(n=!!a.error);let d=a.error?0:a.duration||0;i+=d;}r&&!n?e.duration=Math.max(i,e.duration):e.duration=i;}removeEvent(e){e.reset(),delete this.eventMap[e.identifier];}};function Ai(s){return `[${s.event?'"'+s.event.identifier+'"':"primary"}: ${s.start.toFixed(2)}-${s.end.toFixed(2)}]`}var wg=class{constructor(e){this.hls=void 0,this.hls=e;}destroy(){this.hls=null;}loadAssetList(e,t){let i=e.assetListUrl,r;try{r=WT(i,this.hls.sessionId,e.baseUrl);}catch(h){let f=this.assignAssetListError(e,M.ASSET_LIST_LOAD_ERROR,h,i);this.hls.trigger(v.ERROR,f);return}t&&r.protocol!=="data:"&&r.searchParams.set("_HLS_start_offset",""+t);let n=this.hls.config,o=n.loader,a=new o(n),l={responseType:"json",url:r.href},d=n.interstitialAssetListLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,m,p)=>{let g=h.data,E=g?.ASSETS;if(!Array.isArray(E)){let y=this.assignAssetListError(e,M.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,p);this.hls.trigger(v.ERROR,y);return}e.assetListResponse=g,this.hls.trigger(v.ASSET_LIST_LOADED,{event:e,assetListResponse:g,networkDetails:p});},onError:(h,f,m,p)=>{let g=this.assignAssetListError(e,M.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,p,m);this.hls.trigger(v.ERROR,g);},onTimeout:(h,f,m)=>{let p=this.assignAssetListError(e,M.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,m);this.hls.trigger(v.ERROR,p);}};return a.load(l,c,u),this.hls.trigger(v.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,i,r,n,o){return e.error=i,{type:ie.NETWORK_ERROR,details:t,fatal:false,interstitial:e,url:r,error:i,networkDetails:o,stats:n}}};function S_(s){var e;s==null||(e=s.play())==null||e.catch(()=>{});}function Mu(s,e){return `[${s}] Advancing timeline position to ${e}`}var Cg=class extends qt{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=false,this.onPlay=()=>{this.shouldPlay=true;},this.onPause=()=>{this.shouldPlay=false;},this.onSeeking=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;let r=i-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let o=r<=-0.01;this.timelinePos=i,this.bufferedPos=i;let a=this.playingItem;if(!a){this.checkBuffer();return}if(o&&this.schedule.resetErrorsInRange(i,i-r)&&this.updateSchedule(true),this.checkBuffer(),o&&i<a.start||i>=a.end){var l;let f=this.findItemIndex(a),m=this.schedule.findItemIndexAtTime(i);if(m===-1&&(m=f+(o?-1:1),this.log(`seeked ${o?"back ":""}to position not covered by schedule ${i} (resolving from ${f} to ${m})`)),!this.isInterstitial(a)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=false),!o&&m>f){let p=this.schedule.findJumpRestrictedIndex(f+1,m);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(m);return}let d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(a)){let f=a.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,f));}return}let c=d.timelineStart,u=d.duration||0;if(o&&i<c||i>=c+u){var h;(h=a.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(a.event,a),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,d);}},this.onTimeupdate=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;let r=this.playingItem;if(!r||this.playingLastItem)return;if(i>=r.end){this.timelinePos=r.end;let a=this.findItemIndex(r);this.setSchedulePosition(a+1);}let n=this.playingAsset;if(!n)return;let o=n.timelineStart+(n.duration||0);i>=o&&this.setScheduleToAssetAtTime(i,n);},this.onScheduleUpdate=(i,r)=>{let n=this.schedule;if(!n)return;let o=this.playingItem,a=n.events||[],l=n.items||[],d=n.durations,c=i.map(p=>p.identifier),u=!!(a.length||c.length);(u||r)&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a}
1953
+ Schedule: ${l.map(p=>Ai(p))} pos: ${this.timelinePos}`),c.length&&this.log(`Removed events ${c}`);let h=null,f=null;o&&(h=this.updateItem(o,this.timelinePos),this.itemsMatch(o,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let m=this.bufferingItem;if(m&&(f=this.updateItem(m,this.bufferedPos),this.itemsMatch(m,f)?this.bufferingItem=f:m.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(m.event,null))),i.forEach(p=>{p.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null);});}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){let g=p.assetItem.timelineStart,E=p.timelineOffset-g;if(E)try{p.timelineOffset=g;}catch(y){Math.abs(E)>po&&this.warn(`${y} ("${p.assetId}" ${p.timelineOffset}->${g})`);}}}),u||r){if(this.hls.trigger(v.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:l.slice(0),durations:d,removedIds:c}),this.isInterstitial(o)&&c.includes(o.event.identifier)){this.warn(`Interstitial "${o.event.identifier}" removed while playing`),this.primaryFallback(o.event);return}o&&this.trimInPlace(h,o),m&&f!==h&&this.trimInPlace(f,m),this.checkBuffer();}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new wg(e),this.schedule=new kg(this.onScheduleUpdate,e.logger),this.registerListeners();}registerListeners(){let e=this.hls;e&&(e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(v.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(v.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(v.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(v.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(v.BUFFER_APPENDED,this.onBufferAppended,this),e.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(v.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(v.MEDIA_ENDED,this.onMediaEnded,this),e.on(v.ERROR,this.onError,this),e.on(v.DESTROYING,this.onDestroying,this));}unregisterListeners(){let e=this.hls;e&&(e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(v.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(v.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(v.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(v.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(v.BUFFER_CODECS,this.onBufferCodecs,this),e.off(v.BUFFER_APPENDED,this.onBufferAppended,this),e.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(v.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(v.MEDIA_ENDED,this.onMediaEnded,this),e.off(v.ERROR,this.onError,this),e.off(v.DESTROYING,this.onDestroying,this));}startLoad(){this.resumeBuffering();}stopLoad(){this.pauseBuffering();}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering();}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering();}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null;}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e);}removeMediaListeners(e){Wt(e,"play",this.onPlay),Wt(e,"pause",this.onPause),Wt(e,"seeking",this.onSeeking),Wt(e,"timeupdate",this.onTimeupdate);}onMediaAttaching(e,t){let i=this.media=t.media;$t(i,"seeking",this.onSeeking),$t(i,"timeupdate",this.onTimeupdate),$t(i,"play",this.onPlay),$t(i,"pause",this.onPause);}onMediaAttached(e,t){let i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!r){this.clearScheduleState();let n=this.findItemIndex(i);this.setSchedulePosition(n);}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null;}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){let n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=false;}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,i=u=>u&&e.getAssetPlayer(u.identifier),r=(u,h,f,m,p)=>{if(u){let g=u[h].start,E=u.event;if(E){if(h==="playout"||E.timelineOccupancy!==uh.Point){let y=i(f);y?.interstitial===E&&(g+=y.assetItem.startOffset+y[p]);}}else {let y=m==="bufferedPos"?o():e[m];g+=y-u.start;}return g}return 0},n=(u,h)=>{var f;if(u!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var m;let p=e.schedule.findItemIndexAtTime(u),g=(m=e.schedule.items)==null?void 0:m[p];if(g){let E=g[h].start-g.start;return u+E}}return u},o=()=>{let u=e.bufferedPos;return u===Number.MAX_VALUE?a("primary"):Math.max(u,0)},a=u=>{var h,f;return (h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[u])||0},l=(u,h)=>{var f,m;let p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${h}"`);let g=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(u,h),y=(m=e.schedule.items)==null?void 0:m[E],_=e.getBufferingPlayer(),S=_?.interstitial,L=S?.appendInPlace,O=g&&e.itemsMatch(g,y);if(g&&(L||O)){let R=i(e.playingAsset),D=R?.media||e.primaryMedia;if(D){let C=h==="primary"?D.currentTime:r(g,h,e.playingAsset,"timelinePos","currentTime"),k=u-C,H=(L?C:D.currentTime)+k;if(H>=0&&(!R||L||H<=R.duration)){D.currentTime=H;return}}}if(y){let R=u;if(h!=="primary"){let C=y[h].start,k=u-C;R=y.start+k;}let D=!e.isInterstitial(y);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(D||y.event.appendInPlace)){let C=e.media||(L?_?.media:null);C&&(C.currentTime=R);}else if(g){let C=e.findItemIndex(g);if(E>C){let H=e.schedule.findJumpRestrictedIndex(C+1,E);if(H>C){e.setSchedulePosition(H);return}}let k=0;if(D)e.timelinePos=R,e.checkBuffer();else {let H=y.event.assetList,q=u-(y[h]||y).start;for(let j=H.length;j--;){let X=H[j];if(X.duration&&q>=X.startOffset&&q<X.startOffset+X.duration){k=j;break}}}e.setSchedulePosition(E,k);}}},d=()=>{let u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;let h=t();return e.isInterstitial(h)?h:null},c={get bufferedEnd(){let u=t(),h=e.bufferingItem;if(h&&h===u){var f;return r(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let u=d(),h=e.effectivePlayingItem;return h&&h===u?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(u){let h=d(),f=e.effectivePlayingItem;f&&f===h&&l(u+f.playout.start,"playout");},get duration(){let u=d();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;let h=(u=d())==null?void 0:u.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;let h=(u=d())==null?void 0:u.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var u;return ((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return ((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return d()?c:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return o()},get currentTime(){let u=e.timelinePos;return u>0?u:0},set currentTime(u){l(u,"primary");},get duration(){return a("primary")},get seekableStart(){var u;return ((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){l(u,"integrated");},get duration(){return a("integrated")},get seekableStart(){var u;return n(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{let u=e.effectivePlayingItem,h=u?.event;if(h&&!h.restrictions.skip){let f=e.findItemIndex(u);if(h.appendInPlace){let m=u.playout.start+u.event.duration;l(m+.001,"playout");}else e.advanceAfterAssetEnded(h,f,1/0);}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return !this.playbackStarted||!t||!i?false:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(r=this.primaryMedia);let n=(t=r)==null?void 0:t.currentTime;if(!(n===void 0||!Q(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return !!(e!=null&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t);}transferMediaFromPlayer(e,t){let i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${We(n)}`),this.detachedData=n;}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused));}transferMediaTo(e,t){var i,r;if(e.media===t)return;let n=null,o=this.hls,a=e!==o,l=a&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource,c;if(o.media)l&&(n=o.transferMedia(),this.detachedData=n),c="Primary";else if(d){let m=this.getBufferingPlayer();m?(n=m.transferMedia(),c=`${m}`):c="detached MediaSource";}else c="detached media";if(!n){if(d)n=this.detachedData,this.log(`using detachedData: MediaSource ${We(n)}`);else if(!this.detachedData||o.media===t){let m=this.playerQueue;m.length>1&&m.forEach(p=>{if(a&&p.interstitial.appendInPlace!==l){let g=p.interstitial;this.clearInterstitial(p.interstitial,null),g.appendInPlace=false,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`);}}),this.hls.detachMedia(),this.detachedData={media:t};}}let u=n&&"mediaSource"in n&&((r=n.mediaSource)==null?void 0:r.readyState)!=="closed",h=u&&n?n:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${c} (media.currentTime: ${t.currentTime})`);let f=this.schedule;if(h===n&&f){let m=a&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!a||m,cueRemoval:!a};}e.attachMedia(h);}onInterstitialCueEnter(){this.onTimeupdate();}checkStart(){let e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);let i=this.timelinePos,r=this.effectivePlayingItem;if(i===-1){let n=this.hls.startPosition;if(this.log(Mu("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){let o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o);}else if(n>=0||!this.primaryLive){let o=this.timelinePos=n>0?n:0,a=e.findItemIndexAtTime(o);this.setSchedulePosition(a);}}else if(r&&!this.playingItem){let n=e.findItemIndex(r);this.setSchedulePosition(n);}}advanceAssetBuffering(e,t){let i=e.event,r=i.findAssetIndex(t),n=Ap(i,r);if(!i.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var o;let a=(o=this.schedule.items)==null?void 0:o[this.findItemIndex(e)+1];a&&this.bufferedToItem(a);}}advanceAfterAssetEnded(e,t,i){let r=Ap(e,i);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){let n=this.schedule.items;if(n){let o=t+1,a=n.length;if(o>=a){this.setSchedulePosition(-1);return}let l=e.resumeTime;this.timelinePos<l&&(this.log(Mu("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(o);}}}else {if(e.appendInPlace){let n=e.assetList[r];n&&this.advanceInPlace(n.timelineStart);}this.setSchedulePosition(t,r);}}setScheduleToAssetAtTime(e,t){let i=this.schedule;if(!i)return;let r=t.parentIdentifier,n=i.getEvent(r);if(n){let o=i.findEventIndex(r),a=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,o,a-1);}}setSchedulePosition(e,t){var i;let r=(i=this.schedule)==null?void 0:i.items;if(!r||this.playbackDisabled)return;let n=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&Ai(n)}) pos: ${this.timelinePos}`);let o=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(o)){let c=o.event,u=this.playingAsset,h=u?.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(o,n)||t!==void 0&&h!==c.assetList[t].identifier)){var l;let m=c.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${c.assetList.length} ${lo(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(v.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:m,event:c,schedule:r.slice(0),scheduleIndex:e,player:f}),o!==this.playingItem){this.itemsMatch(o,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(c,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(h,n),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia();}if(!this.eventItemsMatch(o,n)&&(this.endedItem=o,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${c} ${Ai(o)}`),c.hasPlayed=true,this.hls.trigger(v.INTERSTITIAL_ENDED,{event:c,schedule:r.slice(0),scheduleIndex:e}),c.cue.once)){var d;this.updateSchedule();let m=(d=this.schedule)==null?void 0:d.items;if(n&&m){let p=this.findItemIndex(n);this.advanceSchedule(p,m,t,o,a);}return}}this.advanceSchedule(e,r,t,o,a);}advanceSchedule(e,t,i,r,n){let o=this.schedule;if(!o)return;let a=t[e]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(c=>{let u=c.interstitial,h=o.findEventIndex(u.identifier);(h<e||h>e+1)&&this.clearInterstitial(u,a);}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);let c=a.event;if(i===void 0){i=o.findAssetIndex(c,this.timelinePos);let m=Ap(c,i-1);if(c.isAssetPastPlayoutLimit(m)||c.appendInPlace&&this.timelinePos===a.end){this.advanceAfterAssetEnded(c,e,i);return}i=m;}let u=this.waitingItem;this.assetsBuffered(a,l)||this.setBufferingItem(a);let h=this.preloadAssets(c,i);if(this.eventItemsMatch(a,u||r)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Ai(a)} ${c.appendInPlace?"append in place":""}`),this.hls.trigger(v.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${c}`);return}if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${c}`);return}this.waitingItem=this.endedItem=null,this.playingItem=a;let f=c.assetList[i];if(!f){this.advanceAfterAssetEnded(c,e,i||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){let m=c.assetList.length;this.warn(`asset ${i+1}/${m} player destroyed ${c}`),h=this.createAssetPlayer(c,f,i),h.loadSource();}if(!this.eventItemsMatch(a,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,i,t,e,l),this.shouldPlay&&S_(h.media);}else a?(this.resumePrimary(a,e,r),this.shouldPlay&&S_(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(o.durations.primary,null));}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===false}get primaryDetails(){var e;return (e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return !!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var r,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Ai(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let a=this.timelinePos;(a<e.start||a>=e.end)&&(a=this.getPrimaryResumption(e,t),this.log(Mu("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e);}if(!i)return;let o=(n=this.schedule)==null?void 0:n.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ai(e)}`),this.hls.trigger(v.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer());}getPrimaryResumption(e,t){let i=e.start;if(this.primaryLive){let r=this.primaryDetails;if(t===0)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Ee.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Mu("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i));}startLoadingPrimaryAt(e,t){var i;let r=this.hls;!r.loadingEnabled||!r.media||Math.abs((((i=r.mainForwardBufferInfo)==null?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering();}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=false,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(v.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(v.BUFFER_CODECS,this.onBufferCodecs,this);}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let r=Oe(Oe({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart();}onAudioTrackUpdated(e,t){let i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Oe(Oe({},this.altSelection),{},{audio:i});return}let n=Oe(Oe({},r),{},{audio:i});this.mediaSelection=n;}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Oe(Oe({},this.altSelection),{},{subtitles:i});return}let n=Oe(Oe({},r),{},{subtitles:i});this.mediaSelection=n;}onAudioTrackSwitching(e,t){let i=Mb(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(i)));}onSubtitleTrackSwitch(e,t){let i=Mb(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.setSubtitleOption(i)));}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i);}onBufferAppended(e,t){this.checkBuffer();}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let r=this.timelinePos;this.bufferedPos=r,this.checkBuffer();}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let r=0;r<t.length;r++){let n=t[r];if(n.cue.post){var i;let o=this.schedule.findEventIndex(n.identifier),a=(i=this.schedule.items)==null?void 0:i[o];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE;}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let i=this.findItemIndex(t);this.setSchedulePosition(i+1);}else this.shouldPlay=false;}updateItem(e,t){var i;let r=(i=this.schedule)==null?void 0:i.items;if(e&&r){let n=this.findItemIndex(e,t);return r[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,o)=>{e.event.isAssetPastPlayoutLimit(o)&&this.clearAssetPlayer(n.identifier,null);});let i=e.end+.25,r=Ee.bufferInfo(this.primaryMedia,i,0);(r.end>i||(r.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${Ai(e)} (was ${Ai(t)})`),this.attachPrimary(i,null,true),this.flushFrontBuffer(i));}}itemsMatch(e,t){return !!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return !!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=false){var t;let i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e));}checkBuffer(e){var t;let i=(t=this.schedule)==null?void 0:t.items;if(!i)return;let r=Ee.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e);}updateBufferedPos(e,t,i){let r=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}let o=this.playingItem,a=this.findItemIndex(o),l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var d;let c=this.findItemIndex(n),u=Math.min(c+1,t.length-1),h=t[u];if((l===-1&&n&&e>=n.end||(d=h.event)!=null&&d.appendInPlace&&e+.01>=h.start)&&(l=u),this.isInterstitial(n)){let f=n.event;if(u-a>1&&f.appendInPlace===false||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>c&&l>a)this.bufferedToItem(h);else {let f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0);}}else i&&o&&!this.itemsMatch(o,n)&&(l===a?this.bufferedToItem(o):l===a+1&&this.bufferedToItem(t[l]));}assetsBuffered(e,t){return e.event.assetList.length===0?false:!e.event.assetList.some(r=>{let n=this.getAssetPlayer(r.identifier);return !(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:r,events:n}=i;if(!r||!n)return t;let o=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ai(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(o){let d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((c,u)=>{let h=this.getAssetPlayer(c.identifier);h&&(u===d&&h.loadSource(),h.resumeBuffering());});}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(v.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)});}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;let r=this.detachedData;r?r.mediaSource?this.attachPrimary(e.start,e,true):this.preloadPrimary(e):this.preloadPrimary(e);}}}preloadPrimary(e){let t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i);}bufferedToEvent(e,t){let i=e.event,r=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(r||!n){let o=this.preloadAssets(i,t);if(o!=null&&o.interstitial.appendInPlace){let a=this.primaryMedia;a&&this.bufferAssetPlayer(o,a);}}}preloadAssets(e,t){let i=e.assetUrl,r=e.assetList.length,n=r===0&&!e.assetListLoader,o=e.cue.once;if(n){let l=e.timelineStart;if(e.appendInPlace){var a;let h=this.playingItem;!this.isInterstitial(h)&&(h==null||(a=h.nextEvent)==null?void 0:a.identifier)===e.identifier&&this.flushFrontBuffer(l+.25);}let d,c=0;if(!this.playingItem&&this.primaryLive&&(c=this.hls.startPosition,c===-1&&(c=this.hls.liveSyncPosition||0)),c&&!(e.cue.pre||e.cue.post)){let h=c-l;h>0&&(d=Math.round(h*1e3)/1e3);}if(this.log(`Load interstitial asset ${t+1}/${i?1:r} ${e}${d?` live-start: ${c} start-offset: ${d}`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);let u=this.assetListLoader.loadAssetList(e,d);u&&(e.assetListLoader=u);}else if(!o&&r){for(let d=t;d<r;d++){let c=e.assetList[d],u=this.getAssetPlayerQueueIndex(c.identifier);(u===-1||this.playerQueue[u].destroyed)&&!c.error&&this.createAssetPlayer(e,c,d);}let l=e.assetList[t];if(l){let d=this.getAssetPlayer(l.identifier);return d&&d.loadSource(),d}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r});});}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return -1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,r,n,o){let a={parentIdentifier:e.identifier,identifier:nD(e,o,t),duration:n,startOffset:i,timelineStart:r,uri:o};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,i){let r=this.hls,n=r.userConfig,o=n.videoPreference,a=r.loadLevelObj||r.levels[r.currentLevel];(o||a)&&(o=Be({},o),a.videoCodec&&(o.videoCodec=a.videoCodec),a.videoRange&&(o.allowedVideoRanges=[a.videoRange]));let l=r.audioTracks[r.audioTrack],d=r.subtitleTracks[r.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){let S=this.timelinePos-t.timelineStart;if(S>1){let L=t.duration;L&&S<L&&(c=S);}}let u=t.identifier,h=Oe(Oe({},n),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:true,startFragPrefetch:true,primarySessionId:r.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:false,testBandwidth:false,videoPreference:o,audioPreference:l||n.audioPreference,subtitlePreference:d||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=true,t.timelineStart&&(h.timelineOffset=t.timelineStart));let f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=Be({},f,{contentId:cl(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);let m=new Rg(this.HlsPlayerClass,h,e,t);this.playerQueue.push(m),e.assetList[i]=t;let p=true,g=S=>{if(S.live){var L;let D=new Error(`Interstitials MUST be VOD assets ${e}`),C={fatal:true,type:ie.OTHER_ERROR,details:M.INTERSTITIAL_ASSET_ITEM_ERROR,error:D},k=((L=this.schedule)==null?void 0:L.findEventIndex(e.identifier))||-1;this.handleAssetItemError(C,e,k,i,D.message);return}let O=S.edge-S.fragmentStart,R=t.duration;(p||R===null||O>R)&&(p=false,this.log(`Interstitial asset "${u}" duration change ${R} > ${O}`),t.duration=O,this.updateSchedule());};m.on(v.LEVEL_UPDATED,(S,{details:L})=>g(L)),m.on(v.LEVEL_PTS_UPDATED,(S,{details:L})=>g(L)),m.on(v.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let E=(S,L)=>{let O=this.getAssetPlayer(u);if(O&&L.tracks){O.off(v.BUFFER_CODECS,E),O.tracks=L.tracks;let R=this.primaryMedia;this.bufferingAsset===O.assetItem&&R&&!O.media&&this.bufferAssetPlayer(O,R);}};m.on(v.BUFFER_CODECS,E);let y=()=>{var S;let L=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${L}`),!L||!this.schedule)return;let O=this.schedule.findEventIndex(e.identifier),R=(S=this.schedule.items)==null?void 0:S[O];this.isInterstitial(R)&&this.advanceAssetBuffering(R,t);};m.on(v.BUFFERED_TO_END,y);let _=S=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=true;let O=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,O,S);};return m.once(v.MEDIA_ENDED,_(i)),m.once(v.PLAYOUT_LIMIT_REACHED,_(1/0)),m.on(v.ERROR,(S,L)=>{if(!this.schedule)return;let O=this.getAssetPlayer(u);if(L.details===M.BUFFER_STALLED_ERROR){if(O!=null&&O.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(true);return}this.handleAssetItemError(L,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${L.error} ${e}`);}),m.on(v.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;let L=new Error(`Asset player destroyed unexpectedly ${u}`),O={fatal:true,type:ie.OTHER_ERROR,details:M.INTERSTITIAL_ASSET_ITEM_ERROR,error:L};this.handleAssetItemError(O,e,this.schedule.findEventIndex(e.identifier),i,L.message);}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${lo(t)}`),this.hls.trigger(v.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:m}),m}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset();}clearAssetPlayers(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t);});}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails();}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(i!==-1){let r=this.playerQueue[i];this.log(`clear ${r} toSegment: ${t&&Ai(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy();}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[];}startAssetPlayer(e,t,i,r,n){let{interstitial:o,assetItem:a,assetId:l}=e,d=o.assetList.length,c=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!c||c.identifier!==l)&&(c&&(this.clearAssetPlayer(c.identifier,i[r]),delete c.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${lo(a)}`),this.hls.trigger(v.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:o,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n);}bufferAssetPlayer(e,t){var i,r;if(!this.schedule)return;let{interstitial:n,assetItem:o}=e,a=this.schedule.findEventIndex(n.identifier),l=(i=this.schedule.items)==null?void 0:i[a];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=o;let d=this.getBufferingPlayer();if(d===e)return;let c=n.appendInPlace;if(c&&d?.interstitial.appendInPlace===false)return;let u=d?.tracks||((r=this.detachedData)==null?void 0:r.tracks)||this.requiredTracks;if(c&&o!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!P_(u,e.tracks)){let h=new Error(`Asset ${lo(o)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),f={fatal:true,type:ie.OTHER_ERROR,details:M.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},m=n.findAssetIndex(o);this.handleAssetItemError(f,n,a,m,h.message);return}}this.transferMediaTo(e,t);}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let r=i.currentTime,n=t.findAssetIndex(e,r),o=e.assetList[n];if(o){let a=this.getAssetPlayer(o.identifier);if(a){let l=a.currentTime||r-o.timelineStart,d=a.duration-l;if(this.warn(`Stalled at ${l} of ${l+d} in ${a} ${e} (media.currentTime: ${r})`),l&&(d/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){let c=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,c,n);}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e);}handleAssetItemError(e,t,i,r,n){if(e.details===M.BUFFER_STALLED_ERROR)return;let o=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${o&&lo(o)} ${e.error}`),!this.schedule)return;let a=o?.identifier||"",l=this.getAssetPlayerQueueIndex(a),d=this.playerQueue[l]||null,c=this.schedule.items,u=Be({},e,{fatal:false,errorAction:ho(true),asset:o,assetListIndex:r,event:t,schedule:c,scheduleIndex:i,player:d});if(this.hls.trigger(v.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;let h=this.playingAsset,f=this.bufferingAsset,m=new Error(n);if(o&&(this.clearAssetPlayer(a,null),o.error=m),!t.assetList.some(p=>!p.error))t.error=m;else for(let p=r;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(true),t.error?this.primaryFallback(t):h&&h.identifier===a?this.advanceAfterAssetEnded(t,i,r):f&&f.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f);}primaryFallback(e){let t=e.timelineStart,i=this.effectivePlayingItem,r=this.timelinePos;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${r} playing: ${Ai(i)} error: ${e.error}`),r===-1&&(r=this.hls.startPosition);let o=this.updateItem(i,r);this.itemsMatch(i,o)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t));}else if(r===-1){this.checkStart();return}if(!this.schedule)return;let n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n);}onAssetListLoaded(e,t){var i,r;let n=t.event,o=n.identifier,a=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(o)))return;let l=n.timelineStart,d=n.duration,c=0;a.forEach((p,g)=>{let E=parseFloat(p.DURATION);this.createAsset(n,g,c,l+c,E,p.URI),c+=E;}),n.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${d}) ${n}`);let u=this.waitingItem,h=u?.event.identifier===o;this.updateSchedule();let f=(r=this.bufferingItem)==null?void 0:r.event;if(h){var m;let p=this.schedule.findEventIndex(o),g=(m=this.schedule.items)==null?void 0:m[p];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(true),this.primaryFallback(n);return}this.setBufferingItem(g);}this.setSchedulePosition(p);}else if(f?.identifier===o){let p=n.assetList[0];if(p){let g=this.getAssetPlayer(p.identifier);if(f.appendInPlace){let E=this.primaryMedia;g&&E&&this.bufferAssetPlayer(g,E);}else g&&g.loadSource();}}}onError(e,t){if(this.schedule)switch(t.details){case M.ASSET_LIST_PARSING_ERROR:case M.ASSET_LIST_LOAD_ERROR:case M.ASSET_LIST_LOAD_TIMEOUT:{let i=t.interstitial;i&&(this.updateSchedule(true),this.primaryFallback(i));break}case M.BUFFER_STALLED_ERROR:{let i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(true);break}}}},A_=500,Dg=class extends vl{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",J.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners();}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null;}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(v.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this);}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(v.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(v.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(v.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this);}startLoad(e,t){this.stopLoad(),this.state=G.IDLE,this.setInterval(A_),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick();}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null;}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t);}onLevelLoaded(e,t){this.mainDetails=t.details;}onSubtitleFragProcessed(e,t){let{frag:i,success:r}=t;if(this.fragContextChanged(i)||(at(i)&&(this.fragPrevious=i),this.state=G.IDLE),!r)return;let n=this.tracksBuffered[this.currentTrackId];if(!n)return;let o,a=i.start;for(let d=0;d<n.length;d++)if(a>=n[d].start&&a<=n[d].end){o=n[d];break}let l=i.start+i.duration;o?o.end=l:(o={start:a,end:l},n.push(o)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick();}onBufferFlushing(e,t){let{startOffset:i,endOffset:r}=t;if(i===0&&r!==Number.POSITIVE_INFINITY){let n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(o=>{for(let a=0;a<o.length;){if(o[a].end<=n){o.shift();continue}else if(o[a].start<n)o[a].start=n;else break;a++;}}),this.fragmentTracker.removeFragmentsInRange(i,n,J.SUBTITLE);}}onError(e,t){let i=t.frag;i?.type===J.SUBTITLE&&(t.details===M.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,true),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==G.STOPPED&&(this.state=G.IDLE));}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&CT(this.levels,t)){this.levels=t.map(i=>new Jr(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{let r=new Jr(i);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,J.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null;}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==G.STOPPED&&this.setInterval(A_);}onSubtitleTrackLoaded(e,t){var i;let{currentTrackId:r,levels:n}=this,{details:o,id:a}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}let l=n[a];if(a>=n.length||!l)return;this.log(`Subtitle track ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(o.live||(i=l.details)!=null&&i.live){if(o.deltaUpdateFailed)return;let u=this.mainDetails;if(!u){this.startFragRequested=false;return}let h=u.fragments[0];if(!l.details)o.hasProgramDateTime&&u.hasProgramDateTime?(sh(o,u),d=o.fragmentStart):h&&(d=h.start,Xp(o,d));else {var c;d=this.alignPlaylists(o,l.details,(c=this.levelLastLoaded)==null?void 0:c.details),d===0&&h&&(d=h.start,Xp(o,d));}u&&!this.startFragRequested&&this.setStartPosition(u,d);}l.details=o,this.levelLastLoaded=l,a===r&&(this.hls.trigger(v.SUBTITLE_TRACK_UPDATED,{details:o,id:a,groupId:t.groupId}),this.tick(),o.live&&!this.fragCurrent&&this.media&&this.state===G.IDLE&&(en(null,o.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)));}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e,r=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&r!=null&&r.key&&r.iv&&fo(r.method)){let o=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,s0(r.method)).catch(a=>{throw n.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.FRAG_DECRYPT_ERROR,fatal:false,error:a,reason:a.message,frag:t}),a}).then(a=>{let l=performance.now();n.trigger(v.FRAG_DECRYPTED,{frag:t,payload:a,stats:{tstart:o,tdecrypt:l}});}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=G.IDLE;});}}doTick(){if(!this.media){this.state=G.IDLE;return}if(this.state===G.IDLE){let{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;let{config:r}=this,n=this.getLoadPosition(),o=Ee.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:a,len:l}=o,d=i.details,c=this.hls.maxBufferLength+d.levelTargetDuration;if(l>c)return;let u=d.fragments,h=u.length,f=d.edge,m=null,p=this.fragPrevious;if(a<f){let y=r.maxFragLookUpTolerance,_=a>f-y?0:y;m=en(p,u,Math.max(u[0].start,a),_),!m&&p&&p.start<u[0].start&&(m=u[0]);}else m=u[h-1];if(m=this.filterReplacedPrimary(m,i.details),!m)return;let g=m.sn-d.startSN,E=u[g-1];if(E&&E.cc===m.cc&&this.fragmentTracker.getState(E)===vt.NOT_LOADED&&(m=E),this.fragmentTracker.getState(m)===vt.NOT_LOADED){let y=this.mapToInitFragWhenRequired(m);y&&this.loadFragment(y,i,a);}}}loadFragment(e,t,i){at(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t);}get mediaBufferTimeRanges(){return new Mg(this.tracksBuffered[this.currentTrackId]||[])}},Mg=class{constructor(e){this.buffered=void 0;let t=(i,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}};}},aD={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},qT=s=>String.fromCharCode(aD[s]||s),Ii=15,Ls=100,lD={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},dD={17:2,18:4,21:6,22:8,23:10,19:13,20:15},cD={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},uD={25:2,26:4,29:6,30:8,31:10,27:13,28:15},hD=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Pg=class{constructor(){this.time=null,this.verboseLevel=0;}log(e,t){if(this.verboseLevel>=e){let i=typeof t=="function"?t():t;Ue.log(`${this.time} [${e}] ${i}`);}}},Yr=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},hh=class{constructor(){this.foreground="white",this.underline=false,this.italics=false,this.background="black",this.flash=false;}reset(){this.foreground="white",this.underline=false,this.italics=false,this.background="black",this.flash=false;}setStyles(e){let t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){let r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r]);}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash;}toString(){return "color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},Og=class{constructor(){this.uchar=" ",this.penState=new hh;}reset(){this.uchar=" ",this.penState.reset();}setChar(e,t){this.uchar=e,this.penState.copy(t);}setPenState(e){this.penState.copy(e);}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState);}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}},Ug=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new hh,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ls;t++)this.chars.push(new Og);this.logger=e;}equals(e){for(let t=0;t<Ls;t++)if(!this.chars[t].equals(e.chars[t]))return false;return true}copy(e){for(let t=0;t<Ls;t++)this.chars[t].copy(e.chars[t]);}isEmpty(){let e=true;for(let t=0;t<Ls;t++)if(!this.chars[t].isEmpty()){e=false;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ls&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ls);}moveCursor(e){let t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t);}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState);}insertChar(e){e>=144&&this.backSpace();let t=qT(e);if(this.pos>=Ls){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1);}clearFromPos(e){let t;for(t=e;t<Ls;t++)this.chars[t].reset();}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset();}clearToEndOfRow(){this.clearFromPos(this.pos);}getTextString(){let e=[],t=true;for(let i=0;i<Ls;i++){let r=this.chars[i].uchar;r!==" "&&(t=false),e.push(r);}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState);}},ul=class{constructor(e){this.rows=[],this.currRow=Ii-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Ii;t++)this.rows.push(new Ug(e));this.logger=e;}reset(){for(let e=0;e<Ii;e++)this.rows[e].clear();this.currRow=Ii-1;}equals(e){let t=true;for(let i=0;i<Ii;i++)if(!this.rows[i].equals(e.rows[i])){t=false;break}return t}copy(e){for(let t=0;t<Ii;t++)this.rows[t].copy(e.rows[t]);}isEmpty(){let e=true;for(let t=0;t<Ii;t++)if(!this.rows[t].isEmpty()){e=false;break}return e}backSpace(){this.rows[this.currRow].backSpace();}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow();}insertChar(e){this.rows[this.currRow].insertChar(e);}setPen(e){this.rows[this.currRow].setPenStyles(e);}moveCursor(e){this.rows[this.currRow].moveCursor(e);}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e);}setPAC(e){this.logger.log(2,()=>"pacData = "+We(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let a=0;a<Ii;a++)this.rows[a].clear();let n=this.currRow+1-this.nrRollUpRows,o=this.lastOutputScreen;if(o){let a=o.rows[n].cueStartTime,l=this.logger.time;if(a!==null&&l!==null&&a<l)for(let d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(o.rows[n+d]);}}this.currRow=t;let i=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,o=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[o].penState.foreground;}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:false};this.setPen(r);}setBkgData(e){this.logger.log(2,()=>"bkgData = "+We(e)),this.backSpace(),this.setPen(e),this.insertChar(32);}setRollUpRows(e){this.nrRollUpRows=e;}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up");}getDisplayText(e){e=e||false;let t=[],i="",r=-1;for(let n=0;n<Ii;n++){let o=this.rows[n].getTextString();o&&(r=n+1,e?t.push("Row "+r+": '"+o+"'"):t.push(o.trim()));}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
1954
+ `)),i}getTextAndFormat(){return this.rows}},fh=class{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new ul(i),this.nonDisplayedMemory=new ul(i),this.lastOutputScreen=new ul(i),this.currRollUpRow=this.displayedMemory.rows[Ii-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i;}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Ii-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null;}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e;}setPAC(e){this.writeScreen.setPAC(e);}setBkgData(e){this.writeScreen.setBkgData(e);}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e);}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(true)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(true)),this.outputDataUpdate());}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON");}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate());}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate();}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e);}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:true});}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON");}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT");}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT");}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(true);}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(true);}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset();}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText());}this.outputDataUpdate(true);}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e);}ccMIDROW(e){let t={flash:false};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else {let i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i];}this.logger.log(2,"MIDROW: "+We(t)),this.writeScreen.setPen(t);}outputDataUpdate(e=false){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory));}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e));}},mh=class{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=mD(),this.logger=void 0;let r=this.logger=new Pg;this.channels=[null,new fh(e,t,r),new fh(e+1,i,r)];}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t);}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){let r=t[i]&127,n=t[i+1]&127,o=false,a=null;if(r===0&&n===0)continue;this.logger.log(3,()=>"["+Yr([t[i],t[i+1]])+"] -> ("+Yr([r,n])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(fD(r,n,l)){Pu(null,null,l),this.logger.log(3,()=>"Repeated command ("+Yr([r,n])+") is dropped");continue}Pu(r,n,this.cmdHistory),o=this.parseCmd(r,n),o||(o=this.parseMidrow(r,n)),o||(o=this.parsePAC(r,n)),o||(o=this.parseBackgroundAttributes(r,n));}else Pu(null,null,l);if(!o&&(a=this.parseChars(r,n),a)){let c=this.currentChannel;c&&c>0?this.channels[c].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?");}!o&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Yr([r,n])+" orig: "+Yr([t[i],t[i+1]]));}}parseCmd(e,t){let i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(i||r))return false;let n=e===20||e===21||e===23?1:2,o=this.channels[n];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),this.currentChannel=n,true}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),false;let r=this.channels[i];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Yr([e,t])+")"),true):false}return false}parsePAC(e,t){let i,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(r||n))return false;let o=e<=23?1:2;t>=64&&t<=95?i=o===1?lD[e]:cD[e]:i=o===1?dD[e]:uD[e];let a=this.channels[o];return a?(a.setPAC(this.interpretPAC(i,t)),this.currentChannel=o,true):false}interpretPAC(e,t){let i,r={color:null,italics:false,indent:null,underline:false,row:e};return t>95?i=t-96:i=t-64,r.underline=(i&1)===1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=true,r.color="white"):r.indent=Math.floor((i-16)/2)*4,r}parseChars(e,t){let i,r=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let o;n===17?o=t+80:n===18?o=t+112:o=t+144,this.logger.log(2,()=>"Special char '"+qT(o)+"' in channel "+i),r=[o];}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+Yr(r).join(",")),r}parseBackgroundAttributes(e,t){let i=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(i||r))return false;let n,o={};e===16||e===24?(n=Math.floor((t-32)/2),o.background=hD[n],t%2===1&&(o.background=o.background+"_semi")):t===45?o.background="transparent":(o.foreground="black",t===47&&(o.underline=true));let a=e<=23?1:2;return this.channels[a].setBkgData(o),true}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset();}Pu(null,null,this.cmdHistory);}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e);}}};function Pu(s,e,t){t.a=s,t.b=e;}function fD(s,e,t){return t.a===s&&t.b===e}function mD(){return {a:null,b:null}}var f0=(function(){if(ih!=null&&ih.VTTCue)return self.VTTCue;let s=["","lr","rl"],e=["start","middle","end","left","right"];function t(a,l){if(typeof l!="string"||!Array.isArray(a))return false;let d=l.toLowerCase();return ~a.indexOf(d)?d:false}function i(a){return t(s,a)}function r(a){return t(e,a)}function n(a,...l){let d=1;for(;d<arguments.length;d++){let c=arguments[d];for(let u in c)a[u]=c[u];}return a}function o(a,l,d){let c=this,u={enumerable:true};c.hasBeenReset=false;let h="",f=false,m=a,p=l,g=d,E=null,y="",_=true,S="auto",L="start",O=50,R="middle",D=50,C="middle";Object.defineProperty(c,"id",n({},u,{get:function(){return h},set:function(k){h=""+k;}})),Object.defineProperty(c,"pauseOnExit",n({},u,{get:function(){return f},set:function(k){f=!!k;}})),Object.defineProperty(c,"startTime",n({},u,{get:function(){return m},set:function(k){if(typeof k!="number")throw new TypeError("Start time must be set to a number.");m=k,this.hasBeenReset=true;}})),Object.defineProperty(c,"endTime",n({},u,{get:function(){return p},set:function(k){if(typeof k!="number")throw new TypeError("End time must be set to a number.");p=k,this.hasBeenReset=true;}})),Object.defineProperty(c,"text",n({},u,{get:function(){return g},set:function(k){g=""+k,this.hasBeenReset=true;}})),Object.defineProperty(c,"region",n({},u,{get:function(){return E},set:function(k){E=k,this.hasBeenReset=true;}})),Object.defineProperty(c,"vertical",n({},u,{get:function(){return y},set:function(k){let H=i(k);if(H===false)throw new SyntaxError("An invalid or illegal string was specified.");y=H,this.hasBeenReset=true;}})),Object.defineProperty(c,"snapToLines",n({},u,{get:function(){return _},set:function(k){_=!!k,this.hasBeenReset=true;}})),Object.defineProperty(c,"line",n({},u,{get:function(){return S},set:function(k){if(typeof k!="number"&&k!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=k,this.hasBeenReset=true;}})),Object.defineProperty(c,"lineAlign",n({},u,{get:function(){return L},set:function(k){let H=r(k);if(!H)throw new SyntaxError("An invalid or illegal string was specified.");L=H,this.hasBeenReset=true;}})),Object.defineProperty(c,"position",n({},u,{get:function(){return O},set:function(k){if(k<0||k>100)throw new Error("Position must be between 0 and 100.");O=k,this.hasBeenReset=true;}})),Object.defineProperty(c,"positionAlign",n({},u,{get:function(){return R},set:function(k){let H=r(k);if(!H)throw new SyntaxError("An invalid or illegal string was specified.");R=H,this.hasBeenReset=true;}})),Object.defineProperty(c,"size",n({},u,{get:function(){return D},set:function(k){if(k<0||k>100)throw new Error("Size must be between 0 and 100.");D=k,this.hasBeenReset=true;}})),Object.defineProperty(c,"align",n({},u,{get:function(){return C},set:function(k){let H=r(k);if(!H)throw new SyntaxError("An invalid or illegal string was specified.");C=H,this.hasBeenReset=true;}})),c.displayState=void 0;}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})(),Ng=class{decode(e,t){if(!e)return "";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function jT(s){function e(i,r,n,o){return (i|0)*3600+(r|0)*60+(n|0)+parseFloat(o||0)}let t=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}var Fg=class{constructor(){this.values=Object.create(null);}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t);}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10));}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),true}return false}};function YT(s,e,t,i){let r=i?s.split(i):[s];for(let n in r){if(typeof r[n]!="string")continue;let o=r[n].split(t);if(o.length!==2)continue;let a=o[0],l=o[1];e(a,l);}}var $g=new f0(0,0,""),Ou=$g.align==="middle"?"middle":"center";function pD(s,e,t){let i=s;function r(){let a=jT(s);if(a===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),a}function n(a,l){let d=new Fg;YT(a,function(h,f){let m;switch(h){case "region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){d.set(h,t[p].region);break}break;case "vertical":d.alt(h,f,["rl","lr"]);break;case "line":m=f.split(","),d.integer(h,m[0]),d.percent(h,m[0])&&d.set("snapToLines",false),d.alt(h,m[0],["auto"]),m.length===2&&d.alt("lineAlign",m[1],["start",Ou,"end"]);break;case "position":m=f.split(","),d.percent(h,m[0]),m.length===2&&d.alt("positionAlign",m[1],["start",Ou,"end","line-left","line-right","auto"]);break;case "size":d.percent(h,f);break;case "align":d.alt(h,f,["start",Ou,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let c=d.get("line","auto");c==="auto"&&$g.line===-1&&(c=-1),l.line=c,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",true),l.size=d.get("size",100),l.align=d.get("align",Ou);let u=d.get("position","auto");u==="auto"&&$g.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u;}function o(){s=s.replace(/^\s+/,"");}if(o(),e.startTime=r(),o(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),o(),e.endTime=r(),o(),n(s,e);}function zT(s){return s.replace(/<br(?: \/)?>/gi,`
1955
+ `)}var Bg=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Ng,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0;}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:true}));function i(){let n=t.buffer,o=0;for(n=zT(n);o<n.length&&n[o]!=="\r"&&n[o]!==`
1956
+ `;)++o;let a=n.slice(0,o);return n[o]==="\r"&&++o,n[o]===`
1957
+ `&&++o,t.buffer=n.slice(o),a}function r(n){YT(n,function(o,a){},/:/);}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=i();let a=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(a!=null&&a[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER";}let o=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(o?o=!1:n=i(),t.state){case "HEADER":/:/.test(n)?r(n):n||(t.state="ID");continue;case "NOTE":n||(t.state="ID");continue;case "ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new f0(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case "CUE":if(!t.cue){t.state="BADCUE";continue}try{pD(n,t.cue,t.regionList);}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case "CUETEXT":{let a=n.indexOf("-->")!==-1;if(!n||a&&(o=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
1958
+ `),t.cue.text+=n;}continue;case "BADCUE":n||(t.state="ID");}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE";}return this}flush(){let e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
1959
+
1960
+ `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t);}return e.onflush&&e.onflush(),this}},gD=/\r\n|\n\r|\n|\r/g,Ip=function(e,t,i=0){return e.slice(i,i+t.length)===t},vD=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!Q(t)||!Q(i)||!Q(r)||!Q(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*r,t+=3600*1e3*n,t};function m0(s,e,t){return cl(s.toString())+cl(e.toString())+cl(t)}var ED=function(e,t,i){let r=e[t],n=e[r.prevCC];if(!n||!n.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=false;return}for(;(o=n)!=null&&o.new;){var o;e.ccOffset+=r.start-n.start,r.new=false,r=n,n=e[r.prevCC];}e.presentationOffset=i;};function yD(s,e,t,i,r,n,o){let a=new Bg,l=ri(new Uint8Array(s)).trim().replace(gD,`
1961
+ `).split(`
1962
+ `),d=[],c=e?Qw(e.baseTime,e.timescale):0,u="00:00.000",h=0,f=0,m,p=true;a.oncue=function(g){let E=t[i],y=t.ccOffset,_=(h-c)/9e4;if(E!=null&&E.new&&(f!==void 0?y=t.ccOffset=E.start:ED(t,i,_)),_){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}y=_-t.presentationOffset;}let S=g.endTime-g.startTime,L=ii((g.startTime+y-f)*9e4,r*9e4)/9e4;g.startTime=Math.max(L,0),g.endTime=Math.max(L+S,0);let O=g.text.trim();g.text=decodeURIComponent(encodeURIComponent(O)),g.id||(g.id=m0(g.startTime,g.endTime,O)),g.endTime>0&&d.push(g);},a.onparsingerror=function(g){m=g;},a.onflush=function(){if(m){o(m);return}n(d);},l.forEach(g=>{if(p)if(Ip(g,"X-TIMESTAMP-MAP=")){p=false,g.slice(16).split(",").forEach(E=>{Ip(E,"LOCAL:")?u=E.slice(6):Ip(E,"MPEGTS:")&&(h=parseInt(E.slice(7)));});try{f=vD(u)/1e3;}catch(E){m=E;}return}else g===""&&(p=false);a.parse(g+`
1963
+ `);}),a.flush();}var xp="stpp.ttml.im1t",QT=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,XT=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,bD={left:"start",center:"center",right:"end",start:"start",end:"end"};function I_(s,e,t,i){let r=be(new Uint8Array(s),["mdat"]);if(r.length===0){i(new Error("Could not parse IMSC1 mdat"));return}let n=r.map(a=>ri(a)),o=zw(e.baseTime,1,e.timescale);try{n.forEach(a=>t(_D(a,o)));}catch(a){i(a);}}function _D(s,e){let r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},o=Object.keys(n).reduce((u,h)=>(u[h]=r.getAttribute(`ttp:${h}`)||n[h],u),{}),a=r.getAttribute("xml:space")!=="preserve",l=x_(Lp(r,"styling","style")),d=x_(Lp(r,"layout","region")),c=Lp(r,"body","[begin]");return [].map.call(c,u=>{let h=ZT(u,a);if(!h||!u.hasAttribute("begin"))return null;let f=kp(u.getAttribute("begin"),o),m=kp(u.getAttribute("dur"),o),p=kp(u.getAttribute("end"),o);if(f===null)throw L_(u);if(p===null){if(m===null)throw L_(u);p=f+m;}let g=new f0(f-e,p-e,h);g.id=m0(g.startTime,g.endTime,g.text);let E=d[u.getAttribute("region")],y=l[u.getAttribute("style")],_=TD(E,y,l),{textAlign:S}=_;if(S){let L=bD[S];L&&(g.lineAlign=L),g.align=S;}return Be(g,_),g}).filter(u=>u!==null)}function Lp(s,e,t){let i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function x_(s){return s.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function ZT(s,e){return [].slice.call(s.childNodes).reduce((t,i,r)=>{var n;return i.nodeName==="br"&&r?t+`
1964
+ `:(n=i.childNodes)!=null&&n.length?ZT(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function TD(s,e,t){let i="http://www.w3.org/ns/ttml#styling",r=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],o=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return o&&t.hasOwnProperty(o)&&(r=t[o]),n.reduce((a,l)=>{let d=Rp(e,i,l)||Rp(s,i,l)||Rp(r,i,l);return d&&(a[l]=d),a},{})}function Rp(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function L_(s){return new Error(`Could not parse ttml timestamp ${s}`)}function kp(s,e){if(!s)return null;let t=jT(s);return t===null&&(QT.test(s)?t=SD(s,e):XT.test(s)&&(t=AD(s,e))),t}function SD(s,e){let t=QT.exec(s),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return (t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function AD(s,e){let t=XT.exec(s),i=Number(t[1]);switch(t[2]){case "h":return i*3600;case "m":return i*60;case "ms":return i*1e3;case "f":return i/e.frameRate;case "t":return i/e.tickRate}return i}var uo=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t;}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null);}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName);}reset(){this.cueRanges=[],this.startTime=null;}},Hg=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=true,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=k_(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(v.FRAG_LOADING,this.onFragLoading,this),e.on(v.FRAG_LOADED,this.onFragLoaded,this),e.on(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this);}destroy(){let{hls:e}=this;e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(v.FRAG_LOADING,this.onFragLoading,this),e.off(v.FRAG_LOADED,this.onFragLoaded,this),e.off(v.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(v.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(v.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(v.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0;}initCea608Parsers(){let e=new uo(this,"textTrack1"),t=new uo(this,"textTrack2"),i=new uo(this,"textTrack3"),r=new uo(this,"textTrack4");this.cea608Parser1=new mh(1,e,t),this.cea608Parser2=new mh(3,i,r);}addCues(e,t,i,r,n){let o=false;for(let a=n.length;a--;){let l=n[a],d=ID(l[0],l[1],t,i);if(d>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),o=true,d/(i-t)>.5))return}if(o||n.push([t,i]),this.config.renderTextTracksNatively){let a=this.captionsTracks[e];this.Cues.newCue(a,t,i,r);}else {let a=this.Cues.newCue(null,t,i,r);this.hls.trigger(v.CUES_PARSED,{type:"captions",cues:a,track:e});}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n,trackId:o}){let{unparsedVttFrags:a}=this;i===J.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:n,trackId:o}),a.length&&(this.unparsedVttFrags=[],a.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(v.FRAG_LOADED,l):this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:false,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")});}));}getExistingTrack(e,t){let{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){let n=i.textTracks[r];if(R_(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e);}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:r}=this,{label:n,languageCode:o}=t[e],a=this.getExistingTrack(n,o);if(a)i[e]=a,co(i[e]),KT(i[e],r);else {let l=this.createTextTrack("captions",n,o);l&&(l[e]=true,i[e]=l);}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,r={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:false,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]});}createTextTrack(e,t,i){let r=this.media;if(r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks();}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,i)return;let{captionsTracks:r}=this;Object.keys(r).forEach(n=>{co(r[n]),delete r[n];}),this.nonNativeCaptionsTracks={};}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=k_(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset());}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let i=0;i<t.length;i++)co(t[i]);}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],r=i.some(n=>n.textCodec===xp);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(CT(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let o=this.media,a=o?Ku(o.textTracks):null;if(this.tracks.forEach((l,d)=>{let c;if(a){let u=null;for(let h=0;h<a.length;h++)if(a[h]&&R_(a[h],l)){u=a[h],a[h]=null;break}u&&(c=u);}if(c)co(c);else {let u=JT(l);c=this.createTextTrack(u,l.name,l.lang),c&&(c.mode="disabled");}c&&this.textTracks.push(c);}),a!=null&&a.length){let l=a.filter(d=>d!==null).map(d=>d.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);}}else if(this.tracks.length){let o=this.tracks.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(v.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:o});}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let r=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!r)return;let n=`textTrack${r[1]}`,o=this.captionsProperties[n];o&&(o.label=i.name,i.lang&&(o.languageCode=i.lang),o.media=i);});}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===J.MAIN){var i,r;let{cea608Parser1:n,cea608Parser2:o,lastSn:a}=this,{cc:l,sn:d}=t.frag,c=(i=(r=t.part)==null?void 0:r.index)!=null?i:-1;n&&o&&(d!==a+1||d===a&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),o.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=c;}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.type===J.SUBTITLE)if(r.byteLength){let n=i.decryptdata,o="stats"in t;if(n==null||!n.encrypted||o){let a=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:true},this.prevCC=i.cc),a&&a.textCodec===xp?this._parseIMSC1(i,r):this._parseVTTs(t);}}else this.hls.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:false,frag:i,error:new Error("Empty subtitle payload")});}_parseIMSC1(e,t){let i=this.hls;I_(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:true,frag:e});},r=>{i.logger.log(`Failed to parse IMSC1: ${r}`),i.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:false,frag:e,error:r});});}_parseVTTs(e){var t;let{frag:i,payload:r}=e,{initPTS:n,unparsedVttFrags:o}=this,a=n.length-1;if(!n[i.cc]&&a===-1){o.push(e);return}let l=this.hls,d=(t=i.initSegment)!=null&&t.data?pi(i.initSegment.data,new Uint8Array(r)).buffer:r;yD(d,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,c=>{this._appendCues(c,i.level),l.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:true,frag:i});},c=>{let u=c.message==="Missing initPTS for VTT MPEGTS";u?o.push(e):this._fallbackToIMSC1(i,r),l.logger.log(`Failed to parse VTT cue: ${c}`),!(u&&a>i.cc)&&l.trigger(v.SUBTITLE_FRAG_PROCESSED,{success:false,frag:i,error:c});});}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||I_(t,this.initPTS[e.cc],()=>{i.textCodec=xp,this._parseIMSC1(e,t);},()=>{i.textCodec="wvtt";});}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>VT(r,n));}else {let r=this.tracks[t];if(!r)return;let n=r.default?"default":"subtitles"+t;i.trigger(v.CUES_PARSED,{type:"subtitles",cues:e,track:n});}}onFragDecrypted(e,t){let{frag:i}=t;i.type===J.SUBTITLE&&this.onFragLoaded(v.FRAG_LOADED,t);}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={};}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:r}=t;if(!(i.type===J.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<r.length;n++){let o=r[n].bytes;if(o){this.cea608Parser1||this.initCea608Parsers();let a=this.extractCea608Data(o);this.cea608Parser1.addData(r[n].pts,a[0]),this.cea608Parser2.addData(r[n].pts,a[1]);}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:n}){let{media:o}=this;if(!(!o||o.currentTime<i)){if(!n||n==="video"){let{captionsTracks:a}=this;Object.keys(a).forEach(l=>Ig(a[l],t,i));}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:a}=this;Object.keys(a).forEach(l=>Ig(a[l],t,r));}}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,r=2;for(let n=0;n<i;n++){let o=e[r++],a=127&e[r++],l=127&e[r++];if(a===0&&l===0)continue;if((4&o)!==0){let c=3&o;(c===0||c===1)&&(t[c].push(a),t[c].push(l));}}return t}};function JT(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function R_(s,e){return !!s&&s.kind===JT(e)&&fg(e,s)}function ID(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function k_(){return {ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:true}}}var xD=/\s/,LD={newCue(s,e,t,i){let r=[],n,o,a,l,d,c=self.VTTCue||self.TextTrackCue;for(let h=0;h<i.rows.length;h++)if(n=i.rows[h],a=true,l=0,d="",!n.isEmpty()){var u;for(let p=0;p<n.chars.length;p++)xD.test(n.chars[p].uchar)&&a?l++:(d+=n.chars[p].uchar,a=false);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=zT(d.trim()),m=m0(e,t,f);s!=null&&(u=s.cues)!=null&&u.getCueById(m)||(o=new c(e,t,f),o.id=m,o.line=h+1,o.align="left",o.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(o));}return s&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>VT(s,h))),r}};function RD(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return false}var kD=/(\d+)-(\d+)\/(\d+)/,ph=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||MD,this.controller=new self.AbortController,this.stats=new hl;}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null;}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=true,this.controller.abort());}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response);}load(e,t,i){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let n=wD(e,this.controller.signal),o=e.responseType==="arraybuffer",a=o?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&Q(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response));},t.timeout),(_l(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var h;this.response=this.loader=u;let f=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response));},d-(f-r.loading.start)),!u.ok){let{status:p,statusText:g}=u;throw new Gg(g||"fetch, bad network response",p,u)}r.loading.first=f,r.total=DD(u.headers)||r.total;let m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&Q(t.highWaterMark)?this.loadProgressively(u,r,e,t.highWaterMark,m):o?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var h,f;let m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let p=u[a];p&&(r.loaded=r.total=p);let g={url:m.url,data:u,code:m.status},E=(h=this.callbacks)==null?void 0:h.onProgress;E&&!Q(t.highWaterMark)&&E(r,e,u,m),(f=this.callbacks)==null||f.onSuccess(g,r,e,m);}).catch(u=>{var h;if(self.clearTimeout(this.requestTimeout),r.aborted)return;let f=u&&u.code||0,m=u?u.message:null;(h=this.callbacks)==null||h.onError({code:f,text:m},e,u?u.details:null,r);});}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null;}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,n){let o=new rh,a=e.body.getReader(),l=()=>a.read().then(d=>{if(d.done)return o.dataLength&&n(t,i,o.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=d.value,u=c.length;return t.loaded+=u,u<r||o.dataLength?(o.push(c),o.dataLength>=r&&n(t,i,o.flush().buffer,e)):n(t,i,c.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function wD(s,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Be({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function CD(s){let e=kD.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function DD(s){let e=s.get("Content-Range");if(e){let i=CD(e);if(Q(i))return i}let t=s.get("Content-Length");if(t)return parseInt(t)}function MD(s,e){return new self.Request(s.url,e)}var Gg=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i;}},PD=/^age:\s*[\d.]+\s*$/im,gh=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new hl,this.retryDelay=0;}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null;}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=true,e.abort()));}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader);}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal();}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=false;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(o=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,true),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e);}).catch(o=>{var a;(a=this.callbacks)==null||a.onError({code:i.status,text:o.message},t,i,r);}):this.openAndSendXhr(i,t,e);}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,true);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:o}=i.loadPolicy;if(r)for(let a in r)e.setRequestHeader(a,r[a]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&Q(n)?n:o,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send();}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let d=t.status,c=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){let m=c??t.response;if(m!=null){var o,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);let p=t.responseType==="arraybuffer"?m.byteLength:m.length;i.loaded=i.total=p,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);let g=(o=this.callbacks)==null?void 0:o.onProgress;g&&g(i,e,m,t);let E={url:t.responseURL,data:m,code:d};(a=this.callbacks)==null||a.onSuccess(E,i,e,t);return}}let u=n.loadPolicy.errorRetry,h=i.retry,f={url:e.url,data:void 0,code:d};if(Zu(u,h,false,f))this.retry(u);else {var l;Ue.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,i);}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(Zu(e,t,true))this.retry(e);else {var i;Ue.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader));}}retry(e){let{context:t,stats:i}=this;this.retryDelay=i0(e,i.retry),i.retry++,Ue.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay);}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total);}getCacheAge(){let e=null;if(this.loader&&PD.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null;}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},OD={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},UD=Oe(Oe({autoStartLoad:true,startPosition:-1,defaultAudioCodec:void 0,debug:false,capLevelOnFPSDrop:false,capLevelToPlayerSize:false,ignoreDevicePixelRatio:false,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:true,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:false,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:true,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:false,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:true,workerPath:null,enableSoftwareAES:true,startLevel:void 0,startFragPrefetch:false,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:false,loader:gh,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:$p,bufferController:vg,capLevelController:Eg,errorController:Hp,fpsController:Ag,stretchShortVideoTrack:false,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:true,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:false,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:false,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:sT,requireKeySystemAccessOnStart:false,testBandwidth:true,progressive:false,lowLatencyMode:true,cmcd:void 0,enableDateRangeMetadataCues:true,enableEmsgMetadataCues:true,enableEmsgKLVMetadata:false,enableID3MetadataCues:true,enableInterstitialPlayback:true,interstitialAppendInPlace:true,interstitialLiveLookAhead:10,useMediaCapabilities:true,preserveManualLevelOnError:false,certLoadPolicy:{default:OD},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},ND()),{},{subtitleStreamController:Dg,subtitleTrackController:xg,timelineController:Hg,audioStreamController:hg,audioTrackController:mg,emeController:ch,cmcdController:Tg,contentSteeringController:Sg,interstitialsController:Cg});function ND(){return {cueHandler:LD,enableWebVTT:true,enableIMSC1:true,enableCEA708Captions:true,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:true}}function FD(s,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let i=Kg(s),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(o=>{let a=`${o==="level"?"playlist":o}LoadPolicy`,l=e[a]===void 0,d=[];n.forEach(c=>{let u=`${o}Loading${c}`,h=e[u];if(h!==void 0&&l){d.push(u);let f=i[a].default;switch(e[a]={default:f},c){case "TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case "MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case "RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case "MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${a}": ${We(e[a])}`);}),Oe(Oe({},i),e)}function Kg(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Kg):Object.keys(s).reduce((e,t)=>(e[t]=Kg(s[t]),e),{}):s}function $D(s,e){let t=s.loader;t!==ph&&t!==gh?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=false):RD()&&(s.loader=ph,s.progressive=true,s.enableSoftwareAES=true,e.log("[config]: Progressive streaming enabled, using FetchLoader"));}var Vu=2,BD=.1,HD=.05,GD=100,Vg=class extends Ju{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=false,this.stalled=null,this.moved=false,this.seeking=false,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0;},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick());},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:false});}},this.hls=e,this.fragmentTracker=t,this.registerListeners();}registerListeners(){let{hls:e}=this;e&&(e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.BUFFER_APPENDED,this.onBufferAppended,this));}unregisterListeners(){let{hls:e}=this;e&&(e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.BUFFER_APPENDED,this.onBufferAppended,this));}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0;}onMediaAttached(e,t){this.setInterval(GD),this.mediaSource=t.mediaSource;let i=this.media=t.media;$t(i,"playing",this.onMediaPlaying),$t(i,"waiting",this.onMediaWaiting),$t(i,"ended",this.onMediaEnded);}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(Wt(i,"playing",this.onMediaPlaying),Wt(i,"waiting",this.onMediaWaiting),Wt(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0;}onBufferAppended(e,t){this.buffered=t.timeRanges;}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t;}poll(e,t){var i,r;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let o=this.media;if(!o)return;let{seeking:a}=o,l=this.seeking&&!a,d=!this.seeking&&a,c=o.paused&&!a||o.ended||o.playbackRate===0;if(this.seeking=a,e!==t){t&&(this.ended=0),this.moved=true,a||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!c&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(c){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&o.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:false}));return}if(!Ee.getBuffered(o).length){this.nudgeRetry=0;return}let u=Ee.bufferInfo(o,e,0),h=u.nextStart||0,f=this.fragmentTracker;if(a&&f&&this.hls){let O=w_(this.hls.inFlightFragments,e),R=u.len>Vu,D=!h||O||h-e>Vu&&!f.getPartialFragment(e);if(R||D)return;this.moved=false;}let m=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(u.len>0)&&!h)return;let R=Math.max(h,u.start||0)-e,C=!!(m!=null&&m.live)?m.targetduration*2:Vu,k=Uu(e,f);if(R>0&&(R<=C||k)){o.paused||this._trySkipBufferHole(k);return}}let p=n.detectStallWithCurrentTimeMs,g=self.performance.now(),E=this.waiting,y=this.stalled;if(y===null)if(E>0&&g-E<p)y=this.stalled=E;else {this.stalled=g;return}let _=g-y;if(!a&&(_>=p||E)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-(m?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:true});return}if(this._reportStall(u),!this.media||!this.hls)return}let L=Ee.bufferInfo(o,e,n.maxBufferHole);this._tryFixBufferStall(L,_,e);}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=false,this.waiting=0,this.hls.trigger(v.STALL_RESOLVED,{});}}nudgeOnVideoHole(e,t){var i;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&r&&r.length>1&&e>r.end(0)){let n=Ee.bufferedInfo(Ee.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let o=Ee.timeRangesToArray(r),a=Ee.bufferedInfo(o,t,0).bufferedIndex;if(a>-1&&a<o.length-1){let l=Ee.bufferedInfo(o,e,0).bufferedIndex,d=o[a].end,c=o[a+1].start;if((l===-1||l>a)&&c-d<1&&e-d<2){let u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${c} buffered index: ${l}`);this.warn(u.message),this.media.currentTime+=1e-6;let h=Uu(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);let f=Ee.bufferInfo(this.media,e,0);this.hls.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.BUFFER_SEEK_OVER_HOLE,fatal:false,error:u,reason:u.message,frag:h,buffer:f.len,bufferInfo:f});}}}}}_tryFixBufferStall(e,t,i){var r,n;let{fragmentTracker:o,media:a}=this,l=(r=this.hls)==null?void 0:r.config;if(!a||!o||!l)return;let d=(n=this.hls)==null?void 0:n.latestLevelDetails,c=Uu(i,o);if((c||d!=null&&d.live&&i<d.fragmentStart)&&(this._trySkipBufferHole(c)||!this.media))return;let u=e.buffered,h=this.adjacentTraversal(e,i);(u&&u.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e));}adjacentTraversal(e,t){let i=this.fragmentTracker,r=e.nextStart;if(i&&r){let n=i.getFragAtPos(t,J.MAIN),o=i.getFragAtPos(r,J.MAIN);if(n&&o)return o.sn-n.sn<2}return false}_reportStall(e){let{hls:t,media:i,stallReported:r,stalled:n}=this;if(!r&&n!==null&&i&&t){this.stallReported=true;let o=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${We(e)})`);this.warn(o.message),t.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.BUFFER_STALLED_ERROR,fatal:false,error:o,buffer:e.len,bufferInfo:e,stalled:{start:n}});}}_trySkipBufferHole(e){var t;let{fragmentTracker:i,media:r}=this,n=(t=this.hls)==null?void 0:t.config;if(!r||!i||!n)return 0;let o=r.currentTime,a=Ee.bufferInfo(r,o,0),l=o<a.start?a.start:a.nextStart;if(l&&this.hls){let c=a.len<=n.maxBufferHole,u=a.len>0&&a.len<1&&r.readyState<3,h=l-o;if(h>0&&(c||u)){if(h>n.maxBufferHole){let m=false;if(o===0){let p=i.getAppendedFrag(0,J.MAIN);p&&l<p.end&&(m=true);}if(!m&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||w_(this.hls.inFlightFragments,l))return 0;let g=false,E=e.end;for(;E<l;){let y=Uu(E,i);if(y)E+=y.duration;else {g=true;break}}if(g)return 0}}let f=Math.max(l+HD,o+BD);if(this.warn(`skipping hole, adjusting currentTime from ${o} to ${f}`),this.moved=true,r.currentTime=f,!(e!=null&&e.gap)){let m=new Error(`fragment loaded with buffer holes, seeking from ${o} to ${f}`),p={type:ie.MEDIA_ERROR,details:M.BUFFER_SEEK_OVER_HOLE,fatal:false,error:m,reason:m.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(v.ERROR,p);}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:r}=this,n=t?.config;if(!i||!n)return 0;let o=i.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){let a=o+(r+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${o} to ${a}`);this.warn(l.message),i.currentTime=a,t.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.BUFFER_NUDGE_ON_STALL,error:l,fatal:false,buffer:e.len,bufferInfo:e});}else {let a=new Error(`Playhead still not moving while enough data buffered @${o} after ${n.nudgeMaxRetry} nudges`);this.error(a.message),t.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.BUFFER_STALLED_ERROR,error:a,fatal:true,buffer:e.len,bufferInfo:e});}}};function w_(s,e){let t=C_(s.main);if(t&&t.start<=e)return t;let i=C_(s.audio);return i&&i.start<=e?i:null}function C_(s){if(!s)return null;switch(s.state){case G.IDLE:case G.STOPPED:case G.ENDED:case G.ERROR:return null}return s.frag}function Uu(s,e){return e.getAppendedFrag(s,J.MAIN)||e.getPartialFragment(s)}var KD=.25;function Wg(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function wp(s,e,t,i,r){let n=new s(e,t,"");try{n.value=i,r&&(n.type=r);}catch{n=new s(e,t,We(r?Oe({type:r},i):i));}return n}var Nu=(()=>{let s=Wg();try{s&&new s(0,Number.POSITIVE_INFINITY,"");}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),qg=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=true,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(v.EVENT_CUE_ENTER,{});},this.hls=e,this._registerListeners();}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null;}_registerListeners(){let{hls:e}=this;e&&(e.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(v.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this));}_unregisterListeners(){let{hls:e}=this;e&&(e.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(v.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this));}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===false&&(this.removeCues=false);}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t);}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&co(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={});}onManifestLoading(){this.dateRangeCuesAppended={};}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let i=e[t];if(i.kind==="metadata"&&i.label==="id3")return KT(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:r}=this.hls.config;if(!i&&!r)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let o=Wg();if(o)for(let a=0;a<n.length;a++){let l=n[a].type;if(l===si.emsg&&!i||!r)continue;let d=bT(n[a].data),c=n[a].pts,u=c+n[a].duration;u>Nu&&(u=Nu),u-c<=0&&(u=c+KD);for(let f=0;f<d.length;f++){let m=d[f];if(!_T(m)){this.updateId3CueEnds(c,l);let p=wp(o,c,u,m,l);p&&this.id3Track.addCue(p);}}}}updateId3CueEnds(e,t){var i;let r=(i=this.id3Track)==null?void 0:i.cues;if(r)for(let n=r.length;n--;){let o=r[n];o.type===t&&o.startTime<e&&o.endTime===Nu&&(o.endTime=e);}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){let{id3Track:n,hls:o}=this;if(!o)return;let{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:l}}=o;if(n&&(a||l)){let d;r==="audio"?d=c=>c.type===si.audioId3&&l:r==="video"?d=c=>c.type===si.emsg&&a:d=c=>c.type===si.audioId3&&l||c.type===si.emsg&&a,Ig(n,t,i,d);}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,true);}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details);}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:i,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:o}=this.hls.config;if(!n)return;let a=Wg();if(i&&r&&!o){let{fragmentStart:p,fragmentEnd:g}=e,E=this.assetCue;E?(E.startTime=p,E.endTime=g):a&&(E=this.assetCue=wp(a,p,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)));}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:d}=e,c=Object.keys(d),u=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.cues)!=null&&h.length){let p=Object.keys(u).filter(g=>!c.includes(g));for(let g=p.length;g--;){var f;let E=p[g],y=(f=u[E])==null?void 0:f.cues;delete u[E],y&&Object.keys(y).forEach(_=>{let S=y[_];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(S);}catch{}}});}}else u=this.dateRangeCuesAppended={};}let m=e.fragments[e.fragments.length-1];if(!(c.length===0||!Q(m?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<c.length;p++){let g=c[p],E=d[g],y=E.startTime,_=u[g],S=_?.cues||{},L=_?.durationKnown||false,O=Nu,{duration:R,endDate:D}=E;if(D&&R!==null)O=y+R,L=true;else if(E.endOnNext&&!L){let k=c.reduce((H,q)=>{if(q!==E.id){let j=d[q];if(j.class===E.class&&j.startDate>E.startDate&&(!H||E.startDate<H.startDate))return j}return H},null);k&&(O=k.startTime,L=true);}let C=Object.keys(E.attr);for(let k=0;k<C.length;k++){let H=C[k];if(!Yk(H))continue;let q=S[H];if(q)L&&!(_!=null&&_.durationKnown)?q.endTime=O:Math.abs(q.startTime-y)>.01&&(q.startTime=y,q.endTime=O);else if(a){let j=E.attr[H];zk(H)&&(j=O_(j));let Y=wp(a,y,O,{key:H,data:j},si.dateRange);Y&&(Y.id=g,this.id3Track.addCue(Y),S[H]=Y,o&&(H==="X-ASSET-LIST"||H==="X-ASSET-URL")&&Y.addEventListener("enter",this.onEventCueEnter));}}u[g]={cues:S,dateRange:E,durationKnown:L};}}}},jg=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=false,this.onTimeupdate=()=>{let{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;let r=this.computeLatency();if(r===null)return;this._latency=r;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:o}=this.config;if(!n||o===1||!i.live)return;let a=this.targetLatency;if(a===null)return;let l=r-a,d=Math.min(this.maxLatency,a+i.targetduration);if(l<d&&l>.05&&this.forwardBufferLength>1){let u=Math.min(2,Math.max(1,o)),h=Math.round(2/(1+Math.exp(-0.75*l-this.edgeStalled))*20)/20,f=Math.min(u,Math.max(1,h));this.changeMediaPlaybackRate(t,f);}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1);},this.hls=e,this.config=e.config,this.registerListeners();}get levelDetails(){var e;return ((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:o,lowLatencyMode:a}=this.config,l=this.hls.userConfig,d=a&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||d===0)&&(d=n!==void 0?n:o*r);let c=r;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,c)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=true;}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let i=this.levelDetails;if(i===null)return null;let r=i.edge,n=e-t-this.edgeStalled,o=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(o,n),a)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return (i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null;}registerListeners(){let{hls:e}=this;e&&(e.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(v.ERROR,this.onError,this));}unregisterListeners(){let{hls:e}=this;e&&(e.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(v.ERROR,this.onError,this));}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate);}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null);}onManifestLoading(){this._latency=null,this.stallCount=0;}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate);}onError(e,t){var i;t.details===M.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"));}changeMediaPlaybackRate(e,t){var i,r;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t);}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},Yg=class extends Tl{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners();}_registerListeners(){let{hls:e}=this;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this),e.on(v.ERROR,this.onError,this);}_unregisterListeners(){let{hls:e}=this;e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this),e.off(v.ERROR,this.onError,this);}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy();}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0;}),super.stopLoad();}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1;}onManifestLoading(e,t){this.resetLevels();}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],n={},o={},a=false,l=false,d=false;t.levels.forEach(c=>{let u=c.attrs,{audioCodec:h,videoCodec:f}=c;h&&(c.audioCodec=h=ju(h,i)||void 0),f&&(f=c.videoCodec=Ek(f));let{width:m,height:p,unknownCodecs:g}=c,E=g?.length||0;if(a||(a=!!(m&&p)),l||(l=!!f),d||(d=!!h),E||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}let{CODECS:y,"FRAME-RATE":_,"HDCP-LEVEL":S,"PATHWAY-ID":L,RESOLUTION:O,"VIDEO-RANGE":R}=u,C=`${`${L||"."}-`}${c.bitrate}-${O}-${_}-${y}-${R}-${S}`;if(n[C])if(n[C].uri!==c.url&&!c.attrs["PATHWAY-ID"]){let k=o[C]+=1;c.attrs["PATHWAY-ID"]=new Array(k+1).join(".");let H=this.createLevel(c);n[C]=H,r.push(H);}else n[C].addGroupId("audio",u.AUDIO),n[C].addGroupId("text",u.SUBTITLES);else {let k=this.createLevel(c);n[C]=k,o[C]=1,r.push(k);}}),this.filterAndSortMediaOptions(r,t,a,l,d);}createLevel(e){let t=new Jr(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){let r=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(r.message),t.supportedResult=q_(r,[]);}return t}isAudioSupported(e){return fl(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return fl(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,r,n){var o;let a=[],l=[],d=e,c=((o=t.stats)==null?void 0:o.parsing)||{};if((i||r)&&n&&(d=d.filter(({videoCodec:y,videoRange:_,width:S,height:L})=>(!!y||!!(S&&L))&&Rk(_))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let y="no level with compatible codecs found in manifest",_=y;t.levels.length&&(_=`one or more CODECS in variant not supported: ${We(t.levels.map(L=>L.attrs.CODECS).filter((L,O,R)=>R.indexOf(L)===O))}`,this.warn(_),y+=` (${_})`);let S=new Error(y);this.hls.trigger(v.ERROR,{type:ie.MEDIA_ERROR,details:M.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:true,url:t.url,error:S,reason:_});}}),c.end=performance.now();return}t.audioTracks&&(a=t.audioTracks.filter(y=>!y.audioCodec||this.isAudioSupported(y.audioCodec)),D_(a)),t.subtitles&&(l=t.subtitles,D_(l));let u=d.slice(0);d.sort((y,_)=>{if(y.attrs["HDCP-LEVEL"]!==_.attrs["HDCP-LEVEL"])return (y.attrs["HDCP-LEVEL"]||"")>(_.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&y.height!==_.height)return y.height-_.height;if(y.frameRate!==_.frameRate)return y.frameRate-_.frameRate;if(y.videoRange!==_.videoRange)return Yu.indexOf(y.videoRange)-Yu.indexOf(_.videoRange);if(y.videoCodec!==_.videoCodec){let S=Rb(y.videoCodec),L=Rb(_.videoCodec);if(S!==L)return L-S}if(y.uri===_.uri&&y.codecSet!==_.codecSet){let S=qu(y.codecSet),L=qu(_.codecSet);if(S!==L)return L-S}return y.averageBitrate!==_.averageBitrate?y.averageBitrate-_.averageBitrate:0});let h=u[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==u.length)){for(let y=0;y<u.length;y++)if(u[y].pathwayId===d[0].pathwayId){h=u[y];break}}this._levels=d;for(let y=0;y<d.length;y++)if(d[y]===h){var f;this._firstLevel=y;let _=h.bitrate,S=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${_}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){let L=Math.min(_,this.hls.config.abrEwmaDefaultEstimateMax);L>S&&S===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=L);}break}let m=n&&!r,p=this.hls.config,g=!!(p.audioStreamController&&p.audioTrackController),E={levels:d,audioTracks:a,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:g&&!m&&a.some(y=>!!y.url)};c.end=performance.now(),this.hls.trigger(v.MANIFEST_PARSED,E);}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let c=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(v.ERROR,{type:ie.OTHER_ERROR,details:M.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:c,reason:c.message}),u)return;e=Math.min(e,t.length-1);}let i=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,o=t[e],a=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,i===e&&r&&n===a)return;this.log(`Switching to level ${e} (${o.height?o.height+"p ":""}${o.videoRange?o.videoRange+" ":""}${o.codecSet?o.codecSet+" ":""}@${o.bitrate})${a?" with Pathway "+a:""} from level ${i}${n?" with Pathway "+n:""}`);let l={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(v.LEVEL_SWITCHING,l);let d=o.details;if(!d||d.live){let c=this.switchParams(o.uri,r?.details,d);this.loadPlaylist(c);}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e);}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e;}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e;}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter(r=>t.indexOf(r)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i;}}onError(e,t){t.fatal||!t.context||t.context.type===Te.LEVEL&&t.context.level===this.level&&this.checkRetry(t);}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===J.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0);}}onLevelLoaded(e,t){var i;let{level:r,details:n}=t,o=t.levelInfo;if(!o){var a;this.warn(`Invalid level index ${r}`),(a=t.deliveryDirectives)!=null&&a.skip&&(n.deltaUpdateFailed=true);return}if(o===this.currentLevel||t.withoutMultiVariant){o.fragmentError===0&&(o.loadError=0);let l=o.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(r,t,l);}else (i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=true);}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e);}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],o=e.details,a=o?.age;this.log(`Loading level index ${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${a&&o.live?" age "+a.toFixed(1)+(o.type&&" "+o.type||""):""} ${i}`),this.hls.trigger(v.LEVEL_LOADING,{url:i,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null});}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e);}removeLevel(e){var t;if(this._levels.length===1)return;let i=this._levels.filter((n,o)=>o!==e?true:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(a=>a.level=-1)),false));uT(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=i.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(v.LEVELS_UPDATED,{levels:i});}onLevelsUpdated(e,{levels:t}){this._levels=t;}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(v.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}));}};function D_(s){let e={};s.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++;});}function eS(){return self.SourceBuffer||self.WebKitSourceBuffer}function tS(){if(!sr())return false;let e=eS();return !e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function VD(){if(!tS())return false;let s=sr();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(ml(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(ml(e,"audio"))))}function WD(){var s;let e=eS();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}var qD=100,zg=class extends vl{constructor(e,t,i){super(e,t,i,"stream-controller",J.MAIN),this.audioCodecSwap=false,this.level=-1,this._forceStartLoad=false,this._hasEnoughToStart=false,this.altAudio=0,this.audioOnly=false,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=false,this.backtrackFragment=null,this.audioCodecSwitch=false,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick();},this.onMediaSeeked=()=>{let r=this.media,n=r?r.currentTime:null;if(n===null||!Q(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;let o=this.getFwdBufferInfoAtPos(r,n,J.MAIN,0);if(o===null||o.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${o?o.len:"empty"})`);return}this.tick();},this.registerListeners();}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(v.MANIFEST_PARSED,this.onManifestParsed,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.LEVEL_LOADED,this.onLevelLoaded,this),e.on(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(v.BUFFER_CREATED,this.onBufferCreated,this),e.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(v.FRAG_BUFFERED,this.onFragBuffered,this);}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(v.MANIFEST_PARSED,this.onManifestParsed,this),e.off(v.LEVEL_LOADED,this.onLevelLoaded,this),e.off(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(v.BUFFER_CREATED,this.onBufferCreated,this),e.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(v.FRAG_BUFFERED,this.onFragBuffered,this);}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying();}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(qD),this.level=-1,!this.startFragRequested){let n=r.startLevel;n===-1&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=true):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t;}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=G.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick();}else this._forceStartLoad=true,this.state=G.STOPPED;}stopLoad(){this._forceStartLoad=false,super.stopLoad();}doTick(){switch(this.state){case G.WAITING_LEVEL:{let{levels:e,level:t}=this,i=e?.[t],r=i?.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=G.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=G.IDLE;break}break}case G.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===G.IDLE&&this.doTickIdle(),this.onTickEnd();}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===false&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged();}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;let o=i[n],a=this.getMainFwdBufferInfo();if(a===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(a,l)){let p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(v.BUFFER_EOS,p),this.state=G.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let d=o.details;if(!d||this.state===G.WAITING_LEVEL||this.waitForLive(o)){this.level=n,this.state=G.WAITING_LEVEL,this.startFragRequested=false;return}let c=a.len,u=this.getMaxBufferLength(o.maxBitrate);if(c>=u)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);let h=this.backtrackFragment?this.backtrackFragment.start:a.end,f=this.getNextFragment(h,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&at(f)&&this.fragmentTracker.getState(f)!==vt.OK){var m;let g=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,E=d.fragments[g-1];E&&f.cc===E.cc&&(f=E,this.fragmentTracker.removeFragment(E));}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let g=this.audioOnly&&!this.altAudio?Ve.AUDIO:Ve.VIDEO,E=(g===Ve.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,g,J.MAIN);}f=this.getNextFragmentLoopLoading(f,d,a,J.MAIN,u);}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,o,h));}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);r===vt.NOT_LOADED||r===vt.PARTIAL?at(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e);}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,J.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY);}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let a=this.getMainFwdBufferInfo();if(!a||a.len<n.targetduration*2)return}if(!t.paused&&e){let a=this.hls.nextLoadLevel,l=e[a],d=this.fragLastKbps;d&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+1:i=0;}else i=0;let o=this.getBufferedFrag(t.currentTime+i);if(o){let a=this.followingBufferedFrag(o);if(a){this.abortCurrentFrag();let l=a.maxStartPTS?a.maxStartPTS:a.start,d=a.duration,c=Math.max(o.end,l+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY);}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case G.KEY_LOADING:case G.FRAG_LOADING:case G.FRAG_LOADING_WAITING_RETRY:case G.PARSING:case G.PARSED:this.state=G.IDLE;break}this.nextLoadPosition=this.getLoadPosition();}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null);}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;$t(i,"playing",this.onMediaPlaying),$t(i,"seeked",this.onMediaSeeked);}onMediaDetaching(e,t){let{media:i}=this;i&&(Wt(i,"playing",this.onMediaPlaying),Wt(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=false);}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(v.BUFFER_RESET,void 0),this.couldBacktrack=false,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=false;}onManifestParsed(e,t){let i=false,r=false;for(let n=0;n<t.levels.length;n++){let o=t.levels[n].audioCodec;o&&(i=i||o.indexOf("mp4a.40.2")!==-1,r=r||o.indexOf("mp4a.40.5")!==-1);}this.audioCodecSwitch=i&&r&&!WD(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=false;}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==G.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=G.WAITING_LEVEL);}onLevelLoaded(e,t){var i;let{levels:r,startFragRequested:n}=this,o=t.level,a=t.details,l=a.totalduration;if(!r){this.warn(`Levels were reset while loading level ${o}`);return}this.log(`Level ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${l}`);let d=t.levelInfo,c=this.fragCurrent;c&&(this.state===G.FRAG_LOADING||this.state===G.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let u=0;if(a.live||(i=d.details)!=null&&i.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,d.details,(h=this.levelLastLoaded)==null?void 0:h.details);}if(d.details=a,this.levelLastLoaded=d,n||this.setStartPosition(a,u),this.hls.trigger(v.LEVEL_UPDATED,{details:a,level:o}),this.state===G.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=G.IDLE;}n&&a.live&&this.synchronizeToLiveEdge(a),this.tick();}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let r=this.hls.liveSyncPosition,n=this.getLoadPosition(),o=e.fragmentStart,a=e.edge,l=n>=o-t.maxFragLookUpTolerance&&n<=a;if(r!==null&&i.duration>r&&(n<r||!l)){let c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||n<a-c)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var d;let u=Ee.bufferInfo(i,r,0);if(!((d=u.buffered)!=null&&d.length)){i.currentTime=r;return}if(u.start<=n){i.currentTime=r;return}let{nextStart:f}=Ee.bufferedInfo(u.buffered,n,0);f&&(i.currentTime=f);}else i.currentTime=r;}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:n}=e,{levels:o}=this;if(!o){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let a=o[i.level];if(!a){this.warn(`Level ${i.level} not found on progress`);return}let l=a.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let d=a.videoCodec,c=l.PTSKnown||!l.live,u=(t=i.initSegment)==null?void 0:t.data,h=this._getAudioCodec(a),f=this.transmuxer=this.transmuxer||new lh(this.hls,J.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,p=m!==-1,g=new gl(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,p),E=this.initPTS[i.cc];f.push(n,u,h,d,i,r,l.totalduration,c,g,E);}onAudioTrackSwitching(e,t){let i=this.hls,r=this.altAudio!==0;if(Qu(t.url,i))this.altAudio=1;else {if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let o=this.fragCurrent;o&&(this.log("Switching to main audio track, cancel main fragment load"),o.abortRequests(),this.fragmentTracker.removeFragment(o)),this.resetTransmuxer(),this.resetLoadingState();}else this.audioOnly&&this.resetTransmuxer();if(r){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(v.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(v.AUDIO_TRACK_SWITCHED,t);}),i.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(v.AUDIO_TRACK_SWITCHED,t);}}onAudioTrackSwitched(e,t){let i=Qu(t.url,this.hls);if(i){let r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r);}this.altAudio=i?2:0,this.tick();}onBufferCreated(e,t){let i=t.tracks,r,n,o=false;for(let a in i){let l=i[a];if(l.id==="main"){if(n=a,r=l,a==="video"){let d=i[a];d&&(this.videoBuffer=d.buffer);}}else o=true;}o&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media;}onFragBuffered(e,t){let{frag:i,part:r}=t,n=i.type===J.MAIN;if(n){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===G.PARSED&&(this.state=G.IDLE);return}let a=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),at(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r);}let o=this.media;o&&(!this._hasEnoughToStart&&Ee.getBuffered(o).length&&(this._hasEnoughToStart=true,this.seekToStartPos()),n&&this.tick());}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=G.ERROR;return}switch(t.details){case M.FRAG_GAP:case M.FRAG_PARSING_ERROR:case M.FRAG_DECRYPT_ERROR:case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.MAIN,t);break;case M.LEVEL_LOAD_ERROR:case M.LEVEL_LOAD_TIMEOUT:case M.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===G.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===Te.LEVEL&&(this.state=G.IDLE);break;case M.BUFFER_ADD_CODEC_ERROR:case M.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case M.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=true:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case M.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=G.IDLE,this._hasEnoughToStart||(this.startFragRequested=false,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate();}onBufferFlushed(e,{type:t}){if(t!==Ve.AUDIO||!this.altAudio){let i=(t===Ve.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,J.MAIN),this.tick());}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels;}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap;}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&i&&(i+=r);let n=this.getLevelDetails(),o=Ee.getBuffered(e),a=o.length?o.start(0):0,l=a-i,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${a}`),e.currentTime=i);}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=true,this._doFragLoad(e,t).then(i=>{let{hls:r}=this,n=i?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=G.IDLE,this.startFragRequested=false,this.bitrateTest=false;let o=n.stats;o.parsing.start=o.parsing.end=o.buffering.start=o.buffering.end=self.performance.now(),r.trigger(v.FRAG_LOADED,i),n.bitrateTest=false;}).catch(i=>{this.state===G.STOPPED||this.state===G.ERROR||(this.warn(i),this.resetFragmentLoading(e));});}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}let{frag:a,part:l,level:d}=o,{video:c,text:u,id3:h,initSegment:f}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(a)){this.fragmentTracker.removeFragment(a);return}if(this.state=G.PARSING,f){let g=f.tracks;if(g){let S=a.initSegment||a;if(this.unhandledEncryptionError(f,a))return;this._bufferInitSegment(d,g,S,n),i.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:t,tracks:g});}let E=f.initPTS,y=f.timescale,_=this.initPTS[a.cc];if(Q(E)&&(!_||_.baseTime!==E||_.timescale!==y)){let S=f.trackId;this.initPTS[a.cc]={baseTime:E,timescale:y,trackId:S},i.trigger(v.INIT_PTS_FOUND,{frag:a,id:t,initPTS:E,timescale:y,trackId:S});}}if(c&&m){p&&c.type==="audiovideo"&&this.logMuxedErr(a);let g=m.fragments[a.sn-1-m.startSN],E=a.sn===m.startSN,y=!g||a.cc>g.cc;if(r.independent!==false){let{startPTS:_,endPTS:S,startDTS:L,endDTS:O}=c;if(l)l.elementaryStreams[c.type]={startPTS:_,endPTS:S,startDTS:L,endDTS:O};else if(c.firstKeyFrame&&c.independent&&n.id===1&&!y&&(this.couldBacktrack=true),c.dropped&&c.independent){let R=this.getMainFwdBufferInfo(),D=(R?R.end:this.getLoadPosition())+this.config.maxBufferHole,C=c.firstKeyFramePTS?c.firstKeyFramePTS:_;if(!E&&D<C-this.config.maxBufferHole&&!y){this.backtrack(a);return}else y&&(a.gap=true);a.setElementaryStreamInfo(c.type,a.start,S,a.start,O,true);}else E&&_-(m.appliedTimelineOffset||0)>Vu&&(a.gap=true);a.setElementaryStreamInfo(c.type,_,S,L,O),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(c,a,l,n,E||y);}else if(E||y)a.gap=true;else {this.backtrack(a);return}}if(p){let{startPTS:g,endPTS:E,startDTS:y,endDTS:_}=p;l&&(l.elementaryStreams[Ve.AUDIO]={startPTS:g,endPTS:E,startDTS:y,endDTS:_}),a.setElementaryStreamInfo(Ve.AUDIO,g,E,y,_),this.bufferFragmentData(p,a,l,n);}if(m&&h!=null&&h.samples.length){let g={id:t,frag:a,details:m,samples:h.samples};i.trigger(v.FRAG_PARSING_METADATA,g);}if(m&&u){let g={id:t,frag:a,details:m,samples:u.samples};i.trigger(v.FRAG_PARSING_USERDATA,g);}}logMuxedErr(e){this.warn(`${at(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`);}_bufferInitSegment(e,t,i,r){if(this.state!==G.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:n,video:o,audiovideo:a}=t;if(n){let d=e.audioCodec,c=Fu(n.codec,d);c==="mp4a"&&(c="mp4a.40.5");let u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){c&&(c.indexOf("mp4a.40.5")!==-1?c="mp4a.40.2":c="mp4a.40.5");let h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(c="mp4a.40.5");}c&&c.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(c="mp4a.40.2",this.log(`Android: force audio codec to ${c}`)),d&&d!==c&&this.log(`Swapping manifest audio codec "${d}" for "${c}"`),n.levelCodec=c,n.id=J.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${c||""}/${d||""}/${n.codec}]`),delete t.audiovideo;}if(o){o.levelCodec=e.videoCodec,o.id=J.MAIN;let d=o.codec;if(d?.length===4)switch(d){case "hvc1":case "hev1":o.codec="hvc1.1.6.L120.90";break;case "av01":o.codec="av01.0.04M.08";break;case "avc1":o.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${o.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${o.codec!==d?" parsed-corrected="+o.codec:""}${o.supplemental?" supplemental="+o.supplemental:""}`),delete t.audiovideo;}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(v.BUFFER_CODECS,t),!this.hls)return;l.forEach(d=>{let u=t[d].initSegment;u!=null&&u.byteLength&&this.hls.trigger(v.BUFFER_APPENDING,{type:d,data:u,frag:i,part:null,chunkMeta:r,parent:i.type});});}this.tickImmediate();}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,J.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=true,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=G.IDLE;}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===false){let i=e.currentTime;if(Ee.isBuffered(e,i)?t=this.getAppendedFrag(i):Ee.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(v.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(v.LEVEL_SWITCHED,{level:n}));}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return Q(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(Q(t)){let i=this.getLevelDetails(),r=this.currentFrag||(i?en(null,i.fragments,t):null);if(r){let n=r.programDateTime;if(n!==null){let o=n+(t-r.start)*1e3;return new Date(o)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},Qg=class extends qt{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e;}abort(e){for(let i in this.keyIdToKeyInfo){let r=this.keyIdToKeyInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort();}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e];}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy();}this.keyIdToKeyInfo={};}createKeyLoadError(e,t=M.KEY_LOAD_ERROR,i,r,n){return new xi({type:ie.NETWORK_ERROR,details:t,fatal:false,frag:e,response:n,error:i,networkDetails:r})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,n=t.length;r<n;r++){let o=t[r];if(e.cc<=o.cc&&(!at(e)||!at(o)||e.sn<o.sn)||!i&&r==n-1)return this.emeController.selectKeySystemFormat(o).then(a=>{if(!this.emeController)return;o.setKeyFormat(a);let l=Bu(a);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let r=al(this.config);if(r.length)return this.emeController.getKeySystemAccess(r)}}return null}load(e){return !e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,d))}let o=n.uri;if(!o)return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${o}"`)));let a=Cp(n),l=this.keyIdToKeyInfo[a];if((i=l)!=null&&i.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(r=l)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case "usable":case "usable-in-future":return l.keyLoadPromise.then(c=>{let{keyInfo:u}=c;return n.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${n.keyId?" keyId: "+It(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case "SAMPLE-AES":case "SAMPLE-AES-CENC":case "SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case "AES-128":case "AES-256":case "AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){let o=ok(t.initSegment.data);if(o.length){let a=o[0];a.some(l=>l!==0)?(this.log(`Using keyId found in init segment ${It(a)}`),vo.setKeyIdForUri(e.decryptdata.uri,a)):(a=vo.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${It(a)}`)),e.decryptdata.keyId=a;}}if(!e.decryptdata.keyId&&!at(t))return Promise.resolve(i);let n=this.emeController.loadKey(i);return (e.keyLoadPromise=n.then(o=>(e.mediaKeySessionContext=o,i))).catch(o=>{throw e.keyLoadPromise=null,"data"in o&&(o.data.frag=t),o})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,r=i.loader,n=new r(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((o,a)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=i.keyLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,m,p)=>{let{frag:g,keyInfo:E}=m,y=Cp(E.decryptdata);if(!g.decryptdata||E!==this.keyIdToKeyInfo[y])return a(this.createKeyLoadError(g,M.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));E.decryptdata.key=g.decryptdata.key=new Uint8Array(h.data),g.keyLoader=null,E.loader=null,o({frag:g,keyInfo:E});},onError:(h,f,m,p)=>{this.resetLoader(f),a(this.createKeyLoadError(t,M.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,Oe({url:l.url,data:void 0},h)));},onTimeout:(h,f,m)=>{this.resetLoader(f),a(this.createKeyLoadError(t,M.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m));},onAbort:(h,f,m)=>{this.resetLoader(f),a(this.createKeyLoadError(t,M.INTERNAL_ABORTED,new Error("key loading aborted"),m));}};n.load(l,c,u);})}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null);let o=Cp(i.decryptdata)||r;delete this.keyIdToKeyInfo[o],n&&n.destroy();}};function Cp(s){if(s.keyFormat!==xt.FAIRPLAY){let e=s.keyId;if(e)return It(e)}return s.uri}function M_(s){let{type:e}=s;switch(e){case Te.AUDIO_TRACK:return J.AUDIO;case Te.SUBTITLE_TRACK:return J.SUBTITLE;default:return J.MAIN}}function Dp(s,e){let t=s.url;return (t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Xg=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners();}startLoad(e){}stopLoad(){this.destroyInternalLoaders();}registerListeners(){let{hls:e}=this;e.on(v.MANIFEST_LOADING,this.onManifestLoading,this),e.on(v.LEVEL_LOADING,this.onLevelLoading,this),e.on(v.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(v.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this);}unregisterListeners(){let{hls:e}=this;e.off(v.MANIFEST_LOADING,this.onManifestLoading,this),e.off(v.LEVEL_LOADING,this.onLevelLoading,this),e.off(v.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(v.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this);}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,r=t.loader,n=i||r,o=new n(t);return this.loaders[e.type]=o,o}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e];}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e);}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders();}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Te.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null});}onLevelLoading(e,t){let{id:i,level:r,pathwayId:n,url:o,deliveryDirectives:a,levelInfo:l}=t;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:Te.LEVEL,url:o,deliveryDirectives:a,levelOrTrack:l});}onAudioTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:o,track:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:Te.AUDIO_TRACK,url:n,deliveryDirectives:o,levelOrTrack:a});}onSubtitleTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:o,track:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:Te.SUBTITLE_TRACK,url:n,deliveryDirectives:o,levelOrTrack:a});}onLevelsUpdated(e,t){let i=this.loaders[Te.LEVEL];if(i){let r=i.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(i.abort(),delete this.loaders[Te.LEVEL]);}}load(e){var t;let i=this.hls.config,r=this.getInternalLoader(e);if(r){let d=this.hls.logger,c=r.context;if(c&&c.levelOrTrack===e.levelOrTrack&&(c.url===e.url||c.deliveryDirectives&&!e.deliveryDirectives)){c.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${c.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort();}let n;if(e.type===Te.MANIFEST?n=i.manifestLoadPolicy.default:n=Be({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),Q((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===Te.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Te.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Te.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){let c=d.partTarget,u=d.targetduration;if(c&&u){let h=Math.max(c*3,u*.8)*1e3;n=Be({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)});}}}let o=n.errorRetry||n.timeoutRetry||{},a={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(d,c,u,h)=>{let f=this.getInternalLoader(u);this.resetInternalLoader(u.type);let m=d.data;c.parsing.start=performance.now(),Qr.isMediaPlaylist(m)||u.type!==Te.MANIFEST?this.handleTrackOrLevelPlaylist(d,c,u,h||null,f):this.handleMasterPlaylist(d,c,u,h);},onError:(d,c,u,h)=>{this.handleNetworkError(c,u,false,d,h);},onTimeout:(d,c,u)=>{this.handleNetworkError(c,u,true,void 0,d);}};r.load(e,a,l);}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t));}handleMasterPlaylist(e,t,i,r){let n=this.hls,o=e.data,a=Dp(e,i),l=Qr.parseMasterPlaylist(o,a);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}let{contentSteering:d,levels:c,sessionData:u,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m,c.forEach(y=>{let{unknownCodecs:_}=y;if(_){let{preferManagedMediaSource:S}=this.hls.config,{audioCodec:L,videoCodec:O}=y;for(let R=_.length;R--;){let D=_[R];fl(D,"audio",S)?(y.audioCodec=L=L?`${L},${D}`:D,go.audio[L.substring(0,4)]=2,_.splice(R,1)):fl(D,"video",S)&&(y.videoCodec=O=O?`${O},${D}`:D,go.video[O.substring(0,4)]=2,_.splice(R,1));}}});let{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":E}=Qr.parseMasterPlaylistMedia(o,a,l);p.length&&!p.some(_=>!_.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:false,autoselect:false,forced:false,id:-1,attrs:new Je({}),bitrate:0,url:""})),n.trigger(v.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:g,captions:E,contentSteering:d,url:a,stats:t,networkDetails:r,sessionData:u,sessionKeys:h,startTimeOffset:f,variableList:m});}handleTrackOrLevelPlaylist(e,t,i,r,n){let o=this.hls,{id:a,level:l,type:d}=i,c=Dp(e,i),u=Q(l)?l:Q(a)?a:0,h=M_(i),f=Qr.parseLevelPlaylist(e.data,c,u,h,0,this.variableList);if(d===Te.MANIFEST){let m={attrs:new Je({}),bitrate:0,details:f,name:"",url:c};f.requestScheduled=t.loading.start+lT(f,0),o.trigger(v.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:c,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null});}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,r,n);}handleManifestParsingError(e,t,i,r,n){this.hls.trigger(v.ERROR,{type:ie.NETWORK_ERROR,details:M.MANIFEST_PARSING_ERROR,fatal:t.type===Te.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n});}handleNetworkError(e,t,i=false,r,n){let o=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===Te.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===Te.AUDIO_TRACK||e.type===Te.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);let a=new Error(o);this.hls.logger.warn(`[playlist-loader]: ${o}`);let l=M.UNKNOWN,d=false,c=this.getInternalLoader(e);switch(e.type){case Te.MANIFEST:l=i?M.MANIFEST_LOAD_TIMEOUT:M.MANIFEST_LOAD_ERROR,d=true;break;case Te.LEVEL:l=i?M.LEVEL_LOAD_TIMEOUT:M.LEVEL_LOAD_ERROR,d=false;break;case Te.AUDIO_TRACK:l=i?M.AUDIO_TRACK_LOAD_TIMEOUT:M.AUDIO_TRACK_LOAD_ERROR,d=false;break;case Te.SUBTITLE_TRACK:l=i?M.SUBTITLE_TRACK_LOAD_TIMEOUT:M.SUBTITLE_LOAD_ERROR,d=false;break}c&&this.resetInternalLoader(e.type);let u={type:ie.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:c,context:e,error:a,networkDetails:t,stats:n};if(r){let h=t?.url||e.url;u.response=Oe({url:h,data:void 0},r);}this.hls.trigger(v.ERROR,u);}handlePlaylistLoaded(e,t,i,r,n,o){let a=this.hls,{type:l,level:d,levelOrTrack:c,id:u,groupId:h,deliveryDirectives:f}=r,m=Dp(t,r),p=M_(r),g=typeof r.level=="number"&&p===J.MAIN?d:void 0,E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!a.config.ignorePlaylistParsingErrors){a.trigger(v.ERROR,{type:ie.NETWORK_ERROR,details:M.LEVEL_PARSING_ERROR,fatal:false,url:m,error:E,reason:E.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:i});return}e.playlistParsingError=null;}if(!e.fragments.length){let y=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(v.ERROR,{type:ie.NETWORK_ERROR,details:M.LEVEL_EMPTY_ERROR,fatal:false,url:m,error:y,reason:y.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:i});return}switch(e.live&&o&&(o.getCacheAge&&(e.ageHeader=o.getCacheAge()||0),(!o.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Te.MANIFEST:case Te.LEVEL:if(g){if(!c)g=0;else if(c!==a.levels[g]){let y=a.levels.indexOf(c);y>-1&&(g=y);}}a.trigger(v.LEVEL_LOADED,{details:e,levelInfo:c||a.levels[0],level:g||0,id:u||0,stats:i,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===Te.MANIFEST});break;case Te.AUDIO_TRACK:a.trigger(v.AUDIO_TRACK_LOADED,{details:e,track:c,id:u||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f});break;case Te.SUBTITLE_TRACK:a.trigger(v.SUBTITLE_TRACK_LOADED,{details:e,track:c,id:u||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f});break}}},ls=class s{static get version(){return El}static isMSESupported(){return tS()}static isSupported(){return VD()}static getMediaSource(){return sr()}static get Events(){return v}static get MetadataSchema(){return si}static get ErrorTypes(){return ie}static get ErrorDetails(){return M}static get DefaultConfig(){return s.defaultConfig?s.defaultConfig:UD}static set DefaultConfig(e){s.defaultConfig=e;}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new n0,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=false;let t=this.logger=zR(e.debug||false,"Hls instance",e.assetPlayerId),i=this.config=FD(s.DefaultConfig,e,t);this.userConfig=e,i.progressive&&$D(i,t);let{abrController:r,bufferController:n,capLevelController:o,errorController:a,fpsController:l}=i,d=new a(this),c=this.abrController=new r(this),u=new Gp(this),h=i.interstitialsController,f=h?this.interstitialsController=new h(this,s):null,m=this.bufferController=new n(this,u),p=this.capLevelController=new o(this),g=new l(this),E=new Xg(this),y=i.contentSteeringController,_=y?new y(this):null,S=this.levelController=new Yg(this,_),L=new qg(this),O=new Qg(this.config,this.logger),R=this.streamController=new zg(this,u,O),D=this.gapController=new Vg(this,u);p.setStreamController(R),g.setStreamController(R);let C=[E,S,R];f&&C.splice(1,0,f),_&&C.splice(1,0,_),this.networkControllers=C;let k=[c,m,D,p,g,L,u];this.audioTrackController=this.createController(i.audioTrackController,C);let H=i.audioStreamController;H&&C.push(this.audioStreamController=new H(this,u,O)),this.subtitleTrackController=this.createController(i.subtitleTrackController,C);let q=i.subtitleStreamController;q&&C.push(this.subtititleStreamController=new q(this,u,O)),this.createController(i.timelineController,k),O.emeController=this.emeController=this.createController(i.emeController,k),this.cmcdController=this.createController(i.cmcdController,k),this.latencyController=this.createController(jg,k),this.coreComponents=k,C.push(d);let j=d.onErrorOut;typeof j=="function"&&this.on(v.ERROR,j,d),this.on(v.MANIFEST_LOADED,E.onManifestLoaded,E);}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i);}once(e,t,i=this){this._emitter.once(e,t,i);}removeAllListeners(e){this._emitter.removeAllListeners(e);}off(e,t,i=this,r){this._emitter.off(e,t,i,r);}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=true;let r=e===v.ERROR;this.trigger(v.ERROR,{type:ie.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=false;}}return false}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(v.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null;}attachMedia(e){if(!e||"media"in e&&!e.media){let n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(v.ERROR,{type:ie.OTHER_ERROR,details:M.ATTACH_MEDIA_ERROR,fatal:true,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,r=t?e:{media:i};this._media=i,this.trigger(v.MEDIA_ATTACHING,r);}detachMedia(){this.logger.log("detachMedia"),this.trigger(v.MEDIA_DETACHING,{}),this._media=null;}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(v.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,i=this._url,r=this._url=Zg.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:true});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(v.MANIFEST_LOADING,{url:e});}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=true,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=false;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering();}));}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering();}));}get inFlightFragments(){let e={[J.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[J.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[J.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec();}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t));}removeLevel(e){this.levelController.removeLevel(e);}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=rD()),e}get levels(){let e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch();}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch();}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e;}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e;}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e;}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e;}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t);}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e);}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated());}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Lk(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated());}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){let o=e[n].attrs["HDCP-LEVEL"];if(o&&o<=i)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e;}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return ((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return ((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e);}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e);}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:false}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e);}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e;}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e;}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e;}get bufferedToEnd(){var e;return !!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return ((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){let i=z_(t);return j_(e,i,navigator.mediaCapabilities)}};ls.defaultConfig=void 0;var iS="important",jD=" !"+iS,Lt=jo(class extends un{constructor(s){if(super(s),s.type!==md.ATTRIBUTE||s.name!=="style"||s.strings?.length>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(s){return Object.keys(s).reduce((e,t)=>{let i=s[t];return i==null?e:e+`${t=t.includes("-")?t:t.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,"-$&").toLowerCase()}:${i};`},"")}update(s,[e]){let{style:t}=s.element;if(this.ft===void 0)return this.ft=new Set(Object.keys(e)),this.render(e);for(let i of this.ft)e[i]==null&&(this.ft.delete(i),i.includes("-")?t.removeProperty(i):t[i]=null);for(let i in e){let r=e[i];if(r!=null){this.ft.add(i);let n=typeof r=="string"&&r.endsWith(jD);i.includes("-")||n?t.setProperty(i,n?r.slice(0,-11):r,n?iS:""):t[i]=r;}}return vs}});var rS=Symbol.for(""),YD=s=>{if(s?.r===rS)return s?._$litStatic$},p0=s=>({_$litStatic$:s,r:rS});var sS=new Map,g0=s=>(e,...t)=>{let i=t.length,r,n,o=[],a=[],l,d=0,c=false;for(;d<i;){for(l=e[d];d<i&&(n=t[d],(r=YD(n))!==void 0);)l+=r+e[++d],c=true;d!==i&&a.push(n),o.push(l),d++;}if(d===i&&o.push(e[i]),c){let u=o.join("$$lit$$");(e=sS.get(u))===void 0&&(o.raw=o,sS.set(u,e=o)),t=a;}return s(e,...t)},nS=g0(ne);function yo(){return typeof document>"u"?"":new URL(import.meta.url).pathname.includes("+esm")?"dist/":""}var v0=["default","synthwave","dolphin"],zD={default:()=>import('./default-OIQBJJAX.js'),synthwave:()=>import('./synthwave-X45G4Z3J.js'),dolphin:()=>import('./dolphin-JJOJS5EI.js')};async function QD(s){if(!v0.includes(s))return;let e=!!yo();if(!e){let r=zD[s];if(r)try{return await r()}catch{}}let t=e?`./dist/themes/${s}.js`:`./themes/${s}.js`,i=new URL(t,import.meta.url).href;return bh(i)}async function bh(s){return import(s)}var bo=class s{constructor(){this.themes=[];}static async get(e,t){if(s.instance||(s.instance=new s),s.instance.themes.find(i=>i.name===e))return s.instance.currentTheme=e,Promise.resolve(s.instance);s.instance.themes.push({name:e}),s.instance.currentTheme=e;try{if(typeof document<"u"&&!v0.includes(e)){let i=document.createElement("link");i.rel="stylesheet",i.href=`${t}/${e}.css`,document.head.appendChild(i);}}catch(i){console.log("[mave-player]: theme css not loaded",i);}try{if(t&&!v0.includes(e)){let{build:i}=await bh(`${t}/${e}.js`);i(e,nt,ne,it);}else {let i=await QD(e);if(i)i.build(e,nt,ne,it);else {let r=`./${yo()}themes/${e}.js`,{build:n}=await bh(r);n(e,nt,ne,it);}}}catch(i){console.log("[mave-player]: theme not loaded",i);}return Promise.resolve(s.instance)}static async external(e){s.instance||(s.instance=new s);let t=e.split("/").pop()?.replace(".js","")||"";try{if(typeof document<"u"){let i=document.createElement("link");i.rel="stylesheet",i.href=`${e.replace(".js","")}.css`,document.head.appendChild(i);}}catch(i){console.log("[mave-player]: theme css not loaded",i);}if(s.instance.themes.find(i=>i.name===t))return s.instance.currentTheme=t,Promise.resolve(s.instance);s.instance.themes.push({name:t}),s.instance.currentTheme=t;try{let{build:i}=await bh(e);i(t,nt,ne,it);}catch(i){console.log("[mave-player]: theme not loaded",i);}return Promise.resolve(s.instance)}static getTheme(){return s.instance?s.instance.currentTheme:""}};var Al="lit-localize-status";var oS=s=>typeof s!="string"&&"strTag"in s,_h=(s,e,t)=>{let i=s[0];for(let r=1;r<s.length;r++)i+=e[t?t[r-1]:r-1],i+=s[r];return i};var Il=(s=>oS(s)?_h(s.strings,s.values):s);var lt=Il,aS=false;function E0(s){if(aS)throw new Error("lit-localize can only be configured once");lt=s,aS=true;}var y0=class{constructor(e){this.__litLocalizeEventHandler=t=>{t.detail.status==="ready"&&this.host.requestUpdate();},this.host=e;}hostConnected(){window.addEventListener(Al,this.__litLocalizeEventHandler);}hostDisconnected(){window.removeEventListener(Al,this.__litLocalizeEventHandler);}},XD=s=>s.addController(new y0(s)),lS=XD;var xl=()=>(s,e)=>(s.addInitializer(lS),s);var Ll=class{constructor(){this.settled=false,this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t;});}resolve(e){this.settled=true,this._resolve(e);}reject(e){this.settled=true,this._reject(e);}};var ws=[];for(let s=0;s<256;s++)ws[s]=(s>>4&15).toString(16)+(s&15).toString(16);function dS(s){let e=0,t=8997,i=0,r=33826,n=0,o=40164,a=0,l=52210;for(let d=0;d<s.length;d++)t^=s.charCodeAt(d),e=t*435,i=r*435,n=o*435,a=l*435,n+=t<<8,a+=r<<8,i+=e>>>16,t=e&65535,n+=i>>>16,r=i&65535,l=a+(n>>>16)&65535,o=n&65535;return ws[l>>8]+ws[l&255]+ws[o>>8]+ws[o&255]+ws[r>>8]+ws[r&255]+ws[t>>8]+ws[t&255]}var ZD="",JD="h",e1="s";function cS(s,e){return (e?JD:e1)+dS(typeof s=="string"?s:s.join(ZD))}var uS=new WeakMap,hS=new Map;function fS(s,e,t){if(s){let i=t?.id??t1(e),r=s[i];if(r){if(typeof r=="string")return r;if("strTag"in r)return _h(r.strings,e.values,r.values);{let n=uS.get(r);return n===void 0&&(n=r.values,uS.set(r,n)),{...r,values:n.map(o=>e.values[o])}}}}return Il(e)}function t1(s){let e=typeof s=="string"?s:s.strings,t=hS.get(e);return t===void 0&&(t=cS(e,typeof s!="string"&&!("strTag"in s)),hS.set(e,t)),t}function b0(s){window.dispatchEvent(new CustomEvent(Al,{detail:s}));}var Sh="",_0,mS,Ah,T0,pS,tn=new Ll;tn.resolve();var Th=0,gS=s=>(E0(((e,t)=>fS(pS,e,t))),Sh=mS=s.sourceLocale,Ah=new Set(s.targetLocales),Ah.add(s.sourceLocale),T0=s.loadLocale,{getLocale:i1,setLocale:s1}),i1=()=>Sh,s1=s=>{if(s===(_0??Sh))return tn.promise;if(!Ah||!T0)throw new Error("Internal error");if(!Ah.has(s))throw new Error("Invalid locale code");Th++;let e=Th;return _0=s,tn.settled&&(tn=new Ll),b0({status:"loading",loadingLocale:s}),(s===mS?Promise.resolve({templates:void 0}):T0(s)).then(i=>{Th===e&&(Sh=s,_0=void 0,pS=i.templates,b0({status:"ready",readyLocale:s}),tn.resolve());},i=>{Th===e&&(b0({status:"error",errorLocale:s,errorMessage:i.toString()}),tn.reject(i));}),tn.promise};var r1={en:()=>import('./en-H7UBETC6.js'),nl:()=>import('./nl-CPFN66G7.js'),de:()=>import('./de-AM53RBF2.js'),fr:()=>import('./fr-2IL2CZKO.js')};function n1(s){return r1[s]}async function vS(s){let e=yo();if(!e)return null;try{return await import(new URL(`./${e}generated/locales/${s}.js`,import.meta.url).href)}catch{return null}}var o1=gS({sourceLocale:"default",targetLocales:["en","nl","de","fr"],loadLocale:async s=>{if(yo()){let i=await vS(s);if(i)return i}let e=n1(s);if(e)try{return await e()}catch(i){console.error(`[mave-player]: failed to load locale ${s}`,i);}let t=await vS(s);return t||(console.log(`[mave-player]: locale not loaded for ${s}`),null)}}),S0=false,_o=class{constructor(e){this._onLoad=e=>{e.detail.status==="loading"?S0=false:e.detail.status==="ready"&&(S0=true),this.host.requestUpdate();};this.host=e,e.addController(this);}get loaded(){return S0}set locale(e){this._locale!==e&&(o1.setLocale(e),this.host.requestUpdate());}get locale(){return this._locale}hostConnected(){typeof window<"u"&&window.addEventListener("lit-localize-status",this._onLoad);}hostDisconnected(){typeof window<"u"&&window.removeEventListener("lit-localize-status",this._onLoad);}};var $,ES,yS,Ih,bS,_S,A0,TS,SS,I0,AS,IS,x0,xh,xS,LS,RS,kS,L0,R0,k0,Lh,wS,w0,C0,CS,D0,Rh,M0,Rl,DS,P0,MS,kh,PS,OS,US,wh,NS,FS,$S,BS,HS,GS,KS,To,Ch,VS,WS,Se=class extends Ei{constructor(){super(...arguments);e(this,$);this._controls=["play","time","seek","volume","audiotracks","fullscreen","subtitles"];this.popped=false;this._isProcessing=false;this._startedPlaying=false;this._audioTrackCount=0;this._hlsAudioTracks=[];this._hlsAudioTrackIdMap=new Map;this._intersectionObserver=new ln(this,{callback:g(this,$,RS).bind(this)});this.embedController=new Mi(this);this._intersected=false;this._queue=[];this.languageController=new _o(this);}get embed(){return this._embedId}set embed(t){this._embedId!=t&&(this._embedId=t,this.embedController.embed=this.embed,this.updateStylePoster(),this.loadTheme());}get token(){return this._token}set token(t){this._token!=t&&(this._token=t,this.requestUpdate("token"),this.embedController.token=this._token);}set loop(t){this._loop=(t===""||t=="true"||t==true)??false;}get loop(){return this._loop}get controls(){return this._controls}set controls(t){typeof t=="string"?this._controls=t.split(" "):Array.isArray(t)?this._controls=t:this._controls=[],this.requestUpdate("controls");}get cache(){return this._cache}set cache(t){this._cache!=t&&(typeof t=="string"?this._cache=t==="true"||t==="":this._cache=false,this.requestUpdate("caching"),this.embedController.caching=this._cache);}get quality(){return this._quality}set quality(t){this._quality!=t&&(this._quality=t);}get theme(){return this._theme||"default"}set theme(t){this._theme!=t&&(this._theme=t,this.requestUpdate("theme"),this.loadTheme());}get poster(){return !this.embed||!this._embedObj||!g(this,$,x0).call(this,"thumbnail","jpg")?null:this._poster&&this._poster=="custom"?this.embedController.embedFile(g(this,$,xh).call(this,"custom_thumbnail")):this._poster&&(!Number.isNaN(parseFloat(this._poster))||!Number.isNaN(parseInt(this._poster)))?this._embedObj.poster&&this._embedObj.poster.renditions&&this._embedObj.poster.renditions.find(t=>t.type=="custom_thumbnail")?this.embedController.embedFile(g(this,$,xh).call(this,"custom_thumbnail")):`https://image.mave.io/${this.embedController.spaceId}${this.embedController.embedId}.jpg?time=${this._poster}`:this._poster?this._poster:this.embedController.embedFile(g(this,$,xh).call(this,"thumbnail"))}set poster(t){t&&(this._poster=t,this.requestUpdate("poster"));}pop(){this.popped=true;}close(){this.popped=false;}set muted(t){let i=(t===""||t=="true"||t==true)??false;this._videoElement?this._videoElement.muted=i:this._queue.push(()=>this._videoElement.muted=i);}get muted(){return this._videoElement?.muted||false}set currentTime(t){this._videoElement?this._videoElement.currentTime=t:this._queue.push(()=>this._videoElement.currentTime=t);}get currentTime(){return this._videoElement?this._videoElement?.currentTime:0}get duration(){return new Promise((t,i)=>{if(this._videoElement&&!isNaN(this._videoElement.duration))return t(this._videoElement.duration);let r=()=>{this._videoElement?.addEventListener("loadedmetadata",()=>{this._videoElement&&t(this._videoElement.duration);}),this._videoElement?.addEventListener("error",()=>{i(new Error("Failed to load video metadata."));});};this._videoElement?r():this.addEventListener("mave:video_element_ready",()=>{r();});})}get paused(){return this._videoElement?this._videoElement.paused:true}play(){this._videoElement&&!this.embedController.loading?g(this,$,Lh).call(this):this._queue.push(()=>g(this,$,Lh).call(this));}restart(){this._videoElement&&(this.pause(),this._videoElement.currentTime=0,this.play());}pause(){this._videoElement?this._videoElement.pause():this._queue.push(()=>this._videoElement?.pause());}updateStylePoster(){this.poster&&this.style.setProperty("background",`center / contain no-repeat url(${this.poster})`);}connectedCallback(){super.connectedCallback(),this.languageController.locale=this.locale||"en",this.loadTheme(),typeof window<"u"&&window.matchMedia&&(this._contrastQuery=window.matchMedia("(prefers-contrast: more)"),this._contrastQueryHandler=()=>{this._controlColorsKey=void 0,this._controlColors=void 0,this.requestUpdate();},this._contrastQuery.addEventListener?this._contrastQuery.addEventListener("change",this._contrastQueryHandler):this._contrastQuery.addListener&&this._contrastQuery.addListener(this._contrastQueryHandler)),this.addEventListener("mave:video_element_ready",g(this,$,yS).bind(this));}requestUpdate(t,i){t==="locale"&&(this.languageController.locale=this.locale||"en"),super.requestUpdate(t,i);}disconnectedCallback(){super.disconnectedCallback(),this._contrastQuery&&this._contrastQueryHandler&&(this._contrastQuery.removeEventListener?this._contrastQuery.removeEventListener("change",this._contrastQueryHandler):this._contrastQuery.removeListener&&this._contrastQuery.removeListener(this._contrastQueryHandler)),this._contrastQuery=void 0,this._contrastQueryHandler=void 0,this._metricsInstance?.demonitor(),g(this,$,I0).call(this),this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],this._currentAudioTrackMenu=void 0,this._themeMutationObserver?.disconnect(),this._themeMutationObserver=void 0,this._themeMutationObserverRoot=void 0;}loadTheme(){this.embed&&this._themeLoaded!=this.theme&&(this.theme&&this.theme.endsWith(".js")?bo.external(this.theme):bo.get(this.theme,`${this.embedController.cdnRoot}/themes/player`),this._themeLoaded=bo.getTheme());}updateEmbed(t){this._embedObj=t,this._audioTrackCount=t.audio_tracks?.length??0,this.updateStylePoster(),g(this,$,Ih).call(this),this.poster=this._embedObj.settings.poster,this.attributes.getNamedItem("color")||(this.color=this._embedObj.settings.color),this.attributes.getNamedItem("opacity")||(this.opacity=this._embedObj.settings.opacity?this._embedObj.settings.opacity:void 0),this.attributes.getNamedItem("aspect-ratio")||(this.aspect_ratio=this._embedObj.settings.aspect_ratio),this.attributes.getNamedItem("width")||(this.width=this._embedObj.settings.width),this.attributes.getNamedItem("height")||(this.height=this._embedObj.settings.height),this.attributes.getNamedItem("autoplay")||(this.autoplay=this._embedObj.settings.autoplay=="on_show"?"lazy":this._embedObj.settings.autoplay),this.attributes.getNamedItem("controls")||(this.controls=this._embedObj.settings.controls),this.attributes.getNamedItem("loop")||(this.loop=this._embedObj.settings.loop);}get styles(){let t={},i=!!this._embedObj?.subtitles?.length,r=this.subtitles==="none"||this.subtitles==="off"||!i,n=this.controls.includes("volume")||this.controls.includes("full"),o=this.color||this._embedObj?.settings.color,a=this.opacity||this._embedObj?.settings.opacity,l=o?`${o}${a||""}`:void 0;if(l){t["--primary-color"]=l;let f=g(this,$,DS).call(this,l);f&&(t["--mave-control-bg"]=f.bg,t["--mave-control-fg"]=f.fg,t["--mave-control-fg-muted"]=f.fgMuted,t["--mave-control-fg-weak"]=f.fgWeak,t["--media-control-background"]=f.bg,t["--media-menu-background"]=f.bg,t["--media-settings-menu-background"]=f.bg);}else g(this,$,P0).call(this)&&(t["--mave-control-bg"]="rgba(0, 0, 0, 0.85)",t["--mave-control-fg"]="rgb(255, 255, 255)",t["--mave-control-fg-muted"]="rgba(255, 255, 255, 0.85)",t["--mave-control-fg-weak"]="rgba(255, 255, 255, 0.6)");if(this.aspect_ratio=="auto"||this._embedObj?.settings.aspect_ratio=="auto"&&!this.aspect_ratio?t["--aspect-ratio"]=this._embedObj?.video.aspect_ratio:t["--aspect-ratio"]=this.aspect_ratio||this._embedObj?.settings.aspect_ratio,(this.width||this._embedObj?.settings.width)&&(t["--width"]=this.width||this._embedObj?.settings.width),(this.height||this._embedObj?.settings.height)&&(t["--height"]=this.height||this._embedObj?.settings.height),!this.controls.includes("full")&&!this.controls.includes("big")&&!this.controls.includes("none")){t["--play-display"]=this.controls.includes("play")?"flex":"none",t["--time-display"]=this.controls.includes("time")?"flex":"none",t["--seek-bar-visibility"]=this.controls.includes("seek")?"visible":"hidden",t["--volume-display"]=this.controls.includes("volume")?"flex":"none",t["--fullscreen-display"]=this.controls.includes("fullscreen")?"flex":"none";let f=this.controls.includes("subtitles")?"flex":"none";t["--media-captions-menu-button-display"]=f,t["--mave-captions-menu-button-display"]=f;}t["--playbackrate-display"]=this.controls.includes("rate")?"flex":"none",(r||this._embedObj?.created_at<1740674988&&!this.subtitles&&!this.active_subtitle)&&(t["--media-captions-menu-button-display"]="none",t["--mave-captions-menu-button-display"]="none"),this.controls.includes("full")||this._embedObj?.settings.controls=="full"&&!this.controls.includes("big")&&!this.controls.includes("none")?t["--media-control-bar-display"]="flex":t["--media-control-bar-display"]="none",this.controls.includes("big")||this._embedObj?.settings.controls=="big"&&!this.controls.includes("full")&&!this.controls.includes("none")?t["--big-button-display"]="flex":t["--big-button-display"]="none",this._embedObj?.video.audio===false?t["--media-mute-button-display"]="none":n?t["--media-mute-button-display"]="flex":t["--media-mute-button-display"]="none";let d=this._audioTrackCount??0,c=this.controls.includes("audiotracks")||this.controls.includes("full"),u=this.audioTracks??"auto",h=c&&d>1;return u==="off"?h=false:u==="on"&&(h=c&&d>0),t["--media-audio-track-menu-button-display"]=h?"flex":"none",Lt(t)}render(){if(!this.embed)return;let t=this.querySelector('[slot="start-screen"], [data-slot="start-screen"]');return ne`
1965
+ <slot
1966
+ name="video"
1967
+ style=${Lt({display:t&&!this._startedPlaying&&!this._isProcessing?"none":"block"})}
1968
+ >
1969
+ ${this.embedController.render({pending:()=>Ce,error:()=>g(this,$,GS).call(this),complete:i=>{if(!i)return g(this,$,HS).call(this);let r=i;return this._embedObj=r,this.updateEmbed(r),g(this,$,KS).call(this)}})}
1970
+ </slot>
1971
+ ${this._embedObj&&this._isProcessing?g(this,$,BS).call(this,this._embedObj?.video?.status):Ce}
1972
+ <slot name="start-screen"></slot>
1973
+ <slot name="end-screen"></slot>
1974
+ <slot name="hover-screen"></slot>
1975
+ `}};$=new WeakSet,ES=function(t,i){let r=new URL(i);if(this.token&&!r.searchParams.get("token")){let n=new URLSearchParams;n.append("token",this.token),r.search=n.toString();}t.open("GET",r.toString());},yS=function(){this._videoElement?.addEventListener("webkitbeginfullscreen",()=>{this.style.setProperty("--subtitle-opacity","1");}),this._videoElement?.addEventListener("webkitendfullscreen",()=>{this.style.setProperty("--subtitle-opacity","0");});},Ih=function(){if(!this._embedObj)return;let t=g(this,$,A0).call(this),i=typeof t=="string",r=!g(this,$,bS).call(this),n=g(this,$,TS).call(this,t),o=i&&g(this,$,_S).call(this);n&&r?g(this,$,SS).call(this):g(this,$,I0).call(this);let a=i&&n&&(r||o);this._isProcessing!==a&&(this._isProcessing=a,this.requestUpdate());},bS=function(){let t=this._embedObj?.video;if(!t)return false;let i=Array.isArray(t.renditions)?t.renditions:[],r=i.some(o=>o.container==="hls"&&o.type==="video"),n=i.some(o=>o.container==="mp4"&&o.type==="video");return r||n||!!t.original},_S=function(){if(this._videoElement){let i=this._videoElement.duration,r=this._videoElement.readyState;return !isFinite(i)||i<=0||r<=Se.METADATA_READY_STATES.HAVE_METADATA}let t=this._embedObj?.video?.duration;return typeof t=="number"?t<=0:false},A0=function(){return this._embedObj?.video?.status},TS=function(t=g(this,$,A0).call(this)){return typeof t=="string"?!["ready","playable"].includes(t):false},SS=function(){typeof window>"u"||this._processingRefreshHandle==null&&(this._processingRefreshHandle=window.setTimeout(()=>{this._processingRefreshHandle=void 0,this.embedController.refresh().catch(()=>{});},Se.PROCESSING_REFRESH_INTERVAL));},I0=function(){typeof window>"u"||this._processingRefreshHandle!=null&&(window.clearTimeout(this._processingRefreshHandle),this._processingRefreshHandle=void 0);},AS=function(t){let i={waiting:()=>lt("waiting for video upload..."),uploading:()=>lt("processing video..."),preparing:()=>lt("processing video..."),playable:()=>lt("processing video..."),ready:()=>lt("preparing your video..."),errored:()=>lt("video failed to process"),default:()=>lt("preparing your video...")};return (t&&i[t]?i[t]():null)??i.default()},IS=function(){if(this.hls){try{this.hls.destroy();}catch{}this.hls=void 0;}},x0=function(t,i){return this._embedObj.poster&&this._embedObj.poster.renditions&&this._embedObj.poster.renditions.find(r=>r.container===i&&r.type===t)},xh=function(t){let i=t=="custom_thumbnail"?"thumbnail":t,r=g(this,$,x0).call(this,i,"jpg");return r?`${i}.jpg${r&&r.date?`?e=${r.date}`:""}`:`${i}.jpg`},xS=function(){let t=[{name:"sd",width:640},{name:"hd",width:1280},{name:"fhd",width:1920},{name:"qhd",width:2560},{name:"uhd",width:3840}],i=t.find(r=>r.name==this.quality);return i?t.indexOf(i):2},LS=function(t){if(t&&t.tagName=="VIDEO"&&(d(this,$,To)||d(this,$,Ch))){this._videoElement=t,this.dispatchEvent(new CustomEvent("mave:video_element_ready",{detail:this._videoElement,bubbles:true,composed:true})),this._intersectionObserver.observe(this._videoElement),g(this,$,Ih).call(this),Ed.forEach(n=>{this._videoElement?.addEventListener(n,o=>{if(n=="play"&&g(this,$,kS).call(this),n=="ended"&&g(this,$,L0).call(this),n=="timeupdate"&&this._videoElement&&this._videoElement.duration-this._videoElement.currentTime<5){let a=this.querySelector('[slot="end-screen"], [data-slot="end-screen"]');if(a&&a.getAttribute("x-mave-end-shows")=="near_end"){g(this,$,L0).call(this);let l=this.querySelector("[name='mave-time-remaining']");if(l){let c=Math.floor(this._videoElement.duration-this._videoElement.currentTime);l.innerHTML=c<=0?"0":c.toString();}if(this._videoElement?.duration-this._videoElement?.currentTime<=0&&a.getAttribute("x-mave-list-trigger-next")=="true"){let c=[...document.querySelectorAll("mave-list")].find(u=>u.containsEmbed(this.embed));if(c){let u=c.getNextForEmbed(this.embed);u&&this.emit(this.EVENT_TYPES.CLICK,{embedId:u.id});}}let d=this.querySelector("[name='mave-list-next-image']");if(d){let c=[...document.querySelectorAll("mave-list")].find(u=>u.containsEmbed(this.embed));if(c){let u=c.getNextForEmbed(this.embed);if(u){let h=document.createElement("mave-img");h.setAttribute("embed",u.id),h.addEventListener("click",()=>{this.emit(this.EVENT_TYPES.CLICK,{embedId:u.id}),d.innerHTML="";}),d.appendChild(h);}else d.innerHTML="";}}}}(n==="loadedmetadata"||n==="durationchange"||n==="loadeddata"||n==="emptied"||n==="waiting"||n==="stalled"||n==="error"||n==="playing"||n==="canplay"||n==="loadstart")&&g(this,$,Ih).call(this),this.dispatchEvent(new CustomEvent(n,{detail:o,bubbles:true,composed:true}));});}),Us.config={apiEndpoint:a$1.metrics.endpoint};({video_id:this._embedObj.video.id,space_id:this._embedObj.space_id});let r=/iPhone|iPad/.test(navigator.userAgent);g(this,$,IS).call(this),ls.isSupported()&&d(this,$,To)&&!r?(this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],this.hls=new ls({startLevel:g(this,$,xS).call(this),capLevelToPlayerSize:true,xhrSetup:g(this,$,ES).bind(this),maxBufferLength:20,maxBufferSize:20,backBufferLength:60}),this.hls?.loadSource(d(this,$,To)),this.hls?.attachMedia(this._videoElement),g(this,$,M0).call(this),a$1.metrics.enabled&&(this._metricsInstance=new Us(this.hls,this.embed,{component:"player"}))):this._videoElement.canPlayType("application/vnd.apple.mpegurl")&&d(this,$,To)?(this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],this._videoElement.src=d(this,$,To),a$1.metrics.enabled&&(this._metricsInstance=new Us(this._videoElement,this.embed,{component:"player"}))):(this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],d(this,$,Ch)&&(this._videoElement.src=d(this,$,Ch)),a$1.metrics.enabled&&(this._metricsInstance=new Us(this._videoElement,this.embed,{component:"player"}))),this._queue.length&&(this._queue.forEach(n=>n()),this._queue=[]),g(this,$,k0).call(this),g(this,$,R0).call(this);}},RS=function(t){for(let{isIntersecting:i}of t)t.length&&(t[0].target.tagName=="VIDEO"||t[0].target.tagName=="MAVE-PLAYER")&&(this._intersected=i,g(this,$,k0).call(this));},kS=function(){if(this.active_subtitle&&!this._startedPlaying){let i;if(this.active_subtitle=="original"||this.subtitles=="original"){let r=this._embedObj.video.language;i=this._videoElement?.querySelector(`track[srclang="${r}"]`);}else i=this._videoElement?.querySelector(`track[srclang="${this.active_subtitle}"]`);i&&(i.track.mode="showing");}this._startedPlaying=true,g(this,$,R0).call(this),this._previousControls&&(this.controls=this._previousControls,this._previousControls=void 0);let t=this.querySelector('[slot="start-screen"], [data-slot="start-screen"]');t&&((this.shadowRoot?.querySelector("slot[name='video']")).removeAttribute("style"),this.startScreenElement.style.display="none",t.style.display="none");},L0=function(){let t=this.querySelector('[slot="end-screen"], [data-slot="end-screen"]');if(t){if(t.tagName==="TEMPLATE"){let i=t,r=i.parentElement,n=document.createElement("div");for(let o of i.attributes)n.setAttribute(o.name,o.value);n.style.display="block",n.innerHTML=i.innerHTML,r?.replaceChild(n,i);}this.endScreenElement.style.display="block",t.style.display="block",this._previousControls||(this._previousControls=this.controls),this.controls="none";}},R0=function(){let t=this.querySelector('[slot="end-screen"], [data-slot="end-screen"]');t&&(this.endScreenElement.style.display="none",t.style.display="none"),this._previousControls&&(this.controls=this._previousControls,this._previousControls=void 0);},k0=function(){this._embedObj&&this.autoplay=="always"&&this._videoElement?.paused&&(this._metricsInstance?.monitor(),this._videoElement.muted=true,this._videoElement?.play()),this._embedObj&&(this.autoplay==="lazy"||this.autoplay==="true"||this._embedObj.settings.autoplay=="on_show")&&(this._intersected?this._videoElement?.paused&&(this._metricsInstance?.monitor(),this._videoElement.muted=true,this._videoElement?.play()):this._videoElement&&!this._videoElement.paused&&this._videoElement.readyState>2&&this._videoElement?.pause());},Lh=function(){this._videoElement?.paused?(this._metricsInstance?.monitor(),this._videoElement?.play()):this._videoElement?.pause();},wS=function(t){let i=t.target.track,r=i.activeCues;if(i.mode=="showing"&&(this._currentTrackLanguage=i.language),!this._subtitlesText){let n=this.shadowRoot?.querySelector(`theme-${this._themeLoaded}`)?.shadowRoot?.querySelector("#subtitles_text");n&&(this._subtitlesText=n);}if(r.length){let n=r[0];this._subtitlesText.style.opacity="1",this._subtitlesText.style.transform="scale(1)",this._subtitlesText.innerHTML=n.text.replace(/\n/g,"<br>");}else this._subtitlesText.style.opacity="0",this._subtitlesText.style.transform="scale(0.99)";},w0=function(t){let i=this._embedObj.video.renditions.filter(o=>o.container==t),r=["sd","hd","fhd","qhd","uhd"];return !i||!i.length?void 0:i.reduce((o,a)=>r.indexOf(a.size)>r.indexOf(o.size)?a:o)},C0=function(){return this._themeLoaded?this.shadowRoot?.querySelector(`theme-${this._themeLoaded}`)?.shadowRoot??null:null},CS=function(t){if(this._themeMutationObserverRoot===t)return;this._themeMutationObserver?.disconnect();let i=new MutationObserver(()=>{g(this,$,Rh).call(this);});i.observe(t,{childList:true,subtree:true}),this._themeMutationObserver=i,this._themeMutationObserverRoot=t;},D0=function(){let t=d(this,$,C0);return t?{menu:t.querySelector("mave-audio-track-menu"),button:t.querySelector("mave-audio-track-menu-button")}:{menu:null,button:null}},Rh=function(){this._pendingAudioTrackSetup==null&&(this._pendingAudioTrackSetup=requestAnimationFrame(()=>{this._pendingAudioTrackSetup=void 0,g(this,$,M0).call(this);}));},M0=function(){if(!this.hls)return;let t=d(this,$,C0);t&&g(this,$,CS).call(this,t);let{menu:i,button:r}=g(this,$,D0).call(this);if(!i||!r){g(this,$,Rh).call(this);return}if(i!==this._currentAudioTrackMenu||!this._cleanupHlsAudioTracks){this._cleanupHlsAudioTracks?.();let a=(c,u)=>{this._hlsAudioTracks=u?.audioTracks??[],g(this,$,Rl).call(this,this._hlsAudioTracks,this.hls?.audioTrack);},l=(c,u)=>{let h=u?.id??(typeof this.hls?.audioTrack=="number"?this.hls.audioTrack:void 0);g(this,$,Rl).call(this,this._hlsAudioTracks,h);},d=c=>{if(c.type!==V.MEDIA_AUDIO_TRACK_REQUEST)return;let u=c.detail;if(u==null)return;let h=this._hlsAudioTrackIdMap.get(String(u));h==null||!this.hls||this.hls.audioTrack!==h&&(this.hls.audioTrack=h,g(this,$,Rl).call(this,this._hlsAudioTracks,h));};i.addEventListener(V.MEDIA_AUDIO_TRACK_REQUEST,d),this.hls.on(ls.Events.AUDIO_TRACKS_UPDATED,a),this.hls.on(ls.Events.AUDIO_TRACK_SWITCHED,l),this._cleanupHlsAudioTracks=()=>{i.removeEventListener(V.MEDIA_AUDIO_TRACK_REQUEST,d),this.hls?.off(ls.Events.AUDIO_TRACKS_UPDATED,a),this.hls?.off(ls.Events.AUDIO_TRACK_SWITCHED,l);},this._currentAudioTrackMenu=i,this.hls.audioTracks?.length&&(this._hlsAudioTracks=this.hls.audioTracks);}let n=(this._hlsAudioTracks&&this._hlsAudioTracks.length?this._hlsAudioTracks:this.hls.audioTracks)??[],o=typeof this.hls.audioTrack=="number"?this.hls.audioTrack:void 0;g(this,$,Rl).call(this,n,o);},Rl=function(t,i){let{menu:r,button:n}=g(this,$,D0).call(this);if(!r||!n){g(this,$,Rh).call(this);return}if(this._hlsAudioTracks=t??[],this._hlsAudioTrackIdMap.clear(),!t?.length){"tracks"in r&&(r.tracks=[],r.selected=void 0),this._audioTrackCount=0,this.requestUpdate();return}let o=t.map((l,d)=>{let c=l?.id??d,u=String(c);this._hlsAudioTrackIdMap.set(u,c);let h=l?.lang??l?.attrs?.LANGUAGE,m=(l?.name??"").trim()||typeof h=="string"&&h.trim()||`Track ${d+1}`,p=i!=null?c===i:l?.default??d===0;return {id:u,language:h,label:m,enabled:p}});!o.some(l=>l.enabled)&&o.length&&(o[0].enabled=true);let a=o.find(l=>l.enabled)??o[0];"tracks"in r&&(r.tracks=o,r.selected=a?.id),this._audioTrackCount=o.length,this.requestUpdate();},DS=function(t){if(!t)return;let i=g(this,$,P0).call(this),r=`${t}|${i?"more":"default"}`;if(this._controlColorsKey===r&&this._controlColors)return this._controlColors;let n=g(this,$,MS).call(this,t);if(!n)return;let o=i?.85:.6,a=Math.max(n.a??1,o),l=`rgba(${n.r}, ${n.g}, ${n.b}, ${a.toFixed(3)})`,d=g(this,$,OS).call(this,n.r,n.g,n.b),c=`rgb(${d.r}, ${d.g}, ${d.b})`,u=i?.78:.55,h=i?.55:.3,f=`rgba(${d.r}, ${d.g}, ${d.b}, ${u})`,m=`rgba(${d.r}, ${d.g}, ${d.b}, ${h})`,p={bg:l,fg:c,fgMuted:f,fgWeak:m};return this._controlColorsKey=r,this._controlColors=p,p},P0=function(){return this._contrastQuery?this._contrastQuery.matches:typeof window>"u"||!window.matchMedia?false:window.matchMedia("(prefers-contrast: more)").matches},MS=function(t){if(typeof document>"u"||!document.body)return;let i=document.createElement("span");i.style.color=t,i.style.position="absolute",i.style.left="-9999px",i.style.top="-9999px",i.style.opacity="0",i.style.pointerEvents="none",document.body.appendChild(i);let r=getComputedStyle(i).color;i.remove();let n=r.match(/rgba?\((.+)\)/);if(!n)return;let a=n[1].replace("/"," ").trim().split(/[\s,]+/).filter(Boolean);if(a.length<3)return;let l=g(this,$,kh).call(this,a[0]),d=g(this,$,kh).call(this,a[1]),c=g(this,$,kh).call(this,a[2]),u=a[3]?g(this,$,PS).call(this,a[3]):1;if(![l,d,c,u].some(h=>Number.isNaN(h)))return {r:l,g:d,b:c,a:u}},kh=function(t){let i=t.trim();return i.endsWith("%")?Math.round(parseFloat(i)/100*255):Math.round(parseFloat(i))},PS=function(t){let i=t.trim(),r=i.endsWith("%")?parseFloat(i)/100:parseFloat(i);return Number.isNaN(r)?1:Math.min(1,Math.max(0,r))},OS=function(t,i,r){let n=g(this,$,US).call(this,t,i,r),o=1.05/(n+.05);return (n+.05)/.05>=o?{r:0,g:0,b:0,a:1}:{r:255,g:255,b:255,a:1}},US=function(t,i,r){let n=d=>{let c=d/255;return c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4)},o=n(t),a=n(i),l=n(r);return .2126*o+.7152*a+.0722*l},wh=function(t,{showSpinner:i=true,overlay:r=false}={}){return ne`
1976
+ <div
1977
+ class=${r?"processing-wrapper processing-wrapper--overlay":"processing-wrapper"}
1978
+ style=${Lt(g(this,$,FS).call(this,r))}
1979
+ >
1980
+ <div
1981
+ class="processing-state"
1982
+ style=${Lt(g(this,$,NS).call(this))}
1983
+ >
1984
+ ${i?ne`<div class="processing-state__spinner" aria-hidden="true"></div>`:Ce}
1985
+ <span class="processing-state__text">${t}</span>
1986
+ </div>
1987
+ </div>
1988
+ `},NS=function(){let t={},i=this.poster;return i&&(t.backgroundImage=`linear-gradient(rgba(0, 0, 0, 0.65), rgba(0, 0, 0, 0.65)), url(${i})`),t},FS=function(t=false){if(t)return {};let i={width:"100%"},r=this.width??this._embedObj?.settings.width,n=this.height??this._embedObj?.settings.height;r&&r!=="auto"&&(i.width=r),n&&n!=="auto"?i.height=n:i.minHeight="200px";let o=g(this,$,$S).call(this);return o&&(i["aspect-ratio"]=o),i},$S=function(){return this.aspect_ratio&&this.aspect_ratio!=="auto"?this.aspect_ratio:this._embedObj?.settings.aspect_ratio&&this._embedObj.settings.aspect_ratio!=="auto"?this._embedObj.settings.aspect_ratio:this._embedObj?.video?.aspect_ratio?this._embedObj.video.aspect_ratio:"16 / 9"},BS=function(t){let i=t!=="errored";return g(this,$,wh).call(this,g(this,$,AS).call(this,t),{showSpinner:i,overlay:true})},HS=function(){return g(this,$,wh).call(this,lt("loading video..."))},GS=function(){return g(this,$,wh).call(this,lt("unable to load this video"),{showSpinner:false})},KS=function(){return this._embedObj?nS`<theme-${p0(this._themeLoaded)} style=${this.styles}>
1989
+ <video
1990
+ @click=${g(this,$,Lh)}
1991
+ playsinline
1992
+ ?loop=${this.loop||this._embedObj.settings.loop}
1993
+ poster=${this.poster}
1994
+ ${vd(g(this,$,LS))}
1995
+ slot="media"
1996
+ crossorigin="anonymous"
1997
+ >
1998
+ ${d(this,$,WS)} ${d(this,$,VS)}
1999
+ </video>
2000
+ </theme-${p0(this._themeLoaded)}>`:Ce},To=function(){let t=g(this,$,w0).call(this,"hls");if(t){let i=new URLSearchParams;return i.append("quality",t.size),this.embedController.embedFile("playlist.m3u8",i)}},Ch=function(){let t=g(this,$,w0).call(this,"mp4");return t?this.embedController.embedFile(`h264_${t?.size}.mp4`):this._embedObj.video.original},VS=function(){if(this._embedObj.subtitles.length>0){let t=this.shadowRoot?.querySelector(`theme-${this._themeLoaded}`)?.shadowRoot?.querySelector("media-captions-menu");return t&&new MutationObserver(r=>{r.forEach(()=>{this._subtitlesText&&t.getAttribute("mediasubtitlesshowing")&&(this._subtitlesText.style.opacity="0");});}).observe(t,{attributes:true}),this._embedObj.subtitles.map(i=>{if(this.subtitles&&this.subtitles.includes(i.language)||this.active_subtitle&&this.active_subtitle==i.language||this.subtitles=="all"||(this.subtitles=="original"||this.active_subtitle=="original")&&this._embedObj.video.language==i.language||!this.subtitles)return ne`
2001
+ <track mode="hidden" @cuechange=${g(this,$,wS)} label=${i.label} kind="subtitles" srclang=${i.language} src=${i.path}></track>
2002
+ `})}},WS=function(){return ne`<track
2003
+ label="thumbnails"
2004
+ default
2005
+ kind="metadata"
2006
+ src=${this.embedController.embedFile("storyboard.vtt")}></track>`},Se.PROCESSING_REFRESH_INTERVAL=5e3,Se.styles=it`
2007
+ :host {
2008
+ display: block;
2009
+ position: relative;
2010
+ }
2011
+
2012
+ video::cue {
2013
+ font-family: Inter, Roboto, 'Helvetica Neue', 'Arial Nova', 'Nimbus Sans', Arial,
2014
+ sans-serif;
2015
+ font-weight: 500;
2016
+ display: var(--subtitle-display, initial);
2017
+ opacity: var(--subtitle-opacity, 0);
2018
+ }
2019
+
2020
+ video::-webkit-media-text-track-display {
2021
+ transform: var(--subtitle-transform, initial);
2022
+ }
2023
+
2024
+ video:focus-visible {
2025
+ outline: 0;
2026
+ }
2027
+
2028
+ :host,
2029
+ theme-default,
2030
+ video {
2031
+ width: 100%;
2032
+ max-height: 100vh;
2033
+ }
2034
+
2035
+ slot[name='start-screen'],
2036
+ slot[name='end-screen'] {
2037
+ position: absolute;
2038
+ width: 100%;
2039
+ height: 100%;
2040
+ z-index: 99;
2041
+ top: 0;
2042
+ left: 0;
2043
+ }
2044
+
2045
+ slot[name='end-screen'] {
2046
+ display: none;
2047
+ }
2048
+
2049
+ .processing-wrapper {
2050
+ position: relative;
2051
+ width: 100%;
2052
+ height: 100%;
2053
+ }
2054
+
2055
+ .processing-wrapper--overlay {
2056
+ position: absolute;
2057
+ inset: 0;
2058
+ width: 100%;
2059
+ height: 100%;
2060
+ pointer-events: auto;
2061
+ z-index: 60;
2062
+ }
2063
+
2064
+ .processing-state {
2065
+ position: absolute;
2066
+ inset: 0;
2067
+ display: flex;
2068
+ flex-direction: column;
2069
+ align-items: center;
2070
+ justify-content: center;
2071
+ gap: 12px;
2072
+ padding: 32px 16px;
2073
+ text-align: center;
2074
+ color: #fff;
2075
+ background: rgba(0, 0, 0, 0.85);
2076
+ border-radius: inherit;
2077
+ background-size: cover;
2078
+ background-position: center;
2079
+ }
2080
+
2081
+ .processing-state__spinner {
2082
+ width: 48px;
2083
+ height: 48px;
2084
+ border-radius: 50%;
2085
+ border: 3px solid rgba(255, 255, 255, 0.25);
2086
+ border-top-color: #fff;
2087
+ animation: processing-spin 1s linear infinite;
2088
+ }
2089
+
2090
+ .processing-state__text {
2091
+ font-weight: 600;
2092
+ letter-spacing: 0.01em;
2093
+ }
2094
+
2095
+ @keyframes processing-spin {
2096
+ to {
2097
+ transform: rotate(360deg);
2098
+ }
2099
+ }
2100
+ `,Se.METADATA_READY_STATES={HAVE_NOTHING:typeof HTMLMediaElement<"u"?HTMLMediaElement.HAVE_NOTHING:0,HAVE_METADATA:typeof HTMLMediaElement<"u"?HTMLMediaElement.HAVE_METADATA:1},c([oe()],Se.prototype,"embed",1),c([oe()],Se.prototype,"token",1),c([oe()],Se.prototype,"locale",2),c([oe({attribute:"aspect-ratio"})],Se.prototype,"aspect_ratio",2),c([oe()],Se.prototype,"width",2),c([oe()],Se.prototype,"subtitles",2),c([oe({attribute:"active-subtitle"})],Se.prototype,"active_subtitle",2),c([oe()],Se.prototype,"height",2),c([oe()],Se.prototype,"autoplay",2),c([oe()],Se.prototype,"color",2),c([oe()],Se.prototype,"opacity",2),c([oe()],Se.prototype,"loop",1),c([oe()],Se.prototype,"controls",1),c([oe({attribute:"audiotracks"})],Se.prototype,"audioTracks",2),c([oe()],Se.prototype,"cache",1),c([oe()],Se.prototype,"quality",1),c([oe()],Se.prototype,"theme",1),c([oe()],Se.prototype,"poster",1),c([Ct()],Se.prototype,"popped",2),c([Ct()],Se.prototype,"_isProcessing",2),c([Di("slot[name='end-screen']")],Se.prototype,"endScreenElement",2),c([Di("slot[name='start-screen']")],Se.prototype,"startScreenElement",2),c([Ct()],Se.prototype,"_embedObj",2),c([oe()],Se.prototype,"muted",1),Se=c([xl()],Se);typeof window<"u"&&window.customElements&&(window.customElements.get("mave-player")||window.customElements.define("mave-player",Se));var Li=class extends nt{get backdrop(){return this._backdropColor||"black"}set backdrop(e){this._backdropColor!=e&&(this._backdropColor=e);}get backdropFilter(){return this._backdropFilter}set backdropFilter(e){this._backdropFilter!=e&&(this._backdropFilter=e);}get styles(){let e={"--backdrop":this.backdrop,"--backdrop-filter":this.backdropFilter};return Lt(e)}open(e){if(this._player=e,e.aspect_ratio){let[i,r]=e.aspect_ratio.split("/");this.style.setProperty("--frame-ratio-w",i),this.style.setProperty("--frame-ratio-h",r);}this.style.display="block";let t=i=>{this._frame.appendChild(e),setTimeout(()=>{this._dialog.showModal();},25),this._dialog.addEventListener("close",r=>{r.preventDefault(),this.close();},{once:true}),i(this);};return new Promise(i=>{if(this._dialog)t(i);else {let r=setInterval(()=>{this._dialog&&(t(i),clearInterval(r));},100);return}})}possibleClose(e){e.target!=this._player&&this.close();}close(){this._dialog.close(),this._backdrop.addEventListener("transitionend",()=>{this._frame.innerHTML="",this.dispatchEvent(new Event("closed",{bubbles:true}));},{once:true});}render(){return ne`
2101
+ <dialog style=${this.styles}>
2102
+ <div class="backdrop"></div>
2103
+ <div class="content" @click=${this.possibleClose}>
2104
+ <div class="wrapper">
2105
+ <slot style="display: none;"></slot>
2106
+ <div class="frame"></div>
2107
+ </div>
2108
+ </div>
2109
+ <div class="button-close" @click=${this.close}>
2110
+ <svg
2111
+ width="24px"
2112
+ height="24px"
2113
+ stroke-width="1"
2114
+ viewBox="0 0 24 24"
2115
+ fill="none"
2116
+ xmlns="http://www.w3.org/2000/svg"
2117
+ color="currentColor"
2118
+ >
2119
+ <path
2120
+ d="M6 12h6m6 0h-6m0 0V6m0 6v6"
2121
+ stroke="currentColor"
2122
+ stroke-width="1"
2123
+ stroke-linecap="round"
2124
+ stroke-linejoin="round"
2125
+ ></path>
2126
+ </svg>
2127
+ </div>
2128
+ </dialog>
2129
+ `}};Li.styles=it`
2130
+ :host {
2131
+ all: initial;
2132
+ --backdrop: black;
2133
+ --frame-max-height: 100vh;
2134
+ --frame-ratio-w: 16;
2135
+ --frame-ratio-h: 9;
2136
+ --backdrop-filter: blur(0);
2137
+ }
2138
+
2139
+ slot {
2140
+ all: initial;
2141
+ position: fixed;
2142
+ }
2143
+
2144
+ dialog {
2145
+ display: block;
2146
+ margin: 0;
2147
+ padding: 0;
2148
+ border: 0;
2149
+ pointer-events: none;
2150
+ background: transparent;
2151
+ }
2152
+
2153
+ dialog .content {
2154
+ position: fixed;
2155
+ width: 100vw;
2156
+ height: 100vh;
2157
+ top: 0;
2158
+ left: 0;
2159
+ opacity: 0;
2160
+ display: flex;
2161
+ justify-content: center;
2162
+ align-items: center;
2163
+ transform: scale(0.96);
2164
+ transition-property: transform, opacity;
2165
+ transition-duration: 200ms;
2166
+ transition-timing-function: ease-out;
2167
+ }
2168
+
2169
+ .backdrop {
2170
+ position: fixed;
2171
+ background: var(--backdrop);
2172
+ backdrop-filter: var(--backdrop-filter);
2173
+ opacity: 0;
2174
+ top: 0;
2175
+ left: 0;
2176
+ width: 100vw;
2177
+ height: 100vh;
2178
+ transition-property: opacity;
2179
+ transition-duration: 200ms;
2180
+ transition-timing-function: ease-out;
2181
+ }
2182
+
2183
+ dialog[open] .backdrop {
2184
+ opacity: 1;
2185
+ }
2186
+
2187
+ dialog::backdrop {
2188
+ background: none;
2189
+ }
2190
+
2191
+ dialog[open] {
2192
+ pointer-events: auto;
2193
+ }
2194
+
2195
+ dialog[open] .content {
2196
+ opacity: 1;
2197
+ transform: scale(1);
2198
+ }
2199
+
2200
+ dialog[open] .button-close {
2201
+ display: block;
2202
+ }
2203
+
2204
+ .button-close {
2205
+ display: none;
2206
+ position: fixed;
2207
+ top: 0.8rem;
2208
+ right: 0.6rem;
2209
+ width: 2.75rem;
2210
+ height: 2.75rem;
2211
+ transition-property: transform;
2212
+ transition-duration: 100ms;
2213
+ transition-timing-function: ease-out;
2214
+ }
2215
+
2216
+ .button-close:hover {
2217
+ cursor: pointer;
2218
+ transform: scale(1.3);
2219
+ }
2220
+
2221
+ .button-close svg {
2222
+ color: white;
2223
+ width: 2.75rem;
2224
+ height: 2.75rem;
2225
+ transform: rotate(45deg);
2226
+ }
2227
+
2228
+ .wrapper {
2229
+ display: flex;
2230
+ align-items: center;
2231
+ justify-content: center;
2232
+ width: 100%;
2233
+ height: 100%;
2234
+ max-width: 100vw;
2235
+ max-height: var(--frame-max-height);
2236
+ }
2237
+
2238
+ .frame {
2239
+ --ratio: calc(var(--frame-ratio-h, 1) / var(--frame-ratio-w, 1) * 100%);
2240
+ --frame-height: min(var(--ratio), var(--frame-max-height));
2241
+ position: relative;
2242
+ padding-bottom: var(--frame-height);
2243
+ width: min(
2244
+ calc(var(--frame-height, 0) * (var(--frame-ratio-w) / var(--frame-ratio-h))),
2245
+ 100%
2246
+ );
2247
+ height: 0;
2248
+ overflow: hidden;
2249
+ background-size: contain;
2250
+ background-position: center center;
2251
+ background-repeat: no-repeat;
2252
+ }
2253
+ `,c([Di("dialog")],Li.prototype,"_dialog",2),c([Di(".content")],Li.prototype,"_content",2),c([Di(".frame")],Li.prototype,"_frame",2),c([Di(".backdrop")],Li.prototype,"_backdrop",2),c([oe()],Li.prototype,"backdrop",1),c([oe({attribute:"backdrop-filter"})],Li.prototype,"backdropFilter",1);typeof window<"u"&&window.customElements&&(window.customElements.get("mave-pop")||window.customElements.define("mave-pop",Li));function qS(s){let e={};if(!s)return e;for(let t=0;t<s.attributes.length;t++){let i=s.attributes[t];e[i.name]=i.value;}return e}var jS=()=>typeof document<"u"?document:void 0,Dh=s=>{let e=jS();if(!e)return;let t=e;function i(a){let l,d,c=t.querySelector(`mave-pop[embed="${a}"]`);if(c)return d=qS(c.querySelector("mave-player")),l=c,{pop:l,attributes:d};let u=t.querySelector("mave-pop:not([embed])");return u?(d=qS(u.querySelector("mave-player")),l=u,{pop:l,attributes:d}):(l=new Li,t.body.appendChild(l),{pop:l})}function r(a,l){let d=new Se;if(l)for(let c in l)d.setAttribute(c,l[c]);return d.embed=a,d}function n(a){a.querySelectorAll("[x-mave-pop]").forEach(l=>{let d=l.getAttribute("x-mave-pop")||l.getAttribute("embed");if(!d)return;let{pop:c,attributes:u}=i(d);r(d,u),l.addEventListener("click",h=>{h.preventDefault();let f=t.querySelectorAll("mave-player");if(!Array.from(f).find(p=>p.popped)){let p=r(d,u);c.open(p).then(()=>{p.play();}),c.addEventListener("closed",()=>{p.pause();});}});});}n(s),new MutationObserver(a=>{for(let l of a)l.type==="childList"&&l.addedNodes.forEach(d=>{d instanceof HTMLElement&&n(d);});}).observe(t.body,{childList:true,subtree:true});},kl=jS();kl&&(kl.readyState==="loading"?kl.addEventListener("DOMContentLoaded",()=>{Dh(kl);}):setTimeout(()=>Dh(kl),500));var Ye,O0,Mh,Ao,wl,Cl,So=class extends Ei{constructor(){super(...arguments);e(this,Ye);this.order="newest";this.embedController=new Mi(this,0);}connectedCallback(){super.connectedCallback(),this.embedController.token=this.token;}requestUpdate(t,i){super.requestUpdate(t,i),t==="embed"&&(this.embedController.token=this.token);}get _slottedChildren(){return this.shadowRoot?.querySelector("slot")?.assignedElements({flatten:true})||[]}updated(){this.shadowRoot&&Dh(this.shadowRoot);}refresh(){return this.embedController.refresh()}containsEmbed(t){return this._collection?.videos?.some(i=>i.id===t)}getNextForEmbed(t){let i=g(this,Ye,O0).call(this),r=i.findIndex(n=>n.id===t);if(r!==-1)return i[r+1]}render(){return ne`
2254
+ ${this.embedController.render({pending:this.renderPending,error:t=>ne`<p>${t instanceof Error?t.message:Ce}</p>`,complete:t=>{if(this._collection=t,!t)return this.renderPending();if(t.error)return console.warn(t.error);let i=this._slottedChildren.map(r=>{function n(){let o;return r.nodeName==="TEMPLATE"?o=r.content.cloneNode(true):o=r.cloneNode(true),o}if(r.getAttribute("name")=="list-title"){let o=n();return o.textContent=this._collection?.name,ne`${o}`}if(r.getAttribute("name")=="mave-list-root"&&this.embedController.embed){let o=n(),a=g(this,Ye,wl).call(this,o,"root-link");return a&&(a.addEventListener("click",l=>{l.preventDefault(),this.emit(this.EVENT_TYPES.CLICK,{action:"back",embedId:""}),this.embedController.embed="";}),g(this,Ye,Cl).call(this,a)),ne`${o}`}if(r.getAttribute("name")=="mave-list-folder"){let o=this._collection.collections?.map(a=>{let l=n(),d=g(this,Ye,wl).call(this,l,"folder-link");return [r,d].forEach(c=>{c instanceof Element&&(c.addEventListener("click",u=>{u.preventDefault(),this.emit(this.EVENT_TYPES.CLICK,{action:"show_collection",collectionId:a.id}),this.embedController.embed=a.id;}),g(this,Ye,Cl).call(this,c));}),g(this,Ye,Ao).call(this,l,"folder-title",a.name),typeof a.video_count=="number"&&g(this,Ye,Ao).call(this,l,"folder-count",a.video_count.toString()),ne`${l}`});return ne`${o}`}if(r.getAttribute("name")=="mave-list-item"||!["mave-list-folder","mave-list-item","mave-list-root","list-title"].includes(r.hasAttribute("name")?r.getAttribute("name"):"")&&r.nodeName=="TEMPLATE"){let o=g(this,Ye,O0).call(this).map((a,l)=>{let d=n(),c=l+1;g(this,Ye,Ao).call(this,d,"item-title",a.name),g(this,Ye,Ao).call(this,d,"item-position",c.toString()),g(this,Ye,Ao).call(this,d,"item-duration",this.durationToTime(a.duration)),g(this,Ye,Mh).call(this,d,"mave-clip",a.id),g(this,Ye,Mh).call(this,d,"mave-player",a.id),g(this,Ye,Mh).call(this,d,"mave-img",a.id);let u=d.querySelector("mave-clip"),h=g(this,Ye,wl).call(this,d,"item-title"),f=d.querySelector("mave-img");return [u,h,f,d].forEach(m=>{m?.addEventListener("click",p=>{this.emit(this.EVENT_TYPES.CLICK,{action:"show_embed",embedId:a.id,position:c});});}),ne`${d}`});return ne`${o}`}}).filter(r=>r);return ne`${this._stylesheets} ${i}`}})}
2255
+ `}renderPending(){return ne`<slot style="display: none"></slot>`}};Ye=new WeakSet,O0=function(){if(!this._collection)return [];let t=this._collection.videos;return this.order=="newest"&&(t=this._collection.videos?.sort((i,r)=>r.created-i.created)),this.order=="oldest"&&(t=this._collection.videos?.sort((i,r)=>i.created-r.created)),this.order=="az"&&(t=this._collection.videos?.sort((i,r)=>i.name.localeCompare(r.name))),this.order=="za"&&(t=this._collection.videos?.sort((i,r)=>r.name.localeCompare(i.name))),t},Mh=function(t,i,r){let n=t.querySelector(i);n&&(n.setAttribute("embed",r),g(this,Ye,Cl).call(this,n));},Ao=function(t,i,r){let n=g(this,Ye,wl).call(this,t,i);n&&(n.textContent=r,g(this,Ye,Cl).call(this,n));},wl=function(t,i){return t.querySelector(`[slot="${i}"], [data-slot="${i}"]`)},Cl=function(t){t&&(t.removeAttribute("slot"),t.removeAttribute("data-slot"));},So.styles=it`
2256
+ :host {
2257
+ display: block;
2258
+ }
2259
+ `,c([oe()],So.prototype,"token",2),c([oe()],So.prototype,"order",2);typeof window<"u"&&window.customElements&&(window.customElements.get("mave-list")||window.customElements.define("mave-list",So));var Ph=class{constructor(e,t){this.host=e,this.embed=t,this.task=new Tr(this.host,async()=>{try{let i=this.embedFile("subtitle.json"),r=await fetch(i);if(r.status!==200)throw new Error;let n=await r.json(),o=n.segments.flatMap(h=>h.words).map(h=>({start:h.start,end:h.end,word:h.word.trim()})),a=[],l={start:0,end:0,text:"",words:[]};o.forEach(h=>{let{start:f,end:m,word:p}=h;l.start===0&&(l.start=f),l.end=m,l.words.push(h),l.text+=(l.text?" ":"")+p,/[.!?]$/.test(p)&&(a.push({...l}),l={start:0,end:0,text:"",words:[]});}),l.words.length>0&&a.push({...l});let d=[],c=1,u=5;if(a.length>0){let h={start:a[0].start,end:a[0].end,text:a[0].text,words:a[0].words},f=1;for(let m=1;m<a.length;m++){let p=a[m],g=a[m-1],E=p.start??0,y=g.end??0;E-y<=c&&f<u?(h.end=p.end,h.text+=" "+p.text,h.words=[...h.words,...p.words],f++):(d.push({...h}),h={start:p.start,end:p.end,text:p.text,words:p.words},f=1);}h.words.length>0&&d.push(h);}return {text:n.text,segments:d}}catch{throw console.warn(`Failed to fetch language file for "${this.embed}"`),new Error}},()=>[this.embed]);}set embed(e){this._embed!=e&&(this._embed=e,this.host.requestUpdate());}get embed(){return this._embed}set token(e){this._token!=e&&(this._token=e,this.host.requestUpdate());}get token(){return this._token}get spaceId(){return this.embed.substring(0,5)}get embedId(){return this.embed.substring(5,this.embed.length)}get version(){return this._version?`/v${this._version}/`:"/"}set version(e){this._version!=e&&(this._version=e,this.host.requestUpdate());}get cdnRoot(){return a$1.cdn.endpoint.replace("${this.spaceId}",this.spaceId)}embedFile(e,t=new URLSearchParams){let i=new URL(`${this.cdnRoot}/${this.embedId}${e=="manifest.json"?"/":this.version}${e}`);return this.token&&t.append("token",this.token),i.search=t.toString(),i.toString()}render(e){return this.task?.render(e)}};var nr,YS,zS,QS,ds=class extends nt{constructor(){super(...arguments);e(this,nr);this._clickable=true;this._autoscroll=true;this._lastScrollTime=0;this.currentTime=0;}get embed(){return this._embedId}set embed(t){this._embedId!=t&&(this._embedId=t,this.captionController=new Ph(this,this.embed),this.reset(),this.requestUpdate("embed"));}get clickable(){return this._clickable}set clickable(t){this._clickable!=t&&(typeof t=="string"?this._clickable=t==="true"||t==="":this._clickable=t,this.requestUpdate("clickable"));}get autoscroll(){return this._autoscroll}set autoscroll(t){this._autoscroll!=t&&(typeof t=="string"?this._autoscroll=t==="true"||t==="":this._autoscroll=t,this.requestUpdate("autoscroll"));}get wordIndex(){return this._wordIndex}set wordIndex(t){if(this._wordIndex!=t&&(this._wordIndex=t,this.autoscroll)){let i=this.shadowRoot?.querySelector(`[data-word-id="word-${this.segmentIndex}-${this.wordIndex}"]`);if(i&&this._lastScrollTime+2500<Date.now()){let r=this.getBoundingClientRect(),n=i.getBoundingClientRect(),o=n.top-r.top;if(o>0){let a=this.scrollTop+o;g(this,nr,YS).call(this,this,a-n.height/2);}}}}get segmentIndex(){return this._segmentIndex}set segmentIndex(t){this._segmentIndex!=t&&(this._segmentIndex=t);}connectedCallback(){super.connectedCallback(),this.addEventListener("scroll",g(this,nr,zS).bind(this)),this.reset();}reset(){if(typeof document>"u")return;this.loop=false,this.currentTime=0,this.wordIndex=0,this.segmentIndex=0;let t=document.querySelector(`mave-player[embed="${this.embed}"]`);t&&(this.player=t,t.addEventListener("play",()=>{this.loop=true,this.loopUpdateTime();}),t.addEventListener("pause",()=>{this.loop=false;}));}updateTime(){this.currentTime=this.player.currentTime;}loopUpdateTime(){this.updateTime(),setTimeout(()=>{this.loop&&requestAnimationFrame(this.loopUpdateTime.bind(this));},10);}inRange({start:t,end:i},r,n,o){if(this.currentTime>=t&&this.currentTime<=i)return o&&(this.wordIndex=o),n&&(this.segmentIndex=n),r||true}segmentStyle(){return this.clickable?{cursor:"pointer"}:{}}wordStyle(t){return t?{"background-color":this.highlight}:{}}render(){return this.captionController?this.captionController.render({complete:t=>(this.captions=t,ne`
2260
+ <div>
2261
+ ${this.captions.segments.map((i,r)=>ne`
2262
+ <p
2263
+ data-segment-id="segment-${r}"
2264
+ style=${Lt(this.segmentStyle())}
2265
+ @click=${this.clickable?g(this,nr,QS):Ce}
2266
+ part=${_r(this.inRange(i,"segment"))}
2267
+ x-caption-segment-start="${i.start}"
2268
+ x-caption-segment-end="${i.end}"
2269
+ >
2270
+ ${i.words.map((n,o)=>ne`
2271
+ <span
2272
+ data-word-id="word-${r}-${o}"
2273
+ style=${Lt(this.wordStyle(this.inRange(n)))}
2274
+ part=${_r(this.inRange(n,"word",r,o))}
2275
+ x-caption-word-start="${n.start}"
2276
+ x-caption-word-end="${n.end}"
2277
+ >${n.word.trim()}</span
2278
+ >
2279
+ `)}
2280
+ </p>
2281
+ `)}
2282
+ </div>
2283
+ `)}):Ce}};nr=new WeakSet,YS=function(t,i,r=500){let n=this.scrollTop,o=i-n,a=null,l=false;function d(u){a||(a=u);let h=u-a,f=Math.min(h/r,1);t.scrollTop=n+o*c(f),h<r&&l?requestAnimationFrame(d):l=false;}function c(u){return u<.5?2*u*u:1-Math.pow(-2*u+2,2)/2}l=true,requestAnimationFrame(d);},zS=function(){this._lastScrollTime=Date.now();},QS=function(t){if(this.clickable){let i=t.target.closest("p");if(i&&this.player){let r=i.getAttribute("x-caption-segment-start");this.player.currentTime=Number(r),this.player.paused&&this.player.play();}}},ds.styles=it`
2284
+ :host {
2285
+ display: block;
2286
+ width: 100%;
2287
+ height: 100%;
2288
+ }
2289
+
2290
+ [part='word'] {
2291
+ background-color: rgba(255, 210, 42, 0.5);
2292
+ }
2293
+ `,c([oe()],ds.prototype,"embed",1),c([oe()],ds.prototype,"highlight",2),c([oe()],ds.prototype,"clickable",1),c([oe()],ds.prototype,"autoscroll",1),c([Ct()],ds.prototype,"currentTime",2),c([Ct()],ds.prototype,"captions",2);typeof window<"u"&&window.customElements&&(window.customElements.get("mave-text")||window.customElements.define("mave-text",ds));function Io(s){"@babel/helpers - typeof";return Io=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Io(s)}function a1(s,e,t){return Object.defineProperty(s,"prototype",{writable:false}),s}function c1(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function u1(s,e,t){return e=Ml(e),h1(s,N0()?Reflect.construct(e,t||[],Ml(s).constructor):e.apply(s,t))}function h1(s,e){if(e&&(Io(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return f1(s)}function f1(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function m1(s,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");s.prototype=Object.create(e&&e.prototype,{constructor:{value:s,writable:true,configurable:true}}),Object.defineProperty(s,"prototype",{writable:false}),e&&Dl(s,e);}function U0(s){var e=typeof Map=="function"?new Map:void 0;return U0=function(i){if(i===null||!g1(i))return i;if(typeof i!="function")throw new TypeError("Super expression must either be null or a function");if(typeof e<"u"){if(e.has(i))return e.get(i);e.set(i,r);}function r(){return p1(i,arguments,Ml(this).constructor)}return r.prototype=Object.create(i.prototype,{constructor:{value:r,enumerable:false,writable:true,configurable:true}}),Dl(r,i)},U0(s)}function p1(s,e,t){if(N0())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,e);var r=new(s.bind.apply(s,i));return t&&Dl(r,t.prototype),r}function N0(){try{var s=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch{}return (N0=function(){return !!s})()}function g1(s){try{return Function.toString.call(s).indexOf("[native code]")!==-1}catch{return typeof s=="function"}}function Dl(s,e){return Dl=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,r){return i.__proto__=r,i},Dl(s,e)}function Ml(s){return Ml=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Ml(s)}var v1=(function(s){function e(t){var i,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;if(c1(this,e),i=u1(this,e,[t]),i.originalRequest=n,i.originalResponse=o,i.causingError=r,r!=null&&(t+=", caused by ".concat(r.toString())),n!=null){var a=n.getHeader("X-Request-ID")||"n/a",l=n.getMethod(),d=n.getURL(),c=o?o.getStatus():"n/a",u=o?o.getBody()||"":"n/a";t+=", originated from request (method: ".concat(l,", url: ").concat(d,", response code: ").concat(c,", response text: ").concat(u,", request id: ").concat(a,")");}return i.message=t,i}return m1(e,s),a1(e)})(U0(Error)),xo=v1;function or(s){}function Pl(s){"@babel/helpers - typeof";return Pl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Pl(s)}function y1(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function ZS(s,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||false,i.configurable=true,"value"in i&&(i.writable=true),Object.defineProperty(s,_1(i.key),i);}}function b1(s,e,t){return e&&ZS(s.prototype,e),Object.defineProperty(s,"prototype",{writable:false}),s}function _1(s){var e=T1(s,"string");return Pl(e)=="symbol"?e:e+""}function T1(s,e){if(Pl(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(Pl(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return (String)(s)}var JS=(function(){function s(){y1(this,s);}return b1(s,[{key:"listAllUploads",value:function(){return Promise.resolve([])}},{key:"findUploadsByFingerprint",value:function(t){return Promise.resolve([])}},{key:"removeUpload",value:function(t){return Promise.resolve()}},{key:"addUpload",value:function(t,i){return Promise.resolve(null)}}])})();var nA="3.7.8",S1=nA,Ro=typeof Buffer=="function",eA=typeof TextDecoder=="function"?new TextDecoder:void 0,tA=typeof TextEncoder=="function"?new TextEncoder:void 0,A1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Ol=Array.prototype.slice.call(A1),Oh=(s=>{let e={};return s.forEach((t,i)=>e[t]=i),e})(Ol),I1=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Rt=String.fromCharCode.bind(String),iA=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):s=>new Uint8Array(Array.prototype.slice.call(s,0)),oA=s=>s.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),aA=s=>s.replace(/[^A-Za-z0-9\+\/]/g,""),lA=s=>{let e,t,i,r,n="",o=s.length%3;for(let a=0;a<s.length;){if((t=s.charCodeAt(a++))>255||(i=s.charCodeAt(a++))>255||(r=s.charCodeAt(a++))>255)throw new TypeError("invalid character found");e=t<<16|i<<8|r,n+=Ol[e>>18&63]+Ol[e>>12&63]+Ol[e>>6&63]+Ol[e&63];}return o?n.slice(0,o-3)+"===".substring(o):n},B0=typeof btoa=="function"?s=>btoa(s):Ro?s=>Buffer.from(s,"binary").toString("base64"):lA,F0=Ro?s=>Buffer.from(s).toString("base64"):s=>{let t=[];for(let i=0,r=s.length;i<r;i+=4096)t.push(Rt.apply(null,s.subarray(i,i+4096)));return B0(t.join(""))},Uh=(s,e=false)=>e?oA(F0(s)):F0(s),x1=s=>{if(s.length<2){var e=s.charCodeAt(0);return e<128?s:e<2048?Rt(192|e>>>6)+Rt(128|e&63):Rt(224|e>>>12&15)+Rt(128|e>>>6&63)+Rt(128|e&63)}else {var e=65536+(s.charCodeAt(0)-55296)*1024+(s.charCodeAt(1)-56320);return Rt(240|e>>>18&7)+Rt(128|e>>>12&63)+Rt(128|e>>>6&63)+Rt(128|e&63)}},L1=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,dA=s=>s.replace(L1,x1),sA=Ro?s=>Buffer.from(s,"utf8").toString("base64"):tA?s=>F0(tA.encode(s)):s=>B0(dA(s)),Lo=(s,e=false)=>e?oA(sA(s)):sA(s),rA=s=>Lo(s,true),R1=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,k1=s=>{switch(s.length){case 4:var e=(7&s.charCodeAt(0))<<18|(63&s.charCodeAt(1))<<12|(63&s.charCodeAt(2))<<6|63&s.charCodeAt(3),t=e-65536;return Rt((t>>>10)+55296)+Rt((t&1023)+56320);case 3:return Rt((15&s.charCodeAt(0))<<12|(63&s.charCodeAt(1))<<6|63&s.charCodeAt(2));default:return Rt((31&s.charCodeAt(0))<<6|63&s.charCodeAt(1))}},cA=s=>s.replace(R1,k1),uA=s=>{if(s=s.replace(/\s+/g,""),!I1.test(s))throw new TypeError("malformed base64.");s+="==".slice(2-(s.length&3));let e,t,i,r=[];for(let n=0;n<s.length;)e=Oh[s.charAt(n++)]<<18|Oh[s.charAt(n++)]<<12|(t=Oh[s.charAt(n++)])<<6|(i=Oh[s.charAt(n++)]),t===64?r.push(Rt(e>>16&255)):i===64?r.push(Rt(e>>16&255,e>>8&255)):r.push(Rt(e>>16&255,e>>8&255,e&255));return r.join("")},H0=typeof atob=="function"?s=>atob(aA(s)):Ro?s=>Buffer.from(s,"base64").toString("binary"):uA,hA=Ro?s=>iA(Buffer.from(s,"base64")):s=>iA(H0(s).split("").map(e=>e.charCodeAt(0))),fA=s=>hA(mA(s)),w1=Ro?s=>Buffer.from(s,"base64").toString("utf8"):eA?s=>eA.decode(hA(s)):s=>cA(H0(s)),mA=s=>aA(s.replace(/[-_]/g,e=>e=="-"?"+":"/")),$0=s=>w1(mA(s)),C1=s=>{if(typeof s!="string")return false;let e=s.replace(/\s+/g,"").replace(/={0,2}$/,"");return !/[^\s0-9a-zA-Z\+/]/.test(e)||!/[^\s0-9a-zA-Z\-_]/.test(e)},pA=s=>({value:s,enumerable:false,writable:true,configurable:true}),gA=function(){let s=(e,t)=>Object.defineProperty(String.prototype,e,pA(t));s("fromBase64",function(){return $0(this)}),s("toBase64",function(e){return Lo(this,e)}),s("toBase64URI",function(){return Lo(this,true)}),s("toBase64URL",function(){return Lo(this,true)}),s("toUint8Array",function(){return fA(this)});},vA=function(){let s=(e,t)=>Object.defineProperty(Uint8Array.prototype,e,pA(t));s("toBase64",function(e){return Uh(this,e)}),s("toBase64URI",function(){return Uh(this,true)}),s("toBase64URL",function(){return Uh(this,true)});},D1=()=>{gA(),vA();},EA={version:nA,VERSION:S1,atob:H0,atobPolyfill:uA,btoa:B0,btoaPolyfill:lA,fromBase64:$0,toBase64:Lo,encode:Lo,encodeURI:rA,encodeURL:rA,utob:dA,btou:cA,decode:$0,isValid:C1,fromUint8Array:Uh,toUint8Array:fA,extendString:gA,extendUint8Array:vA,extendBuiltins:D1};var VA=b$1(CA());function W0(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){var e=Math.random()*16|0,t=s==="x"?e:e&3|8;return t.toString(16)})}function q0(){q0=function(){return e};var s,e={},t=Object.prototype,i=t.hasOwnProperty,r=Object.defineProperty||function(x,T,I){x[T]=I.value;},n=typeof Symbol=="function"?Symbol:{},o=n.iterator||"@@iterator",a=n.asyncIterator||"@@asyncIterator",l=n.toStringTag||"@@toStringTag";function d(x,T,I){return Object.defineProperty(x,T,{value:I,enumerable:true,configurable:true,writable:true}),x[T]}try{d({},"");}catch{d=function(I,P,U){return I[P]=U};}function c(x,T,I,P){var U=T&&T.prototype instanceof E?T:E,w=Object.create(U.prototype),B=new X(P||[]);return r(w,"_invoke",{value:k(x,I,B)}),w}function u(x,T,I){try{return {type:"normal",arg:x.call(T,I)}}catch(P){return {type:"throw",arg:P}}}e.wrap=c;var h="suspendedStart",f="suspendedYield",m="executing",p="completed",g={};function E(){}function y(){}function _(){}var S={};d(S,o,function(){return this});var L=Object.getPrototypeOf,O=L&&L(L(Y([])));O&&O!==t&&i.call(O,o)&&(S=O);var R=_.prototype=E.prototype=Object.create(S);function D(x){["next","throw","return"].forEach(function(T){d(x,T,function(I){return this._invoke(T,I)});});}function C(x,T){function I(U,w,B,z){var te=u(x[U],x,w);if(te.type!=="throw"){var se=te.arg,re=se.value;return re&&sn(re)=="object"&&i.call(re,"__await")?T.resolve(re.__await).then(function(Ie){I("next",Ie,B,z);},function(Ie){I("throw",Ie,B,z);}):T.resolve(re).then(function(Ie){se.value=Ie,B(se);},function(Ie){return I("throw",Ie,B,z)})}z(te.arg);}var P;r(this,"_invoke",{value:function(w,B){function z(){return new T(function(te,se){I(w,B,te,se);})}return P=P?P.then(z,z):z()}});}function k(x,T,I){var P=h;return function(U,w){if(P===m)throw Error("Generator is already running");if(P===p){if(U==="throw")throw w;return {value:s,done:true}}for(I.method=U,I.arg=w;;){var B=I.delegate;if(B){var z=H(B,I);if(z){if(z===g)continue;return z}}if(I.method==="next")I.sent=I._sent=I.arg;else if(I.method==="throw"){if(P===h)throw P=p,I.arg;I.dispatchException(I.arg);}else I.method==="return"&&I.abrupt("return",I.arg);P=m;var te=u(x,T,I);if(te.type==="normal"){if(P=I.done?p:f,te.arg===g)continue;return {value:te.arg,done:I.done}}te.type==="throw"&&(P=p,I.method="throw",I.arg=te.arg);}}}function H(x,T){var I=T.method,P=x.iterator[I];if(P===s)return T.delegate=null,I==="throw"&&x.iterator.return&&(T.method="return",T.arg=s,H(x,T),T.method==="throw")||I!=="return"&&(T.method="throw",T.arg=new TypeError("The iterator does not provide a '"+I+"' method")),g;var U=u(P,x.iterator,T.arg);if(U.type==="throw")return T.method="throw",T.arg=U.arg,T.delegate=null,g;var w=U.arg;return w?w.done?(T[x.resultName]=w.value,T.next=x.nextLoc,T.method!=="return"&&(T.method="next",T.arg=s),T.delegate=null,g):w:(T.method="throw",T.arg=new TypeError("iterator result is not an object"),T.delegate=null,g)}function q(x){var T={tryLoc:x[0]};1 in x&&(T.catchLoc=x[1]),2 in x&&(T.finallyLoc=x[2],T.afterLoc=x[3]),this.tryEntries.push(T);}function j(x){var T=x.completion||{};T.type="normal",delete T.arg,x.completion=T;}function X(x){this.tryEntries=[{tryLoc:"root"}],x.forEach(q,this),this.reset(true);}function Y(x){if(x||x===""){var T=x[o];if(T)return T.call(x);if(typeof x.next=="function")return x;if(!isNaN(x.length)){var I=-1,P=function U(){for(;++I<x.length;)if(i.call(x,I))return U.value=x[I],U.done=false,U;return U.value=s,U.done=true,U};return P.next=P}}throw new TypeError(sn(x)+" is not iterable")}return y.prototype=_,r(R,"constructor",{value:_,configurable:true}),r(_,"constructor",{value:y,configurable:true}),y.displayName=d(_,l,"GeneratorFunction"),e.isGeneratorFunction=function(x){var T=typeof x=="function"&&x.constructor;return !!T&&(T===y||(T.displayName||T.name)==="GeneratorFunction")},e.mark=function(x){return Object.setPrototypeOf?Object.setPrototypeOf(x,_):(x.__proto__=_,d(x,l,"GeneratorFunction")),x.prototype=Object.create(R),x},e.awrap=function(x){return {__await:x}},D(C.prototype),d(C.prototype,a,function(){return this}),e.AsyncIterator=C,e.async=function(x,T,I,P,U){U===void 0&&(U=Promise);var w=new C(c(x,T,I,P),U);return e.isGeneratorFunction(T)?w:w.next().then(function(B){return B.done?B.value:w.next()})},D(R),d(R,l,"Generator"),d(R,o,function(){return this}),d(R,"toString",function(){return "[object Generator]"}),e.keys=function(x){var T=Object(x),I=[];for(var P in T)I.push(P);return I.reverse(),function U(){for(;I.length;){var w=I.pop();if(w in T)return U.value=w,U.done=false,U}return U.done=true,U}},e.values=Y,X.prototype={constructor:X,reset:function(T){if(this.prev=0,this.next=0,this.sent=this._sent=s,this.done=false,this.delegate=null,this.method="next",this.arg=s,this.tryEntries.forEach(j),!T)for(var I in this)I.charAt(0)==="t"&&i.call(this,I)&&!isNaN(+I.slice(1))&&(this[I]=s);},stop:function(){this.done=true;var T=this.tryEntries[0].completion;if(T.type==="throw")throw T.arg;return this.rval},dispatchException:function(T){if(this.done)throw T;var I=this;function P(se,re){return B.type="throw",B.arg=T,I.next=se,re&&(I.method="next",I.arg=s),!!re}for(var U=this.tryEntries.length-1;U>=0;--U){var w=this.tryEntries[U],B=w.completion;if(w.tryLoc==="root")return P("end");if(w.tryLoc<=this.prev){var z=i.call(w,"catchLoc"),te=i.call(w,"finallyLoc");if(z&&te){if(this.prev<w.catchLoc)return P(w.catchLoc,true);if(this.prev<w.finallyLoc)return P(w.finallyLoc)}else if(z){if(this.prev<w.catchLoc)return P(w.catchLoc,true)}else {if(!te)throw Error("try statement without catch or finally");if(this.prev<w.finallyLoc)return P(w.finallyLoc)}}}},abrupt:function(T,I){for(var P=this.tryEntries.length-1;P>=0;--P){var U=this.tryEntries[P];if(U.tryLoc<=this.prev&&i.call(U,"finallyLoc")&&this.prev<U.finallyLoc){var w=U;break}}w&&(T==="break"||T==="continue")&&w.tryLoc<=I&&I<=w.finallyLoc&&(w=null);var B=w?w.completion:{};return B.type=T,B.arg=I,w?(this.method="next",this.next=w.finallyLoc,g):this.complete(B)},complete:function(T,I){if(T.type==="throw")throw T.arg;return T.type==="break"||T.type==="continue"?this.next=T.arg:T.type==="return"?(this.rval=this.arg=T.arg,this.method="return",this.next="end"):T.type==="normal"&&I&&(this.next=I),g},finish:function(T){for(var I=this.tryEntries.length-1;I>=0;--I){var P=this.tryEntries[I];if(P.finallyLoc===T)return this.complete(P.completion,P.afterLoc),j(P),g}},catch:function(T){for(var I=this.tryEntries.length-1;I>=0;--I){var P=this.tryEntries[I];if(P.tryLoc===T){var U=P.completion;if(U.type==="throw"){var w=U.arg;j(P);}return w}}throw Error("illegal catch attempt")},delegateYield:function(T,I,P){return this.delegate={iterator:Y(T),resultName:I,nextLoc:P},this.method==="next"&&(this.arg=s),g}},e}function DA(s,e,t,i,r,n,o){try{var a=s[n](o),l=a.value;}catch(d){t(d);return}a.done?e(l):Promise.resolve(l).then(i,r);}function V1(s){return function(){var e=this,t=arguments;return new Promise(function(i,r){var n=s.apply(e,t);function o(l){DA(n,i,r,o,a,"next",l);}function a(l){DA(n,i,r,o,a,"throw",l);}o(void 0);})}}function HA(s,e){return j1(s)||q1(s,e)||GA(s,e)||W1()}function W1(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2294
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function q1(s,e){var t=s==null?null:typeof Symbol<"u"&&s[Symbol.iterator]||s["@@iterator"];if(t!=null){var i,r,n,o,a=[],l=true,d=false;try{if(n=(t=t.call(s)).next,e===0);else for(;!(l=(i=n.call(t)).done)&&(a.push(i.value),a.length!==e);l=!0);}catch(c){d=true,r=c;}finally{try{if(!l&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(d)throw r}}return a}}function j1(s){if(Array.isArray(s))return s}function sn(s){"@babel/helpers - typeof";return sn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},sn(s)}function Y1(s,e){var t=typeof Symbol<"u"&&s[Symbol.iterator]||s["@@iterator"];if(!t){if(Array.isArray(s)||(t=GA(s))||e){t&&(s=t);var i=0,r=function(){};return {s:r,n:function(){return i>=s.length?{done:true}:{done:false,value:s[i++]}},e:function(d){throw d},f:r}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
2295
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var n=true,o=false,a;return {s:function(){t=t.call(s);},n:function(){var d=t.next();return n=d.done,d},e:function(d){o=true,a=d;},f:function(){try{!n&&t.return!=null&&t.return();}finally{if(o)throw a}}}}function GA(s,e){if(s){if(typeof s=="string")return MA(s,e);var t=Object.prototype.toString.call(s).slice(8,-1);if(t==="Object"&&s.constructor&&(t=s.constructor.name),t==="Map"||t==="Set")return Array.from(s);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return MA(s,e)}}function MA(s,e){(e==null||e>s.length)&&(e=s.length);for(var t=0,i=new Array(e);t<e;t++)i[t]=s[t];return i}function PA(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i);}return t}function ko(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?PA(Object(t),true).forEach(function(i){z1(s,i,t[i]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):PA(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i));});}return s}function z1(s,e,t){return e=KA(e),e in s?Object.defineProperty(s,e,{value:t,enumerable:true,configurable:true,writable:true}):s[e]=t,s}function Q1(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function OA(s,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||false,i.configurable=true,"value"in i&&(i.writable=true),Object.defineProperty(s,KA(i.key),i);}}function X1(s,e,t){return e&&OA(s.prototype,e),t&&OA(s,t),Object.defineProperty(s,"prototype",{writable:false}),s}function KA(s){var e=Z1(s,"string");return sn(e)=="symbol"?e:e+""}function Z1(s,e){if(sn(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(sn(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return (String)(s)}var Fh="tus-v1",$h="ietf-draft-03",Ul="ietf-draft-05",J1={endpoint:null,uploadUrl:null,metadata:{},metadataForPartialUploads:{},fingerprint:null,uploadSize:null,onProgress:null,onChunkComplete:null,onSuccess:null,onError:null,onUploadUrlAvailable:null,overridePatchMethod:false,headers:{},addRequestId:false,onBeforeRequest:null,onAfterResponse:null,onShouldRetry:qA,chunkSize:Number.POSITIVE_INFINITY,retryDelays:[0,1e3,3e3,5e3],parallelUploads:1,parallelUploadBoundaries:null,storeFingerprintForResuming:true,removeFingerprintOnSuccess:false,uploadLengthDeferred:false,uploadDataDuringCreation:false,urlStorage:null,fileReader:null,httpStack:null,protocol:Fh},WA=(function(){function s(e,t){Q1(this,s),"resume"in t&&console.log("tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead."),this.options=t,this.options.chunkSize=Number(this.options.chunkSize),this._urlStorage=this.options.urlStorage,this.file=e,this.url=null,this._req=null,this._fingerprint=null,this._urlStorageKey=null,this._offset=null,this._aborted=false,this._size=null,this._source=null,this._retryAttempt=0,this._retryTimeout=null,this._offsetBeforeRetry=0,this._parallelUploads=null,this._parallelUploadUrls=null;}return X1(s,[{key:"findPreviousUploads",value:function(){var t=this;return this.options.fingerprint(this.file,this.options).then(function(i){return t._urlStorage.findUploadsByFingerprint(i)})}},{key:"resumeFromPreviousUpload",value:function(t){this.url=t.uploadUrl||null,this._parallelUploadUrls=t.parallelUploadUrls||null,this._urlStorageKey=t.urlStorageKey;}},{key:"start",value:function(){var t=this,i=this.file;if(!i){this._emitError(new Error("tus: no file or stream to upload provided"));return}if(![Fh,$h,Ul].includes(this.options.protocol)){this._emitError(new Error("tus: unsupported protocol ".concat(this.options.protocol)));return}if(!this.options.endpoint&&!this.options.uploadUrl&&!this.url){this._emitError(new Error("tus: neither an endpoint or an upload URL is provided"));return}var r=this.options.retryDelays;if(r!=null&&Object.prototype.toString.call(r)!=="[object Array]"){this._emitError(new Error("tus: the `retryDelays` option must either be an array or null"));return}if(this.options.parallelUploads>1)for(var n=0,o=["uploadUrl","uploadSize","uploadLengthDeferred"];n<o.length;n++){var a=o[n];if(this.options[a]){this._emitError(new Error("tus: cannot use the ".concat(a," option when parallelUploads is enabled")));return}}if(this.options.parallelUploadBoundaries){if(this.options.parallelUploads<=1){this._emitError(new Error("tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled"));return}if(this.options.parallelUploads!==this.options.parallelUploadBoundaries.length){this._emitError(new Error("tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`"));return}}this.options.fingerprint(i,this.options).then(function(l){return t._fingerprint=l,t._source?t._source:t.options.fileReader.openFile(i,t.options.chunkSize)}).then(function(l){if(t._source=l,t.options.uploadLengthDeferred)t._size=null;else if(t.options.uploadSize!=null){if(t._size=Number(t.options.uploadSize),Number.isNaN(t._size)){t._emitError(new Error("tus: cannot convert `uploadSize` option into a number"));return}}else if(t._size=t._source.size,t._size==null){t._emitError(new Error("tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option"));return}t.options.parallelUploads>1||t._parallelUploadUrls!=null?t._startParallelUpload():t._startSingleUpload();}).catch(function(l){t._emitError(l);});}},{key:"_startParallelUpload",value:function(){var t,i=this,r=this._size,n=0;this._parallelUploads=[];var o=this._parallelUploadUrls!=null?this._parallelUploadUrls.length:this.options.parallelUploads,a=(t=this.options.parallelUploadBoundaries)!==null&&t!==void 0?t:tM(this._source.size,o);this._parallelUploadUrls&&a.forEach(function(c,u){c.uploadUrl=i._parallelUploadUrls[u]||null;}),this._parallelUploadUrls=new Array(a.length);var l=a.map(function(c,u){var h=0;return i._source.slice(c.start,c.end).then(function(f){var m=f.value;return new Promise(function(p,g){var E=ko(ko({},i.options),{},{uploadUrl:c.uploadUrl||null,storeFingerprintForResuming:false,removeFingerprintOnSuccess:false,parallelUploads:1,parallelUploadBoundaries:null,metadata:i.options.metadataForPartialUploads,headers:ko(ko({},i.options.headers),{},{"Upload-Concat":"partial"}),onSuccess:p,onError:g,onProgress:function(S){n=n-h+S,h=S,i._emitProgress(n,r);},onUploadUrlAvailable:function(){i._parallelUploadUrls[u]=y.url,i._parallelUploadUrls.filter(function(S){return !!S}).length===a.length&&i._saveUploadInUrlStorage();}}),y=new s(m,E);y.start(),i._parallelUploads.push(y);})})}),d;Promise.all(l).then(function(){d=i._openRequest("POST",i.options.endpoint),d.setHeader("Upload-Concat","final;".concat(i._parallelUploadUrls.join(" ")));var c=UA(i.options.metadata);return c!==""&&d.setHeader("Upload-Metadata",c),i._sendRequest(d,null)}).then(function(c){if(!wo(c.getStatus(),200)){i._emitHttpError(d,c,"tus: unexpected response while creating upload");return}var u=c.getHeader("Location");if(u==null){i._emitHttpError(d,c,"tus: invalid or missing Location header");return}i.url=BA(i.options.endpoint,u),or("Created upload at ".concat(i.url)),i._emitSuccess(c);}).catch(function(c){i._emitError(c);});}},{key:"_startSingleUpload",value:function(){if(this._aborted=false,this.url!=null){or("Resuming upload from previous URL: ".concat(this.url)),this._resumeUpload();return}if(this.options.uploadUrl!=null){or("Resuming upload from provided URL: ".concat(this.options.uploadUrl)),this.url=this.options.uploadUrl,this._resumeUpload();return}this._createUpload();}},{key:"abort",value:function(t){var i=this;if(this._parallelUploads!=null){var r=Y1(this._parallelUploads),n;try{for(r.s();!(n=r.n()).done;){var o=n.value;o.abort(t);}}catch(a){r.e(a);}finally{r.f();}}return this._req!==null&&this._req.abort(),this._aborted=true,this._retryTimeout!=null&&(clearTimeout(this._retryTimeout),this._retryTimeout=null),!t||this.url==null?Promise.resolve():s.terminate(this.url,this.options).then(function(){return i._removeFromUrlStorage()})}},{key:"_emitHttpError",value:function(t,i,r,n){this._emitError(new xo(r,n,t,i));}},{key:"_emitError",value:function(t){var i=this;if(!this._aborted){if(this.options.retryDelays!=null){var r=this._offset!=null&&this._offset>this._offsetBeforeRetry;if(r&&(this._retryAttempt=0),$A(t,this._retryAttempt,this.options)){var n=this.options.retryDelays[this._retryAttempt++];this._offsetBeforeRetry=this._offset,this._retryTimeout=setTimeout(function(){i.start();},n);return}}if(typeof this.options.onError=="function")this.options.onError(t);else throw t}}},{key:"_emitSuccess",value:function(t){this.options.removeFingerprintOnSuccess&&this._removeFromUrlStorage(),typeof this.options.onSuccess=="function"&&this.options.onSuccess({lastResponse:t});}},{key:"_emitProgress",value:function(t,i){typeof this.options.onProgress=="function"&&this.options.onProgress(t,i);}},{key:"_emitChunkComplete",value:function(t,i,r){typeof this.options.onChunkComplete=="function"&&this.options.onChunkComplete(t,i,r);}},{key:"_createUpload",value:function(){var t=this;if(!this.options.endpoint){this._emitError(new Error("tus: unable to create upload because no endpoint is provided"));return}var i=this._openRequest("POST",this.options.endpoint);this.options.uploadLengthDeferred?i.setHeader("Upload-Defer-Length","1"):i.setHeader("Upload-Length","".concat(this._size));var r=UA(this.options.metadata);r!==""&&i.setHeader("Upload-Metadata",r);var n;this.options.uploadDataDuringCreation&&!this.options.uploadLengthDeferred?(this._offset=0,n=this._addChunkToRequest(i)):((this.options.protocol===$h||this.options.protocol===Ul)&&i.setHeader("Upload-Complete","?0"),n=this._sendRequest(i,null)),n.then(function(o){if(!wo(o.getStatus(),200)){t._emitHttpError(i,o,"tus: unexpected response while creating upload");return}var a=o.getHeader("Location");if(a==null){t._emitHttpError(i,o,"tus: invalid or missing Location header");return}if(t.url=BA(t.options.endpoint,a),or("Created upload at ".concat(t.url)),typeof t.options.onUploadUrlAvailable=="function"&&t.options.onUploadUrlAvailable(),t._size===0){t._emitSuccess(o),t._source.close();return}t._saveUploadInUrlStorage().then(function(){t.options.uploadDataDuringCreation?t._handleUploadResponse(i,o):(t._offset=0,t._performUpload());});}).catch(function(o){t._emitHttpError(i,null,"tus: failed to create upload",o);});}},{key:"_resumeUpload",value:function(){var t=this,i=this._openRequest("HEAD",this.url),r=this._sendRequest(i,null);r.then(function(n){var o=n.getStatus();if(!wo(o,200)){if(o===423){t._emitHttpError(i,n,"tus: upload is currently locked; retry later");return}if(wo(o,400)&&t._removeFromUrlStorage(),!t.options.endpoint){t._emitHttpError(i,n,"tus: unable to resume upload (new upload cannot be created without an endpoint)");return}t.url=null,t._createUpload();return}var a=Number.parseInt(n.getHeader("Upload-Offset"),10);if(Number.isNaN(a)){t._emitHttpError(i,n,"tus: invalid or missing offset value");return}var l=Number.parseInt(n.getHeader("Upload-Length"),10);if(Number.isNaN(l)&&!t.options.uploadLengthDeferred&&t.options.protocol===Fh){t._emitHttpError(i,n,"tus: invalid or missing length value");return}typeof t.options.onUploadUrlAvailable=="function"&&t.options.onUploadUrlAvailable(),t._saveUploadInUrlStorage().then(function(){if(a===l){t._emitProgress(l,l),t._emitSuccess(n);return}t._offset=a,t._performUpload();});}).catch(function(n){t._emitHttpError(i,null,"tus: failed to resume upload",n);});}},{key:"_performUpload",value:function(){var t=this;if(!this._aborted){var i;this.options.overridePatchMethod?(i=this._openRequest("POST",this.url),i.setHeader("X-HTTP-Method-Override","PATCH")):i=this._openRequest("PATCH",this.url),i.setHeader("Upload-Offset","".concat(this._offset));var r=this._addChunkToRequest(i);r.then(function(n){if(!wo(n.getStatus(),200)){t._emitHttpError(i,n,"tus: unexpected response while uploading chunk");return}t._handleUploadResponse(i,n);}).catch(function(n){t._aborted||t._emitHttpError(i,null,"tus: failed to upload chunk at offset ".concat(t._offset),n);});}}},{key:"_addChunkToRequest",value:function(t){var i=this,r=this._offset,n=this._offset+this.options.chunkSize;return t.setProgressHandler(function(o){i._emitProgress(r+o,i._size);}),this.options.protocol===Fh?t.setHeader("Content-Type","application/offset+octet-stream"):this.options.protocol===Ul&&t.setHeader("Content-Type","application/partial-upload"),(n===Number.POSITIVE_INFINITY||n>this._size)&&!this.options.uploadLengthDeferred&&(n=this._size),this._source.slice(r,n).then(function(o){var a=o.value,l=o.done,d=a!=null&&a.size?a.size:0;i.options.uploadLengthDeferred&&l&&(i._size=i._offset+d,t.setHeader("Upload-Length","".concat(i._size)));var c=i._offset+d;return !i.options.uploadLengthDeferred&&l&&c!==i._size?Promise.reject(new Error("upload was configured with a size of ".concat(i._size," bytes, but the source is done after ").concat(c," bytes"))):a===null?i._sendRequest(t):((i.options.protocol===$h||i.options.protocol===Ul)&&t.setHeader("Upload-Complete",l?"?1":"?0"),i._emitProgress(i._offset,i._size),i._sendRequest(t,a))})}},{key:"_handleUploadResponse",value:function(t,i){var r=Number.parseInt(i.getHeader("Upload-Offset"),10);if(Number.isNaN(r)){this._emitHttpError(t,i,"tus: invalid or missing offset value");return}if(this._emitProgress(r,this._size),this._emitChunkComplete(r-this._offset,r,this._size),this._offset=r,r===this._size){this._emitSuccess(i),this._source.close();return}this._performUpload();}},{key:"_openRequest",value:function(t,i){var r=NA(t,i,this.options);return this._req=r,r}},{key:"_removeFromUrlStorage",value:function(){var t=this;this._urlStorageKey&&(this._urlStorage.removeUpload(this._urlStorageKey).catch(function(i){t._emitError(i);}),this._urlStorageKey=null);}},{key:"_saveUploadInUrlStorage",value:function(){var t=this;if(!this.options.storeFingerprintForResuming||!this._fingerprint||this._urlStorageKey!==null)return Promise.resolve();var i={size:this._size,metadata:this.options.metadata,creationTime:new Date().toString()};return this._parallelUploads?i.parallelUploadUrls=this._parallelUploadUrls:i.uploadUrl=this.url,this._urlStorage.addUpload(this._fingerprint,i).then(function(r){t._urlStorageKey=r;})}},{key:"_sendRequest",value:function(t){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;return FA(t,i,this.options)}}],[{key:"terminate",value:function(t){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=NA("DELETE",t,i);return FA(r,null,i).then(function(n){if(n.getStatus()!==204)throw new xo("tus: unexpected response while terminating upload",null,r,n)}).catch(function(n){if(n instanceof xo||(n=new xo("tus: failed to terminate upload",n,r,null)),!$A(n,0,i))throw n;var o=i.retryDelays[0],a=i.retryDelays.slice(1),l=ko(ko({},i),{},{retryDelays:a});return new Promise(function(d){return setTimeout(d,o)}).then(function(){return s.terminate(t,l)})})}}])})();function UA(s){return Object.entries(s).map(function(e){var t=HA(e,2),i=t[0],r=t[1];return "".concat(i," ").concat(EA.encode(String(r)))}).join(",")}function wo(s,e){return s>=e&&s<e+100}function NA(s,e,t){var i=t.httpStack.createRequest(s,e);t.protocol===$h?i.setHeader("Upload-Draft-Interop-Version","5"):t.protocol===Ul?i.setHeader("Upload-Draft-Interop-Version","6"):i.setHeader("Tus-Resumable","1.0.0");for(var r=t.headers||{},n=0,o=Object.entries(r);n<o.length;n++){var a=HA(o[n],2),l=a[0],d=a[1];i.setHeader(l,d);}if(t.addRequestId){var c=W0();i.setHeader("X-Request-ID",c);}return i}function FA(s,e,t){return j0.apply(this,arguments)}function j0(){return j0=V1(q0().mark(function s(e,t,i){var r;return q0().wrap(function(o){for(;;)switch(o.prev=o.next){case 0:if(typeof i.onBeforeRequest!="function"){o.next=3;break}return o.next=3,i.onBeforeRequest(e);case 3:return o.next=5,e.send(t);case 5:if(r=o.sent,typeof i.onAfterResponse!="function"){o.next=9;break}return o.next=9,i.onAfterResponse(e,r);case 9:return o.abrupt("return",r);case 10:case "end":return o.stop()}},s)})),j0.apply(this,arguments)}function eM(){var s=true;return typeof navigator<"u"&&navigator.onLine===false&&(s=false),s}function $A(s,e,t){return t.retryDelays==null||e>=t.retryDelays.length||s.originalRequest==null?false:t&&typeof t.onShouldRetry=="function"?t.onShouldRetry(s,e,t):qA(s)}function qA(s){var e=s.originalResponse?s.originalResponse.getStatus():0;return (!wo(e,400)||e===409||e===423)&&eM()}function BA(s,e){return new VA.default(e,s).toString()}function tM(s,e){for(var t=Math.floor(s/e),i=[],r=0;r<e;r++)i.push({start:t*r,end:t*(r+1)});return i[e-1].end=s,i}WA.defaultOptions=J1;var Bh=WA;var iM=function(){return typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative"},Hh=iM;function Y0(s){return new Promise(function(e,t){var i=new XMLHttpRequest;i.responseType="blob",i.onload=function(){var r=i.response;e(r);},i.onerror=function(r){t(r);},i.open("GET",s),i.send();})}var sM=function(){return typeof window<"u"&&(typeof window.PhoneGap<"u"||typeof window.Cordova<"u"||typeof window.cordova<"u")},jA=sM;function z0(s){return new Promise(function(e,t){var i=new FileReader;i.onload=function(){var r=new Uint8Array(i.result);e({value:r});},i.onerror=function(r){t(r);},i.readAsArrayBuffer(s);})}function Nl(s){"@babel/helpers - typeof";return Nl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Nl(s)}function rM(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function YA(s,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||false,i.configurable=true,"value"in i&&(i.writable=true),Object.defineProperty(s,oM(i.key),i);}}function nM(s,e,t){return e&&YA(s.prototype,e),Object.defineProperty(s,"prototype",{writable:false}),s}function oM(s){var e=aM(s,"string");return Nl(e)=="symbol"?e:e+""}function aM(s,e){if(Nl(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(Nl(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return (String)(s)}var Q0=(function(){function s(e){rM(this,s),this._file=e,this.size=e.size;}return nM(s,[{key:"slice",value:function(t,i){if(jA())return z0(this._file.slice(t,i));var r=this._file.slice(t,i),n=i>=this.size;return Promise.resolve({value:r,done:n})}},{key:"close",value:function(){}}])})();function Fl(s){"@babel/helpers - typeof";return Fl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Fl(s)}function lM(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function zA(s,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||false,i.configurable=true,"value"in i&&(i.writable=true),Object.defineProperty(s,cM(i.key),i);}}function dM(s,e,t){return e&&zA(s.prototype,e),Object.defineProperty(s,"prototype",{writable:false}),s}function cM(s){var e=uM(s,"string");return Fl(e)=="symbol"?e:e+""}function uM(s,e){if(Fl(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(Fl(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return (String)(s)}function QA(s){return s===void 0?0:s.size!==void 0?s.size:s.length}function hM(s,e){if(s.concat)return s.concat(e);if(s instanceof Blob)return new Blob([s,e],{type:s.type});if(s.set){var t=new s.constructor(s.length+e.length);return t.set(s),t.set(e,s.length),t}throw new Error("Unknown data type")}var XA=(function(){function s(e){lM(this,s),this._buffer=void 0,this._bufferOffset=0,this._reader=e,this._done=false;}return dM(s,[{key:"slice",value:function(t,i){return t<this._bufferOffset?Promise.reject(new Error("Requested data is before the reader's current offset")):this._readUntilEnoughDataOrDone(t,i)}},{key:"_readUntilEnoughDataOrDone",value:function(t,i){var r=this,n=i<=this._bufferOffset+QA(this._buffer);if(this._done||n){var o=this._getDataFromBuffer(t,i),a=o==null?this._done:false;return Promise.resolve({value:o,done:a})}return this._reader.read().then(function(l){var d=l.value,c=l.done;return c?r._done=true:r._buffer===void 0?r._buffer=d:r._buffer=hM(r._buffer,d),r._readUntilEnoughDataOrDone(t,i)})}},{key:"_getDataFromBuffer",value:function(t,i){t>this._bufferOffset&&(this._buffer=this._buffer.slice(t-this._bufferOffset),this._bufferOffset=t);var r=QA(this._buffer)===0;return this._done&&r?null:this._buffer.slice(0,i-t)}},{key:"close",value:function(){this._reader.cancel&&this._reader.cancel();}}])})();function rn(s){"@babel/helpers - typeof";return rn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},rn(s)}function X0(){X0=function(){return e};var s,e={},t=Object.prototype,i=t.hasOwnProperty,r=Object.defineProperty||function(x,T,I){x[T]=I.value;},n=typeof Symbol=="function"?Symbol:{},o=n.iterator||"@@iterator",a=n.asyncIterator||"@@asyncIterator",l=n.toStringTag||"@@toStringTag";function d(x,T,I){return Object.defineProperty(x,T,{value:I,enumerable:true,configurable:true,writable:true}),x[T]}try{d({},"");}catch{d=function(I,P,U){return I[P]=U};}function c(x,T,I,P){var U=T&&T.prototype instanceof E?T:E,w=Object.create(U.prototype),B=new X(P||[]);return r(w,"_invoke",{value:k(x,I,B)}),w}function u(x,T,I){try{return {type:"normal",arg:x.call(T,I)}}catch(P){return {type:"throw",arg:P}}}e.wrap=c;var h="suspendedStart",f="suspendedYield",m="executing",p="completed",g={};function E(){}function y(){}function _(){}var S={};d(S,o,function(){return this});var L=Object.getPrototypeOf,O=L&&L(L(Y([])));O&&O!==t&&i.call(O,o)&&(S=O);var R=_.prototype=E.prototype=Object.create(S);function D(x){["next","throw","return"].forEach(function(T){d(x,T,function(I){return this._invoke(T,I)});});}function C(x,T){function I(U,w,B,z){var te=u(x[U],x,w);if(te.type!=="throw"){var se=te.arg,re=se.value;return re&&rn(re)=="object"&&i.call(re,"__await")?T.resolve(re.__await).then(function(Ie){I("next",Ie,B,z);},function(Ie){I("throw",Ie,B,z);}):T.resolve(re).then(function(Ie){se.value=Ie,B(se);},function(Ie){return I("throw",Ie,B,z)})}z(te.arg);}var P;r(this,"_invoke",{value:function(w,B){function z(){return new T(function(te,se){I(w,B,te,se);})}return P=P?P.then(z,z):z()}});}function k(x,T,I){var P=h;return function(U,w){if(P===m)throw Error("Generator is already running");if(P===p){if(U==="throw")throw w;return {value:s,done:true}}for(I.method=U,I.arg=w;;){var B=I.delegate;if(B){var z=H(B,I);if(z){if(z===g)continue;return z}}if(I.method==="next")I.sent=I._sent=I.arg;else if(I.method==="throw"){if(P===h)throw P=p,I.arg;I.dispatchException(I.arg);}else I.method==="return"&&I.abrupt("return",I.arg);P=m;var te=u(x,T,I);if(te.type==="normal"){if(P=I.done?p:f,te.arg===g)continue;return {value:te.arg,done:I.done}}te.type==="throw"&&(P=p,I.method="throw",I.arg=te.arg);}}}function H(x,T){var I=T.method,P=x.iterator[I];if(P===s)return T.delegate=null,I==="throw"&&x.iterator.return&&(T.method="return",T.arg=s,H(x,T),T.method==="throw")||I!=="return"&&(T.method="throw",T.arg=new TypeError("The iterator does not provide a '"+I+"' method")),g;var U=u(P,x.iterator,T.arg);if(U.type==="throw")return T.method="throw",T.arg=U.arg,T.delegate=null,g;var w=U.arg;return w?w.done?(T[x.resultName]=w.value,T.next=x.nextLoc,T.method!=="return"&&(T.method="next",T.arg=s),T.delegate=null,g):w:(T.method="throw",T.arg=new TypeError("iterator result is not an object"),T.delegate=null,g)}function q(x){var T={tryLoc:x[0]};1 in x&&(T.catchLoc=x[1]),2 in x&&(T.finallyLoc=x[2],T.afterLoc=x[3]),this.tryEntries.push(T);}function j(x){var T=x.completion||{};T.type="normal",delete T.arg,x.completion=T;}function X(x){this.tryEntries=[{tryLoc:"root"}],x.forEach(q,this),this.reset(true);}function Y(x){if(x||x===""){var T=x[o];if(T)return T.call(x);if(typeof x.next=="function")return x;if(!isNaN(x.length)){var I=-1,P=function U(){for(;++I<x.length;)if(i.call(x,I))return U.value=x[I],U.done=false,U;return U.value=s,U.done=true,U};return P.next=P}}throw new TypeError(rn(x)+" is not iterable")}return y.prototype=_,r(R,"constructor",{value:_,configurable:true}),r(_,"constructor",{value:y,configurable:true}),y.displayName=d(_,l,"GeneratorFunction"),e.isGeneratorFunction=function(x){var T=typeof x=="function"&&x.constructor;return !!T&&(T===y||(T.displayName||T.name)==="GeneratorFunction")},e.mark=function(x){return Object.setPrototypeOf?Object.setPrototypeOf(x,_):(x.__proto__=_,d(x,l,"GeneratorFunction")),x.prototype=Object.create(R),x},e.awrap=function(x){return {__await:x}},D(C.prototype),d(C.prototype,a,function(){return this}),e.AsyncIterator=C,e.async=function(x,T,I,P,U){U===void 0&&(U=Promise);var w=new C(c(x,T,I,P),U);return e.isGeneratorFunction(T)?w:w.next().then(function(B){return B.done?B.value:w.next()})},D(R),d(R,l,"Generator"),d(R,o,function(){return this}),d(R,"toString",function(){return "[object Generator]"}),e.keys=function(x){var T=Object(x),I=[];for(var P in T)I.push(P);return I.reverse(),function U(){for(;I.length;){var w=I.pop();if(w in T)return U.value=w,U.done=false,U}return U.done=true,U}},e.values=Y,X.prototype={constructor:X,reset:function(T){if(this.prev=0,this.next=0,this.sent=this._sent=s,this.done=false,this.delegate=null,this.method="next",this.arg=s,this.tryEntries.forEach(j),!T)for(var I in this)I.charAt(0)==="t"&&i.call(this,I)&&!isNaN(+I.slice(1))&&(this[I]=s);},stop:function(){this.done=true;var T=this.tryEntries[0].completion;if(T.type==="throw")throw T.arg;return this.rval},dispatchException:function(T){if(this.done)throw T;var I=this;function P(se,re){return B.type="throw",B.arg=T,I.next=se,re&&(I.method="next",I.arg=s),!!re}for(var U=this.tryEntries.length-1;U>=0;--U){var w=this.tryEntries[U],B=w.completion;if(w.tryLoc==="root")return P("end");if(w.tryLoc<=this.prev){var z=i.call(w,"catchLoc"),te=i.call(w,"finallyLoc");if(z&&te){if(this.prev<w.catchLoc)return P(w.catchLoc,true);if(this.prev<w.finallyLoc)return P(w.finallyLoc)}else if(z){if(this.prev<w.catchLoc)return P(w.catchLoc,true)}else {if(!te)throw Error("try statement without catch or finally");if(this.prev<w.finallyLoc)return P(w.finallyLoc)}}}},abrupt:function(T,I){for(var P=this.tryEntries.length-1;P>=0;--P){var U=this.tryEntries[P];if(U.tryLoc<=this.prev&&i.call(U,"finallyLoc")&&this.prev<U.finallyLoc){var w=U;break}}w&&(T==="break"||T==="continue")&&w.tryLoc<=I&&I<=w.finallyLoc&&(w=null);var B=w?w.completion:{};return B.type=T,B.arg=I,w?(this.method="next",this.next=w.finallyLoc,g):this.complete(B)},complete:function(T,I){if(T.type==="throw")throw T.arg;return T.type==="break"||T.type==="continue"?this.next=T.arg:T.type==="return"?(this.rval=this.arg=T.arg,this.method="return",this.next="end"):T.type==="normal"&&I&&(this.next=I),g},finish:function(T){for(var I=this.tryEntries.length-1;I>=0;--I){var P=this.tryEntries[I];if(P.finallyLoc===T)return this.complete(P.completion,P.afterLoc),j(P),g}},catch:function(T){for(var I=this.tryEntries.length-1;I>=0;--I){var P=this.tryEntries[I];if(P.tryLoc===T){var U=P.completion;if(U.type==="throw"){var w=U.arg;j(P);}return w}}throw Error("illegal catch attempt")},delegateYield:function(T,I,P){return this.delegate={iterator:Y(T),resultName:I,nextLoc:P},this.method==="next"&&(this.arg=s),g}},e}function ZA(s,e,t,i,r,n,o){try{var a=s[n](o),l=a.value;}catch(d){t(d);return}a.done?e(l):Promise.resolve(l).then(i,r);}function fM(s){return function(){var e=this,t=arguments;return new Promise(function(i,r){var n=s.apply(e,t);function o(l){ZA(n,i,r,o,a,"next",l);}function a(l){ZA(n,i,r,o,a,"throw",l);}o(void 0);})}}function mM(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function JA(s,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||false,i.configurable=true,"value"in i&&(i.writable=true),Object.defineProperty(s,gM(i.key),i);}}function pM(s,e,t){return e&&JA(s.prototype,e),Object.defineProperty(s,"prototype",{writable:false}),s}function gM(s){var e=vM(s,"string");return rn(e)=="symbol"?e:e+""}function vM(s,e){if(rn(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(rn(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return (String)(s)}var eI=(function(){function s(){mM(this,s);}return pM(s,[{key:"openFile",value:(function(){var e=fM(X0().mark(function i(r,n){var o;return X0().wrap(function(l){for(;;)switch(l.prev=l.next){case 0:if(!(Hh()&&r&&typeof r.uri<"u")){l.next=11;break}return l.prev=1,l.next=4,Y0(r.uri);case 4:return o=l.sent,l.abrupt("return",new Q0(o));case 8:throw l.prev=8,l.t0=l.catch(1),new Error("tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. ".concat(l.t0));case 11:if(!(typeof r.slice=="function"&&typeof r.size<"u")){l.next=13;break}return l.abrupt("return",Promise.resolve(new Q0(r)));case 13:if(typeof r.read!="function"){l.next=18;break}if(n=Number(n),Number.isFinite(n)){l.next=17;break}return l.abrupt("return",Promise.reject(new Error("cannot create source for stream without a finite value for the `chunkSize` option")));case 17:return l.abrupt("return",Promise.resolve(new XA(r,n)));case 18:return l.abrupt("return",Promise.reject(new Error("source object may only be an instance of File, Blob, or Reader in this environment")));case 19:case "end":return l.stop()}},i,null,[[1,8]])}));function t(i,r){return e.apply(this,arguments)}return t})()}])})();function Z0(s,e){return Hh()?Promise.resolve(EM(s,e)):Promise.resolve(["tus-br",s.name,s.type,s.size,s.lastModified,e.endpoint].join("-"))}function EM(s,e){var t=s.exif?yM(JSON.stringify(s.exif)):"noexif";return ["tus-rn",s.name||"noname",s.size||"nosize",t,e.endpoint].join("/")}function yM(s){var e=0;if(s.length===0)return e;for(var t=0;t<s.length;t++){var i=s.charCodeAt(t);e=(e<<5)-e+i,e&=e;}return e}function $l(s){"@babel/helpers - typeof";return $l=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},$l(s)}function J0(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function tI(s,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||false,i.configurable=true,"value"in i&&(i.writable=true),Object.defineProperty(s,bM(i.key),i);}}function ev(s,e,t){return e&&tI(s.prototype,e),Object.defineProperty(s,"prototype",{writable:false}),s}function bM(s){var e=_M(s,"string");return $l(e)=="symbol"?e:e+""}function _M(s,e){if($l(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if($l(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return (String)(s)}var iI=(function(){function s(){J0(this,s);}return ev(s,[{key:"createRequest",value:function(t,i){return new TM(t,i)}},{key:"getName",value:function(){return "XHRHttpStack"}}])})();var TM=(function(){function s(e,t){J0(this,s),this._xhr=new XMLHttpRequest,this._xhr.open(e,t,true),this._method=e,this._url=t,this._headers={};}return ev(s,[{key:"getMethod",value:function(){return this._method}},{key:"getURL",value:function(){return this._url}},{key:"setHeader",value:function(t,i){this._xhr.setRequestHeader(t,i),this._headers[t]=i;}},{key:"getHeader",value:function(t){return this._headers[t]}},{key:"setProgressHandler",value:function(t){"upload"in this._xhr&&(this._xhr.upload.onprogress=function(i){i.lengthComputable&&t(i.loaded);});}},{key:"send",value:function(){var t=this,i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;return new Promise(function(r,n){t._xhr.onload=function(){r(new SM(t._xhr));},t._xhr.onerror=function(o){n(o);},t._xhr.send(i);})}},{key:"abort",value:function(){return this._xhr.abort(),Promise.resolve()}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})(),SM=(function(){function s(e){J0(this,s),this._xhr=e;}return ev(s,[{key:"getStatus",value:function(){return this._xhr.status}},{key:"getHeader",value:function(t){return this._xhr.getResponseHeader(t)}},{key:"getBody",value:function(){return this._xhr.responseText}},{key:"getUnderlyingObject",value:function(){return this._xhr}}])})();function Bl(s){"@babel/helpers - typeof";return Bl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Bl(s)}function AM(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function sI(s,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||false,i.configurable=true,"value"in i&&(i.writable=true),Object.defineProperty(s,xM(i.key),i);}}function IM(s,e,t){return e&&sI(s.prototype,e),Object.defineProperty(s,"prototype",{writable:false}),s}function xM(s){var e=LM(s,"string");return Bl(e)=="symbol"?e:e+""}function LM(s,e){if(Bl(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(Bl(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return (String)(s)}var iv=false;try{iv="localStorage"in window,Gh="tusSupport",tv=localStorage.getItem(Gh),localStorage.setItem(Gh,tv),tv===null&&localStorage.removeItem(Gh);}catch(s){if(s.code===s.SECURITY_ERR||s.code===s.QUOTA_EXCEEDED_ERR)iv=false;else throw s}var Gh,tv,rI=iv,nI=(function(){function s(){AM(this,s);}return IM(s,[{key:"findAllUploads",value:function(){var t=this._findEntries("tus::");return Promise.resolve(t)}},{key:"findUploadsByFingerprint",value:function(t){var i=this._findEntries("tus::".concat(t,"::"));return Promise.resolve(i)}},{key:"removeUpload",value:function(t){return localStorage.removeItem(t),Promise.resolve()}},{key:"addUpload",value:function(t,i){var r=Math.round(Math.random()*1e12),n="tus::".concat(t,"::").concat(r);return localStorage.setItem(n,JSON.stringify(i)),Promise.resolve(n)}},{key:"_findEntries",value:function(t){for(var i=[],r=0;r<localStorage.length;r++){var n=localStorage.key(r);if(n.indexOf(t)===0)try{var o=JSON.parse(localStorage.getItem(n));o.urlStorageKey=n,i.push(o);}catch{}}return i}}])})();function Do(s){"@babel/helpers - typeof";return Do=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Do(s)}function RM(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function oI(s,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||false,i.configurable=true,"value"in i&&(i.writable=true),Object.defineProperty(s,cI(i.key),i);}}function kM(s,e,t){return t&&oI(s,t),Object.defineProperty(s,"prototype",{writable:false}),s}function wM(s,e,t){return e=Kh(e),CM(s,dI()?Reflect.construct(e,t||[],Kh(s).constructor):e.apply(s,t))}function CM(s,e){if(e&&(Do(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return DM(s)}function DM(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function dI(){try{var s=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch{}return (dI=function(){return !!s})()}function Kh(s){return Kh=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Kh(s)}function MM(s,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");s.prototype=Object.create(e&&e.prototype,{constructor:{value:s,writable:true,configurable:true}}),Object.defineProperty(s,"prototype",{writable:false}),e&&sv(s,e);}function sv(s,e){return sv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(i,r){return i.__proto__=r,i},sv(s,e)}function aI(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i);}return t}function Co(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?aI(Object(t),true).forEach(function(i){PM(s,i,t[i]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):aI(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i));});}return s}function PM(s,e,t){return e=cI(e),e in s?Object.defineProperty(s,e,{value:t,enumerable:true,configurable:true,writable:true}):s[e]=t,s}function cI(s){var e=OM(s,"string");return Do(e)=="symbol"?e:e+""}function OM(s,e){if(Do(s)!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(Do(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(s)}var lI=Co(Co({},Bh.defaultOptions),{},{httpStack:new iI,fileReader:new eI,urlStorage:rI?new nI:new JS,fingerprint:Z0}),uI=(function(s){function e(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return RM(this,e),i=Co(Co({},lI),i),wM(this,e,[t,i])}return MM(e,s),kM(e,null,[{key:"terminate",value:function(i){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return r=Co(Co({},lI),r),Bh.terminate(i,r)}}])})(Bh);var Gl=s=>typeof s=="function"?s:function(){return s},NM=typeof self<"u"?self:null,Mo=typeof window<"u"?window:null,hs=NM||Mo||globalThis,FM="2.0.0",fs={connecting:0,open:1,closing:2,closed:3},$M=1e4,BM=1e3,ni={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Cs={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},rv={longpoll:"longpoll",websocket:"websocket"},HM={complete:4},nv="base64url.bearer.phx.",Vh=class{constructor(s,e,t,i){this.channel=s,this.event=e,this.payload=t||function(){return {}},this.receivedResp=null,this.timeout=i,this.timeoutTimer=null,this.recHooks=[],this.sent=false;}resend(s){this.timeout=s,this.reset(),this.send();}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=true,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}));}receive(s,e){return this.hasReceived(s)&&e(this.receivedResp.response),this.recHooks.push({status:s,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=false;}matchReceive({status:s,response:e,_ref:t}){this.recHooks.filter(i=>i.status===s).forEach(i=>i.callback(e));}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent);}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null;}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,s=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=s,this.matchReceive(s);}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{});},this.timeout);}hasReceived(s){return this.receivedResp&&this.receivedResp.status===s}trigger(s,e){this.channel.trigger(this.refEvent,{status:s,response:e});}},hI=class{constructor(s,e){this.callback=s,this.timerCalc=e,this.timer=null,this.tries=0;}reset(){this.tries=0,clearTimeout(this.timer);}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback();},this.timerCalc(this.tries+1));}},GM=class{constructor(s,e,t){this.state=ni.closed,this.topic=s,this.params=Gl(e||{}),this.socket=t,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=false,this.joinPush=new Vh(this,Cs.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new hI(()=>{this.socket.isConnected()&&this.rejoin();},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin();})),this.joinPush.receive("ok",()=>{this.state=ni.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[];}),this.joinPush.receive("error",()=>{this.state=ni.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=ni.closed,this.socket.remove(this);}),this.onError(i=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,i),this.isJoining()&&this.joinPush.reset(),this.state=ni.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new Vh(this,Cs.leave,Gl({}),this.timeout).send(),this.state=ni.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.on(Cs.reply,(i,r)=>{this.trigger(this.replyEventName(r),i);});}join(s=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=s,this.joinedOnce=true,this.rejoin(),this.joinPush}onClose(s){this.on(Cs.close,s);}onError(s){return this.on(Cs.error,e=>s(e))}on(s,e){let t=this.bindingRef++;return this.bindings.push({event:s,ref:t,callback:e}),t}off(s,e){this.bindings=this.bindings.filter(t=>!(t.event===s&&(typeof e>"u"||e===t.ref)));}canPush(){return this.socket.isConnected()&&this.isJoined()}push(s,e,t=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${s}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let i=new Vh(this,s,function(){return e},t);return this.canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}leave(s=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=ni.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Cs.close,"leave");},t=new Vh(this,Cs.leave,Gl({}),s);return t.receive("ok",()=>e()).receive("timeout",()=>e()),t.send(),this.canPush()||t.trigger("ok",{}),t}onMessage(s,e,t){return e}isMember(s,e,t,i){return this.topic!==s?false:i&&i!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:s,event:e,payload:t,joinRef:i}),false):true}joinRef(){return this.joinPush.ref}rejoin(s=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=ni.joining,this.joinPush.resend(s));}trigger(s,e,t,i){let r=this.onMessage(s,e,t,i);if(e&&!r)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let n=this.bindings.filter(o=>o.event===s);for(let o=0;o<n.length;o++)n[o].callback(r,t,i||this.joinRef());}replyEventName(s){return `chan_reply_${s}`}isClosed(){return this.state===ni.closed}isErrored(){return this.state===ni.errored}isJoined(){return this.state===ni.joined}isJoining(){return this.state===ni.joining}isLeaving(){return this.state===ni.leaving}},qh=class{static request(s,e,t,i,r,n,o){if(hs.XDomainRequest){let a=new hs.XDomainRequest;return this.xdomainRequest(a,s,e,i,r,n,o)}else if(hs.XMLHttpRequest){let a=new hs.XMLHttpRequest;return this.xhrRequest(a,s,e,t,i,r,n,o)}else {if(hs.fetch&&hs.AbortController)return this.fetchRequest(s,e,t,i,r,n,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(s,e,t,i,r,n,o){let a={method:s,headers:t,body:i},l=null;if(r){l=new AbortController;setTimeout(()=>l.abort(),r);a.signal=l.signal;}return hs.fetch(e,a).then(d=>d.text()).then(d=>this.parseJSON(d)).then(d=>o&&o(d)).catch(d=>{d.name==="AbortError"&&n?n():o&&o(null);}),l}static xdomainRequest(s,e,t,i,r,n,o){return s.timeout=r,s.open(e,t),s.onload=()=>{let a=this.parseJSON(s.responseText);o&&o(a);},n&&(s.ontimeout=n),s.onprogress=()=>{},s.send(i),s}static xhrRequest(s,e,t,i,r,n,o,a){s.open(e,t,true),s.timeout=n;for(let[l,d]of Object.entries(i))s.setRequestHeader(l,d);return s.onerror=()=>a&&a(null),s.onreadystatechange=()=>{if(s.readyState===HM.complete&&a){let l=this.parseJSON(s.responseText);a(l);}},o&&(s.ontimeout=o),s.send(r),s}static parseJSON(s){if(!s||s==="")return null;try{return JSON.parse(s)}catch{return console&&console.log("failed to parse JSON response",s),null}}static serialize(s,e){let t=[];for(var i in s){if(!Object.prototype.hasOwnProperty.call(s,i))continue;let r=e?`${e}[${i}]`:i,n=s[i];typeof n=="object"?t.push(this.serialize(n,r)):t.push(encodeURIComponent(r)+"="+encodeURIComponent(n));}return t.join("&")}static appendParams(s,e){if(Object.keys(e).length===0)return s;let t=s.match(/\?/)?"&":"?";return `${s}${t}${this.serialize(e)}`}},KM=s=>{let e="",t=new Uint8Array(s),i=t.byteLength;for(let r=0;r<i;r++)e+=String.fromCharCode(t[r]);return btoa(e)},Hl=class{constructor(s,e){e&&e.length===2&&e[1].startsWith(nv)&&(this.authToken=atob(e[1].slice(nv.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=true,this.reqs=new Set,this.awaitingBatchAck=false,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(s),this.readyState=fs.connecting,setTimeout(()=>this.poll(),0);}normalizeEndpoint(s){return s.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+rv.websocket),"$1/"+rv.longpoll)}endpointURL(){return qh.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(s,e,t){this.close(s,e,t),this.readyState=fs.connecting;}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",false);}isActive(){return this.readyState===fs.open||this.readyState===fs.connecting}poll(){let s={Accept:"application/json"};this.authToken&&(s["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",s,null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:i,messages:r}=e;if(t===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",false);return}this.token=i;}else t=0;switch(t){case 200:r.forEach(n=>{setTimeout(()=>this.onmessage({data:n}),0);}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=fs.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",false);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${t}`)}});}send(s){typeof s!="string"&&(s=KM(s)),this.currentBatch?this.currentBatch.push(s):this.awaitingBatchAck?this.batchBuffer.push(s):(this.currentBatch=[s],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null;},0));}batchSend(s){this.awaitingBatchAck=true,this.ajax("POST",{"Content-Type":"application/x-ndjson"},s.join(`
2296
+ `),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=false,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",false)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]);});}close(s,e,t){for(let r of this.reqs)r.abort();this.readyState=fs.closed;let i=Object.assign({code:1e3,reason:void 0,wasClean:true},{code:s,reason:e,wasClean:t});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",i)):this.onclose(i);}ajax(s,e,t,i,r){let n,o=()=>{this.reqs.delete(n),i();};n=qh.request(s,this.endpointURL(),e,t,this.timeout,o,a=>{this.reqs.delete(n),this.isActive()&&r(a);}),this.reqs.add(n);}};var Wh={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(s,e){if(s.payload.constructor===ArrayBuffer)return e(this.binaryEncode(s));{let t=[s.join_ref,s.ref,s.topic,s.event,s.payload];return e(JSON.stringify(t))}},decode(s,e){if(s.constructor===ArrayBuffer)return e(this.binaryDecode(s));{let[t,i,r,n,o]=JSON.parse(s);return e({join_ref:t,ref:i,topic:r,event:n,payload:o})}},binaryEncode(s){let{join_ref:e,ref:t,event:i,topic:r,payload:n}=s,o=this.META_LENGTH+e.length+t.length+r.length+i.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),l=new DataView(a),d=0;l.setUint8(d++,this.KINDS.push),l.setUint8(d++,e.length),l.setUint8(d++,t.length),l.setUint8(d++,r.length),l.setUint8(d++,i.length),Array.from(e,u=>l.setUint8(d++,u.charCodeAt(0))),Array.from(t,u=>l.setUint8(d++,u.charCodeAt(0))),Array.from(r,u=>l.setUint8(d++,u.charCodeAt(0))),Array.from(i,u=>l.setUint8(d++,u.charCodeAt(0)));var c=new Uint8Array(a.byteLength+n.byteLength);return c.set(new Uint8Array(a),0),c.set(new Uint8Array(n),a.byteLength),c.buffer},binaryDecode(s){let e=new DataView(s),t=e.getUint8(0),i=new TextDecoder;switch(t){case this.KINDS.push:return this.decodePush(s,e,i);case this.KINDS.reply:return this.decodeReply(s,e,i);case this.KINDS.broadcast:return this.decodeBroadcast(s,e,i)}},decodePush(s,e,t){let i=e.getUint8(1),r=e.getUint8(2),n=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=t.decode(s.slice(o,o+i));o=o+i;let l=t.decode(s.slice(o,o+r));o=o+r;let d=t.decode(s.slice(o,o+n));o=o+n;let c=s.slice(o,s.byteLength);return {join_ref:a,ref:null,topic:l,event:d,payload:c}},decodeReply(s,e,t){let i=e.getUint8(1),r=e.getUint8(2),n=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=t.decode(s.slice(a,a+i));a=a+i;let d=t.decode(s.slice(a,a+r));a=a+r;let c=t.decode(s.slice(a,a+n));a=a+n;let u=t.decode(s.slice(a,a+o));a=a+o;let h=s.slice(a,s.byteLength),f={status:u,response:h};return {join_ref:l,ref:d,topic:c,event:Cs.reply,payload:f}},decodeBroadcast(s,e,t){let i=e.getUint8(1),r=e.getUint8(2),n=this.HEADER_LENGTH+2,o=t.decode(s.slice(n,n+i));n=n+i;let a=t.decode(s.slice(n,n+r));n=n+r;let l=s.slice(n,s.byteLength);return {join_ref:null,ref:null,topic:o,event:a,payload:l}}},fI=class{constructor(s,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||$M,this.transport=e.transport||hs.WebSocket||Hl,this.primaryPassedHealthCheck=false,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||hs&&hs.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Wh.encode.bind(Wh),this.defaultDecoder=Wh.decode.bind(Wh),this.closeWasClean=false,this.disconnecting=false,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=false,this.transport!==Hl?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let t=null;Mo&&Mo.addEventListener&&(Mo.addEventListener("pagehide",i=>{this.conn&&(this.disconnect(),t=this.connectClock);}),Mo.addEventListener("pageshow",i=>{t===this.connectClock&&(t=null,this.connect());}),Mo.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=true:(this.pageHidden=false,this.isConnected()||this.teardown(()=>this.connect()));})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.rejoinAfterMs=i=>e.rejoinAfterMs?e.rejoinAfterMs(i):[1e3,2e3,5e3][i-1]||1e4,this.reconnectAfterMs=i=>e.reconnectAfterMs?e.reconnectAfterMs(i):[10,50,100,150,200,250,500,1e3,2e3][i-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(i,r,n)=>{console.log(`${i}: ${r}`,n);}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Gl(e.params||{}),this.endPoint=`${s}/${rv.websocket}`,this.vsn=e.vsn||FM,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new hI(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(()=>this.connect());},this.reconnectAfterMs),this.authToken=e.authToken;}getLongPollTransport(){return Hl}replaceTransport(s){this.connectClock++,this.closeWasClean=true,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=s;}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let s=qh.appendParams(qh.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return s.charAt(0)!=="/"?s:s.charAt(1)==="/"?`${this.protocol()}:${s}`:`${this.protocol()}://${location.host}${s}`}disconnect(s,e,t){this.connectClock++,this.disconnecting=true,this.closeWasClean=true,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=false,s&&s();},e,t);}connect(s){s&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Gl(s)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Hl?this.connectWithFallback(Hl,this.longPollFallbackMs):this.transportConnect());}log(s,e,t){this.logger&&this.logger(s,e,t);}hasLogger(){return this.logger!==null}onOpen(s){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,s]),e}onClose(s){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,s]),e}onError(s){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,s]),e}onMessage(s){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,s]),e}ping(s){if(!this.isConnected())return false;let e=this.makeRef(),t=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let i=this.onMessage(r=>{r.ref===e&&(this.off([i]),s(Date.now()-t));});return true}transportConnect(){this.connectClock++,this.closeWasClean=false;let s;this.authToken&&(s=["phoenix",`${nv}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),s),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e);}getSession(s){return this.sessionStore&&this.sessionStore.getItem(s)}storeSession(s,e){this.sessionStore&&this.sessionStore.setItem(s,e);}connectWithFallback(s,e=2500){clearTimeout(this.fallbackTimer);let t=false,i=true,r,n,o=a=>{this.log("transport",`falling back to ${s.name}...`,a),this.off([r,n]),i=false,this.replaceTransport(s),this.transportConnect();};if(this.getSession(`phx:fallback:${s.name}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),n=this.onError(a=>{this.log("transport","error",a),i&&!t&&(clearTimeout(this.fallbackTimer),o(a));}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(t=true,!i)return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${s.name}`,"true"),this.log("transport",`established ${s.name} fallback`);clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(a=>{this.log("transport","connected to primary after",a),this.primaryPassedHealthCheck=true,clearTimeout(this.fallbackTimer);});}),this.transportConnect();}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer);}onConnOpen(){this.hasLogger()&&this.log("transport",`${this.transport.name} connected to ${this.endPointURL()}`),this.closeWasClean=false,this.disconnecting=false,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach(([,s])=>s());}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=false,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),BM,"heartbeat timeout"));}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs));}teardown(s,e,t){if(!this.conn)return s&&s();let i=this.connectClock;this.waitForBufferDone(()=>{i===this.connectClock&&(this.conn&&(e?this.conn.close(e,t||""):this.conn.close()),this.waitForSocketClosed(()=>{i===this.connectClock&&(this.conn&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),s&&s());}));});}waitForBufferDone(s,e=1){if(e===5||!this.conn||!this.conn.bufferedAmount){s();return}setTimeout(()=>{this.waitForBufferDone(s,e+1);},150*e);}waitForSocketClosed(s,e=1){if(e===5||!this.conn||this.conn.readyState===fs.closed){s();return}setTimeout(()=>{this.waitForSocketClosed(s,e+1);},150*e);}onConnClose(s){this.conn&&(this.conn.onclose=()=>{});let e=s&&s.code;this.hasLogger()&&this.log("transport","close",s),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&e!==1e3&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(([,t])=>t(s));}onConnError(s){this.hasLogger()&&this.log("transport",s);let e=this.transport,t=this.establishedConnections;this.stateChangeCallbacks.error.forEach(([,i])=>{i(s,e,t);}),(e===this.transport||t>0)&&this.triggerChanError();}triggerChanError(){this.channels.forEach(s=>{s.isErrored()||s.isLeaving()||s.isClosed()||s.trigger(Cs.error);});}connectionState(){switch(this.conn&&this.conn.readyState){case fs.connecting:return "connecting";case fs.open:return "open";case fs.closing:return "closing";default:return "closed"}}isConnected(){return this.connectionState()==="open"}remove(s){this.off(s.stateChangeRefs),this.channels=this.channels.filter(e=>e!==s);}off(s){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([t])=>s.indexOf(t)===-1);}channel(s,e={}){let t=new GM(s,e,this);return this.channels.push(t),t}push(s){if(this.hasLogger()){let{topic:e,event:t,payload:i,ref:r,join_ref:n}=s;this.log("push",`${e} ${t} (${n}, ${r})`,i);}this.isConnected()?this.encode(s,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(s,e=>this.conn.send(e)));}makeRef(){let s=this.ref+1;return s===this.ref?this.ref=0:this.ref=s,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs));}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(s=>s()),this.sendBuffer=[]);}onConnMessage(s){this.decode(s.data,e=>{let{topic:t,event:i,payload:r,ref:n,join_ref:o}=e;n&&n===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${r.status||""} ${t} ${i} ${n&&"("+n+")"||""}`,r);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];l.isMember(t,i,r,o)&&l.trigger(i,r,n,o);}for(let a=0;a<this.stateChangeCallbacks.message.length;a++){let[,l]=this.stateChangeCallbacks.message[a];l(e);}});}leaveOpenTopic(s){let e=this.channels.find(t=>t.topic===s&&(t.isJoined()||t.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${s}"`),e.leave());}};var Po=class{static connect(e){if(typeof window>"u"){let n={on:()=>n,push:()=>n,join:()=>n,leave:()=>Promise.resolve(),off:()=>{}};return {token:e,channel:n}}let t=new fI(a$1.upload.socket,{params:{token:e},reconnectAfterMs:n=>[1e3,3e3,5e3,1e4][n-1]||1e4});t.connect();let i=t.channel(`embed:${e}`),r={token:e,channel:i,socket:t};return i.on("initiate",({upload_id:n})=>{r.upload_id=n;}),i.join(),r}static async disconnect(e){if(e){try{await e.channel.leave();}catch{}e.socket?.disconnect();}}};var Ne=class extends nt{constructor(){super(...arguments);this.disableCompletion=false;this._progress=0;this._completed=false;this._dragging=false;this._error=null;this._hasErrorSlot=false;this.playableEmitted=false;this.languageController=new _o(this);this.lastState="initial";this.lastProgress=-1;}connectedCallback(){super.connectedCallback(),this.addEventListener("click",this.handleActionClick),this.addEventListener("keydown",this.handleActionKeyDown),this.languageController.locale=this.locale||"en",this.updateHasErrorSlot(),typeof MutationObserver<"u"&&(this.slotObserver=new MutationObserver(()=>{this.updateHasErrorSlot();}),this.slotObserver.observe(this,{childList:true,subtree:true,attributes:true,attributeFilter:["slot"]})),this.embedChannel=Po.connect(this.token),this.embedChannel.upload_id&&(this._upload_id=this.embedChannel.upload_id),this.embedChannel.channel.on("initiate",({upload_id:t})=>{this._upload_id=t,this.embedChannel.upload_id=t,this.playableEmitted=false;}),this.embedChannel.channel.on("completed",this.completed.bind(this)),this.embedChannel.channel.on("rendition",this.rendition.bind(this)),this.embedChannel.channel.on("error",this.error.bind(this));}requestUpdate(t,i){super.requestUpdate(t,i),t==="locale"&&(this.languageController.locale=this.locale);}reset(){this._progress=0,this._completed=false,this._error=null,this.playableEmitted=false,this.currentEmbed=void 0,this.embedChannel.channel.push("reset",{});}disconnectedCallback(){Po.disconnect(this.embedChannel),this.removeEventListener("click",this.handleActionClick),this.removeEventListener("keydown",this.handleActionKeyDown),this.slotObserver?.disconnect(),this.slotObserver=void 0,super.disconnectedCallback();}handleDrop(t){t.preventDefault(),this._dragging=false;let i=t.dataTransfer;if(!i)return;let r=this.collectFilesFromDataTransfer(i);if(!r.length)return;this._error=null;let n=false;for(let o of r)this.isSupportedFile(o)?(n||(this._progress=1,n=true),this.upload(o)):this.handleUnsupportedFile(o);}handleForm(t){let i=t.target;if(i.files){i.files.length&&(this._error=null);let r=false;for(let n of i.files)this.isSupportedFile(n)?(r||(this._progress=1,r=true),this.upload(n)):this.handleUnsupportedFile(n);i.value="";}}upload(t){this.dispatchEvent(new CustomEvent("upload",{bubbles:true,composed:true,detail:{file:t}})),this._error=null;let i=new uI(t,{endpoint:a$1.upload.endpoint,retryDelays:[0,3e3,5e3,1e4,2e4,6e4,6e4],metadata:{title:t.name,filetype:t.type,token:this.token,upload_id:this._upload_id},onError:r=>{console.log(r),this.dispatchEvent(new CustomEvent("failed",{bubbles:true,composed:true,detail:r}));},onProgress:(r,n)=>{let o=Math.round(r/n*100);o>this._progress&&(this._progress=o),this.dispatchEvent(new CustomEvent("progress",{bubbles:true,composed:true,detail:{progress:o}}));},onSuccess:()=>{this._progress=100,this.dispatchEvent(new CustomEvent("processing",{bubbles:true,composed:true}));},removeFingerprintOnSuccess:true});i.findPreviousUploads().then(r=>{r.length&&i.resumeFromPreviousUpload(r[0]),i.start();});}completed(t){this.currentEmbed=t?.embed,setTimeout(()=>{this.disableCompletion||(this._completed=true),this.dispatchEvent(new CustomEvent("completed",{bubbles:true,composed:true,detail:t}));},250);}rendition(t){!this.playableEmitted&&this.isPlayableRendition(t)&&(this.playableEmitted=true,setTimeout(()=>{this.dispatchEvent(new CustomEvent("playable",{bubbles:true,composed:true,detail:{embed:this.currentEmbed}}));},250)),this.dispatchEvent(new CustomEvent("rendition",{bubbles:true,composed:true,detail:t}));}error(t){console.warn(`[mave-upload] ${t.message}`),this._error={reason:"upload error",message:t.message},this._progress=0,this._completed=false,this.dispatchEvent(new CustomEvent("error",{bubbles:true,detail:t}));}isPlayableRendition(t){return typeof t?.container=="string"&&t.container==="hls"&&t?.type==="video"}updateHasErrorSlot(t){let i=!!this.querySelector('[slot="error"]');this._hasErrorSlot!==i&&(this._hasErrorSlot=i);}render(){switch(this.currentState){case "error":return this.renderError();case "uploading":return this.renderUploading();case "processing":return this.renderProcessing();case "done":return this.renderDone();default:return this.renderInitial()}}styleOpacity(){return this.languageController.loaded?this._upload_id?{}:{pointerEvents:"none",opacity:"0.5"}:{pointerEvents:"none",opacity:"0"}}styleFont(){return this.font?{fontFamily:this.font}:{fontFamily:"system-ui"}}get currentState(){return this._error?"error":this._completed?"done":this._progress>=100&&this._progress>0?"processing":this._progress>0?"uploading":"initial"}openFileDialog(){this.fileInput&&!this.fileInput.disabled&&this.fileInput.click();}findActionTarget(t){for(let i of t.composedPath())if(i instanceof HTMLElement&&i.hasAttribute("data-mave-upload-select"))return i;return null}handleActionClick(t){this.findActionTarget(t)&&(t.preventDefault(),this.openFileDialog());}handleActionKeyDown(t){if(t.key!=="Enter"&&t.key!==" ")return;this.findActionTarget(t)&&(t.preventDefault(),this.openFileDialog());}blockSubmit(t){t.preventDefault();}collectFilesFromDataTransfer(t){let i=[];if(t.items&&t.items.length){for(let r of t.items){if(r.kind!=="file")continue;let n=r.getAsFile();n&&i.push(n);}if(i.length)return i}if(t.files&&t.files.length)for(let r of t.files)i.push(r);return i}hasSupportedFiles(t){let i=this.collectFilesFromDataTransfer(t);if(i.length)return i.some(n=>this.isSupportedFile(n));if(typeof navigator<"u"&&/^((?!chrome|crios|chromium|android).)*safari/i.test(navigator.userAgent))return true;if(t.items&&t.items.length)for(let n of t.items){if(n.kind!=="file")continue;let o=(n.type||"").toLowerCase();if(o.startsWith("video/")||o.startsWith("audio/"))return true}return false}handleDragEnter(t){t.preventDefault();let i=t.dataTransfer;if(!i){this._dragging=false;return}let r=this.hasSupportedFiles(i);i.dropEffect=r?"copy":"none",this._dragging=r;}handleDragOver(t){t.preventDefault();let i=t.dataTransfer;if(!i){this._dragging=false;return}let r=this.hasSupportedFiles(i);i.dropEffect=r?"copy":"none",this._dragging=r;}handleDragLeave(t){t.preventDefault();let i=t.currentTarget,r=t.relatedTarget;if(!i){this._dragging=false;return}(!r||!(r instanceof Node)||!i.contains(r))&&(this._dragging=false);}isSupportedFile(t){let i=(t.type||"").toLowerCase(),r=Ne.getFileExtension(t);return i.startsWith("video/")?!r||Ne.SUPPORTED_VIDEO_EXTENSIONS.has(r):i.startsWith("audio/")?!r||Ne.SUPPORTED_AUDIO_EXTENSIONS.has(r):r?!!(Ne.SUPPORTED_VIDEO_EXTENSIONS.has(r)||Ne.SUPPORTED_AUDIO_EXTENSIONS.has(r)):false}static getFileExtension(t){let i=t.name||"",r=i.lastIndexOf(".");if(!(r===-1||r===i.length-1))return i.slice(r+1).toLowerCase()}handleUnsupportedFile(t){let i={file:t,reason:"unsupported type",allowedExtensions:{video:Array.from(Ne.SUPPORTED_VIDEO_EXTENSIONS),audio:Array.from(Ne.SUPPORTED_AUDIO_EXTENSIONS)}};this._error=i,this._progress=0,this._completed=false,this.dispatchEvent(new CustomEvent("invalid",{bubbles:true,composed:true,detail:{...i,message:lt("unsupported file type")}}));}updated(t){super.updated(t);let i=this._progress||0,r=this.currentState;this.setAttribute("state",r),this.setAttribute("progress",`${i}`),this.toggleAttribute("drag-over",this._dragging),this.toggleAttribute("ready",!!this._upload_id&&this.languageController.loaded);let n=r!==this.lastState,o=i!==this.lastProgress,a=t.has("_dragging");(n||o||a)&&this.dispatchEvent(new CustomEvent("statechange",{bubbles:true,composed:true,detail:{state:r,progress:i,dragging:this._dragging,error:this._error}})),this.lastState=r,this.lastProgress=i;}renderInitial(){let t=this.color?this.color:"#1997FF",i=this.radius?this.radius:"16px";return ne`<form
2297
+ class="state state--initial"
2298
+ style=${Lt({...this.styleOpacity(),...this.styleFont()})}
2299
+ @submit=${this.blockSubmit}
2300
+ @dragenter=${this.handleDragEnter}
2301
+ @dragover=${this.handleDragOver}
2302
+ @dragleave=${this.handleDragLeave}
2303
+ @drop=${this.handleDrop}
2304
+ >
2305
+ <slot name="initial">
2306
+ <div class="upload-default-title">${lt("drop video here")}</div>
2307
+ <div class="upload-default-subtitle">${lt("or browse your files")}</div>
2308
+ <button
2309
+ type="button"
2310
+ data-mave-upload-select
2311
+ class="upload-default-button"
2312
+ style=${Lt({background:t,borderRadius:i})}
2313
+ >
2314
+ ${lt("select file")}
2315
+ </button>
2316
+ </slot>
2317
+ <input
2318
+ id="mave-upload-input"
2319
+ .disabled=${!this._upload_id}
2320
+ type="file"
2321
+ accept="video/*, audio/*"
2322
+ @change=${this.handleForm}
2323
+ hidden
2324
+ />
2325
+ </form>`}renderError(){return this._hasErrorSlot?ne`<form
2326
+ class="state state--error"
2327
+ style=${Lt({...this.styleOpacity(),...this.styleFont()})}
2328
+ @submit=${this.blockSubmit}
2329
+ @dragenter=${this.handleDragEnter}
2330
+ @dragover=${this.handleDragOver}
2331
+ @dragleave=${this.handleDragLeave}
2332
+ @drop=${this.handleDrop}
2333
+ >
2334
+ <slot name="error" @slotchange=${this.updateHasErrorSlot}></slot>
2335
+ <input
2336
+ id="mave-upload-input"
2337
+ .disabled=${!this._upload_id}
2338
+ type="file"
2339
+ accept="video/*, audio/*"
2340
+ @change=${this.handleForm}
2341
+ hidden
2342
+ />
2343
+ </form>`:this.renderInitial()}renderUploading(){let t=Math.max(0,Math.min(100,this._progress||0));return ne`<div class="state state--uploading" style=${Lt(this.styleFont())}>
2344
+ <slot name="uploading">
2345
+ <div class="upload-default-progress" role="status">
2346
+ <div
2347
+ class="upload-default-progress-bar"
2348
+ role="progressbar"
2349
+ aria-valuemin="0"
2350
+ aria-valuemax="100"
2351
+ aria-valuenow=${t}
2352
+ >
2353
+ <div class="upload-default-progress-value" style="width: ${t}%;"></div>
2354
+ </div>
2355
+ <div class="upload-default-progress-label">${lt("uploading...")}</div>
2356
+ </div>
2357
+ </slot>
2358
+ </div>`}renderProcessing(){return ne`<div class="state state--processing" style=${Lt(this.styleFont())}>
2359
+ <slot name="processing">
2360
+ <div class="upload-default-status" role="status">${lt("just a minute...")}</div>
2361
+ </slot>
2362
+ </div>`}renderDone(){return ne`<div class="state state--done" style=${Lt(this.styleFont())}>
2363
+ <slot name="done">
2364
+ <div class="upload-default-status" role="status">${lt("done")}</div>
2365
+ </slot>
2366
+ </div>`}};Ne.SUPPORTED_VIDEO_EXTENSIONS=new Set(["3g2","3gp","avi","mov","mp4","m4v","mkv","qt","ts","mts","m2t","m2ts","webm"]),Ne.SUPPORTED_AUDIO_EXTENSIONS=new Set(["aac","amr","flac","m4a","m4b","m4p","mp3","ogg","wav"]),Ne.styles=it`
2367
+ :host {
2368
+ all: initial;
2369
+ display: block;
2370
+ width: 100%;
2371
+ aspect-ratio: 16 / 9;
2372
+ position: relative;
2373
+ }
2374
+
2375
+ .state {
2376
+ display: flex;
2377
+ flex-direction: column;
2378
+ justify-content: center;
2379
+ align-items: center;
2380
+ background: white;
2381
+ width: 100%;
2382
+ height: 100%;
2383
+ }
2384
+
2385
+ .state--initial {
2386
+ transition: box-shadow 160ms ease;
2387
+ gap: 12px;
2388
+ }
2389
+
2390
+ .state--error {
2391
+ transition: box-shadow 160ms ease;
2392
+ gap: 12px;
2393
+ }
2394
+
2395
+ .upload-default-error {
2396
+ display: flex;
2397
+ flex-direction: column;
2398
+ align-items: center;
2399
+ gap: 12px;
2400
+ text-align: center;
2401
+ width: 100%;
2402
+ padding: 0 24px;
2403
+ }
2404
+
2405
+ .upload-default-error-filename {
2406
+ font-size: 14px;
2407
+ font-weight: 500;
2408
+ color: #111;
2409
+ max-width: 320px;
2410
+ overflow-wrap: anywhere;
2411
+ }
2412
+
2413
+ .upload-default-error-title {
2414
+ font-size: 24px;
2415
+ font-weight: 400;
2416
+ color: #e5484d;
2417
+ }
2418
+
2419
+ .upload-default-error-subtitle {
2420
+ opacity: 0.6;
2421
+ max-width: 320px;
2422
+ }
2423
+
2424
+ .upload-default-title {
2425
+ font-size: 32px;
2426
+ padding-bottom: 2px;
2427
+ font-weight: 300;
2428
+ opacity: 0.9;
2429
+ text-align: center;
2430
+ }
2431
+
2432
+ .upload-default-subtitle {
2433
+ opacity: 0.5;
2434
+ padding-bottom: 16px;
2435
+ text-align: center;
2436
+ }
2437
+
2438
+ .upload-default-button {
2439
+ position: relative;
2440
+ width: 150px;
2441
+ height: 40px;
2442
+ overflow: hidden;
2443
+ color: white;
2444
+ display: flex;
2445
+ justify-content: center;
2446
+ align-items: center;
2447
+ cursor: pointer;
2448
+ border: none;
2449
+ font: inherit;
2450
+ text-transform: none;
2451
+ background: #1997ff;
2452
+ border-radius: 16px;
2453
+ transition: opacity 160ms ease;
2454
+ }
2455
+
2456
+ .upload-default-button:hover,
2457
+ .upload-default-button:focus {
2458
+ opacity: 0.9;
2459
+ outline: none;
2460
+ }
2461
+
2462
+ .upload-default-button:disabled {
2463
+ opacity: 0.5;
2464
+ cursor: not-allowed;
2465
+ }
2466
+
2467
+ .upload-default-progress {
2468
+ width: 70%;
2469
+ max-width: 380px;
2470
+ display: flex;
2471
+ flex-direction: column;
2472
+ gap: 16px;
2473
+ align-items: center;
2474
+ }
2475
+
2476
+ .upload-default-progress-bar {
2477
+ width: 100%;
2478
+ height: 4px;
2479
+ border-radius: 999px;
2480
+ background: #e6e6e6;
2481
+ overflow: hidden;
2482
+ }
2483
+
2484
+ .upload-default-progress-value {
2485
+ height: 100%;
2486
+ background: #1997ff;
2487
+ transition: width 200ms cubic-bezier(0, 0, 0.2, 1);
2488
+ }
2489
+
2490
+ .upload-default-progress-label {
2491
+ opacity: 0.6;
2492
+ }
2493
+
2494
+ .upload-default-status {
2495
+ opacity: 0.6;
2496
+ padding-bottom: 24px;
2497
+ text-align: center;
2498
+ }
2499
+ `,c([oe()],Ne.prototype,"token",2),c([oe()],Ne.prototype,"locale",2),c([oe()],Ne.prototype,"color",2),c([oe()],Ne.prototype,"font",2),c([oe()],Ne.prototype,"radius",2),c([oe({type:Boolean})],Ne.prototype,"disableCompletion",2),c([Ct()],Ne.prototype,"_progress",2),c([Ct()],Ne.prototype,"_upload_id",2),c([Ct()],Ne.prototype,"_completed",2),c([Ct()],Ne.prototype,"_dragging",2),c([Ct()],Ne.prototype,"_error",2),c([Ct()],Ne.prototype,"_hasErrorSlot",2),c([Di("#mave-upload-input")],Ne.prototype,"fileInput",2),Ne=c([xl()],Ne);typeof window<"u"&&window.customElements&&(window.customElements.get("mave-upload")||window.customElements.define("mave-upload",Ne));/*! Bundled license information:
2500
+
2501
+ lit-html/is-server.js:
2502
+ (**
2503
+ * @license
2504
+ * Copyright 2022 Google LLC
2505
+ * SPDX-License-Identifier: BSD-3-Clause
2506
+ *)
2507
+
2508
+ @lit-labs/observers/intersection-controller.js:
2509
+ @lit/reactive-element/decorators/query-assigned-elements.js:
2510
+ @lit/localize/internal/locale-status-event.js:
2511
+ @lit/localize/internal/str-tag.js:
2512
+ @lit/localize/internal/types.js:
2513
+ @lit/localize/internal/default-msg.js:
2514
+ @lit/localize/internal/localized-controller.js:
2515
+ @lit/localize/internal/localized-decorator.js:
2516
+ @lit/localize/internal/runtime-msg.js:
2517
+ @lit/localize/init/runtime.js:
2518
+ @lit/localize/init/transform.js:
2519
+ (**
2520
+ * @license
2521
+ * Copyright 2021 Google LLC
2522
+ * SPDX-License-Identifier: BSD-3-Clause
2523
+ *)
2524
+
2525
+ @lit/reactive-element/css-tag.js:
2526
+ (**
2527
+ * @license
2528
+ * Copyright 2019 Google LLC
2529
+ * SPDX-License-Identifier: BSD-3-Clause
2530
+ *)
2531
+
2532
+ @lit/reactive-element/reactive-element.js:
2533
+ lit-html/lit-html.js:
2534
+ lit-element/lit-element.js:
2535
+ @lit/reactive-element/decorators/custom-element.js:
2536
+ @lit/reactive-element/decorators/property.js:
2537
+ @lit/reactive-element/decorators/state.js:
2538
+ @lit/reactive-element/decorators/event-options.js:
2539
+ @lit/reactive-element/decorators/base.js:
2540
+ @lit/reactive-element/decorators/query.js:
2541
+ @lit/reactive-element/decorators/query-all.js:
2542
+ @lit/reactive-element/decorators/query-async.js:
2543
+ @lit/reactive-element/decorators/query-assigned-nodes.js:
2544
+ lit-html/directive.js:
2545
+ lit-html/async-directive.js:
2546
+ @lit/task/task.js:
2547
+ (**
2548
+ * @license
2549
+ * Copyright 2017 Google LLC
2550
+ * SPDX-License-Identifier: BSD-3-Clause
2551
+ *)
2552
+
2553
+ lit-html/directives/if-defined.js:
2554
+ lit-html/directives/style-map.js:
2555
+ (**
2556
+ * @license
2557
+ * Copyright 2018 Google LLC
2558
+ * SPDX-License-Identifier: BSD-3-Clause
2559
+ *)
2560
+
2561
+ lit-html/directive-helpers.js:
2562
+ lit-html/directives/ref.js:
2563
+ lit-html/static.js:
2564
+ @lit/localize/internal/deferred.js:
2565
+ @lit/localize/internal/id-generation.js:
2566
+ @lit/localize/lit-localize.js:
2567
+ (**
2568
+ * @license
2569
+ * Copyright 2020 Google LLC
2570
+ * SPDX-License-Identifier: BSD-3-Clause
2571
+ *)
2572
+
2573
+ @lit/localize/internal/fnv1a64.js:
2574
+ (**
2575
+ * @license
2576
+ * Copyright 2014 Travis Webb
2577
+ * SPDX-License-Identifier: MIT
2578
+ *)
2579
+
2580
+ tus-js-client/lib.esm/upload.js:
2581
+ tus-js-client/lib.esm/browser/fileReader.js:
2582
+ (*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE *)
2583
+ */export{li as a,Xo as b,_d as c,Se as d,Li as e,So as f,ds as g,Ne as h};